text:
Q: Using subclass of std::unique_ptr with std::variant I have a subclass of std::unique_ptr and am trying to use it with std::variant. I have the following setup
// main.cc
#include <iostream>
#include <variant>

using namespace std;

class Content {
  public:
    Content() = default;
    ~Content() { cout << "deconstructing Content" << endl; };

    int value = 10;
};

template<typename T>
class Wrapper : public unique_ptr<T> {
  public:
    Wrapper(T *value): unique_ptr<T>(value) {};
    ~Wrapper() { cout << "deconstructing Wrapper" << endl; };
};

static variant<Wrapper<Content>, int> do_sth(bool flag) {
  if (flag) return Wrapper(new Content());
  return 1;
}

int main(int argc, const char *argv[]) {
  auto result = do_sth(true);
  if (auto wrapper = get_if<Wrapper<Content>>(&result)) {
    cout << wrapper->get()->value << endl;
  } else {
    cout << *get_if<int>(&result) << endl;
  }

  return 0;
}

compiled on macOS 10.14 with Xcode 10.1 using
$ #c++ --version -> Apple LLVM version 10.0.0 (clang-1000.11.45.5)
$ c++ -std=gnu++17 main.cc

The compiler complaints with the following
main.cc:25:12: error: no viable conversion from returned value of type 'Wrapper<Content>' to function return type 'variant<Wrapper<Content>, int>'
    return Wrapper(new Content());
           ^~~~~~~~~~~~~~~~~~~~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/variant:1142:3: note: candidate constructor not viable: no
      known conversion from 'Wrapper<Content>' to 'const std::__1::variant<Wrapper<Content>, int> &' for 1st argument
  variant(const variant&) = default;
  ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/variant:1155:13: note: candidate template ignored:
      substitution failure [with _Arg = Wrapper<Content>, $1 = 0, $2 = 0, $3 = 0]: no type named 'type' in
      'std::__1::result_of<std::__1::__variant_detail::__overload<Wrapper<Content>, int> (Wrapper<Content> &&)>'
  constexpr variant(_Arg&& __arg) noexcept(
            ^
1 error generated.

I have two questions: First, what am I doing wrong? Second, when I remove the deconstructor of Wrapper, i.e.,
template<typename T>
class Wrapper : public unique_ptr<T> {
  public:
    Wrapper(T *value): unique_ptr<T>(value) {};
};

then it compiles and runs with the following output
10
deconstructing Content

Why does it (seem to?) work without deconstructor?

A: Because Wrapper inherits from unique_ptr instance of this class can be only moved.
You have defined destructor for Wrapper so move operations (constructor and assignment operator) are deleted - you can read here when move operations are generated by compiler.
You could:
1) remove destructor of Wrapper, then compiler generates default move operations
or
2) add move operations
Wrapper(T *value): unique_ptr<T>(value) {};
Wrapper(Wrapper&&) = default; // added
~Wrapper() { cout << "deconstructing Wrapper" << endl; };


text:
Q: Unable to install pyhook and pywin32 I'm tring to install pyhook and pywin32, but it can not find python 3.3 which I is installed (and so is 2.7) in the registry. Thats all it really tells me, I'm using Windows 7 with AMD64 bit CPU.

A: You use installer for 32bit architecture. Please check this installer for 64bit: http://www.lfd.uci.edu/~gohlke/pythonlibs/#pyhook.

redpajama_set_name: RedPajamaStackExchange


text:
Q: toDataURL() in Angular2 returns URL with blank image To be in context: I'm using latest version of Angular with TypeScript and I need to show the selected image from a file selector. After select any image i convert to base64 to get the String. Given that String i show the selected image, and after i'll push to a REST server as an attribute of an entity.
The problem is that I not getting the right base64 String of the image, but i can see in Google developer tools that there's two URL of the image generated: one is the correct, and the other is blank, the last is which one is returning toDataURL() function.
I been trying with lots of examples and different codes but still not working.
Also i have to say that it works randomly about 1% of the times i tested.
Following the code:
floor-form.component.html
<div *ngIf="showForm" class="form-group row">
  <input type="file" id="picture" autofocus=""  #file (change)="addPicture(file)" />
    <img [src]="floor.picture" />
</div>

floor-form.component.ts
addPicture(input) {
   const file = input.files[0];
   const reader = new FileReader();

   reader.addEventListener('load', (event: any) => {
      this.floor.picture = this.resizeImage(event.target.result, file.type, 480, 480);
   }, false);

   reader.readAsDataURL(file);
}

resizeImage(imageData, type, MAX_WIDTH = 480, MAX_HEIGHT = 480) {
    const img = document.createElement('img');
    img.src = imageData;
    let width = img.width;
    let height = img.height;
    if (width > height) {
      if (width > MAX_WIDTH) {
        height *= MAX_WIDTH / width;
        width = MAX_WIDTH;
      }
    } else {
      if (height > MAX_HEIGHT) {
        width *= MAX_HEIGHT / height;
        height = MAX_HEIGHT;
      }
    }
    const canvas = document.createElement('canvas');
    canvas.width = width;
    canvas.height = height;
    const ctx = canvas.getContext('2d');
    ctx.drawImage(img, 0, 0, width, height);
    return canvas.toDataURL(type);
  }

chrome developer tools screenshot In this screenshot can see it returns empty URL, but if i delete the if's of the resizeImage() i'll get full URL's but with empty image.
Sorry if I missing something but I'm new on Angular.


text:
Q: The searchbar of my django website isnt working This is the code in my base site(i.e base.html) for search bar:
       <form  method="get" class="navbar-form navbar-right" role="search">

          <input id="search_box" type="text" name="q" class="form-control" placeholder="Search this site" style="width:550%">

                   <button type="submit" id="s1" class="btn btn-default">

                    </button>

url of the searchbar view(present in "urls.py" of "myapp":
url(r'^search/?$', views.search)
view of the searchbar:
def search(request):
query= request.GET.get("q")
if query:
    queryset_list= queryset_list.filter(title__icontain=query)

I dont know why it's not working. im able to see search item in web browser url bar. but it's not showing any results in the webpage.


text:
Q: android - MYSQL PHP Android Chat not work Momently I'm working on an android chat application for my Website. At my Website I can chat in realtime but in my android app I don't know how to update the Listview when I got a new message. Also I would like get an notifycation at the device when the app don't open and I get a new message.
A least I have an app with an Chat overview. Also I can pen the chat, read old messages and send a new one. But after sending a new message the listview hasn't been updated.
Here are some Steps how I send/recive the messages:
SENDING MESSAGES:
void send_message(final String message) {
    Thread t = new Thread() {
        private String result = "";
        public void run() {
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            try{
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://mywebsite.com/app/send_message.php?email="+ MainActivity.user_email+"&with="+ chat_with+"&message="+message);
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
            }
            catch(Exception e){
                showAlert("ERROR", "No connection to Internet.");
            }
        }
    };
    t.start();
    getData(chat_with);
    listview = (ListView) findViewById(R.id.listView_chat);
    while(!this.dataComplete) {
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    this.updateData();

}

*

*Get new message content from editText

*POST the data to an PHP file on my webserver

*The PHP script insert the messsage and change the chat status for new mesages from a friend to 1

*Update the Listview(not working yet)

RECIVE MESSAGES:
public void get_messages(final String with_user) {
    Thread t = new Thread() {
        private String result = "";
        public void run() {
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            try{
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://mywebsite.com/app/get_messages.php?email="+ MainActivity.user_email+"&with="+ with_user);
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
            }
            catch(Exception e){
                showAlert("ERROR", "No connection to Internet.");
            }
            try{
                BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "n");
                }
                is.close();
                result=sb.toString();
            }
            catch(Exception e){
                showAlert("ERROR","Can't parse data.");
            }
            try{
                JSONArray jArray = new JSONArray(result);
                for(int i=0;i<jArray.length();i++){
                    json_data = jArray.getJSONObject(i);
                    results_messages.add((String) json_data.get("message"));
                }
                dataComplete = true;
            }
            catch(JSONException e){
                showAlert("ERROR","No connection to Internet.");
            }
        }};
    t.start();
}

*

*Get logged in user infos and friend infos

*POST data to PHP file on my webserver

*Get messages as json response

*Convert json to listview

*Auto refresh Listview if I get a new message(not working yet)
And to fill the Listview I use:
public void fillList() {
    listview.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, results_messages));
}

I hope I get some helpful answers.
Tip: message_adapter.notifyDataSetChanged(); I test but it don't work


text:
Q: ViewModel when implementing Room in Foreground Service I currently have an app with a ForegroundService for all server/API interactions, and a Room database for local persistence. I have been trying to implement an AndroidViewModel to help with data persistence and quick UI refreshes.
However, as per the documentation, ViewModels can't be implemented in Services, and so far I've used the Service to update information locally and notify components using LocalBroadcasts (which is what I want to eliminate using ViewModels and Observers).
I need to have the service running as the app needs to keep running in the background (its a mission critical app and the app getting closed means that the user will not be available to provide critical services), and update certain information on a periodic basis (nearby requests, etc. ).
So to ask the core question -

*

*How do I separate the service from the ViewModel, and if the service has the latest synced data from the servers, how do I update the (Mutable)LiveData lists in my ViewModel?

*This article and this answer to a question here on SO  says it is better to separate the ViewModel from the Repository while this other one gives an example of including the Room database inside the ViewModel. Which is the better option?

Some of my ViewModel code is as follows:
 public class HouseCallViewModel extends AndroidViewModel {

        private String TAG = HouseCallViewModel.class.getSimpleName();

        private MutableLiveData<List<HouseCall>> housecallList;
        private MutableLiveData<List<HouseCall>> openHousecalls, confirmedHousecalls, closedHousecalls, missedHousecalls, userCancelledHousecalls, respCancelledHousecalls;
        private MutableLiveData<List<Incident>> incidentList, openIncidents;
        private MutableLiveData<List<Incident>> closedIncidents, usercancelIncidents, respcancelIncidents;
        RevivDatabase database;
        Context context;

        public HouseCallViewModel(Application application) {
            super(application);

            //      DANGER WILL ROBINSON
            context = application.getApplicationContext();
            database = Room.databaseBuilder(this.getApplication(),
                    RevivDatabase.class, application.getResources().getString(R.string.database)).build();
        }
        public LiveData<List<HouseCall>> getHousecallList() {
                if (housecallList == null) {
                    housecallList = new MutableLiveData<>();
                    loadHousecalls(); // need to call API and sync
                }
                return housecallList;
            }
       public LiveData<List<HouseCall>> getIncidentList() {
                    if (incidentList == null) {
                        incidentList = new MutableLiveData<>();
                        loadIncidents(); // need to call API and sync
                    }
                    return housecallList;
                }

    // other constructors, getters and setters here, and functions to update the data
    }

A: 1)
As you did not provide code details about your Service and its related components, this answer is abstract.
To separate the ViewModel from the Service, create an Activity that will access the ViewModel; you will have an Activity, a ViewModel, and a Service.
This means that you will create a bound Service (https://developer.android.com/guide/components/services#CreatingBoundService and, more specifically, https://developer.android.com/guide/components/bound-services). A bound Service provides an interface that an Activity can use to interact with the Service.
A good example of a bound Service is Google's Location Update Service: https://github.com/googlesamples/android-play-location/tree/master/LocationUpdatesForegroundService/app/src/main/java/com/google/android/gms/location/sample/locationupdatesforegroundservice
In your instance, the Service will be tasked with originating data and transmitting that data to the Activity which will then provide that data to the ViewModel.
To transmit data from the Service to the ViewModel, I suggest using Greenrobot's EventBus (http://greenrobot.org/eventbus/documentation/how-to-get-started/).
Whenever you want the Service to transmit data to the ViewModel, a single-line call to EventBus in your Service will transmit the data to the Subscribers in the Activity that are listening for that type of data.
The Activity, upon receipt of data, will then update the ViewModel with the data. Any Observers registered with the ViewModel will then receive the latest data.
2)
The Separation of Concerns principle militates in favor of separating the ViewModel from the repository. The ViewModel should be concerned with only keeping state of data that will be displayed to the user, and keeping such state across configuration changes.


text:
Q: Is there a Dirichlet Unitary Unit Theorem? Dirichlet's unit theorem computes the group of units of the algebraic numbers of a number field. There are a few generalisations for orders available.
Assume the order has an involution. For example, the number field $\mathbb{Q}(\xi_1,\dots,\xi_n)$ can be equipped with an involution $\xi_k \mapsto \overline{\xi_k} = \pm \xi_k$ and the ring of algebraic numbers will (hopefully) inherit this involution.
It is natural to ask for the "unitary units" of the order i.e. all $x$ such that $x\overline{x}=1$.
Is there a theorem that tells us the structure of the group of unitary units? Do we know at least when this group is (in-)finite?

A: Yes.  Let $K \subset \mathbb{C}$ be a number field that is closed under complex conjugation (not necessarily Galois).
Modulo the roots of unity, the group of unitary units in $K$ is free of rank equal to the number of infinite primes of $K$ minus the number of infinite primes of the real subfield $K \cap \mathbb{R}$.  Recall that the number of infinite primes of a field is the number of real embeddings + half the number of complex embeddings.  This is proved nicely in this paper by Daileda.
Note that $K$ and its real subfield have the same number of infinite places iff either $K$ is totally real or $K$ is CM (meaning a totally imaginary quadratic extension of a totally real field).  So for precisely these cases, the only unitary units in $K$ are roots of unity.


text:
Q: How to play a video with any video format into HTML5 ( previously played using Flash) The problem faced is that when there is an input of a video (any video in any format), the web will play the video using flash technology. However, flash technology is no longer used and the video input will be played using HTML5. I'm stuck in this code and here is the code
This is a webscript for html5

<#if node??>${node.title!node.name}<#else>${msg("header.video")}</#if>

      ${msg("link.configure")}

${msg("label.preparingPreviewer")}


text:
Q: How to refactor to a higher order function? How to refactor this function to a higher order function?
It is meant to return a new array containing the sub-arrays of characters that contain the value 'Rambo'.
function isRamboCharacter(characters) {

 const x = [];

  for (let i = 0; i < characters.length; i++) {
    if (characters[i].movie.includes('Rambo')) {
      x.push(characters[i]);
    }
  }

return x;
}

I tried:
return characters.movie.includes('Rambo');

A: Solution

const characters = [
    { movie: ["Rambo", "Rockey", "Avengers"] },
    { movie: ["Fatherhood", "Rockey", "Avengers"] }
 ]

const isRamboCharacter = (characters) => characters.filter((char) => char.movie.includes("Rambo"))

console.log(isRamboCharacter(characters));

Or you could directly call Array's filter method
console.log(characters.filter((char) => char.movie.includes("Rambo")));

//output - [ { movie: [ 'Rambo', 'Rockey', 'Avengers' ] } ]

A: You can curry it (Return a function in a function)
function isCharacterInMovie(movie) {
  return function filterFunction(characters) {
    const x = [];
    for (let i = 0; i < characters.length; i++) {
      if (characters[i].movie.includes(movie)) {
        x.push(characters[i]);
      }
    }
    return x;
  }
}
const isRamboInMovie = isCharacterInMovie('rambo') // returns the inner function which holds on to the value from when you called it
 isRamboInMovie(charactersInTheMatrix); // []
 isRamboInMovie(charactersInRambo); // ['rambo']

The 'You don't know JS' book series has a great (short AND free) book on this, and it explains it incredibly well
You Don't Know JS Yet: Scope & Closures - 2nd Edition


text:
Q: Save Docker containers as single image I don't have much experience with Docker so not sure if this is even possible, but I'm trying to export my Docker containers as a single image.
I've created a web server using various images from the official repos (nginx, php7, postgresql). I have a docker-compose.yml file to start each container and link them.
There are volumes for the web hosting root directory and the postgresql data directories.
I now need to export this whole lot, including the volumes so that our technicians out in the field can easily install our web server on client networks. We generally do not have access to the internet on those PCs which is why I can't simply give them the compose and Dockerfiles.
Apologies if I'm not being clear but this is still pretty new to me.
web:
 image: nginx:latest

 environment:
  - DOCKER_WEB=true

 #stdin_open: true
 #tty: true
 ports:
 - "8080:80"

 volumes:
  - ./code:/code
  - ./default.conf:/etc/nginx/conf.d/default.conf

 links:
 - php

cron:
 build: './docker/cron'

 links:
 - web

throwaway:
 build: './docker/throwaway'
 volumes:
  - ./code:/code

php:
 #image: php:7-fpm
 build: './docker/php'

 links:
 - postgres

 volumes:
  - ./code:/code

postgres:
 image: postgres:latest

 environment:
  - POSTGRES_USER=un_rftags
  - POSTGRES_PASSWORD=pwd_RFT@gs01
  - POSTGRES_DB=db_rftags

 volumes:
  - ./postgres-data:/var/lib/postgresql/data

 ports:
 - "9090:5432"

A: You can save all your images at once with docker save, and then import them on the destination system with docker load.
This means, of course, that you need to create images, but you seem to be doing that already.
For example:
docker save nginx:latest cron throwaway php | xz -c > all-images.tar.xz

Import them to the destination docker with:
xz -dc < all-images.tar.xz | docker load


text:
Q: Hibernate JPA: 'IS EMPTY' condition doesn't work for collections passed as parameters I'm trying to write a query in which I need to check whether the collection passed as a parameter empty or not.
I'm writing something like this:
@Query("SELECT u FROM User u" +
        "WHERE" +
        "   :ids IS EMPTY" +
        "   OR u.id IN :ids")
Collection<User> findUsers(@Param("ids") Collection<String> ids);

This code fails on startup with QuerySyntaxException: ??? is not mapped. The stack-trace doesn't give any valuable information, but I found out that if I remove the next part:
:ids IS EMPTY

it starts working.
Q: How to use IS EMPTY for query parameters? Or how to check that collection is empty in any other way?
Note:

*

*I'm using Spring Boot 1.5.8.RELEASE.

*I also looked on "Passing empty list as parameter to JPA query throws error" which is different and didn't help.

*The code I posted is primitive, it was added just for illustration purpose, my real query is quite complex and I really need to check collection emptiness.

A: The JPA documentation clearly states, that you should avoid empty collections as parameters.
4.6.8 In Expressions from the JPA 1.0 specification

There must be at least one element in the comma separated list that defines the set of values for the IN expression.

If you think about it, JPA can't do much about it. if the query contains WHERE id in ?0 - how to handle an empty collection? WHERE id in () is invalid syntax, as well as WHERE id in... So it would neet to remove the whole where-constraint, which is not what is desired in most situations.
Guess you need to handle this in your Application rather than on a query level.
Side-Node: If you are working with filter values with only little options, you could get the result by adding ALL ids, if the user does not select something, i.e.
where color_id in (1,2,..,10) and type_id in (1,2,3) AND tile_id in (1,2,..,5)
instead of the invalid
where color_id in () and type_id in () AND tile_id in ()

Just not working, if you have thousands of options, or you'll exceed the query length.

A: In your query, you ask the database to check on the value of :ids, which is not a column in the database, but a Collection in your Java program.
So naturally the persistence framework has no idea what you are talking about and tells you "... is not mapped", which is true.
I think you probably wanted the following query:
@Query("SELECT u FROM User u" +
    "WHERE" +
    "   u.id IS NULL" +
    "   OR u.id IN :ids")

If that is not the case, please describe what you want to achieve with the query.


text:
Q: Pre-processor macro variables I have the code:
#DEFINE NEW = 1;

And a Struct:
typedef struct PCB
{

 /*Process state:new, ready, running, waiting, terminated*/
 int state;
 }PCB;

How can I assign NEW, such that state=1?
More info, I get the error:
expected ':', ',', ';', '}' or '__attribute__' before '=' token

A: Remove both semicolon and the =
#DEFINE NEW 1


text:
Q: How to ignore specific character on Regex.Match Hi this is my first question on this forum, as i don't find a solution for this on my own i decided to ask for help
string pattern = @"Chapter\s?(.*):\s*(.*)";
var m = Regex.Match(input, pattern);

I have been using this pattern but not all strings has the same format, i´d like to know if there a way to ignore the ":" character to make it work, or if there a better way to do it
//Examples:
"Chapter 3.10:  Some Text"
"Chapter 2.2:  Some Text(2)"
"Chapter 1.20"

//Outputs
"3.10" "Some Text"
"2.2" "Some Text(2)"
"" ""
// The last return nothing on both groups
// In this case i would like to get only the first group (the chapter number)

PS: My english can be poor but thanks in advance

A: You may use a pattern which the second group is optional:
Chapter\s?([^:]+)(?::\s*(.*))?

Demo
Your updated code:
string pattern = @"Chapter\s?([^:]+)(?::\s*(.*))?";
var m = Regex.Match(input, pattern);


text:
Q: Laravel - Undefined property: stdClass - search query So I have this Laravel car project with search. I do my search with DB::table() query and it's working fine until I add model relationship. I will explain, here is my code.
This is my search motoopremapretraga function:
/**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     */
    public function motoopremapretraga(Request $request)
    {
        $autoQuery = DB::table('motoopremas');

        //pretraga - marka i model
        foreach ($request->only(['marka', 'model']) as $term => $value) {
            if (empty($value)) {
                continue;
            }
            $autoQuery->where($term, $value);
        }

        //pretraga - cijena od/do whereBetween
        if (
            $cijenaod = (int)$request->input('cijenaod')
            && $cijenado = (int)$request->input('cijenado')
        ) {
            $autoQuery->whereBetween('cijena', [(int)$cijenaod = $request->input('cijenaod'), (int)$cijenado = $request->input('cijenado')]);
        }

        //pretraga - vrsta cijene
        if ($vrsta_cijene = $request->get('vrsta_cijene')) {
            $autoQuery->where('vrsta_cijene', $vrsta_cijene);
        }

        //pretraga - grupa opreme
        if ($grupa_opreme = $request->get('grupa_opreme')) {
            $autoQuery->where('grupa_opreme', $grupa_opreme);
        }

        //pretraga - djelovi
        if ($tip = $request->get('tip')) {
            $autoQuery->where('tip', $tip);
        }

        //pretraga - ostecenje
        if ($ostecenje = $request->get('ostecenje')) {
            $autoQuery->where('ostecenje', $ostecenje);
        }

        //pretraga - zamjena
        if ($zamjena = $request->get('zamjena')) {
            $autoQuery->where('zamjena', $zamjena);
        }

        //pretraga - stanje
        if ($stanje = $request->get('stanje')) {
            $autoQuery->where('stanje', $stanje);
        }

        //vracanje rezultata
        $automobili = $autoQuery->get();

        return view('site.motooprema.pretraga')->with('automobili', $automobili);
    }

You see I'm using DB::table('motoopremas') to find my results from search, and at the end just $automobili = autoQuery->get(); to specify my blade variable.
Okay then this is my results blade view really simple just to show if everything works fine:
@foreach($automobili->where('deleted_at', null) as $auto)
{{$auto->naslov}}
@endforeach

And everything is working fine, but when I add my relationship from my Motooprema.php model like this:
@foreach($automobili->where('deleted_at', null) as $auto)
<!-- this is my relationship -->
@if($auto->sifraMotoopremaaktivnosts->first()->status == 1)

{{$auto->naslov}}

@endif
@endforeach

It gives me ERROR like this:
Undefined property: stdClass::$sifraMotoopremaaktivnosts

And this is my Motooprema.php model with this sifraMotoopremaaktivnosts relationship:
public function sifraMotoopremaaktivnosts()
    {
        return $this->hasMany(Motoopremaaktivnost::class, 'sifra_id', 'id');
    }

I don't know what I'm doing wrong, I need to have this search and this relationship is just showing activated car posts. What should I do ?

A: DB::table does not return a Motooprema class.
For this reason you cannot use relationship. ( $auto->sifraMotoopremaaktivnosts... )
Replace the $autoQuery = DB::table('motoopremas'); line with $autoQuery = Motooprema::query(); and it should return an instance of Motooprema.


text:
Q: Problem with side scroller href with CSS and html I've been practicing code trying to make website with HTML and CSS, and I had an idea for a menu that you can scroll sideways. You've probably seen them, I have everything down but the href tags. Once you click on the letters, its supposed to jump to a certain "menuItem". click a, you go to b, b to c, c back to a. The problem is that it only works once, and after that, it stops jumping. So I can press a, it'll go to b, and then stop working when I press b to go to c. Please help, thanks.

.portfolioWrapper .portScroller {
  overflow: auto;
  white-space: nowrap;
  height: 100%;
}

.portfolioWrapper .portScroller li.a {
  width: 100%;
  background-color: blue;
  display: inline-block;
  text-align: center;
}

.portfolioWrapper .portScroller li.b {
  width: 100%;
  background-color: red;
  display: inline-block;
  text-align: center;
}

.portfolioWrapper .portScroller li.c {
  width: 100%;
  background-color: green;
  display: inline-block;
  text-align: center;
}

li.a a.oneAnch {
  text-align: right;
}

li.a a.twoAnch {
  text-align: right;
}

li.a a.threeAnch {
  text-align: right;
}

a

b

c

A: You avoid this problem by defining an  element to show the starting position before the list.

/* The following styles have been added. */
a {
  color: white;
  text-decoration: none;
}

.portfolioWrapper .portScroller {
  overflow: auto;
  white-space: nowrap;
  height: 100%;
}

.portfolioWrapper .portScroller li.a {
  width: 100%;
  background-color: blue;
  display: inline-block;
  text-align: center;
}

.portfolioWrapper .portScroller li.b {
  width: 100%;
  background-color: red;
  display: inline-block;
  text-align: center;
}

.portfolioWrapper .portScroller li.c {
  width: 100%;
  background-color: green;
  display: inline-block;
  text-align: center;
}

li.a a.oneAnch {
  text-align: right;
}

li.a a.twoAnch {
  text-align: right;
}

li.a a.threeAnch {
  text-align: right;
}

            First

            Second

            Thirth


text:
Q: Windows 7 Scheduled task command line This command should create a task that every minute runs the calculator windows application.
schtasks /Create /tn "mytask" /sc MINUTE /mo 1  /ru "myuser" /rp "mypassword" /tr "C:\Windows\System32\calc.exe"

It runs OK, the tasks gets added. The task looks right. The tasks shows as started in the schedular but the calculator does not get fired up. The exe exists, I can run it separately.
Anyone know why I don't see the calculator?

A: How to Create, Modify and Delete Scheduled Tasks from the Command Line
Windows XP/Server 2003 introduced us to the SchTasks command line tool which usurped the At tool offered in Windows 2000. This tool offers the ability to control every aspect of your Scheduled Tasks through calls to this command.
While the wizard Windows uses to help you graphically create Scheduled Tasks is very good, the command line tool is ideal for situations such as:
Manipulate tasks in batch scripts.
Control and create tasks on networked machines without having to login to them.
Mass create/sync task across multiple machines.
Use in custom applications to communicate with the Task Scheduler instead of having to make API calls.
Eg:
Create 'My Task' to run C:RunMe.bat at 9 AM everyday:
    SchTasks /Create /SC DAILY /TN "My Task" /TR "C:RunMe.bat" /ST 09:00
Modify 'My Task' to run at 2 PM:
SchTasks /Change /TN "My Task" /ST 14:00
Create 'My Task' to run C:RunMe.bat on the first of every month:
SchTasks /Create /SC MONTHLY /D 1 /TN "My Task" /TR "C:RunMe.bat" /ST 14:00
Create 'My Task' to run C:RunMe.bat every weekday at 2 PM:
SchTasks /Create /SC WEEKLY /D MON,TUE,WED,THU,FRI /TN "My Task" /TR "C:RunMe.bat" /ST 14:00
Delete the task named 'My Task':
SchTasks /Delete /TN "My Task"

A: Probably because the task isn't running interactively.  Add the '/it' option:

/IT
  A value that enables the task to run interactively only if the
  /RU user is currently logged on at the time the task runs. The task
  runs only if the user is logged on.

Without the /it option, tasks run in session 0, which doesn't allow interaction with the user.  For more information, do a web search for "Session 0 isolation".


text:
Q: How to change the hamburger menu to the word menu in shopify I am using the theme Simple in my Shopify store and I need to change the hamburger menu into the text "menu" instead. Also the website is www.allabouttoytrains.com I was playing with the inspect element trying to get the desired effect but I'm also posting the file containing the HTML incase it helps.
sidebar.liquid

    <button id="ToggleMobileMenu" class="mobile-menu-icon medium-up--hide" aria-haspopup="true" aria-owns="SiteNav">

      {{ 'layout.navigation.menu' | t }}
    </button>

        {% for link in menus[section.settings.main_menu_link_list].links %}
          {% assign child_list_handle = link.title | handleize %}
          {% if menus[child_list_handle].links != blank %}

              <button class="site-nav__link btn--link site-nav__expand hidden" aria-expanded="false" aria-controls="Collapsible{{ forloop.index }}">
                {{ link.title }}
                +
              </button>
              <button class="site-nav__link btn--link site-nav__collapse" aria-expanded="true" aria-controls="Collapsible{{ forloop.index }}">
                {{ link.title }}
                -
              </button>

                {% for childlink in menus[child_list_handle].links %}

 0 %} site-nav--active {% endunless %}{% endif %}">
                    {{ childlink.title | escape }}

                {% endfor %}

          {% else %}

              {{ link.title }}

          {% endif %}
        {% endfor %}
        {% if shop.customer_accounts_enabled %}
          {% if customer %}

              {{ 'layout.customer.account' | t }}

              {{ 'layout.customer.log_out' | t }}

          {% else %}

              {{ 'layout.customer.log_in' | t }}

              {{ 'layout.customer.create_account' | t }}

          {% endif %}
        {% endif %}

        {% if settings.social_facebook_link != blank %}

              {% include 'icon-facebook' %}
              Facebook

        {% endif %}
        {% if settings.social_twitter_link != blank %}

              {% include 'icon-twitter' %}
              Twitter

        {% endif %}
        {% if settings.social_pinterest_link != blank %}

              {% include 'icon-pinterest' %}
              Pinterest

        {% endif %}
        {% if settings.social_instagram_link != blank %}

              {% include 'icon-instagram' %}
              Instagram

        {% endif %}
        {% if settings.social_google_plus_link != blank %}

              {% include 'icon-google-plus' %}
              Google Plus

        {% endif %}
        {% if settings.social_tumblr_link != blank %}

              {% include 'icon-tumblr' %}
              Tumblr

        {% endif %}
        {% if settings.social_youtube_link != blank %}

              {% include 'icon-youtube' %}
              YouTube

        {% endif %}
        {% if settings.social_vimeo_link != blank %}

              {% include 'icon-vimeo' %}
              Vimeo

        {% endif %}
        {% if settings.social_fancy_link != blank %}

              {% include 'icon-fancy' %}
              Fancy

        {% endif %}
        {% if settings.main_blog != blank %}

              {% include 'icon-rss' %}
              Blog

        {% endif %}

{% schema %}
  {
    "name": "Sidebar",
    "settings": [
      {
        "type": "link_list",
        "id": "main_menu_link_list",
        "label": "Menu",
        "default": "main-menu"
      }
    ]
  }
{% endschema %}

A: a possible way is, to remove the 4 times

maybe then you have to set the height from your menu also.
actually I saw "menu" at your site and also the hamburger menu.
btw. this is not an elegant solution, it`s more quick and dirty.

A: Well, work the effect based on what you already have.

var McButton = $("[data=hamburger-menu]");
var McBar1 = McButton.find("b:nth-child(1)");
var McBar2 = McButton.find("b:nth-child(2)");
var McBar3 = McButton.find("b:nth-child(3)");

McButton.click( function() {
  $(this).toggleClass("active");

  if (McButton.hasClass("active")) {
    McBar1.velocity({ top: "50%" }, {duration: 200, easing: "swing"});
    McBar3.velocity({ top: "50%" }, {duration: 200, easing: "swing"})
       .velocity({rotateZ:"90deg"}, {duration: 800, delay: 200, easing: [500,20] });
    McButton.velocity({rotateZ:"135deg"}, {duration: 800, delay: 200, easing: [500,20] });
  } else {
    McButton.velocity("reverse");
  McBar3.velocity({rotateZ:"0deg"}, {duration: 800, easing: [500,20] })
       .velocity({ top: "100%" }, {duration: 200, easing: "swing"});
   McBar1.velocity("reverse", {delay: 800});
  }
});
/* Global Styles */
body {
  margin: 0;
  padding: 0;
  background-color: hsl(355, 75%, 56%);
}
/* Hamburger Menu */
.McButton {
  position: absolute;
  top: 50%;
  left: 50%;
  margin-left: -22px;
  margin-top: -22px;
  width: 44px;
  height: 33px;
  cursor: pointer;
}
.McButton b {
  position: absolute;
  left: 0;
  width: 44px;
  height: 3px;
  background-color: white;
}
.McButton b:nth-child(1) {
  top: 0;
}
.McButton b:nth-child(2) {
  top: 50%;
}
.McButton b:nth-child(3) {
  top: 100%;
}
/* McButton */


text:
Q: How to share variables between routes in Flask (python) I am trying to use sessions to share variables among routes in Flask. This is the code I am using:
from flask import Flask, jsonify, request, session
from flask_cors import CORS
from flask_session import Session

app = Flask(__name__)
CORS(app)

SESSION_TYPE = 'filesystem'
app.config.from_object(__name__)
app.secret_key = 'abc'

@app.route("/getinputData", methods = ['POST'])
def getData():
    inputData = json.loads(request.data)
    molID = inputData["ID"]
    searchType = inputData["searchType"]
    session["sharedmolID"] = molID
    session["sharedsearchType"] = searchType
    return inputData

@app.route("/querydatabyMol", methods = ['GET'])
def querydatabyMol():
    sharedmolID = session.get("sharedmolID", None)
    sharedsearchType = session.get("sharedsearchType", None)
    print(sharedmolID)
    print(sharedsearchType)
    return sharedmolID

if __name__ == '__main__':
    app.run(debug=True)

sess = Session()
sess.init_app(app)

But when the second route prints the variables I get None. I have temporarily solved this using global variables, but I read that they are not thread safe, so I would like to use sessions.
Any idea of what is wrong here?

A: You could try replacing the "session.get()" Method with:
@app.route("/querydatabyMol", methods = ['GET'])
def querydatabyMol():
    sharedmolID = session["sharedmolID"]
    sharedsearchType = session["sharedsearchType"]
    print(sharedmolID)
    print(sharedsearchType)
    return sharedmolID

also see this for a related problem


text:
Q: Change width of event in FullCalendar (React JS) I like to change the width of an event in context of React JS.
Similiar questions described here:

*

*How to edit width of event in FullCalendar?

*Change Fullcalendar width

*...

Unfortunately, in the quoted questions is nothing mentioned how to solve this in a react environment.

A: I figured it out how to do it. eventRender does no longer exist (v4) but instead different "event render hooks" (v5):

*

*eventClassNames: Specifically for changing the .css of an event

*eventContent: To inject content into the event

*and others (see:https://fullcalendar.io/docs/event-render-hooks)

Now, depending what you want to achieve, there are two ways to do this in React JS. (Note: I used TypeScript)
Applying CSS change to all events
We can use styled to create our own .css definition for any event and use that as a wrapper (StyleWrapper)
import React from 'react';
import FullCalendar from '@fullcalendar/react';
import timeGridPlugin from '@fullcalendar/timegrid';
import styled from '@emotion/styled';
export interface ISampleProps {}

//our Wrapper that will go around FullCalendar
export const StyleWrapper = styled.div`
    .fc-event {
        width: 98px !important;
    }
`;
//Reacct Functional Component
const Sample: React.FunctionComponent<ISampleProps> = (props) => {

    const events = [
       /*some events */
    ];

    return (
        <>

        </>
    );
};

export default Sample;

Apply specific CSS to specific events
With this way, you can tell FullCalendar exactly how an event has to look like depending self-defined props you add to an event. Your self-defined props will be added to extendedProps which will be used in our event render hook eventClassNames
//same imports from earlier (but you don't need "styled" for this one)
const Sample: React.FunctionComponent<ISampleProps> = (props) => {

     function eventAddStyle(arg: any) {
        //all self-created props are under "extendedProps"
        if (arg.event.extendedProps.demanding) {
            return ['maxLevel']; //maxLevel and lowLevel are two CSS classes defined in a .css file
        } else {
            return ['lowLevel'];
        }
    }

    const events = [
        {
            id: 'a',
            title: 'This is just an example',
            start: '2022-03-19T12:30:00',
            end: '2022-03-19T16:30:00',
            backgroundColor: '#74AAEB',
            demanding: true //our self-created props
        },
        {
            id: 'b',
            title: 'This is another example',
            start: '2022-03-17T08:00:00',
            end: '2022-03-17T11:30:00',
            demanding: false // our self-created props
        },
    ];
    return (
        <>

                <FullCalendar
                    plugins={[timeGridPlugin]}
                    initialView="timeGridWeek"
                    eventClassNames={eventAddStyle}
                    events={events}
                />

        </>
    );
};

export default Sample;


text:
Q: Set bootstrap modal body height by percentage I am trying to make a modal with a body that will scroll when the content becomes too large. However, I want the modal to be responsive to the screen size. When I set the max-height to 40% it has no effect. However, if I set the max-height to 400px it works as expected, but is not responsive. I am sure I am just missing something simple, but I can't seem to get it to work.
Here is an example
Doesn't work:
.modal-body {
    max-height:40%;
    overflow-y: auto;
}

Works:
.modal-body {
    max-height:400px;
    overflow-y: auto;
}

A: This worked for me
.modal-dialog,
.modal-content {
    /* 80% of window height */
    height: 80%;
}

.modal-body {
    /* 100% = dialog height, 120px = header + footer */
    max-height: calc(100% - 120px);
    overflow-y: scroll;
}

Fiddle: http://jsfiddle.net/mehmetatas/18dpgqpb/2/

A: You've no doubt solved this by now or decided to do something different, but as it has not been answered & I stumbled across this when looking for something similar I thought I'd share my method.
I've taken to using two div sets. One has hidden-xs and is for sm, md & lg device viewing. The other has hidden-sm, -md, -lg and is only for mobile. Now I have a lot more control over the display in my CSS.
You can see a rough idea in this js fiddle where I set the footer and buttons to be smaller when the resolution is of the -xs size.

          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    <button type="button" class="btn btn-primary">Save changes</button>

    <button type="button" class="btn btn-xs btn-default" data-dismiss="modal">Close</button>
    <button type="button" class="btn btn-xs btn-primary">Save changes</button>

A: Instead of using a %, the units vh set it to a percent of the viewport (browser window) size.
I was able to set a modal with an image and text beneath to be responsive to the browser window size using vh.
If you just want the content to scroll, you could leave out the part that limits the size of the modal body.
/*When the modal fills the screen it has an even 2.5% on top and bottom*/
/*Centers the modal*/
.modal-dialog {
  margin: 2.5vh auto;
}

/*Sets the maximum height of the entire modal to 95% of the screen height*/
.modal-content {
  max-height: 95vh;
  overflow: scroll;
}

/*Sets the maximum height of the modal body to 90% of the screen height*/
.modal-body {
  max-height: 90vh;
}
/*Sets the maximum height of the modal image to 69% of the screen height*/
.modal-body img {
  max-height: 69vh;
}

A: This should work for everyone, any screen resolutions:
.modal-body {
    max-height: calc(100vh - 143px);
    overflow-y: auto; }

First, count your modal header and footer height, in my case I have H4 heading so I have them on 141px, already counted default modal margin in 20px(top+bottom).
So that subtract 141px is the max-height for my modal height, for the better result there are both border top and bottom by 1px, for this, 143px will work perfectly.
In some case of styling you may like to use overflow-y: auto; instead of overflow-y: scroll;, try it.
Try it, and you get the best result in both computer or mobile devices.
If you have a heading larger than H4, recount it see how much px you would like to subtract.
If you don't know what I am telling, just change the number of 143px, see what is the best result for your case.
Last, I'd suggest have it an inline CSS.

A: The scss solution for Bootstrap 4.0
.modal {
  max-height: 100vh;
  .modal-dialog {
    .modal-content {
      .modal-body {
        max-height: calc(80vh - 140px);
        overflow-y: auto;
      }
    }
  }
}

Make sure the .modal max-height is 100vh. Then for .modal-body use calc() function to calculate desired height. In above case we want to occupy 80vh of the viewport, reduced by the size of header + footer in pixels. This is around 140px together but you can measure it easily and apply your own custom values. For smaller/taller modal modify 80vh accordingly.

A: this is the solution

.modal-dialog{
            height:100%
        }
        .modal-content{
            height:90%
        }
        .modal-body{
            height:100%;
            overflow:auto
        }


text:
Q: Let $f(x)$ be irreducible in $F[x]$, where $F$ is a field. If $f(x) | p(x)q(x)$, prove that either $f(x) | p(x)$ or $f(x) | q(x)$.
Let $f(x)$ be irreducible in $F[x]$, where $F$ is a field. If $f(x) | p(x)q(x)$, prove that either $f(x) | p(x)$ or $f(x) | q(x)$.

Is this true because every irreducible element in a field is prime?

A: Yes, every irreducible element in $F[x]$ geberates a prime ideal, since $F[x]$ (polynomial ring in one indeterminate over a field) is a P.I.D.
The same would be true for several indeterminates since $F[x_1,\dots ,x_n]$ is a U.F.D.

A: Prove it by contradiction(using factorisation of $p(x)\ and\ q(x)$),i.e.,
Case 1: Both of p(x) and q(x) are irreducible
This is not possible because then $p(x)$ and $q(x)$ are the only factors of $p(x)q(x)$.
Case 2: Exactly one of them is reducible
In this case, $f(x)$ must be a factor of the reducible one($\because$ only factors of $p(x)q(x)$ are the irreducible polynomial and the factors of the reducible one)
Case 3: Both of them are reducible
Say $$p(x) = \prod_{i=1}^mg_i^{k_i}(x)$$ $$q(x) = \prod_{i=1}^nh_i^{l_i}(x)$$
Then, $f(x)$ being a factor of $p(x)q(x)$, must be factored in terms of $g_i(x)$ and $h_i(x)$,which is a contradiction to its irreducbility.
Hope it is helpful

A: $F[X]$ with $F$ a field is a unique factorisation domain, so the irreducible elements are prime and the conclusion is straightforward.


text:
Q: HDD dismounts when reading a specific file For the life of me I can't find the answer on google.
I have damaged files on my additional internal hard drive, when the HDD tries to read them, it dismounts on it's own.
I bought a new hard disk and copied all the files from the old one there, and I get the same problem on the new one, so it's definitely a file issue.
Trying to delete the damaged files with windows explorer causes a dismount and fails.
How do I correct this so that all the files work?
Deleting them is fine, but recovery is preferred.


text:
Q: Clear jQuery placeholder on submit I use jQuery to simulate the HTML5 placeholder function:
// placeholder code
$(function() {
    $('[placeholder]').focus(function() {
      var input = $(this);
      if (input.val() == input.attr('placeholder')) {
        input.val('');
        input.removeClass('placeholder');
      }
    }).blur(function() {
      var input = $(this);
      if (input.val() == '' || input.val() == input.attr('placeholder')) {
        input.addClass('placeholder');
        input.val(input.attr('placeholder'));
      }
    }).blur().parents('form').submit(function() {
      $(this).find('[placeholder]').each(function() {
        var input = $(this);
        if (input.val() == input.attr('placeholder')) {
          input.val('');
        }
      })
    });
});

When I now submit the form without changing the placeholders, it uses the placeholders as values.
Can you tell me how to remove all values / placeholders from the textfields when clicking on the submit button? I have seen some solutions here, but it didn't work with the placeholder attribute.
Here is one of my textfield:
<input class="frmInputLong" name="inptName" type="text" value="" placeholder="Peter Smith">

Here is my form definition:
<form id="frmBook" method="post" action="doSomething" >

A: Either execute the submit using jQuery's .submit or add .click handler to the submit button. Inside the function you can do something along the lines of:
$("input").attr("placeholder", "");

This sets the value of the attribute "placeholder" to an empty string.

A: This should clear all placeholders right before submit unless filled with an actual value
$("form:has(.placeholder)").live("submit", function(e){
  $(this).find(".placeholder").val("");
});


text:
Q: How to play RMTP audio url in AVAudioPlayer Swift I am looking to a great way to implement audio streaming using RMTP url in AVAudioPlayer.
Any ways to make this possible?  Or any suggestions?
Thanks
UPDATE 1: Code included
So here is the code:
let queue : dispatch_queue_t = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
        dispatch_async(queue, { () -> Void in
            if let songData = NSData(contentsOfURL: url) {
                if let player = AVAudioPlayer(data: songData, error: nil) {
                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        self.audioPlayer = player

                        self.audioPlayer!.delegate = self

                        if let startTime = startingTime {
                            self.audioPlayer?.currentTime = startTime
                        }

                        self.audioPlayer!.prepareToPlay()
                        self.audioPlayer!.play()
                        self.delegate?.mmPlayerManagerDelegate_playerStartedPlaying()
                    })
                }
            }
            else {
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    if appDelegate.bIsCurUserListener == false {
                        //=>    Call delegate
                        self.delegate?.mmPlayerManagerDelegate_prepareNextSongToPlay()
                    }
                })
            }
        })

And url is here:

*

*"rtmpLocation" : "rtmp://limelight-fmstream-42.musicnet.com/a4396/e1",

*"rtmpResource" : "mp4:/spl/114/602/883/spl_029.mp4?e=1435348059&h=8b4b2fd16683faa9bda9b4bab6d79705",


text:
Q: Real time update from a variable in php I have this code and its working fine. It shows real time update.
function progress($resource,$download_size, $downloaded, $upload_size, $uploaded)
{
if($download_size > 0)
    $GLOBALS['progress'] = round($downloaded / $download_size  * 100);
    echo $GLOBALS['progress'];
    echo str_pad("", 1024, " ");
    flush();
    usleep(20000);
}

Then why this code doesn't show real time update. It shows 100 at the end of execution of script.
function progress($resource,$download_size, $downloaded, $upload_size, $uploaded)
{
if($download_size > 0)
    $GLOBALS['progress'] = round($downloaded / $download_size  * 100);
 }
if($GLOBALS['progress']) {
echo $GLOBALS['progress'];
echo str_pad("", 1024, " ");
flush();
usleep(20000);
 }

Actually I don't need to show real time update. What I want is to start a task when the value of $GLOBALS['progress'] is greater than 0. For ex.
if($GLOBALS['progress']>0){
  //start another download immediately not when the value reaches to 100
}

When I am trying with 2nd version of my code it starts the task when the value is 100. I need immediately to execute a code as soon as its value reaches to 1 or greater than 0. Can anyone tell why 2nd version of my code is not working and how can I accomplish my actual task? Any suggestion will be greatly appreciated.


text:
Q: Java streaming options to merge the list of string on the same map object I have use case to get the distinct value from the map. Is there any way using streams
Sample Model data set = {"Ford":{"hatchback", "sedan", "TEST"}, "Honda":{"hatchback", "sedan"}, "Toyota":{"hatchback", "sedan", "TeST2"}}

for (Entry<String, Set<String>> model: models.entrySet()) {
modelList.addAll(model.getValue());
}

Final List: {"hatchback", "sedan", "TEST", "TeST2"}

A: You can use .flatMap() and .collect() like this
Preparation of Data just to showcase:
    HashMap<String, Set<String>> models = new HashMap<>();
    models.put("Ford", Set.of("hatchback", "sedan", "TEST"));
    models.put("Honda", Set.of("hatchback", "sedan"));
    models.put("Toyota", Set.of("hatchback", "sedan", "TeST2"));

Usage of .flatMap() and .collect() on a stream
    Set<String> uniqueModels = models.entrySet().stream()
            .flatMap(entry -> entry.getValue().stream())
            .collect(Collectors.toSet());

    // This will print "[TEST, sedan, hatchback, TeST2]"
    System.out.println(uniqueModels);

A:         List<String> unique=set.stream().flatMap(map->map.values().stream()).flatMap(list->list.stream()).distinct().collect(Collectors.toList());


text:
Q: What is the fastest way of copying long paths for the cp command? I'm controlling a Linux based NAS through SSH on a Windows computer. What I'm trying to do is use the cp -al command to rapidly copy folders from one directory to another, hardlinking all the files inside. Currently what I do is I list the directory with ls, then I highlight it with my mouse, copy it with right click, then paste it back in, for example if I'm hardlinking a directory called "Madagascar.2005.1080p.BluRay.DTS.x264" I would copy only the name of that directory, then manually write out
cp -al "sourceDir/Movie/ then I paste in the "Madagascar.2005.1080p.BluRay.DTS.x264". I do the same for the second directory to build the whole command:
cp -al "sourceDir/Madagascar.2005.1080p.BluRay.DTS.x264" "dstDir/Movie/Madagascar.2005.1080p.BluRay.DTS.x264"
This whole process is pretty cumbersome, and feels unnatural when everything else done on linux shell is done without the mouse.
Is there a better way of building this long command without having to copy and paste things using the mouse, or to type out entire names manually?
edit: I do not want to delete the source directory. The source directory looks like this aproximately:
'Lost S04 720p BluRay DTS x264
 Lost.S03.720p.BluRay.DTS.x264
'Million.Dollar.Extreme.Presents.World.Peace.S01.1080p'
'The Simpsons S01 1080p DSNP WEBRip DDP5.1 x264'
'The Simpsons S02 1080p DSNP WEBRip DDP5.1 x264'

I will be changing the source or destination directories frequently.

A: So, first of all, you clearly are trying to work as if you had a proper file manager. That's not a crime, and you should use one :)
Traditionally, Midnight Commander is the tool you should use, mc; chances are you can directly install it on your NAS, even!
In this day and age, ranger (you say you're on debian, so sudo apt install ranger it is.) is probably closer to what you want, it feels a lot more modern. You can  select multiple files in any "pane" with space, and then press @ to run a command on them: You'll see :shell  %s at the bottom of the screen. The %s will be expanded to all the selected file names when you hit enter, so just type in your command, so that there's :shell cp -al -t /dstDir/Movie %s and hit enter. That's it.
However, ranger is a mighty tool (and so is mc, which at least has more prominent menus!), and 10 minutes with a tutorial will probably make a world of a difference.

without having to copy and paste things using the mouse, or to type out entire names manually?

You need to have heard about tab-completion that all but the most rudimentary shells have! Type the first letters of any file name, hit tab. If there's only one file that starts like that, it gets completed. If there's multiple choices, press tab twice to get a list of candidates. (If you're using zsh with oh-my-zsh, or some of the many other good shell extenders instead of stock bash, you will get to enjoy even more handy completion).

A: The fastest way to Copy-Paste long file names would be to not Copy-Paste at all !
(1) Use a variable:
Eg:
cd sourceDir/
OneDir=$(ls -d Mada*) # Make sure you get only One Directory ; no Copy with mouse !
echo $OneDir # verify
cp -al "$oneDir" "../dstDir/Movie/$OneDir" # Navigate to Dest Directory ; no Paste with mouse !
OneDir=$(ls -d T*Sim*S01*)
echo $OneDir
cp -al $oneDir ../dstDir/Movie/$OneDir
OneDir=$(ls -d T*Sim*S02*)
echo $OneDir
cp -al $oneDir ../dstDir/Movie/$OneDir

(2) Augment that with a script to automate it:
# Pseudo-Code
cd sourceDir/
for OneDir in $(ls -d *) {  # Use the "for" Syntax (& Quoting Syntax) according to your Shell
    echo $OneDir  # You could include interactivity, to ask whether to Process Current OneDir or not
    cp -al "$oneDir" "../dstDir/Movie/$OneDir"
}

A: You say that you want to,

use the cp -al command to rapidly hard link folders from one directory to another

But then you show a process for copying a file at a time.
If you actually want to copy a directory and its contents, this command will do it all in one step:
cp -al sourceDir/. dstDir/Movie/

Perhaps you want to move selected files from your sourceDir to different dstDir directories. You can use wildcards to pick up one or more files matching a pattern, or Tab to autocomplete a partially typed name (hit it a second time to see the set of remaining matches):
cp -al sourceDir/Lost* dstDir/Movie/


text:
Q: XAMPP .htaccess AddEncoding br brotli I install no my MacOs HighSierra fresh XAMPP (osx-7.4.6-0-vm) and start it - server runs on IP 192.168.64.2 . Then I mount /opt/lampp and click to Explore. The Finder window open and I go to directory htdocs/. Then inside htdocs I create folder assets and inside it I copy file alice.wasm (this file is compressed using brotli (br)). You can download this test (brotli compressed) file using this jsfiddle generator. Inside htdocs I create following  .htaccess file
<IfModule mod_mime.c>
  AddType application/wasm .wasm
  AddEncoding br .wasm
  AddOutputFilterByType DEFLATE application/wasm
</IfModule>

Problem
When I go to http://192.168.64.2/assets/alice.wasm browser not download file and in chrome>networks tab I see (here are more details)

(failed) net::ERR_CONTENT_DECODING_FAILED

However, when I change AddEncoding br .wasm to AddEncoding rar .wasm (or instead 'br' I use zip, or none) then browser download file (details) but the problem is that browser automatically NOT decompress file (so it save compressed file).
When I put this .htacces file and alice.wasm file to some AZURE apache-like server (but I don't have access to it configuration files) then browser download file and decompress it on the fly (details) - so this is POSSIBLE.
Question: What I should do to make XAMPP working as expected?

A: brotli module works only on HTTPS mod. See it here: why does not brotli work on http?. If you have ssl certificate, it will work there.

A: It is very strange, but when I enable port forwarding

And go to http://localhost:8080/assets/alice.wasm then Chrome download file and automatically decompress it (exactly what I want). AZURE works on HTTPS and file was downloaded properly probably because brotli compression is support only for HTTPS - however probably on Chrome localhost is 'special' and allows it too.


text:
Q: Quadratic Form in Gauss-Markov Theorem The following is the derivation of the Gauss-Markov Theorem in Greene's Econometric Analysis (8th ed.)

I am trying to understand two points about the passage in yellow about the quadratic form.

*

*Why does $DD'$ have a quadratic form?

*For $Var[b_o|X] \geqslant Var[b|X]]$, $DD'$ must be equal or greater than 0. Why is this true?


text:
Q: JavaFX и наполнение ComboBox объектами Есть класс Street, с описанием объекта типа "улица", который содержит себе private String name;, private int id;, private String tymeName и private int typeId, а так же public методы для получения значений данных переменных.
Также есть @FXML ComboBox<Street> streetList;
Задача: нужно вывести список улиц беря названия из переменной name с помощью метода getName. а при выборе определённой улицы запускать обработку события через new ChangeListener<Street>() {...}.
Пытался сделать по аналогии с TableView и TableColumn через .setCellFactory и коллекции.
Вопрос: Как сделать, что бы из объекта в список забирался атрибут name через getNameи срабатывал new ChangeListener<Street>() {...} передавая выбранный объект для дальнейшей работы.
Метод тыка, в данном случае, не помогает.
Как реализовать поставленную цель через строки понятно. Но вот что получится, если, на пример, в списке будет Ленина и Ленина? Причём первый вариант - проспект, второй - улица, но в выпадающем списке это не должно обозначаться. Опять же можно придумать обход через строки, но, как мне кажется, возможно решить через передачу объектов, а не только строк. В таблицах же данный метод работает.

A: Поочередно отвечаю на вопросы.

нужно вывести список улиц беря названия из переменной name с помощью
  метода getName

streetList.setCellFactory(p -> new ListCell <Street> () {

    @Override
    protected void updateItem(Street item, boolean empty) {
        super.updateItem(item, empty);
        if (item != null && !empty) {
            setText(item.getName());
        } else {
            setText(null);
        }
    }
});

а при выборе определённой улицы запускать обработку события через new
  ChangeListener() {...}.

streetList.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) - > {
    //тут описываешь логику лисенера
});

тут я использовал лямбду, а не new ChangeListener()...

Но вот что получится, если, на пример, в списке будет Ленина и
  Ленина? Причём первый вариант - проспект, второй - улица, но в
  выпадающем списке это не должно обозначаться

У тебя будет и проспект и улица, если объекты Street будут разные ( необходимо переопределить методы hashCode() и equals())
UPDATE
По поводу картинки в коментарии, возможны 2 пути.

*

*Переопределить метод toString() в классе Street

*Переопределить buttonCell следующим образом
streetList.setButtonCell(new ListCell < Street > () {
@Override
protected void updateItem(Street item, boolean empty) {
    super.updateItem(item, empty);
    if (item != null && !empty) {
        setText(item.getName()); // или любую другую логику тут можно написать
    } else {
        setText(null);
    }
}

A: В дополнение к ответу @AndrewBystrov. Чтобы в текстовом поле ComboBox после выбора элемента также отобразился один из его аргументов, необходимо прописать конвертер:
public class StringConverterStreet extends StringConverter<Street> {

    @Override
    public String toString(Street street) {
        return street == null ? null : street.getName();
    }

    @Override
    public Street fromString(String string) {
        return null;
    }

}

Использовал его перед
streetList.setConverter(new StringConverterStreet());
streetList.setCellFactory(p -> new ListCell <Street> () {
    @Override
    protected void updateItem(Street item, boolean empty) {
        super.updateItem(item, empty);
        if (item != null && !empty) {
            setText(item.getName());
        } else {
            setText(null);
        }
    }
});

UPDATE
Воспользовался советом @AndrewBystrov и вместо конвертера просто переопределил метод toString. В результате получилось следующее:
public class Street {
    private int id, typeId;
    private String typeName, name;

    public Street() {
        Street(null, null, null, null);
    }

    public Street(...) {
        ...
    }

    public String getName () {
        return name;
    }

    ...

    @Override
    public String toString () {
        return typeName + " " + name;
    }
}

Спасибо большое за помощь!


text:
Q: Fourier series-odd and even functions
f+ is the even part of the function and f- is the odd part. I'm not able to understand how it is that they got the values of modulus of x and x for the even and odd parts of the function respectively.
For the even part, I think it might be because f(x) would be reflected in the y-axis but then for the even part shouldn't we have modulus of 2x instead of modulus of x?
For the odd part I have no idea how they got it to be x.
Any help would be much appreciated.

A: For a general function $f$, you can find the odd and even parts as follows:
If $f(x) = f^+(x) + f^-(x)$, then $f(-x) = f^+(x) - f^-(x)$ (by properties of even/oddness).
Then
$$
\frac12(f(x) + f(-x)) = f^+(x)
$$
and
$$
\frac12(f(x) - f(-x)) = f^-(x).
$$


text:
Q: copy each file to each folder I'm very impressed with your knowledge level.
My question is:
I have a folder with 31 MP3 files, one to each day of the month.
I need a batch to create folders named 01 02....31 and copy the 01.mp3
to 01 folder, 02.mp3 to 02 folder and so forth.
This is possible in the windows server 2k8 r2 command?
I try to use the following:
FOR /F %%j in (filelist.txt) do (
FOR /F "tokens=1 delims=." %%i in (filelist.txt) do (
xcopy %%j e:\%%i\
))

And a lot of others...
But the batch creates 31 folders with 31 MP3 files on each folder.
Best Regards.
          Leopoldo.

A: You have nested loops, each of which goes through the entire list of files. That is why you end up with 31 folders each containing 31 file.
Instead, you should probably process the list just once. Try this:
FOR /F %%j IN (filelist.txt) DO XCOPY %%j E:\%%~nj\

The ~n modifier changes the value of %%j so it evaluates to name only (01.mp3 -> 01).
Read help on the FOR command (FOR /?) to get more information about modifiers.

A: Since this was the first result on google and Andriy's example does not work. Here is an actually working result
for /r "%CD%" %%f in (.) do (copy "filelist.txt" "%%~ff" > nul)

Credit to extramaster


text:
Q: how to update xml file attribute with new value (add date time) in shell script? This is my xml below
<Deployer exitOnError="true" sourceType="Repository">
<Projects projectPrefix="">
<SubProject description="" name="Ship" overwrite="false" type="Repository">
</SubProject>
</Projects>
</Deployer>

I want o change name="Ship" to name="Ship"+currentdatetime using shell script. Any help appreciated.
I want to use sed or awk preferably (I dont want xmlstarlet as I cannot have xml tool box on my linux machine)
Please find below, which I tried.
sed "/DeployerSpec>/,<Project description='' name='bstar' overwrite='false' type='Repository'>" file

sed -i 's:<DeployerSpec exitOnError="true" sourceType="Repository"><Projects projectPrefix=""><Project description="" name="bstar" overwrite="false" type="Repository"></Project></Projects></DeployerSpec>:<DeployerSpec exitOnError="true" sourceType="Repository"><Projects projectPrefix=""><Project description="" name="bstar"+$(date+%x_%r) overwrite="false" type="Repository"></Project></Projects></DeployerSpec>:' sample.xml

sed -i.bak "s/<Project description='' name='bstar' overwrite='false' type='Repository'>/<Project description='' name='bstar'+$(date +%x_%r) overwrite='false' type='Repository'>/g" a.xml

A: Struggling with managers and client is an eternal process ... I understand.For you simple case you may use sed approach:
sed -i 's/name="Ship"/name="'"$(date)"'"/g' your.xml

The xml file content (you'll have a different datetime at your locale):
<Deployer exitOnError="true" sourceType="Repository">
<Projects projectPrefix="">
<SubProject description="" name="Mon 22 May 15:41:23 EEST 2017" overwrite="false" type="Repository">
</SubProject>
</Projects>
</Deployer>

*

*-i - to modify the file in-place

*$(date) - to get current datetime value

Anyway, if there would be more complex and sophisticated tasks like "change attribute name value if it's a child of the parent element ServiceProject and that parent should also have a child element city with attribute balance greater than 1000". Unix shell tools will fail in such cases and your managers would have a need to reconsider their attitude for XML parsers

A: try:
DATE=$(date)
sed 's/Ship/& '"${DATE}"'/g' Input_file

creating a variable named DATE which has current date, then simply using sed to substitute string Ship with Ship and current date.

A: sudo sed -i '/<Project\s\description=""/s/name="[^"]*/name="'"$(date)"'"/g' Demo.xml


text:
Q: Differences between Abstract Factory Pattern and Factory Method,confused by one case The main difference between a "factory method" and an "abstract factory" is that the factory method is a single method, and an abstract factory is an object. But, sometimes I can't say what it is,for example
class Product{

}
interface Facotory{
    public Product create();
}

class FactoryA implements Facotory{
public Product create() {
    return null;
}
}

class FactoryB implements Facotory{
    public Product create() {
    return null;
    }
}

Can you tell me it is factory method or abstract factory?Thank you!

A: IMO, Your current example above is Factory Method.
As you have defined an interface (Factory) with a factory method (create) that allows sub classes (FactoryA and FactoryB) to decide which class to instantiate (Product derived classes).


text:
Q: Vb.net Excel move to next row Hey all I am looking to see how to go about moving 1 row over where I am currently in my spreadsheet.
I have tried:
Dim xlsApp As Excel.Application
Dim xlsWB As Excel.Workbook
Dim xlsSheet As Excel.Worksheet
Dim xlsCell As Excel.Range

xlsCell = xlsSheet.Range("A1", "A100")

For Each oRowRange As Excel.Range In xlsCell.Rows
    For Each oCellRange As Excel.Range In oRowRange.Columns

      If colorRGB = "252, 213, 180" Then
         Debug.WriteLine(oCellRange.Text)
         oCellRange.Offset(0, 1).Select()
         Debug.WriteLine(oCellRange.Text)
         etc...
      End If
    Next
Next

In the example above, it keeps putting the same text:

BOB
BOB

When it really should be:

BOB
JON

So any help would be great!

A: I think your issue is that you use the same line twice Debug.WriteLine(oCellRange.Text). After the first one, the oCellRange isn't changed. You're using .Select, kind of.  You do .Select, but then never use Selection...this is a good thing.  However, just tweak that second line and remove the .Select line:
     Debug.WriteLine(oCellRange.Text)
     Debug.WriteLine(oCellRange.Offset(0, 1).Text)

Edit: Alternatively, you could replace the .Select line with Set oCellRange = oCellRange.Offset(0,1) and leave that third line as is.  However, I don't suggest this and would personally keep the .Offset() method.


text:
Q: Spark Fixed Width File Import Large number of columns causing high Execution time I am getting the fixed width .txt source file from which I need to extract the 20K columns.
As lack of libraries to process fixed width files using spark, I have developed the code which extracts the fields from fixed width text files.
Code read the text file as RDD with
sparkContext.textFile("abc.txt")

then reads JSON schema and gets the column names and width of each column.

*

*In the function I read the fixed length string and using the start and end position we use substring function to create the Array.

*Map the function to RDD.

*Convert the above RDD to DF and map colnames and write to Parquet.
The representative code
rdd1=spark.sparkContext.textfile("file1")

{ var now=0
 { val collector= new array[String] (ColLenghth.length)
 val recordlength=line.length
for (k<- 0 to colLength.length -1)
 { collector(k) = line.substring(now,now+colLength(k))
 now =now+colLength(k)
 }
 collector.toSeq}

StringArray=rdd1.map(SubstrSting(_,ColLengthSeq))
#here ColLengthSeq is read from another schema file which is column lengths

StringArray.toDF("StringCol")
  .select(0 until ColCount).map(j=>$"StringCol"(j) as column_seq(j):_*)
  .write.mode("overwrite").parquet("c"\home\")

This code works fine with files with less number of columns however it takes lot of time and resources with 20K columns.
As number of columns increases , it also increase the time.
If anyone has faced such issue with large number of columns.
I need suggestions on performance tuning , how can I tune this Job or code


text:
Q: If we have US7ASCII characterset why does it let us store non-ascii characters? We have an Oracle database that has the NLS_CHARACTERSET = US7ASCII.
As a test, we ran an insert into a table that contains a VARCHAR(4000) field as were able to put a CHR(176) value in that column (degrees symbol).
That character doesn't appear to be supported by US7ASCII.
Why would the database allow that value to be stored in that column?

A: It works because following conditions are both true:

*

*Client character set is equal to your database character set.

*The character set permits any byte values

Your database character set and your client character set are set to US7ASCII. In such case each data is written/read one by one without any conversion, i.e. the bytes you send are exactly written to database. Probably you did not set NLS_LANG at all on your client side but Oracle defaults it to AMERICAN_AMERICA.US7ASCII.
US7ASCII is a 7-bit encoding. I assume a pure ASCII application (which could be fairly difficult to find) would just ignore the 8th bit which is stored in an 8-Bit architecture. Other character sets, e.g. AL32UTF8 do not allow each byte value. In this case such characters will be replaced by a  placeholder, e.g. ¿ or ?.
Note, you set your client character set to US7ASCII which is most likely not correct. Set it properly to the character set which is used by your application, then ° will get replaced.
In case you use SQL*Plus check console codepage with command chcp, resp. locale charmap. Set your NLS_LANG environment variable accordingly before you start sqlplus.

A: The database allows that value to be stored because Oracle will handle the character set conversion for you.
More info can be found here: Special Characters in Oracle


text:
Q: My PC got got high Electric Power and burned my Gpu'Cpu and motherboard The electricity turned on/off 4 times in the building. My PC shutdown once. After a couple hours, I tried to start my PC, but it didn't start. I went to a PC hardware expert who said my:

*

*GPU (Gtx1660Ti)

*CPU (i5 9400f)

*Motherboard (Aorus b360 Gaming 3 wifi)

are all not receiving power. Why did my power supply not get damaged first and prevent the other components from getting damaged since the power supply receives power first and supplies it to all PC components?
The memory (RAM) is fine, the power supply (Gigabyte p550w 80 bronze) is fine, and the HDD is fine. I managed to fix my motherboard - it was under warranty. While the CPU and GPU both have a warranty, I'm in Egypt and I purchased them in UK - which is very far away. Intel and Gigabyte don't exist in Egypt. Is there a way to fix them? If I managed to go to the UK,  what are the steps to fix them?


text:
Q: Optimizing Data Streamer Pool size to improve ignite performance I am using Ignite 2.6 with  data streamer nodes consuming data from kafka and putting in ignite cache. A high server load average is being observed with reduced throughput.
I have tried giving  index inline size for the indexes defined in the cache which is giving a good performance but also increases the server memory utilization  and high load average.  Please advise how does increasing the datastreamer threadpool size will impact in this case.

A: When optimizing data streamer performance, you need to understand, where the bottleneck is. It may be either on data nodes or streaming nodes. Servers may be inserting data slowly or streamers may be just giving too little load.
CPU, memory, network, disk resources can be drained on either side. Therefore, before trying to optimize configuration parameters, try to look for a reason, that's causing the slowness. Using JFR, JProfiler, VisualVM or something similar may help you with it.
If the bottleneck is on the streaming side, then in most cases calling IgniteDataStreamer#addData on a single data streamer from multiple threads increases servers' utilization.
If you see the issue on the server's side, then you may need to increase the number of servers or try to optimize the insertion time.


text:
Q: How do I Iterate over an array of objects to create new instances of a Class? Ruby on Rails I have an Order Model which contains an array of objects called item_details.
When I create a new order, I want to iterate over item_details and create new instances of OrderDetail which include the Order id.
OrderDetail is a join table so I want to create instances after creating an Order so that I can include the order_id in OrderDetails.
How do I go about doing this? I have the data type for item_details as json, this way I managed to save it to my database.
Before I had it as text/string and it was saving a symbol as a string.
Order Sample
{
    "id": 5,
    "customer_id": 1,
    "order_date": "2023-01-03",
    "total_cost": 0,
    "item_details": [
        {
            "product_id": 3,
            "quantity": 3
        },
        {
            "product_id": 9,
            "quantity": 4
        }
    ],

Schema
  create_table "order_details", force: :cascade do |t|
    t.integer "product_id"
    t.integer "order_id"
    t.integer "quantity"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end

  create_table "orders", force: :cascade do |t|
    t.integer "customer_id"
    t.string "order_date"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.json "item_details"
  end

Models
class Order < ApplicationRecord
    belongs_to :customer
    has_many :order_details
    has_many :products, through: :order_details

end

class OrderDetail < ApplicationRecord

    validates :quantity, numericality: { only_integer: true }

    belongs_to :order
    belongs_to :product

end

Serializers
class OrderSerializer < ActiveModel::Serializer
  attributes :id, :customer_id, :order_date, :total_cost, :item_details

  belongs_to :customer
  has_many :order_details
  has_many :products

  def total_cost
    cost = []
    self.object.order_details.each do |details|
      product = self.object.products.find {|product| product.id == details.product_id}
      cost << product.price * details.quantity
    end
    return cost.sum
  end

 class OrderDetailSerializer < ActiveModel::Serializer
  attributes :id, :product_id, :order_id, :quantity, :product

  belongs_to :order
  belongs_to :product
end

Order Controller
class OrdersController < ApplicationController
    wrap_parameters format: []
    skip_before_action :authorized, only: :create

    def index
        orders = Order.all
        if orders
        render json: orders
        else
            render json: {error: "Order Not Found" }, status: :not_found
        end
    end

    def show
        order = Order.find_by(id: params[:id])
        if order
            render json: order
        else
            render json: { error: "Order Not Found" }, status: :not_found
        end
    end

    def create
        order = Order.create(order_params)
        if order.valid?
            order.item_details.each do |i|
                OrderDetail.create(order_id: params[:id], product_id: i[:product_id], quantity: i[:quantity])
            end
            render json: order
        else
            render json: { errors: order.errors.full_messages }, status: :unprocessable_entity
        end
    end

    def update
        order = Order.find_by(id: params[:id])
        if order
            order.update(order_params)
            render json: order
        else
            render json: { error: "Order Not Found" }, status: :not_found
        end
    end

    def destroy
        order = Order.find_by(id: params[:id])
        if order
            order.destroy
            head :no_content
        else
            render json: {error: "Order Not Found"}, status: :not_found
        end
    end

    private

    def order_params
        params.permit(:customer_id, :order_date, item_details: [:product_id, :quantity] )
    end

end

OrderDetail Controller
class OrderDetailsController < ApplicationController

    skip_before_action :authorized, only: :create

    def index
        order_details = OrderDetail.all
        if order_details
        render json: order_details
        else
            render json: {error: "Not Found"}, status: :not_found
        end
    end

    def create
        order_detail = OrderDetail.create(order_details_params)
        if order_detail.valid?
            render json: order_detail
        else
            render json: { errors: order_detail.errors.full_messages }, status: :unprocessable_entity
        end
    end

    def update
        order_detail = OrderDetail.find_by(id: params[:id])
        if order_detail
            order_detail.update(order_details_params)
            render json: order_detail
        else
            render json: { error: "Not Found" }, status: :not_found
        end
    end

    private

    def order_details_params
        params.permit(:order_id, :product_id, :quantity)
    end

end

A: For example
order = Order.create(order_attribs)
order_items.each do |item_attribs|
  order.order_items.create(item_attribs)
end

A: The way that you typically creating multiple records in a single request in Rails is to have the parent record accept nested attributes for its children:
class Order
  has_many :order_details
  accepts_nested_attributes_for :order_details
  validates_associated :order_details
end

This will create a order_details_attributes= setter which takes an array of hashes as input. And which will initialize/create the nested records.
class OrdersController
  # POST /orders
  def create
    @order = Order.new(order_params)
    if @order.save
      # either just respond with a location
      head :created, location: @order
      # or the entity as json
      render json: @order
    else
      render json: { errors: order_detail.errors.full_messages },
        status: :unprocessable_entity
    end
  end

  private

  def order_params
    params.require(:order)
          .permit(:foo, :bar, order_details_attributes: [:product_id, :quantity])
  end
end

However this is really just somewhat of a kludge to manage multiple resources in one single syncronous request and doesn't always result in the best user experience or good code.
If your users are adding an item to a shopping cart it would be better to save the order right when they add the first item and then have the client send atomical POST /orders/:order_id/order_details requests to add items to the cart - updating the quantity of a single item would be done with PATCH /orders/:order_id/order_details/:id. See nested routes.
There are also a lot of issues with the controller in the question and you would be better off if you just started over from a scaffold.

*

*Use find and not find_by(id: ...). It will raise a NotFoundException if the record is not found and respond with a 404 status response. It will break out of the method without adding a bunch of cyclic complexity and duplication. You don't need to return json: { error: "Not Found" }. That is just a silly anti-pattern.

*if order_detail.valid? doesn't actually guarentee that the record is persisted to the database. It just says that the validations passed. Check the return value of .save or .persisted? instead.

*You're not actually checking if order_detail.update(order_details_params) is successful. Always code for invalid user input.


text:
Q: Height of ImageView in LinearLayout Have LinearLayout with height=100dp. Need to dynamically add 5 ImageView, and they need to stay on 1 line and have same height.
When i do this on display size => 4.5' - all fine. But when i use AVD with 4' or 480 resolutin, last item is smaller.
Please help me find solution and sorry for my english!
Here most simplest code for add imageview:
ImageView image = new ImageView(getApplicationContext());
            image.setImageResource(imageArray[position]);
            image.setTag(imageNames[position]);
linearLayout.addView(image);

and here is container
<LinearLayout
    android:id="@+id/ll"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="100dp"
    android:gravity="center_horizontal"/>

A: You have to use android:weightSum attribute in LinearLayout and android:weight in each ImageView.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:orientation="horizontal"
    android:weightSum="1">

    <ImageView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="0.2" />

    <ImageView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="0.2" />

    <ImageView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="0.2" />

    <ImageView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="0.2" />

    <ImageView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="0.2" />
</LinearLayout>

Note: This type of code will probably shrink images in small screen sizes. So you could use LinearLayout with HorizontalScroolView instead

A: Your image views width and height is not set. therefore, will depend on screen and images resolutions.
Code:
ImageView image = new ImageView(getApplicationContext());
image.setImageResource(imageArray[position]);
image.setTag(imageNames[position]);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(layoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT, 1.0f);
image.setLayoutParams(layoutParams);
linearLayout.addView(image);


text:
Q: Rcpp NumericMatrix - how to erase a row / column? A novice question as I learn the Rcpp classes / data structures: Is there a member function to erase a row / column for an object of class Rcpp::NumericMatrix? (Or other types of type **Matrix -- I'm assuming it's a template class)?
library(Rcpp)
cppFunction('
  NumericMatrix sub1 {NumericMatrix x, int& rowID, int& colID) {
    // let's assume separate functions for rowID or colID
    // but for the example case here
    x.row(rowID).erase(); // ??? does this type of member function exist?
    x.col(colID).erase(); // ???
    return x;
}')

If this type of member function doesn't exist, how about this?
cppFunction('NumericMatrix row_erase (NumericMatrix& x, int& rowID) {
  // a similar function would exist for removing a column.
  NumericMatrix x2(Dimension(x.nrow()-1, x.ncol());
  int iter = 0; // possibly make this a pointer?
  for (int i = 0; i < x.nrow(); i++) {
    if (i != rowID) {
      x2.row(iter) = x.row(i);
      iter++;
    }
  }
  return x2;
}')

Or perhaps we wish to remove a set of rows/columns:
cppFunction('NumericMatrix row_erase (NumericMatrix& x, IntegerVector& rowID) {
  // a similar function would exist for removing a column.
  rowID = rowID.sort();

  NumericMatrix x2(Dimension(x.nrow()- rowID.size(), x.ncol());
  int iter = 0; // possibly make this a pointer?
  int del = 1; // to count deleted elements
  for (int i = 0; i < x.nrow(); i++) {
    if (i != rowID[del - 1])
      x2.row(iter) = x.row(i);
      iter++;
    } else {
      del++;
    }
  }
  return x2;
}')

A: How about using RcppArmadillo? I think the intention of the code would be much clearer...
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]

using namespace arma;

// [[Rcpp::export]]
mat sub1( mat x, uword e) {
  x.shed_col(e-1);
  x.shed_row(e-1);
  return x;
}

/*** R
sub1( matrix(1:9,3), 2 )
*/

> sub1( matrix(1:9,3), 2 )
     [,1] [,2]
[1,]    1    7
[2,]    3    9

A: Yes, both of these do work (fixing my typos above). I got a conversion error trying to replace int iter with Rcpp::NumericMatrix::iterator iter though. Any fix for this?
Note that we do not need the row_erase(NumericMatrix& x, int& ref) since this is a special case of row_erase(NumericMatrix& x, IntegerVector& ref).
NumericMatrix row_erase (NumericMatrix& x, IntegerVector& rowID) {
  rowID = rowID.sort();

  NumericMatrix x2(Dimension(x.nrow()- rowID.size(), x.ncol()));
  int iter = 0;
  int del = 1; // to count deleted elements
  for (int i = 0; i < x.nrow(); i++) {
    if (i != rowID[del - 1]) {
      x2.row(iter) = x.row(i);
      iter++;
    } else {
      del++;
    }
  }
  return x2;
}

NumericMatrix col_erase (NumericMatrix& x, IntegerVector& colID) {
  colID = colID.sort();

  NumericMatrix x2(Dimension(x.nrow(), x.ncol()- colID.size()));
  int iter = 0;
  int del = 1;
  for (int i = 0; i < x.ncol(); i++) {
    if (i != colID[del - 1]) {
      x2.col(iter) = x.column(i);
      iter++;
    } else {
      del++;
    }
  }
  return x2;
}


text:
Q: Windows 7 LAN Unidentified Network I've got a home network with several computers connected through a hub and another running OpenBSD as the gateway/firewall.  I recently tried to connect a Windows 7 computer to the network, but it says "Unidentified Network" and gives me "no route to host" when I try to ping anything else on the LAN.  I've got the Windows 7 box's IPV4 address set to 192.168.1.18 and the gateway set to 192.168.1.1. I'm not using DHCP and there are no local DHCP servers on the network.

A: You need to download, compile, and run the LLTD responder daemon.  I've never done so on OpenBSD, but have done so successfully on Linux.  http://msdn.microsoft.com/en-us/windows/hardware/gg463094.  You might also look into disabling LLTD on all Windows Vista/7 computers but I'm not sure if that will affect Windows "network identification".

A: Well, route print pls, from Win7 box and check default route
It seems as some misconfiguration of IPv4-interface (thin netmask, wrong default GW) for me (if other hosts are interpingable)


text:
Q: Sending mail SMTP works with Gmail but fails when I try to send it from my domain I'm trying to send mail using SMTPClient in C#.
Everything was fine when I was sending mail using my Gmail account
using HOSTNAME: smtp.gmail.com
and PORT NUMBER: 587.
Here is the code which I used:
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com",587)
//mail
mail.From = new MailAddress("someone@mydomain.com","myself");
mail.To.Add("itsme@gmail.com");
mail.Subject = "Test Mail C#";
mail.Body = "Hello";
mail.IsBodyHtml = true;
//smtpclient
SmtpServer.Port = 587;
SmtpServer.EnableSsl = true;
SmtpServer.Credentials = new  System.Net.NetworkCredential("someone@mydomain.com", "password");

Boolean MailSent=true;
try
{
    SmtpServer.Send(mail);
}
catch (SmtpException ex)
{
    MessageBox.Show(ex.Message);
    MailSent = false;
}
finally
{
    if (MailSent == true)

        MessageBox.Show("mail sent");
    else
        MessageBox.Show("Failed to send mail");
}

Here are the details provided by the hosting service provider:

*

*Secure SSL/TLS Settings (Recommended)
Username:   someone@opastonline.com
Password:   Use the email account's password.
Incoming Server:    mocha7004.mochahost.com
IMAP Port: 993
POP3 Port: 995
Outgoing Server:    mocha7004.mochahost.com
SMTP Port: 465
Authentication is required for IMAP, POP3, and SMTP.

*Non-SSL Settings
(This is NOT recommended.)
Username:   someone@opastonline.com
Password:   Use the email account's password.
Incoming Server:    mail.opastonline.com
IMAP Port: 143
POP3 Port: 110
Outgoing Server:    mail.opastonline.com
SMTP Port: 25 --> When raised a ticket they also suggested me to use 2525 or 25
Authentication is required for IMAP, POP3, and SMTP.
But when I replace them using the details provided by my host provider, I am unable to push the mail.
It shows different error messages when I change port numbers (which I was given by the provider):

*

*port 25: The remote certificate is invalid according to the validation procedure.

*port 2525: Failure Sending Mail

*port 465: Operation timed out

I cross checked every possible thing, but seems I am lost somewhere.

A: Go to security settings at the followig link https://www.google.com/settings/security/lesssecureapps and enable less secure apps . So that you will be able to login from all apps.


text:
Q: Find pdf of sum of n indp exp RVs w/o using MGFs From Williams' Probability w/ Martingales:

Re $E[f(S_n)]$, how do I obtain $f_{S_n}(s)$? It seems that
$$f_{S_n}(s) = \frac{s^{n-1} e^{-\lambda s} \lambda^n}{(n-1)!}$$
I tried computing $M_{S_n}(t) = (\frac{\lambda}{\lambda - t})^n$ for $t < \lambda$ and then compared it to the mgf of a gamma function: $(1-t\theta)^{-k}$ for $t < \frac{1}{\theta}$ by letting $\lambda = \frac{1}{\theta}$ and $k = n$ and that seems to work, but is there a way to do it from using only CDFs? I was thinking:
$$F_{S_n}(s) = P(S_n \le s)$$
$$ = P(X_1 + ... + X_n \le s)$$
$$ = \int_{0}^{a_1} \int_{0}^{a_2} \cdots \int_{0}^{a_n} \lambda^n e^{-\lambda(x_1 + \cdots + x_n)} dx_1 dx_2 \cdots dx_n$$
where $a_1 + a_2 + ... + a_n = s$
$$ = \int_{0}^{a_1} \int_{0}^{a_2} \cdots \int_{0}^{a_n} \lambda^n e^{-\lambda(s_n)} dx_1 dx_2 \cdots dx_n$$
or something like that and then differentiate $F_{S_n}(s)$.

A: No need for moment generating functions or Laplace transforms; this follows from a simple induction argument.
Let $X_k\stackrel{\mathrm{i.i.d.}}\sim\operatorname{Exp}(\lambda)$ and $S_n=\sum_{k=1}^n X_k$. Then $X_1$ has density $$ f_{S_1}(t) = f_{X_1}(t)=\lambda e^{-\lambda t}\mathsf 1_{(0,\infty)}(t) = \frac{(\lambda t)^{n-1}}{(n-1)!}\lambda e^{-\lambda t}\mathsf 1_{(0,\infty)}(t).$$
Now, assuming that $S_n$ has density
$$f_{S_n}(t) = \lambda e^{-\lambda t}\mathsf 1_{(0,\infty)}(t) = \frac{(\lambda t)^{n-1}}{(n-1)!}\lambda e^{-\lambda t}\mathsf 1_{(0,\infty)}(t)$$
for a positive integer $n$ and since we have $S_{n+1}=S_n+X_{n+1}$, by convolution the density of $S_{n+1}$ is,
\begin{align}
f_{S_{n+1}}(t) &= (f_{S_n}\star f_{X_1})(t)\\
&= \int_\mathbb R f_{S_n}(\tau)f_{X_1}(t-\tau)\ \mathsf d\tau\\
&= \int_\mathbb R \frac{(\lambda \tau)^{n-1}}{(n-1)!}\lambda e^{-\lambda \tau}\mathsf 1_{(0,\infty)}(\tau)\lambda e^{-\lambda(t-\tau)}\mathsf 1_{(0,\infty)}(t-\tau)\ \mathsf d\tau\\
&= \frac{\lambda^{n+1}}{(n-1)!}e^{-\lambda t}\mathsf 1_{(0,\infty)}(t)\int_0^t \tau^{n-1}\ \mathsf d\tau\\
&= \frac{(\lambda t)^n}{n!}\lambda e^{-\lambda t}\mathsf 1_{(0,\infty)}(t).
\end{align}


text:
Q: Lenovo s10-3 wireless problems I have the Lenovo s10-3 machine and I have wireless problems. I am running xubuntu 12.04. I had to lspci -k to identify my driver and install the correct broadcom drivers to get it out of hard blocked. rfkill list shows nothing is blocked now and everything seems to be working but it can not find a single wireless connection.
Any suggestions? Thanks

A: Have you checked the "hardware drivers" (which is in the system or settings menu)? Also the command
sudo dmesg | egrep 'air|ath|carl|at7|iwl|ipw|rtl8|rt2|rt3|rt6|rt7|r818|r871|rtl8|tg3|ssb|wl|b43|bcma|brcm|b44|eth1|ndis|wmi|wlan0'
can give helpful info.


text:
Q: R Binomial Regression I am trying to develop a binomial model in R.
I want to use a formula that looks like this: VAL = X0 + b1 * X1 + b2 * X2
Where X0, X1, and X2 are variables in my data frame and b1 and b2 are the coefficients I want to develop. I want the target value Y to be TRUE/1 if this formula produces a VAL > 0 and FALSE/0 if it produces a VAL < 0.
Sample Data with b1 & b2 set to 1:
Target X0  X1   X2  VAL  Result
1      86  -54  17   49     1
0      0   -54  17  -37     0
1      40  -15  23   48     1
0      50  -20 -25    5     1
I want the value of X0 to be incorporated in the prediction, but I do not want this variable to have a coefficient (as this is a predefined formula that I can't change).
The reason I need X0 in the model is because if X1 and X2 are equal for two observations that have different X0 values (as in first 2 observations), I want to reflect that in my formula. One observation's X0 could cause VAL to be negative and the other observations's X0 could cause VAL to be positive, but this would not be reflected if X0 was left completely out of the model. Also note the last observation in which I would either need to increase b1 or b2 so that VAL is negative and the result is 0 (which the model would not see without seeing X0).
I currently am using a formula that looks like glm("Y~X0+X1+X2", family = binomial(link = "logit")), but this model produces a coefficient for X0. How would I develop a model forcing X0 to have no coefficient?

A: As an update, I was looking for the offset() function. In this case, I used offset(X0) as an added predictor to my model.

A: It looks like what you want is to have the coefficient for X0 be zero. If you can't change the formula (to omit X0), you could change the data. Here's an example:
n = 1000
df = data.frame('x1'=rnorm(n), 'x2'=rnorm(n))
df0 = df
df0[,2] = 0

y = 0.5 + 1.5*df[,1] - 1.0*df[,2] + rnorm(n, 0, 0.1)

mod1 = lm(y ~ x1, data = df)
mod2 = lm(y ~ x1 + x2, data = df)
mod3 = lm(y ~ x1 + x2, data = df0)

It sounds like mod1 is what you want, but since you can't change the formula, you're stuck with mod2 or mod3. mod2 won't work since this will give an estimate for x2. mod3 is the same as mod1 except the coefficient for x2 will be NA, but the intercept and x1 will have the same cofficients.
Having the coefficient for x2 be NA is comparable to having it be zero. The predictions from mod1 and mod3 will be the same, but mod3 does throw a warning.