问:
How to access a variable from another dart file . Flutter
I am new to Flutter and I need to access a variable from another dart file.I am using showDatePicker to select a date.I need to get that date in another file in which where dob.dart is calling to insert in database.

dob.dart

```<code>class _DateOfBirthState extends State<DateOfBirth> {
  DateTime? dateTime;
  String _text = '';
  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        border: Border.all(),
        borderRadius: BorderRadius.circular(5),
      ),
      width: double.infinity,
      child: Padding(
        padding: const EdgeInsets.only(left: 8, right: 8),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            const Text('Date Of Birth'),
            Text(_text),
            ElevatedButton(
              onPressed: () async {
                dateTime = await showDatePicker(
                  context: context,
                  initialDate: dateTime ?? DateTime.now(),
                  firstDate: DateTime(1900),
                  lastDate: DateTime.now(),
                );
                setState(() {
                  _text =
                      '${dateTime?.day}/${dateTime?.month}/${dateTime?.year}';
                });
              },
              child: const Text('Date Of Birth'),
            ),
          ],
        ),
      ),
    );
  }
}
</code>```

I need to use value of dateTime in another file addStudents.dart

addstudents.dart

```<code>class _AddStudentsState extends State<AddStudents> {
  final _nameController = TextEditingController();
  final _addressController = TextEditingController();
  final _mobileController = TextEditingController();
  final _emailController = TextEditingController();
  final GlobalKey<FormState> _formkey = GlobalKey<FormState>(); @override
  Widget build(BuildContext context) {
    return Center(
      child: SingleChildScrollView(
        child: Form(
          key: _formkey,
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Column(
              children: [
                TextFormField(
                  validator: (value) {
                    if (value!.isEmpty) {
                      return 'Enter your name';
                    }
                  },
                  controller: _nameController,
                  decoration: const InputDecoration(
                      labelText: 'Name',
                      hintText: 'Alex',
                      border: OutlineInputBorder()),
                ),
                DateOfBirth(),
                TextFormField(
                  maxLines: 5,
                  keyboardType: TextInputType.multiline,
                  controller: _addressController,
                  decoration: const InputDecoration(
                      labelText: 'Address',
                      hintText:
                          'House 21\nKolachery mukk\nP.O.Kolachery\nKannur\n670601',
                      border: OutlineInputBorder()),
                ),
                TextFormField(
                  maxLength: 10,
                  keyboardType: TextInputType.number,
                  controller: _mobileController,
                  decoration: const InputDecoration(
                    labelText: 'Mobile Number',
                    prefixText: '+91',
                    hintText: '0000000000',
                    border: OutlineInputBorder(),
                  ),
                ),
                TextFormField(
                  keyboardType: TextInputType.emailAddress,
                  controller: _emailController,
                  decoration: const InputDecoration(
                      labelText: 'Email',
                      hintText: 'name@example.com',
                      border: OutlineInputBorder()),
                ),
                SizedBox(
                  width: double.infinity,
                  child: ElevatedButton(
                    child: const Text('Submit'),
                    onPressed: () async {
                      if (!_formkey.currentState!.validate()) {
                        return;
                      }

                      await DataBaseHelper.instance.addStudent(
                        StudentDetails(
                          name: _nameController.text,
                          dob:
                              // '${dateTime!.day}/${dateTime!.month}/${dateTime!.year}',
                          address: _addressController.text,
                          phone: _mobileController.text,
                          email: _emailController.text,
                        ),
                      );
                    },
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

</code>```

答:
If you are navigating from dob.dart to addstudents.dart then you can pass the value of DateTime though the constructor.

or

you can store it inside local database like sharedpreferences, and access it in any file.

Body:
I am new to Flutter and I need to access a variable from another dart file.I am using showDatePicker to select a date.I need to get that date in another file in which where dob.dart is calling to insert in database.

dob.dart

class _DateOfBirthState extends State<DateOfBirth> {
  DateTime? dateTime;
  String _text = '';
  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        border: Border.all(),
        borderRadius: BorderRadius.circular(5),
      ),
      width: double.infinity,
      child: Padding(
        padding: const EdgeInsets.only(left: 8, right: 8),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            const Text('Date Of Birth'),
            Text(_text),
            ElevatedButton(
              onPressed: () async {
                dateTime = await showDatePicker(
                  context: context,
                  initialDate: dateTime ?? DateTime.now(),
                  firstDate: DateTime(1900),
                  lastDate: DateTime.now(),
                );
                setState(() {
                  _text =
                      '${dateTime?.day}/${dateTime?.month}/${dateTime?.year}';
                });
              },
              child: const Text('Date Of Birth'),
            ),
          ],
        ),
      ),
    );
  }
}

I need to use value of dateTime in another file addStudents.dart

addstudents.dart

class _AddStudentsState extends State<AddStudents> {
  final _nameController = TextEditingController();
  final _addressController = TextEditingController();
  final _mobileController = TextEditingController();
  final _emailController = TextEditingController();
  final GlobalKey<FormState> _formkey = GlobalKey<FormState>(); @override
  Widget build(BuildContext context) {
    return Center(
      child: SingleChildScrollView(
        child: Form(
          key: _formkey,
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Column(
              children: [
                TextFormField(
                  validator: (value) {
                    if (value!.isEmpty) {
                      return 'Enter your name';
                    }
                  },
                  controller: _nameController,
                  decoration: const InputDecoration(
                      labelText: 'Name',
                      hintText: 'Alex',
                      border: OutlineInputBorder()),
                ),
                DateOfBirth(),
                TextFormField(
                  maxLines: 5,
                  keyboardType: TextInputType.multiline,
                  controller: _addressController,
                  decoration: const InputDecoration(
                      labelText: 'Address',
                      hintText:
                          'House 21\nKolachery mukk\nP.O.Kolachery\nKannur\n670601',
                      border: OutlineInputBorder()),
                ),
                TextFormField(
                  maxLength: 10,
                  keyboardType: TextInputType.number,
                  controller: _mobileController,
                  decoration: const InputDecoration(
                    labelText: 'Mobile Number',
                    prefixText: '+91',
                    hintText: '0000000000',
                    border: OutlineInputBorder(),
                  ),
                ),
                TextFormField(
                  keyboardType: TextInputType.emailAddress,
                  controller: _emailController,
                  decoration: const InputDecoration(
                      labelText: 'Email',
                      hintText: 'name@example.com',
                      border: OutlineInputBorder()),
                ),
                SizedBox(
                  width: double.infinity,
                  child: ElevatedButton(
                    child: const Text('Submit'),
                    onPressed: () async {
                      if (!_formkey.currentState!.validate()) {
                        return;
                      }

                      await DataBaseHelper.instance.addStudent(
                        StudentDetails(
                          name: _nameController.text,
                          dob:
                              // '${dateTime!.day}/${dateTime!.month}/${dateTime!.year}',
                          address: _addressController.text,
                          phone: _mobileController.text,
                          email: _emailController.text,
                        ),
                      );
                    },
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}


来源: stackexchange

问:
flutter problem: How to fill collor on card?
I want to fill red color abbove my card image and below text as a showing in screen shot but problem is that color not being cerculer I mentioned in my Screenshot.

This is my card code.

ListView.builder(
    shrinkWrap: true,
    physics: NeverScrollableScrollPhysics(),
    itemCount: mpListData.length,
    itemBuilder: (context, index) {
      return isMPLoading
          ? SingleChildScrollView(
              child: Column(
                children: [
                  CardSkeleton(),
                  CardSkeleton(),
                  CardSkeleton(),
                ],
              ),
            )
          : Padding(
              padding: const EdgeInsets.only(
                left: 12,
                right: 12,
                bottom: 15,
              ),
              child: SizedBox(
                height:
                    mpListData[index]['name'] == "Starter" ? 160 : 167,
                width: MediaQuery.of(context).size.width,
                child: Stack(
                  alignment: Alignment.center,
                  children: [
                    Stack(
                      children: [
                        Container(
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(20),
                            image: DecorationImage(
                              image: mpListData[index]['name'] ==
                                      "Starter"
                                  ? AssetImage(
                                      "assets/light_green_card.png")
                                  : AssetImage("assets/white_card.png"),
                              fit: BoxFit.fill,
                            ),
                          ),
                          height: 142,
                          width: MediaQuery.of(context).size.width,
                          child: Container(
                            color: Colors.red.withOpacity(0.25),
                            child: Container(
                              margin: const EdgeInsets.only(top: 10),
                              padding: EdgeInsets.only(
                                  right: 15, left: 15, top: 8),
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Padding(
                                    padding: const EdgeInsets.only(
                                        top: 20.0),
                                    child: Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        Text(
                                          "${mpListData[index]['name']!.length <= 10 ? mpListData[index]['name'] : mpListData[index]['name']!.substring(0, 10) + ".."} Package",
                                          style: TextStyle(
                                              fontSize: tSize18,
                                              fontWeight:
                                                  FontWeight.w500),
                                        ),
                                        SizedBox(
                                          height: 6,
                                        ),
                                        Text(
                                          "Best package for price",
                                          style: TextStyle(
                                            fontSize: tSize14,
                                          ),
                                        ),
                                        SizedBox(
                                          height: 13,
                                        ),
                                        Text(
                                          mpListData[index]['name'] ==
                                                  "Starter"
                                              ? "FREE"
                                              : "\$99 USD",
                                          style: TextStyle(
                                              fontSize: tSize27,
                                              fontWeight:
                                                  FontWeight.w500),
                                        ),
                                      ],
                                    ),
                                  ),
                                  Padding(
                                    padding: EdgeInsets.only(bottom: 8),
                                    child: Image.asset(
                                      mpListData[index]['name'] ==
                                              "Starter"
                                          ? 'assets/onaa.png'
                                          : mpListData[index]['name'] ==
                                                  "Explorer"
                                              ? 'assets/white_ex.png'
                                              : 'assets/white_champ.png',
                                      height: 114,
                                      width: 114,
                                    ),
                                  )
                                ],
                              ),
                            ),
                          ),
                        ),
                        mpListData[index]['name'] == "Starter"
                            ? Container()
                            : Positioned(
                                top: 0,
                                right: 15,
                                child: Container(
                                  decoration: BoxDecoration(
                                    color: Color(0xff158998),
                                    borderRadius: BorderRadius.all(
                                        Radius.circular(8)),
                                  ),
                                  width: 130,
                                  height: 22,
                                  child: Center(
                                    child: Text(
                                      'Upcoming Plans',
                                      style: TextStyle(
                                        color: Colors.white,
                                        fontSize: tSize14,
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                      ],
                    ),
                    Positioned(
                      width: 18,
                      bottom: 0,
                      child: Center(
                        child: Container(
                          height: 15,
                          width: 15,
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(50),
                          ),
                          child: Theme(
                            data: ThemeData(
                              //here change to your color
                              unselectedWidgetColor: Color(0xff3a99a4),
                            ),
                            child: Radio(
                              activeColor: Colors.green,
                              overlayColor:
                                  MaterialStateProperty.all(Colors.red),
                              value: index,
                              groupValue: 0,
                              onChanged: (int? value) {
                                // setState(() {
                                //   isSelect = value!;
                                // });
                              },
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            );
    }),

```

答:
Wrap with ClipRRect with providing borderRadius as @Dima Rostopira commented.

itemBuilder: (context, index) {
  return ClipRRect(
    borderRadius: ,
      child: isMPLoading?
```

If you like to have only for Cart, wrap card Widget with ClipRRect.

ContentLicense: CC BY-SA 4.0

Body:
Wrap with ClipRRect with providing borderRadius as @Dima Rostopira commented.

itemBuilder: (context, index) {
  return ClipRRect(
    borderRadius: ,
      child: isMPLoading?

If you like to have only for Cart, wrap card Widget with ClipRRect.


问:
How do I detect tab was touched in xamarin forms TabbedPage
How could I detect tab was touched in xamarin forms TabbedPage?
(which is different from page changed detection which I figured how to detect)

Here is why:
I'm trying to work around a rather ugly tabbed page overflow UI
(the ugly scroller that shows up on the right over the tabbar
whenever there are >5 tabs)
So the 5th tab press shows a custom menu, second press hides that menu, etc.

Thanks!

答:
It has been a while since this was asked but just in case here is an answer.

Perform an action when a tab is tapped is the same as when:

The tab has changed

The tab is "reselected"

So for the first one you can use @femil-shajin 's answer or as I do here which is more direct and for the second one you need to make some custom renderers for the TabbedPage:

public class MyTabbedPage : TabbedPage
{
    ...

    protected override void OnCurrentPageChanged()
    {
         // do whatever
    }

    public void OnTabReselected()
    {
         // do whatever
    }

    ...
}
```
<p>Then on Android:</p>
<pre class="lang-cs prettyprint-override"><code>[assembly: ExportRenderer(typeof(TabbedPage), typeof(CustomTabbedRenderer))]
namespace MyNamespace.Droid.Renderers
{
    public class CustomTabbedRenderer : TabbedPageRenderer, NavigationBarView.IOnItemReselectedListener
    {
        ...
        protected override void OnElementChanged(ElementChangedEventArgs<TabbedPage> e)
        {
            base.OnElementChanged(e);
            if (e.NewElement != null)
            {
                GetBottomNavigationView()?.SetOnItemReselectedListener(this);
            }
        }

        private BottomNavigationView GetBottomNavigationView()
        {
            // this may need to change on some cases
            for (var i = 0; i < ViewGroup.ChildCount; i++)
            {
                var childView = ViewGroup.GetChildAt(i);
                if (childView is ViewGroup viewGroup)
                {
                    for (var j = 0; j < viewGroup.ChildCount; j++)
                    {
                        var childRelativeLayoutView = viewGroup.GetChildAt(j);
                        if (childRelativeLayoutView is BottomNavigationView bottomNavigationView)
                        {
                            return bottomNavigationView;
                        }
                    }
                }
            }
            return null;
        }

        public void OnNavigationItemReselected(IMenuItem item)
        {
            if (Element is MyTabbedPage tabbedPage)
            {
                tabbedPage.OnTabReselected();
            }
        }
        ...
    }
}
</code>```

And on iOS:

[assembly: ExportRenderer(typeof(TabbedPage), typeof(CustomTabbedRenderer))]
namespace MyNamespace.iOS.Renderers
{
    public class CustomTabbedRenderer : TabbedRenderer
    {
        private UITabBarItem _previousSelectedItem;

        ...
        public override void ViewDidAppear(bool animated)
        {
            base.ViewDidAppear(animated);

            if (SelectedIndex < TabBar.Items.Length)
            {
                _previousSelectedItem = TabBar.Items[SelectedIndex];
            }
        }

        public override void ItemSelected(UITabBar tabbar, UITabBarItem item)
        {
            if (_previousSelectedItem == item && Element is MyTabbedPage tabbedPage)
            {
                tabbedPage.OnTabReselected();
            }
            _previousSelectedItem = item;
        }
        ...
    }
}
```

Source: Part of this was based on this page

ContentLicense: CC BY-SA 3.0

Body:
It has been a while since this was asked but just in case here is an answer.

Perform an action when a tab is tapped is the same as when:

The tab has changed

The tab is "reselected"

So for the first one you can use @femil-shajin 's answer or as I do here which is more direct and for the second one you need to make some custom renderers for the TabbedPage:

public class MyTabbedPage : TabbedPage
{
    ...

    protected override void OnCurrentPageChanged()
    {
         // do whatever
    }

    public void OnTabReselected()
    {
         // do whatever
    }

    ...
}

Then on Android:

[assembly: ExportRenderer(typeof(TabbedPage), typeof(CustomTabbedRenderer))]
namespace MyNamespace.Droid.Renderers
{
    public class CustomTabbedRenderer : TabbedPageRenderer, NavigationBarView.IOnItemReselectedListener
    {
        ...
        protected override void OnElementChanged(ElementChangedEventArgs<TabbedPage> e)
        {
            base.OnElementChanged(e);
            if (e.NewElement != null)
            {
                GetBottomNavigationView()?.SetOnItemReselectedListener(this);
            }
        }

        private BottomNavigationView GetBottomNavigationView()
        {
            // this may need to change on some cases
            for (var i = 0; i < ViewGroup.ChildCount; i++)
            {
                var childView = ViewGroup.GetChildAt(i);
                if (childView is ViewGroup viewGroup)
                {
                    for (var j = 0; j < viewGroup.ChildCount; j++)
                    {
                        var childRelativeLayoutView = viewGroup.GetChildAt(j);
                        if (childRelativeLayoutView is BottomNavigationView bottomNavigationView)
                        {
                            return bottomNavigationView;
                        }
                    }
                }
            }
            return null;
        }

        public void OnNavigationItemReselected(IMenuItem item)
        {
            if (Element is MyTabbedPage tabbedPage)
            {
                tabbedPage.OnTabReselected();
            }
        }
        ...
    }
}

And on iOS:

[assembly: ExportRenderer(typeof(TabbedPage), typeof(CustomTabbedRenderer))]
namespace MyNamespace.iOS.Renderers
{
    public class CustomTabbedRenderer : TabbedRenderer
    {
        private UITabBarItem _previousSelectedItem;

        ...
        public override void ViewDidAppear(bool animated)
        {
            base.ViewDidAppear(animated);

            if (SelectedIndex < TabBar.Items.Length)
            {
                _previousSelectedItem = TabBar.Items[SelectedIndex];
            }
        }

        public override void ItemSelected(UITabBar tabbar, UITabBarItem item)
        {
            if (_previousSelectedItem == item && Element is MyTabbedPage tabbedPage)
            {
                tabbedPage.OnTabReselected();
            }
            _previousSelectedItem = item;
        }
        ...
    }
}

Source: Part of this was based on this page


问:
Using cummean with group_by and ignoring NAs
```<code>df <- data.frame(category=c("cat1","cat1","cat2","cat1","cat2","cat2","cat1","cat2"),
                 value=c(NA,2,3,4,5,NA,7,8))
</code>```

I'd like to add a new column to the above dataframe which takes the cumulative mean of the value column, not taking into account NAs. Is it possible to do this with dplyr? I've tried

```<code>df <- df %>% group_by(category) %>% mutate(new_col=cummean(value))
</code>```

but cummean just doesn't know what to do with NAs.

EDIT: I do not want to count NAs as 0.

答:
I needed something similar, but cannot replace NAs with 0. So I created this simple function, which works with dplyr. Hope this helps.

```<code>cummean.na <- function(x, na.rm = T)
{
  # x = c(NA, seq(1, 10, 1)); na.rm = T
  n <- length(x)
  op <- rep(NA, n)
  for(i in 1:n) {op[i] <- ifelse(is.na(x[i]), NA, mean(x[1:i], na.rm = !!na.rm))}
  rm(x, na.rm, n, i)
  return(op)
}
</code>```

Body:
df <- data.frame(category=c("cat1","cat1","cat2","cat1","cat2","cat2","cat1","cat2"),
                 value=c(NA,2,3,4,5,NA,7,8))

I'd like to add a new column to the above dataframe which takes the cumulative mean of the value column, not taking into account NAs. Is it possible to do this with dplyr? I've tried

df <- df %>% group_by(category) %>% mutate(new_col=cummean(value))

but cummean just doesn't know what to do with NAs.

EDIT: I do not want to count NAs as 0.

Body:
I needed something similar, but cannot replace NAs with 0. So I created this simple function, which works with dplyr. Hope this helps.

cummean.na <- function(x, na.rm = T)
{
  # x = c(NA, seq(1, 10, 1)); na.rm = T
  n <- length(x)
  op <- rep(NA, n)
  for(i in 1:n) {op[i] <- ifelse(is.na(x[i]), NA, mean(x[1:i], na.rm = !!na.rm))}
  rm(x, na.rm, n, i)
  return(op)
}


问:
In TypeScript, how can a declaration omit multiple methods from a base type?
While searching for ways to fix errors in a d.ts file, I need to omit a few methods from the base type because the custom class I'm working on redefines them.

I found the Omit helper type, which is used in examples like this one :

```<code>type Foo = {
  a() : void;
  b() : void;
  c() : void;
  toString() : string;
};
type BaseFoo = Omit<Foo, "a">;
</code>```

However, what if I need to remove both a, b, and c in BaseFoo?

It seems that I can do

```<code>type BaseFoo = Omit<Omit<Omit<Foo, "a">, "b">, "c">;
</code>```

But is there a cleaner way to do this?

答:
Yes, use union:

type BaseFoo = Omit<Foo, 'a'|'b'|'c'>;
```

Or just use Pick<Foo,'toString'>

Body:
While searching for ways to fix errors in a d.ts file, I need to omit a few methods from the base type because the custom class I'm working on redefines them.

I found the Omit helper type, which is used in examples like this one :

type Foo = {
  a() : void;
  b() : void;
  c() : void;
  toString() : string;
};
type BaseFoo = Omit<Foo, "a">;

However, what if I need to remove both a, b, and c in BaseFoo?

It seems that I can do

type BaseFoo = Omit<Omit<Omit<Foo, "a">, "b">, "c">;

But is there a cleaner way to do this?

Body:
Yes, use union:

type BaseFoo = Omit<Foo, 'a'|'b'|'c'>;

Or just use Pick<Foo,'toString'>


问:
Undefined type 'App\Http\Middleware\Auth'
i am new to laravel and i am trying to make an admin dashboard but in the adminmiddleware file i am having this error with both of my Auth</p>
```<code>Undefined type 'App\Http\Middleware\Auth'
</code>```
```<code>namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class AdminMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        if (Auth::check()) {
            if (Auth::user()->role_as == '1') {
                return $next($request);
            } else {
                return redirect('/home')->with('status', 'Access denied! as you are not an admin');
            }
        } else {
            return redirect('/home')->with('status', ' pleaselogin first');
        }
    }
}
</code>```

答:
add

```<code>use Illuminate\Support\Facades\Auth;
</code>```

before

```<code>use Illuminate\Http\Request;
</code>```

Body:
i am new to laravel and i am trying to make an admin dashboard but in the adminmiddleware file i am having this error with both of my Auth

Undefined type 'App\Http\Middleware\Auth'

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class AdminMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        if (Auth::check()) {
            if (Auth::user()->role_as == '1') {
                return $next($request);
            } else {
                return redirect('/home')->with('status', 'Access denied! as you are not an admin');
            }
        } else {
            return redirect('/home')->with('status', ' pleaselogin first');
        }
    }
}

Body:
add

use Illuminate\Support\Facades\Auth;

before

use Illuminate\Http\Request;


问:
How to install terality on google colabrotary
I want to install terality on google colab how to do that

i tried this first i wrote:

```<code>pip install --upgrade terality
terality account configure --email myemail@gmail.com
</code>```

but after the next command it shows this error:

```<code>File "<ipython-input-5-01d28d6ffdce>", line 1
    terality account configure --email myemail17@gmail.com

SyntaxError: invalid syntax
</code>```

i even tried this:

```<code>pip install terality
</code>```

and then i directly tried to use terality but it says the terlity client is not installed.

i want to use terality as it is faster so pls help:)

答:
These snippets are not Python code, but shell commands. In Google Colab, as well as in most Jupyter notebooks, a cell runs Python code by default.

To run a shell command in a cell, prefix the commands with a !:

```<code>!pip install terality
</code>```
```<code>!terality account configure  --email myemail17@gmail.com
</code>```

Also, this terality command is interactive (it reads further input from stdin), which likely won't work in a Jupyter notebook. You can use the non-interactive form instead:

```<code>!terality account configure  --email myemail17@gmail.com --api-key <apikey> --overwrite
</code>```

(this non-interactive version is otherwise discouraged, as it stores your API key in the notebook itself).

Body:
I want to install terality on google colab how to do that

i tried this first i wrote:

pip install --upgrade terality
terality account configure --email myemail@gmail.com

but after the next command it shows this error:

File "<ipython-input-5-01d28d6ffdce>", line 1
    terality account configure --email myemail17@gmail.com

SyntaxError: invalid syntax

i even tried this:

pip install terality

and then i directly tried to use terality but it says the terlity client is not installed.

i want to use terality as it is faster so pls help:)

Body:
These snippets are not Python code, but shell commands. In Google Colab, as well as in most Jupyter notebooks, a cell runs Python code by default.

To run a shell command in a cell, prefix the commands with a !:

!pip install terality

!terality account configure  --email myemail17@gmail.com

Also, this terality command is interactive (it reads further input from stdin), which likely won't work in a Jupyter notebook. You can use the non-interactive form instead:

!terality account configure  --email myemail17@gmail.com --api-key <apikey> --overwrite

(this non-interactive version is otherwise discouraged, as it stores your API key in the notebook itself).


问:
Perl Get File Last Modified Date Time No Module
I'm creating a script where I need to get the Last Modified Date of the files
I checked this thread How do I get a file's last modified time in Perl?

So I used the script below to get the last modified, at first it was working but when I try to run it again, the timestamp returns 00:00 January 1, 1970.

Why is that happening and how can I get the correct last modified date and time?

```<code>my $dir = '/tmp';

opendir(DIR, $dir) or die $!;
@content=readdir(DIR);

foreach(@content)
{
    next unless ($_ =~ m/\bfile.txt|file2.csv\b/);

    my $epoch_timestamp = (stat($_))[9];
    my $timestamp       = localtime($epoch_timestamp);
    $f_detail = $_ .' '.$timestamp;
    print "$f_detail\n";
}
closedir(DIR);

exit 0;
</code>```

When I tried to run the perl, I will get this result

file.txt Thu Jan  1 00:00:00 1970

file2.csv Thu Jan  1 00:00:00 1970

Ok, last update, it is working now, I try to run all of the scripts you've given to me, standalone script. I found what's causing the default time, see the script below, I remove that in my program and it works, didn't notice this at first, sorry. But still, it feels weird because I was sure that it is working when I first run it, but now it is working so yeah thank you guys!

```<code>if (($month = ((localtime)[4] + 1)) < 10)
{
  $month = '0' . $month;
}
if (($day = ((localtime)[3])) < 10)
{
  $day = '0' . $day;
}
if (($year = ((localtime)[5]+1900)) >= 2000)
{

  if (($year = $year - 2000) < 10)
  {
    $year = '0' . $year;
  }
}
else
{
  $year = $year - 1900;
}

$date = $month . $day . $year;
</code>```

答:
If you have a directory name, and you want to see if some files whose names you already know exist in that directory, there's really no need for opendir/readdir - that's more helpful if you don't know the filenames ahead of time. When you do, you can just build a path using both parts and use file test operators/stat/etc. on it.

#!/usr/bin/env perl
use strict;
use warnings;
use feature qw/say/;

my $dir = '/tmp';
my @files = qw/file.txt file2.csv/;

for my $file (@files) {
    # Better to use File::Spec->catfile($dir, $file), but your question
    # title said no modules...
    my $name = "$dir/$file";
    if (-e $name) { # Does the file exist?
        # _ to re-use the results of the above file test operator's stat call
        my $epoch_timestamp = (stat _)[9];
        my $timestamp       = localtime $epoch_timestamp;
        say "$file $timestamp";
    }
}
```
<p>Example execution:</p>
<pre class="lang-none prettyprint-override"><code>$ perl demo.pl
file.txt Tue Feb  8 07:26:07 2022
file2.csv Tue Feb  8 07:26:10 2022
</code>```

Body:
I'm creating a script where I need to get the Last Modified Date of the files
I checked this thread How do I get a file's last modified time in Perl?

So I used the script below to get the last modified, at first it was working but when I try to run it again, the timestamp returns 00:00 January 1, 1970.

Why is that happening and how can I get the correct last modified date and time?

my $dir = '/tmp';

opendir(DIR, $dir) or die $!;
@content=readdir(DIR);

foreach(@content)
{
    next unless ($_ =~ m/\bfile.txt|file2.csv\b/);

    my $epoch_timestamp = (stat($_))[9];
    my $timestamp       = localtime($epoch_timestamp);
    $f_detail = $_ .' '.$timestamp;
    print "$f_detail\n";
}
closedir(DIR);

exit 0;

When I tried to run the perl, I will get this result

file.txt Thu Jan  1 00:00:00 1970

file2.csv Thu Jan  1 00:00:00 1970

Ok, last update, it is working now, I try to run all of the scripts you've given to me, standalone script. I found what's causing the default time, see the script below, I remove that in my program and it works, didn't notice this at first, sorry. But still, it feels weird because I was sure that it is working when I first run it, but now it is working so yeah thank you guys!

if (($month = ((localtime)[4] + 1)) < 10)
{
  $month = '0' . $month;
}
if (($day = ((localtime)[3])) < 10)
{
  $day = '0' . $day;
}
if (($year = ((localtime)[5]+1900)) >= 2000)
{

  if (($year = $year - 2000) < 10)
  {
    $year = '0' . $year;
  }
}
else
{
  $year = $year - 1900;
}

$date = $month . $day . $year;

Body:
If you have a directory name, and you want to see if some files whose names you already know exist in that directory, there's really no need for opendir/readdir - that's more helpful if you don't know the filenames ahead of time. When you do, you can just build a path using both parts and use file test operators/stat/etc. on it.

#!/usr/bin/env perl
use strict;
use warnings;
use feature qw/say/;

my $dir = '/tmp';
my @files = qw/file.txt file2.csv/;

for my $file (@files) {
    # Better to use File::Spec->catfile($dir, $file), but your question
    # title said no modules...
    my $name = "$dir/$file";
    if (-e $name) { # Does the file exist?
        # _ to re-use the results of the above file test operator's stat call
        my $epoch_timestamp = (stat _)[9];
        my $timestamp       = localtime $epoch_timestamp;
        say "$file $timestamp";
    }
}

Example execution:

$ perl demo.pl
file.txt Tue Feb  8 07:26:07 2022
file2.csv Tue Feb  8 07:26:10 2022


问:
How can I use a decorated name with _Generic?
I'm writing a library which lets the user decorate the function names like this:

#ifndef DECORATE // Define this before including if you want to change the names.
#define DECORATE(name) lib_##name
#endif
```
<p>I now what to use <code>_Generic</code> to create a generic function <code>foo</code> like this:</p>
<pre class="lang-c prettyprint-override"><code>#define DECORATE(foo)(x)            \
    _Generic((x),                   \
             int:   DECORATE(fooi), \
             float: DECORATE(foof)  \
    )(x)
</code>```

This of course gives me an error, because I can't define the DECORATE macro twice. Is there a way to decorate the name of the generic function or is this impossible?

答:
You need to give your macros two different names so one can use the other.  Also, in the case of the one using _Generic, both parameters need to be in one set of parenthesis separated by spaces.

```<code>#ifndef DECORATEX
#define DECORATEX(name) lib_##name
#endif

#define DECORATE(foo,x)            \
    _Generic((x),                   \
             int:   DECORATEX(foo##i), \
             float: DECORATEX(foo##f)  \
    )(x)

void lib_abci(int x)
{
    printf("in abci, x=%d\n", x);
}

void lib_abcf(float x)
{
    printf("in abcf, x=%f\n", x);
}

int main()
{
    int a=3;
    float b=4.5;
    DECORATE(abc,a);
    DECORATE(abc,b);
    return 0;
}
</code>```

Output:

in abci, x=3
in abcf, x=4.500000
```

Body:
I'm writing a library which lets the user decorate the function names like this:

#ifndef DECORATE // Define this before including if you want to change the names.
#define DECORATE(name) lib_##name
#endif

I now what to use _Generic to create a generic function foo like this:

#define DECORATE(foo)(x)            \
    _Generic((x),                   \
             int:   DECORATE(fooi), \
             float: DECORATE(foof)  \
    )(x)

This of course gives me an error, because I can't define the DECORATE macro twice. Is there a way to decorate the name of the generic function or is this impossible?

Body:
You need to give your macros two different names so one can use the other.  Also, in the case of the one using _Generic, both parameters need to be in one set of parenthesis separated by spaces.

#ifndef DECORATEX
#define DECORATEX(name) lib_##name
#endif

#define DECORATE(foo,x)            \
    _Generic((x),                   \
             int:   DECORATEX(foo##i), \
             float: DECORATEX(foo##f)  \
    )(x)

void lib_abci(int x)
{
    printf("in abci, x=%d\n", x);
}

void lib_abcf(float x)
{
    printf("in abcf, x=%f\n", x);
}

int main()
{
    int a=3;
    float b=4.5;
    DECORATE(abc,a);
    DECORATE(abc,b);
    return 0;
}

Output:

in abci, x=3
in abcf, x=4.500000


问:
Simple Question: How to split date (08-17-2011) into month, day, year? PHP
I have a variable called $orderdate and it is set to a date format like this mm-dd-yyyy.

In PHP how would I split this variable into $month, $day, $year?

Thanks for your help.

答:
```<code>list($month, $day, $year) =explode("-",$orderdate);
</code>```


问:
pygame - Screen size issue?
Edit: I've uploaded a screenshot of the bug; at the very bottom of the post. I'm still lost in regards to the origin of this bug, sadly.

I've put together a version of Conway's Game of Life in python with pygame, but I'm having issues with pygame's screen. The game only seems to occupy a portion of the screen, resulting in huge bars along the top and left of the window. I'm not sure how to address this. Here is the code. The images being used (located at the end of comp.py) are just two differently-colored single pixels.

stage.py:

```<code>import comp

class Stage:

    bg = [[comp.Node(0,0) for _ in range(100)] for _ in range(100)]

    def drawNodes(self):
        for i in range(100):
            for j in range(100):
                self.bg[i][j].pos(i,j)

stage1 = Stage()
</code>```

comp.py:

```<code>import pygame
import stage

class Node:

    onoff = False

    ns = 0

    def __init__(self,x,y):
        self.x = x
        self.y = y

    def pos(self,x,y):
        self.x = x
        self.y = y
        self.n1 = [x,(y-1)]
        self.n2 = [(x+1),(y-1)]
        self.n3 = [(x+1),y]
        self.n4 = [(x+1),(y+1)]
        self.n5 = [x,(y+1)]
        self.n6 = [(x-1),(y+1)]
        self.n7 = [(x-1),y]
        self.n8 = [(x-1),(y-1)]

    def nCount(self): #neighbor counter
        self.ns = 0
        counter = {
            True: 1,
            False: 0
        }
        try:
            self.ns += counter[stage.stage1.bg[self.n1[0]][self.n1[1]].onoff]
        except IndexError as error:
            pass
        try:
            self.ns += counter[stage.stage1.bg[self.n2[0]][self.n2[1]].onoff]
        except IndexError as error:
            pass
        try:
            self.ns += counter[stage.stage1.bg[self.n3[0]][self.n3[1]].onoff]
        except IndexError as error:
            pass
        try:
            self.ns += counter[stage.stage1.bg[self.n4[0]][self.n4[1]].onoff]
        except IndexError as error:
            pass
        try:
            self.ns += counter[stage.stage1.bg[self.n5[0]][self.n5[1]].onoff]
        except IndexError as error:
            pass
        try:
            self.ns += counter[stage.stage1.bg[self.n6[0]][self.n6[1]].onoff]
        except IndexError as error:
            pass
        try:
            self.ns += counter[stage.stage1.bg[self.n7[0]][self.n7[1]].onoff]
        except IndexError as error:
            pass
        try:
            self.ns += counter[stage.stage1.bg[self.n8[0]][self.n8[1]].onoff]
        except IndexError as error:
            pass
        if (self.ns > 4):
            self.ns = 4
        if (self.ns == 2):
            if (self.onoff == True):
                self.ns = 3
        return self.ns

    onImg = pygame.image.load("C:\\Users\\#####\\PythonScripts\\conway\\tiles\\pink.png")
    offImg = pygame.image.load("C:\\Users\\#####\\PythonScripts\\conway\\tiles\\purple.png")
</code>```

systems.py:

```<code>import pygame
import comp
import stage
import random

pygame.init()

win = pygame.Surface((100,100)) #surface for resizing

screen = pygame.display.set_mode((600,600)) #target surface

def ruleFilter(node):
    n = {
        0: False,
        1: False,
        2: False,
        3: True,
        4: False
    }
    node.onoff = n[node.ns]

def turn(bg,x=100,y=100): #advance the game one turn
    for i in range(x):
        for j in range(y):
            bg[i][j].nCount()
    for i in range(x):
        for j in range(y):
            ruleFilter(bg[i][j])
    for i in range(x):
        for j in range(y):
            if (bg[i][j].onoff == True):
                win.blit(bg[i][j].onImg,(i,j))
            else:
                win.blit(bg[i][j].offImg,(i,j))

run = True

stage.stage1.drawNodes()

for i in range(100): #randomly activates 40% of cells
    for j in range(100):
        x = random.randint(1,100)
        if (x<=40):
            stage.stage1.bg[i][j].onoff = True

while run==True: #primary loop
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            run=False

    turn(stage.stage1.bg)

    win2 = pygame.transform.scale(win,(600,600)) #resized surface

    for x in range(100): #update screen surface
        for y in range(100):
            screen.blit(win2,(x,y))

    pygame.display.flip() #update screen

    pygame.time.delay(10) #delay before next turn

pygame.quit()
</code>```

Here is a screenshot of the bug in action:

答:
You can set the SCALED flag in your screen parameters like so

```<code>screen = pygame.display.set_mode((600,600)) #target surface
</code>```

to

```<code>screen = pygame.display.set_mode((600,600), SCALED) #target surface
</code>```

Additionally, you can add the FULLSCREEN flag if you would like to fill the screen. This should remove the black bars and fill the display with the game. Hope that this helps you.

Title: pygame - Screen size issue?

Body:
Edit: I've uploaded a screenshot of the bug; at the very bottom of the post. I'm still lost in regards to the origin of this bug, sadly.

I've put together a version of Conway's Game of Life in python with pygame, but I'm having issues with pygame's screen. The game only seems to occupy a portion of the screen, resulting in huge bars along the top and left of the window. I'm not sure how to address this. Here is the code. The images being used (located at the end of comp.py) are just two differently-colored single pixels.

stage.py:

import comp

class Stage:

    bg = [[comp.Node(0,0) for _ in range(100)] for _ in range(100)]

    def drawNodes(self):
        for i in range(100):
            for j in range(100):
                self.bg[i][j].pos(i,j)

stage1 = Stage()

comp.py:

import pygame
import stage

class Node:

    onoff = False

    ns = 0

    def __init__(self,x,y):
        self.x = x
        self.y = y

    def pos(self,x,y):
        self.x = x
        self.y = y
        self.n1 = [x,(y-1)]
        self.n2 = [(x+1),(y-1)]
        self.n3 = [(x+1),y]
        self.n4 = [(x+1),(y+1)]
        self.n5 = [x,(y+1)]
        self.n6 = [(x-1),(y+1)]
        self.n7 = [(x-1),y]
        self.n8 = [(x-1),(y-1)]

    def nCount(self): #neighbor counter
        self.ns = 0
        counter = {
            True: 1,
            False: 0
        }
        try:
            self.ns += counter[stage.stage1.bg[self.n1[0]][self.n1[1]].onoff]
        except IndexError as error:
            pass
        try:
            self.ns += counter[stage.stage1.bg[self.n2[0]][self.n2[1]].onoff]
        except IndexError as error:
            pass
        try:
            self.ns += counter[stage.stage1.bg[self.n3[0]][self.n3[1]].onoff]
        except IndexError as error:
            pass
        try:
            self.ns += counter[stage.stage1.bg[self.n4[0]][self.n4[1]].onoff]
        except IndexError as error:
            pass
        try:
            self.ns += counter[stage.stage1.bg[self.n5[0]][self.n5[1]].onoff]
        except IndexError as error:
            pass
        try:
            self.ns += counter[stage.stage1.bg[self.n6[0]][self.n6[1]].onoff]
        except IndexError as error:
            pass
        try:
            self.ns += counter[stage.stage1.bg[self.n7[0]][self.n7[1]].onoff]
        except IndexError as error:
            pass
        try:
            self.ns += counter[stage.stage1.bg[self.n8[0]][self.n8[1]].onoff]
        except IndexError as error:
            pass
        if (self.ns > 4):
            self.ns = 4
        if (self.ns == 2):
            if (self.onoff == True):
                self.ns = 3
        return self.ns

    onImg = pygame.image.load("C:\\Users\\#####\\PythonScripts\\conway\\tiles\\pink.png")
    offImg = pygame.image.load("C:\\Users\\#####\\PythonScripts\\conway\\tiles\\purple.png")

systems.py:

import pygame
import comp
import stage
import random

pygame.init()

win = pygame.Surface((100,100)) #surface for resizing

screen = pygame.display.set_mode((600,600)) #target surface

def ruleFilter(node):
    n = {
        0: False,
        1: False,
        2: False,
        3: True,
        4: False
    }
    node.onoff = n[node.ns]

def turn(bg,x=100,y=100): #advance the game one turn
    for i in range(x):
        for j in range(y):
            bg[i][j].nCount()
    for i in range(x):
        for j in range(y):
            ruleFilter(bg[i][j])
    for i in range(x):
        for j in range(y):
            if (bg[i][j].onoff == True):
                win.blit(bg[i][j].onImg,(i,j))
            else:
                win.blit(bg[i][j].offImg,(i,j))

run = True

stage.stage1.drawNodes()

for i in range(100): #randomly activates 40% of cells
    for j in range(100):
        x = random.randint(1,100)
        if (x<=40):
            stage.stage1.bg[i][j].onoff = True

while run==True: #primary loop
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            run=False

    turn(stage.stage1.bg)

    win2 = pygame.transform.scale(win,(600,600)) #resized surface

    for x in range(100): #update screen surface
        for y in range(100):
            screen.blit(win2,(x,y))

    pygame.display.flip() #update screen

    pygame.time.delay(10) #delay before next turn

pygame.quit()

Here is a screenshot of the bug in action:

Body:
You can set the SCALED flag in your screen parameters like so

screen = pygame.display.set_mode((600,600)) #target surface

to

screen = pygame.display.set_mode((600,600), SCALED) #target surface

Additionally, you can add the FULLSCREEN flag if you would like to fill the screen. This should remove the black bars and fill the display with the game. Hope that this helps you.


问:
Cannot read properties of null (reading 'parentElement') during Unit Test
I am trying to write a unit test for the following function:

```<code>    focusSkipButton(event: MouseEvent, isLoggedIn: boolean): void {
    if (isLoggedIn) {
      return;
    }
    const button: HTMLButtonElement = document.querySelector('.skip-btn');
    const overlay = document.querySelector('.story-viewer-login-container');
    const target = event.target as Element;
    if (event.target !== overlay &&
      (target.parentElement && target.parentElement !== overlay)) {
      button.focus();
    }
   }
</code>```

This is what I have come up with:

```<code>it('should set focus on skip buuton', fakeAsync(()=>{
    let button = document.createElement('button');
    spyOn(document, 'querySelector').and.returnValue(button);
    spyOn(button, 'focus');

    var event = new MouseEvent('click', {
      view: window,
      bubbles: true,
      cancelable: true
    });

    let parent = document.createElement('div');
    let child = document.createElement('div');
    parent.append(child);
    child.dispatchEvent(event);

    component.focusSkipButton(event, false);
    tick();

    expect(button.focus).toHaveBeenCalled();

    component.focusSkipButton(event, true);
    tick();

    expect(button.focus).not.toHaveBeenCalled();
  }));
</code>```

However during running this test I am getting an error:

```<code>Cannot read properties of null (reading 'parentElement')
</code>```

I'm not sure what I'm missing here.
Any help would be greatly appreciated.

答:
The element you dispatched the click event on isn't in the DOM. target property on MouseEvent is null in that case.

You could try adding the element to the DOM, but generally I would avoid doing DOM access within Angular without ViewChild and the other Angular ways of doing it.

Body:
I am trying to write a unit test for the following function:

    focusSkipButton(event: MouseEvent, isLoggedIn: boolean): void {
    if (isLoggedIn) {
      return;
    }
    const button: HTMLButtonElement = document.querySelector('.skip-btn');
    const overlay = document.querySelector('.story-viewer-login-container');
    const target = event.target as Element;
    if (event.target !== overlay &&
      (target.parentElement && target.parentElement !== overlay)) {
      button.focus();
    }
   }

This is what I have come up with:

it('should set focus on skip buuton', fakeAsync(()=>{
    let button = document.createElement('button');
    spyOn(document, 'querySelector').and.returnValue(button);
    spyOn(button, 'focus');

    var event = new MouseEvent('click', {
      view: window,
      bubbles: true,
      cancelable: true
    });

    let parent = document.createElement('div');
    let child = document.createElement('div');
    parent.append(child);
    child.dispatchEvent(event);

    component.focusSkipButton(event, false);
    tick();

    expect(button.focus).toHaveBeenCalled();

    component.focusSkipButton(event, true);
    tick();

    expect(button.focus).not.toHaveBeenCalled();
  }));

However during running this test I am getting an error:

Cannot read properties of null (reading 'parentElement')

I'm not sure what I'm missing here.
Any help would be greatly appreciated.


问:
Disable automatic LaTeX symbol replacement in VS Code
When editing RMarkdown files in Visual Studio Code, the editor automatically replaces many LaTeX-style sequences with their unicode 'equivalents'. E.g., when I type \sum followed by a space, it is converted to ∑. While this is convenient in some cases, it is catastrophic when trying to embed LaTeX source into my file for rendering later on. Typing something like $\sum \sqrt {x_i}$ is converted to $∑ √ {x_i}$, which renders quite differently. Even pressing "escape" when the suggested replacements show up does not prevent the substitution.

Is there a way to turn this off? I've looked through the settings quite thoroughly and cannot find a way to do so. Any help would be appreciated!

(The workaround I've come up with is to copy a single space character and paste it after my symbol instead of pressing the space key on the keyboard.)

Visual Studio Code Version: 1.63.2
Mac OS 10.14.6

答:
It turns out I had an extension installed called "Fast Unicode Math Characters" which, true to it's name, was inserting unicode math characters

Disabling this fixed the issue.

(I decided to answer my own question rather than deleting the question in case someone else has a similar issue)


问:
Linked List insertion isn't working in for/while loop
I am learning DSA, and was trying to implement linked list but the insertion function that i wrote is not
working in a for or while loop, its not the same when i call that function outside the loop, it works that way. I am not able to figure it out, please someone help me.

```<code>#include <iostream>

class Node {

public:
  int data;
  Node *next;

  Node(int &num) {
    this->data = num;
    next = NULL;
  }
};

class LinkedList {

  Node *head = NULL;

public:
  void insert(int num) {
    Node *tmp;
    if (head == NULL) {
      head = new Node(num);
      tmp = head;
    } else {
      tmp->next = new Node(num);
      tmp = tmp->next;
    }
  }

  void printList() {
    Node *tmp = head;
    while (tmp) {
      std::cout << tmp->data << "  ";
      tmp = tmp->next;
    }
    std::cout << std::endl;
  }

  void reverseList() {
    Node *curr = head, *prev = NULL, *nextNode;
    while (curr) {
      nextNode = curr->next;
      curr->next = prev;
      prev = curr;
      curr = nextNode;
    }
    head = prev;
  }
};

int main() {
  LinkedList list1;
  // This is not working
  int num;
  while (num != -1) {
    std::cin >> num;
    list1.insert(num);
  }

  // This is working
  // list1.insert(1);
  // list1.insert(2);
  // list1.insert(3);
  // list1.insert(4);
  // list1.insert(5);

  list1.printList();
  list1.reverseList();
  list1.printList();

  return 0;
}
</code>```

I expect this after insertion

Edit:
although @Roberto Montalti solved this for me, but before that I tried passing incrementing value using a for loop which worked but as soon as I pull that cin out it crashes. can someone tell me what's happening under the hood?

```<code>for (int i = 1; i <= 10; i++)
{
    list1.insert(i);
}
</code>```

答:
There was an issue with your insert function.
Read about segmentation fault here https://www.geeksforgeeks.org/core-dump-segmentation-fault-c-cpp/#:~:text=Core%20Dump%2FSegmentation%20fault%20is,is%20known%20as%20core%20dump.

for a quick workaround you can use this

```<code>using namespace std;
#include <iostream>
    class Node
    {
    public:
        int data;
        Node *next;
        Node(int num)
        {
            this->data = num;
            next = NULL;
        }
    };

    class LinkedList
    {
    Node *head = NULL;

    public:
        void insert(int num)
        {
            Node *tmp= new Node(num);
            tmp->next=head;
            head=tmp;
        }
        void printList()
        {
            Node *tmp = head;
            while (tmp)
            {
                std::cout << tmp->data << "  ";
                tmp = tmp->next;
            }
            std::cout << std::endl;
        }
        void reverseList()
        {
            Node *curr = head, *prev = NULL, *nextNode;
            while (curr)
            {
                nextNode = curr->next;
                curr->next = prev;
                prev = curr;
                curr = nextNode;
            }
            head = prev;
        }
    };

    int main()
    {
        LinkedList list1;
        // This is not working
        int num,i=0,n;
        cout<<"Type the value of n";
        cin>>n;
        while (i<n)
        {
            cin >> num;
            cout<<num<<" "<<&num<<endl;
            list1.insert(num);
            i++;
        }

        list1.printList();
        list1.reverseList();
        list1.printList();

        return 0;
    }
</code>```

Body:
I am learning DSA, and was trying to implement linked list but the insertion function that i wrote is not
working in a for or while loop, its not the same when i call that function outside the loop, it works that way. I am not able to figure it out, please someone help me.

#include <iostream>

class Node {

public:
  int data;
  Node *next;

  Node(int &num) {
    this->data = num;
    next = NULL;
  }
};

class LinkedList {

  Node *head = NULL;

public:
  void insert(int num) {
    Node *tmp;
    if (head == NULL) {
      head = new Node(num);
      tmp = head;
    } else {
      tmp->next = new Node(num);
      tmp = tmp->next;
    }
  }

  void printList() {
    Node *tmp = head;
    while (tmp) {
      std::cout << tmp->data << "  ";
      tmp = tmp->next;
    }
    std::cout << std::endl;
  }

  void reverseList() {
    Node *curr = head, *prev = NULL, *nextNode;
    while (curr) {
      nextNode = curr->next;
      curr->next = prev;
      prev = curr;
      curr = nextNode;
    }
    head = prev;
  }
};

int main() {
  LinkedList list1;
  // This is not working
  int num;
  while (num != -1) {
    std::cin >> num;
    list1.insert(num);
  }

  // This is working
  // list1.insert(1);
  // list1.insert(2);
  // list1.insert(3);
  // list1.insert(4);
  // list1.insert(5);

  list1.printList();
  list1.reverseList();
  list1.printList();

  return 0;
}

I expect this after insertion

Edit:
although @Roberto Montalti solved this for me, but before that I tried passing incrementing value using a for loop which worked but as soon as I pull that cin out it crashes. can someone tell me what's happening under the hood?

for (int i = 1; i <= 10; i++)
{
    list1.insert(i);
}

Body:
There was an issue with your insert function.
Read about segmentation fault here https://www.geeksforgeeks.org/core-dump-segmentation-fault-c-cpp/#:~:text=Core%20Dump%2FSegmentation%20fault%20is,is%20known%20as%20core%20dump.

for a quick workaround you can use this

using namespace std;
#include <iostream>
    class Node
    {
    public:
        int data;
        Node *next;
        Node(int num)
        {
            this->data = num;
            next = NULL;
        }
    };

    class LinkedList
    {
    Node *head = NULL;

    public:
        void insert(int num)
        {
            Node *tmp= new Node(num);
            tmp->next=head;
            head=tmp;
        }
        void printList()
        {
            Node *tmp = head;
            while (tmp)
            {
                std::cout << tmp->data << "  ";
                tmp = tmp->next;
            }
            std::cout << std::endl;
        }
        void reverseList()
        {
            Node *curr = head, *prev = NULL, *nextNode;
            while (curr)
            {
                nextNode = curr->next;
                curr->next = prev;
                prev = curr;
                curr = nextNode;
            }
            head = prev;
        }
    };

    int main()
    {
        LinkedList list1;
        // This is not working
        int num,i=0,n;
        cout<<"Type the value of n";
        cin>>n;
        while (i<n)
        {
            cin >> num;
            cout<<num<<" "<<&num<<endl;
            list1.insert(num);
            i++;
        }

        list1.printList();
        list1.reverseList();
        list1.printList();

        return 0;
    }


问:
EXEC sp_executesql: No cross server join
I'd like to execute following statement with a clause to prevent cross server joins:

```<code>SET @Sql = N'
    SELECT TOP(1) @CodeID = CodeType
    FROM ' + QUOTENAME(@Db) + '.bla.Field
    WHERE Name = @SearchName'

EXEC sp_executesql @Sql,
    N'@SearchName NVARCHAR(256), @CodeID NVARCHAR(256) OUTPUT',
    @SearchName, @CodeID OUTPUT
</code>```

For EXEC I use this statement:

```<code>  SET @Sql = 'EXEC (''' + REPLACE(@Sql, '''', '''''') + ''')' + CASE WHEN @ServerName = @ThisServer THEN '' ELSE ' AT ' + @ServerName END
    EXEC ( @Sql )
</code>```

How do I adapt my statement to work with EXEC sp_executesql?

答:
You can use the fact that the procedure name EXEC calls can be furnished via a variable. So that can be:

```<code>DECLARE @exec nvarchar(1000) = N'sys.sp_executesql';
EXEC @exec N'SELECT 1';
</code>```

-- or

```<code>DECLARE @exec nvarchar(1000) = QUOTENAME(@db)
  + N'.sys.sp_executesql';
EXEC @exec N'SELECT 1';
</code>```

-- or

```<code>DECLARE @exec nvarchar(1000) = QUOTENAME(@server) + N'.'
  + QUOTENAME(@db)
  + N'.sys.sp_executesql';
EXEC @exec N'SELECT 1';
</code>```

In your case:

```<code>DECLARE @Sql nvarchar(max) = N'
    SELECT TOP(1) @CodeID = CodeType
    FROM bla.Field
    WHERE Name = @SearchName;';

DECLARE @exec nvarchar(1000) = CASE
  WHEN @ServerName = @ThisServer THEN N''
  ELSE QUOTENAME(@ServerName) + N'.' END
  + QUOTENAME(@db) + N'.sys.sp_executesql';

EXEC @exec @Sql,
    N'@SearchName NVARCHAR(256), @CodeID NVARCHAR(256) OUTPUT',
    @SearchName, @CodeID OUTPUT;
</code>```

Body:
I'd like to execute following statement with a clause to prevent cross server joins:

SET @Sql = N'
    SELECT TOP(1) @CodeID = CodeType
    FROM ' + QUOTENAME(@Db) + '.bla.Field
    WHERE Name = @SearchName'

EXEC sp_executesql @Sql,
    N'@SearchName NVARCHAR(256), @CodeID NVARCHAR(256) OUTPUT',
    @SearchName, @CodeID OUTPUT

For EXEC I use this statement:

  SET @Sql = 'EXEC (''' + REPLACE(@Sql, '''', '''''') + ''')' + CASE WHEN @ServerName = @ThisServer THEN '' ELSE ' AT ' + @ServerName END
    EXEC ( @Sql )

How do I adapt my statement to work with EXEC sp_executesql?

Body:
You can use the fact that the procedure name EXEC calls can be furnished via a variable. So that can be:

DECLARE @exec nvarchar(1000) = N'sys.sp_executesql';
EXEC @exec N'SELECT 1';

-- or

DECLARE @exec nvarchar(1000) = QUOTENAME(@db)
  + N'.sys.sp_executesql';
EXEC @exec N'SELECT 1';

-- or

DECLARE @exec nvarchar(1000) = QUOTENAME(@server) + N'.'
  + QUOTENAME(@db)
  + N'.sys.sp_executesql';
EXEC @exec N'SELECT 1';

In your case:

DECLARE @Sql nvarchar(max) = N'
    SELECT TOP(1) @CodeID = CodeType
    FROM bla.Field
    WHERE Name = @SearchName;';

DECLARE @exec nvarchar(1000) = CASE
  WHEN @ServerName = @ThisServer THEN N''
  ELSE QUOTENAME(@ServerName) + N'.' END
  + QUOTENAME(@db) + N'.sys.sp_executesql';

EXEC @exec @Sql,
    N'@SearchName NVARCHAR(256), @CodeID NVARCHAR(256) OUTPUT',
    @SearchName, @CodeID OUTPUT;


问:
Registering bugs by email
What is a best way to parse an email with bug description. One client decided recently that it would be nice for user to be able to send an email to known mailbox and a bug would be registered in bug tracker (not exactly bu close).

The problem is bug description has lot of fields like dates, times, descriptions, comments, losses, attachments etc. Relying on user to use some specific mail format is not the smartest thing to do.

The question is how could one parse email to get all needed information. The format should be not to strict, but enough to guess what fields mean what. I would also be interested to hear both correct and easiest solutions for this.

P.S.
Actually this feature was requested by a bank. They have a public mailbox where clients would sends discovered issues. The problem is to get as much information from these letters before bank employee will actually look at it.

答:
We do something similar to this with RT, however the email isn't really parsed. All the emails go into a single queue where it is evaluated by our IT staff. Basically, the parsing is done by humans - they modify the ticket to have as much information as they can glean from the email.

You're unlikely to get users to adhere (correctly) to any special syntax or formatting you come up with - unless they are employees, highly trained, or have some incentive to follow your rules.

Another option would be to have the initial email respond with an email that is formatted as a questionaire. In other words, the user writes an initial bug report and immediately (or as soon as your email server can respond) gets back a "thank you - can you provide more info" message with prompts for more info. You could then parse that email and have it populate your bug tracking system with more accurate info,

Good luck! Sounds like a cool idea!

OwnerDisplayName: Sergej Andrejev

ContentLicense: CC BY-SA 2.5

Title: Registering bugs by email

LastEditorDisplayName: Sergej Andrejev

OwnerDisplayName: Todd R


问:
jquery:install doesn't work in Rails
I have installed gem jquery-rails in Rails 3.1 app. But line below

```<code>rails generate jquery:install --ui
</code>```

Getting error:

```<code>Could not find generator jquery:install.
</code>```

答:
In rails 3.1, because jquery is the default, you no longer need to install it, it will be required in app/assets/jquery/application.js and it will look something like:

```<code>//= require jquery
//= require jquery_ujs
//= require_tree .
</code>```

You can verify which generators are available by executing rails g without anything else:

```<code>rails g
</code>```

Title: jquery:install doesn't work in Rails

Body:
I have installed gem jquery-rails in Rails 3.1 app. But line below

rails generate jquery:install --ui

Getting error:

Could not find generator jquery:install.

Body:
In rails 3.1, because jquery is the default, you no longer need to install it, it will be required in app/assets/jquery/application.js and it will look something like:

//= require jquery
//= require jquery_ujs
//= require_tree .

You can verify which generators are available by executing rails g without anything else:

rails g


问:
java.lang.SecurityException: signer information does not match signer information of other classes in the same package in PowerMock
When using PowerMockito.mockStatic(Test.class), where Test.class is part of the jar which is signed, I am getting SecurityException.
This happens at java.lang.ClassLoader.checkCerts(ClassLoader.java:898)
Is there anyway to avoid cert check in tests.
I am using powermock-mockito 1.6.4 version. Not able to figure out how to resolve this issue. Any help here.</p>

答:
I got a similar issue but with different details with the powermock dependency,

"java.lang.SecurityException: class ""'s signer information does not match signer information of other classes in the same package"

when i searched, almost people said the same things like this link

It means that you have two or more classes in the same package with different signature data. Usually that means the classes come from different JARs, one of which is signed and the other is unsigned.

I tried to change the dependency version but it doesn't work.
but when I downgrade the maven version from 3.6.3v to use 3.0.5v. Everything is working fine.


问:
Unable to add coverlet nuget package(s) - Version string portion was too short or too long
When I try to add coverlet.msbuild to my test project I get this error:

```<code>The expression "[System.Version]::Parse('')" cannot be evaluated. Version string portion was too short or too long.  C:\my_repo\packages\coverlet.msbuild.3.1.2\build\coverlet.msbuild.targets
</code>```

I do see changes to my csproj:

```<code><Import Project="..\packages\coverlet.msbuild.3.1.2\build\coverlet.msbuild.props" Condition="Exists('..\packages\coverlet.msbuild.3.1.2\build\coverlet.msbuild.props')" />

<Error Condition="!Exists('..\packages\coverlet.msbuild.3.1.2\build\coverlet.msbuild.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\coverlet.msbuild.3.1.2\build\coverlet.msbuild.props'))" />
<Error Condition="!Exists('..\packages\coverlet.msbuild.3.1.2\build\coverlet.msbuild.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\coverlet.msbuild.3.1.2\build\coverlet.msbuild.targets'))" />

<Import Project="..\packages\coverlet.msbuild.3.1.2\build\coverlet.msbuild.targets" Condition="Exists('..\packages\coverlet.msbuild.3.1.2\build\coverlet.msbuild.targets')" />
</code>```

But no changes to packages.config, so it looks like the nuget isn't actually installed.

I'm trying to add this to a .net 4.8 test project.

Any ideas to what may cause this?

答:
The error message tells you that the error is coming from C:\my_repo\packages\coverlet.msbuild.3.1.2\build\coverlet.msbuild.targets. So let's take a look at it. Since Coverlet is open source, I can link to its source: https://github.com/coverlet-coverage/coverlet/blob/1e74dd43824fc49e90622a3442133c2d9f4e8e01/src/coverlet.msbuild.tasks/coverlet.msbuild.targets (current master branch commit, using permalink just in case the file changes in the future)

Since the error talks about System.Version, we can search for it, and we find it near the top, on line 11. It's trying to parse two properties, _CoverletSdkNETCoreSdkVersion and _CoverletSdkMinVersionWithDependencyTarget. The first property is defined as _CoverletSdkNETCoreSdkVersion>$(NETCoreSdkVersion)</_CoverletSdkNETCoreSdkVersion>.

Therefore I conclude that the package author only intends to support SDK sytle projects, not ".NET Framework" (non-sdk) style projects. They just implemented it in a way that crashes their code in non-sdk style projects.

Note that you can still target the .NET Framework using an SDK style project. Create a ".NET" (new branding for .NET Core since .NET 5) test project, then edit the csproj and change <TargetFramework>net6.0</TargetFramework> to <TargetFramework>net48</TargetFramework>.

I don't know why coverlet isn't in your packages.config, the package installation seems successful, it's only failing at build time, which does not happen until install is finished.

Body:
When I try to add coverlet.msbuild to my test project I get this error:

The expression "[System.Version]::Parse('')" cannot be evaluated. Version string portion was too short or too long.  C:\my_repo\packages\coverlet.msbuild.3.1.2\build\coverlet.msbuild.targets

I do see changes to my csproj:

<Import Project="..\packages\coverlet.msbuild.3.1.2\build\coverlet.msbuild.props" Condition="Exists('..\packages\coverlet.msbuild.3.1.2\build\coverlet.msbuild.props')" />

<Error Condition="!Exists('..\packages\coverlet.msbuild.3.1.2\build\coverlet.msbuild.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\coverlet.msbuild.3.1.2\build\coverlet.msbuild.props'))" />
<Error Condition="!Exists('..\packages\coverlet.msbuild.3.1.2\build\coverlet.msbuild.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\coverlet.msbuild.3.1.2\build\coverlet.msbuild.targets'))" />

<Import Project="..\packages\coverlet.msbuild.3.1.2\build\coverlet.msbuild.targets" Condition="Exists('..\packages\coverlet.msbuild.3.1.2\build\coverlet.msbuild.targets')" />

But no changes to packages.config, so it looks like the nuget isn't actually installed.

I'm trying to add this to a .net 4.8 test project.

Any ideas to what may cause this?


问:
'Step Into' is suddenly not working in Visual Studio
All of a sudden, I have run into an issue where I cannot step into any code through debugging in Visual Studio. The step over works fine, but it refuses to step into (F11) any of my code. This was working before, now all of a sudden it does not.

I've tried some things below, but I still had no success:

Delete all bin files in every project in my solution, clean solution, re-build solution.

Build projects in solution indivdualy

Restart machine

It an ASP.NET C# application consuming a WCF sevice locally. It is in debug mode. I have a breakpoint set on the page consuming the service. The breakpoint hits, but it will not step into the service code.

The ASP.NET site and the service code is all in the same solution. This all of a sudden does not work, it did work before.

How can I fix this problem?

Adding a breakpoint to the service project I get a warning:

Breakpoint will not currently be hit. No symbols have been loaded for this document.

I deleted all the bin folders for all the projects and re-built them one by one. They all succeeded, but still I am getting the symbols won't load on any breakpoint I put into any project in the solution other than the ASP.NET project where the breakpoint works. I was able to debug step into all the projects before, this is an all of a sudden thing.

Information from the output window..

```<code>'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\windows\Microsoft.Net\assembly\GAC_MSIL\SMDiagnostics\v4.0_4.0.0.0__b77a5c561934e089\SMDiagnostics.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.Runtime.DurableInstancing\v4.0_4.0.0.0__31bf3856ad364e35\System.Runtime.DurableInstancing.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.Xaml.Hosting\v4.0_4.0.0.0__31bf3856ad364e35\System.Xaml.Hosting.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\2d49cf50\14eee2cf\App_Web_jmow15fw.dll', Symbols loaded.
'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.Runtime.Serialization\v4.0_4.0.0.0__b77a5c561934e089\System.Runtime.Serialization.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.WorkflowServices\v4.0_4.0.0.0__31bf3856ad364e35\System.WorkflowServices.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Web\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Web.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Discovery\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Discovery.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Activities\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Activities.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Routing\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Routing.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Channels\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Channels.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.IdentityModel\v4.0_4.0.0.0__b77a5c561934e089\System.IdentityModel.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
</code>```

答:
Had this issue in VS2022 preview and deleting the .suo file fixed it.

Had to search for the file using file explorer. Also the file is contained within a hidden .vs folder.

Body:
All of a sudden, I have run into an issue where I cannot step into any code through debugging in Visual Studio. The step over works fine, but it refuses to step into (F11) any of my code. This was working before, now all of a sudden it does not.

I've tried some things below, but I still had no success:

Delete all bin files in every project in my solution, clean solution, re-build solution.

Build projects in solution indivdualy

Restart machine

It an ASP.NET C# application consuming a WCF sevice locally. It is in debug mode. I have a breakpoint set on the page consuming the service. The breakpoint hits, but it will not step into the service code.

The ASP.NET site and the service code is all in the same solution. This all of a sudden does not work, it did work before.

How can I fix this problem?

Adding a breakpoint to the service project I get a warning:

Breakpoint will not currently be hit. No symbols have been loaded for this document.

I deleted all the bin folders for all the projects and re-built them one by one. They all succeeded, but still I am getting the symbols won't load on any breakpoint I put into any project in the solution other than the ASP.NET project where the breakpoint works. I was able to debug step into all the projects before, this is an all of a sudden thing.

Information from the output window..

'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\windows\Microsoft.Net\assembly\GAC_MSIL\SMDiagnostics\v4.0_4.0.0.0__b77a5c561934e089\SMDiagnostics.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.Runtime.DurableInstancing\v4.0_4.0.0.0__31bf3856ad364e35\System.Runtime.DurableInstancing.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.Xaml.Hosting\v4.0_4.0.0.0__31bf3856ad364e35\System.Xaml.Hosting.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\2d49cf50\14eee2cf\App_Web_jmow15fw.dll', Symbols loaded.
'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.Runtime.Serialization\v4.0_4.0.0.0__b77a5c561934e089\System.Runtime.Serialization.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.WorkflowServices\v4.0_4.0.0.0__31bf3856ad364e35\System.WorkflowServices.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Web\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Web.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Discovery\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Discovery.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Activities\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Activities.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Routing\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Routing.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.ServiceModel.Channels\v4.0_4.0.0.0__31bf3856ad364e35\System.ServiceModel.Channels.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'WebDev.WebServer40.EXE' (Managed (v4.0.30319)): Loaded 'C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.IdentityModel\v4.0_4.0.0.0__b77a5c561934e089\System.IdentityModel.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.


问:
Transpose (rotate) data from datatable column to rows
Let' say we have the following table:

Col1
Col2
Col3
Col4

Value 1
Value 4
Value 7
10.0

Value 2
Value 5
Value 8
10.0

Value 3
Value 6
Value 9
69.47

I would like to have something like this if the user selects Col4 (or any other column, this is just an example) from the select:

Col1
Col2
Col3

Col4: 10.00

Value 1
Value 4
Value 7

Value 2
Value 5
Value 8

Col4: 69.47

Value 3
Value 6
Value 9

LIVE DATATABLES DEMO

I've been searching for hours and couldn't find anything neither in the official documentation, nor in the plugins, nor in the previous stack overflow questions.

Some people suggest you could rotate via css the datatable, but the thread it's a bit old and I haven't got it to work for my purpose.

答:
With css only I am not sure whether this is possible entirely but with jquery, you can dynamically add rows to the data table example added here (this is just for ideation the code can be cleaned up further)

Also to add the rows in particular index is based upon the ordering conditions applied to the table. (Official documentation is here)

However there is a concept of row grouping in data table (example official link here)

So by getting selected column data dynamically(follow link 1)
and then grouping as row headers (follow link 3), you can get your desired result.


问:
Edit the Web.Config file
I'm attempting to update some values in the web.config file from code during an install process.

So far I've found this for updating the connection  string,

```<code>    ' Open Application's Web.Config
    Dim config = WebConfigurationManager.OpenWebConfiguration("/" + TargetVDir, friendlySiteName)

    'Add new connection string setting for web.config
    Dim appDatabase = New ConnectionStringSettings()
    appDatabase.Name = "TimeOffEntities"
    appDatabase.ConnectionString = EFconnectionstring

    config.ConnectionStrings.ConnectionStrings.Clear()
    config.ConnectionStrings.ConnectionStrings.Add(appDatabase)

    ' Persist web.config settings
    config.Save()
</code>```

However I need to update another section and I'm not sure how. I have the settings for an email and I'm not sure how to update them. Relevant web.config section below,

```<code><configuration>

  <system.net>
    <mailSettings>
      <smtp>
        <network
             host="relayServerHostname"
             port="portNumber"
             userName="username"
             password="password" />
      </smtp>
    </mailSettings>
  </system.net>

</configuration>
</code>```

答:
You can do it as follows:

```<code>Configuration config = WebConfigurationManager.OpenWebConfiguration(...);

ConfigurationSection section = config.GetSection("system.net/mailSettings/smtp");
System.Net.Configuration.SmtpSection smtpSection = section as
                      System.Net.Configuration.SmtpSection;
if (smtpSection != null)
{
    smtpSection.Network.Host = ...;
}
config.Save();
</code>```

And of course similarly for other configuration sections.

If you click on "More..." in the Inheritance Hierarchy section of the MSDN documentation for the ConfigurationSection class you'll get a list of the ConfigurationSection-derived types for all the standard configuration sections.

Title: Edit the Web.Config file

Body:
I'm attempting to update some values in the web.config file from code during an install process.

So far I've found this for updating the connection  string,

    ' Open Application's Web.Config
    Dim config = WebConfigurationManager.OpenWebConfiguration("/" + TargetVDir, friendlySiteName)

    'Add new connection string setting for web.config
    Dim appDatabase = New ConnectionStringSettings()
    appDatabase.Name = "TimeOffEntities"
    appDatabase.ConnectionString = EFconnectionstring

    config.ConnectionStrings.ConnectionStrings.Clear()
    config.ConnectionStrings.ConnectionStrings.Add(appDatabase)

    ' Persist web.config settings
    config.Save()

However I need to update another section and I'm not sure how. I have the settings for an email and I'm not sure how to update them. Relevant web.config section below,

<configuration>

  <system.net>
    <mailSettings>
      <smtp>
        <network
             host="relayServerHostname"
             port="portNumber"
             userName="username"
             password="password" />
      </smtp>
    </mailSettings>
  </system.net>

</configuration>

Body:
You can do it as follows:

Configuration config = WebConfigurationManager.OpenWebConfiguration(...);

ConfigurationSection section = config.GetSection("system.net/mailSettings/smtp");
System.Net.Configuration.SmtpSection smtpSection = section as
                      System.Net.Configuration.SmtpSection;
if (smtpSection != null)
{
    smtpSection.Network.Host = ...;
}
config.Save();

And of course similarly for other configuration sections.

If you click on "More..." in the Inheritance Hierarchy section of the MSDN documentation for the ConfigurationSection class you'll get a list of the ConfigurationSection-derived types for all the standard configuration sections.


问:
How to create linear function in Python without using numpy.linspace()
So, i am trying to create a linear functions in python such has y = x  without using numpy.linspace(). In my understanding numpy.linspace() gives you an array which is discontinuous. But to fo

I am trying to find the intersection of y = x and a function unsolvable analytically ( such has the one in the picture ) .

Here is my code I don't know how to define x. Is there a way too express y has a simple continuous function?

```<code>import random as rd
import numpy as np

a = int(input('choose a :'))
eps = abs(float(input('choose epsilon :')))

b = 0
c = 10
x = ??????

y1 = x
y2 = a*(1 - np.exp(x))

z = abs(y2 - y1)
while z > eps :
    d = rd.uniform(b,c)
    c = d
    print(c)
print(y1 , y2 )
</code>```

答: “Not solvable analytically” means there is no closed-form solution. In other words, you cant write down a single answer on paper like a number or equation and circle it and say ”thats my answer.”  For some math problems it’s impossible to do so. Instead, for these kinds of problems, we can approximate the solution by running simulations and getting values or a graph of what the solution is.</p>

Body:
So, i am trying to create a linear functions in python such has y = x  without using numpy.linspace(). In my understanding numpy.linspace() gives you an array which is discontinuous. But to fo

I am trying to find the intersection of y = x and a function unsolvable analytically ( such has the one in the picture ) .

Here is my code I don't know how to define x. Is there a way too express y has a simple continuous function?

import random as rd
import numpy as np

a = int(input('choose a :'))
eps = abs(float(input('choose epsilon :')))

b = 0
c = 10
x = ??????

y1 = x
y2 = a*(1 - np.exp(x))

z = abs(y2 - y1)
while z > eps :
    d = rd.uniform(b,c)
    c = d
    print(c)
print(y1 , y2 )


问:
Onclick function in js not working properly
onclick function to change an image once clicked but its giving me an error in Js saying unexpected else please I need an assistance Im a newbie in programming

function changeImage(){
    let a=document.getElementById("changeimg").src
        if (a==="img/save.png") {
            return a = "img/saveblack.png"
        }

}
 else{
    return a= "img/save.png"
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code></div>

                <div class="wrapper_center">
                    <img src="img/profilepix.jpg">
                </div>

                <div class="wrapper_bottom">
                    <div class="reaction_wrapper">
                        <img src="img/heart.png">
                        <img src="img/messagereaction.png">
                        <img src="img/message.png">
                        <img src="img/save.png" id="changeimg" onclick="changeImage()">
                    </div></code>```

答:
Try this ( I suggest you use a good text editor lik vscode, webstorm, itellij or atom, all the syntax errors you have will be highlighted)

function changeImage(){
    let element = document.getElementById("changeimg")
    element.src = element.src ==="img/save.png" ? "img/saveblack.png" : "img/save.png";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper_center">
<img src="img/profilepix.jpg">
</div>
<div class="wrapper_bottom">
 <div class="reaction_wrapper">

    <img src="img/heart.png">

   <img src="img/messagereaction.png">
   <img src="img/message.png">
   <img src="img/save.png" id="changeimg" onclick="changeImage()">  </div>
</div></code>```

Body:
Try this ( I suggest you use a good text editor lik vscode, webstorm, itellij or atom, all the syntax errors you have will be highlighted)

function changeImage(){
    let element = document.getElementById("changeimg")
    element.src = element.src ==="img/save.png" ? "img/saveblack.png" : "img/save.png";
}

<div class="wrapper_center">
<img src="img/profilepix.jpg">
</div>
<div class="wrapper_bottom">
 <div class="reaction_wrapper">
   <a href="">
    <img src="img/heart.png">
   </a>
   <a href=""><img src="img/messagereaction.png"></a>
   <a href=""><img src="img/message.png"></a>
   <img src="img/save.png" id="changeimg" onclick="changeImage()">  </div>
</div>


问:
Cx_freeze bdist_msi directories syntax? how to interpret 'directory_table'
I am having trouble creating new directories with the MSI generated with cx_freeze.  I don't understand the windows direcotry_tables object and there is little to no documentation explaining it.  has anyone had any success with this?

here is the documentation for the setup script for cx_freeze bdist_msi.

https://cx-freeze.readthedocs.io/en/latest/setup_script.html#commands

similar windows documentation on 'directory tables'

https://learn.microsoft.com/en-us/windows/win32/msi/directory-table?redirectedfrom=MSDN

I would like my installer to create a directory in C:\ProgramData but I can't figure out what arguments to use in the "directory_table" 3 tuple to do this.  Below is the default example directory table which works with no errors but I am not sure where the directory is actually put.

```<code>directory_table = [
    ("ProgramMenuFolder", "TARGETDIR", "."),
    ("MyProgramMenu", "ProgramMenuFolder", "MYPROG~1|My Program"),]
</code>```

Hopefully someone has run into this previously, thanks for the help.
below is my setup.py:

```<code>from cx_Freeze import setup, Executable
import sys

company_name = 'MyCompany'
product_name = 'TestTKApp'

#list of 3-tuples.  need help here.
directory_table = [
    ("ProgramMenuFolder", "TARGETDIR", "."),
    ("MyProgramMenu", "ProgramMenuFolder", "MYPROG~1|My Program"),]

base = None
if sys.platform == 'win32':
    base = 'Win32GUI'

build_exe_options = {"includes": ["testmath"],
                     "path" : sys.path,
                     "include_files": [(r"PATH\TO\SOME\FILE","junk.txt")],

                     }

bdist_msi_options = {
    # 'upgrade_code': '{66620F3A-DC3A-11E2-B341-002219E9B01E}',
    'add_to_path': False,
    'initial_target_dir': r'C:\ProgramFiles\%s\%s' % (company_name, product_name),
    'target_name' : 'TestTKapp Installer',
    'directories' : directory_table,
    "summary_data": {"author": "Me",
    "comments": "Test TKapp",}
    }
setup(name='Test Dist App',
      version = ' 1.0.0',
      executables = [Executable(r"C:\PATH\TO\MY\APP\TestTKAPP.py", base = "Win32GUI")],
      options={'bdist_msi': bdist_msi_options,
               'build_exe': build_exe_options},
      )
</code>```

答:
Ended up using an Inno Script to create my MSI.  would still like to know how to do with with cx_freeze.

see documentation for inno scripting here.  much easier and simply process for building windows installers:

https://jrsoftware.org/isdl.php

in summary(How to build a python exe);

use pipreqs to create a requirements.txt for my project

build virtual environment with that requirments.txt

create a cx_freeze setup.py script to create MyApp.exe

run cx_freeze setup.py from my virtual environment

use Inno Script to create windows installer (msi) for MyApp.exe

Body:
I am having trouble creating new directories with the MSI generated with cx_freeze.  I don't understand the windows direcotry_tables object and there is little to no documentation explaining it.  has anyone had any success with this?

here is the documentation for the setup script for cx_freeze bdist_msi.

https://cx-freeze.readthedocs.io/en/latest/setup_script.html#commands

similar windows documentation on 'directory tables'

https://learn.microsoft.com/en-us/windows/win32/msi/directory-table?redirectedfrom=MSDN

I would like my installer to create a directory in C:\ProgramData but I can't figure out what arguments to use in the "directory_table" 3 tuple to do this.  Below is the default example directory table which works with no errors but I am not sure where the directory is actually put.

directory_table = [
    ("ProgramMenuFolder", "TARGETDIR", "."),
    ("MyProgramMenu", "ProgramMenuFolder", "MYPROG~1|My Program"),]

Hopefully someone has run into this previously, thanks for the help.
below is my setup.py:

from cx_Freeze import setup, Executable
import sys

company_name = 'MyCompany'
product_name = 'TestTKApp'

#list of 3-tuples.  need help here.
directory_table = [
    ("ProgramMenuFolder", "TARGETDIR", "."),
    ("MyProgramMenu", "ProgramMenuFolder", "MYPROG~1|My Program"),]

base = None
if sys.platform == 'win32':
    base = 'Win32GUI'

build_exe_options = {"includes": ["testmath"],
                     "path" : sys.path,
                     "include_files": [(r"PATH\TO\SOME\FILE","junk.txt")],

                     }

bdist_msi_options = {
    # 'upgrade_code': '{66620F3A-DC3A-11E2-B341-002219E9B01E}',
    'add_to_path': False,
    'initial_target_dir': r'C:\ProgramFiles\%s\%s' % (company_name, product_name),
    'target_name' : 'TestTKapp Installer',
    'directories' : directory_table,
    "summary_data": {"author": "Me",
    "comments": "Test TKapp",}
    }
setup(name='Test Dist App',
      version = ' 1.0.0',
      executables = [Executable(r"C:\PATH\TO\MY\APP\TestTKAPP.py", base = "Win32GUI")],
      options={'bdist_msi': bdist_msi_options,
               'build_exe': build_exe_options},
      )


问:
Magento How do I set the product price to 4 decimal places
For a UK or Europe store we have to show inc VAT prices. i.e. a product selling for £15.95 on the store front would be stored in the admin as £13.5744 - so that when the VAT(17.5%) is added it will make £15.95

Unfortunately Mag seems to only store the price to 2dp. Even is you enter 13.5744 in the admin for the price - you get 13.57 on refresh.

Is it possible to store admin product price in 4dp and at frontend we show on 2dp?.

Cheers,

答: For those who don't want to change Magento code is available free extension CurrencyManager that can do it.</p>