text:
Q: Why i am getting the same mac address using getmac package even though i am using two different devices I have a webserver and the backend is written in nodejs. I am trying to get the mac address of each device accessing my website. I am using the getmac package and here is my code
Const getmac = require('getmac')
Const device = getmac.default()
Console.log(device)

Even though i am accessing my website from two totally different devices. I get the same mac address. Can some clarify. By the way i checked mac address of each device in my modem config page and there are different

A: I assume you are getting the mac address of the server the nodejs code is running on. It doesn't get the mac address of the client (browser).
The opening statement at https://www.npmjs.com/package/getmac:

This library will not run in web browsers / on the client-side / in webpack / in browserify / in angular / in react / in jQuery / in HTML. It will only run on Node.js environments, which the web browser is not.

A: The getmac package only gets the mac address of the listening machine.
You are getting the same mac addresses because it has nothing to do with the mac addresses of the devices you are using to visit the server. It can ONLY get the server's own mac address.


text:
Q: How to remove empty space in Avada WordPress theme How do I remove the built-in blank space below the header?
The theme is Avada

A: to remove the built-in blank space below the header you should this css of code:
#main {
       padding-top: 0;
    }

    .header-avada {
       margin-bottom: 0;
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Three ways to use css() jQuery supports multiple ways of specifying CSS properties:
// With colon:
$('p').css({marginTop: '5px'});
$('p').css({'margin-top': '5px'});
$('p').css({'marginTop': '5px'});

// With comma:
$('p').css('marginTop', '50px');
$('p').css('margin-top', '50px');

// omg

Does they have any advantages / disadvantages (in comparison with one another) from practical point of view?

A: All of the above are identical behind the scene, but from a code maintenance standpoint, using $('p').css({'margin-top': '5px'}); might be better to set a single property as it's the required format to get a property.
$('p').css({marginTop: '5px'}); is great when setting multiple properties.


text:
Q: Platform Specific Natives in Python This page goes over the specifics of how to extend Python with C. However, I didn't see anything about using different C code depending on the OS.
I'm fairly sure this can be done, because the python library colorama has cross platform terminal color support, which as far as I know needs different code for Windows and Unix. However, I looked through the source code and couldn't find anything. It should be noted that I may have missed it because neither python nor C is my area of expertise.
TL;DR: How does one extend python using OS-specific C code?

A: Normally in C this is done using conditional compilation.  Most compilers will have a pre-processor macro indicating the OS.  For example:
#ifdef WIN32
     // do Windows stuff
#else
     // do something else
#endif

The names of these macros are compiler specific.
Alternatively my preferred option is to place OS specific code in its own DLL or shared object and link the code into your platform-independent python interface.
For example, you write the Python interface as being portable, when you get to something which is OS specific you make a call to a generic function of your own invention.  There is a copy of this generic function in each shared library for Linux, Windows, OS X, etc which is resolved at linker time.
Whether to go for conditional compilation or OS specific libraries depends on how much code is different.


text:
Q: Draw Custom shape Flutter I'm trying to draw the shape in this image
The shape that I want to draw
Put I can't get the same result by my code :
CustomShapeClipper extends CustomClipper<Path> {
@override

Path getClip(Size size) {

final Path path = Path()

..moveTo(0, size.height * 0.6)

..quadraticBezierTo(

size.width * 0.7 , size.height - (size.height * 0.1) ,

size.width, size.height * 0.8

)

..lineTo(size.width, 0)

..lineTo(0, 0)

..close();

return path;

}

@override

bool shouldReclip(CustomClipper oldClipper) => true;

}

I get this result My Result
Kindly guide me for this.
Thanks in advance

A: Try this and let me know if it works for you.
In your widget body you can have a build method looking similar to this
 @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: <Widget>[
          ClipPath(
            clipper: BottomEndClipper(),
            child: Container(
              height: MediaQuery.of(context).size.height * .5,
              decoration: BoxDecoration(
               //Your gradient or own color
                color: Colors.purple,
              ),
            ),
          ),
        ],
      ),
    );
  }
}

And your custom clipper looking like this
class BottomEndClipper extends CustomClipper<Path> {
  @override
  Path getClip(Size size) {
    var path = Path();
    path.lineTo(0, size.height - 80);
    path.lineTo(size.width * .7, size.height - 10);
    path.quadraticBezierTo(
        size.width * .8, size.height, size.width * .95, size.height * .90);

    path.lineTo(size.width, size.height*.87);
    path.lineTo(size.width, 0);

    path.close();
    return path;
  }
  //Should return false if you don't wish to redraw every time
  @override
  bool shouldReclip(CustomClipper<Path> oldClipper) => false;
}

A: I managed to draw something similar using cubicTo instead of quadraticBezierTo. A simple example for what you need:
final Path path = Path()
      ..moveTo(0, size.height * 0.6)
      ..lineTo(size.width * 0.7 - (size.width * 0.05),
          size.height - 2 * (size.height * 0.1))
      ..cubicTo(
          size.width * 0.7 - (size.width * 0.01),
          size.height - 1.88 * (size.height * 0.1),
          size.width * 0.7 + (size.width * 0.01),
          size.height - 1.88 *  (size.height * 0.1),
          size.width * 0.7 + (size.width * 0.05),
          size.height - 2 * (size.height * 0.1))
      ..lineTo(size.width, size.height * 0.7)
      ..lineTo(size.width, 0)
      ..lineTo(0, 0)
      ..close();

I know that there are a lot of numbers, but you can extract some points as separate variables for a better readability.
Practically instead of drawing a Quadric Bezier, we draw 2 lines and the curve between them.
Also you can add clipBehavior: Clip.antiAliasWithSaveLayer to your ClipPath for a smooth drawing


text:
Q: How can I reveal type hints in PyCharm? Python's mypy has a special function called reveal_type() which asks the linter to display the type of variables.
PyCharm does not support it and instead shows the function as non-existing.
How can I display the type hint of a variable?

A: By default, PyCharm binds the F1 key to the "display documentation" command.

When displaying the documentation, you're able to see the type of variables, function signatures, class signatures, and docstrings.
You're also able to view the type directly using ctrl+shift+P or by hovering with the mouse and pressing ctrl.
If you do not use the default keymap, you may navigate to View | Quick documentation:


text:
Q: Ruby on rails: Remote Upload A File Using AJAX I've successfully uploaded a file using PUT and html, but is there a way to upload a file in a ajax remote_form_for ?
I've tried this to no success:
<% remote_form_for @song,:html => { :multipart => true }, :url => { :action => 'upload' } do |f| %>

A: The standard remote_form_for doesn't understand multipart form submission so you can't actually do this without some leg-work as indicated by yoda above.
The other way to achieve this is by using an iframe.

A: If you're using Rails 3, try the Remotipart gem. It makes AJAX style file uploads relatively painless.
http://rubygems.org/gems/remotipart
http://github.com/leppert/remotipart


text:
Q: Rewrite friendly URL not work by click on link I'm trying to rewrite my website URL to more friendly URL, for example:

www.mysite.com/profile.php

to

www.mysite.com/profile

so far I'm able to do it by writing the rewrite URL in the URL address bar, but when go to the page by click on the link, the profile page URL doesn't change to rewrite URL. Am I missing something here?
this is my .htaccess codes
Options +FollowSymLinks
RewriteEngine On    # Turn on the rewriting engine
RewriteRule    ^profile/?$    profile.php    [NC,L]   # Handle requests for "profile"

Thanks for any suggestions.

A: You need to change the URL of profile..
Profile

A: mod_rewrite will not change URLs in your code. You have to do it.
If you can't or don't want to, you can use RewriteRule with R option to map from old to new URL.

A: It doesn't change because your rule only internally rewrites profile to profile.php, you need a different rule to do it the other way, and externally so the browser gets redirected:
RewriteCond %{THE_REQUEST} \ /profile\.php
RewriteRule ^ /profile [L,R]


text:
Q: Holomorphic map onto a complex curve has finitely many critical values Let $\pi:S\to C$ be a holomorphic map where $S$ is a compact complex surface and $C$ is a complex curve. How can we show that the set of critical values of $\pi$ is a finite subset of $C$? (I know that Sard's theorem implies that the set of regular values of $\pi$ is a dense subset of $C$, but I can't see that this implies that there are only finitely many critical values.)
P.S. For a holomorphic map between compact complex manifolds, does the set of critical values (which is a closed set of the target) is a subvariety of the target? (If this is true the above result follows immediately.)

A: Consider the subset $X\subset S$ consisting of points $x\in S$ such that where $d\pi(x)=0$. Note that $x\in S$ is a critical point of $\pi$ precisely when $x\in X$ (since the range of $\pi$ is is complex 1-dimensional and $\pi$ is holomorphic).
Then $X$ is a (closed) analytic subvariety in $S$. By the compactness of $S$, $X$ is also compact. Hence, it has only finitely many irreducible components $X_1,...,X_m$.
(These components need not have the same dimension.)
For each irreducible component $X_k$ of $X$, $\pi|_{X_k}$ is constant (since $d\pi$ vanishes at $X_k$ and $X_k$ is irreducible). The subset
$$
\{\pi(X_k): k=1,...,m\}$$
is exactly the set of critical values of $\pi$. It is finite since each $\pi(X_k)$ is a singleton.
Note that this proof did not use the assumption that $S$ is 2-dimensional: The result holds whenever $S$ is a compact complex manifold and the range of $\pi$ is complex 1-dimensional.


text:
Q: How to show rows with duplicate values first in SQL without grouping I have a Table like this
I want to fetch all products, but I want to show products with the same PID first (without grouping them)
Sample Table
pid product
1   Red
3   Green
2   Blue
4   Violet
3   Magenta
1   Black

Expected Results
pid product
1   Red
1   Black
3   Green
3   Magenta
2   Blue
4   Violet

I tried this  ORDER BY pid ASC
it partially solves the problem but results appear like this
pid product
1   Red
1   Black
2   Blue (comes in between)
3   Green
3   Magenta
4   Violet

I want all products with more than one pid to come first sorted from top to bottom.

A: From the comment I think your MySQL version doesn't support windows function so you could use:
SELECT
  t.pid,
  t.product,
            ( SELECT COUNT('pid')
              FROM test_tbl ct
              WHERE ct.pid = t.pid
            ) as counter
FROM
  test_tbl t
  order by counter desc,pid asc ;

Result:
pid   product   counter
1      Red        2
1      Black      2
3      Green      2
3      Magenta    2
2      Blue       1
4      Violet     1

Demo

A: WITH cte AS (
    SELECT *, COUNT(*) OVER (PARTITION BY pid) cnt
    FROM datatable
)
SELECT * FROM cte ORDER BY cnt DESC


text:
Q: Android send ArrayList commands with delay to OBD I need to send a list of commands to OBD port with some delay because the ELM327 can't manage all commands together...
I'm trying with this code but not work
public void repeatCommand(){

        for (final String command : commandArray){

            Log.d(TAG, "Giro for");

            final Handler handlerTimed = new Handler();
            handlerTimed.postDelayed(new Runnable() {
                @Override
                public void run() {
                    //Do something after 100ms
                    sendMessage(command);
                }
            }, 1000);

        }

        /*String message = "010C\r";
        sendMessage(message);*/
    }

It's only send the first command after 1 sec but the other commands nope.
How can i send all comands delayed for let the write to manage all commands sended to the OBD?
Ok i use the suggested method that send the first command and wait for response.... when get response, send the next message.
 private synchronized void manage(BluetoothSocket socket, BluetoothDevice
            device) {
        Log.d(TAG, "connected, Socket Type:");

        // Cancel the thread that completed the connection
        if (mConnectThread != null) {
            mConnectThread.cancel();
            mConnectThread = null;
        }

        // Cancel any thread currently running a connection
        if (mConnectedThread != null) {
            mConnectedThread.cancel();
            mConnectedThread = null;
        }
        // Cancel any thread currently managing connections
        if (mManageThread != null) {
            mManageThread.cancel();
            mManageThread = null;
        }

        // Start the thread to manage the connection and perform transmissions
        mManageThread = new ManageDataThread(socket);
        mManageThread.start();

        // Send the name of the connected device back to the UI Activity
        Message msg = mHandler.obtainMessage(Constants.MESSAGE_DEVICE_NAME);
        Bundle bundle = new Bundle();
        bundle.putString(Constants.DEVICE_NAME, device.getName());
        msg.setData(bundle);
        mHandler.sendMessage(msg);
        // Update UI title
        updateUserInterfaceTitle();
    }

Here the Thread that manage connection..
  public class ManageDataThread extends Thread {

        private final BluetoothSocket mmSocket;
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;
        private boolean wait_response = false;

        public ManageDataThread(BluetoothSocket socket) {
            Log.d(TAG, "create ManageDataThread: ");

            mmSocket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;

            // Get the BluetoothSocket input and output streams
            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) {
                Log.e(TAG, "temp sockets not created", e);
            }

            mmInStream = tmpIn;
            mmOutStream = tmpOut;
            mState = STATE_CONNECTED;

        }

        public void run() {

            while(true) {
                for (final String command : commandArray) {

                    byte[] send = command.getBytes();
                    write(send);
                    //mState = STATE_WAIT_RESPONSE;

                    byte[] buffer = new byte[1024];
                    int bytes;

                    // Keep listening to the InputStream while connected
                    while (wait_response) {
                        try {
                            // Read from the InputStream
                            bytes = mmInStream.read(buffer);

                            //TODO devo gestire l'arrivo di bytes
                            ObdCommand obc = new ObdCommand();
                            obc.readResult(mmInStream);

                            formattedMessage = obc.getResult();
                            //buffer = (byte) obc.getBuffer();

                            // Send the obtained bytes to the UI Activity
                            mHandler.obtainMessage(Constants.MESSAGE_READ, bytes, -1, formattedMessage)
                                    .sendToTarget();

                            wait_response = false;

                        } catch (IOException e) {
                            Log.e(TAG, "disconnected", e);
                            connectionLost();
                            break;
                        }
                    }

                }
            }

        }

It's little bit imperfect but now it's work....
I will open a new post for stop it and update the array list of commands because if i change the list of commands, the loop keep the old array list, so i need to notify the thread that the arraylist has change
EDIT
Don't use while(true) inside thread, better to use a variable set to True e when need to stop thread set the variable to false, or problem occurs when stop thread....

A: One thing to consider is that when you create a handler and don't provide it with a looper it will use the looper of it's current thread.
So my best guess, since we don't have your code, is that you do in fact run it in a thread which is not the main one. make sure your thread doesn't get killed somewhere along the way and it should work.
Also, a few coding tips:
First, I must say that it would be more efficient to set the handler outside of the loop.
That way you don't waste memory creating a handler in each iteration.
So it should look something like that:
public void repeatCommand()
{
    final Handler handlerTimed = new Handler();

    for (final String command : commandArray){

        Log.d(TAG, "Giro for");

        handlerTimed.postDelayed(new Runnable() {
            @Override
            public void run() {
                //Do something after 100ms
                sendMessage(command);
            }
        }, 1000);
    }
}

Second, I strongly recommend that you will set the consts of your class, like that 1000 value.

A: The proper way to work with OBD2 – which is a serial protocol – is to implement something like a command queue with command-specific callbacks that deliver the response to the command you have requested to it. The command queue should work in a background thread, operating the queue and listening to the serial port. Don't even start w/ delays or similar approaches.


text:
Q: why is my search function return an error Related Field got invalid lookup: category My search function works fine but it throws me an error every time i try to search an existence post in my website. when i deleted ForeignKey in the Question model under category field the error is gone. please how can i filter that category that have a ForeignKey
the error:
FieldError at /index/
Related Field got invalid lookup: category

my models:
class Category(models.Model):
    name = models.CharField(max_length=100, blank=False, null=False)

    def __str__(self):
        return str(self.name)

class Question(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=100, blank=False, null=False)
    body = RichTextField(blank=False, null=False)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    slug = models.SlugField(unique=True, max_length=200)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.title)
        super(Question, self).save(*args, **kwargs)

    def __str__(self):
        return str(self.title)

the views:
def index(request):
    query = request.GET.get('q', None)
    list_of_question = Question.objects.all()
    if query is not None:
        list_of_question = Question.objects.filter(
            Q(title__icontains=query) |
            Q(category__category__icontains=query)
        )
    unread_notifications = Notification.objects.filter(user=request.user, is_read=False).count()

    paginator = Paginator(list_of_question, per_page=1)
    return render(request, 'index.html', {'unread_notifications':unread_notifications,'list_of_question':list_of_question, 'paginator':paginator})

my form:
<form action="" method="GET">
        <input placeholder="Search By Category" type="text" class="form-control" name="q">
    </form>

A: If you filter with category__… this means that the rest of the filter should deal with fields of a Category model, and a Category has a name field, so you filter with:
list_of_question = Question.objects.filter(
    Q(title__icontains=query) |
    Q(category__name__icontains=query)
)


text:
Q: How Do I Properly Setup For Cross Domain Script Execution? We utilize a third party reporting application server. Our application (we will call this Site A) includes a script, provided by the reporting server, that has a method for embedding reports. When the method is called, it creates an iFrame that loads the requested report, scripts and styles from the reporting server (we will call this Site B).
The report page loads as expected, embedded in it's iFrame. Interaction, within the report, runs as expected. However, the report page (from Site B) then sends a postMessage() to the parent (Site A) to call a method to resize the container element holding the iFrame, and another postMessage() to the parent (Site A) to scroll to the top of same container element.
The vendor tells us we need to implement the proper CORS settings to allow this to work, offering no further explanation other than "other clients are using this approach". Currently it throws an error in the console stating:

Uncaught DOMException: Blocked a frame with origin "[Site B]" from
  accessing a cross-origin frame.

I've read a ton of documentation, on MDN and other sites, over the past two days and I am still confused as to which server which settings are applied towards? I have seen several examples regarding setting headers here and there, but nearly everything I've read applies solely to making Ajax requests from the client (served by Site A) to the remote (Site B), and nothing at all regarding what is necessary for the scenario we are dealing with. Anyone out there that can shed some light here? Which server needs which headers?
Any help is greatly appreciated.

A: CORS is irrelevant here.
The error message indicates that Site B is trying to access something on Site A which is forbidden. That means that Site B should be using postMessage, but isn't (or at least, isn't correctly).

A: In order to avoid CORS problems you need the following:
if site A is using an iframe to load site B. On site B NGINX/APACHE configuration you need to include this headers:
add_header 'Access-Control-Allow-Origin' "$http_origin" always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Requested-With' always;

on APACHE: https://enable-cors.org/server_apache.html
on NGINX: https://enable-cors.org/server_nginx.html


text:
Q: kubeadm init --config issue I'm trying to init a kubernetes cluster using kubeadm. I followed the instructions found here for the stacked control plane/etcd nodes. For the container runtime installation, it is recommended that the runtime (in my case, containerd) and kubelet use the same cgroup driver (in my case, systemd).
Still following the instructions, I added
[plugins."io.containerd.grpc.v1.cri".containerd.runtimes.runc]
    ...
    [plugins."io.containerd.grpc.v1.cri".containerd.runtimes.runc.options]
       SystemdCgroup = true

to /etc/containerd/config.toml and then restarted containerd using sudo systemctl restart containerd
So far so good, everything work as expected. Then I get to the part where I have to configure cgroup driver used by kubelet. It says I have to call kubeadm init with a config file. Something like: sudo kubeadm init --config.yaml. Here is my problem: I found very little information about what should that config file look like. The documentation says kubeadm config print init-defaults should print the default config but the default config has nothing to do with my setup (ie, it uses docker instead of containerd). I found an example of a file here but so far I've not managed to adapt it to my setup and I've found very little documentation to do so. There has to be a simpler way than just rewriting an entire config file just for one attribute change, right? How come I can't print the literal config file used by kubeadm init?

A: My solution was to restart containerd with default config (no systemd cgroup), then run kubeadm init as I would normally. Once the cluster was started, I printed the config to a file with: kubeadm config view. I then modified that file to add the required parameters to set systemd cgroup. Finally, I configured containerd to use systemd and ran kubeadm init with the newly created config file. Everything worked.
Warning: The command kubeadm config view says that the "view" command is deprecated and to use kubectl get cm -o yaml -n kube-system kubeadm-config instead, but the output of that command doesn't create a valid kubeadm config file, so I don't recommend doing that.


text:
Q: Unable to set DataContext through XAML, but the same can be set through Code Datacontext does not work when I declare it in XAML. But the same works if set in Code.
Detailed Analysis.
My XAML
    <Window x:Class="SimpleDatabindingwithclass.MainWindow"
       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525" Name="windo">
    <Grid DataContext="{Binding ElementName=windo,Path=objectOfStudent}">
    <Grid.RowDefinitions>
        <RowDefinition Height="*"></RowDefinition>
    </Grid.RowDefinitions>
    <TextBox Grid.Row="0" Margin="25" Height="25" Width="100" HorizontalAlignment="Left" Name="TextBox1" Text="{Binding Path=StudentName}"></TextBox>

</Grid>
</Window>

Corresponding code.
    namespace SimpleDatabindingwithclass
    {
     /// <summary>
     /// Interaction logic for MainWindow.xaml
     /// </summary>
     public partial class MainWindow : Window
     {
         public MainWindow()
         {
              InitializeComponent();
              Student objectOfStudent = new Student();
              objectOfStudent.StudentName = "John diley";
              objectOfStudent.Address = "20, North Travilia, Washington DC.";
              //not setting datacontext here since i set that in xaml
         }
         public class Student
         {
             private string studentname;
             private string address;

             public string Address
             {
                 get { return address; }
                 set { address = value; }
        }
        public string StudentName
        {
            get{return studentname;}
            set{studentname = value;}
        }
    }
}

}
But, the same when I use this XAML & set datacontext through code, it works!
ie, When I put something like
     this.DataContext = objectOfStudent;

in MainWindow(), the application Works!
What do u think the problem is?

A: Binding only works with public properties, you can't bind to some local variable. Make objectOfStudent as public property of your MainWindow.
Edit:
public Student objectOfStudent { get; set; }

public MainWindow()
{
    InitializeComponent();
    objectOfStudent = new Student();
    objectOfStudent.StudentName = "John diley";
    objectOfStudent.Address = "20, North Travilia, Washington DC.";
    //not setting datacontext here since i set that in xaml
 }

Edit:
Also you need to implement INotifyPropertyChanged interface in the MainWindow and Student classes and raise PropertyChanged when you set the properties. That is the right way, the binding will be updated everytime you change the properties. Or a simple way: create objectOfStudent before calling InitializeComponent.
public MainWindow()
{
    objectOfStudent = new Student();
    objectOfStudent.StudentName = "John diley";
    objectOfStudent.Address = "20, North Travilia, Washington DC.";
    InitializeComponent();
    //not setting datacontext here since i set that in xaml
 }

A: This is because you are trying to use a local variable named objectOfStudent via XAML - this has no meaning in the context of XAML. XAML only accepts fields and properties, not local variables.


text:
Q: How to make a perfect square. I have the following expression:
$$ 9b^2c^2-84abce+36a^2e^2~$$
As it stands this is not a perfect square. Please how do I make it into a perfect square by placing conditions on the product $ae$?  Thanks.
Edit: I would like to get something of the form $$(A*bc)^2$$ preferably.

A: Hint:  $(3b-6ae)^2=9b^2c^2-36abce+36a^2e^2$


text:
Q: Up to date gwt-incubator jars for Maven I want to use the latest gwt-incubator drop - gwt-incubator-july-14-2009.jar - in a Maven project.
The most recent version published on central is 1.5-Dec_28.
Is there a more up-to-date maven repo for the gwt-incubator jar?

A: Of all the places, I found it at http://dist.codehaus.org/mule/dependencies/maven2/com/google/gwt/gwt-incubator/.

A: The july-14-2009 version of gwt-incubator has recently (17th September 2009) been released  to the maven.xwiki.org repository.


text:
Q: Can I split a .txt corpus based on first appearance of each item in a list (in python)? I have a large .txt corpus which I would like to text.split() into its subsections based on the first appearance of each item in a list, as follows:
"No. 1.", "No. 2.", "No. 3." etc. up to "No. 4800."

These values mark the start of each new document that I want to divide the full corpus into and create a document term matrix for. Within a document, these numbers appear several times but the first appearance always marks the start of the new document.
Splitting on "No. " hasn't worked as there are many other instances of it in the text. I've created a list of all the No. 1-4800 indicators, but cant figure out how to split the text based on that list. Any help/ideas would be greatly appreciated!

A: For anyone with a similar issue, I was able to solve it using this code below:
myfile2 = re.split("\n\nNo.\s[1-5000].\n", myfile)

The re.split() was able to detect the digits while my original attempt: myfile.split("\n\nNo.\s[1-5000].\n") was not able to.


text:
Q: how to add watermark to pdf using itexpdf i am using following code to generate pdf file, everything is fine and working but i need to add watermark with the pdf file also alternate color to rows generated in pdf table.
response.setHeader("Content-disposition", "attachment; filename=\"" + reportName + ".pdf\"");
        response.setContentType("application/pdf");
        PdfWriter.getInstance(document,response.getOutputStream());

        try {
            document.open();
            addTitlePage(document, reportName,path);

           /* Image image = Image.getInstance(path+"images/abi.png");
            image.setAbsolutePosition(40f, 770f);
            image.scaleAbsolute(70f, 50f);
            document.add(image);*/

            //float[] colsWidth = {1.5f,3f,4f,4f,2f};

            List<Float> colsWidth = new ArrayList<Float>();
            int iterator = 1;
           while (iterator <= headerMap.size()) {
               if(iterator==1){
                   colsWidth.add(1.5f);
               }else{
                colsWidth.add(3f);
               }
                iterator++;
            }
           float[] floatArray = ArrayUtils.toPrimitive(colsWidth.toArray(new Float[0]), 0.0F);

           PdfPTable table = new PdfPTable(floatArray);
            table.setWidthPercentage(98);
            table.setHorizontalAlignment(Element.ALIGN_CENTER);

            PdfPCell c1 = new PdfPCell();
            for (Iterator it = headerMap.keySet().iterator(); it.hasNext();) {
                String headerName = (String) headerMap.get(it.next());
                c1 = new PdfPCell(new Phrase(headerName, headerFont));
                c1.setBackgroundColor(BaseColor.LIGHT_GRAY);
                table.addCell(c1);
            }
            table.setHeaderRows(1);
            table = custDAO.creadPDFTable(query, table);
            document.add(table);
            document.addAuthor(userViewModel.getUsername());
            document.addCreationDate();
            document.addCreator("POC");
            document.close();
            response.flushBuffer();
private static void addTitlePage(Document document, String reportName,String path) throws DocumentException, MalformedURLException, IOException {
        Paragraph preface = new Paragraph();
        addEmptyLine(preface, 1);
        /**
         * Lets write a big header
         */
        Paragraph paragraph = new Paragraph(reportName, titleFont);
        paragraph.setAlignment(Element.ALIGN_CENTER);
        document.add(paragraph);

        /**
         * Add one empty line
         */
        addEmptyLine(preface, 1);
        document.add(preface);
        Image image = Image.getInstance(path+"/"+"/abilogo.PNG");
        image.setAbsolutePosition(40f, 770f);
        image.scaleAbsolute(70f, 50f);
        document.add(image);

    }
    private static void addEmptyLine(Paragraph paragraph, int number) {
        for (int i = 0; i < number; i++) {
            paragraph.add(new Paragraph(" "));
        }
    }

and this the method i use to create pdftable.(rows)
public PdfPTable creadPDFTable(String query,PdfPTable table){
        int numberOfColumns=0,sno=1;
        Connection connection = getConnection();
        if (connection != null) {
            try {
                PreparedStatement reportTablePS = connection.prepareStatement(query);
                ResultSet reportTable_rst = reportTablePS.executeQuery();
                ResultSetMetaData reportTable_rsmd = reportTable_rst.getMetaData();
                numberOfColumns = reportTable_rsmd.getColumnCount();
                while (reportTable_rst.next()) {
                    table.addCell(new PdfPCell(new Paragraph(String.valueOf(sno), textFont)));
                            for (int columnIterator = 1; columnIterator <= numberOfColumns; columnIterator++) {
                                 String column = reportTable_rst.getString(columnIterator);
                                 table.addCell(new PdfPCell(new Paragraph(column, textFont)));
                            }
                            sno++;
            }
            } catch (Exception ex) {
                ex.printStackTrace();
            }finally {
                try {
                    closeConnection(connection, null, null);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
        return table;
    }

my main concern is to add watermark also adding alternate color to rows.
Please help to resolve this as i am unable to fix this for long time.
Regards

A: If you want add an watermark as a image u can use the code below. An other way to add a text watermark is to use annotations.
PdfReader pdfReader = null;
    Stream outputStream = null;
    PdfStamper pdfStamper = null;

    try
    {
        pdfReader = GetPdfReaderObject();
        outputStream = new FileStream(filePathDestination, FileMode.Create, FileAccess.Write, FileShare.None);
        pdfStamper = new PdfStamper(pdfReader, outputStream);

            PdfLayer layer = new PdfLayer("watermark", pdfStamper.Writer);

            for (int pageIndex = 1; pageIndex <= pdfReader.NumberOfPages; pageIndex++) {
                pdfStamper.FormFlattening = false;
                iTextSharp.text.Rectangle pageRectangle = pdfReader.GetPageSizeWithRotation(pageIndex);
                PdfContentByte pdfData = pdfStamper.GetOverContent(pageIndex);

                pdfData.BeginLayer(layer);

                PdfGState graphicsState = new PdfGState();
                graphicsState.FillOpacity = 0.5F;
                pdfData.SetGState(graphicsState);
                pdfData.BeginText();

                iTextSharp.text.Image watermarkImage = iTextSharp.text.Image.GetInstance(System.Drawing.Image.FromFile(watermarkImagePath), ImageFormat.Png);

                float width = pageRectangle.Width;
                float height = pageRectangle.Height;

                watermarkImage.SetAbsolutePosition(width / 2 - watermarkImage.Width / 2, height / 2 - watermarkImage.Height / 2);

                pdfData.AddImage(watermarkImage);
                pdfData.EndText();
                pdfData.EndLayer();
            }
        }
        pdfStamper.Close();
        outputStream.Close();
        outputStream.Dispose();
        pdfReader.Close();
        pdfReader.Dispose();

    } catch (Exception e) {
        ....
    }
}

And not forget to remove the watermark if you want to add an other watermark.


text:
Q: select elements after last occurence of a class and before a particular class with CSS I am trying to solve a problem without using JavaScript loops. I want to apply css rules to table cells. I struggle with applying the rules before my start cell.
I found this question Select all elements before element with class?
I struggle with the implementation of this technique as my code would need a more sophisticated check. Especially when thinking of dealing with two bookings before the start.
If I could find the last booking before the start I could use the technique from that question.
Does anyone have an idea how to solve this without javascript?

table {
  margin: auto;
  width: 100%;
  border: thick groove black;
  border-radius: 5px;
  text-align: center;
}
td {
  border: thin groove gray;
  width: 10vw;
  height: 5vh;
}
td:hover {
  cursor: pointer;
}
td.start {
  background-color: green;
}
td.booked {
  background-color: orange;
  cursor: not-allowed;
}
td.start ~ td:not(.booked) {
  background-color: lightblue;
}
td.start ~ td ~ td.booked:hover {
  cursor: not-allowed;
}
td.start ~ td ~ td.booked ~ td {
  background-color: red;
}
td.start ~ td ~ td.booked ~ td:hover {
  cursor: not-allowed;
}

      Invalid
      Invalid
      Booked
      OK
      OK
      Start
      OK
      OK
      Booked
      Invalid
      Invalid

  Relative to th start cell, cells after a booking are not allowed. Cells before a booking are allowed.

  We can select the cells after the start cell with:

  td.start ~ td:not(.booked) { background-color: lightblue; }

  We can select the cells after the booked cell after the start cell with:

  td.start ~ td ~ td.booked ~ td { background-color: red; }

    Q. How can we select the cells before the start cell and apply the rules ?

A: In this case, I think can't achieve it by linked question's next-sibling combinator and universal selector combination. Use JavaScript or apply class, data-* attribute each td elements.

A: CSS doesn't do "look behind", so you can never style something based on what comes after it. The linked trick works because it styles everything, then removes the style after the condition was met. We can use the same technique.

table {
  margin: auto;
  width: 100%;
  border: thick groove black;
  border-radius: 5px;
  text-align: center;
}
td {
  border: thin groove gray;
  width: 10vw;
  height: 5vh;
}

tbody td {
  /* style everything */
  background-color: red;
  cursor: not-allowed;
}
tbody td.booked ~ * {
  /* everything following "booked" */
  background-color: lightblue;
  cursor: pointer;
}
tbody td.start {
  background-color: green;
}
tbody td.booked {
  background-color: orange;
  cursor: not-allowed;
}
tbody td.start ~ td.booked ~ * {
  /* everything following "booked" following "start" */
  background-color: red;
  cursor: not-allowed;
}

      Invalid
      Invalid
      Booked
      OK
      OK
      Start
      OK
      OK
      Booked
      Invalid
      Invalid

As you can see, this works even with two 'booked' items before start, but we lose control of the 'invalid' in between them. This is because we have to style everything after 'booked' before we know if 'start' is coming next.
A better solution, if at all possible, is to add classes to each cell within the code that generates the HTML. Or, as you've mentioned, retroactively add classes with JavaScript.


text:
Q: Ironclad Cryptography Library for Emacs Lisp? I love the Ironclad cryptography library for Common Lisp. Out of curiosity, has anyone implemented this library into their Emacs Lisp project?  In researching this question, I suspected there would be too much work to make it compatible with a pure Emacs Lips project, but a hybrid Elisp and CL project might also be an option for what I need to do.

A: Some of the functionality of ironclad is built-in to Emacs via the secure-hash and md5 functions. http://www.gnu.org/software/emacs/manual/html_node/elisp/Checksum_002fHash.html has more information.
These functions are written in C. I don't know for sure, but it seems like Emacs Lisp's slow speed and small fixnums would be a real obstacle for doing this work directly in pure elisp.


text:
Q: List of Mysql "Write" commands, or how to determine whether a mysql command involves a write operation I'm looking to identify all the write commands to mysql database and perform a function every time a mysql write command is called. This could be something like filtering (blocking) some of the commands or making a web request on a new thread. As of right now, I'm planning to use the general log of mysql to determine what these write commands are, but this doesn't work for filtering (blocking) commands.
Here's a list of some "write" mysql commands i've found:

*

*insert

*update

*replace

Are there any other edge cases I have to worry about? For example, is there anything that could modify a select command to make it a write operation somehow? Would the following write operation eventually be re-executed as one of the above 3?
Is "set" a write command to the database, or only for variables used in the mysql session?

A: I had done a similar sort of filtering in PHP code. The context was different though; we were utilizing Master-Slave replication architecture. For directing queries to relevant servers (Read queries to Slave, and Write Queries to Master), a custom function is written to identify the type of query.
One noteworthy point is that, queries within a Transaction/Lock/Unlock operation, are always considered Write queries.
Also, for Set, only SET AUTOCOMMIT and SET TRANSACTION are Write commands.
Please find below a largely toned down version of the actual code we are using:
/*
* All the WRITE operation commands
*/
$write_commands = array(
    'create',
    'alter',
    'drop',
    'truncate',
    'comment',
    'rename',
    'insert',
    'update',
    'delete',
    'merge',
    'call',
    'lock',
    'unlock',
    'start',
    'commit',
    'rollback',
    'savepoint',
    'set',
    'replace'
);

/*
* method to determine whether Read or Write
* @param $sql String (SQL query string)
* @return: void
*/
function determineReadOrWrite(string $sql): void {

    $dml_query = false;

    $words = str_word_count(strtolower(trim($sql)), 1);
    $first_word = isset($words[0]) ? $words[0] : '';
    $second_word = isset($words[1]) ? $words[1] : '';

    if (in_array($first_word, $this->write_commands)) {
        /* if it is not "set" then we set to master link */
        if ($first_word !== 'set'
        || ($first_word === 'set' && $second_word === 'autocommit')
        || ($first_word === 'set' && $second_word === 'transaction')
        ) {
            $dml_query = true;

            /* If we Lock tables or Begin a Transaction, we should run on Write servers only */
            /* till we Commit/Rollback or Unlock Tables */
            if(($first_word === 'start' && $second_word === 'transaction')
            || $first_word === 'lock'){

                /* Set whether the current query is starting a Transaction / Lock etc */
                $this->wait_for_commit_rollback = true;
            }

            /* We are doing Commit/Rollback or Unlock Tables */
            if ($first_word === 'commit'
            || $first_word === 'rollback'
            || $first_word === 'unlock') {
                $this->wait_for_commit_rollback = false;
            }
        }
    }

    /* It's a insert/update/delete/etc query - to be run on Write Db only */
    if ($dml_query || $this->wait_for_commit_rollback) {
        $this->setActiveConnectionToWrite(true);

    } else {
        $this->setActiveConnectionToRead();
    }

}

A: Well, you have asked a lot in this question, so what you can do:

*

*If you want global counters for operations performed by MySQL then
SHOW STATUS
will return all counters for your server including those for operations like
Com_insert
Com_insert_select
Com_replace
Com_replace_select
Com_select
Com_update

You can just check those values whether any of such operation have been performed

*Another way to monitor INSERT, UPDATE, REPLACE etc. is to use triggers (https://dev.mysql.com/doc/refman/8.0/en/trigger-syntax.html). Example in documentation clearly shows where triggers do their best - serving as means for increasing local counters (variables). But still you should remember that triggers are specific for current operation/table.

*Speaking of edge cases. Yes, they are - transactions and procedures for example. Procedure can include a lot of operations above. Thus you need check those.

*And generally speaking it's not the best idea to monitor atomic operations like INSERT from outside of DB. You should rely on DB means on that (triggers, variables, global counters)


text:
Q: How to save firmware file selected from document picker in swift I am trying to upgrade the radar using a firmware file. I am selecting a firmware file using a document picker and saving its path to a singleton class variable. But the problem is when I go to the background and return it shows that the file does not exist in that path. How can I resolve the issue? The code for saving the path is
`
    let file = urls[0]
    do {
         let filePath = file.path

         self.firmwareLocalfilePath = filePath

         SessionController.sharedController.filePath = self.firmwareLocalfilePath

'
Here SessionController.sharedController.filePath is my singleton variable. The condition to check file availability is
if FileManager().fileExists(atPath: self.firmwareLocalfilePath!)
When I go to the background and come back it is getting that
"File does not exist [/private/var/mobile/Containers/Data/Application/92D35520-C1E8-44DD-960E-B7024E8602E8/tmp/com.houston-radar.app-Inbox/dc300b04_v297.frm]"
There are lots of other kinds of stuff there that's why I am not uploading the full code. The code is related to the file I wrote here. How can I resolve this issue? Can I save the file somewhere like userdefault. I googled it a lot but did not get any solution. Thank you for your help

A: Your file is loaded/stored in a temporary directory. iOS itself decides when it wants to remove files from that directory. It appears you're currently experiencing it while going to the background. I would recommend trying to initially save it in a non temporary directory, but I'm not sure if that's possible. Therefore, you could try to move it from the temporary folder to a non temporary folder, such as the Application Support folder.
do {
    // 1. Get the firmware URL at which the firmware file is located
    //    (your current temporary URL)
    let firmwarePath: URL = NSURL.fileURL(withPath: localFilePath)

    // 2. Create a persistent URL
    let newFirmwarePath = try FileManager.default
        .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
        .appendingPathComponent(firmwarePath.lastPathComponent)

    // 3. Try moving the file from the temporary directory to a non temporary directory
    //.   This is where we move it from the /tmp to /Application Support
    try FileManager.default.moveItem(at: firmwarePath, to: newFirmwarePath)

    // 4. Lastly, update your static property
    SessionController.sharedController.filePath = newFirmwarePath.path
} catch {
    print(error)
}

I feel like storing the path this way is very error prone, so I can only recommend trying to figure out an alternative way to communicate the file/path/location. But I suppose this should work


text:
Q: Pandas groupby.agg removes columns I've read the other questions regarding similar issues but i still couldn't figure out how to overcome this.
This expression loses all my df columns except the one on which i groupby on and another column (do not know why that in particular).
df = df.groupby('Full_name').agg(';'.join).reset_index()
The solutions given in the other questions was this reset_index() but it does not work in my case. How do i avoid this automatic-exclusion-of nuisance-columns otherwise?
Thing is i'm using the same expression on other dataframes and it works like a charm.

A: Try to convert all columns to strings:
df = df.astype(str).groupby('Full_name').agg(';'.join).reset_index()


text:
Q: Excluding BlobProperty in GAE model in to_dict I learned some python for a project using GAE and I've got everything figured out except one thing.  When converting a GAE model to JSON, how do I skip over a BlobProperty (say, if a Profile model has an avatar property)?  So instead of the standard:
def to_dict(self):
    return dict([(p, unicode(getattr(self, p))) for p in self.properties()])

I'd need something like:
def to_dict(self):
    return dict([(p, unicode(getattr(self, p))) for p in self.properties() if type(p) is not db.BlobProperty])

But it's not working for me. I was looking at this thread, which is pretty similar, but I can't get it to work for my case.  I'm probably doing something wrong in Python .  Any thoughts?

A: db.Model.properties() returns a dict of strings to properties, and dict.iter yields keys only.  So type(p) is always going to be a string.  If you want to keys and values use db.Model.properties().items() instead.  db.Model.
Instead try something like:
def to_dict(self):
  return dict([(p, unicode(getattr(self, p))) for p,t in self.properties().items() if type(t) is not db.BlobProperty])


text:
Q: How to set the GenericDirCtrl to show custom folder as top directory in wxpython? I want to show my folder as top directory in wxPython's GenericDirCtrl component. I tried SetPath() and path in my code but it only focuses the selected folder , not making it the top of the tree.
In my form's constructor i create it like that:
self.folder_tree_project = wx.GenericDirCtrl(self.pnl_edit, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(200, -1), wx.DIRCTRL_3D_INTERNAL | wx.SUNKEN_BORDER, wx.EmptyString, 0)

self.folder_tree_project.ShowHidden(False)
bSizer5.Add(self.folder_tree_project, 0, wx.ALL | wx.EXPAND, 5)

and then i am trying to change the top directory by using the working directory in my config file:
if self.config.workdir != "":
    # self.folder_tree_project.SetPath(self.config.workdir)
    # self.folder_tree_project.Path=self.config.workdir

both only focuses. Not changing the top directory.
Is there any way or attribute  to handle it?

A: You can use the wx.GenericDirList GetTreeCtrl() function to get the pointer to  its wx.TreeCtrl attribute, and then use the TreeCtrl.AppendItem() to append the name of the directory you wanted to its root item.
its only the name of the directory however, and You're going to have to code its functionality, by binding mouse clicks and appending the directory's child files and child directories using os.walk (or by any other means), while working with the wx.TreeCtrl pointer.
maybe there's a better, embeded in wxpython api, way to do this, but i could'nt find anything in the documentation.
anyways here's the code for Adding the directory name to the wx.TreeCtrl pointer:
    DirectoryNameHere = "mypath"
    Bsizer = wx.BoxSizer(wx.VERTICAL)
    self.folder_tree_project = wx.GenericDirCtrl(self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(200, -1), wx.DIRCTRL_3D_INTERNAL | wx.SUNKEN_BORDER, wx.EmptyString, 0)

    self.folder_tree_project.ShowHidden(False)
    Tree = self.folder_tree_project.GetTreeCtrl()
    Tree.AppendItem(Tree.GetRootItem(), DirectoryNameHere)

    Bsizer.Add(self.folder_tree_project,1,wx.ALL | wx.EXPAND)
    self.SetSizer(Bsizer)


text:
Q: Generalisation of Binomial Theorem, Leibniz Formula and similar theorems Since the beginning of the year, our maths teacher showed us the Binomial Theorem in $\mathbb{R}$\, then in $\mathbb{C}$\, in $M_n(\mathbb{K)}$ with two matrices which commute, and now the Leibniz Theorem for derivatives.
Each time the proof of the theorem was very similar, by induction, but not exactly the same.
Isn't there a "big" theorem which would gather all these previous theorems as particular cases?
Or isn't there a proof which would be the same for all of these?

A: I think you probably want something like

Let $A,B:M \to M$ be linear operators acting on a module $M$ over an abelian ring $R$ (with identity $1_R$), such that $AB=BA$. Then we have the identity
  $$ (A+B)^n = \sum_{k=0}^n \binom{n}{r}_R A^r B^{n-r}, $$
  where the coefficients are defined recursively by
  $$ \binom{n}{0}_R = \binom{n}{n}_R = 1_R, \\
\binom{n}{r}_R = \binom{n-1}{r-1}_R+\binom{n-1}{r}_R. $$

(I'm not sure this result has a name in this general form, but it'll probably involve at least one of the words "binomial" and "Leibniz".)
This obviously has the usual inductive proof. It contains specialisations to multiplying by $x$ and $y$ over the real and complex numbers, commuting matrices on a field, and derivatives on rings of smooth functions. This last may not be obvious, so I'll just point out an algebraic way of doing it.
As you know, the derivative acts by the product/Leibniz rule as
$$ D(f \cdot g)=(Df) \cdot g+f \cdot (Dg), $$
omitting variables. But that means that we can define the action on $f$ and $g$ as
$$ D = \partial_f+\partial_g, $$
i.e. the sum of a partial derivative which only acts on $f$ and one which only acts on $g$. You can see that the operators $\partial_f,\partial_g$ are commutative, and then the general Leibniz rule follows from the above result.
In the binomial form, this is probably the best you can do (you need the additive and multiplicative structure of the module, for example).


text:
Q: Query Data and arrange data Laravel I have 5 columns as [ ID , Type_1 , Type_2 , Salary , Value ]. I want to query data from SQL Server using Laravel fremwork.
if the Type_1 = AAA and Type_2 = BBB I want to sum all salary that have in type_1 'AAA' and Type_2 'BBB' and get all data as the one Item dynamically. See following image for more details.

A: You can try like in this way
$results=Salary::where('Type_1', 'AAA')->where('Type_2', 'BBB')->sum('salary')->get();


text:
Q: Как сделать чтобы переменная сохранялась при выходе из программы в python Мне нужно сделать программу где есть переменная userName, но когда я выхожу из программы мне нужно чтобы эта переменная где то сохранилась и при следующем запуске кода переменная userName, так сказать, была востановленна.
Главный вопрос как это сделать?

A: Ссылка на ответ на английском СО
import pickle as pkl

with open('my_variables','wb') as f:
    pkl.dump([wb1,wbr,body_ang],f)

import pickle as pkl

with open('my_variables','rb') as f:
    new_script=pkl.load(f)


text:
Q: Typescript How to update every object value I have a object like this:
enum FeatureNames = {
  featureA = 'featureA',
  featureB = 'featureB',
  featureC = 'featureC'
}

interface FeatureDetails {
  on: boolean;
}

type Features = Record<FeatureNames,FeatureDetails>;

const myObj: Features = {
  [FeatureNames.featureA]: {
    on: true
  },
  [FeatureNames.featureB]: {
    on: false
  },
  [FeatureNames.featureC]: {
    on: false
  }
}

How can I update the value of every member of myObj so the on value is true?
Without typescript I would just use reduce, but I get a overload error when I try to do so.
Here's the error:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Record'.
    No index signature with a parameter of type 'string' was found on type 'Record'.ts(7053)

A: You can explicit cast the key argument within the reduce function:
Object.keys(myObj).reduce((obj, key) => (obj[key as FeatureNames].on = true, obj), myObj)


text:
Q: SwiftUI, How to publish data from view to a viewModel then to a second view? I have one view (with a Form), a viewModel, and a second view that I hope to display inputs in the Form of the first view.  I thought property wrapping birthdate with @Published in the viewModel would pull the Form input, but so far I can't get the second view to read the birthdate user selects in the Form of the first view.
Here is my code for my first view:
struct ProfileFormView: View {
@EnvironmentObject var appViewModel: AppViewModel
@State var birthdate = Date()

var body: some View {
    NavigationView {
        Form {
            Section(header: Text("Personal Information")) {
                DatePicker("Birthdate", selection: $birthdate, displayedComponents: .date)
            }
        }
    }

Here is my viewModel code:
class AppViewModel: ObservableObject {
@Published var birthdate = Date()

func calcAge(birthdate: String) -> Int {
    let dateFormater = DateFormatter()
    dateFormater.dateFormat = "MM/dd/yyyy"
    let birthdayDate = dateFormater.date(from: birthdate)
    let calendar: NSCalendar! = NSCalendar(calendarIdentifier: .gregorian)
    let now = Date()
    let calcAge = calendar.components(.year, from: birthdayDate!, to: now, options: [])
    let age = calcAge.year
    return age!

and here is my second view code:
struct UserDataView: View {
@EnvironmentObject var viewModel: AppViewModel
@StateObject var vm = AppViewModel()
var body: some View {
    VStack {
        Text("\(vm.birthdate)")

        Text("You are signed in")

        Button(action: {
            viewModel.signOut()
        }, label: {
            Text("Sign Out")
                .frame(width: 200, height: 50)
                .foregroundColor(Color.blue)
        })
    }
}

And it may not matter, but here is my contentView where I can tab between the two views:
struct ContentView: View {
@EnvironmentObject var viewModel: AppViewModel

var body: some View {
    NavigationView {
        ZStack {
            if viewModel.signedIn {
                ZStack {
                    Color.blue.ignoresSafeArea()
                        .navigationBarHidden(true)
                    TabView {
                        ProfileFormView()
                            .tabItem {
                                Image(systemName: "square.and.pencil")
                                Text("Profile")
                            }
                        UserDataView()
                            .tabItem {
                                Image(systemName: "house")
                                Text("Home")
                            }
                    }
                }
            }
            else
            {
                SignInView()
            }
        }
    }
    .onAppear {
        viewModel.signedIn = viewModel.isSignedIn
    }
}

One last note, I've got a second project that requires this functionality (view to viewmodel to view) so skipping the viewmodel and going direct from view to view will not help.
Thank you so much!!

A: Using a class AppViewModel: ObservableObject like you do is the appropriate way to "pass" the data around your app views. However, there are a few glitches in your code.
In your first view (ProfileFormView), remove @State var birthdate = Date() and use
DatePicker("Birthdate", selection: $appViewModel.birthdate, ....
Also remove @StateObject var vm = AppViewModel() in your second view (UserDataView),
you already have a @EnvironmentObject var viewModel: AppViewModel, no need for 2 of them.
Put @StateObject var vm = AppViewModel() up in your hierarchy of views,
and pass it down (as you do) using the @EnvironmentObject with
.environmentObject(vm)
Read this info to understand how to manage your data: https://developer.apple.com/documentation/swiftui/managing-model-data-in-your-app


text:
Q: Proxy object no ejecuta mi handler Estoy aprendiendo proxy y quiero interceptar el cambio a la propiedad pi para multiplicarla por 2 y que ese sea el valor final pero no he podido conseguirlo

    const obj = {pi: 31.1}
        const proxy = new Proxy(obj,{set: function(object,prop,value){
            console.log("change")
            object[prop] = value * 2
            return true
        }});

        obj["pi"] = 30.23
console.log(obj["pi"])

No me funciona, no se porque, debería ser 60.46 el valor de la propiedad pi, gracias de antemano

A: El problema se da porque estas utilizando la variable obj y no el resultado devuelto por new Proxy.
Solución:
Necesitas trabajar con el objeto devuelto por new Proxy, por ejemplo, así:

const obj = new Proxy({
  pi: 31.1
}, {
  set: function(object, prop, value) {
    object[prop] = prop == 'pi' ? value * 2 : value;
    return true;
  }
});

obj["pi"] = 30.23
console.log(obj["pi"])


text:
Q: How to force even number of pages in output document? Similar things have been asked, but I would like to know how to do in order to have my output PDF be an even-number-of-pages document. This code
\AtEndDocument{\cleardoublepage}

only makes the "even-LaTeX-page" to be the last, but in my document the last LaTeX-page (122) is 127th of the entire document. I want the "output PDF" to be even for printing reasons. Thanks

A: Here I define the extra page if needed to be totally blank.  I provide a commented \renewcommand that instead prints "Intentionally left blank" on the extra page.
Whether or not you uncomment the %\clearpage Page 2 content line, the document will contain 2 pdf pages.
\documentclass{article}
\usepackage{changepage}
\newcommand\finishonevenpage{%
  \clearpage\checkoddpage\ifoddpage\else\blankpage\fi}
\newcommand\blankpage{\clearpage\mbox{}}% EMPTY EXTRA PAGE IF NEEDED
%\renewcommand{\blankpage}{
%  \clearpage
%  \begin{center}
%    {\textsc{\rule{0em}{4.5in}Intentionally left blank.}}
%  \end{center}
%}
\begin{document}
Page 1 content
%\clearpage Page 2 content
\finishonevenpage
\end{document}

A: You don't say what class you are using but the memoir class (encompasses the book, report and article classes) has a \leavespergathering{<num>} macro.
In your case:
\documentclass{memoir}
\leavespergathering{4}
...

will work to give you 128 pages, the last being blank.
A gathering --- a publishers term --- consists of a number of leaves (so twice that of pages) and publishers like a document to have an integral number of gatherings for printing. The leavespergathering{<num>} results in a document with a multiple of 2<num> pages; if there are less than 2<num> typeset pages the extras are blank.


text:
Q: How to stop component re-render when redux store change When I dispatch an action from a child component that triggers a change in the Redux store, the whole tree gets re-render including the child component itself. How can I stop that?
For example ...
1- I'm listening for when a user clicks on a child component to expand it.
const [expanded, setExpanded] = useState(false);
 setExpanded(!expanded)}>Expand

2- Then if expanded is true I dispatch an action in useEffect ...
useEffect(() => {
    if (expanded) {
        dispatch(asyncGetItems())
    }
}, [expanded]);

3- Then inside the async dispatch it changes the redux store based on the returned data ...
export const getItems = (items: {}): AppActions => {
    return {
        type: GET_ITEMS,
        payload: items,
    };
};

export const asyncGetItems = () => {
    return async (dispatch: any, getState: () => AppState) => {
        try {
            const { data } = await apiGetItems();
            dispatch(getItems(data));
        } catch (error) {
            handleResponseError(error);
        }
    };
};

Now, when I do that and change the data in the store the component gets re-rendered because its parents get re-rendered, how to stop that?
I tried to use memo like this, but it didn't work ...
export default memo(MyComponent);

And when I don't change anything in the store and just return the data like this ...
export const asyncGetItems = () => {
    return async (dispatch: any, getState: () => AppState) => {
        try {
            const { data } = await apiGetItems();
            return data;
        } catch (error) {
            handleResponseError(error);
        }
    };
};

The component doesn't get re-rendered.


text:
Q: nested foreach loop, with php and laravel I am having problem with my nested foreach loop,  I have this code of my controller retrieving the values of two columns in separate table in my database.
What I want is to compare each values against the other table vice versa,...
table1             table2
some column1       some column2
 a                  b
 b                  b
 c                  c

My desired output would be if the values of two columns compare, if it is true then output "match" otherwise "mismatch".
Here the attempt, but it doesn't work, only the last item in both tables column are being compared. i think i am missing with my nested loops.
///snippet///
controller
$temp_answers = array();
$answers = array();

$temp_answers = Tempanswer::where('subject_id', $subject_id)
                             ->where('student_id', $student_id)
                             ->lists('temp_answer');

$answers = Question::where('subject_slug', $subject->slug)
                             ->lists('letteranswer');

foreach ($temp_answers as $temp_answer) {

    foreach ($answers as $answer) {
        if($answer == $temp_answer){
            $flag = 'match';
        }else
            $flag = 'mismatch';
    }
    echo $flag.' ';

 }

A: CMIIW.
You want to check table1 and table2 is match. So if its not match you will get message "mismatch"
Assumption 1: if each data from table1 is compared with all data in table2.
foreach ($temp_answers as $temp_answer) {

    foreach ($answers as $answer) {
        if($answer == $temp_answer){
            $flag = 'match';
        }else {
            $flag = 'mismatch';
            break;
        }
    }

    if($flag == 'mismatch'){
        break;
    }
 }

echo $flag;

Assumption 2: Each table is compared by each row. I mean row1 table1 is compared with row1 table2 and than row2 table1 is compared with row2 table2.
$flag='';
foreach ($temp_answers as $key1=>$temp_answer) {
    foreach ($answers as $key2=>$answer) {
        if($key1 == $key2){
            if($answer == $temp_answer){
                $flag = $flag.'match ';
            }else {
                $flag = $flag.'mismatch ';
            }
            break;
        }
    }
}
echo $flag;

A: Well I would have done it like this.
First give variables names that help you know what is in them
Second always use {} in if else even if there is only one line in the if or else, it makes it easier to see where things actually start and finish.
Then always use indentation as well so you can visually see where a block of code starts and finishes. Remember, you may have to come back to a piece of code weeks after writing it, so make it easy to read as it may be you that has to work out what you did.
Also when you output info about what matches or mismatches also include the data you need to see in order to tell that the matching is correct. Then if it does not do quite what you want you can easily see whats going wrong.
$temp_answers = array();
$questions = array();

$temp_answers = Tempanswer::where('subject_id', $subject_id)
                             ->where('student_id', $student_id)
                             ->lists('temp_answer');

$questions = Question::where('subject_slug', $subject->slug)
                             ->lists('letteranswer');

foreach ($temp_answers as $temp_answer) {

    foreach ($questions as $question ) {

        if($question == $temp_answer){
            echo "Question = $question TempAnswer = $temp_answer > MATCH" . PHP_EOL;
        } else {
            echo "Question = $question TempAnswer = $temp_answer > MISMATCH" . PHP_EOL;
        }
    }

 }


text:
Q: Could not hide my third child element with nth-child here is my generated html. How do I hide my second hole card?

        8
        ♣

        10
        ♥

I tried below but not working
 $("#cardContainerDealer:nth-child(2)").hide();

A: You are using nth-child wrong. Despite it's naming it matches siblings as childs of an element, so you need to select the class .card as well:

$("#cardContainerDealer .card:nth-child(2)").hide();

    8
    ♣

    10
    ♥

A: Use Jquery eq ref https://api.jquery.com/eq/

$('.card').eq(1).hide()

        8
        ♣

        10
        ♥


text:
Q: App widget layout: text line above an image, center inside bounding box I've got a very simple app widget layout: a line of text above an image.
The image should scale to fit the widget's bounding box (maintaining aspect ratio) and the text should be left-aligned with the image below it. Together they should appear in the middle of the widget's bounding box.
I can't get that to work. The best I managed was aligning to top-left of the bounding box, as follows:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical">
    <TextView
            android:id="@+id/text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
    />
    <ImageView
        android:id="@+id/image"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:layout_gravity="top"
        android:scaleType="fitStart"
    />
</LinearLayout>

I can't specify a scaleType which would align top-center and I also can't make the image view take just as much space as it needs for the image.

A: Try this, Here is an image, If you want your layout should visible as you want in landscape mode, you have to make another layout for the landscape mode or keep your view in portrait mode.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
    android:id="@+id/txt"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/img"
    android:text="Text Line"
    android:textColor="@color/black" />

<ImageView
    android:id="@+id/img"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:adjustViewBounds="true"
    android:src="@drawable/signuptop" />

</RelativeLayout>


text:
Q: Census Geocoder connection problems So I recently was able to geocode a batch of 5,000 addresses from the US Census batch geocoder using the following code:
COVID_19_Reported_Patient_Impact_and_Hospital_Capacity_by_Facility <- read_csv("~COVID-19_Reported_Patient_Impact_and_Hospital_Capacity_by_Facility.csv")

library(readr)
library(tidygeocoder)
library(sf)
library(mapview)
library(tigris)
library(tidyverse)
library(conflicted)
conflict_prefer("filter", "dplyr")

hospitaldirectory<-COVID_19_Reported_Patient_Impact_and_Hospital_Capacity_by_Facility%>%
  select(hospital_pk, state, ccn, hospital_name, address, city, zip, hospital_subtype, fips_code, is_metro_micro, geocoded_hospital_address)%>%
  group_by(hospital_pk) %>%
  filter(row_number()== 1)%>%
  ungroup%>%
  geocode(street=address, city = city, state = state, postalcode = zip, method="census", return_input =TRUE)

It worked the first time, but I accidentally erased the dataset. I tried again later on in the course of the day but now I keep on getting this error:
Error in curl::curl_fetch_memory(url, handle = handle) :
  Send failure: Connection was reset

I've rebooted the computer and tested my network with no avail. Any ideas as to how to get around this error?


text:
Q: Google chart tooltips I am using google spreadsheet to feed to my Column chart. To get the single columns to be a different color I used sort of a hack by setting values to 0 on opposite columns in the spreadsheet for each column in the chart. This gave me the the difference in color I needed for each column in the chart.  The issue I am now having is the tooltips do not work for each column and was wondering how I can implement to work correctly in my code.
google.load('visualization', '1', {packages: ['corechart']});
</script>
<script type="text/javascript">
var visualization;

function drawVisualization() {
    var query = new google.visualization.Query(
        'http://spreadsheets.google.com/tq?key=0AjlSK7_zXoNHdDhrU2xiaHVIQmR1WldYZm1yMTNkM3c&pub=1');

    // Apply query language statement.

    // Send the query with a callback function.
    query.send(handleQueryResponse);
  }

  function handleQueryResponse(response) {
    if (response.isError()) {
      alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
      return;
    }

    var data = response.getDataTable();
     // set the 3rd column to the "tooltip" role
    data.setColumnProperty(3, 'role', 'tooltip');
    visualization = new google.visualization.ColumnChart(document.getElementById('visualization'));
    visualization.draw(data, {legend: 'none', colors:['blue','red'],is3D:'True', isStacked:'true'});
  }

google.setOnLoadCallback(drawVisualization);

A: Option A:
Adjust your underlying data so that you have 4 columns instead of 3, with the same values in column 2 (after the first set of data) as you have in your current column 3 (with the tooltip). Use the setColumnProperty() on the new columns 2 and 4 as tooltip.
Option B:
Copy your tooltip column 3 in Javascript to Column 2 (after the first data set) using insertColumn(), this should have the same effect as Option A. You will have to loop through to copy over the values, or otherwise add the same data via javascript.


text:
Q: Updating a group of Django objects in one click I have a Message model with an 'unread' field set to default=True:
class Message(models.Model):
    user = models.ForeignKey(Profile, on_delete=models.CASCADE)
    sender = models.ForeignKey(Profile, on_delete=models.CASCADE)
    message = models.TextField(blank=True)
    unread = models.BooleanField(default=True)

I want to be able to select a group of these objects at once and alter their unread status on click. Each of them are currently being displayed with a checkbox alongside, wrapped inside a form:
<form action="{% url 'users:read_message' %}" method="post">
    {% csrf_token %}
    <button type="submit">Mark as read</button>

    {% for msg in messages %}
        <input type="checkbox" name="message" value="{{ msg.id }}">
        <p>{{ msg.message }}</p>
    {% endfor %}
</form>

And here is the view:
def message_unread(request):
    if request.method == 'POST':
        selected_messages = request.POST.getlist('message')
        Message.objects.filter(id__in=selected_messages).update(unread=True)
        return redirect('users:messages')
    return redirect('users:my_profile')

This is working, however I will also need a second form in order to change the status back to unread=False, and ideally a third to be able to delete them. Since HTML forbids the use of nested forms, how can I achieve this without displaying three loops of messages

A: I was able to solve the issue using three submit buttons on the form each containing the formaction attribute


text:
Q: JQuery can't call css method twice at a time? I have a codepen where I am recreating (recreating because I saw this in someone else's pen) a loading icon that looks like a newton's cradle. That codepen can be found here.
My issue is that I want the balls to change their background color to the same color as their border when they swing out and change back to transparent when they return to the center.
I thought that I could just change the color before and after I animate each ball within the moveRight and moveLeft functions, but that doesn't seem to be working for whatever reason. I have checked the syntax of the JQuery functions several times, but can't seem to find an error with how I am calling them.
At first, I believed that the issue has something to do with setting the balls to be transparent, but I have (I believe) debunked that theory. My new theory is that it is trying to call the css function twice at a time on two different elements and is just malfunctioning as a result. I'm not sure that this is true however, as the function should be terminated before it is called again, right?
Every time I call either function, I pass a parameter similar to '#1-1'. This is the id of one of the five dots, the second digit representing the number (so the first is 1-1, second 1-2, etc. The animation is working, so I would assume that there is no issue with the selectors inside of the functions.
Can someone shed some light on this issue? Is this just a codepen problem? I have been having lots of issues in the past relating to backgroundcolor on the web, both on codepen and JSFiddle, so that could be the reason. I don't think that this is the problem though because in another pen I got backgroundcolor setting to work only with JQuery.
Here is the javascript that is causing me problems:
$(document).ready(function() {
  window.setInterval(function() {
    moveRight('#1-1');
    moveRight('#1-2');
  }, 1000);
  window.setTimeout(function() {
    window.setInterval(function() {
      moveLeft('#1-3');
      moveLeft('#1-4');
      moveLeft('#1-5');
    }, 1000);
  }, 500);
});

function moveRight(id) {
  $(id).css("background-color", "#00094F");
  $(id).animate({
    marginLeft: "-=70",
    marginTop: "-=50",
  }, 250, function() {
    $(id).animate({
      marginLeft: "+=70",
      marginTop: "+=50",
    }, 250);
  });
  $(id).css("background-color", "#78FF81");
}

function moveLeft(id2) {
  $(id).css("background-color", "#00094F");
  $(id2).animate({
    marginLeft: "+=70",
    marginTop: "-=50",
  }, 250, function() {
    $(id2).animate({
      marginLeft: "-=70",
      marginTop: "+=50",
    }, 250);
  });
  $(id).css("background-color", "#78FF81");
}

EDIT: My newest issue is that when I try to change the background colors before and after each animation call, the left three dots that call moveLeft don't do anything anymore, not even animate. Something is definitely amiss here, any ideas for this too?

A: Try placing it in a animate complete function:
  //place this inside of your animate function as a property
  complete:function() {

   $(id).css("background-color", "#78FF81");

   });


text:
Q: where to connect socket in flutter apps I am facing an issue when calling multiply socket connection with different name spaces in the same screen.
What I want to achieve is online connection for both chat and notification,
in NodeJS back end, I have many socket namespaces for different propose.
In this code here is my mobile screen layout which is a page view since I had errors calling my provider in main
so I chose to call the provider's methods which connect to different sockets.
But when doing this only the last provider call works and the first one don't seem to work at all when calling them separately in different screens they woks
i want to createan socket connection for bothe name spaces in my app so i can get notification and messages when i am online
where should i call my socket connection and should i not use name spacese or may i consider to make all my socket request in only on fucketion so one calll but that make the code not so clean and create other preformanse problems..
this is where i call the tow socket functions but only one of them work
class _MobilScreenLayoutState extends State<MobilScreenLayout> {
  @override
  void didChangeDependencies() async{
    // TODO: implement didChangeDependencies

    // notifiaction
   await Provider.of<Notifications>(context, listen: false).connectAndListen();
   // chat and listen to emited messages
   await  Provider.of<Conversation>(context, listen: false).getConversations();

    super.didChangeDependencies();
  }

here is my methods that i call from defferent providers
Future<void> connectAndListen() async {
    print("connectAndListen");
    final jwt = await storage.read(key: "token");
    final userid = await storage.read(key: "id");
    var areweConnected = false;
    final IO.Socket socket = IO.io(
        'http://192.168.0.5:8080/not',
        IO.OptionBuilder()
            .setTransports(['websocket'])
            .setExtraHeaders({"token": jwt})
            .disableAutoConnect()
            .setQuery({"token": jwt})
            .setAuth({"token": jwt})
            .build());

    try {
      socket.connect();
      List res;
      socket.emit("not");
      socket.emit("allNots");
      socket.on(
          'allNots',
          (data) => {
                _notifications = jsonToNotificationModel(data, userid!),
                notifyListeners(),
              });
      socket.on(
          'not',
          (data) => {
                print("not emit ${data}"),
                for (var i in data)
                  {
                    _notifications.insert(
                      0,
                      {
                        i["id"]: NotificationModel(
                            id: i["id"],
                            leading: Icons.ac_unit as IconData,
                            userNmae: i['user']['first_name'],
                            userId: i['user']['id'],
                            message: "Whats to connect withe you",
                            date: i['createdAt'],
                            traiel: 'flolow ',
                            roll: i['user']['roll'],
                            tagline: i['user']['tagline'],
                            areWeConnecting:
                                i['user_id_Connect_resiver_user_id'])
                      },
                    ),
                  },
                notifyListeners(),
              });
      print("done withe the not socket");
    } catch (error) {
      print("error");
    }
  }
    Future<void> getConversations() async {
        var jwt = await storage.read(key: "token");
        var userid = await storage.read(key: "id");
        List<ChatModel> _chats = [];
        final IO.Socket socket = IO.io(
            'http://192.168.0.5:8080/chatRomms',
            IO.OptionBuilder()
                .setTransports(['websocket'])
                .setExtraHeaders({"token": jwt})
                .disableAutoConnect()
                .setQuery({"token": jwt})
                .setAuth({"token": jwt})
                .build());

        try {
          print("socket");
          socket.connect();
          socket.on(
              'result',
              (data) => {
                    _chatRomms = listjsonTochatRoomModel(data, int.parse(userid!)),
                  });
          socket.on("singelMessage", (data) {
            singelJsonTochatRoomModel(data, int.parse(userid!));
          });
        } catch (error) {
          print(error);
          rethrow;
        }
      }

here is my main app
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    // Provider.of<Conversation>(context, listen: false).getConversations();
    // final provider = Provider.of<Auth>(context).isAuth;
    final ThemeData theme = ThemeData(
        // primarySwatch: Colors.red
        );
    return MultiProvider(
        providers: [
          ChangeNotifierProvider(
            create: (ctx) => Idea(),
          ),
          ChangeNotifierProvider(
            create: (ctx) => User(),
          ),
          ChangeNotifierProvider(
            create: (ctx) => UserSignUpModel(),
          ),
          ChangeNotifierProvider(create: (ctx) => Auth()),
          ChangeNotifierProvider(create: (ctx) => ConnectionsProvider()),
          ChangeNotifierProvider(create: (ctx) => SocketProvider()),
          ChangeNotifierProvider(
            create: (ctx) => Notifications(),
          ),
          ChangeNotifierProvider(create: (ctx) => Industry()),
          ChangeNotifierProvider(create: (ctx) => Requiment()),
          ChangeNotifierProvider(create: (ctx) => Conversation()),
          ChangeNotifierProvider(create: (ctx) => ChatProvider()),
        ],
        child: GestureDetector(
          onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
          child: Consumer<Auth>(
            builder: (ctx, auth, _) => MaterialApp(
              debugShowCheckedModeBanner: false,
              title: 'Flutter Demo',
              theme: ThemeData(
                primarySwatch: Colors.grey,
                appBarTheme: const AppBarTheme(
                  backwardsCompatibility: false,
                  brightness: Brightness.dark,
                  systemOverlayStyle: SystemUiOverlayStyle.dark,
                ),
              ),
              home: FutureBuilder(
                future: auth.jwtOrEmpty,
                builder: (context, snapshot) {
                  if (!snapshot.hasData) return CircularProgressIndicator();
                  // orginal here is !=
                  if (snapshot.data != "") {
                    print("data ${snapshot.data}");
                    return FutureBuilder(

                      builder: (context, snapshot) {
                      return MobilScreenLayout();
                    });


text:
Q: Loosing request body on the doCatch after exception Apache Camel I'm having an issue on route configuration with Apache Camel.
For some reason, after falling into an exception, I'm loosing the ${body}, it's just simply wiping out. Is there any way to keep what I have on ${body} if my request fail?
This is the chunk of code:
.to(pricingDomainUrl + "?bridgeEndpoint=true").process(PRICING_DOMAIN_RESPONSE_PROCESSOR)
.doCatch(Exception.class)
.doTry()
.setProperty("exception", simple("true"))
.log(LoggingLevel.INFO, logger, "BODY ON TRY: ${body}")<- prints an empty body
.log(LoggingLevel.WARN, "First call failed, trying cleaning headers")
.process(PRICING_DOMAIN_REQUEST_PROCESSOR)
.doCatch(Exception.class)
.process(EXCEPTION_PROCESSOR);


text:
Q: Encrypt with AES without header I'm trying to encrypt a 16KiB block with AES.
I tried to do it with openssl, but the size grew from 16384 to 16416. Looks like openssl put a 32B header.
Is there any way to "remove" the 32B header? If it matters, my environment is Redhat 5.11.
Edit:
I tried only the command line tools of openssl:
Encryption:
openssl aes-256-cbc -in text.txt -out encrypted.txt

Decryption:
openssl aes-256-cbc -d -in encrypted.txt -out decrypted.txt

Also - I need a tool that I can use with C++.

A: No, it did not put a header. It did padding.
The AES is a block cipher with 128 bit block size that requires the length of data being enciphered to be even to the cipher block size. This padding is also used to recover the original data stream length after deciphering.
Edit:
According to @jww the openssl lib also prepends the stream with 16byte header containing a magic 8-byte string "Salted__" and and an IV, derived from the password

A: OpenSSL inserts the "Salted__" header and parameters when it has to generate a key from a user-supplied password. If you specify the key manually using the -k <key_in_hex> argument, the header will be omitted.


text:
Q: How to disable browser's back button after logout in asp.net? I want to disable browser's back button after login in asp.net. I tried to put javascript  like window.history.forward(1) function or Response.Cache function. That coding works in my web application. But back button is not disabled. How to do that?

A: We cannot disable browser back button.You can try below code, it may help:-
 <META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE">

 <META HTTP-EQUIV="EXPIRES" CONTENT="0">

 <meta http-equiv="pragma" content="no-cache">

A: This is not possible. Back history is maintained by browser, you will need to close the window.

A: Maybe you could just redirect logged in user to your desired page like a user dashboard or something when they go back to your login page? You could use sessions to determine logged in users.


text:
Q: Can I disable the 'close' button of a form using C#? How can I disable the close button of a form like in the image below? (the image below show a MessageBox window)

The MessageBox above was generated by me! I want to disable the close button of a normal form.

A: You should override the CreateParams function derived from System.Windows.Forms.Form
And change the Class Style
myCp.ClassStyle = 0x200;

A:  Closing += (s, eventArgs) =>
        {
            DialogResult = DialogResult.None; //means that dialog would continue running
        };

A: Right click on the window in question, then click Properties. Under Properties click Events. Double click on the FormClosing event.
The following code will be generated by Windows Form Designer:
private void myWindow_FormClosing(object sender, FormClosingEventArgs e)
{

}

Simply update the code to look like this (add e.Cancel = true;):
private void myWindow_FormClosing(object sender, FormClosingEventArgs e)
{
     e.Cancel = true;
}

You're done!
Alternatively, if you want to disable the close, maximize, and minimize buttons of the window:
You can right click the window in question, then click Properties. Under Properties set the ControlBox property to false.

A: If you are working with an MDI child window and disabling the close button during creation of the window is ruled out (i.e. you want to disable it at certain times during the form's life) none of the previously proposed solutions will work¹.
Instead we must use the following code:
[DllImport("user32")]
public static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);

[DllImport("user32")]
public static extern bool EnableMenuItem(IntPtr hMenu, uint itemId, uint uEnable);

public static void DisableCloseButton(this Form form)
{
    // The 1 parameter means to gray out. 0xF060 is SC_CLOSE.
    EnableMenuItem(GetSystemMenu(form.Handle, false), 0xF060, 1);
}

public static void EnableCloseButton(this Form form)
{
    // The zero parameter means to enable. 0xF060 is SC_CLOSE.
    EnableMenuItem(GetSystemMenu(form.Handle, false), 0xF060, 0);
}

¹ You can set ControlBox = false if you do not want any buttons, but that is not what the question is asking.

A: You handle the Closing event (and not the Closed event) of the Form.
And then you use e.CloseReason to decide if you really want to block it (UserClose) or not (TaskManager Close).
Also, there is small example Disabling Close Button on Forms on codeproject.


text:
Q: Getting data to automatically come up once having selected a product I am trying to make a form on access which allows me to select a product from a drop down list and then the details that go with that product such as colour and description automatically come up. Beloe is the coding which I have done on each of the texts boxes which im using.
Any ideas?
Private Sub filterDescriptionTextBox_Click()

End Sub

Private Sub filterProductTextBox_Click()

End Sub

Private Sub sourceGroup_AfterUpdate()
    ApplyDataSource
End Sub

Private Sub filterCategoryComboBox_AfterUpdate()
    PerformFilter
End Sub

Private Sub filterDescriptionTextBox_AfterUpdate()
    PerformFilter
End Sub

Private Sub filterProductTextBox_AfterUpdate()
    PerformFilter
End Sub

Private Sub productTextBox_Click()
    Shortcuts.viewProduct Me.[Colour]
End Sub

Thanks in advance, Dominique

A: What is your control field behind the Text (IE ListBox.selected.Value)?
As well is the form itself bound to a Table or View?

*

*If you have a Form bound to a Table then assign the Table field names to the appropriate controls but make them dependent to the ListBox selection.

*If its based on a View, then you will need to remove the Form's Bound source and then in VBA perform the data population to the TextBox but also handle the Updating of information from the selected ListBox and text from TextBox.


text:
Q: How can I access Windows COM objects in R v3? Some time ago, you used to be able to install the rcom package in R to use COM scripting (eg, access to external programs.)  Unfortunately, it seems to be discontinued:

Package 'rcom' was removed from the CRAN repository.
Formerly available versions can be obtained from the archive.
This depends on statconnDCOM, which nowadays restricts use, contrary
  to the CRAN policy for a package with a FOSS licence. See
  http://rcom.univie.ac.at/ and http://www.statconn.com/.

Following the archive and statconn links and installing one of the older versions in R version 3 gives the error:

"Error: package 'rcom' was built before R 3.0.0: please re-install
  it".

I am not very familiar with R, but there seems no way around this message - after all, it occurs when installing, so re-installing doesn't seem to be the answer. It appears as though rcom is simply not available for recent (3.0+) versions of R.  I have also scanned the package list, although searching for "COM" there returns over a hundred results and it is possible I missed the right one when clicking through them.
How can I use the rcom package, or use COM from within R some other way?
(Note: I am asking this question on behalf of a colleague.  I have no experience with R myself at all. Both of us, when searching for answers, could not find anything. I am sure that others are also using COM in the latest version of R, though!)

A: I looked at the rcom source code a few months ago. It seems I can get it to build and install OK on R3.0.1. Below is the procedure if it helps.

*

*Get a checkout of the latest source code of rcom. I have rcom_2.2-5.tar.gz locally. I can google something at the following address, but I have no idea of the provenance, so up to you to check it is legit. http://cran.open-source-solution.org/web/packages/rcom/index.html

*in R do install.packages('rscproxy')

*install Rtools as per the instructions on the R web site (http://cran.r-project.org/bin/windows/Rtools),

*open a Windows command prompt i.e. run "CMD"

*go to the folder containing the 'rcom' folder, and at the command prompt:
set R="c:\Program Files\R\R-3.0.1\bin\i386\R.exe"
%R% CMD check --no-manual rcom

*check it passes without too many complaints. Your call as to the --no-manual option (if you have MiKTeX installed you may remove it)
%R% CMD INSTALL rcom

should result in
    installing to c:/Rlib/rcom/libs/i386
    ** R
    ** inst
    ** preparing package for lazy loading
    ** help
    *** installing help indices
    ** building package indices
    ** testing if installed package can be loaded
    rcom requires a current version of statconnDCOM installed.
    To install statconnDCOM type
         installstatconnDCOM()
    This will download and install the current version of statconnDCOM
    You will need a working Internet connection
    because installation needs to download a file.
    * DONE (rcom)

*

*in R:
library(rcom)
installstatconnDCOM()

*I tried a comRegisterRegistry() ; comRegisterServer()
; x<-comGetObject("Excel.Application") but I get a NULL for x. I am not a user of rcom so while it all seems to compile fine; it may just not work anymore.
If you happen to need to access .NET code, a viable option (and yes I have a vested interest in mentioning it) may be the rClr package.
Hope this helps; I'd be interested to hear how you go.

A: This really should be a comment, but I don't have enough rep points yet to leave one.
I found that the above steps did not work for me, but the answer posted by Lisa Ann on this question, RExcel in R 3.0.x, did solve my problem installing rcom. Since you need rcom to run RExcel, the initial steps to install RExcel cover installing rcom on newer versions of R (such as 3.0.2).
Specifically, following the advice on statconn's wiki, http://homepage.univie.ac.at/erich.neuwirth/php/rcomwiki/doku.php?id=wiki:how_to_install

You also need to follow these instructions if you upgrade R, i.e. you install a new >release of R after you have installed RExcel.
Download the statconn DCOM server and execute the program you downloaded
  Start R as administrator (on Windows 7 you need to right-click the R icon and click the >corresponding item)
  In R, run the following commands (you must start R as administrator to do this)

install.packages(c("rscproxy","rcom"),repos="http://rcom.univie.ac.at/download",lib=.Library)
library(rcom)
comRegisterRegistry()

Now you have rcom installed, [instructions for installing RExcel follow...]

A: New versions of rcom and rscproxy (also for current versions of R) are available from a different repository. Just use http://rcom.univie.ac.at/download as the R repository to install from and you can download and install binary versions of statconn packages from there.
Hope this helps!


text:
Q: Pandas - pd.merge, add a check to make sure column doesn't exist? I have two dataframes, one main one that I work with and an auxiliary one that I want to bring info in from.
df1 (main) contains a Reporter column with various name strings.
df2 (additional information) contains the reporter name and their location.
I want the location column added as a new column in df1.
I can do the following as a one off with:
df1 = pd.merge(df1, df2, on='Reporter', how='left')

and it works.
My problem is I run a frequently updating script (checking for new rows and checking for updates on old rows) and running this line of code repeatedly adds multiple columns for each execution.

*

*The trouble with just checking if the column exists is that a new row (that contains a new reporter name) may have been added to the df that I DO want to know/update the location of.

*Am I going about this the right way? Or should I do some sort of dict lookup and conditionally map the location each time? How can I do that in pandas?

A: The problem with pd.merge is it always adds suffixes to the result.
Don't use it.
Use the equivalent DataFrame.join or DataFrame.merge on the one you're doing the LEFT JOIN on.
df1 = df1.join(df2, on='Reporter', how='left')

Or,
df1 = df1.merge(df2, on='Reporter', how='left')

The common column is only retained once in the result. Other, identical columns between the two (if you have them) are duplicated (with suffixes), however.

A: For a single series, I often prefer to map a series rather than merge or join (both also valid options, if used correctly).
Note I assume you have already applied str conversion to all columns as appropriate.
s = df2.set_index('Reporter')['Reporter Location']

df['Reporter Location'] = df['Reporter'].map(s)

In general, there is no need for converting your series to dict or for using zip on pd.Series objects. Using zip with numpy arrays can be inefficient.

A: Thanks for the info coldspeed but I went with the second option, mapping the dict.
reporter_dict = dict(zip(df2['Reporter'].astype(str),df2['Reporter Location']))
df['Reporter Location'] = df['Reporter'].astype(str).map(reporter_dict)