text:
Q: How to save time correctly so that it can be edited later I have had trouble saving time for some time. Maybe I will first describe how I would like it to work. The application saves time during several events, subtracts or adds these values in this way counting the time spent e.g. at work or on any activity. Time is saved to Firebase - for this reason it is saved as timeinmilis -> Long. I would also like to be able to edit the time, so I download the time, and change it freely using the timepicker or datapicker to choose start and end activities. After selecting the beginning and end I calculate the time and the problem is giving me time zone, using var timezone = 0L internal var zone = Calendar.getInstance (). TimeZone.getOffset (timezone) I tried to deal with this problem, to no avail. Is there a right way to write and perform mathematical operations (mainly adding and subtracting) in the language of kotlin?
i heard about jodatime but i didn't find anything about joda in kotlin .......


text:
Q: ruby on rails validation regex comma separated email addresses I am new to regex and need to parse a comma-separated input of email address extensions (everything after the @ symbol).  Example:
foo.bar,foo.bar.baz,foo-bar.baz
I know that there are no whitespaces in the string. Also. following is the regex I want to use for just a single email extension:
/[a-z\d\-.]+\.[a-z]+\z/i

How do I modify the regex in Ruby to work with multiple extensions which are comma separated?
Thanks!

A: \A(([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})[, ]?)*\Z

The above regular expression works for 0 or more number of email addresses separated b commas. You may like to chomp (",") the string before saving or using it to remove the trailing comma.

A: try
/(,{0,1}[a-zA-Z_]+[^.]*\.[a-zA-Z]{2,6})+/i
based on my test:
p 'True' if 'foo.bar,foo.bar.baz,foo-bar.baz' =~ /(,{0,1}[a-zA-Z_]+[^.]*\.[a-zA-Z]{2,6})/i
will give
True

A: You're probably better of splitting the list into components and then checking each component:
hosts  = 'foo.bar,foo.bar.baz,foo-bar.baz'
all_ok = true
hosts.split(/\s*,\s*/).each do |host|
    all_ok = false unless(host =~ /[a-z\d\-.]+\.[a-z]+\z/i)
end

That may not be a one-liner but it will probably be a lot easier to understand six months down the road (unless, of course, your regex-fu gets stronger).

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the appropriate way for a .py file to import another .py file in the same package,? I have a folder mypackage at the location /mypath/mypackage/, and it contains an __init__.py file which is empty. mypackage contains two python files: packagefile1 and packagefile2, and packagefile2 contains import packagefile1.
When I then call a python script at /myotherpath/script.py which contains import packagefile2, it correctly finds packagefile2, but I get an error :
Traceback (most recent call last):
  File "/myotherpath/script.py", line 5, in <module>
    from mypackage import packagefile2
  File "/mypath/packagefile2.py", line 16, in <module>
    import packagefile1
ModuleNotFoundError: No module named 'packagefile1'

However, I don't get this error when I call packagefile2 directly, so it must be because I am not calling the scripts in the mypackage folder.
What is the appropriate way to solve this?
I have read here that the solution is to change import packagefile1 to import .packagefile1, but then I read here that relative imports using . are outdated. So what is the appropriate way to import modules within the same package?
ps: /mypath/ is part of the pythonpath variable (when I command env | grep -i python in bash, it shows PYTHONPATH=:/mypath/).


text:
Q: Best algorithm/practice when creating a search mechanism for your database? I have been designing a database where it is very important to provide users with a good search mechanism. So I was wondering what some of the best practices are for using keywords to search over multiple database tables and return the relevent records?
Some other things I am curious about:

*

*The users location, if they provide an address

*The speed of the algorithm

Additional Information:
I am using C# and LINQ-To-SQL.

A: It depends on the situation and what you are trying to search against. I remember we implemented a search solution for a customer by creating a database view that concatenated several fields from different tables into one field and we ran our search against that view.

A: There are basically three options (in addition to using naive "LIKE" statements):

*

*Full text search, if your database allows it

*Sphinx, Lucene, and similar options

*Google/Yahoo/Bing custom search and APIs, if applicable

My own preference goes to full text search (it's quite good and highly configurable in Postgres). Many devs prefer Sphinx or Lucene -- I've never found the need to use either, but see this post for a second opinion.
For user location, some kind of GIS infrastructure (e.g. PostGIS in Postgres) is useful if you plan to extract relevant information in a timely manner (e.g. collect stats on users in a certain area/region). I'm not familiar enough with Sphinx and Lucene to know what the latter two have to offer on this front.

A: While all of the above are important the most important thing in relation to providing a good search mechanism/experience is the database (and maybe the gui) performance.
In terms of database performance you need to ensure you search columns are correctly indexed, that statistics are current, that your SQL is using current query plans and that your database has sufficient memory and a decent CPU.
In terms of search result presentation you need to ensure the results are displayed in a timely manner. No point in having the database return results in <1 second but the gui is taking 2 minutes to display them. You need to ensure the display code is optimised and maybe supports paging.

A: To get a better search, the following solutions can be implemented :

*

*Make proper indexing of the column depending upon the search
conditions. Also keep in mind that the number of indexes must be
optimum, other wise it will overburden the database.

*Define the primary keys for the column in the table.

*If the search is too frequent then try to define the full text search option at the time of creating the database.


text:
Q: java regex expression to get everything in closed brackets I would like to know if it is possible to have a java regex expression for getting everything inbetween brackets
as in [any string] and return any string
I was thinking something like [? . ]? I guess cause [? searches for one open bracket and the . means any character.

A: try this regex:
(?<=\\[).*?(?=\\])

A: Try the following regex :
(?<=\[).*(?=\])

A: No need for look-arounds. Try this:
\[([^\]]+)

This matches an opening bracket and then captures everything which is not a closing bracket, up to the next closing bracket. You can get the captured back-reference with $1


text:
Q: Libraries for Online learning I am looking for packages (either in python, R, or a standalone package) to perform online learning to predict stock data.
I have found and read about Vowpal Wabbit (https://github.com/JohnLangford/vowpal_wabbit/wiki),
which seems to be quite promising but I am wondering if there are any other packages out there.
Thanks in advance.

A: If you are willing to try Julia (or pyjulia for calling Julia from Python), there is OnlineStats.jl.  The StatLearn type for statistical learning may be of use to you.

A: Late answer, but...
Liblinear (standalone)
The authors recently released a new, faster version. A multi-threaded implementation is also available. LIBLINEAR is a linear classifier for data with millions of instances and features. It supports :

*

*L2-regularized classifiers

*L2-loss linear SVM, L1-loss linear SVM, and logistic regression (LR)

*L1-regularized classifiers

*L2-loss linear SVM and logistic regression (LR)

*L2-regularized support vector regression

*L2-loss linear SVR and L1-loss linear SVR.

Sofia (R, standalone)
Google released Sofia, which is also callable from R through RSofia. It performs regressions, classification and ranking through:

*

*Pegasos SVM

*Stochastic Gradient Descent (SGD)

*SVM Passive-Aggressive

*Perceptron Perceptron with Margins

*ROMMA

*Logistic Regression (with Pegasos Projection)

There is an implementation of online kmeans, which is available in the source code, but not in the R package.
Online random forests (Python, standalone)
Some implementation of online random forests are available on git. To mention a few : here is a C standalone implementation and here is a python implementation. Note that the theory is at its early stages, new implementations may come latter.

A: The Weka library (implemented in Java) has support for online learning as well. The term Weka uses is "updateable classifier", that is, an algorithm that can learn from a single training instance, and it doesn't need the entire dataset to be available in memory.
Here's the list of classifiers supported, that are capable of online learning.


text:
Q: flutter gridview horizontal how to fill height I am imitating telegram desktop app.
First time, I tried to put listview in row. But I failed.
So I use GridView.count with crossAxisCount: 2.
I want to fill empty area under contents.
https://github.com/kangsudal/kkunglegram/issues/1

https://github.com/kangsudal/kkunglegram/blob/main/lib/main.dart
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.yellow,
      ),
      home: InitScreen(),
    );
  }
}

class InitScreen extends StatelessWidget {
  const InitScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (BuildContext context, BoxConstraints constraints) {
        final width = constraints.maxWidth;
        final height = constraints.maxHeight;
        final ratio = width / height;
        print(
          "width: $width\nheight: $height\naspect ratio: $ratio",
        );
        return Scaffold(
          body: ratio >= 1 ? const ChatListWithRoom() : const ChatList(),
        );
      },
    );
  }
}

class ChatList extends StatelessWidget {
  const ChatList({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ListView.builder(itemBuilder: (context, index) {
      return ListTile(
        leading: CircleAvatar(),
        title: Text("대화상대명"),
        subtitle: Text("최신메세지"),
        trailing: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.end,
          children: const [
            Text(
              "최근메세지 날짜or시간",
              style: TextStyle(
                // fontSize: 12,
                color: Colors.grey,
              ),
            ),
            CircleAvatar(
              maxRadius: 10,
              child: FittedBox(
                fit: BoxFit.scaleDown,
                child: Text("쌓여있는메세지개수"),
              ),
            ),
          ],
        ),
      );
    });
  }
}

class ChatListWithRoom extends StatelessWidget {
  const ChatListWithRoom({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GridView.count(
      crossAxisCount: 2,
      children: [
        ChatList(),
        Container(
          color: Colors.blue,
          child: Center(child: Text("대화방을 선택해주세요")),
        )
      ],
    );
  }
}

A: Instead of using a gridview which has a child aspect ratio of 1 as default (So you can a square layout for children) you can return a row with 2 expanded widgets (for equal size) and add chat list and image as children of expanded widgets as shown below.

class ChatListWithRoom extends StatelessWidget {
  const ChatListWithRoom({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Row(

      children: [
       Expanded(
        child: ChatList(),
       ),
       Expanded(
        child: Container(
          color: Colors.blue,
          child: Center(child: Text("대화방을 선택해주세요")),
        )
       )
      ],
    );
  }
}

A: The GridView is a bit tricky to work with - You'd need to play with GridView.childAspectRatio to make it fill the entire space. The solution is to replace the GridView with a Row and use Expanded on both children so they share the same amount of space horizontally.
Check out the fixed ChatListWithRoom:

And here's the code:
class ChatListWithRoom extends StatelessWidget {
  const ChatListWithRoom({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Expanded(child: ChatList()),
        Expanded(
          child: Container(
            color: Colors.blue,
            child: Center(child: Text("대화방을 선택해주세요")),
          ),
        ),
      ],
    );
  }
}


text:
Q: Horizontal long text like newspaper Lets say I've got long lorem ipsum in div. Div width is 30% and there is so much text that page need to scroll up/down. I want to make it scrolling horizontally: when there is more text than can fit in div I want it to continue in next column next to the first one, equally like in almost every newspaper etc.
Is it possible?

A: Use CSS3 multi-column layouts
Check Demo Page here
You can now use any of these CSS3 multi-column properties in your stylesheet:
column-count: 3;
column-width: 300px;
column-gap:10px;
column-rule: 1px solid #999;

A: you could use : overflow-x: scroll


text:
Q: hql equivalent of case when sql I have a sql query which says
select case when col='city' then (select name from Table) end AliasName
    from SomeOtherTable

I am unable to use subqueries in hql case-when-then expression. Is there any other method I can accomplish the same

A: This is a workaround rather a direct answer; create a view in database and a new class in your application. now you are free of your hql totally.
of course this link is about another question but somehow relates to yours and talks about features that are not supported in HQL or are hard to implement:
Hibernate Union alternatives


text:
Q: Nodejs process locks up reading from blocking FUSE file I have a nodejs webserver which reads files and serves the content. Some of the files are FUSE virtual files which may block reads for long periods of time while their backing services wait for data to provide.
It seems that if 5 of these read requests pile up, the process will no longer read from any files. Also, I'm not sure how to terminate these pending reads if necessary.
Is this a limitation of nodejs or is the FUSE filesystem behaving in a manner inconsistent with FUSE's expectations?

A: According to this NodeJS issue report #7256, if a thread in the underlying libuv I/O thread pool attempts to read from a file that blocks, the thread will hang until the device or process backing the target file yields control to the thread, ie the read call returns.
Furthermore, NodeJS v0.10 on *nix systems relies on a fixed size thread pool with a default size of 4, according to this libuv issue report #649. This explains why the system appeared to lock-up after ~5 read attempts.
The situation can be worked around in several ways:

*

*Increase the size of underlying libuv thread pool using the UV_THREADPOOL_SIZE environment variable. This glosses over the issue by simply allowing more opportunities to read before the Node process begins to suffer.

*Open the blocking files using the recently exported O_NONBLOCK flag. This change is a part of the Node 0.10 code stream and I have confirmed that it works as expected (having compiled Node from source with _XOPEN_SOURCE set) but is not in the latest 0.10.28 release at the time of this comment. It seems reasonable to believe that the nonblock functionality will be a part of the 0.10.29 release. The device backing the file must also respect the O_NONBLOCK flag for this to work properly.
Some code to demonstrate option #2
var constants = process.binding('constants');
fs.open('/path/to/file', constants.O_NONBLOCK, function(err,fd){
    fs.read(fd, buf, 0, 10, null, function(err, bytesRead, buffer){
        // Read should return immediately
        if(err.code === 'EAGAIN'){
            // Not ready to read, try again later
        } else {
            // Do something
        }
    });
});

A: are you using readFileSync to read from these files? If so, thats your problem right there.
Node should be able to wait for a large number of resources while still serving requests. Show us your code to read from the files.


text:
Q: Cannot install into target mounted with noexec or nodev while doing qemu-deboot strapping I'm trying to install the armel version of Ubuntu with qemu-deboot-strap on my desktop X64 system,but I've found this error :
$ mkdir precise

$ sudo qemu-debootstrap --arch=armel precise ./precise/

I: Running command:
 $ debootstrap --arch armel --foreign precise ./precise/
 /usr/sbin/debootstrap: 1280: /usr/sbin/debootstrap: cannot create  /media/ziomario/Nexus-10/Images/313/precise/test-dev-null: Permission denied

E: Cannot install into target '/media/ziomario/Nexus-10/Images/313/precise' mounted with noexec or nodev

do you know how to fix it ? my system is like this :
Linux ziomario-Macmini 3.11.0-15-generic #23-Ubuntu SMP Mon Dec 9 18:17:04 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux

and this is the content of the /etc/fstab file :
<file system> <mount point>   <type>  <options>       <dump>  <pass>
proc            /proc           proc    nodev,noexec,nosuid 0       0

/ was on /dev/sda5 during installation
UUID=c703f96e-42fd-4734-b622-15ba1dd5fc21 /               ext4    errors=remount-ro 0       1

swap was on /dev/sda6 during installation
UUID=1c2b872f-3be3-4c6c-b021-6cec3e8b77e2 none            swap    sw              0       0

Thanks.

A: Remounting with exec and dev is the solution. If your filesystem is encrypted, you also need to pass -i to mount.
 sudo mount -i -o remount,exec,dev /home/user

Where in my case /home/user/ is my encrypted home directory. After that debootstrap had no issues any more.
I found this answer here on Super User and it worked for me.


text:
Q: loop through dataframe columns to do simple linear regression? import pandas as pd
import numpy as np

from sklearn.linear_model import LinearRegression

df = pd.read_excel("Book1.xlsx")

for column in df:

    X = df["Row Labels"]

    Y = df[column]
    y1 =Y.values.reshape(-1,1)
    x1 =X.values.reshape(-1,1)
    regressor = LinearRegression()
    regressor.fit(x1, y1)
    y_new = []
    y_i = []
    for i in range(12,24):
        y_new.append(regressor.predict([[i]]))
        y_i.append(i)

    df2 = pd.DataFrame({'column':y_new})

i write this code to loop through the dataframe columns to do simple linear regression and put all the predicted value in dataframe. but it is predicting only the last columns value.

A: df2 = pd.DataFrame({'column':y_new}) creates a column named 'column' verbatim (not the name saved in the variable column. Moreover, df2 is recreated in every iteration, each iteration it only saves the last y_new.
I think what you want is to create a new column in df2 in each iteration:
import pandas as pd
import numpy as np

from sklearn.linear_model import LinearRegression

df = pd.read_excel("Book1.xlsx")

df2 = pd.DataFrame()

for column in df:

    X = df["Row Labels"]

    Y = df[column]
    y1 =Y.values.reshape(-1,1)
    x1 =X.values.reshape(-1,1)
    regressor = LinearRegression()
    regressor.fit(x1, y1)
    y_new = []
    y_i = []
    for i in range(12,24):
        y_new.append(regressor.predict([[i]]))
        y_i.append(i)

    df2[column] = y_new


text:
Q: Soldering iron struggling to solder to ground plane I've got a 48W Soldering iron which I'm using on PCB's, which I'm designing with Eagle and getting made up for me. I'm a hobbyist, so needless to say, I may well have the wrong tool for the job here.
My designs use surface mount components and my soldering iron is really struggling to melt the solder when I'm trying to solder to a surface mount pad which is connected to the ground plane.
Is 48W a bit on the small side? Should I replace the iron with a more powerful one or is that not the problem? I'd be very grateful for any help.

A: You just need to heat the pad for a longer time. Use big flat tip on your soldering iron to maximize heat flow.  If you still cannot solder you may try placing a hot plate under your board to preheat it.
And next time remember to use thermal reliefs:

A: I would recommend using a heat gun or hair dryer to raise the temp on the entire board. Then after 30 secs or so, reattempt to solder the component.
If that fails, buy a flux pen. Apply some flux to the pad to refresh the 'old' solder.
Especially useful for re-work. https://www.sparkfun.com/products/8967

A: Soldering iron wattage plays a role, but even more important is thermal recovery and capacity. For example, your iron may be at the proper temperature, but as soon as you transfer heat into a large wire or pad, that heat conducts away from the iron and it now must regenerate it. If the iron has a low thermal capacity, it might require that you hold the iron to the pin or pad in question for a long time, which could cause damage to components or pads.
I strongly recommend that you get an iron with good thermal recovery and temperature control. (See other threads for recommendations.)
As @Szymon mentioned, one way to reduce the heat requirement on the PCB is with thermal relief pads. But if you have a component that has a tab specifically designed to solder to a large copper pour as heat-sink, you will run into the issue anyway.


text:
Q: SQL query / SQL Reporting Services Been rattling my brain for a while and I could not get pass how to do the SQL query that will show the relationship/connections between my two tables.
I'm working on an IT equipment inventory program. I have two tables;
SELECT serial_number, model, ship_dat, status FROM items_list
SELECT item_serial, connected-to_serial FROM connections
All items like desktops, laptops, monitors, etc are on the items_list table. To track down the relationship/connections of the items, I created the connections table. IE, Monitor with serial_number=Screen#1 is connected to a Desktop with serial_number=Serial#1. It works ok with my Window Form application because I
used a datagridview control to list all devices simple SQL query.
However, when trying to show the relationship/connection on SQL Reports I've ran out of ideas how to do it. I'm aiming to get the report look like below or something along the lines. I just need to show the connections between the items.

Thank you

A: You should be able to do this with a table in SSRS if that is what you are using.  The query you would need to drive the table of all related items would be:
SELECT item_serial, connected-to_serial, mainItem.*, connectedItem.*
FROM connections
    INNER JOIN items_list mainItem ON connections.item_serial = items_list.serial_number
    INNER JOIN items_list connectedItem ON connections.connected-to_serial = connectedItem.serial_number

You can of course tailor the SELECT statement to your needs, mainItem.* and connectedItem.* will not give you the most descriptive column names.  Using column aliases (found under column_alias here) you can give a more descriptive name to each column.
From here you should be able to use a table and create a row group on the main item (either name or serial number) to get the type of look you are looking to achieve here.  I believe the Report Wizard actually has most of the functionality you are looking for and should handle the bulk of this.  You may have to move some of the cells around to get the look you are going for though.


text:
Q: how to write my own program to login to vpn service I want to automate the following terminal commands into a single clickable or executable or something that involves less entries on my behalf. I use the following to login to my vpn service from terminal. what can i do with bash or script or something else to make a single file that carries out all of the entries below in one shot a template would be amazing if anyone could please help me with this i am new to linux and still getting my head around most things linux but am never going back to windows
cd Documents/vpn
sudo openvpn --config ipvanish-AU-Sydney-syd-a01.ovpn
password for user
Enter Auth Username- blabla@hotmail.com
Enter Auth Password: 123456789


text:
Q: How do I tar ball a directory hierarchy with soft links in Linux? How do I tar ball/compress a directory hierarchy with soft links in Linux?

A: GNU tar normally includes symlinks in the tarball it generates. If you want it to include the file the symlink points to instead then pass it -h/--dereference when creating the tarball.

A: When used with standard arguments tar xvf,
the soft links are saved in the tar archive as soft-links.
Then there are two cases:

*

*If your symlink is a full pathname, it might be broken when untarred.

*If your symlink is a relative pathname, under the folder you are tarring,
it will work fine when extracted.

If you want to tar the file and not the symlink, you can use the -h / --dereference arguments.


text:
Q: Issues with compiling multiple files So I'm trying to write a bit of code to work with sudoku puzzles, and I keep getting errors when I try to compile, and each time i compile it deletes the driver.
heres the code for the driver:
/*
 * Jared C
 * C++ Project
 */
#include <iostream>
#include "SudokuBoard.h"

using namespace std;

int main()
{
    SudokuBoard board("sudoku.txt");
    board.printBoard();
}

And here's the header file
/*
 * Jared C
 * SudokuBoard.h
 */

#ifndef __SUDOKUBOARD_H_INCLUDED__
#define __SUDOKUBOARD_H_INCLUDED__

#include <iostream>
#include <string>

class SudokuBoard
{
  private:
    int content[9][9];

  public:
    SudokuBoard(std::string filename);
    void printBoard();
    int getNumAt(int, int);
    void setNumAt(int, int, int);
};

#endif

And finally the Sudoku Board.cpp
/*
 * Jared C
 * SudokuBoard.cpp
 */

#include <iostream>
#include <fstream>
#include "stdlib.h"
#include "SudokuBoard.h"

using namespace std;

SudokuBoard::SudokuBoard(string filename)
{
    string output;
    string line;
    int count = 0;
    ifstream file;
    file.open(filename.c_str());
    if (file.is_open())
    {
        while (getline (file, line))
        {
            output += line;
        }
        file.close();
    }
    else cout<< "unable to open file" << endl;
    for(int y = 0; y < 9; y++)
    {
        for(int x = 0; x < 9; x++)
        {
            content[x][y] = atoi(output.substr(count,1).c_str());
            count ++;
        }
    }
}

void SudokuBoard::printBoard()
{
    string output = "\n";

    for(int y = 0; y < 9; y++)
    {
        if(y%3==0)
        {
            output += '\n';
        }
        for(int x = 0; x < 9; x++)
        {
            if(x%3==0)
            {
                output += " ";
            }
            output += content[x][y];
            output += "\n";
        }
    }
    cout<<output<<endl;
}

int SudokuBoard::getNumAt(int x, int y)
{
    return content[x][y];
}

void SudokuBoard::setNumAt(int x, int y, int value)
{
    content[x][y] = value;
}

When i call gcc -c SudokuBoard.cpp I get the SudokuBoard.o file just fine, but when I then call 'gcc -o Driver.cpp SudokuBoard.o' I get a huge wall of error messages, heres a sample of them:
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 0 has invalid symbol index 11

SudokuBoard.cpp:(.text+0x34): undefined reference to `std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string()'
SudokuBoard.cpp:(.text+0x43): undefined reference to `std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string()'

And it deletes Driver.cpp Any idea what I'm doing wrong?

A: Your command line is incorrect:
gcc -o Driver.cpp SudokuBoard.o

Instructs gcc to link the object file SudokuBoard.o as an executable file named Driver.cpp.  No surprise that it first erases the destination file.
Furthermore, you do not specify the runtime library to link with and gcc does not default to C++: this explains the error message.
You should instead write:
g++ -o Sudoku Driver.o SudokuBoard.o

A: Use g++ to compile C++ code, not the common C-oriented gcc.
g++ invokes gcc for compilation and linking with the right options for C++.
In short, it's a good idea to use a C++ compiler for C++ source code, a Fortran compiler for Fortran source code, and so on.

Also, for the issue of "And it deletes Driver.cpp", simply don't specify that source file as an output file.

A: The compiler is telling you it can't find the implementation for std::basic_string<...>.
You need to tell the compiler how to find the compiled code for std::basic_string<...>. Much how with your own code, if you tried to build an executable out of just Driver.cpp the compiler would complain about missing SudokuBoard references until you told it about SudokuBoard.o.
In this case you need to tell the compiler about the C++ standard library. This library are usually shipped with your distribution. On Windows in the form of dll files, on OS X dylib files and on Linux so files. Conceptually they are similar, many bags of .o files all together. Either way, you tell the linker to link to the C++ standard library.
gcc calls the C++ standard library libstdc++, so your command would be something like: gcc -o Driver Driver.cpp SudokuBoard.o -lstdc++.

A: The problem is that the -o option with gcc is used for specifying the output file. If you write
gcc -o Driver.cpp SudokuBoard.o

you tell the compiler to create an executable file named Driver.cpp out of the object file SudokuBoard.o. But as SudokuBoard.o has no main method, this will fail, therefore the error messages.
Try
gcc -c SudokuBoard.cpp
gcc -c Driver.cpp
gcc -o Sudoku SudokuBoard.o Driver.o

instead.


text:
Q: Get all IP addresses in a range in PHP I have 900+ IP address ranges from the Microsoft Azure datacentres (http://www.microsoft.com/en-us/download/confirmation.aspx?id=41653) and I want to find out if an IP address is coming from one of these addresses. I've converted it into a single list which could be stored in a text file.
So: is it more costly to loop through each address and use ip2long() such as point 3 here (https://mebsd.com/coding-snipits/php-ipcalc-coding-subnets-ip-addresses.html) OR is it better to convert all IP addresses in the range, store them in a database and then look them up? If the latter, how does one achieve this (i.e. convert a range to all IP addresses within it)?
The key for me is that it must be fast as we'll be checking this fairly often.
Example IP addresses/ranges:
40.112.124.0/24
65.52.128.0/19
94.245.97.0/24
104.47.169.0/24
104.214.240.0/24
137.116.192.0/19
157.55.8.96/27
157.55.8.128/27
157.55.8.160/28
168.63.0.0/19

A: Wow, there's almost 1000 IP ranges in the list!  To optimize verifying a single IP address is in one of the IP ranges, you definitely should do some pre-processing of the IP range list.  Creating a database is one way.  I'd look at SQLite as it is a super-fast local file format that can be faster for read-only tasks like this than sending a query to another process (or machine) running a database.
Create a table with columns "range_start" and "range_end" and indexes on these columns.  For each IP address range, insert one row with the start and end of the range.  You'll have less than 1000 rows when done.  Now, to test an IP address ...
SELECT * FROM IP_RANGES WHERE $testIP>=range_start AND $testIP<=range_end

(modify this SQL statement to match how you're calling the database, preferably with PDO, and preferably in an SQL-injection safe way).
UPDATE: Sorry, missed the comments above while I was typing my answer.
@Ukuser32, yes, use ip2long to convert dotted decimal to long ints (much easier to work with; store long ints in the database).  To get the end of the range, look at the 2nd part of the CIDR.  It is the number (N) of bits, starting from the left, that are fixed within the range.  That means 32-N is the number of variable bits.  Which means there are 2**(32-N) ips in the range.  Which means $range_end can be calculated ...
list($range_start, $range_end) = cidr2range('40.112.124.0/24');
echo "Start: $range_start, end: $range_end\n";

function cidr2range($cidr) {
    $cidr = explode('/', $cidr);
    $range_start = ip2long($cidr[0]);
    $range_end = $range_start + pow(2, 32-intval($cidr[1])) - 1;
    return [$range_start, $range_end];
}


text:
Q: Ошибка установки модуля canvas | Nodejs Пытаюсь установить canvas через npm. Первый раз ругался на то что нет  питона 2.7
Установил питон, и конфиг. Пытаюсь установить заного но тут я уже не понял что не так. Помогите кто может см скрин ниже)

A: У вас не установлен GTK2. Попробуйте установить его вручную (шаг 2).
Ручная установка: https://github.com/Automattic/node-canvas/wiki/Installation:-Windows#2-installing-gtk-2


text:
Q: react-table: How to insert a single, empty, editable row below the header? There is a table of items. For adding new ones, a user is presented with a single, empty row below the headers. They can fill out the fields and press the button in the ID field to submit this pseudo-form to the server.
Creating an completely empty row was the easy part (just prepend an empty object to data). This example revolves around editing all rows, while I only need the very first one—the one below the headers but before the rows with actual data—to be editable.
What would be my steps to achieve this?


text:
Q: Launching debugger in windows service I'm having problems with the Debugger.Launch() function. In my windows service I'm trying to debug a job that it has to do but for some reason the JIT function opens a new instance of VS (which is ok) but for some reason it's not hitting the Debugger.Launch() line but does execute the next line.
    public override void DoJob()
    {
        Debugger.Launch(); //---> doenst stop here
        Debug.WriteLine("Job started"); //-----> but writes this
    }

I've tried numerous thing as in resetting VS completely , import settings from a VS where it works , rebooting , restarting VS, clean and rebuild (i think 6000 times about now), deleting all bin folder and obj folders, etc.
Anyone has a clue why I can't debug but my Debug.WriteLine works ?

A: use
Debugger.Launch();
Debugger.Break();

that should do it


text:
Q: undefined local variable or method `correspondent_loans' for #I am using rails 4 & ruby 2.0.0.
when I hit rake db:migrate I get the error.  It points to the add_index line having an issue.
 ==  CreateCorrespondentLoans: migrating ======================================
-- create_table(:correspondent_loans)
-> 0.0036s
-- correspondent_loans()
rake aborted!
 StandardError: An error has occurred, this and all later migrations canceled:

 undefined local variable or method `correspondent_loans' for #<CreateCorrespondentLoans:

Here's the code
    class CreateCorrespondentLoans < ActiveRecord::Migration
 def change
 create_table :correspondent_loans do |t|
  t.string :correspondent
  t.date :purchase_date
  t.decimal :loan_amount, precision: 15, scale: 2
  t.string :curr_status
  t.string :instrument_name
  t.string :loan_id, null: false

  t.timestamps
end

add_index correspondent_loans, loan_id, name: "index_correspondent_loans_loan_id", unique: true, using: :btree
  end
end

A: class CreateCorrespondentLoans < ActiveRecord::Migration
    def change
        create_table :correspondent_loans do |t|
            t.string :correspondent
            t.date :purchase_date
            t.decimal :loan_amount, precision: 15, scale: 2
            t.string :curr_status
            t.string :instrument_name
            t.string :loan_id, null: false
            t.timestamps
    end
    add_index :correspondent_loans, :loan_id, name: "index_correspondent_loans_loan_id", unique: true, using: :btree
    end
end

correspondent_loans and load_id should be a symbol.


text:
Q: Splitting a string of strings in VBA I'm importing data into MS Word from a CSV. My issue comes when I try to split the data using the built-in split() function. It ought to be straightforward, but when I try to split it, I get a "Type mismatch" error. This is my first line of text as appears in the immediate window:
"Acct","SSN","Name","Last name","Phone1","Phone2","Address","City","State","Ph home","Ph work","Ph mobile","Ph other","Email","Notes","Zip"

When I hover over the variable during debug, however, I think the entire line is treated as a string:
""Acct","SSN","Name","Last name","Phone1","Phone2","Address","City","State","Ph home","Ph work","Ph mobile","Ph other","Email","Notes","Zip""

I'm assuming that upon import, each element of the line is treated as a string, and then the line itself is turned into one giant string? I'm really not sure. For now, all I want to do is split the line in two, and check the first item against a predetermined variable. I haven't made use of this function yet, and I'm not quite savvy with VBA on Word yet.
In short, how can I treat this line as a data type that I can interact with enough to split it into its elements? I think it's all being treated as one element, thus giving me issues.
    Private Function importCSV_(x)

    Dim filenum As Integer
    Dim arrLines() As String
    Dim arrSplit As Variant

    Dim textline As String
    Dim lines

filenum = FreeFile()
Open "\\...\studentData.csv" For Input As #filenum

Do Until EOF(filenum)
    Line Input #filenum, textline
    lines = lines + 1

        Debug.Print textline
        Debug.Print split(textline, ",", 2) '<--- ERROR APPEARS HERE

        arrSplit = split(textline, ",", 2)

    ReDim Preserve arrLines(lines)
        arrLines(lines) = arrSplit

    If checkForFour_(arrSplit(0)) = True Then
            arrSplit(UBound(arrLines)) = split(arrLines(lines), ",")
        Else
            arrSplit(UBound(arrLines) - 1) = split(arrLines(lines) - 1) & "," & split(arrLines(lines), ",")
        End If

Loop

Debug.Print UBound(arrLines)
Debug.Print UBound(arrSplit)

End Function

The checkForFour_ function is a private function that just checks the formatting of data input. I'm still learning programming and by myself for that matter, so I'm constantly making my job easier, thereby creating some garbage code.

A: Slight syntax error:
Debug.Print split(textline, ",")(2)

That should do it for you. The element comes in brackets after the array.


text:
Q: Does excision imply that these inclusions are isomorphisms in homology? In exercise $4$, page 230 of Bredon, he asks for a proof of the Mayer-Vietoris sequence using a commutative braid diagram which substitutes some terms by others using excision. I've solved the exercise assuming the validity of the diagram, but it is not clear to me why the excision step is true.
The context is the following. We have $X=\text{int}(A)\cup \text{int}(B)$ (no assumption is made over $A,B$). He then proceeds to say that the inclusions
$$(A,A \cap B) \hookrightarrow (A \cup B, B)$$
and
$$(B, A \cap B) \hookrightarrow (A \cup B, A)$$
provide isomorphisms via excision. But the excision axiom  states that we must have the following situation:

$U \subset K$, $U$ open in $X$ such that $\overline{U} \subset \text{int}(K).$

But when we excise in the previous situation, we are eliminating (for instance, in the first example) the set $B-A$, which is not even necessarily open.
Therefore, my question is: Can we really use excision, as stated, in this situation? If so, how?
EDIT: As pointed out in the comments, excision holds in less restrictive situations in singular homology. But the point of this exercise is to prove that "Therefore, the Mayer-Vietoris sequence follows from the axioms alone" (in Bredon's words). And in the axioms for homology, he states clearly:

"Given the pair $(X,A)$ and an open set $ U \subset X$ such that $\overline{U} \subset \text{int}(A)$ (...)"

A: The excision axiom in its general form (each $U$ such that $\overline{U} \subset int(A)$ can be excised) is equivalent to the following statement:
If $X=\text{int}(A)\cup \text{int}(B)$, then the inclusion
$$j : (A,A \cap B) \hookrightarrow (A \cup B, B) = (X,B)$$
induces isomorphisms in homology.
This is an easy excercise. See also for example Proposition 7.2 in
Switzer, Robert M. Algebraic topology-homotopy and homology. Springer, 2017.
This shows that under the assumption in Bredon's exercise (excision axiom for open sets) you cannot prove that $j$ induces isomorphisms in homology.
Added:
As Cave Johnson pointed out in his comment, my above claim that you cannot prove that $j$ induces isomorphisms in homology is somewhat courageous. In fact, this claim means that the excision axiom for open sets is strictly weaker than the general excision axiom.
Let us look to the classic
Eilenberg, Samuel, and Norman Steenrod. Foundations of algebraic topology
from 1952. In Chapter I the axioms of a homology theory are introduced. The excison axiom (Axiom 6) occurs in the "open" variant. It is shown that it is equivalent to
Axiom 6'. Let $X_1$ and $X_2$ be subsets of a space $X$ such that $X_1$ is
closed and $X = int(X_1) \cup int(X_2)$ . If $i: (X_1,X_1 \cap X_2) \to (X_1  \cup X_2,X_2)$ is admissible, then it induces isomorphisms $i_\ast : H_q (X_1,X_1 \cap X_2) \approx H_q(X_l \cup X_2,X_2)$ for each $q$.
Here, being admissible means that both pairs of spaces belong to the admissible category $\mathfrak{A}$ on which the homology theory is defined (Eilenberg and Steenrod do not restrict to the category $\mathfrak{T}^2$ of all pairs of topological spaces).
In Chapter VII Theorem 9.1 they show that singular homology theory satisfies the "general" excision axiom for arbitrary $U$ and close with the following remark:
It should be pointed out that the excision axiom that has been
obtained for the singular theories is stronger than that required in I,3,
namely, the assumption that $U$ be an open subset of $X$ was not made.
A discussion about various variants of excision can be found in Chapter X Section 5. The variants considered by us occur as (E) and (E$_2$).
I do not know whether they are equivalent on $\mathfrak{T}^2$, but I doubt it.
My observation is that in the literature one most frequently finds the excision axiom in its stronger form, but it seems to depend on the taste of the author. For practical applications it doesn't make much difference anyway.


text:
Q: How to center jquery Dialog box in IE compatibility mode? I created a jquery dialog box which works fine in IE when not in compatibility mode.  However, my company requires IE's compatibility mode usage for some legacy code.  Below is what I have thus far.  Any ideas on how I can change it so that it will display in the center while using iE compatibility?
var originalColor;

function Form2958MessageBox(isValid) {
    var target = $(this);
    if (isValid) {
        $("#Form2958DataGridSuccess").dialog({
            position: { my: "center", at: "center"},
            title: "Successful Submission!",
            modal: true,
            buttons: {
                "Close": function () {
                    $(this).dialog("destroy");
                }
            }
        });
    }
    else {
        $("#Form2958DataGridFailure").dialog({
            position: { my: "center", at: "center", of: target},
            title: "Submission Errors Found",
            modal: true,
            buttons: {
                "Close": function () {
                    $(".ui-dialog-title").css("color", originalColor);
                    $(this).dialog("destroy");
                }
            },
            create: function (e, u) {
                originalColor = $(".ui-dialog-title").css("color");
                $(".ui-dialog-title").css("color", "red");
            }
        });
    }
}

A: IE Compatibility mode (IE7 emulation) emulates IE7 and lower and does not recognize the auto rule for the css margin property.
you can add an align attribute to the div to allow it to gracefully fallback.
<div align="center" style="margin:0 auto;text-align:left;vertical-align:top">
you may have to specify the text alignment rules also (as above);
Your page will probably not validate at validator.w3.org, but you can safely ignore the warning/error.
or
You can add the x-ua IE=Edge meta to your page to force any IE7 browsers or any users who still may be using IE8 and 'display all sites in compatibility view' to force IE8+ rendering and css 2.1 compliance. Use the x-ua meta if your site is an intranet site and you have enforced 'display intranet sites in compatibility view'.
IE7 emulation also doesn't support static positioning.....your div overlay should be positioned absolutely or relative; the workaround for static positioning in IE7 emulation is to use the MSIE calc rule on a .static class.
Regards.


text:
Q: Django - Logging - How to get the class name when running function GET inside it? So I tried to create a logging for my code:
views.py
class name_of_API(generics.GenericAPIView):
    @my_logging
    @swagger_auto_schema
    def get(self, request):
        **running something
        return ...

my_logging.py
def func_detail(func):
    @wraps(func)
    def func_wrapper(request, *args, **kwargs):
        ex = None
        try:

            response = func(request, *args, **kwargs)
            log = logging.getLogger('main')
            log.info(str(func.__class__.__name__)+ ' Called success')
            print(func.__class__.__name__)
            return response
        except:
            log = logging.getLogger('internal')
            ex = Exception
            ex_type, ex_value, ex_traceback = sys.exc_info()
            log.debug(ex_type(ex_value).with_traceback(ex_traceback))
            raise  ex_type(ex_value).with_traceback(ex_traceback)
    return func_wrapper

format in settings.py
'format': '%(asctime)s.%(msecs)03d|%(levelname)s|%(process)d:%(thread)d|%(filename)s:%(lineno)d|%(module)s.%(funcName)s|%(message)s'

info.log:

2020-12-21 10:30:04.845|INFO|12560:11868|logger.py:11|logger.func_wrapper| function Called success

The problem here:
This row below
func.__class__.__name__

return function instead of name_of_API


text:
Q: Fade-In after timed visibility through Javascript using CSS or JS I have an image that disappears (via javascript) and then fades out (via CSS) on my page, and then once this happens I have a div with text that appears once the image disappears. What I am hoping to do and am having problems with is making the text that appears after 5 seconds appear with a fade in ... html/js as follows:

Div with Text

CSS:
.fadeout {
    animation: fadeOut 1s forwards;
    animation-delay: 3s;
}

@keyframes fadeOut {
    from {opacity: 1;}
    to {opacity: 0;}
}

/* One option I tried that did not work out

.fadein {
    animation: fadeIn 3s forwards;
    animation-delay: 5s;
}

@keyframes fadeIn {
    from {opacity: 0;}
    to {opacity: 1;}
}
*/

/*my most current attempt at fadein through CSS */

.animated {
    animation-duration: 3s;
    animation-fill-mode: both;
    animation-delay: 5;
}

@keyframes fadeIn {
    0% {opacity: 0;}
    100% {opacity: 1;}
}
.fadeIn {
    animation-name: fadeIn;
}

#introText {
    width: auto;
    padding: 100px;
    visibility: hidden;
    text-align: center;
    height: auto;
}
'''

Am i able to add a fade-in transition into the visibility script? I tried doing a fade in with CSS but could not get it to work.

I do not know the JS to add it to my script and have tried searching for it but could not find anything for my specific situation.

If anyone sees anything I could fix in my CSS to make it fade in properly (maybe a timing issue?) or know how I can include a fade-in in my script making the text visible it would be much appreciated!

Thanks!!

A: Maybe instead of toggleing visibility you can toggle the display from none to block.
Take a look here:

.fadeout {
    animation: fadeOut 1s forwards;
    animation-delay: 3s;
}

@keyframes fadeOut {
    from {opacity: 1;}
    to {opacity: 0;}
}

/* One option I tried that did not work out

.fadein {
    animation: fadeIn 3s forwards;
    animation-delay: 5s;
}

@keyframes fadeIn {
    from {opacity: 0;}
    to {opacity: 1;}
}
*/

/*my most current attempt at fadein through CSS */

.animated {
    animation-duration: 3s;
    animation-fill-mode: both;
}

@keyframes fadeIn {
    0% {opacity: 0;}
    100% {opacity: 1;}
}
.fadeIn {
    animation-name: fadeIn;
}

#introText {
    width: auto;
    padding: 100px;
    display: none;
    text-align: center;
    height: auto;
}

Div with Text


text:
Q: Graph historical program status data in M/Monit I would like to use monit and M/Monit to monitor our Postgresql database. Setting it up to monitor the Postgresql process is simple enough. The next most important thing for us to monitor is the number of connections.
Current solution
I can write a bash script that will query the number of connections. The script will exit with a status code equal to the number of connections. I can call this script from Monit using
check program pg-replication-lag with path /tmp/count-connections.sh
    if status > 45 then alert

This will alert if more than 45 connections are consumed.
Problem
While getting alerts in such situations is very important, we would also like to visualize the number of connections over time. M/Monit has some great graphs of systems variables like RAM, CPU, etc..., but I do not see any way of graphing a check program status value in M/Monit, but I hope that I am just overlooking it.
Is it possible to graph arbitrary data collected by check program? Can anyone think of a better way to collect this data and visualize it in M/Monit?
PS: Though I used the number of connections as an example here, there is other numeric data that we would like to plot over time as well (e.g. replication lag).

A: I use monit a lot, I'll be honest, I've never used M/Monit. What I tend to use for graphing is Munin - it is pretty easy to write custom plugins, so I just put together a graph of what I'm monitoring in monit.
I use monit to start/stop services and send alerts, then use Munin to do all my graphing.


text:
Q: inputrc command not found I'm trying to modify .inputrc to change key-bindings for bash, so I can use Alt with the arrow keys, but when I source the changes I get "command not found".
I have the following options set:
set enable-keypad on

# mappings for Ctrl-left-arrow and Ctrl-right-arrow
"\e[D": beginning-of-line
"\e[C": end-of-line

I have used the read utility to determine the keybindings.
I have also tried the bind command. Am I setting this in correct place?


text:
Q: Volley parse Error org.json.JSONException: End of input at character 0 of I;m developing a android app and java Jax rs Restful web service. When my app sending json on service that error occure. And if I send json from Restful Client browser Service Successfully receive data but cannot receive from android app....
my app and service code is here.This is my android Activity.
public class feedback extends SameCodeClass implements View.OnClickListener {
String f_name, f_mobile, f_description, f_ratVel;
double f_rating;
RequestQueue requestQueue;
String responseServer;
feedbackModel fbModel;

private String TAG = feedback.class.getSimpleName();
private String tag_json_obj = "jobj_req", tag_json_arry = "jarray_req";
private ProgressDialog pDialog;
EditText name, mobile, des;
TextView rating;
RatingBar ratingBar;
Button submint_fb;

protected void onCreate(Bundle b) {
    super.onCreate(b);
    setContentView(R.layout.feedback);

    Initialize();
    addListenerOnRatingBar();
}

protected void Initialize() {
    name = (EditText) findViewById(R.id.name);
    mobile = (EditText) findViewById(R.id.mobile);
    des = (EditText) findViewById(R.id.des);
    rating = (TextView) findViewById(R.id.rating);
    ratingBar = (RatingBar) findViewById(R.id.ratingBar);
    submint_fb = (Button) findViewById(R.id.fsbutton);

    submint_fb.setOnClickListener(this);

    pDialog = new ProgressDialog(this);
    pDialog.setMessage("Loading...");
    pDialog.setCancelable(false);

    requestQueue = Volley.newRequestQueue(this);

}

private void showProgressDialog() {
    if (!pDialog.isShowing())
        pDialog.show();
}

private void hideProgressDialog() {
    if (pDialog.isShowing())
        pDialog.hide();
}

protected void setValues() {
    f_name = name.getText().toString();
    f_mobile = mobile.getText().toString();
    f_description = des.getText().toString();
    f_ratVel = rating.getText().toString();
    f_rating = Double.parseDouble(f_ratVel);

    if (f_name != null && f_mobile != null && f_description != null && f_rating != 0.0) {
        //   Toast.makeText(getBaseContext(),f_name+","+f_mobile+","+f_description+","+f_rating,Toast.LENGTH_LONG).show();
             createJsonObj();

    } else {

        if (f_name.isEmpty()) {
            Toast.makeText(getBaseContext(), "Enter Name First.", Toast.LENGTH_LONG).show();
        } else if (f_mobile.isEmpty()) {
            Toast.makeText(getBaseContext(), "Enter Mobile Number.", Toast.LENGTH_LONG).show();
        } else if (f_description.isEmpty()) {
            Toast.makeText(getBaseContext(), "Enter Your Message.", Toast.LENGTH_LONG).show();
        } else if (f_ratVel.isEmpty()) {
            Toast.makeText(getBaseContext(), "0.0 Rating Not Acceptable.", Toast.LENGTH_LONG).show();
        }
    }

}

//  Volley Json Request...

private void createJsonObj() {

    String url = "http://192.168.23.1:8080/RESTfulExample/rest/file/feedback";
    showProgressDialog();

    Map<String, String> jsonParams = new HashMap<String, String>();
    //jsonParams.put("param1", youParameter);
    jsonParams.put("name", f_name);
    jsonParams.put("mobile", f_mobile);
    jsonParams.put("description", f_description);
    jsonParams.put("rating", f_ratVel);

    JsonObjectRequest myRequest = new JsonObjectRequest(
            Request.Method.POST,
            url,
            new JSONObject(jsonParams),

            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    // verificationSuccess(response);
                    Toast.makeText(getBaseContext(), response.toString(), Toast.LENGTH_LONG).show();
                    hideProgressDialog();
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    //  verificationFailed(error);
                    VolleyLog.d(TAG, "Error: " + error.getMessage());
                    hideProgressDialog();

                    NetworkResponse networkResponse = error.networkResponse;
                    if (networkResponse != null) {
                        Log.e("Volley", "Error. HTTP Status Code:" + networkResponse.statusCode);
                    }

                    if (error instanceof TimeoutError) {
                        Log.e("Volley", "TimeoutError");
                    } else if (error instanceof NoConnectionError) {
                        Log.e("Volley", "NoConnectionError");
                    } else if (error instanceof AuthFailureError) {
                        Log.e("Volley", "AuthFailureError");
                    } else if (error instanceof ServerError) {
                        Log.e("Volley", "ServerError");
                    } else if (error instanceof NetworkError) {
                        Log.e("Volley", "NetworkError");
                    } else if (error instanceof ParseError) {
                        Log.e("Volley", "Parse Error: "+ error.getMessage());
                    }

                }
            }) {

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json; charset=utf-8");
            // headers.put("User-agent", "My useragent");
            return headers;
        }

        @Override
        public Priority getPriority() {
            return Priority.IMMEDIATE;
        }
    };

         requestQueue.add(myRequest);

}

public void addListenerOnRatingBar() {

    ratingBar = (RatingBar) findViewById(R.id.ratingBar);
    rating = (TextView) findViewById(R.id.rating);

    //if rating value is changed,
    //display the current rating value in the result (textview) automatically
    ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
        public void onRatingChanged(RatingBar ratingBar, float rat,
                                    boolean fromUser) {

            rating.setText(String.valueOf(rat));

        }
    });
}

public void onClick(View v) {
    switch (v.getId()) {
        case R.id.fsbutton: {
            if(isOnline()){
                setValues();
           //     requestData("http://192.168.23.1:8080/RESTfulExample/rest/file/show");

            }else{
                Toast.makeText(this,"Network isn't available", Toast.LENGTH_LONG).show();
            }

        }
    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id != R.id.fdb) {
        DealMenu(id);
    }

    return super.onOptionsItemSelected(item);
}

@Override
public void onBackPressed() {
    BackButtonHandle();
    return;
}
protected boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    } else {
        return false;
    }
}

}

Now my service method that receive the that of this class.
@POST
@Path("/feedback")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.TEXT_PLAIN)
public void postFeedback(newFeedModel fbkModel){

    String name, mobile,description;
    int rating;
    f_name = fbkModel.getName();
    f_mobile = fbkModel.getMobile().toString();
    f_description = fbkModel.getDescription();
    f_rating = fbkModel.getRating();

    dataService.insertFeedback(f_name, f_mobile, f_description, f_rating);
}

And my feedback Model is here,...
package com.live.rest.Model;
import java.io.Serializable;
public class newFeedModel implements Serializable{

public String id;
public String name;
public String mobile;
public String description;
public String rating;

public void setId(String id) {
    this.id = id;
}
public newFeedModel() {
    super();
}

public newFeedModel(String name, String mobile, String description, String rating) {
    super();
    this.name = name;
    this.mobile = mobile;
    this.description = description;
    this.rating = rating;
}

public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getMobile() {
    return mobile;
}
public void setMobile(String mobile) {
    this.mobile = mobile;
}
public String getDescription() {
    return description;
}
public void setDescription(String description) {
    this.description = description;
}
public String getRating() {
    return rating;
}
public void setRating(String rating) {
    this.rating = rating;
}
}

A: You are getting a blank / empty response. You are not getting exception  but the json encoded text is empty.
Check for Post Request / Get request - what you are using in the server side.
Check whether the API returns the valid json by debugging.
Check that the response should be a valid json. you can check whether the json is valid or not in the below link.
Json Validator
Check whether you added the below permission to the Android Manifest.
<uses-permission android:name = "android.permission.INTERNET"/>

Check whether you have working internet connection.
Reference Links :
Link 1, Link 2, Link 3
Tutorial
Happpy Coding..!!


text:
Q: How can i configure ffmpeg with both openssl and h264 I use this to configure ffmpeg:
./configure --enable-shared --enable-yasm --enable-openssl --enable-gpl --enable-libx264 --prefix=/mnt/newdatadrive/apps/ffmpeg/ffmpeg-master

But it returned a error:

OpenSSL <3.0.0 is incompatible with the gpl

But i need both of them, how to resolve this?

A: It seems to be that openSSL 3.0 is not compatible with GPL 2.0. My guess is that you should try using GPL 3.0 or higher instead. The issue seems to be that the apache license is not compatible with GPL 2.0.
You can try using --enable-gpl with --enable-version3 build params which should help.
You can try using --enable-nonfree as well. Not sure if this is useful though
You should consider looking into ./configure --help for more details on what you're doing.

A: Try to Use.
./configure --enable-shared --enable-yasm --enable-openssl --enable-gpl --enable-libx264 --enable-nonfree --prefix=/mnt/newdatadrive/apps/ffmpeg/ffmpeg-master


text:
Q: How do I retrieve all the markers in gmap4rails?   Gmaps.store.handler = Gmaps.build('Google');
  Gmaps.store.handler.buildMap({ provider: {}, internal: {id: 'map'}}, function(){
    mapping.forEach(function(item) {
      Gmaps.store.marker = Gmaps.store.handler.addMarker(
        {
          ...
        }
      );
    });
    console.log(Gmaps.store.handler);
    Gmaps.store.handler.bounds.extendWith(Gmaps.store.marker);
    Gmaps.store.handler.fitMapToBounds();
  })

I'm adding markers one by one. But I would like the map to extend and cover all the markers. How do I retrieve the markers. So I can pass them into extendWith()?

A: Just had to shift the extendWith() into my iterator and pass each marker into it.
mapping.forEach(function(item) {
  Gmaps.store.marker = Gmaps.store.handler.addMarker(
    {
      ...
    }
  );
  Gmaps.store.handler.bounds.extendWith(Gmaps.store.marker);
});


text:
Q: Playing Videos using MPMoviePlayer Now I am here with new question related to MPMoviePlayer. I am having a table view that lists the videos on one side of ipad, on other side - I play the video selected in list. These happens in same view. Now switching to different videos works fine. Now when I am editing the video using UIVideoEditorController, I am replacing the current video file in documents folder and then play the video again. But then my player stops working...
I think the issue is that player within the UIVideoEditorController is not released properly. I released the editor but still I am there only.. NOTHING WORKS AGAIN :(
Please help me asap
-(void)playVideoWithIndex:(NSNumber *)index1
{
int index = [index1 intValue];
indexVideo = [index1 intValue];
if(index > [SourceArray count]){
    NSLog(@"dg");
    return;
}

if (mp) {
    [mp stop];
    [mp.view removeFromSuperview];
    [mp release];
    mp=nil;
}
//  NSArray *sourcePaths=[[NSArray alloc] initWithArray:[[NSBundle mainBundle] pathsForResourcesOfType:@"mov" inDirectory:nil]];
videoDtls *v =[SourceArray objectAtIndex:index];
lbl_date.text=v.iVideoDate;
lbl_Title.text=v.iVideoTitle;
lbl_description.text=v.iVideoDesc;
lblDesc.text = @"Description";

lable_title.text = v.iVideoTitle;
NSString *documentFolderPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSString *mainImageFolderPath=[documentFolderPath stringByAppendingPathComponent:@"Videos"];
NSString *urlStr  = [mainImageFolderPath stringByAppendingPathComponent:v.iVideoPath];
self.vpath = urlStr;
NSLog(@"asdsd %@",urlStr);
NSURL *url = [NSURL fileURLWithPath:urlStr];

mp =  [[MPMoviePlayerController alloc] initWithContentURL:url];

if ([mp respondsToSelector:@selector(loadState)])
{
    // Set movie player layout
    //[mp setControlStyle:MPMovieControlStyleFullscreen];

    //[mp setFullscreen:YES];
    // May help to reduce latency
    [mp prepareToPlay];
    mp.useApplicationAudioSession = NO;
//  mp.controlStyle = MPMovieControlStyleDefault;
//  mp.useApplicationAudioSession = YES;
    // Register that the load state changed (movie is ready)
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(moviePlayerLoadStateChanged:)
                                                 name:MPMoviePlayerLoadStateDidChangeNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(moviePlayerEnterFullScreen:)
                                                 name:MPMoviePlayerDidEnterFullscreenNotification
                                               object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(moviePlayerExitFullScreen:)
                                                 name:MPMoviePlayerWillExitFullscreenNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(moviePlayerDidFinish:)
     name:MPMoviePlayerPlaybackDidFinishNotification
     object:nil];

    [[mp view] setFrame:CGRectMake(0, 0, 480, 320)];

    // Add movie player as subview
    [playerView addSubview:[mp view]];
    mp.initialPlaybackTime = -1.0;

}
else
{
    // Register to receive a notification when the movie is in memory and ready to play.
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(moviePreloadDidFinish:)
                                                 name:MPMoviePlayerContentPreloadDidFinishNotification
                                               object:nil];
}

// Register to receive a notification when the movie has finished playing.
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(moviePlayBackDidFinish:)
                                             name:MPMoviePlayerPlaybackDidFinishNotification
                                           object:nil];

}
This method is called when a video is played from table view..
- (void)videoEditorController:(UIVideoEditorController *)editor didSaveEditedVideoToPath:(NSString *)editedVideoPath
{
CFShow(editedVideoPath);
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSError *error = nil;
NSString *path = self.vpath;
NSLog(@"PATH %@", self.vpath);
if([fileManager removeItemAtPath:path error:&error] != YES){
    NSLog(@"ERROR 1 : %@",[error localizedDescription]);
}
else{
// can do save here. the data has *not* yet been saved to the photo album
if ([fileManager copyItemAtPath:editedVideoPath toPath:path error:&error] != YES)
    NSLog(@"Can't move file with error: %@", [error localizedDescription]);
}
[popOver dismissPopoverAnimated:YES];
[self dismissMoviePlayerViewControllerAnimated];
[editor release];
[self performSelector:@selector(playVideoWithIndex:) withObject:[NSNumber numberWithInt:indexVideo] afterDelay:0.2];

}
This method is called when editor returns successfully.
After This my video does not play

A: Finally I solved issue by using UIVideoEditorController in another view controller and then delaying playing video for fraction of second. May this happened because I was trying to play a video that was being replaced.


text:
Q: Let $\frac{a}{b},\frac{c}{d}\in \mathbb{Q}$. prove that the product is well-defined We have that $\frac{a}{b}\cdot \frac{c}{d}=\frac{a'}{b'}\cdot\frac{c'}{d'}$, which can be rewritten as $\frac{ac}{bd} = \frac{a'c'}{b'd'}$ and again as $(ac)(b'd') = (bd)(a'c').$
If $\frac{a}{b} = \frac{a'}{b'}$ and $\frac{c}{d} = \frac{c'}{d'}, $ then $ab' = ba'$ and $cd' = dc'.$
$= (ab')(dd') = (ba')(dd')$ and $(cd')(bb') = (dc')(bb')$
$= (ab')(dd')(cd')(bb') = (ba')(dd')(dc')(bb')$ when multiplying the two equations.
Here is where I got stuck. I was attempting to get the final equation equal to $(ac)(b'd') = (bd)(a'c')$ so as to prove that the multiplication is well-defined, but I am unsure of how to get there from where I am or whether I'm thinking about this wrong to begin with.

A: You are correct that you need to prove that $(ac)(b'd')=(bd)(a'c')$, but you're making it too complicated. By definition,
$$\frac{a}{b} = \frac{a'}{b'} \: \: \text{and} \:\: \frac{c}{d} = \frac{c'}{d'}, $$
means that $ab' = ba'$ and $cd' = dc'$. By multiplying these two equations together (ie left times left, right times right) you simply get $(ac)(b'd')=(bd)(a'c')$, which is what you're looking for.

A: You can simply say:
$$\frac{a}{b}\cdot\frac{c}{d}=\frac{a}{b}\cdot\frac{c}{d}$$
which is always verified.
For the hypothesis done $\left (\frac{a}{b}=\frac{a_1}{b_1}, \frac{c_1}{d_1}=\frac{c}{d}\right)$, we arrive at:
$$\frac{a}{b}\cdot\frac{c}{d}=\frac{a_1}{b_1}\cdot\frac{c_1}{d_1}$$


text:
Q: Change the default host key to RSA in OpenSSH over Windows Server I have a Windows Server 2019 that runs an OpenSSH server. I need to change the OpenSSH default host key type from ECDSA to RSA.
I tried to do:

*

*Generated a new RSA key.
ssh-keygen -t rsa

*Copy the id_rsa to authorized_keys
Get-Content "C:\Users\user.ssh\id_rsa.pub" | Out-File $env:USERPROFILE.ssh\authorized_keys -Encoding ascii

*Restart the service
Restart-Service sshd
But it doesn't work. I appreciate some help :)


text:
Q: Puzzle game using Kinetic js
*

*This my code of puzzle game. I just used tutorial code from http://www.html5canvastutorials.com/labs/html5-canvas-animals-on-the-beach-game-with-kineticjs/ using Kinetic javascript. I tried to run the code but it doesn't work. I checked error with html and javascript. But I couldn't find what's the problem in my code.
Please let me know if there's someone know what's the error which makes it doesn't work.

A: The first thing I want you to do is this... change this line to add what I have in BOLD ...

var outline = new Kinetic.Image({
        image: imageObj,
        x: out.x,
        y: out.y,
          draggable: true
      });

Then tell me if you are still struggling.
(This will make Latvia draggable, for instance). So you will see the red version of the country under the green version. Hope this is a start at helping.


text:
Q: Export html and css to a file using jquery Imagine I have a 3 column layout. Left, center and right div. I want to export only the center div. This is my export method so far:
function getHtml() {
    var htmlStartTag = function(){
        var attrs = $('html')[0].attributes;
        var result = '';
        return result;
    }

return htmlStartTag() + $('html').html() + '';
}

My question is, how can I save the DOM to a html file, say template.html? When the user clicks export, the entire DOM should be saved or downloaded as html file. Is this possible, can you give an example? My application just uses jquery and html. It is not a serverside application!

A: You can use data:URI, as seen in Using HTML5/Javascript to generate and save a file (2nd answer, the one with the 50+ upvotes)
something like http://jsfiddle.net/gBxrB/ should do the trick in your case.
HTML

leftleftleft

center

rightrightright

export

JS
$('a.export').on('click',function(){
   uriContent = "data:application/octet-stream," + encodeURIComponent( $('.center').html() );
   window.open(uriContent, 'myDocument');
});

A: You cant save files with javascript


text:
Q: Click event lost after css animation For a laugh I have put a Google-esk barrel roll on one of my sites.
All works fine on the first click of the selected element, but it won't fire again after that.
I have tried .click, .on('click', function() {}) and neither work.
Any ideas on how to fix and why this is happening?
Basic jsFiddle here
Source code example;

        <title>
            Roll Me
        </title>

click me

A: You need to remove the animation that you applied after it has finished and then re-add it on subsequent clicks.

var $body = $('body');

$('#roll').on('click', function() {
    $body.addClass('barrel-roll');
});

$body.on('animationEnd webkitAnimationEnd mozAnimationEnd',function(e) {
    $body.removeClass('barrel-roll');
});
@-webkit-keyframes roll {
from { -webkit-transform: rotate(0deg) }
to { -webkit-transform: rotate(360deg) }
}

@-moz-keyframes roll {
from { -moz-transform: rotate(0deg) }
to { -moz-transform: rotate(360deg) }
}

@keyframes roll {
from { transform: rotate(0deg) }
to { transform: rotate(360deg) }
}

.barrel-roll {
 -webkit-animation-name: roll;
 -webkit-animation-duration: 4s;
 -webkit-animation-iteration-count:1;
 -moz-animation-name: roll;
 -moz-animation-duration: 4s;
 -moz-animation-iteration-count:1;
}

click me

A: That's because by that point the body element already has that CSS styling applied. The way to fix it is to remove the style properties from your body element:
setTimeout(function() {
    $('body').removeAttr('style');
}, 4000);

I've used setTimeout here to ensure the style attribute gets reset only after your animation has completed (after 4 seconds).
JSFiddle demo.

A: It isn't the click handler isn't firing. You can verify that with console.log. You need to reset the animation.

A: After your animation completes, you have already set the animation! The only way to solve this is to remove it again, and then re-trigger it. The best way to do that, however, is CSS classes:

var busy = false;

$('#roll').on('click', function() {
  if(busy) return;
  else busy = true;
  $('body').addClass("do-the-barrel-roll");
  setTimeout(function(){
    $('body').removeClass("do-the-barrel-roll");
    busy = false;
  }, 2100);
});
@-webkit-keyframes roll {
from { -webkit-transform: rotate(0deg) }
to { -webkit-transform: rotate(360deg) }
}

@-moz-keyframes roll {
from { -moz-transform: rotate(0deg) }
to { -moz-transform: rotate(360deg) }
}

@keyframes roll {
from { transform: rotate(0deg) }
to { transform: rotate(360deg) }
}

body.do-the-barrel-roll {
  -webkit-animation: roll 2s;
  -moz-animation: roll 2s;
  animation: roll 2s;
  -webkit-animation-fill-mode: backwards;
  -moz-animation-fill-mode: backwards;
  animation-fill-mode: backwards;
}

click me

Simple add the class and remove it after the time it takes for the animation to complete. Also, I added a busy to prevent multiple clicks from making this hell.

A: What is happening is that the css is applied. Since it is already applied then when it is applied again on the next click nothing happens. I have created something that works, adding a class then removing after a timeout that matches the animation length. https://jsfiddle.net/5yqrxvkd/3/
$('#roll').on('click', roll);

function roll(){
    $('body').addClass("animate");
    setTimeout(function(){
        $("body").removeClass("animate");
    }, 4000);
}

There may be a better way using animate or something but I'm not that farmiliar with it.


text:
Q: NewtonSoft JSON Deserialization: System.StackOverflowException The JSON deserialization is failing with the exception System.StackOverflowException.
I'm trying the deserialize the following entity. Need help, why this is causing the issue.
var workingJSONString = "{\"FBTOrLeaseYear\":{\"DateFrom\":\"2019-03-02T00:00:00\",\"DateTo\":\"2020-03-01T00:00:00\"},\"Registration\":\"155SQN\",\"NovatedLeaseFortnightBenefitGroups\":[],\"NovatedLeaseAnnualBenefitGroups\":[]}";

var exceptionJSONString = "{\"FBTOrLeaseYear\":{\"DateFrom\":\"2019-03-02T00:00:00\",\"DateTo\":\"2020-03-01T00:00:00\"},\"Registration\":\"155SQN\",\"NovatedLeaseFortnightBenefitGroups\":[{\"BenefitGroupID\":1,\"BenefitGroupName\":\"Fuel\",\"TotalAnnualBudgetAmount\":4992.0000,\"TotalFortnightBudgetAmount\":192.0000,\"TotalSpentToDate\":3327.43,\"TotalFortnightSpent\":141.59276595744680851063829788,\"TotalProjAnnualAmount\":3681.4119148936170212765957447,\"TotalVariationAmount\":1310.5880851063829787234042553,\"AverageSpentPercentage\":14.645499465811966666666666667,\"NovatedLeaseBudgetSpentDataForBenefits\":[]}],\"NovatedLeaseAnnualBenefitGroups\":[]}";

Test.Entities.NovatedLeaseBenefitsBudgetSpentFBTYear novatedLeaseBenefitsBudgetSpentFBTYearResponse = new Test.Entities.NovatedLeaseBenefitsBudgetSpentFBTYear();

novatedLeaseBenefitsBudgetSpentFBTYearResponse = JsonConvert.DeserializeObject<Test.Entities.NovatedLeaseBenefitsBudgetSpentFBTYear>(exceptionJSONString); // Exception is thrown here

Entities:
On deserialization of the "Test.Entities.NovatedLeaseBenefitsBudgetSpentFBTYear" entity,
I'm getting an exception "System.StackOverflowException". Can one please help me why the deserizarion is failing for this JSON.
public class NovatedLeaseBenefitsBudgetSpentFBTYear
{
    public FBTOrLeaseYear FBTOrLeaseYear { get; set; }
    public string Registration { get; set; }
    public List<NovatedLeaseBenefitGroup> NovatedLeaseFortnightBenefitGroups { get; set; }
    public List<NovatedLeaseBenefitGroup> NovatedLeaseAnnualBenefitGroups { get; set; }
}

 public class NovatedLeaseBenefitGroup
{
    public int BenefitGroupID { get; set; }
    public string BenefitGroupName { get; set; }
    public double TotalAnnualBudgetAmount { get; set; }
    public double TotalFortnightBudgetAmount { get; set; }
    public double TotalSpentToDate { get; set; }
    public double TotalFortnightSpent { get; set; }
    public double TotalProjAnnualAmount { get; set; }
    public double TotalVariationAmount { get; set; }
    public double AverageSpentPercentage { get; set; }
    public List<NovatedLeaseBudgetSpentDataForBenefit> NovatedLeaseBudgetSpentDataForBenefits { get; set; }
}

public class NovatedLeaseBudgetSpentDataForBenefit
{
    public int BenefitId { get; set; }
    public string BenefitName { get; set; }
    public double AnnualBudgetAmount { get; set; }
    public double FortnightBudgetAmount { get; set; }
    public double SpentToDate { get; set; }
    public double FortnightSpent { get; set; }
    public double ProjAnnualAmount { get; set; }
    public double VariationAmount { get; set; }
    public double SpentPercentage { get; set; }
}

public class FBTOrLeaseYear
{
    public string DateFrom { get; set; }
    public string DateTo { get; set; }
}


text:
Q: C# WinForms flicker by scrolling - Janus Controls i got a little problem with a Control containig the Janus Controls ExplorerBar. The Size oft this ExplorerBar-Instance is much bigger than the max. Size of the Control, so a Scrollbar appears automatically.
Normal Scrolling in this Control (by Scrollwheel or by the Buttons of the Scrollbar) is no big deal and happens very smooth. But if I scroll by dragging the Scrollbar with the Mouse up or down, the Controls appear flickering while the scrolling is in progress. After releasing the Scrollbar, they paint instantly.
So my idea was to hook into the Scroll-Event of the ExplorerBar to make the scrolling smooth by myself (by deriving a Class     MyExplorerBar from the Janus.Windows.ExplorerBar.ExplorerBar). But there's no Scroll-Event. I also tried if theres a Method like OnScroll which I can override. But there is none.
So I thought asking a question here is good idea, because I allways got good Answers here. Do you know how to solve this Problem? Has anyone had the same or a similar Problem?


text:
Q: How to persist aggregates with repositories? I am trying to learn some concepts about DDD and the part of persisting Aggregates is confusing me a bit. I have read various answers on the topic on SO but none of them seem to answer my question.
Let's say I have an Aggregate root of Product. Now I do not want to inject the ProductRepository that will persist this aggregate root in the constructor of the Product class itself. Imagine me writting code like
var prod = new Product(Factory.CreateProductRepository(), name, costprice);

in the UI layer. If I do not want to inject my repository via dependency injection in the Aggregate Root, then the question is where should this code go? Should I create a class only for persisting this AR? Can anyone suggest what is the correct & recommended approach to solve this issue?
My concern is not which ORM to use or how to make this AR ORM friendly or easy to persist, my question is around the right use of repositories or any persistence class.

A: Application Services
You are right, the domain layer should know nothing about persistence. So injecting the repository into Product is indeed a bad idea.
The DDD concept you are looking for is called Application Service. An application service is not part of the domain layer, but lives in the service layer (sometimes called application layer). Application services represent a use case (as opposed to a domain concept) and have the following responsibilities:

*

*Perform input validation

*Enforce access control

*Perform transaction control
The last point means that an application service will query a repository for an aggregate of a specific type (e.g. by ID), modify it by using one of its methods, and then pass it back to the repository for updating the DB.
Repository Ganularity
Concerning your second question

Should I create a class only for persisting this AR?

Yes, creating one repository per aggregate is a common approach. Often, standard repository operations like getById(), update(), delete(), etc. are extracted into a reusable class (either a base class or by aggregation).
You can also create additional repositories for non-domain information, e.g. statistical data. In these cases, make sure that you don't accidentally miss a domain concept, however.


text:
Q: Trouble Removing Slick Slider / Carosel Below Certain Resolution I'm having trouble removing my slick carosel for screens below a certain resolution (768px). Here is the code I'm using (I found it here on Stack overflow). The trouble is, my slick carosel won't display at all after adding this code.
 $slickGreen = false;
    function greenSlider(){
        if($(window).width() > 768){
            if(!$slickGreen){
                $('#book-carosel').slick({
            slidesToShow: 6,
        slidesToScroll: 1,
        autoplay: true,
        autoplaySpeed: 2000,
        arrows: true,
        infinite:true
       }).show();

                });
                $slickGreen = true;
            }
        } else if($(window).width() < 767){
            if($slickGreen){
                $('#book-carosel').slick('unslick');
                $slickGreen = false;
            }
        }
    };
 });

$(document).ready(function(){
        ....
        greenSlider();
    });
    $(window).on('resize', function(){
         ....
         greenSlider();
    });

My original code that does work to display the carosel is as follows:
  $(document).ready(function(){
      $('#book-carosel').slick({
        slidesToShow: 6,
        slidesToScroll: 1,
        autoplay: true,
        autoplaySpeed: 2000,
        arrows: true,
        infinite:true

      }).show();
    });

Any help would be much appreciated.

A: In case this helps someone, I have finally figured out how to do this. All of the code I used is below. Note: XML characters were used since I am using a Blogger template, which doesn't allow ' or > < signs.

$(document).ready(function() {
    // This will fire when document is ready:
    $(window).on('resize', function(){
        // This will fire each time the window is resized:
        if($(window).width() >= 1024) {
            // if larger or equal
        $('#book-carosel').slick({
        slidesToShow: 6,
        slidesToScroll: 1,
        autoplay: true,
        autoplaySpeed: 2000,
        arrows: true,
        infinite:true

      }).show();

             } else if ($(window).width() >= 800) {
            // if smaller
            $('#book-carosel').slick({
                slidesToShow: 4,
                slidesToScroll: 1,
                autoplay: true,
                autoplaySpeed: 2000,
               arrows: true,
               infinite:true

              }).show();

           } else if ($(window).width() >= 600) {
            // if smaller
            $('#book-carosel').slick({
                slidesToShow: 3,
                slidesToScroll: 1,
                autoplay: true,
                autoplaySpeed: 2000,
               arrows: true,
               infinite:true

              }).show();

        } else if ($(window).width() >= 300) {
            // if smaller
            $('#book-carosel').slick({
                slidesToShow: 2,
                slidesToScroll: 1,
                autoplay: true,
                autoplaySpeed: 2000,
               arrows: true,
               infinite:true

              }).show();

        } else {
  //  block of code to be executed if the condition1 is false and condition2 is false
            $('#book-carosel').unslick();
        }
    }).resize(); // This will simulate a resize to trigger the initial run.
});


text:
Q: Content Database(Size) when using RBS When using RBS what is the total size limit that can be uploaded to SharePoint?
Is there any size limitation concerning the data?
When I right click on my content database that enable RBS it shows me the size of the content database plus the size of the RBS file, is this size has the limit (200GB) or the size of the ".MDF" file only (excluding the size of RBS)

A: When using RBS what is the total size limit that can be uploaded to SharePoint?
Is there any size limitation concerning the data?
Per file: The absolute maximum size per file that can be uploaded is 2GB - RBS does not change this.
Per content db: The standard 200GB (on SP2010 and 2013) or 100GB (on SP2007) includes both the data within the SQL db (i.e. mdf files) and externalized files:
"If you are using Remote BLOB Storage (RBS), the total volume of remote BLOB storage and metadata in the content database must not exceed the 200GB limit."
Ref: https://technet.microsoft.com/en-us/library/cc262787.aspx
When I right click on my content database that enable RBS it shows me the size of the content database plus the size of the RBS file, is this size has the limit (200GB) or the size of the ".MDF" file only (excluding the size of RBS)
Typically when right clicking content databases and viewing the size - via properties - this will only be the size of the MDFs and LDFs - not the externalized files.
The standard way to view the total size of external files via T-SQL is with a command such as:
SELECT SUM(DATALENGTH()) FROM ;
Although you could perhaps run this command on a content db and get away with it, it would not be recommended.
Ideally just view the total size via Windows Explorer or if you're using a third party provider such as AvePoint/Metalogix then the total externalized data should be visible through their UIs.
HTH.


text:
Q: How can I retrieve values from a DropDownList dynamically added to a GridView in the RowUpdating event? I'm very new to ASP.NET and really programming in general. I have a GridView to which I've added a DropDownList on edit in the RowDataBound event. The existing control is readonly and does not seem to display on edit.
protected void GridViewVehicles_RowDataBound(object sender, GridViewRowEventArgs e)
{
     if (e.Row.RowType == DataControlRowType.DataRow)
     {
         if (e.Row.RowState == DataControlRowState.Edit)
         {
             DropDownList ddlVehicles = GetVehicles();
             string make = e.Row.Cells[9].Text;
             ddlVehicles.Items.FindByText(reportsTo).Selected = true;
             e.Row.Cells[10].Controls.Add(ddlVehicles);
         }
     }
}

The problem is that I cannot seem to access the selected value of the DropDownList in the RowUpdating event. That table cell seems to have a controls count of 0. The following throws and Argument Out of Range exception.
protected void GridViewEmployees_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    string vehicle = ((DropDownList)(row.Cells[10].Controls[0])).SelectedValue;
}

In the Chrome debugger, I do see the correct value being posted, but I just can't figure out how to access it.
I've read that it might be possible to use the OnSelectedIndexChanged event for the DropDownList and store the value in ViewState, but I've been having difficulty with that as well.
Any guidance on how best to proceed would be greatly appreciated. Thanks in advance!

A: It looks like the method GetVehicles() is dynamically creating the drop-down list, since you are adding the drop-down to Controls collection on the last line of second if statement.
When you are dynamically creating controls, you have to recreate them on every postback.
Instead, place the drop-down control inside EditItemTemplate and then find this control using the FindControl method and populate it in code behind like you are doing now.
Here is the example of GridView definition:
<asp:GridView runat="server" ID="GridViewVehicles" OnRowDataBound="GridViewVehicles_RowDataBound" OnRowUpdating="GridViewVehicles_RowUpdating">
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <!-- Text of selected drop-down item -->
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:DropDownList runat="server" ID="ddlVehicles" />
                </EditItemTemplate>
            </asp:TemplateField>

        </Columns>
    </asp:GridView>

And the code-behind:
protected void GridViewVehicles_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowState == DataControlRowState.Edit)
            {
                //Get the drop-down datasource and perform databinding
            }
        }

        protected void GridViewVehicles_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            DropDownList ddlVehicles = GridViewVehicles.Rows[e.RowIndex].FindControl("ddlVehicles") as DropDownList;

            if (ddlVehicles != null)
            {
                string selectedValue = ddlVehicles.SelectedValue;
            }
        }

Hope it helps!
Regards,
Uroš


text:
Q: Unable to do Replication of MySQL DB, Is their any other way to keep online DB updated I am unable to do Replication of local MySQL DB to online DB, Is their any other way to keep online DB updated. Like am I able to create a log file and implement that log file to online mysql DB.

A: First, I would contact your hosting provider to see if they have a solution.  They may be able to set it up for you.
If you have no control over the slave's (read-only online DB) configuration then you may be able to do log based replication.  Follow the instructions in Setting Up Binary Log File Position Based Replication, it should only require issuing SQL commands.
As for replicating both ways (aka master-master or cluster replication) it's complicated. I don't think that's possible without being able to fully control all the servers.
Consider switching to a hosting provider which supports MySQL replication, for example, Rackspace.


text:
Q: Button disabled state bases on multiple TextFormFields I have a username textfield, a password textfield and a button.
When one of these fields are empty, the button should be disabled (onPressed null). When both of these fields contains text, the button should be enabled (onPressed not null).
A very basic usecase, which I cannot find a solution for.
ValueListenableBuilder only works for a single TextEditingController, and Listenable.merge cannot be uses on multiple TextEditingController´s either.
I read another solution where you could wrap multiple ValueListenableBuilders into another widget, and then use this widget. But this seems to "complex" for me for such a simple problem, and this is not a nice scaleable solution.
I´ve tried creating a getter:
get loginButtonEnabled {
    if (_usernameController.text != '' && _passwordController.text != '' && !loading) {
      return true;
    }
    return false;
}

then use it on the button:
ElevatedButton.icon(
   onPressed: loginButtonEnabled ? loginClicked : null,
   label: Text('Login'),
),

and when onChanged fired on my textfields, they would call setState() to update the ui.
Problem with this is, that when the user types in some text, the textfield loses focus for some reason. And furthermore, this is not an elegant solution either.
So is there a more suitable approach to this common usecase?

A: You can follow this snippet, I am listening both controller. You might use StatefulWidget, for that overrideinitState and dispose state
class LogForm extends StatelessWidget {
  const LogForm({super.key});

  @override
  Widget build(BuildContext context) {
    final ValueNotifier<bool> isEnabled = ValueNotifier(false);
    late final TextEditingController passController;
    late final TextEditingController nameController;

    nameController = TextEditingController()
      ..addListener(() {
        if (passController.text.isNotEmpty && nameController.text.isNotEmpty) {
          isEnabled.value = true;
        } else {
          isEnabled.value = false;
        }
      });
    passController = TextEditingController()
      ..addListener(() {
        if (passController.text.isNotEmpty && nameController.text.isNotEmpty) {
          isEnabled.value = true;
        } else {
          isEnabled.value = false;
        }
      });
    return Column(
      children: [
        TextFormField(
          controller: nameController,
        ),
        TextFormField(
          controller: passController,
        ),
        ValueListenableBuilder<bool>(
          valueListenable: isEnabled,
          builder: (context, value, child) {
            return ElevatedButton(
                onPressed: value ? () {} : null, child: Text("Btn"));
          },
        )
      ],
    );
  }
}


text:
Q: Help me!!!! Profit is going down I have a game on Ubuntu Software Center. It costs 5 $. But I only get 4$. Ok. But, when my 2nd buyer bought, instead of having 8$, I had 7.20$. Now, I got a third buyer and I have 10.40$ instaed of 12$. Why????

A: The answer is already here, CLICK HERE to read it (scroll down a bit).
Don't desist, the world needs more games. ;-)


text:
Q: AWS Lambda - Could not determine an appropriate location for storing user secrets We published our Net6 web API to an AWS Lambda but when we make a request it fails.
Status: 502 Bad Gateway
{
  "message": "Internal server error"
}

We get this on CloudWatch:
  2022-09-01T10:42:07.359-03:00 Unhandled exception. System.InvalidOperationException: Could not determine an appropriate location for storing user secrets. Set the DOTNET_USER_SECRETS_FALLBACK_DIR environment variable to a folder where user secrets should be stored.
  2022-09-01T10:42:07.359-03:00 at Program.<Main>$(String[] args) in C:\repository\codetria\palier\backend\backend-palier\Src\Presentation\Palier.API\Program.cs:line 12

Program.cs - line 12:
var builder = WebApplication.CreateBuilder(args);

It's not the first time that we published an API in this way and we've never had to set this environment variable.
This's the command we use to publish the API
dotnet lambda deploy-function lambda-name `
  --region us-east-2 `
  --project-location $API_LOCATION `
  --profile profile `
  --function-runtime dotnet6

Any thoughts?

A: I just a similar error trying to deploy to AWS, for me it turned out to be that I a UserSecretsId in my csproj by mistake. The error went away when I remove this value. Here is a reference on how to use UserSecrets in deployed environments https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets?view=aspnetcore-6.0&tabs=windows


text:
Q: Generate a DES key and use cipher for encryption I want to learn about cryptography with java and I found
these slides on the internet. On page 9 I found on an example and I tried to use it. However, the following code is not compiling. Where is the mistake?
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class Gen_DESAES_key{

byte[] message = "Hello World".getBytes();

KeyGenerator keygenerator = KeyGenerator.getInstance("DES");
SecretKey desKey = keygenerator.generateKey();

Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
desCipher.init(Cipher.ENCRYPT_MODE,deskey);

byte[] encryptedMessage = desCipher.doFinal(message);
}

A: Fix #1: Fixing the variable name
Variable names are case-sensitive in Java. Your variable name is desKey and not deskey.
Fix #2: Wrapping your code into a method and handling exceptions
Apart from that, you must wrap your code into a method, as shown below:
import javax.crypto.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class Gen_DESAES_key {

    public static void main(String[] args) throws NoSuchAlgorithmException,
                                                  NoSuchPaddingException,
                                                  BadPaddingException,
                                                  IllegalBlockSizeException,
                                                  InvalidKeyException {

        byte[] message = "Hello World".getBytes();

        KeyGenerator keygenerator = KeyGenerator.getInstance("DES");
        SecretKey desKey = keygenerator.generateKey();

        Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        desCipher.init(Cipher.ENCRYPT_MODE, desKey);

        byte[] encryptedMessage = desCipher.doFinal(message);
        System.out.println(new String(encryptedMessage));
    }
}

Please mind that your code will throw a bunch of exceptions that must be handled by a try-catch block or declared in the throws clause of the method. For more details, refer to the documentation.
Bonus #1: Using Base64
To avoid some weird characters when showing the encrypted message, you can encode it with Base64. If you are using Java 8 or later, you can use java.util.Base64:
System.out.println(Base64.getEncoder().encodeToString(encryptedMessage));

Bonus #2: Decrypting your message
To decrypt your encrypted message, use:
desCipher.init(Cipher.DECRYPT_MODE, desKey);
byte[] decryptedMessage = desCipher.doFinal(encryptedMessage);

System.out.println(new String(decryptedMessage));

A: You forgot to write a method, and there is a spelling mistake in a variable name:
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class Gen_DESAES_key{

    public static void main(String[] args) {
        byte[] message = "Hello World".getBytes();

        KeyGenerator keygenerator = KeyGenerator.getInstance("DES");
        SecretKey desKey = keygenerator.generateKey();

        Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        desCipher.init(Cipher.ENCRYPT_MODE,desKey);

        byte[] encryptedMessage = desCipher.doFinal(message);
    }
}