text:
Q: Flutter & Firebase: Compression before upload image I want to send photo selected by user in my app to Firebase Storage. I have a simple class with property _imageFile which is set like this:
File _imageFile;

_getImage() async {
    var fileName = await ImagePicker.pickImage();
    setState(() {
        _imageFile = fileName;
    });
}

after that I send photo like with this code:
final String rand1 = "${new Random().nextInt(10000)}";
final String rand2 = "${new Random().nextInt(10000)}";
final String rand3 = "${new Random().nextInt(10000)}";
final StorageReference ref = FirebaseStorage.instance.ref().child('${rand1}_${rand2}_${rand3}.jpg');
final StorageUploadTask uploadTask = ref.put(_imageFile);
final Uri downloadUrl = (await uploadTask.future).downloadUrl;
print(downloadUrl);

The problem is that the photos are often very large. Is there any method in Flutter/Dart to compress and resize photo before upload? I am ok with loss of quality.

A: June 05, 2020 - Update
The image_picker plugin now supports an imageQuality paramater. You can do something like
ImagePicker imagePicker = ImagePicker();
PickedFile compressedImage = await imagePicker.getImage(
  source: ImageSource.camera,
  imageQuality: 85,
);

Old Answer
or if you want to compress an image without using ImagePicker
I ran into this and was able to accomplish compression / resizing with the Dart image package along with path provider. You can look at dart image api and examples for other ways and more help.
Here's what I did:
import 'package:image/image.dart' as Im;
import 'package:path_provider/path_provider.dart';
import 'dart:math' as Math;

void compressImage() async {
  File imageFile = await ImagePicker.pickImage();
  final tempDir = await getTemporaryDirectory();
  final path = tempDir.path;
  int rand = new Math.Random().nextInt(10000);

  Im.Image image = Im.decodeImage(imageFile.readAsBytesSync());
  Im.Image smallerImage = Im.copyResize(image, 500); // choose the size here, it will maintain aspect ratio

  var compressedImage = new File('$path/img_$rand.jpg')..writeAsBytesSync(Im.encodeJpg(image, quality: 85));
}

Then I uploaded compressedImage to firebase storage. You can adjust the quality that the jpg is saved with using the quality property, in my case I chose 85 (out of 100).
Hope this helps! Let me know if you have any questions.

A: Use image_picker plugin and call pick image function as
Future<File> imageFile = ImagePicker.pickImage(source: ImageSource.gallery  , maxHeight:  200 , maxWidth: 200 );
change maxHeight and maxWidth to whatever size of image you need.

A: There are many solutions :
Use image_picker package:
You can use the built-in imageQuality property of ImagePicker to compress the image. This property takes a value between 0 and 100 and represents a percentage of the quality of the original image.
First, add image_picker as a dependency in your pubspec.yaml file.
Usage
  File _image;

  Future getImage() async {
    var image = await ImagePicker.pickImage(
        source: ImageSource.gallery,
                imageQuality: 25,
    );

    setState(() {
      _image = image;
    });
  }

The advantage of this approach is that it is embedded in the
image_picker package and is therefore incredibly easy to use.

You can also adjust the quality from the Image widget.
Use filterQuality  to set the FilterQuality of the image.
Example :
Image.asset('assets/kab1.png', filterQuality: FilterQuality.high,),

These properties are present in AssetImage , NetworkImage , FileImage and MemoryImage.

You can also simply resize the image (Resizing an image can compress it). To do so, try the ResizeImage widget
Another solution is to use flutter_image_compress package

A: Besides mentioning this native library:
https://pub.dartlang.org/packages/flutter_image_compress
This is a fully dart based compressor with isolates, which might make the compression parallel to UI thread in multi core CPUs.

You might want to use compute function which makes using isolates simpler:
  https://docs.flutter.io/flutter/foundation/compute.html
https://flutter.io/cookbook/networking/background-parsing/

import 'package:image/image.dart' as ImageLib;
import 'package:path_provider/path_provider.dart';

Future<void> getCompressedImage(SendPort sendPort) async {
  ReceivePort receivePort = ReceivePort();

  sendPort.send(receivePort.sendPort);
  List msg = (await receivePort.first) as List;

  String srcPath = msg[0];
  String name = msg[1];
  String destDirPath = msg[2];
  SendPort replyPort = msg[3];

  ImageLib.Image image =
      ImageLib.decodeImage(await new File(srcPath).readAsBytes());

  if (image.width > 500 || image.height > 500) {
    image = ImageLib.copyResize(image, 500);
  }

  File destFile = new File(destDirPath + '/' + name);
  await destFile.writeAsBytes(ImageLib.encodeJpg(image, quality: 60));

  replyPort.send(destFile.path);
}

Future<File> compressImage(File f) async {
  ReceivePort receivePort = ReceivePort();

  await Isolate.spawn(getCompressedImage, receivePort.sendPort);
  SendPort sendPort = await receivePort.first;

  ReceivePort receivePort2 = ReceivePort();

  sendPort.send([
    f.path,
    f.uri.pathSegments.last,
    (await getTemporaryDirectory()).path,
    receivePort2.sendPort,
  ]);

  var msg = await receivePort2.first;

  return new File(msg);
}

if (false ==
    await SimplePermissions.checkPermission(
        Permission.ReadExternalStorage)) {
  await SimplePermissions.requestPermission(
    Permission.ReadExternalStorage);
}

File img = await ImagePicker.pickImage(
    source: ImageSource.gallery);
if (null != img) {
  img = await compressImage(img);
}

A: The image_picker plugin is currently very simple. It would be straightforward to add an option for specifying the desired size/quality of the picked image. If you do this, please send us a pull request!

A: The following code is what I use to take an image with the camera and then compress it:
import 'dart:async' show Future;
import 'dart:io' show File;
import 'package:flutter/foundation.dart' show compute;
import 'package:flutter/material.dart' show BuildContext;
import 'package:image/image.dart' as Im;
import 'dart:math' as Math;
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart' show getTemporaryDirectory;

Future<File> takeCompressedPicture(BuildContext context) async {
  var _imageFile = await ImagePicker.pickImage(source: ImageSource.camera);
  if (_imageFile == null) {
    return null;
  }

  // You can have a loading dialog here but don't forget to pop before return file;

  final tempDir = await getTemporaryDirectory();
  final rand = Math.Random().nextInt(10000);
  _CompressObject compressObject =
      _CompressObject(_imageFile, tempDir.path, rand);
  String filePath = await _compressImage(compressObject);
  print('new path: ' + filePath);
  File file = File(filePath);

  // Pop loading

  return file;
}

Future<String> _compressImage(_CompressObject object) async {
  return compute(_decodeImage, object);
}

String _decodeImage(_CompressObject object) {
  Im.Image image = Im.decodeImage(object.imageFile.readAsBytesSync());
  Im.Image smallerImage = Im.copyResize(
      image, 1024); // choose the size here, it will maintain aspect ratio
  var decodedImageFile = File(object.path + '/img_${object.rand}.jpg');
  decodedImageFile.writeAsBytesSync(Im.encodeJpg(smallerImage, quality: 85));
  return decodedImageFile.path;
}

class _CompressObject {
  File imageFile;
  String path;
  int rand;

  _CompressObject(this.imageFile, this.path, this.rand);
}

You can call this very easy with this:
import 'path/to/compress_image.dart' as CompressImage;
// ...
File file = await CompressImage.takeCompressedPicture(context);

A: While i am using

package:image/image.dart

facing below issues

*

*showing blank page while converting image ( may be taking so much process while compressing image)

*After compression image was stretched and not looking good

Then used below plugin, same working fine without any issue, even faster and what i expected
https://github.com/btastic/flutter_native_image.git

steps and method available in above link.

A: You can use a plugin called flutter_image_compress
// Active image file
File _imageFile;

// Select an image via gallery or camera
Future<void> _pickImage(ImageSource source) async {
  File selected = await ImagePicker.pickImage(source: source);

// Compress plugin
  File compressedImage = await FlutterImageCompress.compressAndGetFile(
    selected.path,
    selected.path,
    quality: 50,
  );

  setState(() {
    _imageFile = compressedImage;
    print('compressedimagesize: ${_imageFile.lengthSync()}');
  });
}

Voila! Compressed file image

A: Since you are using Firebase, one option would be using the Extension - Resize Image. It gives you the option to keep or delete the original image and it is very easy to install and use.

A: You can do as follows,
//Compressing Image
    File compressedImg = await FlutterNativeImage.compressImage(
      _image.path,
      quality: 70,
    );
//Compressing Image

A: Well
1. If you are in mobile you could use flutter_image_compress: ^1.0.0  will do the work
Eg.
Pass youe Uint8List and quality, you will get compressed image in no time.
Future<Uint8List> testComporessList(Uint8List uint8List) async {
    var result = await FlutterImageCompress.compressWithList(
      uint8List,
      quality: 50,
    );
    return result;
}

2. But If you are in flutter web then you won't get any other option than image picker etc etc.
I end up using javascript. You can find answer here.
Flutter Web: How Do You Compress an Image/File?

A: Update 2020 'pickImage' is deprecated and shouldn't be used. Use imagePicker.getImage() method instead**
  ImagePicker picker = ImagePicker();
   PickedFile compressedImage = await imagePicker.getImage(
  source: ImageSource.camera,
  imageQuality: 80,
);

Doc for ImageQuality :

Returns a PickedFile object wrapping the image that was picked. The
returned PickedFile is intended to be used within a single APP
session. Do not save the file path and use it across sessions. The
source argument controls where the image comes from. This can be
either ImageSource.camera or ImageSource.gallery. Where iOS supports
HEIC images, Android 8 and below doesn't. Android 9 and above only
support HEIC images if used in addition to a size modification, of
which the usage is explained below. If specified, the image will be at
most maxWidth wide and maxHeight tall. Otherwise the image will be
returned at it's original width and height. The imageQuality argument
modifies the quality of the image, ranging from 0-100 where 100 is the
original/max quality. If imageQuality is null, the image with the
original quality will be returned. Compression is only supported for
certain image types such as JPEG and on Android PNG and WebP, too. If
compression is not supported for the image that is picked, a warning
message will be logged. Use preferredCameraDevice to specify the
camera to use when the source is ImageSource.camera. The
preferredCameraDevice is ignored when source is ImageSource.gallery.
It is also ignored if the chosen camera is not supported on the
device. Defaults to CameraDevice.rear. Note that Android has no
documented parameter for an intent to specify if the front or rear
camera should be opened, this function is not guaranteed to work on an
Android device. In Android, the MainActivity can be destroyed for
various reasons. If that happens, the result will be lost in this
call. You can then call getLostData when your app relaunches to
retrieve the lost data.


text:
Q: Is there a way to sync Dynamics CRM contacts to surveymonkey? Is there a way to sync Dynamics CRM contacts to surveymonkey? I would like to find a syncing app which can automatically import all my Dynamics CRM contacts to Surveymonkey. It would make my workflow much easier, instead of uploading CSV files... Any ideas? Someone?

A: Power Automate would be a good solution for what you're looking to achieve.
Power Automate will effectively let you integrate practically any service that uses an API using a concept of connectors. survey monkey has a connector for power Automate, however you may have to create a custom connector to perform bulk data uploads - I checked the survey monkey connector and it does not have a lot of actions - https://learn.microsoft.com/en-gb/connectors/surveymonkey/#actions
Your Power Automate flow can be created to run on a daily basis to move data between dynamics and Survey Monkey

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use launchctl for .ovpn file execution and dns I am running BigSur OS.
Recently I was given an OpenVPN file to run a VPN.
When I execute this in the terminal I get
➜  vpn sudo openvpn --config ./bpu-vpn.ovpn
Options error: --up script fails with '/usr/bin/update-systemd-resolved': No such file or directory (errno=2) Options error: Please correct this error. Use --help for more information
update-systemd-resolved is a linux thing. Some google searches reveal that mac needs to use daemon via launchd on mac. But how to configure this, I am completely lost.
The VPN file tries to hit /usr/bin/update-systemd-resolved bash file in my system, of which there is none.
What is the way to manage this DNS issue with mac?


text:
Q: Is there a way to get the canned ACL of an existing S3 object? I'm trying to copy an existing object from one key to another in the same bucket.
I'd like to get the canned ACL e.g.  "private"|"public-read"|"public-read-write"|"authenticated-read"|"aws-exec-read"|"bucket-owner-read"|"bucket-owner-full-control" so that I can then apply this to the new object.
What's the best way to do this using the Node.js SDK?

A: You can call getObjectAcl() to obtain the ACL on the source object, and then specify that information using putObjectAcl(), or even specify it as part of the copyObject() call.
You won't get the "canned ACL", but you will get the permissions on the object that were created as a result of the original Canned ACL.


text:
Q: How to install Hive without HDFS on windows 10 I want to install hive in standalone mode on windows 10. I want o use my local system for metastore storage instead of HDFS. what changes should be done in hive-site.xml file to start HIVE in command prompt.

A: The hive Metadata is just stored in a relational DB, this is not on Hdfs. There is a default which you can configure to point elsewhere. The actual hive data needs to rest on Hdfs as far as I know.


text:
Q: What is the short key to delete the whole row in Excel 2007 without using mouse? I am trying to find the short key for deleting the entire row in Excel 2007 without taking help of mouse.

A: You can use Ctrl + -
Ctrl+-  == Deletes Rows, Columns, or Cells Depends on selection

You should first select the entire row.
For this you can use Home then  Ctrl + Shift + Right Arrorw.
OR
You can just click on the row number to select entire row.
After selecting the entire row, If you press Ctrl + - then entire row will be deleted.


text:
Q: ASM to C: What does 4(%esp) refer to I'm trying to translate the following assembly code to C code:
fct:
    movl 4(%esp), %eax
    cmpl $0,%eax
    jg n
    movl $-1,%eax
    ret
n:  movl $0,%ebx
    movl %eax, %ecx
    movl $0, %eax
    movl $0, %edx
l:  addl $2, %ebx
    addl %ebx, %eax
    addl $1, %edx
    cmpl %ecx, %edx
    jl l
    ret

As I think I can translate most of this pretty easily, I can't seem to find what the first line (movl 4(%esp), %eax) does.  What does 4(%esp) refer to in this context?
I know the %esp register refers to the last instruction of the pile and that 4(%esp) refers to the second one.

A: mov is a "move" instruction. l in movl means that it operates on "long" value (32-bit in your case). Parenthesis around %esp in (%esp) mean that it should move not the content of the register %esp, but should load memory at address in register %esp. 4 in 4(%esp) refers to offset that is added to %esp before it is dereferenced.
So this instruction loads 32-bit value from address %esp + 4 and stores it in register %eax.
Because in x86 all function arguments are store on the thread stack (mostly, other calling conventions can be used), this instruction loads function argument in register %eax.
In C arguments are pushed in reversed order (from the last to the first), so it loads the first argument.
Seems that original function was defined in C like this:
int fct(int val);

Instruction jg is generated for signed greater comparison, so the first line seems to be
if (val > 0)
   ...


text:
Q: What are power supply "rails" and how do I use them? I have a EVGA 1500 Classified and am learning how to build my first high end PC in 12 years.  Since the '90s something called Power Supply "Rails" was invented and I think it has something to do with the GPU.
What are power supply rails (electrically speaking) and how should I use them intelligently (or not) in a custom build?

A: Rails are independent power channels.
For example:
Rail 1   5 Volt 20 Amp
Rail 2   5 Volt 30 Amp

You have a total of 50 Amp at 5 volt, but they are isolated.
Positives:
A electrical short on 1 rail will not effect the other rail and vice versa.
Negative:
A device requiring 35 Amps at 5 volts can not be connected since neither rail has that much.
Video cards are generally placed on a separate rail, whenever possible, since they consume so much power.
The same principles apply for 3.3V and 12V.
If any rail drops below 5% of the stated voltage you need to move something to a different rail.  5 volt can go to 4.75, and 12V can go as low as 11.4V (but should not)
You need to check the rails under load and not under idle.


text:
Q: PHP Sessions issues while on server but no on localhost I'm passing the user variable through sessions. It works fine on the localhost but once on the web server it does weird things.
After logging in, the session variable works as should.....until you click on about three pages and it suddenly goes POOF!
Notice the "Welcome, jordan." as opposed to the "Welcome, ." Also the top left corner.
Session functioning:
http://imageshack.us/photo/my-images/32/loggedins.png/
Session POOF!
http://imageshack.us/photo/my-images/515/loggedinno.png/
Login/Create session variable code:
<?php
        if (!isset($_SESSION['user']))
        {
        if (isset($_POST['user']))
        {
        $user = sanitizeString($_POST['user']);
        $pass = sanitizeString($_POST['pass']);
        if (preg_match($txtMatch,$user))
        {
        if ($user == "" || $pass == "")
        {
        $error = "Please enter all required fields";
        }
        else
        {
        $query = "SELECT * FROM gtmembers WHERE user='$user'";
        $result = queryMysql($query);
        $rank = mysql_result($result, 0, 'rank');
        if (!mysql_num_rows($result))
        {
        $error = "Username does not exist.";
        }
        else
        {
        $getPass = mysql_result($result, 0, 'pass');
        $salt = substr($getPass, 0, 64);
        $hash = $salt . $pass;
        for ($i = 0; $i < 100000; $i++)
        {
        $hash = hash('sha256', $hash);
        }
        $hash = $salt . $hash;
        if ($hash == $getPass)
        {
        if ($rank != "Banned")
        {
        $userLow = strtolower($user);
        $_SESSION['user'] = $userLow;
        $_SESSION['rank'] = $rank;
        echo <<<_END

        _END;
        echo "Successfully logged in. Click here to continue.";
        }

Header Code:
        <?php //gtheader.php
        session_start();
        include_once 'gtfunctions.php';
        $loggedIn = FALSE;

        if (isset($_SESSION['user']))
        {
        $user = $_SESSION['user'];
        if ($user) echo "Current User: $user
";
        else echo "Current User: None
";
        $rank = $_SESSION['rank'];
        $loggedIn = TRUE;
        echo "is set SESSION['user']? Yes";
        }
        else echo "is set SESSION['user']? No";

        echo "

$appname
";
        if ($loggedIn == TRUE)
        {
        $query = "SELECT * FROM gtmessages WHERE recip='$user' AND status='0'";
        $result = queryMysql($query);
        if (mysql_num_rows($result) == 0) $num = "";
        else $num = "[".mysql_num_rows($result)."]";
        if ($rank == 'Owner' || $rank == 'Admin')
        {
        echo "Welcome, $user$num. [Logout] | Admin
";
        }
        else
        {
        echo "Welcome, $user$num. [Logout]
";
        }
        }
?>

A: If it works in one environment and not the other, I'm guessing your PHP.ini has session.auto_start = 1 in the environment that works.  Best practice is to always call session_start() at the top of your page and not rely on php.ini to be set correctly.  This should make it work in any environment.

A: Solved.
The issue here is that Host Gator registers global variables. So since I use $user, and $_SESSION['user'] gets registered, it gets overwritten.
I fixed the issue by changing $_SESSION['user'] in all files to $_SESSION['myUser']
Thanks for the help.

A: Must call session_start() at the top of the page
gtheader.php
<?php
    session_start();
    include_once 'gtfunctions.php';
    $loggedIn = FALSE;
    .....


text:
Q: Where to put the language for an AC_DEFUN? I'm using an alternate AC_COMPILE_IFELSE as shown below.
BAD_RESULT="fatal|error|unknown|unrecognized|illegal|ignored|not found|not exist|cannot find"

AC_DEFUN([XXX_COMPILE_IFELSE],
   [AC_REQUIRE([AC_PROG_EGREP])
   AC_COMPILE_IFELSE(
      [$1],
      [retval=0
        if $EGREP -i -c -E "$BAD_RESULT" conftest.err >/dev/null; then retval=1; fi
      ],[retval=1]
   )
   AS_IF([test $retval = 0],[$2],[$3])]
)

When I autoreconf to create the configure scipt, the alternate is generating a lot of warnings like:
configure.ac:812: warning: AC_LANG_CONFTEST: no AC_LANG_SOURCE call detected in body
../../lib/autoconf/lang.m4:194: AC_LANG_CONFTEST is expanded from...
../../lib/autoconf/general.m4:2591: _AC_COMPILE_IFELSE is expanded from...
../../lib/autoconf/general.m4:2607: AC_COMPILE_IFELSE is expanded from...
configure.ac:152: XXX_COMPILE_IFELSE is expanded from...
configure.ac:812: the top level

The Autotools documents (here and here and here) don't discuss where to put the language. I tried to bookend AC_COMPILE_IFELSE with calls to AC_LANG_PUSH([C++]) and AC_LANG_POP but it did not squash the warning.
Where do I tell machinery that the language is C++?

Here is an example of using XXX_COMPILE_IFELSE.
XXX_PROGRAM="#include <wmmintrin.h>
  int main(int argc, char* argv[]) {
     __m128i x;
     x=_mm_aesenc_si128(x,x);
     x=_mm_aesenclast_si128(x,x);
     return 0;
  }"

CXXFLAGS="-xarch=aes"
AC_MSG_CHECKING([if $CXXNAME supports $CXXFLAGS])
XXX_COMPILE_IFELSE(
  [$XXX_PROGRAM],
  [AC_MSG_RESULT([yes]); AC_SUBST([tr_RESULT], [1])],
  [AC_MSG_RESULT([no]);  AC_SUBST([tr_RESULT], [0])]
)

The head of configure.ac has the following. It seems like it is not being honored since switching to XXX_COMPILE_IFELSE.
AC_INIT([Crypto++], [7.1], ...)
AM_INIT_AUTOMAKE

AC_CONFIG_MACRO_DIR([m4])
AC_CONFIG_HEADERS([local.h])
AC_CONFIG_FILES([Makefile] [libcryptopp.pc])
AC_CONFIG_SRCDIR([configure.ac])

AM_PROG_AS
AC_PROG_LIBTOOL
LT_INIT

AC_PROG_CXX
AC_LANG([C++])
AC_PROG_GREP

## Assert this once to avoid surprises
AC_LANG_ASSERT([C++])


text:
Q: ASP.NET Core option dependency in constructor I'm using ASP.NET Core and I'm attempting to create a resolvable class which has an optional parameter:
public class Foo
{
     public Foo() : this(null)
     {}

     public Foo(IValidator<FooEntity> validator)
     {
     }
}

I've created two constructors for this object so that if a dependency isn't found, I would assume it would just fall back to the default constructor.
However when I run my application I receive this error

Additional information: Unable to resolve service for type 'FluentValidation.IValidator`1[FooEntity]' while attempting to activate 'Foo'

I know there is probably a way to manually resolve the construction of the Foo object. But I would prefer not to do that because I will have to do this for every class that I create without a validator.
Does anyone know how to configure ASP.NET Core DI to fall back to a different constructor if the dependency is not found?
EDIT
Sorry, I should of been a bit more clear before.
This Foo class I'm referring to in really a base class for a CRUD Service,  which will be used over and over again.
I'm looking for a generic solution which doesn't require me to configure each Service I create each time.
So using a lambda to resolve this is not an option,  The null object pattern seems feasible but I can't comprehend how to write a generic one in which I won't have to configure for each service

A: I think its general behavior of Containers to resolve the constructor with the most parameters.
Basically what AddTransient does is the following:
services.AddTransient<Foo>();
//equals to:
services.AddTransient<Foo>(c=> new Foo(c.GetService<IValidator<FooEntity>()));

So you can register it yourself like this:
services.AddTransient<Foo>(c=> new Foo());

At this point in the startup class you should know if IValidator<FooEntity> has been registered. Or, if you are using reflection add this logic to your reflection code.
Difference
The difference between the 2 options is that with the first option is that the lambda function to resolve the class is created on startup. + if you change the constructor no code needs to be changed elsewhere.
If you create the lambda yourself this lambda is compiled on build, so theoretically startup should be faster (I have not tested this).
Great mindset
A great mindset is to own the libraries you are using. In Visual studio/Resharper you can decompile source-code, or you can find the repositories on github nowadays.
There you can see the source code, you can see how the services parameters is 'compiled' to the IServiceProvider (see BuildServiceProvider() method, it will give you alot of insight.)
Also look at:

*

*ServiceDescriptor, Your type registration.

*Service, the one that resolves the type.

Solution
best way to do it is this, (sorry for psuedo code but i have no editor at hand).
getTypes()
    .Where(x=> x.EndsWith("Entity") //lets get some types by logic
    .Select(x=> typeof(IValidator<>).MakeGeneric(x)) //turn IValidator into IValidator<T>
    .Where(x=> !services.IsRegistered(x))
    .Each(x=> services.Add(x, c=> null)) //register value null for IValidator<T>

A: You need to register the IValidator<T> first:
  var services = new Microsoft.Extensions.DependencyInjection.ServiceCollection();
  services.AddTransient<IValidator<FooEntity>, RealValidator<FooEntity>>();
  services.AddTransient<Foo>();

  var serviceProvider = services.BuildServiceProvider();
  var validator = serviceProvider.GetService<IValidator<FooEntity>>();
  var foo = serviceProvider.GetService<Foo>();

  Assert.NotNull(validator);
  Assert.NotNull(foo);


text:
Q: Execution of JavaScript without script tag in SAPUI5 I am using the sap ui5. which loads and executes controller.js files and view.js files dynamically. But the thing is these javascript files are used without script tag. you can see in this picture.

Here you can see the HelloWorld.view.js
But there are no script in the html content. I just want to know how that file is added to the workspace (left side sources tab) and not linked with script tag. but strange it is working. we can put debugger on that JavaScript file also in developer mode. I am curious to know this for my clear understanding.
Thanks

A: Helloworld view is loaded by UI5 dependency management system. Here it is loaded once you declare your view sap.ui.view. Internally there's a call to jQuery.sap.require that loads the view (a.k.a module). This is called Modularization and Dependency Management and it makes sure that the module is loaded only when it is required. In case the module is required multiple times, it's also loaded only one time.

A: I think what you are looking for can be found here:
https://github.com/SAP/openui5/blob/master/src/sap.ui.core/src/jquery.sap.global.js#L1739
Those other script files are loaded by AJAX requests as strings and then parsed/evaluated. But before parsing a new "line" is added at the end, with the
//# sourceUrl=...
 directive. This makes the browser understand where the code was loaded from and display the code as if it were directly loaded from that URL..
Also see https://developer.mozilla.org/en-US/docs/Tools/Debugger/How_to/Debug_eval_sources for more details.


text:
Q: Lightning component get user's language rather than user's locale I have a few labels I use on my Lightning Components. They are all based on the user's locale but nothing changes when user's language changes.
How can I change this ? My users never change locale parameter but only language field.
Thank you

A: Maybe it's taking your company's default language/locale.
Not sure about it, but I found this :
"Click on Setup | Administration Setup | Company Profile | Company Information | Edit and change the Default Language, Default Locale, and Currency Locale. All new users will inherit these Language and Locale settings."

A: I found something else : https://success.salesforce.com/issues_view?id=a1p3A000000IYHKQA4
Try a hard refresh, Ctrl+Shift+R .


text:
Q: Twitter icon missing on the profile page of the network sites
When I first started seeing this, I thought this could be some render because of poor internet error that time or whatever. I basically ignored it. I think its a issue which was okay few weeks ago I guess.

A: The issue is now resolved after disabling ad-blocker / adding site to exception list. There's nothing wrong with the site. It was working few days back (maybe 1 week) and when it stopped working, without checking things properly I thought this is something with the site.
Thanks to @Sebastian Simon. According to him,

That means, you probably have enabled some "social media blocker" or similar which blocks icons with a class name of iconTwitter or perhaps anything containing "Twitter" (same for "Facebook", etc.). Maybe you can set Stack Exchange as an exception somehow.


text:
Q: Matrix-like operations for 3D arrays in R? I'm currently estimating a model in R using optim, but it's really slow, on the order of 30 minutes if I initialize it with zeroes.  When I profile the whole thing, I find that apply is taking the most time, which makes sense.  So that leads me to my question:
x.arr <- array(1:9, c(3, 10, 3))
b    <- 1:3

f <- function(x, b) {
    exp(x%*%b)
}

u.mat <- apply(x.arr, 2, f, b = b)

Is there a more efficient way to do this? x.arr is a 3D array, so it seems like there ought to be some way to use matrix operations to solve the same goal.
Additionally, I run Linux, so I assume that I can also easily do something with mclapply or something, but every time that I've made the attempt, I've managed to hang my entire R session.
There's also a package, tensor but everything I've tried from it so far was so far from what I was actually looking for that I wasn't even sure what I was getting back.
My linear algebra isn't the best, but something tells me there ought to be some sort of good option without using apply.

A: As these things go, I found a solution that speeds it up considerably using the tensor package. (I spent 4 hours on this yesterday, but apparently today things just clicked.)
require(tensor)

x.arr <- array(1:9, c(3, 10, 3))
b     <- 1:3

u.mat <- exp(tensor(x.arr, b, alongA = 3, alongB = 1))

Which now takes me from a time of ~ 30 minutes to a time of around ~ 10 minutes.
I'm still interested if anyone has an idea of how to make it faster, of course, but maybe if someone else finds this question, this will at least be a satisfactory answer for them.


text:
Q: Verify formatting in a number I have a table full of numbers and need to verify if each of the number has 0 decimals and has separators',' used for '000s .
Like:  123,456
How can i verify this?
Thanks

A: s = '74,456,890'
if s =~ /^\d{1,3}(?:,\d{3}+)$/
   # String s has the required format
else
   # String s does not have the required format
end

A: Assuming that numbers are stings (because there are , sign):
numbers = [
  '100,000',
  '100,246.40',
  '100,000,304',
  '300.210',
  '10,200'
]

numbers.map { |n| n =~ /^\d{1,3},((\d{3})|(\d{3},))+$/ ? n : nil }.compact
#=> ["100,000", "100,000,304", "10,200"]


text:
Q: Extend GWT application with Angular What we have: an application built with GWT, it is single page, "tree on the left", "tabs on the right".
What we need: We would love to extend it using Angular.
Question: Is it possible to embed Angular elements to a few places of our app, also note "multi-tabs" nature, so many documents can be opened at once and each document can have its own plugins configuration?
PS: Seems it might be an answer Angular and GWT in perfect harmony


text:
Q: convert list to dictionary with numbers list = ["a", "b", "c", "d", "e"]

I want to convert this list into dictionary as follows
dictionary = {"1": "a", "2": "b", "3": "c", "4": "d", "5": "e"}

Here numbers should incremented based on the list length.

A: {str(i): k for i, k in enumerate(list, 1) }

Change your list var name.
Note: passing a int to enumerate(list, number), you can choose from what number the counting start.

A: {str(i + 1): v for i, v in enumerate(list)}

Please note that it is very unwise to call a list (or anything else) list (since you'd lose access to the list type).


text:
Q: После закрытия окна остается висеть процесс. Здравствуйте. Копаю Glut и OpenGL. Компилирую MinGW:
g++ main.cpp -o main -mwindows glut32.lib -lopengl32 -lglu32

Код программы (использовал не только этот - все такая же проблема):
#include <windows.h>
#include <GL/glut.h>

void display()
{
  glClear(GL_COLOR_BUFFER_BIT);
  glBegin(GL_LINES);
  glColor3f(1.0, 0.0, 0.0);
  glVertex2f(0.25, 0.25);
  glVertex2f(0.75, 0.75);
  glColor3f(0.0, 1.0, 0.0);
  glVertex2f(0.75, 0.25);
  glVertex2f(0.25, 0.75);
  glColor3f(0.0, 0.0, 1.0);
  glVertex2f(0.50, 0.25);
  glVertex2f(0.50, 0.75);
  glEnd();
  glFlush();
}

int main(int argc, char **argv)
{
  glutInit(&argc, argv);
  glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
  glutInitWindowSize(240, 240);
  glutInitWindowPosition(100, 740);
  glutCreateWindow("Test");
  glClearColor(1.0, 1.0, 1.0, 1.0);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
  glutDisplayFunc(display);
  glutMainLoop();
  return 0;
}

Суть такова - программа работает хорошо , всё компилируется  , предупреждений нет. Но закрыв окно программы (любым способом) процесс остается висеть в диспетчере. Поэтому приходится заходить каждый раз в процессы и там вырубать main.exe. Как это побороть?
Заранее спасибо.
A:
Поэтому приходится заходить каждый раз в процессы и там вырубать main.exe

Если подождать некоторое время, то процесс сам не заканчивается?
А вообще ответ таков, что процесс и не должен оставаться в памяти.
3.090 How can I make glutMainLoop() return to my calling program?

glutMainLoop() isn't designed to return to the calling routine. GLUT was designed around the idea of an event-driven application, with the exit method being captured through an input event callback routine, such as a GLUT menu or keyboard callback handler.
If you insist on returning to your program from glutMainLoop(), there is only one way to do so. You need to download the GLUT source and hack gluMainLoop() to do what you want it to. Then compile and link into your program this hacked version of glutMainLoop().


text:
Q: TinyMCE plugin not showing My plugin doesnt show up in tinymce even though I can see it getting called.  Anyone see what Ive missed?
(function () {
tinymce.PluginManager.requireLangPack('prettifier');
tinymce.create('tinymce.plugins.PrettifierPlugin', {
    init: function (ed, url) {
        debugger;
        //            ed.addCommand('mcePrettifier', function () {
        //                ed.windowManager.open({
        //                    file: url + '/dialog.htm',
        //                    width: 320 + ed.getLang('prettifier.delta_width', 0),
        //                    height: 120 + ed.getLang('prettifier.delta_height', 0),
        //                    inline: 1
        //                });
        //            });

        //            ed.addButton('prettifier', {
        //                title: 'prettifier.desc',
        //                cmd: 'mcePrettifier',
        //                image: url + '/img/prettifier.gif'
        //            });

        ed.addButton('prettifier', {
            title: 'prettifier.desc',
            cmd: 'mcePrettifier',
            image: url + '/img/prettifier.gif',
            onclick: function () {
                ed.focus(),
                ed.selection.setContent('
' + ed.selection.getContent() + '
');
            }
        });

    },

    createControl: function (n, cm) {
        return null;
    },

    getInfo: function () {
        return {
            longname: 'Code Prettifier plugin',
            author: 'blah',
            authorurl: 'http://blah.com',
            infourl: 'http://blah.com',
            version: "1.0"
        };
    }
});

debugger;
tinymce.PluginManager.add('prettifier', tinymce.plugins.PrettifierPlugin);
})();

Thanks

A: Assuming that you've included it correctly in both the plugins element and a *theme_advanced_buttons* config item then I suspect the problem is a JavaScript error in your plugin.
In the code you've included, you have a comma instead of a semi-colon at the end of ed.focus() in the onclick for the button.


text:
Q: Test: is caller from Internet Explorer ended? (sorry for my bad english)
In a my.vbs I start the IE with:
Set oIE_ = WScript.CreateObject( "InternetExplorer.Application", "IE_" )

and make some settings in the IE with:
oIE_.navigate my.html

Then I have this Sub:
Sub IE_onQuit
   msgbox "IE closed !"
End Sub

With this callback-Sub the my.vbs can recognize, if the IE was closed. This works very good.
But now I want also recognize in my.html (with Javascript), if the caller my.vbs was finished/closed. If I close my.vbs, then the IE keep going. I found no way, to start the IE as a child-process, in order to if the vbs was closed then the IE also closed automatically.
I'm searching now for 3 days with no luck. I want tell more, but my english is not enough.
Can anyone help me please?


text:
Q: For loop through multiple rows by the index using pandas Using the following data in train_data_sample and the below code, how can I iterate through each index latitude and longitude? (see below for wished results)
   latitude longitude price
0   55.6632 12.6288 2595000
1   55.6637 12.6291 2850000
2   55.6637 12.6291 2850000
3   55.6632 12.6290 3198000
4   55.6632 12.6290 2995000
5   55.6638 12.6294 2395000
6   55.6637 12.6291 2995000
7   55.6642 12.6285 4495000
8   55.6632 12.6285 3998000
9   55.6638 12.6294 3975000

from numpy import cos, sin, arcsin, sqrt
from math import radians

def haversine(row):

    for index in train_data_sample.index:
        lon1 = train_data_sample["longitude"].loc[train_data_sample.index==index]
        lat1 = train_data_sample["latitude"].loc[train_data_sample.index==index]
        lon2 = row['longitude']
        lat2 = row['latitude']
        lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
        dlon = lon2 - lon1
        dlat = lat2 - lat1
        a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
        c = 2 * arcsin(sqrt(a))
        km = 6367 * c
    return km

def insert_dist(df):
    df["distance"+str(index)] = df.apply(lambda row: haversine(row), axis=1)
    return df

print(insert_dist(train_data_sample))

This is the result for index 0. It looks at the coordinates for index 0 versus every other row and returns the distance in meters. So the distance between coordinates for index 0 and 1 are ~50 meters.
latitude    longitude   price   distance0
0   55.6632 12.6288 2595000    0.000000
1   55.6637 12.6291 2850000    0.058658
2   55.6637 12.6291 2850000    0.058658
3   55.6632 12.6290 3198000    0.012536
4   55.6632 12.6290 2995000    0.012536
5   55.6638 12.6294 2395000    0.076550
6   55.6637 12.6291 2995000    0.058658
7   55.6642 12.6285 4495000    0.112705
8   55.6632 12.6285 3998000    0.018804
9   55.6638 12.6294 3975000    0.076550

The end result should return not only distance0, but also distance1, distance2, etc.

A: It seems like your making things a bit more complicating than necessary. By nesting a for loop in another for loop you can achieve what you want in a more straightforward way.
from numpy import cos, sin, arcsin, sqrt
from math import radians
import pandas as pd
import numpy as np

# recreate your dataframe
data = [[55.6632, 12.6288, 2595000],
        [55.6637, 12.6291, 2850000],
        [55.6637, 12.6291, 2850000],
        [55.6632, 12.6290, 3198000]]

data = np.array(data)

train_data_sample = pd.DataFrame(data, columns = ["latitude", "longitude", "price"])

# copied  "distance calculating" code here
def GetDistance(lon1, lat1, lon2, lat2):
    lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
    dlon = lon2 - lon1
    dlat = lat2 - lat1
    a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
    c = 2 * arcsin(sqrt(a))
    km = 6367 * c
    return km

# loop over every row with iterrows
for index, row in train_data_sample.iterrows():

    distances = []

    lat1, lon1 = row[["longitude", "longitude"]]

    # loop again over every row with iterrows
    for index_2, row_2 in train_data_sample.iterrows():
        lat2, lon2 = row_2[["longitude", "longitude"]]
        # get the distance
        distances.append( GetDistance(lon1, lat1, lon2, lat2) )

    # add the column to the dataframe
    train_data_sample["distance"+str(index)] = distances

A: I would not use apply here as it works row wise, but would go for a matrix approach using numpy instead.
First convert all degrees into radians:
df['latitude'] *= np.pi/180
df['longitude'] *= np.pi/180

Then turn the latitude and longitude vectors into matrices by duplicating the vector as many times as the length of the vector. For lat2/lon2 take the transpose.
lat1 = np.tile(df['latitude'].values.reshape([-1,1]),(1,df.shape[0]))
lon1 = np.tile(df['longitude'].values.reshape([-1,1]),(1,df.shape[0]))

lat2 = np.transpose(lat1)
lon2 = np.transpose(lon1)

Now you have 4 matrices, which contain all combinations between the lat/lon pairs on which you can simply apply your function all at once to get all the distances in one go:
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * arcsin(sqrt(a))
km = 6367 * c

This result can be stitched to your original dataframe:
result = pd.concat([df,pd.DataFrame(km,columns=df.index)],axis=1)


text:
Q: Moving Stored Procedures from SSMS into TFS 2012 I am needing to move all of my stored procedures into TFS 2012. I was wondering what the best/fastest way to accomplish this is. I am using SQL Server 2012.

A: Our suggestion would be to use the SQL Server Data Tools (SSDT) and create a database schema change management project in Visual Studio that you can then check-in to Team Foundation Server.  It has quite a few benefits like being able to "compile" the schema and has tools that can be used in generating automatic change scripts for target servers (whether they are empty, test, or even production servers).
http://msdn.microsoft.com/en-us/data/tools.aspx

A: SSDT is definitely the way to go, It's a component of Visual Studio. There is an SSDT for database projects, and SSDT-BI for reports etc.
Create a database project in Visual Studio and add your database objects (stored procedures, views, functions, tables, schemas etc) into the project. It allows for all database objects to be stored in there (even database roles/users, certificates, keys etc).
Alternatively, you can use Visual Studio to import a database from a server. It will read your database and populate the project with all the objects from that database. It's very cool.
You can check in to TFS as you would with any other project which allows you to do versioning (with comments), attach that work to TFS tickets (if you manage your workload that way) and perform branching and merging and you can also compare different versions of the project or the project against already deployed versions.
Once you're happy with your database you can 'publish' your project up to a server of your choosing. This is a very useful method for creating code that can be deployed to multiple environments (i.e. different dev/test environments). You can also compare your project against a deployed version to see changes. For example, you could compare your project against a test environment to see what the differences are and generate a script to update the test environment to match source (or vice-versa).
SSDT is great for deployments because it calculates how to apply your database project (rather than just dropping the database and creating a new one). You can also use pre & post deployment scripts to work with data or add permissions onto your objects for example.
You can publish to a database/server, script or DACPAC (which is the format for copying your entire project/database schema and allows you to perform deployments/drift reports etc from outside of Visual Studio)


text:
Q: Centralized session in multiple product having different domain I am developing centralized admin module for multiple product. Trying to maintain same session across multiple product.

For Product1 : Authenticate successfully and send token in response header
Request URL:http://localhost:8080/admin-web/rest/authenticate/
Request Headers
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Host:localhost:8080
Origin:http://product1.com:9090
Pragma:no-cache
Referer:http://product1.com:9090/p1/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.109 Safari/537.36
Response Headers
Set-Cookie:token=asdf123sfs1f23sfsf321sfsf21; Version=1; Comment=""; Domain=localhost; Path=/ <------------------------------------???
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://product1.com:9090
Content-Encoding:gzip
Content-Type:application/json
Date:Mon, 13 Nov 2017 12:38:27 GMT
Server:Apache-Coyote/1.1
Transfer-Encoding:chunked
Vary:Origin
Vary:Accept-Encoding

For Product2 :
Request URL:http://localhost:8080/admin-web/rest/authenticate/
Request Headers
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Content-Length:156
Content-Type:application/json;charset=UTF-8
Host:localhost:8080
Origin:http://product2.com:9090
Pragma:no-cache
Referer:http://product2.com:9090/p2/
token:null <------------------------------------???
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.109 Safari/537.36

While doing product2 authentication after product1 authentication, token found null. If I deploy product1 on same domain, it works fine.
So, I want to use token header for same service url in another product request. How can I do it? Please find my CORS configuration below :
<filter>
    <filter-name>CORS</filter-name>
    <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>

    <init-param>
        <param-name>cors.allowOrigin</param-name>
        <param-value>*</param-value>
    </init-param>
    <init-param>
        <param-name>cors.supportedMethods</param-name>
        <param-value>GET, HEAD, POST, OPTIONS, PUT, DELETE</param-value>
    </init-param>
</filter>

A: I have resolved this by creating subdomain for each product just like Google, where I can share cookies across subdomain.
Reference Share cookie between subdomain and domain


text:
Q: Invalid date value storing in atk4 MVCForm I have created a form using MVCForm and set Model class extended Model_Table. In model class I have a date field.
I tried to edit existing record (using GET and loadData() in model), but date field populating with invalid data for example if I saved 10/01/2012 (M/d/Y) , it populated with 01/10/2012
I have following config for date
$config['locale']['time']='H:i:s';
$config['locale']['date']='m/d/Y';
$config['locale']['date_js']='mm/dd/yy';
$config['locale']['datetime']='m/d/Y H:i:s';

A: Check out these Github links. Maybe you can find something useful there.
https://github.com/atk4/atk4/issues/92
https://github.com/atk4/atk4/issues/89
https://github.com/atk4/atk4/issues/90
I was working on custom date, datetime need too, but right now have put this issue on the pause because it have lower priority in my project.


text:
Q: ExFat mount permission I am trying to mount an exfat drive using fstab with read write permission for both user and group.
The line of etc/fstab for this drive is:
UUID=5E98-37EA /home/ftagliacarne/data/media exfat defaults,rw,uid=1000,gid=1001,umask=002 0 1

Using these option the drive gets mounted to the correct location to the correct user and group, however, the group does not have rad-write access. i.e. the permission are set to:
drwxr-xr-x 7 ftagliacarne docker-media 262144 Sep 24 20:40 media

Is there any way of setting the group permission to also have read-write access?
Desired outcome:
drwxrwxr-x 7 ftagliacarne docker-media 262144 Sep 24 20:40 media

Some of the things I tried:

*

*Setting umaskto 002

*Using chmod before/after mounting

*Using chmod recursively on the parent directory

Appreciate any help you can give me.
Update 1:
I also tried changing the fstab file to the following
UUID=5E98-37EA /home/ftagliacarne/data/media exfat defaults,uid=1000,gid=1001,dmask=0002,fmask=0113 0 1

Alas, it still does not work
Update 2:
After having issues at boot due to the configurations above, I changed the /etc/fstab entry to the following:
UUID=5E98-37EA /home/ftagliacarne/data/media exfat defaults,uid=1000,gid=1001,fmask=0113,dmask=0002,nofail 0 0

And now it works. I suspect the issue was with the pass option being 1, as changing that to 0 seems to have fixed it. Thank you to everyone who helped!

A: chmod and chown will not work for mounted fat32, exfat and ntfs-3g, period.
What you're looking for is dmask=0002,fmask=0113.


text:
Q: Why is a capacitor before a voltage regulator more effective than after? I have 5 V coming in from a USB power bank to an LDO voltage regulator that drops it down to 3.3 V. On the 3.3 V line I have several ICs and IR sensors. One of the IR sensor consumes quite a bit of current in short bursts (I have a 10 µF cap across it).
Whenever that power hungry IR sensor turns on, it causes some other parts of my circuit to behave oddly for a split second. I figured adding a large capacitor to the 3.3 V rail would help eliminate that, which it did. But I also noticed that I could instead add a significantly smaller capacitor on the 5 V side, and that also solved the problem.
Why is it that the capacitor is more effective on the input side of the regulator rather than the output? I figured the charge would be "more readily available" to the system if it was on the output/3.3 V side, where the sensor is.
(I just tinker with electronics and have no formal knowledge beyond basic physics E&M.)
*Edit: Before the problem/experimentation I already had on either side of the regulator a 0.1uF cap, a 1uF cap, and two 10uF caps (totaling 21.1uF on either side). I began to add extra caps after the problem.

A: Because dQ = C*dV.
Unless you're running the regulator right on its limits, you can tolerate a larger dV on the input capacitor, allowing a smaller C.

A: The voltage drop during a transient at the utilization point is roughly composed of the following:

*

*inductance of the wire and the source before the regulator. In case of a typical system that uses long and thin power supply cable this is usually significant because the inductance of the cable is high.

*inductance of the wire/PCB track after the regulator. This is usually short if the utilization is near the regulator but may be significant if the system uses a big PCB or perhaps more interconnected PCBs.

*response time of the regulator. There are two major events that the regulator should respond to: input voltage variations, output load variations. These parameters can be found in its datasheet.
During a transient at the output of the regulator, the following happens:

*

*the voltage in the output capacitor drops

*the control loop of the regulator senses the voltage deviation and tries to conduct more. This takes time (the load regulation response time in the datasheet), and during this, the voltage falls more.

*the regulator conducts more and pulls more current from the input capacitor.

*the voltage difference between the cap and the supply voltage before the cable causes the current to begin flowing through the cable filling back the
input capacitor. This takes time because (roughly speaking) the inductance limits how fast the current can start flowing.

If the input capacitor can not hold enough charge until it is filled back by the source the voltage drops below the regulator's minimum allowed input voltage. The regulator can not do anything: the output voltage remains below the nominal level until the input reaches the minimal level.
Forcing the regulator out of its designed operating region may have other serious drawbacks. If the originally closed loop control opens, the pass device may saturate. It is also possible that the input voltage is not enough to reliably power the internal circuitry and the device may shut down due to undervoltage lockout functionality or just not work properly. The recovery time from these situations may be much longer than the typical load response when there is enough input voltage. You should avoid this happening.
This can occur even if the output capacitor is large. The voltage across it will drop, and the regulator senses and tries to keep the output voltage and fill it back. If the cap is too large, the regulator will pull high current from the input side. The first problem is that it comes from the input capacitor so even if you have a large cap at the output the above situation can occur. The second problem is that it is possible that the current may be high enough to trigger the overcurrent protection which in itself slows down the response plus the recovery from overcurrent may be slower than the load regulation time. You should keep the regulator in normal operating conditions to achieve the best performance.
The output capacitor should be as small as possible, just enough to bridge the time when the regulator responds and compensates for the increased load.
Roughly speaking, if you increase the output cap you just hardening the work of the regulator.
The best real-world approach is to start with a sufficiently large cap on the input side and a small one on the output side. Read the datasheet for recommendations. Check the transient on the output side with an oscilloscope. If it is not satisfactory, try increasing the output cap or replacing it with one that has a lower series inductance. Then examine the transient at the input and try to reduce the input cap. Keep some safety margin at both sides.
EDIT:
The impedance of the wire/PCB track after the regulator...
...has the same effect mentioned before: during transients or also in case of continuous but high frequency loading, at the utilization point there will be voltage notch (or continuous drop). If you compare the signal with an oscilloscope at the output of the regulator and at the utilization point, you will see that at the regulator there will be much smaller noise.
The inductance of the wire/track combined with the capacitor at the output of the regulator is an LC low-pass filter, effectively dampening the HF components.
This is good, because the noisy load does not distort the voltage of the regulator (too much). You can supply the MCU or other (analog) circuits all independently from the regulator in a star topology. This will effectively reduce the interference. If the track's inductance is not high enough, you can deliberately include inductors in the line. This can be seen often in equipments similar to yours: high power transient loads combined with sensitive analog/digital control.
High supply impedance is also bad, because you want smooth supply on every load, but this can be fixed with adding (low-ESR) capacitors to every utilization point. If you examine a PC motherboard for example, you will see hundreds of ceramic caps everywhere for that very reason.

A: With a capacitor on the output, if the input voltage drops below what is required to achieve output regulation, there will be a dropout in the supply, and the output capacitor will droop.
With a capacitor on the input the regulator will always have a voltage reserve, and if it holds above the minimum input voltage the output regulation can be maintained even with no capacitor (with somewhat compromised higher frequency impedance).
With rectified AC this effect would be very evident. With your 5 V supply it seems to point towards rather less current capability than your sensors need.
Try and get a look at the supply ripple waveforms with a scope. Consider having dedicated regulators if the budget and specifications can justify it. This will prevent a sensor from affecting the other parts.

A: The basic premise of the question is invalid and not universally applicable. Certainly regulators (of whatever variety) need to have reasonably smooth (filtered) raw power to work with.  Few if any will operate on the pulsed-DC comping out of a typical AC source and rectifier stage.  This is where we typically see the large "bulk" filter capacitors.
HOWEVER, there are some cases where large capacitance is required to hold up the power supply bus in the presence of large, intermittent loads such as the one given as an example in the question.
It is not a question of "more effective before or after".  Those are two separate and independent cases and cannot be logically combined as in the question as asked.

A: A capacitor on the output side of a regulator won't even start trying to do anything useful unless or until the output voltage changes.  A capacitor on the input side will start supplying current when the input voltage drops.  A typical regulator will try to minimize the extent to which changes on the input voltage affect the output, so the input-voltage drop necessary to make the input-side capacitor start supplying energy will typically not cause any significant output-voltage change.
In some cases, a regulator might not be able to react instantly to a sudden current demand, and in such cases an output capacitor may be helpful (if not
required) to supply some current to the output during the time it takes the
regulator to react to an increased load.  The output cap won't be able to
feed current very effectively without the output voltage dropping noticeably,
but it may be able to feed enough to give the regulator time to react to the
increased demand.


text:
Q: Spring4.3.0 integration with Hiberbnate 5 In Hibernate 5 bootstrapping api is changed by introducing BootStrapServiceRegistry class, now how can I bootstrap the sessionFactoryBean from spring context.xml file . Please provide me on approaches for xml bootstrapping rather than programmatic way that's explained in docs.
Currently we have spring 4 and hibernate 4 integration in the context.xml and we are planning to migrate to Hibernate 5. We are facing challenges with LocalSessionFactoryBean, getting No qualifying bean exceptions for the serices, which is thrown by another exception like no qualifying bean JtaTransaction Manager


text:
Q: Cannot access domain property from Java class (in src folder) I cannot access exploits property in domain class - Scenario , from my java class - MatchScenario , located in Grails src folder.
Already tried :

*

*Explicit methods :
I have tried explicitly creating the get;set; but I get stackOverflow error since the setExploits() is called infinitely by itself for some reason.

*Service to return the exploit field,
Though the service was created, it's never called on my fork-debug integration testing, so tests hangs with no exception
compilation error ->
Error:(59, 44) java: cannot find symbol
symbol:   variable exploits
location: variable scenario of type core.Scenario

Java class, error on the inner loop ->
public class MatchScenario implements Callable{
    private static final Logger LOG = Logger.getLogger(MatchScenario.class.getCanonicalName());

    private List<Scenario> scenarioList

    @Override
    public List<Scenario> call() throws Exception {
        LOG.debug( "***********************    schedule matcher called *****************************" );
        if (scenarioList==null) {
            LOG.debug("scenarioList not initialized ");
            return null;
        }
        List<Scenario> scenarioAvailable = new ArrayList<Scenario>();
        for (Scenario scenario : scenarioList){
            for (Exploit exploit : scenario.exploits){
                //println 'exploit -> '+exploit
                if (!match( exploit.getExpression() ) ){
                    break;
                }
            }
            //happens only when  all scenario are available ( no break issued )
            scenarioAvailable.add(scenario);
        }

        return scenarioAvailable;
    }

    private boolean match(String expression) {
        return true;
    }
}

Scenario domain object ->
package core

class Scenario {
    String name

    static belongsTo = [ Exploit ]

    static hasMany = [ exploits : Exploit ]

    static constraints = {
        name nullable: false , maxSize: 32
    }
}

A: You're confusing fields and properties. When you declare a property in a Groovy class, e.g. String name, the Groovy compiler converts that to a private field and adds a getter and a setter (unless you already defined one or both of them - it won't overwrite), in this case something like
private String name
public void setName(String name) { this.name = name }
public String getName() { return name }

It only does this if there's no scope modifier, so public String name and protected String name would both stay as defined.
One benefit of this is that you can later add logic to the getter and/or setter to modify the value, do some validation checks or computations, etc., and in Groovy you would still read and write to the name property since property access always calls the underlying setters and getters, and since properties like this are a Groovy-only thing that Java can't access, you would have been calling the setter and getter from Java all along, so you wouldn't need to recompile the Java classes that used the class.
Declaring a hasMany like yours creates an exploits property, effectively
Set<Exploit> exploits

and that property (added by a Grails AST transformation) is likewise converted to a private field with a getter and setter. So to get this working from Java, use the getter:
for (Exploit exploit : scenario.getExploits()) {


text:
Q: Order form in product list I would like to add an order form to a product category list.  I have created the form manually following other posts but when I hit submit, I receive the following error: Please specify the product's option(s).
The following code is what I used to generate the form.  I have done a lot of low-level comparisons and cannot spot any errors. Could someone please point me in the right direction if I am off course?  Thanks in advance.

<?php foreach ($_productCollection as $idx => $_product): ?>
<?php
    $attributeSetModel = Mage::getModel("eav/entity_attribute_set");
    $attributeSetModel->load($_product->getAttributeSetId());
    $attributeSetName  = $attributeSetModel->getAttributeSetName();
?>
<li class="product-list col-md-12 <?= $_product->getAttributeText('yuleys_css_color') ?>">

<a href="#product-<?= $idx ?>-description">Product Description

<a href="#product-<?= $idx ?>-warranty">YULEYS® Warranty

<a href="#product-<?= $idx ?>-reviews">Reviews

                <div class="tab-pane fade in active" id="product-<?= $idx ?>-description"><?= $_product->getDescription() ?>

                <div class="tab-pane fade" id="product-<?= $idx ?>-warranty"><?= $_product->getData('yuleys_warranty') ?>

                <div class="tab-pane fade" id="product-<?= $idx ?>-reviews">

        <img src="<?= $_product->getImageUrl() ?>" alt="<?= $_product->getName() ?>">

<?= $_product->getName() ?>

<?php echo $this->getPriceHtml($_product, true) ?>

<?= $this->__('Availablility') ?>: <?= ($_product->getIsSalable() ? $this->__('In stock') : $this->__('Out of stock')) ?>

<?= $this->__('Product Code') ?>: <?= $_product->getSku() ?>

            <?php if ( $_product->isSaleable() ): ?>
                <form action="<?php echo $this->helper('checkout/cart')->getAddUrl($_product) ?>" method="post" id="product_addtocart_form" <?php if($_product->getOptions()): ?> enctype="multipart/form-data"<?php endif; ?>>
                    <?php echo $this->getBlockHtml('formkey') ?>
                    <input type="hidden" name="product" id="<?= $_product->getId() ?>">
                    <input type="hidden" name="related_product" id="related-products-field" value="">
                    <?php if ( $_product->getTypeId() == 'configurable'):

                        $config_product = Mage::getModel('catalog/product')->load($_product->getId());
                        $productAttributeOptions = $config_product->getTypeInstance(true)->getConfigurableAttributesAsArray($config_product);

                        foreach($productAttributeOptions as $attribute):
                            ?>

                            <label for="attribute<?= $attribute['id'] ?>"><?= $attribute['label'] ?>
                            <select name="super_attribute[<?= $attribute['id'] ?>]" id="attribute<?= $attribute['id'] ?>" class="required-entry super-attribute-select" required="required">
                                <option value=""><?= $this->__("Select {$attribute['label']}...") ?></option>
                                <?php foreach($attribute['values'] as $val): ?>
                                    <option value="<?= $val['value_index'] ?>" price="<?= empty($val['pricing_value']) ? '0' : $val['pricing_val'] ?>"><?= $val['label'] ?></option>
                                <?php endforeach; ?>
                            </select>

                            <?php
                        endforeach;

                    endif;
                    ?>

                        <label for="qty<?= $_product->getId() ?>">Qty
                        <input name="qty" id="qty<?= $_product->getId() ?>" type="number" step="1" min="1" required="required" class="input-text qty" id="qty_<?php echo $_product->getId()?>" maxlength="12" value="<?php echo $this->getMinimalQty($_product)== null?1:$this->getMinimalQty($_product); ?>">

                    <button type="submit" class="btn btn-primary"><?php echo $this->__('Add to Cart') ?></button>

                </form>
            <?php endif; ?>

<?php endforeach; ?>

A: I assume you get the error after submitting the form on the cart or form page.
The problem is, that your product is either an configurable product or has custom options. These options/attributes need to be selected when adding the product to the cart.
In the Magento wiki can be found more about this.

To add a simple product with custom options simply add
  options[id]=[value] to the end. The basic structure is:
/path/to/magento/checkout/cart/add?product=$id&qty=$qty&options[$id]=$value

For example:
http://magentoserver.com/checkout/cart/add?product=13&qty=1&options[12]=57

For adding a Configurable Product to the Cart via Querystring you need
  a url format like following
(line broken for better readability)
http://www.your_domain.com/checkout/cart/add
?product=68&qty=1&super_attribute[528]=55&super_attribute[525]=56


text:
Q: Javascript [Prototype/Scriptaculous] - create an infinite unidirectional slideshow let's say you've got a slideshow like this (I omit here the 'previous' and 'next' buttons):

[...]

[...]

[...]

There are 3 slides here, but that is totally dynamic.
My big issue is not so to create an infinite slideshow, but to create one which transitions from one slide to the other always in the same way.
If we consider this cycle:
slide 1 -> slide 2 -> slide 3 -> slide 1 -> slide 2 -> slide 3 -> slide 1 -> ...

What I want is the impression we always slide to the left (even when we get back from slide 3 to slide 1!!).
If you have any ideas, please tell me, I have already tried many things.
Thanks in advance,
Rolf
P.S.: I'm using Prototype v1.6 and Scriptaculous v1.9.0

A: Assuming you know how to work the slideshow, you want to utilise the modulus function to give you that infinite loopyness.
So if you have a variable id which is the one which is meant to go 1->2->3 and then back around, you would need to update it so it goes back from 3 to 1, as such:
id=(id+2)%4-1

That'll give you the 1->2->3->1->2->3... effect
That little formula may look slightly confusing because you're going from 1 to 3 rather than 0 to 2. If you were to start at 0 the simplified formula would be:
id=(id+1)%3

You just need to adapt the 3 on the end to the number of slides the slideshow as, or in the top example, the number of slides+1.


text:
Q: enclose columns in quotes using hiveql Hive Version 0.13

I am having a column in hive which needs to be enclosed in double quotes
I am trying with the below query but the output is returned as NULL
select "\""+notes_detail+"\"" from  service_request_notes.TSS_INCIDENT_NOTES_F_SAMPLE limit 1;

where as the output should be this
select notes_detail from  service_request_notes.TSS_INCIDENT_NOTES_F_SAMPLE limit 1;

Job 0: Map: 106   Cumulative CPU: 151.24 sec   MAPRFS Read: 0 MAPRFS Write: 0 SUCCESS
Total MapReduce CPU Time Spent: 2 minutes 31 seconds 240 msec
OK
notes_detail
From: scottw@acespower.com


text:
Q: CSS3 font family doesn't work in safari I have a problem changing the font-family of my h1 and p tags. The fonts work fine in Internet Explorer and Firefox, but in mobile Safari they turn in to Arial.
h1 {
    font-family: Cambria, "Times New Roman";
}

.text_1 {
    font-family: Cambria, "Times New Roman";
}

p and h1 are placed in the same floated container with auto height.
Any tips?

A: Right away, we can see that only one of the displayed fonts overlaps: Arial. None of the Calibri or Cambria fonts are available on the Mac, and the Mac has at least a dozen just on this page that aren't available in Windows!
In fact, between these two systems, there are only ten fonts that overlap:


text:
Q: rsyslog with redis => ELK is not showing any logs I am really new to the ELK stack, any help will be appreciated.
The idea was to have:
rsyslog server -> redis -> ELK stack

by following this recipe: https://sematext.com/blog/recipe-rsyslog-redis-logstash/
I can see the traffic go all the way to Elasticsearch, but have not been able to debug Elasticsearch yet. I believe that traffic should be going there because tcpdump shows it.
If I go to "Stack monitoring", Logstash is not showing up there. When going deeper, it does say that the "Logstash node has been detected", and nothing more.

A: The issue was that Kibana is not automatically showing logs in the Observability/Stream.
On the top of the page there is a link to settings where you should choose
log index pattern that you have created.
A little unintuitive considering having that massive screaming button to add integrations.


text:
Q: Sorting columns with NG-TABLE I am new to Angular. I have created a table that successfully loads a set of JSON data and display in the table that I have created. The problem is the sorting of the columns. I want to give users the ability to sort the data displayed based on each column displayed.
I have tried to follow the tutorial in the ng-table page but somehow it doesn't seem to work. I have tried to sort the data only by a specific column (timestampCreated, see example below) but even that doesn't work. What might the problem be?
This is the HTML file:
<!DOCTYPE html>

    <title>Jade Demo</title>

Purchases

            <input type="checkbox" ng-model="col.show">{{col.title}}

             {{row[col.field]}}

This is the JS file:
(function() {
'use strict';

angular
    .module('purchases')
    .controller('AnomaliesController', ['$log', '$scope', '$http', 'NgTableParams', function ($log, $scope, $http, NgTableParams) {

        this.cols = [
            {field:"purchaseID", title: "ID", sortable: "purchaseID", show: true },
            {field:"timestampCreated", title: "Date Created", sortable: "timestampCreated", show: true },
            {field:"customerNumber", title: "Customer Number", sortable: "customerNumber", show: true },
            {field:"contractNumber", title: "Contract Number", sortable: "contractNumber", show: true },
            {field:"reg", title: "Registration Number", sortable: "reg", show: true },
            {field:"iptf", title: "IPTF", sortable: "iptf", show: true },
            {field:"type", title: "Type", sortable: "type", show: true },
            {field:"status", title: "Status", sortable: "status", show: true },
            {field:"reviewStatus", title: "Review Status", sortable: "reviewStatus", show: true }
        ];

        $scope.populateTable = function () {

            this.tableParams = new NgTableParams({}, {
                filterDelay: 300,
                sorting: { timestampCreated: "asc" },
                getData: function (params) {
                    return $http({
                        method: 'GET',
                        url: '/server/purchases.json'
                    }).then(function (response) {
                        return response.data;
                    }, function (response) {
                        $log.log(response);
                        return [];
                    });
                }
            });
        }.bind(this);

    }]);

})();

A: Put sortable column name in single quote :

                {{user.name}}

In your case like this
 sortable: "'timestampCreated'"

A: try the following code
(function() {
'use strict';

angular
    .module('purchases')
    .controller('AnomaliesController', ['$log', '$scope', '$http', 'NgTableParams', function ($log, $scope, $http, NgTableParams) {

        this.cols = [
            {field:"purchaseID", title: "ID", sortable: "purchaseID", show: true },
            {field:"timestampCreated", title: "Date Created", sortable: "timestampCreated", show: true },
            {field:"customerNumber", title: "Customer Number", sortable: "customerNumber", show: true },
            {field:"contractNumber", title: "Contract Number", sortable: "contractNumber", show: true },
            {field:"reg", title: "Registration Number", sortable: "reg", show: true },
            {field:"iptf", title: "IPTF", sortable: "iptf", show: true },
            {field:"type", title: "Type", sortable: "type", show: true },
            {field:"status", title: "Status", sortable: "status", show: true },
            {field:"reviewStatus", title: "Review Status", sortable: "reviewStatus", show: true }
        ];

        $scope.populateTable = function () {

            this.tableParams = new NgTableParams({
                sorting: { timestampCreated: "asc" }
              }, {
                filterDelay: 300,
                getData: function (params) {
                    return $http({
                        method: 'GET',
                        url: '/server/purchases.json'
                    }).then(function (response) {
                        return response.data;
                    }, function (response) {
                        $log.log(response);
                        return [];
                    });
                }
            });
        }.bind(this);

    }]);

})();

source : http://ng-table.com/#/sorting/demo-sorting-basic


text:
Q: ATL, VS2008 extension: Adding event handler to WindowEvents Used the New Add-in Wizard to create a Visual C++ / ATL add-in project.
Generated code:
HRESULT hr = S_OK;
pApplication->QueryInterface(__uuidof(DTE2), (LPVOID*)&m_pDTE);
pAddInInst->QueryInterface(__uuidof(AddIn), (LPVOID*)&m_pAddInInstance);`

Get the Events object, and the WindowEvents:
m_pDTE->get_Events(&m_pEvents);
m_pEvents->get_WindowEvents(0, &m_pWinEvents);

How to add an event handler?
if (NULL != m_pWinEvents) {
    m_pWinEvents += ????
}

Thanks for any hints or references...
UPDATE, trying Alien01's suggestion:
m_pWinEvents->WindowActivated += new _dispWindowEvents_WindowActivatedEventHandler(this.WindowActivated);

1>Compiling...
1>Connect.cpp
1>c:\work\visstudio_addin\cbaddin3\cbaddin3\connect.cpp(43) : error C2039: 'WindowActivated' : is not a member of 'EnvDTE::_WindowEvents'
1>        c:\work\visstudio_addin\cbaddin3\cbaddin3\debug\dte80a.tlh(1006) : see declaration of 'EnvDTE::_WindowEvents'
1>c:\work\visstudio_addin\cbaddin3\cbaddin3\connect.cpp(43) : error C2061: syntax error : identifier '_dispWindowEvents_WindowActivatedEventHandler'

A: You can try using

m_pWinEvents. WindowCreated +=
  new _dispWindowEvents_WindowCreatedEventHandler(this.WindowCreated);

and then define handler
   public :
   void WindowCreated(EnvDTE.Window window)
    {
        // some code
    }


text:
Q: How to store (and/or POST) user ID as their form is POSTed? I'm building a site where users create profiles and projects (startups, research, inventions, etc) and share and connect with others for a valuable exchange.
I started the site sometime ago with a friend and we've since stopped working on it together.  He wrote all of the php and I did all the front end.  Now I'm doing both and the concept has changed a bit.  This means I'm adapting a lot of the code he has already written.
When users posts a new project, there is certain background information that needs to be posted with it.  Therefore, when they create a new post I want to store their ID with it.  This way when their post is displayed, it also shows the pertinent user profile information.
How do I properly store (and/or POST) their user ID as the form is POSTed?
(I apologize, I'm fairly new to PHP.  Doing my best with the lingo.)
Here is some of the code (not all is needed, I know)
<?php
require_once("../includes/config.php");
require_once("../assets/classes/projects.php");
$x = new projects();

if(isset($_SESSION['username']))
{
    $_SESSION['logged_in'] = 1;
}

$dbh = config::get();

$checkCountQ = $dbh->prepare("SELECT cork_user_notes.tf_index FROM `cork_user_notes` INNER JOIN `cork_users` ON cork_user_notes.tf_index = cork_users.tf_index WHERE cork_users.tf_username = :un");
$checkCountQ->bindParam(":un", $_GET['user']);
$checkCountQ->execute();
$checkCountR = $checkCountQ->rowCount();

?>

<form action="addProjects.php" method="POST">

                    Enter your project name

                    <input type="text" name="title" placeholder="project name">

                     Enter your project's category

                    <select name="category">
                         <option value="1">Startup</option>
                         <option value="2">Software</option>
                         <option value="3">Hardware</option>
                         <option value="4">Research</option>
                         <option value="5">Discovery</option>
                         <option value="6">Invention</option>
                    </select>

A: Allowing the user to alter their user_id is not safe for your records because a user could pose as someone else. Here there is no user_id in your code, only their username which if unique, might work just as well. In order to do this efficiently it might be best to pass the value in a hidden form field in addition to a hashed field that contains a value known only to you to verify on the other side:
<?php
print "<input type=\"hidden\" name=\"uid\" value=\"".$_SESSION['username']."\">";
print "<input type=\"hidden\" name=\"uidh\"
value=\"".md5($_SESSION['username']."Something that only you know")."\">";
?>

On the other side you check the hash.
if (!empty($_POST['uid'])&&!empty($_POST['uidh'])
      &&$_POST['uid']==md5($_POST['uidh']."Something that only you know")){
//then they're okay
} else {
//fail spectacularly at their attempt
}

If your server is setup to handle sessions with cookies, the cookies are unsafe and can't be trusted as well.
To verify sessions you would want to hash the data with a unique key only known to you as well.

A: Why does the user ID value need to be posted from the form at all?
You have an authenticated user, you have their user's ID on the server side in some shape or fashion (maybe stored in the session or something similar). Use that when creating the project, and do not accept a user-supplied user ID.

A: Two ways to do this.

*

*You session the user id when the user logs in like this
 $_SESSION['userid'] = $id;

which you can subsequently used anywhere in the website as this case maybe when inserting

*create an hidden field in the form to store userid
<input type="hidden" name="id" value="<?php echo $_SESSION['userid']; ?>" />

you can then get it with $_POST['id'] when submit button isset.


text:
Q: Classification of commutative ring ideal closure operators? First, some setup:
So: given a commutative ring $R$, let $Ideals(R)$ be set of ideals of $R$ and let $IdealClosure(R)$ be the set of closure operations $cl: \mathcal{P}(R) \rightarrow Ideals(R)$.  In other words, let $IdealClosure(R)$ be the set of functions $cl: \mathcal{P}(R) \rightarrow \mathcal{P}(R)$ such that

*

*$cl(A) \subseteq R$ is an ideal for all $A \subseteq R$,

*$A \subset cl(A)$ for all $A \subseteq R$,

*$cl(cl(A)) = cl(A)$ for all $A \subseteq R$, and

*$A_1 \subseteq A_2 \implies cl(A_1) \subseteq cl(A_2)$ for all $A_1,A_2 \subseteq R$.

Note that since the ideals of a ring form a bounded lattice, the set $IdealClosure(R)$ is also a bounded lattice.  Now if $\mathcal{R}$ is some set of rings, let $IdealClosure(\mathcal{R})$ be the collection of functions which assign to each ring $R$ an element of $IdealClosure(R)$.  Again, $IdealClosure(\mathcal{R})$ is a bounded lattice by defining the lattice operations pointwise, ring by ring.
Let $\mathcal{R}$ be a set containing at least one representative from each isomorphism class of the finitely presented commutative rings.  Then we can assume $\mathcal{R}$ is countable.
It seems then that given a few more 'naturality' conditions the set $IdealClosure(\mathcal{R})$ would likewise countable.  For example, without going to far into symbolic logic, a natural ideal closure operator would be defined by one of a countable collection of statements in FOL or ZFC.
One obvious condition is this:  an ideal closure operation should treat isomorphic rings equivalently, or more formally: if $R_1 \in \mathcal{R}$, $R_2 \in \mathcal{R}$, $\varphi: R_1 \rightarrow R_2$ is an isomorphism, and $cl_1 = c(R_1)$, $cl_2 = c(R_2)$ where $c \in IdealClosure(\mathcal{R})$ then $\varphi[cl_1(A)] = cl_2[\varphi(A)]$ for all $A \subseteq R$.
What other conditions are reasonable?  Are such sets of closure operations studied?

A: Note that for any such "closure operations" one has $cl(A) = cl(\langle A\rangle)$ where $\langle A\rangle$ denotes the ideal generated by $A$. Hence it can be defined as an operation on ideals.
Now if you add a conditions of compatibility with intersection of ideals: $cl(A \cap B) = cl(A) \cap cl(B)$ for $A$ and $B$ ideals then a closure operation on a ring $R$ is the same as a nuclei on the set of ideals of $R$, i.e. it is the same as a sub-locale of the spectrum of the ring (i.e. a subspace of the spectrum from the point of view of pointfree topology).
With this insight in mind it is fairly easy to see that this has no chance to be countable: Pick any subset of prime numbers $Q$, then there is a sub-locale $Q \cup \{ \infty\}$ of $Spec  \mathbb{Z}$ which will corresponds to such a closure operation on $\mathbb{Z}$:
To a set $P \subset \mathbb{Z}$ you associate the intersection of $\mathbb{Z}$ with the ideal generated by $P$ in $\mathbb{Z}[Q' ^{-1}]$ where $Q'$ is the complement of $Q$.
Now, for any ring $A$, $Spec A$ has a canonical map to $Spec \mathbb{Z}$, so you will obtain a sublocale of $Spec A$ by just pulling back any given sublocale of $Spec \mathbb{Z}$ hence any sublocale of $Spec \mathbb{Z}$ gives a canonical and functorial choices of such a closure operation on $Spec A$.
For example, here you will obtain on every ring $A$ the closure operation which associate to any set $P \subset A$ the intersection of $A$ with the ideal of $A[Q'^{-1}]$ generated by $P$.
Of course the set of subset of of prime number is uncoutable so you will obtain an uncountable number of such assignment of closure operations.
Note that if you take both the "intersection" condition and sufficiently* strong functoriality condition on your assignment in the definition you can have that a functorial assignment of closure operation is the same as a closure operation on the base ring, and hence if you chose a base ring with a finite spectrum then you can have only a finite set of such functorial assignment of closure operation.
(*) meaning that when you have a ring morphism $f :A \rightarrow B$ then the closure operation on $B$ is given by the closure operation on $A$ in the way I described above for $\mathbb{Z}$ and an aribtrary ring $A$.


text:
Q: Can a heavy process running all month crash the computer? If I start a software process that uses 100% CPU, and keep it running many days, is it going  to crash the computer in a short time (one month)? I don't think so but I see some guys talking about these and I don't believe it, because, of course, the fan keep the processor cold.

A: Yes, or no!
There's too many variables to give a definitive answer - yes, processor overheating is a possibility, but it also depends on the robustness of the code, its data management routines (garbage collection), robustness of the system board, memory timing, power stability. system cooling effectiveness.....it's a 'try it and find out' situation.

A: All computer components are built to tolerances and have certain inbuilt "error rates".  Running a computer on a heavy duty cycle for a long period of time will increase the chance that you hit one of these errors during the course of your program running.
As an example it is not unknown (though it is relatively uncommon) for bits to instantaneously "flip" in DRAM modules and as a result ECC memory is recommended for high-uptime servers as it can correct the data "in-flight" before your program has anything to do with it.
In a study by Google they found that in DRAM memory sticks there were up to:

4,000 errors per year
That may not sound like a high fraction, but bear these factors in mind, too: each memory module experienced an average of nearly 4,000 correctible errors per year, and unlike your PC, Google servers use error correction code (ECC) that can nip most of those problems in the bud. That means an correctable error on a Google machine likely is an uncorrectable error on your computer, said Peter Glaskowsky, an analyst at the Envisioneering Group (and member of CNET's blog network).
Read more: http://news.cnet.com/8301-30685_3-10370026-264.html#ixzz1QTxjigI8

That equates to somewhere around 330 memory faults per month.
If you care about running a process for a long period of time then you'll need to keep it cool (as temperature can also affect bit-flip action), make it as rock solid a system as you can (premium components) and make sure that wherever possible error correction is in use.

A: When you say crash, if you mean physically damage, then that is highly unlikely - It would really require there to be a significant hardware fault, and in that cause your computer would likely be heading for a failure anyway.
If you mean cause the software, or operating system to stop functioning correctly, or stop all together then that is more possible.
If you genuinely have the CPU nailed at 100% then there will be very little opportunity for your operating system to perform the little house-keeping tasks it would normally run periodically and so over time your computer could start to malfunction.
Also, if your program is using 100% of the CPU, this could also indicate that your computer may not be up to the task, which could cause the program itself to fail.
Ultimately, though, it's going to be hit an miss. Computers do crash, even when not overloaded, overloading them makes it more likely but not certain.

A: Yes, it could happen.  However, no, it's not supposed to.  If the equipment has a weak point, you may well find it.  If it's all up to spec though, it shouldn't be a problem.


text:
Q: Converting openssl_public_encrypt (PHP) in C# code So I have to convert some PHP code to C# and my PHP code does following:
    if (null === $date)
        $date = time();
    $plain = "user:{$login};system:{$system};date:{$date};";

    if (!openssl_public_encrypt($plain, $encrypted, $this->key)) {
        throw new \Exception("Error while encoding with message: "  . openssl_error_string());
    }

    return base64_encode(base64_encode($encrypted));

And now I wrote following Code in C#:
if (date == null) date = DateTimeOffset.Now;

        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
        RSAParameters rsaParam = rsa.ExportParameters(false);
        rsaParam.Modulus = key;
        rsa.ImportParameters(rsaParam);

        var plain = $"user:{login};system:{system};date:{date.Value.ToUnixTimeSeconds()};";
        var result = rsa.Encrypt(Encoding.UTF8.GetBytes(plain), RSAEncryptionPadding.Pkcs1);

        return Convert.ToBase64String(Encoding.UTF8.GetBytes(Convert.ToBase64String(result)));

Unfortunately, the result looks very different in length and I saw that the C# code misses two "==" at the end, while in the PHP result, there is always "==" at the end. I checked the "plain" text, it's the same in both PHP and C# (beside the date timestamp, but that's because it changes every second). Can anyone help me?

A: So randomly we came to a solution. We used a converter to convert the PEM public key to XML and used the method "FromXmlString" and then it worked:
var rsa = new RSACryptoServiceProvider(2048);
        rsa.FromXmlString("<RSAKeyValue><Modulus>[...]</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>");

We used this converter: https://raskeyconverter.azurewebsites.net/PemToXml
Hopefully this helps other people.


text:
Q: How to obtain hydrodynamics from many-body quantum mechanics? Background: It is well known that the Schrodinger equation is equivalent to the Euler equation (with a "quantum potential" term) plus the probability conservation equation (which is formally identical to the mass conservation equation of the usual hydrodynamic theories). Establishing this mapping is quite simple and it's based on the so-called Madelung transformation, i.e. on writing the wave function as
$$
\psi(\mathbf{x},t) = \sqrt{n(\mathbf{x},t)} e^{\phi(\mathbf{x},t)}.
$$
This polar representation of the wavefunction must be inserted into the Shroedinger equation to map it into the system given by continuity+Euler equations for an irrotational fluid (see also this seminal Landau's work).
Now, this works for a single-particle system. Not only: for a Bose condensate, we can interpret $\psi(\mathbf{x},t)$ as the "collective wave function" (in the Hartree–Fock approximation, the total wave-function of the system of $N$ bosons is taken as a product of $N$ identical single-particle functions $\psi(\mathbf{x},t)$). Hence, the same "single-particle" case applies also to the many-particle condensate and we end up with the known hydrodynamic theory of a condensate.
Question: All this is extremely cool and kind of textbook physics... but how to derive the hydrodynamic equations for a system that is comprised of many particles and it's not a condensate?
What concerns me: where does the temperature or the entropy (that are typically important quantities in hydrodynamics) come from? To have a hydro formulation, we have to assume local thermodynamic equilibrium, so the fundamental object should be the density matrix, I guess.


text:
Q: Is this mathematical correct? Fraction with functions Say I have a fraction a $\frac{f(x)}{1+f(x)g(x)}$, where $f$ and $g$ are functions.
Is it mathematical correct to let $h(x)=f(x)g(x)$ and write $\frac{f(x)}{1+h(x)}$?
Or must I also remove $f(x)$ from the numerator and write $\frac{\frac{h(x)}{g(x)}}{1+h(x)}$?

A: Both are "mathematically correct". You are simply expressing $f(x)g(x)$ (a function of $x$) as something else. You have to be somewhat careful about writing $\frac{h(x)}{g(x)}$, as this may not be well defined (specifically if there is a case where $g(x) = 0$.


text:
Q: How to validate a multistep form with only single form using jQuery Validate I have a multistep form which is within a single form. I want to validate every single step, for eg. if i'm validating content inside div with id 1 then only that div validation should work but current scenario is the validation is not working if i have single form for all the steps and I don't want multiple forms to be validated. Is there any way to fulfill the above requirement?

  <form name="" id="">

  </form>

jQuery('form#addform select').each(function() {
  jQuery(this).rules('add', {
    required_select: true
  });
});

jQuery.validator.addMethod('required_select', function(value, element) {
  return value > 0;
}, 'Please choose a option');

jQuery("form#addform").validate({
  submitHandler: function(form) {
    // ...
  }
});