text:
Q: Check if a number exists in the database and if not assign the number to an database-object? I have a method for generating a random OrderNumber which, if the number doesn't exist, stores the number in the database.
Is this the right way to do it?
I'm not sure If I should write while (OrderNumber != null) or  while (OrderNumber == null)
This is my code:
private string loadOrderNr()
{
    using (Db db = new Db())
    {
        Random rnd = new Random();
        long part1 = rnd.Next(100000, 999999);
        long part2 = rnd.Next(1000, 9999);

        string OrderNr = "CA-" + part1 + "-" + part2;

        return OrderNr;
    }
}

And for saving in Database
using (Db db = new Db())
{
    string OrderNumber = loadOrderNr();
    var CheckifOrderNrExist = db.CarAnn.Where(x => x.OrderNr ==  OrderNumber).FirstOrDefault();

    do
    {
        OrderNumber = loadOrderNr();
    }
    while (CheckifOrderNrExist != null);

    CarAnn ann = new CarAnn();
    ann.Description = model.Description;
    ann.Title = model.Title;
    ann.OrderNr = OrderNumber;
    db.CarAnn.Add(ann);
    db.SaveChanges();
}

I'm not sure about my solution and the do/while-loop.

A: This would be my approach!
It is important to keep the separation of concerns!
Therefore you have to write a Service-Class and an Interface from which you will call your Service-Methods.
public class IOrderService
{
    string SetOrderNumber();
}

public class OrderService : IOrderService
{
    private readonly Random random = new Random();

    private string LoadOrderNr()
    {
       long part1 = rnd.Next(100000, 999999);
       long part2 = rnd.Next(1000, 9999);

       return "CA-" + part1 + "-" + part2;
    }

    public string SetOrderNumber()
    {
        var orderNumber = "";

        do
        {
           orderNumber = LoadOrderNr();
        }
        while (db.CarAnn.Any(x => x.OrderNr == orderNumber));

        return orderNumber;
    }
}

After you have added the OrderService into your project - could be at the Service-Layer or as in the example in another Folder called Services that holds all the Service-Classes and Interfaces - you need to inject the service into your controller.
Then you can simply use it. This is the way to achieve a separation of concerns!
Controller-Logic
using System.Web.Mvc;
using ExampleProject.Services;

namespace ExampleProject.Controllers
{

    public class ExampleController : Controller
    {
        private IOrderService _orderService;

        public ExampleController(IOrderService orderService)
        {
            _orderService = orderService;
        }

        public ActionResult Post(Model model)
        {

            using (Db db = new Db())
            {
             var ann = new CarAnn()
             {
                Description = model.Description;
                Title = model.Title;
                OrderNr = _orderService.SetOrderNumber();
              };

             db.CarAnn.Add(ann);
             db.SaveChanges();
            }

            return Ok();
        }
    }

}

In my opinion, the Database-Context should be injected as well - but to be honest I am not sure how to do this. I am more familiar with ASP.NET-Core. ;)
For further information for dependency-injection look here: ASP.NET-Documentation

A: Your current code will work only if the number doesn't exist. If the number exist then you enter an infinite loop because you don't update the variable CheckIfOrderNrExist
You should change your code to check that number everytime you create it, so
string OrderNumber = loadOrderNr();
var CheckifOrderNrExist = db.CarAnn.FirstOrDefault(x => x.OrderNr ==  OrderNumber);

while(CheckIfOrderNrExist != null)
{
   OrderNumber = loadOrderNr();
   CheckifOrderNrExist = db.CarAnn.FirstOrDefault(x => x.OrderNr ==  OrderNumber);
}

Also it is important to not create a Random instance inside a loop, because you could get the same result. Better to place the creation of the Random instance as class level variable
public class OrderDB
{
     private Random rnd = new Random();

     .... other class code....

    private string loadOrderNr()
    {
        // Do you really use the Db variable here? Otherwise you can remove it
        using (Db db = new Db())
        {
            // Random rnd = new Random();
            long part1 = rnd.Next(100000, 999999);
            long part2 = rnd.Next(1000, 9999);

            string OrderNr = "CA-" + part1 + "-" + part2;

            return OrderNr;

        }
    }
}


text:
Q: Find all closed subsets of a given X Let $X$ = {1, 2, 3, 4, 5} and $\tau$ = {$\emptyset$, {1}, {1,2}, {1,2,5}, {1,3,4}, {1,2,3,4}, $X$}. Show that $\tau$ is a topology and find all closed subsets of $X$.
I showed that $\tau$ is a topology via the definition, but I'm not quite sure whether I have found the correct closed subsets. My suggestions would be:
open sets: bascially all of $\tau$, so:
open sets = $\emptyset$, {1}, {1,2}, {1,2,5}, {1,3,4}, {1,2,3,4}, $X$
closed sets: I far I understand it, the closed sets are the complements of the members of $\tau$ (in regards to $X$), so:
closed sets = $X$, {2,3,4,5}, {3,4,5}, {3,4}, {2,5}, {5}, $\emptyset$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Flutter: Update specific screen using provider that's consumed in multiple screens I have a typical CRUD operation task: (List Sites, Add Site, ...)
I created a SitesProvider. In the same provider, I added 2 methods for add and edit. I was thinking to use the same provider in the 2 screens (ListSites and AddEditSite)
In the ListSites screen, it works fine. Here is the problem:

*

*I open the AddSite screen by clicking the AddButton in the ListSites screen

*Hit submit (did not enter data, simulating error case)

*The error gets displayed in the ListSites screen, not in the AddSite screen.

It makes sense. They both use the same provider, both screens are on the stack. It seems that the first one only consumes the state update and displays the error.
I use MultipleProviders approach that wraps the MaterialApp with all providers in the app.
Can we fix that without creating separate providers for each of the 2 screens?
EDIT:
I used provider.removeListener in the ListSites screen right before I open the AddEdit and it shows the error in the correct screen now. I still have to do some other tweaks to get it back to listen after I add. Not efficient I think but it is a step.

A: I ended up doing that:

*

*Added Another Field in the provider (stateType: list/addedit)

*Change the type per the screen I'm currently in
provider.stateType = UIStateType.add_edit;
await Navigator.push(context,
MaterialPageRoute(builder: (context) => AddEditSiteScreen()));
provider.stateType = UIStateType.list;

*in build(), I check for the type
sitesProvider = Provider.of(context);
if (sitesProvider.stateType != UIStateType.add_edit) return Container();


text:
Q: How update UI (ListView) when DB data recieved or button pressed I have a ListView that represents an order list, and a listAdapter that sets recieved data from DB to the listView, and I want to dynamically do:

*

*paint white if item is not selected or started

*paint green if item is selected (but not started)

*paint orange if item selected is started (button pressed)

*delete item if finish button is pressed

*(with paint I mean setBackground color of item)
**(Order have an atribute "state" to know if they are Started or not)
Currently I'm doing this only when buttons are pressed, and I want to also update  UI and repaint items when orders are received and if one order is started paint it
some code of OrdersActivity:
private void updateOrders() {
        if (!listItemIsSelected) {
            orderAdapter.clear();
            orderAdapter.notifyDataSetChanged();
            populateListView();
        } else {
            debugLog("item is selected, list not updated");
        }
    }

    private void populateListView() {
        try {
            // Read items from server
            Log.d("LSO", "Reading from Database");
            ListObtainer listObtainer = new ListObtainer(this);
            listObtainer.getTmOfsDTOList(user, orderAdapter); // this method returns list of objects from DB and populates adapter
        } catch (Exception e) {
            e.printStackTrace();
        }
        configureAdapter();
    }

    private void configureAdapter() {

    // Configure listview
    listView = (ListView) findViewById(R.id.lvOrdenes);
    listView.setAdapter(orderAdapter);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            try {
                OrderRO orderRO = (OrderRO) parent.getItemAtPosition(position);
                listItemIsSelected = true;
                lastChildSelected = currentChildSelected;
                currentChildSelected = (View) listView.getChildAt(position);
                uptadteUI();

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

        }
    });
}
private void uptadteUI() {

    try {

        if (lastChildSelected != null) {
            lastChildSelected.setBackgroundColor(getResources().getColor(R.color.transparent));
        }
        if (orderIsStarted) {  // Block scroll, disable start, paint item
            disableIniciarOrden();
            disableBotonSalir();
            enableTerinarOrden();
            currentChildSelected.setBackgroundColor(getResources().getColor(R.color.light_orange));
            listView.setEnabled(false);
        } else {// if there is no started order
            listView.setEnabled(true);
            enableBotonSalir();
            disableTerminarOrden();
            if (listItemIsSelected) {  // enable start, paint item
                enableIniciarOrden();
                currentChildSelected.setBackgroundColor(getResources().getColor(R.color.light_green));
            }
        }
    } catch (Exception e) {
        Log.e("error", "error updating UI" + e);
    }
}

   public class UpdateOrdersAsync extends AsyncTask {
        @Override
        protected Object doInBackground(Object[] params) {
            while (updateService == true) {
                try {
                    Thread.sleep(180000);

                } catch (InterruptedException e) {
                    e.printStackTrace();

                }
                publishProgress();

            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Object[] values) {
            //super.onProgressUpdate(values);
            debugLog(". . . calling list update");
            updateOrders();
        }
    }

This looks to me very dirty and I have a problem: if the DB changed and Adapter is updated I can receive an Order already started and I don't know how to paint it from activity, I'm new using custom adapters and I'm confused on what I should do, I can  paint the started orders directly in adapter but this breaks the logic I already did in activity(posted code) because I don't know from the activity wich orders are started(check the atribute of one item from activity).
Sorry if the question is difficult to understand or poorly explained, It's difficult to me to transmit my problem

A: So, you want to update the list of items on a ListView when you receive more information, correct?
I have modified your code a bit to enhance readability.
Lets say you have a list with the items :
List<Items> listItems = new List<Items>;
listItems.add(item1);
listItems.add(item2);
listItems.add(item3);

with an adapter associated to it. Then you just associated the adapter to your listView like :
ArrayAdapter<String> orderAdapter = new ArrayAdapter<String>(this,android.R.layout.listem_item, listItems);
listView.setAdapter(orderAdapter);

Now you have all your items. Lets say those items change like this :
listItems.remove(item1); // you remove item1
listItems.add(item4); // and you add item4

Now you want to inform the adapter that you have changed the base data.
You can do it like :
listView.getAdapter().notifyDataSetChanged();

What I strongly recommend is that you associate the background color to the Model instace of the row instead of the its view. This way, if the view gets re-drawn, the information will still be store inside the Model.
public class OrderRo
    ...
    String color = "red";
    boolean isOrderStarted = false;
    ...

    ...
    public boolean isOrderStarted(){
        return isOrderStarted;
    }

    public void setIsOrderStarted(boolean isOrderStarted){
        this.isOrderStarted = isOrderStarted;
    }

    public String getColor(){
        return this.color;
    }

    public void setColor(String color){
        this.color = color;
    }
    ....

and
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            try {
                OrderRO orderRO = listView.getAdapter().getItem(position);
                orderRO.setColor("orange");
                orderRO.setIsOrderStarted(true);
                uptadteUI(orderRO, (View) listView.getChildAt(position));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
private void uptadteUI(OrderRO order, View selectChild) {
    try {
        if (selectChild != null) {
            selectChild.setBackgroundColor(getResources().getColor(R.color.transparent));
        }
        if (order.isOrderStarted()) {  // Block scroll, disable start, paint item
            disableIniciarOrden();
            disableBotonSalir();
            enableTerminarOrden();
            selectChild.setBackgroundColor(getResources().getColor(R.color.light_orange));
            listView.setEnabled(false);
        } else {// if there is no started order
            listView.setEnabled(true);
            enableBotonSalir();
            disableTerminarOrden();
            if (listItemIsSelected) {  // enable start, paint item
                enableIniciarOrden();
                selectChild.setBackgroundColor(getResources().getColor(R.color.light_green));
            }
        }
    } catch (Exception e) {
        Log.e("error", "error updating UI" + e);
    }
}

A: I think you should keep state in your OrderRO class.And when state is changed,call notifyDataSetChanged.In getView method,paint view with different colors according to the state in OrderRO.

A: Add status attribute to OrderRO class like started, pressed etc. In your adapter, where inflate the listview items check this status and set view color. On onItemClick method change item status and call adapter.notifyDataSetChanged().

A: first, you have to fill the data source that ListView gets the data from, and then, call the method:
listView.getAdapter().notifyDataSetChanged();

then the list will get all the new data filled in the data source


text:
Q: got C2758 error for my third party call I declared my class as follows in my "first.h" :
class MyClass
{
public:
    MyClass ( cv::Mat& _model ) : tmpM ( _model )
    {
    };
private:
cv::Mat& tmpM;
}

then in "first.cpp", I used it like this:
MyClass::tmpM ( cv::Mat& _model )
{
    ...
}

Then I included this "first.h" in my "second.h", and include this "second.h" in my "third.h", then in my "third.cpp" I tried to do this:
cv::Mat testMat ( height, width, CV_8UC3 );
tmpM myM ( testMat );

Then I got errors saying:

'MyClass::tmpM': not a function
error C2512: 'MyClass': no appropriate default constructor available
IntelliSense: declaration is incompatible with "cv::Mat& MyClass::tmpM"
IntelliSense: explicit type is missing ('int' assumed)

Before you ask, I have to say I indeed searched and asked about this, but still couldn't solve it. I am a learner, so could someone help me out of this? thank you.

A: The errors you got are quite explicit.
'MyClass::tmpM': not a function

Means that tmpM is not a function and it comes from the declaration
MyClass::tmpM ( cv::Mat& _model ) {
    ...
}

I think you are confused and wanted to declare the constructor, in which case you should have written in your header file (i added a default constructor)
class MyClass {
public:
    MyClass ( cv::Mat& _model );
private:
    MyClass(); // Private default constructor
    cv::Mat& tmpM;
}

And then in your cpp file
MyClass::MyClass( cv::Mat& _model ) {
    // Do things
}

This will solve your second error message:
error C2512: 'MyClass': no appropriate default constructor available

Your third file is also problematic because in line
tmpM myM ( testMat );

tmpM is not a type. I think you meant
MyClass myM( testMat );

and that's what the two last errors are telling you.

A: You declared this:
cv::Mat& tmpM;

and redeclared it thusly:
MyClass::tmpM ( cv::Mat& _model )

In the first, you declare on object. In the second you declare a function.
Fix one or the other so that they match.


text:
Q: Sign in with Instagram I need to make sign in with Instagram on my web site.
But its looks impossible in Instargam Graph API.
I tried to to a sign in with Facebook and take information about Instagram,
but i do not know how.
I just need to have a real not fake accounts username. That is all.
How can i do it?

A: The suggested answers are correct. If you want to use the Instagram Graph API to login, you actually use a "Connect with Facebook" button because the Insta Graph API is powered by Facebook's OAuth.
A lot of the old Instagram (legacy) API is being sunset. You may still be able to build a simple OAuth, but it won't really give you much data beyond an auth token.
https://www.instagram.com/developer/authentication/

A: It appears all of the links above are broken - as far as I can tell, as of 2021-11-01 this can only be done via Facebook, still researching to see if Oauth with Instagram credentials VIA Facebook is possible.


text:
Q: c# unit testing file not recognised I was following a tutorial to learn some unit tests
I have installed a all libraries needed for it
and generated another test project based on the project
but it still looks like not picking it up.
'''
using System;
using NUnit.Framework;
using UnitTesting.Dundamentals;

namespace reservation.unitTest
{
    [TestFixture]
    public class Program
    {
        [Test]
        public void Test1()
        {
            Assert.Pass();
        }
    }
}

'''


text:
Q: Why would Caesar send Crismus Bonus to Outer Mongolia? In Asterix and the Gauls, Caesar says that he will send Crismus Bonus to Outer Mongolia, to deal with a "Barbarian Rebellion".

As far as I know, Outer Mongolia is quite far away from the borders of the Roman Empire at the time? The Romans might have have had some trade with the Far East, but certainly they would not be concerned with rebellions, or be sending troops there?
Or is that the point? Sending Crismus Bonus and his men to Mongolia means he will be killed by the nomads there? Or is Ceasar just joking?

A: This question probably belongs somewhere like Literature rather than here as there isn't strictly a canon response.
The translations of Asterix are highly localised, even the character names are language specific rather than being translations.
In terms of the plot, what you're looking at here is a person whose loyalty to Caesar has been called into question. Caesar's response to this is to post him and his men (who are likely loyal to him rather than Caesar) to Outer Mongolia.
Outer Mongolia had a specific meaning in English culture at the point in time when these comics were being translated. It was considered to be the most remote and hardest to reach place in the world. You may find in other languages that the actual location of the posting is different.
Ultimately Caesar is disposing of a problematic person by sending him as far away as possible using an idiomatic location rather than a historically accurate one.

A: Might be worth pointing out that these jokes about Outer Mongolia are somewhat based on actual historical events: Vyacheslav Molotov was the Soviet foreign minister from 1939 to 1949 under Stalin and again from 1953 to 1956. He was made the Soviet ambassador in Mongolia after Khrushchev came to power and served there from 1957 to 1960 or so.
If this question is about the first Asterix comic, Molotov's "appointment" would have been quite current affairs (Asterix the Gaul first being published around 1960).

According to the comments below the OP, the French version has "Mongolie inférieure" which looks like a misspelling for "Mongolie intérieure", i.e. Inner Mongolia, which is part of China. This makes the connection to Molotov somewhat less likely. On the other hand Inner Mongolia and Mongolia get mixed up quite frequently, and this may just be another example of this confusion.


text:
Q: Cordova Build on Android Not Using Code from WWW Folder I'm using cordova to package up a pre written angular js application by placing the contents of the app into the www folder inside the cordova sturcture and running the following commands:
cordova platform add ios

cordova build ios

cordova emulate ios

The app then loads on the ios emulator, but instead of the app content as I would expect to see, it shows the hello cordova index file. I have done the exact same thing for android and it works perfectly on that and shows the app correctly. Any help with finding out why the default cordova index page is still shown would be great thanks.

A: Managed to get it working. When I built the code using cordova, I then opened the xcode.proj file in xcode, and that has done something to some of the files, and it was causing the app to crash at the splash screen. This is why I thought it was not using the www/ code as the splash screen is almost identical to the hello cordova default index file.
Using the cordova emulate command line option to run the app without touching xcode allows the app to run correctly.


text:
Q: Password Protect HTML5 Offline Application Directory I have an HTML5 app which is capable of running offline.  However, I need to password protect the directory this app resides in to only allow access to authorized users.  Initially I was using a PHP login page which set a cookie (outside of the app directory) then redirected to the app directory.  The app (JavaScript) checks for the cookie and if it's there it lets the user run the app.  If not, it redirects them back out of the app directory.
The problem with this method is that all of the files in the directory are still accessible if referenced directly (which I don't want).  I do not want users to have to authenticate every time they hit the directory (it's a one-time authentication process; the cookie is there so that they never have to type their username/password again), and I also want to have a stylized login form (i.e. not using the default browser login box for http authentication).
Finally, because this is an offline HTML5 app, I can't include any PHP code in the app itself.
Any suggestions?

A: That doesn't sound like something you could do from Javascript. The script would need access to the file system to be able to restrict access to the folder, wouldn't it?
Unless this feature is exposed by the browser via a javascript API, I don't think it will be possible. It sounds like it would be a useful feature though.
Perhaps you could encrypt vital data, but apart from slowing down the application, I'm not sure what good it would do, since all the necessary keys would have to be stored locally as well...
Since the general rule of security on the web is that you can never ever rely on anything that happens client-side (e.g. in Javascript) without a double check on the server-side, this will of course pose a problem when the app is running offline and the server-side is not available :(
Looking at the "make Javascript redirect if the cookie exists" problem, unless I'm mistaken, it would be trivial for a malicious user to edit the Javascript, using for example Firebug, to redirect in any case.
EDIT: By the way, what level of security are you looking for? The "mom won't be able to accidentally access my account"-level (which it sounds like you already achieved), or the "no one, except maybe the NSA, should be able to hack it"-level?


text:
Q: PHP background process I've wrote a php irc bot, but i need it to work in the background. With this there'd be no quits or so. What is the best way to do this?
Thanks and Regards.

A: Take a look at the following website. There is a pretty descend explanation on how to write PHP daemons.
http://kevin.vanzonneveld.net/techblog/article/create_daemons_in_php/

A: Run it in screen, then detach.  You can then quit the terminal and re-attach to the screen session later.

A: I use something similar:
nohup php /path/to/script.php > /dev/null 2> /dev/null&


text:
Q: How to have x-Axis in years if input is in time, in SVG d3 area chart? var input = [{1307555600000,786},{1306693800000,506},{1306693800040,986}];
// time, price
I plotted it on Area chart, but on X-Axis I don't want to show all the entities, as input data is large, it is not possible to see all. Instead I just want to show year range.
e.g. x-Axis:


text:
Q: How to insert unique items into vector? I have a type called Neighbors:
typedef vector<pair<data,int>> Neighbors;

and here's data:
struct data
{
    int par[PARAMETERS];
    int cluster;
    bool visited;
    bool noise;
};

I'm trying to write a function that inserts values from _NeighborPts to NeighborPts (but only ones that aren't already in NeighborPts):
void insert_unique(Neighbors* NeighborPts, const Neighbors& _NeighborPts)
{
    Neighbors_const_it _it = _NeighborPts.begin();
    while(_it != _NeighborPts.end())
    {
        if(/* _it->first.par isn't in *NeighborPts */)
            NeighborPts->push_back(*_it);
        ++_it;
    }
}

and i already have a function equal() which checks if 2 pars are equal.
So do i have to iterate through NeighborPts in a while loop and check if the item is found? or could i use some built-in find or find_if function to do that for me?

A: You can maintain a sorted vector. Use the lower_bound function from C++ algorithms to locate the insert position each time. If the element at the insert position is equal to the insert element then you have a duplicate.
The performance of this will be pretty good unless the vector grows too large. The point at which you're better off using a set or a unordered_set varies and you'd need to benchmark to find it.

A: Your current solution with vector will run in O(N^2) time, which is not efficient.
For efficient solution an associative container will be great - such as std::set .
Also you will need to have some "operator less" (instead of "equal ()"), to pass to the function.
template < class T,                        // set::key_type/value_type
           class Compare = less<T>,        // set::key_compare/value_compare
           class Alloc = allocator<T>      // set::allocator_type
           > class set;

So you need to provide compare class
struct data_compare {
    bool operator() (const data& lhs, const data& rhs) const{
      //...
    }
};

set<int64_t, data_compare> exising_items;

You may define such a function, or override "operator <" in struct data.
insert all "data" from "_NeighborPts" into a set - O(N*log(N)) time
std::set  other_items;
in a loop - iterate _NeighborPts and insert data elements
other_items.insert (_NeighborPts [i]);

std::set  my_items;
in a loop - iterate _NeighborPts and insert data elements
my_items.insert (NeighborPts [i]);

Now you need to compare between the 2 sets:
You can do it using std::set_intersection
. or construct a simple loop on the set "my_items"
if the current element in other_items isn't in _my_items, insert it in "NeighborPts"
this solution will run in O(Nlog(N)) time

A: *

*There is no getting around iterating over the items in _NeighborPts.

*As long as you are using an std::vector, there is no getting around the check to determine whether an item is in NeighborPts before inserting in it.

You can make the code a little bit easier to read by using std::for_each and a functor.
struct UniqueItemInserter
{
   UniqueItemInserter(Neighbors* neighborsIn) : neighbors(neighborsIn) {}

   void operator(pair<data,int> const& item)
   {
     if ( std::find(neighbors->begin(), neighbors->end(), item) != neighbors->end() )
     {
        neighbors->push_back(item);
     }
   }

   Neighbors* neighbors;
};

void insert_unique(Neighbors* NeighborPts, const Neighbors& _NeighborPts)
{
    std::for_each(_NeighborPts.begin(), _NeighborPts.end(), UniqueItemInserter(NeighborPts));
}


text:
Q: Any good cfml Shopping Cart app? Any good cfml Shopping Cart app?  Tried using one?  What's your experience with it?

A: There are few carts listed in Arehart's list. Haven't tried any, so can't give advices.

A: I've used SiteSirector by QuillDesign before, and tried a few others. SiteDirector was the best I've seen. It's pretty easily extended and has a lot of features out of the box. I would recommend you take a look at it.

A: I have been using Cartweaver so far.  It has been pretty good.  If you are integrating it with an existing site you will have to merge the application cfm/cfc's which can get a bit hairy.
Cartweaver is well written otherwise though.  I hope in future versions they will make the entire cart into cfc's, but it is a great value for the dollar.

A: My needs have allways required completly custom applications; however, this package has allways interested me: http://www.cfwebstore.com/

*

*Great Price

*Open Source Code

Good luck.


text:
Q: Not save image in PDF getting error in node/expressJs I have expressJs application i am going to save image in PDF file Here is my code to save image in pdf file
exports.getPDF = function (req, res) {
  doc = new PDF();
  doc.pipe(fs.createWriteStream('./public/Competition.pdf'));
    db.competitions.find({where: {id: req.params.competitionId}}).success(function(competition){

    //MY_URL_IS = http://d16dgegkincj5i.cloudfront.net/1_2_brandLogo_new_update_code-thumbnail.png

    var options = {
        host: 'http://d16dgegkincj5i.cloudfront.net',
        port: 80,
        path: '/1_2_brandLogo_new_update_code-thumbnail.png'
    }

    var request = http.get(options, function(res){
      var imagedata = ''
      res.setEncoding('binary')

      res.on('data', function(chunk){
        imagedata += chunk
      })

      res.on('end', function(){
        fs.writeFile('./public/Competition.pdf', imagedata, 'binary', function(err){
          if (err) throw err
          console.log('File saved.')
        })
      })
    })
  }).error(function(error){
  });
};

I am getting error
events.js:85
      throw er; // Unhandled 'error' event
            ^
Error: getaddrinfo ENOTFOUND

when i get image by http.get and after write to pdf file it will give error and not writing image

A: The error:
Error: getaddrinfo ENOTFOUND

means that the url was not found.
Just removing the http:// from your host should do the job, like:
var options = {
    host: 'd16dgegkincj5i.cloudfront.net',
    port: 80,
    path: '/1_2_brandLogo_new_update_code-thumbnail.png'
}


text:
Q: find all lines that contains an email address I try to save all the lines from an file that contains an email adress.
Exemple, file.txt:
Lorem ipsum dolor email1@mail.com sit amet,
consectetur adipiscing elit
sed do eiusmod tempor incididunt ut labore
et dolore magna aliqua. Ut enim ad minim veniam
email2@gmail.com quis nostrud exercitation ullamco
laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat
non proident email3@yahoo.com
sunt in culpa qui officia deserunt mollit anim id est laborum.

From file.txt i want to save only the lines :
Lorem ipsum dolor email1@mail.com sit amet,
email2@gmail.com quis nostrud exercitation ullamco
non proident email3@yahoo.com

I tried something, but regex is giving me a big headache :(
import re

def saveresults(var):
    with open("email-lines.txt", 'a') as target:
        target.write(var+ '\n')
    target.close()
    print " line writed: ", var

file = "test.txt"

emaillines = [linie.rstrip('\n') for linie in open(file)]

for i in emaillines:
    a = re.findall(r"(^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,63}$)", i)
    print a

What i`m doing wrong ?

A: Your regular expression starts with ^ (start-of-string anchor) and ends with $ (end-of-string anchor), which means the email address must be the entire line, with nothing else on the line, for the regex to match. You're also using [A-Z] but not a-z, and you aren't using the case-insensitive flag, which means that lower-case letters in the email addresses won't work.
Change to:
pattern = re.compile(r"(?i)[\w.%+-]+@[a-z\d.-]+\.[a-z]{2,63}")
for i in lines:
    if pattern.search(i):
        print(i)

(?i) makes the regex case-insensitive, and a character set containing [0-9A-Za-z_] means those characters can all be replaced with \w in most situations.

A: Using regular expressions, you can use something like this:
result = []
for line in emaillines:
    if re.search (r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,10}', line) is not None:
        result.append(line)

The problems with your regular expression were :

*

*[A-Z] matches only uppercase letters

*The caret at the beginning was wrong

*You were forcing the email to be at the end of the line with $
I also changed the power from {2, 63} to {2, 10}. You were allowing someone to put up to 63 letters after the dot. Maybe that was intentional though, change that back in that case.
Also, you could shorten the regular expression to:
r'[\w.%+-]+@[a-zA-Z\d.-]+\.[a-zA-Z]{2,10}'


text:
Q: Find value of first occurrence in following rows after certain value in row in Pandas I would like to find the value of the first occurrence after certain value in row.
Test dataframe:
df = pd.DataFrame({'part': ["Toyota", "basic", "upgraded", "Skoda", "basic", "upgraded", "VW", "basic", "upgraded"],
                   'id': ["", 1, 2, "", 4, 5, "", 6, 7]})

       part id
0    Toyota
1     basic  1
2  upgraded  2
3     Skoda
4     basic  4
5  upgraded  5
6        VW
7     basic  6
8  upgraded  7

I am looking for the value in the "upgraded" row that is after "Skoda" - thus 5.
Any tips how to do this in Pandas dataframe?
Thank you.

A: You can use boolean indexing with masks:
# locate "upgraded" items
m1 = df['part'].eq('upgraded')

# mask values after the first "Skoda"
m2 = df['part'].eq('Skoda').cummax()

# find all "upgraded" that are after first "Skoda"
# and slice first occurrence
df[m1&m2].iloc[0]

output:
part    upgraded
id             5
Name: 5, dtype: object


text:
Q: How to checkout merge request locally, and create new local branch? I have GitLab repository there and I need to test every merge request locally, before merging to the target branch.
How can I pull/fetch merge request as a new branch?

A: *

*Pull merge request to new branch
git fetch origin merge-requests/REQUESTID/head:BRANCHNAME
i.e
git fetch origin merge-requests/10/head:file_upload

*Checkout to newly created branch
git checkout BRANCHNAME
i.e (git checkout file_upload)
OR with single command
git fetch origin merge-requests/REQUESTID/head:BRANCHNAME && git checkout BRANCHNAME
i.e
git fetch origin merge-requests/18/head:file_upload && git checkout file_upload

A: This is also documented in GitLab online documentation :
https://docs.gitlab.com/ee/user/project/merge_requests/reviewing_and_managing_merge_requests.html#checkout-merge-requests-locally-through-the-head-ref
They supply this script (git alias) :
[alias]
    mr = !sh -c 'git fetch $1 merge-requests/$2/head:mr-$1-$2 && git checkout mr-$1-$2' -

Then you can use this command :

git mr origin 4

So a new local branch mr-origin-4 will be created.

A: You can also add the line
fetch = +refs/merge-requests/*/head:refs/remotes/origin/merge-requests/*

to your .git/config to have git fetch fetch all merge requests.

A: There is a Check out branch button in GitLab.

Then you can copy comments from Step 1. Fetch and check out the branch for this merge request.
git fetch <repo> <branch>
git checkout -b <branch>


text:
Q: Zimbra outgoing email forwarding/ redirecting from internal to external domain How can I automatically forward outgoing emails to a different domain?
As an example, a user sends an email to 1234564@fax.mydomain.com and I want the exact email forwarded outside mydomain.com to 1234564@example.com.
Note There are no accounts on the local Zimbra server under the fax.mydomain.com subdomain and the prefix 123456 will not be constant, e.g. it will change depending on fax recipient's number.
I know that the easy thing would be to have users send the emails directly to the @example.com domain, but I'd rather have them use the local fax.mydomain.com domain and have the email forwarded/ redirected.
I don't know whether to use postfix transports, procmail or something within zimbra.
I think that postfix transports requires that I specify a different SMTP server, e.g. otherdomain.com     :[smtp.otherdomain.com]
With procmail I think I would need to use a pipe, but I've never used procmail.
I've tried to find a feature within Zimbra and I tried to zmprov md fax.mydomain.com zimbraMailCatchAllForwardingAddress @example.com but the emails bounced.
How do I best achieve this?

A: Only forwarding is probably not enough, you also have to masquerade the domain name, otherwise the example.com mail server probably rejects the mail and this is what you see as bounces.
For us it works like this:
zmprov md fax.mydomain.org zimbraMailCatchAllAddress @example.com
zmprov md fax.mydomain.org zimbraMailCatchAllForwardingAddres @example.com
zmprov md fax.mydomain.org zimbraMailCatchAllForwardingAddress @example.com
zmprov md fax.mydomain.org zimbraMailTransport smtp:mail.example.com
zmprov md fax.mydomain.org zimbraMailCatchAllAddress @fax.mydomain.org zimbraMailCatchAllCanonicalAddress @example.com

Mails arriving at example will still have the To:- field as xx@fax.mydomain.org but the envelope is correct.


text:
Q: characters does not print in json i can't print the characters in encode. even i tried the ways ;
echo json_encode($user,JSON_UNESCAPED_UNICODE);

or iconv("ISO-8859-1", "UTF-8",$user)
Can you help me ? here codes;
$user = "ğığığı";
echo json_encode($user);

thanks for help.

A: You should use
echo json_encode($user,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
You can see it work here http://sandbox.onlinephpfunctions.com/code/05d859c4b23417e54aad12fd96c8548949075c67


text:
Q: Use NumberFormatException with boolean variable Is there a way to throw the error message if the user input is blank? I can't use catch (NumberFormatException e) because of the boolean variable.
 boolean numberSet;
 do {
    numberSet = jerseys[position].setNumber(Integer.parseInt(JOptionPane.showInputDialog("Enter number of jersey")));
    if (!numberSet) {
       JOptionPane.showMessageDialog(null, "Number cannot be less than 0.");
    }
 } while (!numberSet);

setNumber method
   public boolean setNumber(int number) {
      if (number >= 0) {
         this.number = number;
         return true;
      }
      else {
         return false;
      }
   }


text:
Q: Preload with Ecto with subquery and using a join from the main query I'm using Ecto to request data from the database, and I've used the following code to preload the cats filtered by price_discount.
Item
|> join(:inner, [i], c in Cat, c.food_category_id == i.id)
|> where([i, c], is_nil(c.price_discount))
|> preload([i, c],
  [
    cats: c,
    cats: :houses
  ])

This works great, but now I want to order Houses by id, so I was hopping this work:
Item
|> join(:inner, [i], c in Cat, c.food_category_id == i.id)
|> where([i, c], is_nil(c.price_discount))
|> preload([i, c],
  [
    cats: c,
    cats: [
      houses: from(h in Houses, order_by: h.id)
    ]
  ])

But it doesn't, this is the error:
from(h in Houses, order_by: h.id()) is not a valid preload expression. preload expects an atom, a list of atoms or a keyword list with more preloads as values. Use ^ on the outermost preload to interpolate a value

The only post to work is to just use one of the following:

*

*Use cats: c without the order

*Use houses: from(h in Houses, order_by: h.id)
The following works, using ^:
Item
|> join(:inner, [i], c in Cat, c.food_category_id == i.id)
|> where([i, c], is_nil(c.price_discount))
|> preload([i, c],
  ^[
    cats: [
      houses: from(h in Houses, order_by: h.id)
    ]
  ])

Is this a bug in Ecto ?

A: When you want to provide a custom query to a preload and also to its nested preloads, you can use the tuple syntax, where the first element is the main query and the second element is a list of preloads just like you'd have at the top level.
What you want can be achieved with this:
|> preload([i, c], [cats: {c, houses: ^from(h in Houses, order_by: h.id)}])

A: The solution that I found was to split |> preload() in two.
Item
|> join(:inner, [i], c in Cat, c.food_category_id == i.id)
|> where([i, c], is_nil(c.price_discount))
|> preload([i, c], [cats: c])
|> preload([cats: [houses: from(h in Houses, order_by: h.id)]])


text:
Q: Biber doesn't work in MacOS M1 but does work in on Windows I am new to LaTex writing a research paper. I am using MikTex and VSCode
I am using \usepackage[backend=biber, style=apa]{biblatex}. This correctly generates references & bibliography on my windows computer, but when I work on my MacOS M1 laptop, it does not.
I have already updated all packages to the latest version. I have also tried adding the code below in settings.json of VSCode.
{
    "name": "biber",
    "command": "biber",
    "args": [
        "%DOCFILE%"
    ]
}

However, running PDFLatex-->biber-->PDFLatex x2 does not work either.
Is there anyway that my installation of MikTex/VSCode/Biber is incorrect for MacOS?


text:
Q: How to find the height and width of screen in android I have a class called crate where i would like to find the height and width. to do this I am using:
public class Crate {
    public int acrossCrate;
    public int upDownCrate;

    public Crate(Context context) {

    DisplayMetrics metrics = context.getResources().getDisplayMetrics();
    int width = metrics.widthPixels;
    int height = metrics.heightPixels;
}
}

But I have another class called draw which calls the crate class, and when i use the Context context in crate it gives an error when calling it in the draw class:
public class Draw extends View {
    float x, y;
    Paint red = new Paint();
    Paint green = new Paint();
    Paint black = new Paint();
    Paint blue = new Paint();
    Bitmap player;
    Bitmap crate;
    int rectSide = 1000;

    Player thePlayer = new Player();
    Crate theCrate = new Crate();//<-- ERROR when i use Context context

Im really stuck and if anyone knows how to do this and could help me that would be great.

A: Call like this
 Crate theCrate;

and in constructor
theCrate = new Crate(context);

A: Once try the following methods
// Get screen width
public static int getScreenWidth(Context c) {
    DisplayMetrics dmetrics = new DisplayMetrics();
    ((Activity) c).getWindowManager().getDefaultDisplay()
            .getMetrics(dmetrics);
    return dmetrics.widthPixels;
}

// Get screen height
public static int getScreenHeight(Context c) {
    DisplayMetrics dmetrics = new DisplayMetrics();
    ((Activity) c).getWindowManager().getDefaultDisplay()
            .getMetrics(dmetrics);
    return dmetrics.heightPixels;
}

Hope this will helps you.

A: Its easy...if Your View class is the Size of the full screen just use the getWidth() and getHeight() methods of this class
Otherwise get it from the windowmanager methods like other suggested


text:
Q: Find the conditional and marginal densities? I'm getting lost in notation here.
We have $f_X(x)=xe^{-x}$ and we have a new random variable, $Y$, which is uniform from $(0,X)$.
We want three things:

*

*Marginal density for $Y$

*Conditional density for $X$ given $Y$

*Joint density function.
From the given information, the conditional density of $Y$ is $f_{Y|X=x}(y)=\frac{1}{x}$.
Since $f_{XY}=f_{X|Y}f_Y$, then $f_{XY}=f_{Y|X}f_X=\frac{1}{x}xe^{-x}=e^{-x}$.
So, then isn't the marginal density of $Y$ the value $e^{-x}$ integrated with respect to $y$? i.e., $f_Y(y)=ye^{-x}-1$.
Then, for the conditional density $X|Y$, we have:
$f_{X|Y}=\frac{f_{XY}}{f_X}=\frac{ye^{-x}-1}{xe^{-x}}$.
Is this even close to right?


text:
Q: Getting count and list of ids using ElasticsearchTemplate in spring-data-elasticsearch I am using spring-data-elasticsearch for a project to provide it with full text search functionality. We keep the real data in a relational database and relevant metadata along with respective id in elasticsearch. So for search results, only id field is required as the actual data will be retrieved from the relational database.
I am building the search query based on search criteria and then performing a queryForIds():
    SearchQuery searchQuery = new NativeSearchQueryBuilder()
            .withIndices(indexName)
            .withTypes(typeName)
            .withQuery(getQueryBuilder(searchParams))
            .withPageable(pageable)
            .build();

    return elasticsearchTemplate.queryForIds(searchQuery);

If I also need the total count for that specific searchQuery, I can do another elasticsearchTemplate.count(searchQuery) call, but that will be redundant as I understand. I think there is a way to get both the list of id and total count by using something like elasticsearchTemplate.queryForPage() in a single call.
Also, can I use a custom class in queryForPage(SearchQuery query, Class<T> clazz, SearchResultMapper mapper) which is not annotated with @Document? The actual document class is really big, and if I am not sure if passing large classes will cause any extra load on the engine since there are over 100 fields to be json mapped, but all I need is the id field. I will have a .withFields("id") in the query builder anyway.

A: If you want to prevent two calls to elasticsearch, i would suggest to write an custom ResultsExtractor:
SearchQuery searchQuery = new NativeSearchQueryBuilder().withIndices(indexName)
        .withTypes(typeName)
        .withQuery(queryBuilder)
        .withPageable(pageable)
        .build();
SearchResult result = template.query(searchQuery, new ResultsExtractor<SearchResult>() {

    @Override
    public SearchResult extract(SearchResponse response) {
        long totalHits = response.getHits()
                .totalHits();
        List<String> ids = new ArrayList<String>();
        for (SearchHit hit : response.getHits()) {
            if (hit != null) {
                ids.add(hit.getId());
            }
        }
        return new SearchResult(ids, totalHits);
    }
});
System.out.println(result.getIds());
System.out.println(result.getCount());

where SearchResult is a custom class:
public class SearchResult {

    List<String> ids;
    long count;

    //getter and setter
}

This way you can get the information you need from the elasticsearch SearchResponse.
Regarding your second question: As far as I can see, when calling queryForPage(SearchQuery query, Class<T> clazz, SearchResultMapper mapper)
the passed class is not checked for the @Document annotation. Just try it out!

A: One may also consider using AggregatedPage<T>. You can get the total number of records, total pages, current page records, etc. just like in Pageable<T>.
SearchQuery searchQuery = new NativeSearchQueryBuilder().withIndices(indexName)
        .withTypes(typeName)
        .withQuery(queryBuilder)
        .withPageable(pageable)
        .build();

AggregatedPage<ElasticDTO> queryResult = elasticsearchTemplate.queryForPage(searchQuery , ElasticDTO.class);


text:
Q: Counting grouped records from multiple tables there is a column comment_id of a table called pic_alb_love which i'd like to add to the query below but i don't know how.  Actually what i want to do is to count the total comment_id of the table pic_alb_love.
SELECT users_pics.wardrobe,
     profile.fname,
     users_pics.pic,
     users_pics.u_pic_id,
     users_pics.email,
     users_pics.make,
     users_pics.designer,
     photo_comment.comment,
     max_photo_comment.count_pic_id
FROM dbo.users_pics
INNER JOIN profile
    ON users_pics.email = profile.email
LEFT Join (SELECT pic_id
                ,MAX(comment_id) max_comment_id
                ,COUNT(pic_id) count_pic_id
           FROM photo_comment
           GROUP BY pic_id
          ) max_photo_comment
    On users_pics.u_pic_id = max_photo_comment.pic_id
LEFT Join photo_comment
    On max_photo_comment.pic_id = photo_comment.pic_id
        AND max_photo_comment.max_comment_id = photo_comment.comment_id
WHERE users_pics.wardrobe = MMColParam
    AND users_pics.email = MMColParam2
ORDER BY u_pic_id asc

these are the various fields of the table pic_alb_love:
(comment_id,pic,love_com, wardrobe, email
    ,com_name,resp_email, play_count, com_stat)

A: LEFT JOIN (SELECT Pic
              ,Count(*) [CommentCount]
           FROM pic_alb_love
           GROUP BY Pic) c
    ON c.Pic=u_pic_id

Assuming that pic_alb_love.pic is the FK on the table...
Use [CommentCount] in the select list.


text:
Q: Cypher zip collections If I have two collections, how might I zip them together?
with [1,2,3] as nums, ['a', 'b', 'c'] as letters
... wat do? ...
return zipped // [{a: 1}, {b: 2}, {c: 3}]

A: It may not be possible to dynamically assign map keys (e.g., using the items in letters). But this query will return something similar to what you want (using collections instead of maps):
WITH [1,2,3] as nums, ['a', 'b', 'c'] as letters
RETURN EXTRACT(i IN RANGE(0, LENGTH(nums) - 1) | [letters[i], nums[i]]) AS result;

The result is:
[["a",1],["b",2],["c",3]]


text:
Q: Physical origin of coisotropic branes The paper "Remarks on A-branes, Mirror Symmetry, and the Fukaya category" develops the possibility of A-model open strings ending on a coisotropic submanifold equipped with a holomorphic transverse structure of the underlying target space.
On the other hand, it is possible to identify non-perturbative corrections to $A$ and $B$ models when topological string theory is embedded into physical string theory [1] [2] as coming from the full theory; examples are the $D(-1)$ and $D1$ instantons of the $B$ model as "descending" from its full IIB counterparts [1],  the non-perturbative completion of the $A$ model counting $D6/D2/D0$ bound states [3], A-model lagrangian branes "descending" from $M5$-branes wrapping lagriangian cycles etc. I was wondering to know if it is possible to have a similar interpretation for coisotropic branes.
Consider the critical $A$-model on a Calabi-Yau threefold with one space-filling coisotropic brane embedded into full string theory as in the section one of [1].
Question: Does the coisotropic brane "descend" from a brane of the physical superstring?


text:
Q: How do I determine if 2 types of data are meaningfully related? I've been asked to see if there's a meaningful relationship in the 5yrs of data we have that is worth putting more research effort into. Particularly, does a relatively small investment in x (<1,000/yr) decrease impact of a much larger possible cost in y (>10,000/yr)?
We have 1,000s of entries. Some entries were invested in, others were not. Some resulting costs in the future were >10,000, and others were 0. There are many categories of investments and sometimes multiple ones were used.
We are most curious about 1 of the investment categories.
Besides directly calculating means, variances and correlation, what other statistics might be useful?
Are the statistics I mentioned even useful without transforming the data somehow like with logs?
We're interested in costs but I thought about also looking at the frequency of the investments and the frequency of the future costs. Good idea?
Am I even approaching this the right way?!??!
I don't need to go as far as modeling (that's for the future). I'm not strong with statistics. Appreciate the help.

A: Without further details it's hard to give a clear answer. And there's often not a 'right' way to do it anyway.
However, it sounds like what you may be interested in is whether investments at one time of less than \$1000 yield a cost savings of at least \$10,000 at some point in the future. If this is what you're going for then you can view the problem as count data and make a table that looks kind of like

|                 | Low Savings | High Savings |
|-----------------|-------------|--------------|
| Low Investment  | a           | b            |
| High Investment | c           | d            |
From this you can measure association using a $\chi^2$ or permutation test for instance.


text:
Q: PhpStorm, Yii2 Basic and Codeception I have configuration:

*

*Open Server 5.2.8 (WAMP)

*PhpStorm 2017.3.4

*Yii 2.0.14 basic

I added to the %PATH% path to PHP and to the Codeception folder:

In the PhpStorm terminal I launched the codecept run command and everything looks good. But the Windows terminal does not maintain colors therefore I wanted to launch tests through PhpStorm.

I made such settings for PHPUnit and Codeception (from Yii2\vendor):

But for some reason I receive such error:

A: You are missing the dependency for phpunit, add the following to your composer.json
"require-dev": {
    "phpunit/phpunit": "3.7.*"
},

and run
composer update

A: Answers here and here. Thanks to @panosru.
Just download new version PHPStorm 2017.3.6.


text:
Q: Ubuntu 16.10 booting in emergency mode after upgrade from 16.04 Ubuntu 16.10 on my Lenovo G500 is booting in emergency mode after upgrade from 16.04. The previous upgrades worked just fine (14.04 to 15.04 to 15.10 and so on).
Things I already tried:

*

*Attempt 1:

*

*Booted using Live Ubuntu 16.04 DVD.

*Started a terminal and did a file check on the my root partition i.e:  e2fsck -pvf /dev/sda9

*Rebooted from HDD
Result: Booted in emergency mode

*Attempt 2

*

*Booted from Live Ubuntu 16.04 DVD

*Did a tune2fs -l /dev/sda9 | grep -i check, turned out fsck was last performed in July 2016.

*Mounted /dev/sda9 and created a file forcefsck in `/´ directory

*Rebooted from HDD.

Result: Booted in emergency mode.
After rebooting the screen looks like this:

Tune2fs results look like this:

I am out of ideas.
Update
I did a fresh install of Ubuntu 16.10, with the contents in my $HOME directory intact. But I still do not know the exact reason, why it failed to boot.

A: Found a simple permanent solution. This worked for me on 16.04.2 LTS:

*

*In your GRUB menu, go into edit mode and find the kernel/linux line that contains "splash quiet" and replace $vt_handoff with nomodeset. You should now be able to boot properly.

*Edit the file /etc/grub.d/10_linux.
Find the vt_handoff variable, around line 27 and change
vt_handoff="1" to vt_handoff="0"
and save the file.

*Finally:
$ sudo update-grub

*Reboot


text:
Q: Exporting CSV in french language shows junk charcters I am having a problem in exporting a csv file using au.com.bytecode.opencsv.CSVWriter. I did something like:
File file = File.createTempFile("UserDetails_", ".csv");
 CSVWriter writer = new CSVWriter(new OutputStreamWriter(
                    new FileOutputStream(file), "UTF-8"),
                    ',');
and then when I exporting the .csv file, it shows the junk characters for french letters.[Data to be saved in the .csv are french characters].
But previously I was doing something like:
CSVWriter writer = new CSVWriter(new FileWriter(file));, then it was perfectly showing all french characters in Windows environment, but in Prod environment[Linux] it was showing junks. So I thought to use the Character set UTF-8 for the file format to be exported.
How can I get rid of the problem?
Please Suggest!!
Thanks in advance!

A: Hypothesis: you use Excel to open your CSVs under Windows.
Unfortunately for you, Excel is crap at reading UTF-8. Even though it should not be required, Excel expects to have a byte order mark at the beginning of the CSV if it uses any UTF-* encoding, otherwise it will try and read it using Windows 1252!
Solution? Errr... Don't use Excel?
Anyway, with your old way:
CSVWriter writer = new CSVWriter(new FileWriter(file));

this would use the JVM's default encoding; this is windows-1252 under Windows and UTF-8 under Linux.
Note that Apache's commons-io has BOM{Input,Output}Stream classes which may help you here.
Another solution would be (ewwww) to always read/write using Windows-1252.
Other note: if you use Java 7, use the Files.newBuffered{Reader,Writer}() methods -- and the try-with-resources statement.


text:
Q: NuxtJS /Vue not firing scroll event I'm using Vue3 and NuxtJS,but it seems like scroll event wont fire. Nothing happens after I scroll,nor I don't have any errors
methods: {
    handleScroll () {
      console.log('scrolled')
      }
  },
created(){
   if(process.client){
    window.addEventListener('scroll', this.handleScroll);
    console.log(window)

}
  },
  destroyed () {
    if(process.client){
    window.removeEventListener('scroll', this.handleScroll);
    }
}

A: I guess the problem is that your process.client is false.
I tried the code below and it works fine for me:
  methods: {
    handleScroll() {
      console.log("scrolled");
    },
  },
  created() {
    window.addEventListener("scroll", this.handleScroll);
    console.log(window);
  },
  destroyed() {
    window.removeEventListener("scroll", this.handleScroll);
  },
</js>


text:
Q: Immutable JS - get a value inside a nested map I'm using immutableJS, React/Redux and I have this map and I need to get the values of actions, so it will be like -> allRetrospectivesMap -> id -> current_stage -> actions

I have this code and it works, but it's super ugly, is there a better way to do it?
    class UserActionItems extends Component {
      render() {
        const { retrospectives } = this.props
        const actions = flatten(
          Object.keys(immutableHelpers.toJS(retrospectives))
          .map(key => retrospectives.get(key))
          .map(retro => immutableHelpers.toJS(retro.getIn(['current_stage', 'actions'])))
        ).value()

    return (
       <div>
          <ActionsList
          actions={actions[0]}
          users={[]}
          />
       </div>
    )
  }
}

    const mapStateToProps = ({ allRetrospectivesMap }) => ({
      retrospectives: allRetrospectivesMap
    })

Thanks!!! :)

A: You can do this with a getIn() method from immutable js.
const id = getId() // you've id from somewhere
const actions= state.getIn(['allRetrospectivesMap', id, 'current_stage', 'actions']); // Note: state is your immutable data.

Read more about it here


text:
Q: MDI window and close button whenever a modal dialog (e.g. call fgl_winmessage(...)) is open from a MDI  window the close action is disabled. I allready tried to reactived from the menu with a dialog.setActionActive with no sucess. Any ideas will be highly appreciated.
TIA
Frederico Moreira

A: Have you tried creating a simple application and testing it?
IMPORT FGL fgldialog

MAIN
    CALL fgl_winMessage("title","text","info")
END MAIN

I did this and there is no "close" action but there is an "ok" action which is enabled.  Any buttons on other forms would be disabled because the modal form has exclusive focus.  The window menu has a "Close Alt+F4" menu item and it is enabled too.
I suspect you might need to look at your action defaults or style files to see if anything is interfering there.
The fgl_winMessage() function has no COMMAND close block in the code so if a button for close did appear on the modal form then it would be disabled.


text:
Q: Consumindo webservice, tela de login Bom dia!
To criando um projeto em JS, EJS e Express.js para estudos, para consumir uma listagem de carros usando o webservice:
https://carros-springboot.herokuapp.com/api/v1/carros
Na tela de login, usando: https://carros-springboot.herokuapp.com/api/v2/login
Preciso pegar o token JWT, preciso mandar um post method com user e password.
Tem os passos nesse site: http://ricardolecheta.com.br/?p=1106
Enfim, usei poucas vezes o recurso npm "request", precisava saber só se pelo menos estou no caminho certo.
Segue o código:

const express = require("express");
const bodyParser = require("body-parser");
const request = require("request");

const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: false
}));

// Post
app.post("/", (req, res) => {
  let user = req.body.username;
  let password = req.body.password;

  let options = {
    url: "https://carros-springboot.herokuapp.com/api/v2/login",
    method: "POST",
    contentType: "application/json"
  };

  request(options, (err, res, body) => {
    let carUser = JSON.parse(username.body);
    let carPassword = JSON.parse(password.body);
    alert(carUser);
    alert(carPassword);
  });

});
<form action="/" method="post" class="form-signin">

Login

  Username
  <input type="username" id="inputUser" class="form-control" placeholder="Username" required autofocus name="username">
  Password
  <input type="password" id="inputPassword" class="form-control" placeholder="Password" required name="password">
  <button class="btn btn-md btn-danger" type="submit">Sign in</button>
</form>

Seria mais ou menos isso?
Alguem da um help?

A: Ta! Já vi que tava tudo errado...
O post seria mais ou menos isso:

app.post("/", (req, res) => {
  let user = req.body.username;
  let password = req.body.password;
  let token_jwt = "";

  request.post({
    "headers": {
      "content-type": "application/json",
      "Authorization": `Bearer ${token_jwt}`
    },
    "url": loginURL,
    "body": JSON.stringify({
      "username": "admin",
      "password": "123"
    })
  }, (err, res, body) => {
    if(err){
      return console.log(err);
    } else {
      if(user === body.username && password === body.password){
        token_jwt = res.body.token;
        console.log(token_jwt);
        console.log("Successfully logged in!");
        res.redirect("/home");
      }

    }
  });

Certo?

A:

// Posts
app.post("/", (req, res) => {

  // Data from login input
  let user = req.body.username;
  let password = req.body.password;
  let token_jwt = "";

  // Fetching data with the webserver
  let data = {
    username: user,
    password: password
  };

  // Stringifying the data
  let jsonData = JSON.stringify(data);

  // Request params
  let options = {
    url: loginURL,
    method: "POST",
    contentType: "application/json",
    headers: {
       "Authorization": `Bearer ${token_jwt}`
     },
    body: jsonData
  };

  // Requesting data
  request(options, (err, resp, body) => {
    if(err) {
      res.redirect("/");
    } else {
      if(resp.statusCode == 200) {
        token_jwt = resp.body.token;
        console.log(token_jwt);
        console.log(body);
        res.redirect("/home");
      } else {
        console.log("Error, please try again.");
        res.redirect("/");
      }
    }
  });

});

Tá, bati a cabeça pra caramba mas deu certo, funcionou!
Agora preciso pegar esse token do response e salva-lo em localStorage.
Alguem da um help?


text:
Q: How to capture the exception and message key when using ErrorHandlingDeserializer2 to handle exceptions during deserialization I'm using spring boot 2.1.7.RELEASE and spring-kafka 2.2.8.RELEASE.And I'm using @KafkaListener annotation to create a consumer and I'm using all default settings for the consumer.And I'm using below configuration as specified in the Spring-Kafka documentation.
// other props
    props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ErrorHandlingDeserializer2.class);
    props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, ErrorHandlingDeserializer2.class);
    props.put(ErrorHandlingDeserializer.KEY_DESERIALIZER_CLASS, StringDeserializer.class);
    props.put(ErrorHandlingDeserializer.VALUE_DESERIALIZER_CLASS, AvroDeserializer.class.getName());
    return new DefaultKafkaConsumerFactory<>(props);

Now, My requirements are when there is a deserialization exception. Please suggest how can i do this.

*

*Capture the exception and the record key to log the details

*Send this record to DLT

A: Add a SeekToCurrentErrorHandler, configured with a DeadLetterPublishingRecoverer to the container.
See the documentation and here.
Deserialization exceptions are treated as fatal and will not be retried.
If you want to write your own error handler for some reason, the code in the DeadLetterPublishingRecoverer shows how the exception information is extracted.


text:
Q: How do I get the form to be on the same line as by navigation buttons? I've tried playing with putting the indents and placement in different places but it still appear underneath the navigation button. I want it on the same line across the top.
I might of made it a bit messy trying to get it on the same line, if so just take out whenever isn't necessary.
`
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Bootstrap For Beginners</title>
    <meta name="description" content="Hello World">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css">

Contact

About

            <form class="form-horizontal">

                        <input type="email" class="form-control" id="exampleInputEmail2" placeholder="Have Feedback?">

                        <button type="submit" class="btn btn-default">Submit Feedback</button>

            </form>

Student

Business

By:

For:

The input bar doesn't seem to be responsive on really really small windows, is that normal?
I also want the footer to be the same size as the nav header and the jumbotron to fill up the rest of the space in between, everything fits in the window with no scrolling.
Thanks in advance.

A: To address part of your issue, try putting the sections you would like to be side-by-side in the same div.row, then wrap a div.col-xx-x around each. For example:

Contact

About

                <form class="form-horizontal">

                            <input type="email" class="form-control" id="exampleInputEmail2" placeholder="Have Feedback?">

                            <button type="submit" class="btn btn-default">Submit Feedback</button>

                </form>

A: I'm really not sure why you're not using the <navbar> class. It's there and ready to accomplish exactly what you're looking for. See this Bootply for example:
Bootply - Navbar

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
        Toggle navigation

      </button>
      Brand

      <form class="navbar-form navbar-left" role="search">

          <input class="form-control" placeholder="Have Feedback?" type="text">

        <button type="submit" class="btn btn-default">Submit Feedback</button>
      </form>

About

Contact

There is a way to do it like you have it, but I'm not sure how to get the <form> to align perfectly with the  class, since there's padding on it and moves it down from the top a bit. You may need some custom CSS to handle that.
Bootply - Original

      <form class="form-horizontal">
        <input class="form-control" id="exampleInputEmail2" placeholder="Have Feedback?" type="email">
      </form>

      <button type="submit" class="btn btn-default">Submit Feedback</button>

Contact

About

Give them both a look and see if either works for you.
Hope that helps!

A: Your code looks great, all you have to do is wrap the form and nav in a wrapper / container then separate the sections with col-md-6. I built an example for you here http://www.bootply.com/P7VmPZOfXp.
/* CSS used here will be applied after bootstrap.css */
.footer {
    height: 58px;
    background: #ccc;

  }

                                <form class="form-horizontal">

                                            <input class="form-control" id="exampleInputEmail2" placeholder="Have Feedback?" type="email">

                                            <button type="submit" class="btn btn-default">Submit Feedback</button>

                                </form>

Contact

About

Student

Business

By:

For:


text:
Q: Google apps script: Get folder name from file in google apps script I have this code:
var files = DriveApp.searchFiles(
 'modifiedDate > "2013-02-28" and title contains "untitled"');
while (files.hasNext()) {
var file = files.next();
Logger.log(file.getName());
}

How can I get the name of the folder where the file resides type this code:
var folderName = folder.getName(); // ?

thank you for help
raffaele

A: Use .getParents() method of File class to get a collection of folders (FolderIterator) that are immediate parents of the file:
var fileParents = file.getParents();
while ( fileParents.hasNext() ) {
  var folder = fileParents.next();
  Logger.log(folder.getName());
}


text:
Q: sending the data in Json android Namevaluepair to the php server I want to send the contact detail which has name and phone number stored in a array list, for this I am converting this array list to NameValuePairs. Now I would like to send this to PHP server, and save those detail in the database. Just for testing purpose I am currently writing this to file and also returning to android to  check the data. Below is my code:
    HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
    HttpResponse response;
    try {
HttpPost post = new HttpPost("xyz.com");

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    for (ContactRetreive cr : al)
    {
    nameValuePairs.add(new BasicNameValuePair("name", cr.name));
            nameValuePairs.add(new     BasicNameValuePair("phone",cr.phone));

}
    Log.i("NameValuePair", nameValuePairs.toString());
    post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

     response = client.execute(post);
    if (response != null) {
    InputStream in = response.getEntity().getContent();
    String a = convertStreamToString(in);
    Log.i("Read from Server", a);
    }
    } catch (Exception e) {
e.printStackTrace();
    }

    public String convertStreamToString(InputStream is) {
    // TODO Auto-generated method stub
    String line = "";
    StringBuilder total = new StringBuilder();
    Log.i("ConvertoStream", "Starting");
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
    try {
        while ((line = rd.readLine()) != null) {
            total.append(line);
        }
    } catch (Exception e) {
        Toast.makeText(getActivity(), "Stream Exception",
                Toast.LENGTH_SHORT).show();
    }
    Log.i("ConvertoStream", "Result:" + total.toString());
    return total.toString();
}

Below is my php code block
    $json = file_get_contents('php://input');
    $obj = json_decode($json);
    $file = fopen("fileOutput1.txt","w");
    echo fwrite($file,$obj);
    foreach ($obj as $item)
    {
       echo $item['name'];
    }

The issue is
1. It is not writing anything on file that means the data I am passing from the android is not  reading in the php.
2. It is returning the error in the android : Invalid argument supplied to ForEach loop.

Please help me I am not able to figure out what is the problem. If you need anything please let me know.

A: To get name and phone in php use $_REQUEST or array_values($_POST) as:
$arr_obj = array_values($_POST);

Now use arr_obj array to get all values posted from android application.
Using $_REQUEST :
$name=$_REQUEST['name'];
$phone=$_REQUEST['phone'];

EDIT : pass Array to php using BasicNameValuePair :
for (ContactRetreive cr : al)
{
  nameValuePairs.add(new BasicNameValuePair("name[]", cr.name));
  nameValuePairs.add(new     BasicNameValuePair("phone[]",cr.phone));

}

and in PHP get Array using $_POST :
$arr_name = array($_POST[name]);
$arr_phone = array($_POST[phone]);


text:
Q: Best autocomplete for huge amount of select options from a 2d array? For fields where are no more than thousand options available drop down lists seem to make the job. However, I have two arrays that flirt around dozens of thousands, so putting them to a comboboxes would be a killer for the browser. My guess is that best would be a simple text input, but with a autocomplete feature. Over the top first went autocomplete from jQueryUI, but I've found out it isn't compatible with 2d arrays like:
var fkOptionList = [[1, 'Orange'],[2, 'Banana'],[3, 'Coconut']]

Since I have my arrays written in this fashion, I'd prefer not to rewrite them. Perhaps you know a workaround for this, or a better way for dealing with such huge amount of options?

A: Assuming you meant:
var fkOptionList = [[1,'Orange'],[2,'Banana'],[3,'Coconut']];

You can use a map function (e.g. the _.map routine in underscore.js) to rewrite the 2d array as the necessary 1d array.  There's also a lot of effort put in to ajax-loaded autocompletes, so if it's easier to process into a 1d array on the server side that might be a good option.

A: Don't be afraid to run it through a map or a loop to flatten it.
myNewArray = [[1, 'Orange'],[2, 'Banana'],[3, 'Coconut']].map(function(el) {
    return el[1];
});

It's a negligible performance hit, especially if you use a functional library such as lodash;


text:
Q: Sliding menu with Tab bar in Onsen UI I'm having trouble making work a tabbed bar interface with a sliding menu using Onsen UI. The problem is that when I click on a item on the sliding menu, the tab bar disappears. Here is my code:
index.html
<ons-sliding-menu
    behind-page="views/menu.html" above-page="views/tab-bar.html" side="left"
    type="reveal" max-slide-distance="300px" swipable="true">
</ons-sliding-menu>

views/menu.html
<ons-page style="background-color: white">
    <ons-list>
      <ons-list-item
        modifier="chevron"
        ng-click="ons.slidingMenu.setMainPage('views/home.html', {closeMenu: true})">
           Noticias
      </ons-list-item>
      <ons-list-item
        modifier="chevron"
        ng-click="ons.slidingMenu.setMainPage('views/settings.html', {closeMenu: true})">
           Reportar Pago
      </ons-list-item>
    </ons-list>
</ons-page>

views/tab-bar.html
<ons-tabbar var="barra">
    <ons-tabbar-item
      active="true"
      label="Home"
      icon="home"
      page="views/home.html">
    </ons-tabbar-item>
    <ons-tabbar-item
      label="Camera"
      icon="camera"
      page="views/camera.html">
    </ons-tabbar-item>
    <ons-tabbar-item
      label="Settings"
      icon="gear"
      page="views/settings.html">
    </ons-tabbar-item>
</ons-tabbar>

A: Usually, slidingMenu is used to switch a category.
The tabbar is used to switch a sub-category.
However, in your code, slidingMenu and tabbar looks like having a same role.
In such case, slidingMenu is not necessary to work independently.
Therefore, the menu.html should be replace by
<ons-page style="background-color: white">
    <ons-list>
      <ons-list-item
        modifier="chevron"
        ng-click="barra.setActiveTab(0); app.slidingMenu.closeMenu();">
           Noticias
      </ons-list-item>
      <ons-list-item
        modifier="chevron"
        ng-click="barra.setActiveTab(2); app.slidingMenu.closeMenu();">
           Reportar Pago
      </ons-list-item>
    </ons-list>
</ons-page>


text:
Q: How to identify which element was double clicked inside a ListBox? I have a listbox. The listbox DataTemplate consists of few Text Blocks and some TextBoxes.
The issue is on mouse double click I need to find out on which element the double click was done, so as to do some further operations like make the TextBox editable and so on. At the same time I need to define some action for list double click also. So I can't handle mouse down separately for each component.
Hence, I need to handle the mouse down for the ListBox and find out on which element the double click was made.
I tried with below code, but it returns the ListBox's Name instead of TextBox's Name:
private void myListBox_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    var mouseWasDownOn = e.Source as FrameworkElement;
    if (mouseWasDownOn != null)
    {
        string elementName = mouseWasDownOn.Name;
    }
}

I have also tried as per below questions
WPF Get Element(s) under mouse
How to know what control the mouse has clicked in a canvas?
Getting the Logical UIElement under the mouse in WPF
public void ListBox_MouseDownHandler(object sender, MouseButtonEventArgs e)
{
    HitTestResult target = VisualTreeHelper.HitTest(myListBoxName, e.GetPosition(myListBoxName));
    while(!(target is Control) && (target != null))
    {
        target = VisualTreeHelper.GetParent(target);
    }
}

But still could not find a solution. Hence please help me to get the element type or element name from double click.

A: You can use FrameworkTemplate.FindName Method (String, FrameworkElement) for this purpose and it should works as you want:
private childItem FindVisualChild<childItem>(DependencyObject obj) where childItem : DependencyObject
{
    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
    {
        DependencyObject child = VisualTreeHelper.GetChild(obj, i);
        if (child != null && child is childItem)
            return (childItem)child;
        childItem childOfChild = FindVisualChild<childItem>(child);
        if (childOfChild != null)
            return childOfChild;
    }
    return null;
}

Then:
private void LstBox_OnPreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    ListBoxItem ListBoxItem = (ListBoxItem)(lstBox.ItemContainerGenerator.ContainerFromIndex(lstBox.SelectedIndex));
    ContentPresenter contentPresenter = FindVisualChild<ContentPresenter>(ListBoxItem);
    DataTemplate myDataTemplate = contentPresenter.ContentTemplate;
    StackPanel temp = (StackPanel)myDataTemplate.FindName("myStackPanel", contentPresenter);
    //*so as to do some further operations like make the textbox editable and so on* as you want
   (temp.FindName("field1TextBox") as TextBox).IsReadOnly = false;
}

Based on your question that you said: The listbox's DataTemplate consists of few TextBlock and some TextBoxes. (I assumed they are inside a StackPanel)


text:
Q: How can I validate an angular form I have this inscription form. I tried to validate it but in vain. inputs are saved in my database despite they are empty I want to have these validations:

*

*All inputs are required

*email address should be valid

*name should be composer by only letters

*Password should have minimum 8 characters, at least 1 uppercase
letter, 1 lowercase letter and 1 number

I want to have a message under evey invalid input.(in

 for example).How can I do this please?
HTML file

Inscription

<form [formGroup]="angForm" (ngSubmit)="postdata(angForm)" autocomplete="off">

Nom
<input type="text" name="name" formControlName="name" autocomplete="off" id="name"
class="form-control input-sm" placeholder="Nom">

Email
<input type="email" name="email" formControlName="email" autocomplete="off" id="email"
class="form-control input-sm" placeholder="Email">

Mot de passe
<input type="password" name="Password" formControlName="password" autocomplete="off"
id="password" class="form-control input-sm" placeholder="Mot de passe">

<button type="sumit" class="btn btn-success">Enregistrer</button>
</form>

Type script file
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, FormBuilder, Validators, NgForm } from '@angular/forms';
import { first } from 'rxjs/operators';
import { Router } from '@angular/router';
import { ApiService } from '../api.service';
@Component({
selector: 'app-inscription',
templateUrl: './inscription.component.html',
styleUrls: ['./inscription.component.css']
})
export class InscriptionComponent implements OnInit {
angForm: FormGroup;
constructor(private fb: FormBuilder,private dataService: ApiService,private router:Router) {
this.angForm = this.fb.group({
email: [],
password: [],
name: [],
mobile: []
});
}
ngOnInit() {
}
postdata(angForm1:any){this.dataService.userregistration(angForm1.value.name,angForm1.value.email,angForm1.value.password)
.pipe(first())
.subscribe(
data => {
this.router.navigate(['login']);

},
error => {
});
}
 get email() { return this.angForm.get('email'); }
 get password() { return this.angForm.get('password'); }
 get name() { return this.angForm.get('name'); }
 }

thanks in advance

A:

this.angForm = this.fb.group({
email: ['', Validators.required, Validators.email],
password: ['', Validators.required, Validators.minLength(8), Validators.pattern("(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}")],
name: ['', Validators.required, Validators.pattern('^[a-zA-Z ]*$')],
mobile: [null, Validators.required, Validators.minLength(10), Validators.maxLength(10)]
});

This is the syntax for Validations.

In HTML, before closing of form-group div write

                                Name is required

Must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters

same applies for email, mobile error msg in HTML.
Please refer for reactive form validation.
https://www.freecodecamp.org/news/how-to-validate-angular-reactive-forms/

A: response to Rothitha
If you don't want to use the "auxiliar variable" submitted you can use in submit.
submit(form:FormGroup)
{
   if (form.invalid)
      form.markallAsTouched()
   else
   {
      ..doSomething..
   }
}

If we can better mannagement about errors (remove this ugly *ngIf="angForm.get('password').touched && angForm.get('password').touched" we can use a tecnica similar bootstrap mannage the error
We use a .css like
.invalid-feedback
{
   display:none
}
.ng-invalid.ng-touched ~ .invalid-feedback
{
  display: block;
}

And an html like

    Email

    <input id="email" formControlName="email">

Email is required

it's not a valid email

See stackblitz


text:
Q: .htaccess rewriterule for changing the url This is my current .htaccess:
Options +FollowSymLinks
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php?page=$1 [QSA,L]
RewriteRule ^games/(.*)$ index.php?page=games&game=$1 [L,QSA]

I need for this to work:
index.php?page=music should be url.com/music
index.php?page=games should be url.com/games
index.php?page=games&game=example should be url.com/games/example
Please help me write my .htaccess for this

A: try following
  Options +FollowSymlinks
    RewriteEngine on
    rewriterule ^index.php?page=music(.*)$ http://otherdomain.com/music$1 [r=301,nc]
rewriterule ^index.php?page=music(.*)$ http://otherdomain.com/music$1 [r=301,nc]
rewriterule ^index.php?page=games(.*)$ http://otherdomain.com/games$1 [r=301,nc]
rewriterule ^index.php?page=games&game=example(.*)$ http://otherdomain.com/games/example$1 [r=301,nc]


text:
Q: One-Panel-Button Web Radio (on/off) fpr xfce. How-to? After looking at about some 50 posts about web radios I think my issue had not been asked yet.
Do you still know those shabby old transistor radios playing in some corner or window sill in offices or workshops? Their tuning wheels are so bad that nobody ever touches them again once a station had been tuned. Also the volume knob is cracking horribly, so they are plugged in in the mornings and unplugged by the last one leaving the office.
That's exactly what I want.
Ideally, this would be a fixed On/Off Icon somewhere in the Panel bar. No window at all. Press it once and the configured web radio stream starts playing. Press again it stops. The radio station is defined by the http address of an m3u file for the stream.
I did not find a app that works like that. I hope I just overlooked the one that exactly fits what I want and you guys can point me to the right one.
Best I found so far was gnome mplayer, but I am not really happy with it.
Its a normal appication. It reduces to a small icon in the panel bar which is good. On/Off is, open the Icon then press Play/Stop - which would be ok.
Not OK is that I can't make it to just play the last stream. Every time it starts I need to open File/Open Location and copy&paste the http address of the m3u file from a text file on the drive. It would be OK for me when there is a way to autostart it with the right stream automatically loaded but not playing.
I had tried to put the stream address into a file and used "Open Recent". It say "start playing" but then stops. This is how the file looked like.
 #EXTM3U
 #EXTINF:-1, Web Radio
 http://some-webradioaddress.com/streamfile.m3u

So
Is there a tool that already does what I want?
Is there a way to make mplayer behave like I need?
If no, how to achieve that by other means using command line apps and scripts or whatever?
Thanks für your creative input,
CatMan

A: I should have waited a bit longer, because just after posting, I accidently found this german page about a tool that exactly matches my needs.
The Tool is called radiotray. It opens as icon in next to network and volume icons. When it is started it remembers the last played station. Left click gives you a context menu with the Start/Stop button (). Perfect. You can set up stations in a tree by dialog. I just deleted all and added my only station path as http://stationaddress.com/PathTo3MuFile.m3u. Now its very compact and super easy to use.
There is a cool build-in plugin you can select in a dialog: sleep timer. It defaults to 15min. In the config file I set it to 2hrs, in case I forget to switch it off.
Installation
sudo apt-get install radiotray python-xdg

The config files are in:
~/.local/share/radiotray

For those who can understand a bit of German there are some more information and images: https://wiki.ubuntuusers.de/Radio_Tray/
Hope some may find it useful.
CatMan


text:
Q: How can we set the lenient option in hibernate-search query builder We are using hibernate search api for elastic search. I came across lenient option in elastic search: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html but unable to figure out how can we set this through hibernate search.
Some of the fields in elastic search are boolean, and range, and we don't want to search through them.

A: There is no such option in Hibernate Search at the moment.
In Hibernate Search 5, you can write your whole query as JSON in order to take advantage of native options. That will require you to write everything as JSON, though, not just the simple-query-string query.
In Hibernate Search 6, you write just the simple-query-string predicate as JSON to take advantage of a native option in this predicate and continue using the Hibernate Search DSL for other predicates in the same query, which should be more convenient.
If you need the feature in the DSL, you can create a JIRA ticket and it will be addressed in Hibernate Search 6 if it makes it to the top of the priority list. If you need it before then, you can of course submit a pull request. Note that new features should go into Hibernate Search 6 (master branch), not Hibernate Search 5 which is currently in maintenance mode.


text:
Q: What does the arbitrary constant in cosine equation of displacement in S.H.M say? The phase and phase constant in a displacement time equation show from where the particle has started.
In my school textbook, first the displacement equation was given as :-
                     $$x= A\sin(\omega t+\phi)$$
where $\phi$ is the phase constant.
But then it said if the particle is at extreme position then we add $\pi/2$ because obviously displacement is maximum at $\pi/2$
So now the equation at extreme should be :-
                     $$x=A\sin\left(\omega t+\frac{\pi}{2}\right)$$
$$x=A\cos(\omega t)$$
But in my textbook the equation is :-
                   $$x=A\cos(\omega t + \phi')$$
It says that $\phi '$ is another arbitrary constant. But technically $\phi$ is $\sin ^{-1} (x/A)$, here $x$ will be $A$ and we get $\pi/2$ so no constant remains. But what is this $\phi '$ constant and on which thing it depends?

A: OK, you already understood the most important part. This is that
$$
\sin{(wt + \frac{\pi}{2})}
= \cos{(wt)}
$$
This implies, that the two following equations are equally valid

*

*$x(t) = A \sin{(wt + \phi)}$ or

*$x(t) = A \cos{(wt + \phi^\prime)}$
to define the position of an oscillator. If we like to start at the max. amplitude at $t=0$ we can either write

*

*$x(t) = A \sin{(wt + \pi/2)}$, where we used $\phi = \pi/2$ or

*$x(t) = A \cos{(wt)}$, where we used $\phi^\prime = 0$.

Thus, no matter what, you will always obtain $\phi = \phi^\prime + \pi/2$.

A: It depends on the initial conditions. If its at maximum displacement at $t=0$ then the equation is $x=A\cos{\omega t}$. If it is at equilibrium position and maximum velocity at $t=0$ then $x=A\sin{\omega t}$. In general, the solution is $x=a\cos{\omega t} + b\sin{\omega t}$ which simplifies to either $A\cos{(\omega t + \phi ')}$ or $A\sin{(\omega t +\phi)}$ using the harmonic addition formula.

A: At $t=0$ the displacement $x$ is not necessarily $0$:
$$
x(0)=A\sin(\phi) \tag{1}
$$
In addition, the velocity at $t=0$
$$
\dot{x}(0)=\omega A \cos(\phi) \tag{2}
$$
(1) and (2) are two equations for your 2 unknowns $A$ and $\phi$.   Thus, as you alluded to
$$
\frac{x(0)}{\dot x(0)}= \omega\tan(\phi)
$$
from which you can determine $\phi$,  and plug it back into either (1) or (2)  to obtain $A$ if you need the amplitude.


text:
Q: Dictionary Calling Function for Each Key I have the following code in which I am trying to build a random number object based on the type of distribution and the parameters of said distribution. The code works insomuch as it generates an object that contains 10,000 points from a uniform distribution.
import numpy as np

rngSeed = 654  # Random seed for reproducibility
numSimulations = 10_000

def get_rand_unif(min_value, max_value, n_samples=1_000):
    """
    This function generates a random number [nd]array of size [n_samples]
    from a uniform distribution between the two input values
    [min_value, max_value)
    Args:
    - min_value (float)
    - max_value (float)
    - n_samples (int)
    Return:
    - Random number [nd]array of [n_samples] between this range (float)
    """
    return np.random.default_rng(rngSeed).uniform(min_value, max_value, n_samples)

def get_rand_norm(mean, std_dev, n_samples=1_000):
    """
    This function generates a random number [nd]array of size [n_samples]
    from a normal distribution with a mean of [mean] and a standard deviation
    of [std_dev].
    Args:
    - mean(float)
    - std_dev (float)
    - n_samples (int)
    Return:
    - Random number [nd]array of [n_samples] from a normal distribution (float)
    """
    return np.random.default_rng(rngSeed).normal(mean, std_dev, n_samples)

class InVar:
    def __init__(self, *parms):
        self.rndData = self.get_disto(*parms)

    def get_disto(self, *parms):
        distR = {
            "unif": get_rand_unif(parms[1], parms[2], numSimulations),
            "norm": get_rand_norm(parms[1], parms[2], numSimulations),
        }
        return distR.get(parms[0])

    def rand_data(self):
        return self.rndData

p1 = InVar("unif", 0, 1)

However, when I debug the code, I notice that random values are being calculated for both the Uniform and Normal distributions. I would like to know how to change  my code so that only the function corresponding to the called key is executed. While anecdotal, I fear that if I were to introduce additional probability distributions that require more than two parameters, I will run into trouble.

A: I think the simple fix you're looking for is to call the function after the dict is constructed.
def get_disto(self, *parms):
    distR = {
        "unif": get_rand_unif,
        "norm": get_rand_norm,
    }
    return distR.get(parms[0])(parms[1], parms[2], numSimulations)

UPDATE: If you want to call the functions separately, like you did before, use an if/else construct.
def get_disto(self, *parms):
    if parms[0] == "unif":
        return get_rand_unif(parms[1], parms[2], numSimulations)
    elif parms[0] == "norm":
        return get_rand_norm(parms[1], parms[2], numSimulations)
    else:
        raise Exception(f"Unrecognized distribution type: {parms[0]}")


text:
Q: correct code for CMD execution Looking for the correct CMD command to run below PowerShell script.
$wshshell = New-Object -ComObject WScript.Shell
$lnk = $wshshell.CreateShortcut("C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Accessories\"+"\Internet Explorer.lnk")
$lnk.TargetPath = "C:\Program Files\Internet Explorer\iexplore.exe"
$lnk.Save()

Tried:
powershell.exe -Command $wshshell = New-Object -ComObject WScript.Shell $lnk = $wshshell.CreateShortcut("C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Accessories\"+"\Internet Explorer.lnk") $lnk.TargetPath = "C:\Program Files\Internet Explorer\iexplore.exe" $lnk.Save()

At line:1 char:81
+ ... ect -ComObject WScript.Shell $lnk = $wshshell.CreateShortcut(C:\Progr ...
+                                                                  ~
Missing ')' in method call.
At line:1 char:145
+ ... \Accessories"+\Internet Explorer.lnk) $lnk.TargetPath = C:\Program Fi ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The string is missing the terminator: ".
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MissingEndParenthesisInMethodCall

A: powershell.exe $wshshell = New-Object -ComObject WScript.Shell; $lnk =
$wshshell.CreateShortcut('C:\ProgramData\Microsoft\Windows\Start
Menu\Programs\Accessories\'+'\Internet Explorer.lnk'); $lnk.TargetPath =
'C:\Program Files\Internet Explorer\iexplore.exe'; "$lnk.Save()"

Semicolons did the job


text:
Q: Approximation of characteristic function by mollifiers I have been asked to show that the Heaviside function $H := \chi_{[0,+ \infty)}$ does not admit weak derivative in $L^1_{loc}(\mathbb{R})$. Here's my reasoning:
By definition the weak derivative of $H$ is a function $w$ s.t. $\forall \varphi \in C^\infty_c(\mathbb{R})$
$$ \int_{\mathbb{R}}\varphi w dx = - \int_{\mathbb{R}}\varphi' H dx = -\lim_{R\to \infty} \int_0^R \varphi'dx = \varphi(0) =  \int_{\mathbb{R}} \varphi \delta_0$$
where $\delta_0$ is the Dirac's delta centered in $0$.
Thus the only thing to show is that
$$ \exists w \in L^1_{loc}(\mathbb{R}) :\forall \varphi \in C^\infty_c(\mathbb{R}) \int_{\mathbb{R}}\varphi  w dx = \int_{\mathbb{R}}\varphi \delta_0 \Longrightarrow wdx = \delta_0$$
i.e. $\delta_0$ admits Radon-Nykodim derivative w.r.t. the Lebesgue measure (which we know is not the case) so to conclude by contraposition.
Let $\mathcal{L}_w^1 := w dx$ be the measure associated to $w$. The idea is that if, for every finite measure borelian $E$ we have
$$ \mathcal{L}_w^1(E) = \delta_0(E)$$
then we are done, as this would imply $\mathcal{L}_w^1 = \delta_0$.
Let $(\rho_h)_h$ be a sequence of mollifiers and define $u_h := \rho_h * \chi_E$. By the properties of mollifiers we have
$$ u_h \xrightarrow{L^1} \chi_E \\ u_h \in C^\infty_c(\mathbb{R})$$
thus
$$ \mathcal{L}_w^1(E) = \int_\mathbb{R} \chi_E ~ \mathcal{L}_w^1 = \lim_{h \to \infty} \int_\mathbb{R} u_h ~ \mathcal{L}_w^1 = \lim_{h \to \infty} \int_\mathbb{R} u_h ~ \delta_0$$
If I could bring the limit inside the integral than I would have done, but since the convergency is only in $L^1$ I shouldn't be able to apply dominated convergency. How can I conclude the proof?

A: You really only need to consider your first equation in order to obtain a contradiction. Suppose that there exists $w \in L^{1}_{\mbox{loc}}(\mathbb{R})$ such that
$$
           \int w\varphi dx = \varphi(0),\;\;\;\varphi \in \mathcal{C}_{c}^{\infty}(\mathbb{R}).
$$
That equation is inconsistent. To see why, find $\varphi\in\mathcal{C}_{c}^{\infty}(\mathbb{R})$ for which $\varphi(0)=1$. Then $\varphi_{\epsilon}(x)=\varphi(x/\epsilon)$ is $1$ at $0$ for all $\epsilon > 0$, remains uniformly bounded as $\epsilon\downarrow 0$ and converges pointwise everywhere to $0$ except at $0$. So you can apply the Lebesgue dominated convergence theorem to $(w\varphi_{\epsilon})$ on some finite interval in order to conclude that
$$
      0=\lim_{\epsilon\downarrow 0}\int w\varphi_{\epsilon}dx = \lim_{\epsilon\downarrow 0}\varphi_{\epsilon}(0)=1.
$$


text:
Q: Very simple filter system? I am trying to build an extremely simple filter system that is based on multiple attributes.
In the case of my example, I used:

*

*Gender

*Height

I would like to be able to choose between 'Male/Female' and 'Short/Tall'. So, there are four possible combinations:

*

*Male/Short

*Male/Tall

*Female/Short

*Female/Tall

In the case of having only two choices in each filter group, only one can be checked at a time.
The problem I am running into is the simple logic. Right now, clicking 'Men' will hide the women. But clicking 'Tall' will show only the 'Tall' people.
I'm just wondering if there is an elegant solution to building this basic system?
Thank you!
http://jsbin.com/ixokek/1

A: You only care for the current filter setting; you do not take the other into account. It would be arguably more elegant if there is a common filter function that reads all filter settings, and a click handler that merely swaps the active state: http://jsbin.com/ixokek/7/.
$('#filter li').click(function(){
    $(this).siblings().removeClass("active");  // remove active from other
    $(this).toggleClass("active");  // toggle active on current
    filter();  // filter elements
});

var filter = function() {
  // array of classes that items need to have
  var classes = $("#filter li.active")
      .map(function() {
        return $(this).data("filter");
      })
      .toArray();

  $(".item").each(function() {
    var $this = $(this);

    // it should show if it has all classes as the settings say
    var show = classes.every(function(aClass) {
      return $this.hasClass(aClass);  // class is a reserved word
    });

    // toggle appropriately
    if(show) {
      $this.fadeIn(200);
    } else {
      $this.fadeOut(200);
    }
  });
};

A: $('#filter li').on('click', function(){
    $(this).toggleClass('active').siblings().removeClass('active');
    var gender = $('#filter ul').eq(0).find('.active').data('filter')||'',
        height = $('#filter ul').eq(1).find('.active').data('filter')||'',
        sel = '.item'+(gender!=''?'.'+gender:'')+(height!=''?'.'+height:'');
    $(sel).fadeIn(200)
    $('.item').not(sel).fadeOut(200);
});

FIDDLE