text:
Q: SOLVE NodeJS Socket.io server not receive message I start create server with Nodejs and socket.io in simple way.
In client connect just fine but when emit pong to server it never show.
This code:
SERVER
var PORT = 3003;
var io = require('socket.io')(PORT);
var clients = [];
setInterval (function() {
    io.sockets.emit('ping');
}, 3000);
io.on('connection', (function(socket) {
    socket.emit ('welcome', { message: 'Connection complete', id: socket.id });
    clients.push ({id: socket.id, clientSocket: socket});
    print ('Client connected ' + socket.id);
    socket.on('disconnect', function() {
        clients.splice(clients.indexOf(socket), 1);
        print (socket.id + " is disconnected.");
    });
    socket.on('pong', function(args) {
        print (args + " is pong.");
    });
}).bind(this));
print('Server starting ...');

CLIENT:
var PORT = 3003;
var io = require('socket.io-client');
var socket = io.connect('http://localhost:' + PORT);
socket.on('connect', function(){
    print ('Client connected...');
});
socket.on('welcome', function(args) {
    print (args.message + ' / ' + args.id);
    // socket.disconnect();
});
socket.on ('ping', function(args) {
    socket.emit ('pong', { id: socket.id });
    print ('Receive ping...');
});
print ('Client Starting...');


text:
Q: Laravel api returns value in postman but returns empty array in Vue js I have a small Api built in laravel that is supposed to return a response when an endpoint is hit.
The problem is, that same end point returns something in postman but returns empty data in Vue Js.
I have been battling this for 48 hours now, and is driving me insane, any help will be appreciated.
Thank you
public function search_passport(Request $request){

        $pass = DB::table('passengers')->where('passport_number',$request->input('passport_number'))->get();

        if($pass->count() == 0){
            return response(['message' => 'Passport number not found, please fill the form']);
        }
        return new PassengerResource($pass);
    }// search_passenger

Above is the code from the controller in the Api
Route::post('/searchpassport', [PassengerController::class, 'search_passport']);

And this is the route
 this.$http.post('searchpassport', this.passport_number, {headers:{
        'Authorization' :  'Bearer ' + this.token.access_token,
        'Accept' : 'application/json',
        'Content-Type' : 'application'
        }})
         .then(res => {
             console.log(res)
         })

This is also the API call am making in the Vue Js

A: Assuming this.$http is Axios and this.passport_number is a string, you're missing the field / property name for the request payload, ie "passport_number". Also, your Content-type header is incorrect.
Try this instead
this.$http.post("/searchpassport", {
  passport_number: this.passport_number
}, {
  headers: {
    Authorization: `Bearer ${this.token.access_token}`
  }
})

You do not need to supply the Accept or Content-type headers. The defaults will be sufficient.

It's good practice to use your browser's developer tools for debugging. The Network tab in particular is great for checking the headers and data sent in your HTTP requests and the responses you get back.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Only parameterless constructors and initializers are supported in LINQ to Entities Following is my linq query.
var values = (from test in entities.Table1
                                     select new Entity
                                     {
                                         Id = test.id,
                                         Value = test.name

                                     });
                    return values.ToList();

When Iam trying to run this, I am getting the following error :
Only parameterless constructors and initializers are supported in LINQ to Entities.

A: Does your class entity have a parameterless constructor?  If not then you can't create a new instance for each record in your linq query because it doesn't know what to pass into the constructor to instantiate it.

A: Knowing a bit more about your "context" would help, such as which version of .Net you're using, which version of EF, etc.
If I must guess only by the code and the error, it seems like that your Entity class doesn't have a parameterless (default) constructor. Try to check that.


text:
Q: pom.xml игнорируется intellij как пофиксить Делала rebase чтобы собрать все коммиты в один - пропал .iml файл. Восстановила его с помощью просмотра локальной истории в IntellijIDEA. Модуль снова стал подсвечиваться, но вот помник - нет:

Слева видно, что пом серый и зачеркнутый, а справа восстановленный iml файл. Как починить?

A: кое-как получилось

*

*Удалила помник

*Отменила удаление

*Проблемный модуль - правая кнопка мыши - add framework support - maven

A: правой кнопкой мыши на pom -> maven -> unignore Projects


text:
Q: How to update the tableview in realtime when the new value is added to array in ios swift I am building a chat application. I want to update the sent status once it delivered from pending state in a tableviewcell. I am getting the values from sqlite database and then displaying it in tableviewcell.
            if !contactDB.executeUpdate("UPDATE user_chats SET message_delivered_status = \"\(messageStatus)\", message_status = \(sendStatus) WHERE messging_user_id = \"\(userDetails!.1)\" AND message = \"\(message)\"", withArgumentsIn: nil) {
                printThis("------ Error : Message status updated ------\n\(contactDB.lastErrorMessage())\n\n\n\n")
            } else {
                printThis("One-to-one message status updated...")
                DispatchQueue.main.async {
                    NotificationCenter.default.post(name: Notification.Name("Notification_To_Reload_TableView"), object: nil)
                }
            }


text:
Q: How to save a locally loaded HTML file in UIWebview I am writing a rich text editor using UIWebView. To do this, I used a template file for a starter.
Then when user finishes editing but has not published yet, I would like to save the current content into a back-up html file in case app corrupts.
How do I do that?

A: Here you go... buddy
    NSFileHandle *file;
    NSMutableData *data;

    const char *bytestring = "black dog";//In your case html string here

    data = [NSMutableData dataWithBytes:bytestring length:strlen(bytestring)];
    NSString *path = //Path to your html file
     if ([filemgr fileExistsAtPath:path] == YES){
    NSLog (@"File exists");
file = [NSFileHandle fileHandleForUpdatingAtPath:path];

        if (file == nil)
                NSLog(@"Failed to open file");

        [file writeData: data];

        [file closeFile];
}
      else
    NSLog (@"File not found");

Complete Tutorial Below
Working With File I/O in objective-c

A: Thanks @Rahui Vyas and @Josh Caswell .. After a little research of my own. I have found the easiest way to save the locally loaded html file or any html loaded on UIWebview.
long words short, here is the code:
//load the file path to save
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savePath = [documentsDirectory stringByAppendingPathComponent:@"backup.html"];

//get the html code from the webview
NSString *jsToGetHTMLSource = @"document.documentElement.outerHTML";
NSString *html = [_changWeiBo stringByEvaluatingJavaScriptFromString:
                        jsToGetHTMLSource];

//save the file
NSError* error = nil;
[html writeToFile:savePath atomically:YES encoding:NSASCIIStringEncoding error:&error];

Hope the laters may find this useful!


text:
Q: Is there a way to specify a default value for the name property of a Chef resource? Ideally, I would like to be able to do:
resource_name :house

property :material, String, default: 'brick', name_property: true
...

so that I could then do
house do
  ...
end

and material property would be set to 'brick', but this results in the error message:
A property cannot be both a name_property/name_attribute and have a default value ...
which is clear enough. I am reasonably certain what I am asking for is not possible, but, I might also be missing an alternative way of achieving the same, so I thought I would ask.

A: No, you would have to do it at the name level itself. See https://github.com/chef/chef/blob/master/lib/chef/resource/apt_update.rb#L31.
This should be used very very sparingly, it's pretty rare for something to be a true global singleton.


text:
Q: "as well" or "as well as" in the mentioned sentence? Is it "as well" or "as well as" in the following sentence. If it is the latter, doesn't we need one more "as" after it?

Those who impose this condition differ as to what sort or degree
  of access is required, as well as to just what it is to which one
  must have access of the proper sort.

A:
Those who impose this condition differ as to what sort or degree of access is required, as well (as) to just what it is to which one must have access of the proper sort.

The word "as" can be used in different ways, as a conjunction, a preposition, an adverb or a pronoun.
In the above sentence, both uses are a preposition.  In the first case "as to" is being used as a preposition to the noun "degree".  In the second case, "as well as" is being used as a multi word preposition to... well something.  The author really is mincing the words! I would suspect the noun "access".  "as well as" means "in addition to".

doesn't we need one more "as" after it?

In answer to the question "do we need one more 'as'" or "don't we need one more 'as'", I would say no. It's an unnecessarily complicated sentence but breaks down roughly as follows, no additional "as" (prepositions) required.
[to just] = preposition, adjective
[what it is] = noun that the adjective refers to
[to which] = preposition, pronoun, refers to antecedent

A:
Those who impose this condition differ as to what sort or degree of access is required, as well as to just what it is to which one must have access of the proper sort.
Those who X differ as to what sort or degree of access is required, ...

The group of people who favor X have different opinions on what access is required. Somne say more, some say less, some say one kind of access, some say a different kind.

... as well as to just what it is to which one must have access

These same people who favor X also have different opinions on what people must be grante4d access to. Some say it must be access to Y, others say access to Z.
Yes the original sentence is complex, but see what a lot of meaning  it packs in.  Two different disputes on related topics among sub-groups of a single group. I wopuld leave out the "to" in "as well as to " but I can't say that it is wrong to leave it in.
I would say, by the way, that the first "as to" serves as the object of the verb differ. It shows, or introduces the clause that shows, what they differ about. "as well as to" implies a re-sue of the verb differ with the same subject but a different object, because there is a second difference of opinion among the same group of people.


text:
Q: Control a MOXA IOLogik wia TCP I know this is strictly not an electrical engineering problem, but I think it's where it has a best chance of being answered.
I'm using a MOXA IOLogik (it's a Ethernet Micro RTU Controller) to monitor and control some security systems with digital IO and I want to modify a IOLokig internal register via TCP to send some commands to the controller from a server.
Anyone knows how to do this? how should the structure of the TCP message be?
UPDATE: It uses the modbus protocol for communication.
Thanks a lot

A: I put up a basic implementation of a ModbusTCP interface at http://pastebin.com/5twF0gUb
This is a C# class that you should mostly be able to plug into an application. I stripped it out of some other code and tried to massage it into a generic format but you may need to tweak it a bit. I glanced at the manual for that controller and it has all the addresses listed that you should need.


text:
Q: Hibernate MySQLMyISAMDialect doesn't work? I'm using hibernate 4.2.1 and MySQL 5.5 .
In persistence.xml i have this :
<!-- ... -->
<properties>
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.hbm2ddl.auto" value="update" />
            <property name="hibernate.dialect"  value="org.hibernate.dialect.MySQLMyISAMDialect" />

</properties>

But When i run my projet my database doesn't contain any table !
Does anyone have any idea ?!
Thanks

A: Remove the dialect line from your config entirely.
Hibernate can detect which dialect to use based on the underlying database metadata assuming you give it the correct username/password. I've never had a problem with Hibernate autodetecting my database version. It's especially useful with MySQL, because MySQL has different versions of dialects that it can use.
If you see the following exception
org.hibernate.HibernateException: Connection cannot be null when 'hibernate.dialect' not set

It means that your username/password is incorrect, and Hibernate couldn't connect to the database, to actually read the metadata to choose it's own dialect.
I have found that it is easier to set up the database tables using SQL scripts, then get Hibernate to validate your schema. Getting Hibernate to generate any database structure (using create-update or just update) is not recommended for a production environment, because you lose the control over how the database is set up.
TL;DR: Let Hibernate choose its own dialect. It will save you hours of fuss.


text:
Q: C# - Entity Framework updating relationship I am using C# with ASP.NET Core and Entity Framework to create a RESTful API.
Everything is running fine, however there is one case that I am trying to solve.
Say I have those 3 classes below.
public class Car
{
    [Key]
    public int Id { get; set; }
    public int Year { get; set; }
}

public class Option
{
    [Key]
    public int Id { get; set; }
    public int Name { get; set; }
}

public class CarOption
{
    [Key]
    public int Id { get; set; }
    public int Car { get; set; }
    public int Option { get; set; }
    public int Value { get; set; }
}

The problem is when I try to update CarOption, the Entity Framework will update the related objects too.
I was expecting only the relationship would be updated. Meaning, the framework would discard the other values of Option object and use only the Primary Key to update CarOption table.
For example:
Assuming that the following code is an example of JSON generate by the API.
{
    "id":1
    "Car":{
        "id":1,
        "year":2020
    },
    "option":{
        "id":1,
        "label":"gear"
    },
    "value":"manual"
}

If I change the payload and update the option part as
{
...
    "option":{
        "id":1,
        "label":"gear2"
    },
...
}

, the Entity Framework will update the table Option with the new value even though the attribute id is present which means that object already exists.
I am using DbContext.CarOption.Update(*payload*).
Is there any solution to avoid this behavior?


text:
Q: What is and isn't a valid variable specification for Manipulate? I have an expression whose terms have arguments (representing subscripts), like this:
myExpr = A[0] + V[1,T]

I would like to put it inside a Manipulate to see its value as I move around the parameters. (The goal is eventually to plot it wrt one of the variables inside.)
However, Mathematica complains when I set V[1,T] as a manipulated variable:
Manipulate[Evaluate[myExpr], {A[0], 0, 1}, {V[1, T], 0, 1}]
  (*Manipulate::vsform: Manipulate argument {V[1,T],0,1} does not have the correct form for a variable specification. >> *)

As a workaround, if I get rid of the symbol T inside the argument, it works fine:
Manipulate[
 Evaluate[myExpr /. T -> 15], {A[0], 0, 1}, {V[1, 15], 0, 1}]

Why this behavior?  Can anyone point me to the documentation that says what counts as a valid variable?  And is there a way to  get Manpiulate to accept an expression with a symbolic argument as a variable?
Investigations I've done so far:

*

*I tried using variableQ from this answer, but it says V[1,T] is fine as a valid variable.

*And Plot works just fine with V[1,T] as the variable, as in:
Plot[myExpr /. A[0] -> 2, {V[{1, T}], 1, 2}]

A: I suspect it's an internal decision by WRI to allow as variables only expressions of the form A[0, 1, 2], that is, a symbol with integer arguments.  You could try reporting your desired functionality to WRI; maybe they will extend what expressions are allowed.  Instead of being localized in the usual way, the expressions are remapped to Unique[] symbols. For instance, the expression A[0] would be mapped to a symbol like $101. In this scheme, almost any expression could be allowed as a variable, because it can be replaced by a valid variable name.  One danger is that in an expression like V[1, T], the symbol T would not be localized, so if T changed value, one should expect a change in behavior.  One could wish that V[0, T] were mapped to $102, but that would remove the dependency on T.  From a programming point of view, this would be really bad.  But if T in a user's program is an inert symbol, then from the user's point of view, it is a bit irritating not to be able to do it.
Well, with some hacking, you could do it like you want, but let me first suggest this:
Manipulate[{A[0], V1T}, {A[0], 0, 1}, {{V1T, 0, HoldForm@V[1, T]}, 0, 1}]

Hack:
The check on what is a valid variable is performed Manipulate`Dump`extendedVariable.  You can add your own allowed forms like this:
Internal`InheritedBlock[{Manipulate`Dump`extendedVariable},
 Manipulate`Dump`extendedVariable[_Symbol[__]] := True;
 Manipulate[{A[0], V[1, T]}, {A[0], 0, 1}, {V[1, T], 0, 1}]
 ]

This would be a little safer, but I would still recommend the first approach above:
Internal`InheritedBlock[{Manipulate`Dump`extendedVariable},
 Manipulate`Dump`extendedVariable[_Symbol[(_Integer | _String) ..]] := True;
 Manipulate[{A[0], V[1, "T"]}, {A[0], 0, 1}, {V[1, "T"], 0, 1}]
 ]

Bug/Restriction (updated):
My point seemed to be lost in the simple example I originally gave, so I have changed it and added some explanation to try to clarify the issues.  My claim was and is: I'm not sure why forms like A[0] are allowed.  They don't work the way they do in normal Mathematica.
The point is that when expressions A[0] etc. are replaced by Unique[] symbols like $123, only the literal expressions like A[0] etc. are replaced in the Manipulate code by kernel, before the Manipulate is sent back to the front end for instantiation.  An expression like A[n] that evaluates to A[0] at runtime will not be linked to the actual variable $123 being used to represent A[0].
Manipulate[{A[0], A[n]}, {A[0], 0, 1}, {n, 0, 1, 1}] // InputForm
(*
  Manipulate[{$3340, A[n]},                                                        (*$*)
    {{$3340, 0, RawBoxes[RowBox[{"A", "[", "0", "]"}]]}, 0, 1},                    (*$*)
    {n, 0, 1, 1}]
*)

A more complicated example, which might illustrate better a more practical use of A[n], is given below.  But simplicity has advantages in an issue that is complicated and potentially confusing.
One reason for using variables like A[0], A[1], etc. is to be able to parametrize them by A[n].  Such functionality can often be accomplished with lists, which can be made to work in Manipulate, but that seems a separate issue.  Workarounds are not an explanation.  My point is that one of the basic uses of A[0] etc. cannot be implemented in Manipulate.
A more complicated example:
Manipulate[
 With[{f = Sum[A[n] x^n, {n, 0, m}]},
  Plot[f, {x, -1, 1}, PlotLabel -> f]
  ],
 {A[0], 0, 1}, {A[1], 0, 1}, {A[2], 0, 1},
 {m, 0, 2, 1}]

Note that A[1], A[2], and A[3] in the list are not updated or connected to the controls.  (This is because, while A[1] is remapped to $nnn, the expression A[n] is not!)  My advice is to avoid them, and use
{{A0, 0, HoldForm@A[0]}, 0, 1}

instead.
A workaround for the last example, for those who like them:
Manipulate[
 With[{f = Sum[A[n] x^n, {n, 0, m}] /. {A[n_] /; n == 0 :> A[0],
      A[n_] /; n == 1 :> A[1], A[n_] /; n == 2 :> A[2]}},
  Plot[f, {x, -1, 1}, PlotLabel -> f]
  ],
 {A[0], 0, 1}, {A[1], 0, 1}, {A[2], 0, 1},
 {m, 0, 2, 1}]

The literal occurrences of A[0], A[1] and A[2] in the replacement rules are
replaced by unique $nnn in the kernel:
{A[n_] /; n == 0 :> A[0], A[n_] /; n == 1 :> A[1], A[n_] /; n == 2 :> A[2]}}

At runtime the rules replace the evaluated A[n] by the corresponding $nnn variable.  Such a set of rules has to be applied at all appropriate places in the code.  For instance it cannot be applied to the whole body, because it has to be applied to f before Plot is evaluated.  In a complicated piece of code, it would be a big pain.  In such an application, it would be best to avoid them.  After all, that is basically what Manipulate is doing already by rewriting them as simple variables (original example):
Manipulate[
  Table[A[n], {n, 3}],
 {A[1], 0, 1}, {A[2], 0, 1}, {A[3], 0, 1}] // InputForm
(*
  Manipulate[Table[A[n], {n, 3}],
    {{$3335, 0, RawBoxes[RowBox[{"A", "[", "1", "]"}]]}, 0, 1},
{{$3336, 0, RawBoxes[RowBox[{"A", "[", "2", "]"}]]}, 0, 1},
{{$3337, 0, RawBoxes[RowBox[{"A", "[", "3", "]"}]]}, 0, 1}]
*)


text:
Q: Accessing specific edges in boost::graph with integer index This is related to a question I had yesterday about accessing vertices using integer indices. That thread is here: Accessing specific vertices in boost::graph
The solution there indicated that using vecS as the type for vertices, it is indeed possible to access specific vertices using the integer index. I was wondering if there is a similar method provided by boost to access arbitrary edges efficiently using integer indices.
Attached is a code that depicts the former (valid access of vertices with integer indices) and accessing the edges based on the developer explicitly maintaining two arrays, from[] and to[], that store the source and the target, respectively of the edges.
The code creates the following graph:

#include <boost/config.hpp>
#include <iostream>
#include <fstream>

#include <boost/graph/graph_traits.hpp>
#include <boost/graph/adjacency_list.hpp>

using namespace boost;

typedef adjacency_list_traits<vecS, vecS, directedS> Traits;

typedef adjacency_list<
    vecS, vecS, directedS,
    property<
    vertex_name_t, std::string,
    property<vertex_index_t, int,
    property<vertex_color_t, boost::default_color_type,
    property<vertex_distance_t, double,
    property<vertex_predecessor_t, Traits::edge_descriptor> > > > >,

    property<
    edge_index_t, int,
    property<edge_capacity_t, double,
    property<edge_weight_t, double,
    property<edge_residual_capacity_t, double,
    property<edge_reverse_t, Traits::edge_descriptor> > > > > >
    Graph;

int main() {
    int nonodes = 4;
    const int maxnoedges = 4;//I want to avoid using this.
    Graph g(nonodes);

    property_map<Graph, edge_index_t>::type             E = get(edge_index, g);

    int from[maxnoedges], to[maxnoedges];//I want to avoid using this.

    // Create edges
    Traits::edge_descriptor ed;

    int eindex = 0;

    ed = (add_edge(0, 1, g)).first;
    from[eindex] = 0; to[eindex] = 1;//I want to avoid using this.
    E[ed] = eindex++;

    ed = (add_edge(0, 2, g)).first;
    from[eindex] = 0; to[eindex] = 2;//I want to avoid using this.
    E[ed] = eindex++;

    ed = (add_edge(1, 3, g)).first;
    from[eindex] = 1; to[eindex] = 3;//I want to avoid using this.
    E[ed] = eindex++;

    ed = (add_edge(2, 3, g)).first;
    from[eindex] = 2; to[eindex] = 3;//I want to avoid using this.
    E[ed] = eindex++;

    graph_traits < Graph >::out_edge_iterator ei, e_end;
    for (int vindex = 0; vindex < num_vertices(g); vindex++) {
        printf("Number of outedges for vertex %d is %d\n", vindex, out_degree(vindex, g));
        for (tie(ei, e_end) = out_edges(vindex, g); ei != e_end; ++ei)
            printf("From %d to %d\n", source(*ei, g), target(*ei, g));
    }

    printf("Number of edges is %d\n", num_edges(g));

    //Is there any efficient method boost provides
    //in lieu of having to explicitly maintain from and to arrays
    //on part of the developer?
    for (int eindex = 0; eindex < num_edges(g); eindex++)
        printf("Edge %d is from %d to %d\n", eindex, from[eindex], to[eindex]);

}

The code builds and compiles without error. The for loop with vindex works fine with out_edges and out_degree working fine taking as parameters integer indices.
Is there a way to do likewise for the next for loop that prints the edges using boost::graph data structures directly?
I looked at the following thread dealing with a similar question:
Boost graph library: Get edge_descriptor or access edge by index of type int
The suggested answer there was to use an unordered_map. Is there any tradeoff in using this as opposed to having the from[] and to[] arrays? Are there any other computationally efficient methods of accessing edges?

A: You can only do this if you

*

*use a different graph model

*an external edge index

Concepts
You could be interested in the AdjacencyMatrix concept. It doesn't exactly sport integral edge ids, but AdjacencyMatrix has lookup of edge by source/target vertices as well.
To get truly integral edge descriptors, you'd probably need write your own graph model class (modeling a set of existing BGL concepts). You might also be interested in grid_graph<> (which has a fixed set of numbered edges per vertex, where the vertices are a grid).

*

*How to access edge_descriptor with given vertex_descriptor in boost::grid_graph - you could devise a "global" numering scheme and thus get linear lookup time

Adjacency List
Here's a modification from the previous answer showing an external index. It's akin to your solution. I chose bimap so at least you get the reverse lookup "automagically".
// Create edges
boost::bimaps::bimap<int, Graph::edge_descriptor> edge_idx;

auto new_edge_pair = [&,edge_id=0](int from, int to) mutable {
    auto single = [&](int from, int to) {
        auto d = add_edge(from, to, EdgeProperty { edge_id, 4 }, g).first;
        if (!edge_idx.insert({edge_id++, d}).second)
            throw std::invalid_argument("duplicate key");
        return d;
    };

    auto a = single(from, to), b = single(to, from);
    rev[a] = b;
    rev[b] = a;
};

new_edge_pair(0, 1);
new_edge_pair(0, 2);
new_edge_pair(1, 3);
new_edge_pair(2, 3);

Now you can do the loop by edge id:
auto& by_id = edge_idx.left;
for (auto const& e : by_id) {
    std::cout << "Edge #" << e.first << " is (" << source(e.second, g) << " -> " << target(e.second, g) << ")\n";
}

You can directly lookup an edge by it's id:
auto ed = by_id.at(random);
std::cout << "Random edge #" << random << " is (" << source(ed, g) << " -> " << target(ed, g) << ")\n";

The reverse lookup is a bit redundant, because you can do the same using BGL quite easily:
std::cout << "Reverse lookup: " << by_desc.at(ed) << "\n"; // reverse, though not very spectacular
std::cout << "Classic property lookup: " << g[ed].id << "\n"; // because it can be done using boost easily

Live On Coliru
#include <boost/graph/adjacency_list.hpp>
#include <boost/property_map/transform_value_property_map.hpp>
#include <boost/graph/boykov_kolmogorov_max_flow.hpp>
#include <functional>
#include <iostream>

#include <boost/bimap.hpp>
#include <random>

std::mt19937 prng { std::random_device{}() };

using namespace boost;

struct VertexProperty { std::string name; };

struct EdgeProperty {
    int id;
    double capacity, residual_capacity;

    EdgeProperty(int id, double cap, double res = 0)
        : id(id), capacity(cap), residual_capacity(res)
    { }
};

typedef adjacency_list<vecS, vecS, directedS, VertexProperty, EdgeProperty> Graph;

int main() {
    int nonodes = 4;
    Graph g(nonodes);

    // reverse edge map
    auto rev    = make_vector_property_map<Graph::edge_descriptor>(get(&EdgeProperty::id, g));

    // Create edges
    boost::bimaps::bimap<int, Graph::edge_descriptor> edge_idx;

    auto new_edge_pair = [&,edge_id=0](int from, int to) mutable {
        auto single = [&](int from, int to) {
            auto d = add_edge(from, to, EdgeProperty { edge_id, 4 }, g).first;
            if (!edge_idx.insert({edge_id++, d}).second)
                throw std::invalid_argument("duplicate key");
            return d;
        };

        auto a = single(from, to), b = single(to, from);
        rev[a] = b;
        rev[b] = a;
    };

    new_edge_pair(0, 1);
    new_edge_pair(0, 2);
    new_edge_pair(1, 3);
    new_edge_pair(2, 3);

    // property maps
    struct VertexEx {
        default_color_type color;
        double distance;
        Graph::edge_descriptor pred;
    };

    auto idx    = get(vertex_index, g);
    auto vex    = make_vector_property_map<VertexEx>(idx);
    auto pred   = make_transform_value_property_map(std::mem_fn(&VertexEx::pred),     vex);
    auto color  = make_transform_value_property_map(std::mem_fn(&VertexEx::color),    vex);
    auto dist   = make_transform_value_property_map(std::mem_fn(&VertexEx::distance), vex);

    auto cap    = get(&EdgeProperty::capacity, g);
    auto rescap = get(&EdgeProperty::residual_capacity, g);

    // algorithm
    double flow = boykov_kolmogorov_max_flow(g, cap, rescap, rev, pred, color, dist, idx, 0, 3);
    std::cout << "Flow: " << flow << "\n";

    {
        auto& by_id   = edge_idx.left;
        auto& by_desc = edge_idx.right;

        for (auto const& e : edge_idx.left) {
            std::cout << "Edge #" << e.first << " is (" << source(e.second, g) << " -> " << target(e.second, g) << ")\n";
        }
        int random = prng() % num_edges(g);
        auto ed = by_id.at(random);
        std::cout << "Random edge #" << random << " is (" << source(ed, g) << " -> " << target(ed, g) << ")\n";

        std::cout << "Reverse lookup: " << by_desc.at(ed) << "\n"; // reverse, though not very spectacular
        std::cout << "Classic property lookup: " << g[ed].id << "\n"; // because it can be done using boost easily
    }
}

Printing
Flow: 8
Edge #0 is (0 -> 1)
Edge #1 is (1 -> 0)
Edge #2 is (0 -> 2)
Edge #3 is (2 -> 0)
Edge #4 is (1 -> 3)
Edge #5 is (3 -> 1)
Edge #6 is (2 -> 3)
Edge #7 is (3 -> 2)
Random edge #2 is (0 -> 2)
Reverse lookup: 2
Classic property lookup: 2

Adjacency Matrix
Keeps everything the same, except for changing the model:
#include <boost/graph/adjacency_matrix.hpp>
typedef adjacency_matrix<directedS, VertexProperty, EdgeProperty> Graph;

And now you get the added capability of lookup by vertices:
Live On Coliru
std::cout << "Finding (3, 1) results in Edge #" << by_desc.at(edge(3, 1, g).first) << "\n";

Prints
Finding (3, 1) results in Edge #5


text:
Q: Scala - Youtube video id from URL I have the following regex from here: https://stackoverflow.com/a/10405818/924999
val regex = """/https?:\/\/(?:[0-9A-Z-]+\.)?(?:youtu\.be\/|youtube\.com(?:\/embed\/|\/v\/|\/watch\?v=|\/ytscreeningroom\?v=|\/feeds\/api\/videos\/|\/user\S*[^\w\-\s]|\S*[^\w\-\s]))([\w\-]{11})[?=&+%\w-]*/ig;""".r

I'm attempting to extract the video ID from youtube video urls with:
val url = "http://www.youtube.com/watch?v=XrivBjlv6Mw"

url match {

    case regex(result) => result

    case _ => null

}

However it seems to always return null, is there something I'm missing or need to do differently?
Thanks in advance for any help, much appreciated :)

A: The regex that you have is php-style regex, not java-style - for example, note /ig; flags at the end.
So you'll just have to edit it a bit:
val youtubeRgx = """https?://(?:[0-9a-zA-Z-]+\.)?(?:youtu\.be/|youtube\.com\S*[^\w\-\s])([\w \-]{11})(?=[^\w\-]|$)(?![?=&+%\w]*(?:[\'"][^<>]*>|</a>))[?=&+%\w-]*""".r

I tested it on all possible youtube urls, and it works. Example:
scala> youtubeRgx.pattern.matcher("http://www.youtube.com/watch?v=XrivBjlv6Mw").matches
res23: Boolean = true

And extracting the value:
"http://www.youtube.com/watch?v=XrivBjlv6Mw" match {
  case youtubeRgx(a) => Some(a)
  case _ => None
}
res33: Option[String] = Some(XrivBjlv6Mw)

It's a pity that java does not allow proper comments in regexps, so I did what I could:
val youtubeRgx = """https?://         # Required scheme. Either http or https.
                   |(?:[0-9a-zA-Z-]+\.)? # Optional subdomain.
                   |(?:               # Group host alternatives.
                   |  youtu\.be/      # Either youtu.be,
                   || youtube\.com    # or youtube.com followed by
                   |  \S*             # Allow anything up to VIDEO_ID,
                   |  [^\w\-\s]       # but char before ID is non-ID char.
                   |)                 # End host alternatives.
                   |([\w\-]{11})      # $1: VIDEO_ID is exactly 11 chars.
                   |(?=[^\w\-]|$)     # Assert next char is non-ID or EOS.
                   |(?!               # Assert URL is not pre-linked.
                   |  [?=&+%\w]*      # Allow URL (query) remainder.
                   |  (?:             # Group pre-linked alternatives.
                   |    [\'"][^<>]*>  # Either inside a start tag,
                   |  | </a>          # or inside <a> element text contents.
                   |  )               # End recognized pre-linked alts.
                   |)                 # End negative lookahead assertion.
                   |[?=&+%\w-]*       # Consume any URL (query) remainder.
                   |""".stripMargin.replaceAll("\\s*#.*\n", "").replace(" ","").r

(adapted from @ridgerunner's answer here: find all youtube video ids in string)

A: A much simpler approach:
scala> val url = "http://www.youtube.com/watch?v=XrivBjlv6Mw"
url: java.lang.String = http://www.youtube.com/watch?v=XrivBjlv6Mw

scala> val regex = "v=[\\w]*"r
regex: scala.util.matching.Regex = v=[\w]*

scala> for (x <-  regex findFirstIn url) yield x.replace("v=","")
res3: Option[java.lang.String] = Some(XrivBjlv6Mw)

A: First Scala accepts Java style regex. If you supply slashes, then they are part of the pattern, not delimiter. Also the flags must be specified per group, not after the regex.
Second, for case regex(result) to match, you have to define a matching group in your pattern. You have to group the video ID as matching pattern - I just don't know if that's the case in the overly complex pattern.


text:
Q: A trend test similar to Mann-kendall but with more than one observation on each time point I'm trying to find the right test for to determine the trend of a set of values with some measure of statistical significance. I came across the mann-kendall test but realized it had the limiation of only one value per timepoint. I tried using the median value but I'm not sure that this is correct since I would imagine cases where the distribution for each set of values is very wide on the same timepoints should be treated differently than cases found in a very narrow distributions.
My data consists of multiple measurements per timepoint (some timepoints may have many observations others with very few or none)

A: You could still test for a Kendall correlation between the observations and their time index.
However you'll have many ties, so ordinary tables for it won't work. You'll either need an asymptotic approximation with an adjusted variance or software that correctly calculates the permutation distribution, or you'll need to approximate it by simulation (sampling the permutation distributions).
However the differing spreads at different time points may raise the question of whether you'd have exchangeability under the null (or a reasonable approximation of it). The fact that the spreads look different in the data doesn't mean that you couldn't have it under the null (the point null is almost certainly to be false, so the appearance of the data doesn't tell you whether or not it's an issue) -- but you should perhaps consider its plausibility if there was truly no trend.
As an example, consider a set of observations over time whose spread is related to the mean (spread increases when the mean increases). Then if under the null you assume that all the means are the same, the spreads would presumably also be the same and the different spreads in the data would be of no consequence.


text:
Q: 1 pixel table border in JTextPane using HTML I'm using a JTextPane to display some HTML that contains a table with a border. I want it to have a simple 1 pixel border.
I tried using style="border: 1px solid; border-collapse:collapse". This works in a web browser, but not in JTextPane.
Is there any way to have a simple 1 pixel table border using HTML in a JTextPane?

A: Use a combination of
public static final String TD = "	";
public static final String TABLE_PROP = "style='border: 1px black solid; background-color: black' width='100%' cellspacing='1' cellpadding='2'";

String html = "
" + "
" + TD + TD + "

" + TD + TD + "

";
try
{
            htmlEditorKit.insertHTML(htmlDocument, caretPosition, html, 0, 0, null);
}

A: Here's a complete example:
package test

import java.awt.SystemColor;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;

@SuppressWarnings("serial")
public class HtmlDemo extends JPanel {

    public HtmlDemo() {
        setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));

        String rgb = Integer.toHexString(SystemColor.window.getRGB());
        String backgroundColor = rgb.substring(2, rgb.length());

        String html = "\n"
            + "\n"
            + "\n"
            + "\n"
            + "\n"
            + "HTML table test:\n"
            + "
\n"
            + "
\n"
            + "
\n" + "\n" + "cell1\n" + "	\n" + "\n" + "cell2\n" + "	\n" + "
\n"
            + "
\n" + "\n" + "cell3\n" + "	\n" + "\n" + "cell4\n" + "	\n" + "
\n"
            + "
\n"
            + "\n"
            + "";

        JLabel label = new JLabel(html);
        label.setVerticalAlignment(SwingConstants.CENTER);
        label.setHorizontalAlignment(SwingConstants.CENTER);

        setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        add(label);
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                JFrame frame = new JFrame("HtmlDemo");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new HtmlDemo());
                frame.pack();
                frame.setVisible(true);
            }
        });
    }
}

A: javax.swing.text.html is based on HTML 3.2, but you can use the border attribute of the
 tag.

A: trashgod is right - Java's HTML support is limited - so why not use an HTML workaround?  Just put your table (with no borders) inside another table with one cell that has a border.

      // Content here

It's not the cleanest of methods, but it does get around HTML 3.2 limitations.'

A: Here's an example to create a border to a table on preferable colour in HTML 3.2:

                Test


text:
Q: Is internal energy a function of pressure? I read that internal energy is a function of temperature only and not pressure. But say, we compress a volume of gas. Won't the particles start moving more quickly? Meaning an increase in their internal energy.
Is this an increase in the internal energy due to pressure?
Or an increase in temperature due to pressure which in turn increases the energy?
How do I see this?

A: For an ideal gas the internal energy only depends on the temperature of the gas. How the temperature relates to pressure is easily seen in the ideal gas law $$PV=NkT$$
So I suppose one could make the argument that the internal energy for the ideal gas depends on the quantity $$\frac{PV}{Nk}$$
and it's up to you how you want to explain the dependency. The problem with this though is that, depending on the process, these variables are constrained to evolve in certain ways.
Indeed, for your compression example, how you are compressing the gas matters. I will cover some typical examples:

If the gas is compressed in such a way so that its pressure is inversely proportional to it's volume, then by the ideal gas law the temperature remains constant. It turns out that in this case the heat that leaves the gas is exactly balanced by the work you do on it. The internal energy does not change.
If the gas is compressed in such a way so that its pressure remains constant, then by the ideal gas law the temperature drops in proportion to the volume. In this case more energy leaves the system as heat than what you put in as work. The internal energy decreases.
If the gas is compressed in such a way so that no heat enters or leaves the system, then all the work you do goes into increasing the internal energy, and hence the temperature of the gas. This process is probably what you had in mind. Here the pressure and volume both change, but the pressure increases in a larger proportion than the volume decreases$^*$. Therefore, by the ideal gas law the temperature increases.

$^*$ In fact, for this process the value $PV^\gamma$ is constant where $\gamma>1$. So, if $V$ decreases by a factor $x>1$, then $P$ must increase by a factor of $x^{\gamma}$. This means that $PV$, and hence $T$, must increase by a factor of $x^{\gamma-1}>1$.

A: As @Asron Stevens has already pointed out the answers to your questions really depend on the thermodynamic process involved as well as the type of gas (ideal or real). For example he has shown you that, for an ideal gas, you can have an increase in pressure with no change in temperature or internal energy (isothermal compression).
When you say you read "internal energy is a function of temperature only", that is correct for ideal gases because there are no intermolecular forces and therefore their internal energy is considered to be all kinetic energy. However it is not necessarily correct for real gases where intermolecular (van der Waal) forces are involved and therefore internal energy is the sum of its internal kinetic and potential energy.
Moving away from gases to solids and liquids,  you can have an increase or decrease in the total internal energy without a change in temperature during isothermal phase changes. Phase changes are generally associated with changes in the potential energy component of the internal energy of substances.
Hope this helps.

A: The important thing to remember is that U is a function of state (a property of the material) independent of any process.  Between two thermodynamics equilibrium states, the change in U is independent of the specific process path that was used to transition the system between these two states.  There are an infinite number of paths that can go between the two states, and Q and W can vary between these paths, but the change in U will be the same for all of them.  So one might as well use a reversible path for which dU = TdS - PdV.  This leads to the relationship between dU and dT and dP that I wrote down in a comment in @BobD's answer.
For an ideal gas, U and H are functions only of T, but for real gases, liquids, and solids, they are also functions of P (and/or V).  This is because the ideal gas behavior applies to real gases in the limit of low pressures, where the molecules are far apart (and don't interact energetically to a significant extent).  In real gases, the pressures/densities are higher, and the molecules do interact significantly, resulting in potential energy interactions and thus effects on internal energy.


text:
Q: Spring Integration xpath expression Multiple Condition Check I have an SAP IDOC that I want to filter but I am Stuck at one Place.
Here is a Sample XML
    <E1EDK14 SEGMENT="1">
        <QUALF>007</QUALF>
        <ORGID>10</ORGID>
    </E1EDK14>
    <E1EDK14 SEGMENT="1">
        <QUALF>008</QUALF>
        <ORGID>BP01</ORGID>
    </E1EDK14>
    <E1EDK14 SEGMENT="1">
        <QUALF>012</QUALF>
        <ORGID>ZMOR</ORGID>
    </E1EDK14>

The Condition would be Something like
if QUALF = 12 and ORGID = ZOR then process else ignore
My Code is Something like this
<int-xml:xpath-router id="splitORGID" input-channel="ORDERS" evaluate-as-string="true" resolution-required="false" default-output-channel="ORDER-TYPE-NOT-SUPPORTED">
    <int-xml:xpath-expression id="splitORGIDExpression" expression="//E1EDK14/ORGID" />
    <int-xml:mapping value="ZOR" channel="ALLOW_ORDERS" />
</int-xml:xpath-router>

I would like to know if this is correct.

A: This is the Solution I came up with and it is working fine
<int-xml:xpath-router id="splitORGID" input-channel="CUSTORDERS" evaluate-as-string="true" resolution-required="false" default-output-channel="ORDERTYPE-NOTSUPPORTED-KTOKD">
    <int-xml:xpath-expression id="splitORGIDExpression" expression="//E1EDK14[QUALF=012]/ORGID" />
    <int-xml:mapping value="ZOR" channel="ORDERS" />
    <int-xml:mapping value="ZSCO" channel="ORDERS" />
    <int-xml:mapping value="ZMOR" channel="HISTORICALORDERS" />
</int-xml:xpath-router>


text:
Q: how to navigate from one page to the other in j2me I am newbie to J2ME. I am trying to navigate from one MIDlet page to the other on the selection of ListItem. But I am getting following error message.
Installing suite from: file:///C:/Users/mohit/Documents/NetBeansProjects/MobileApp1/dist/nbrun8756732879038612272/MobileApp1.jad
6370272 - ERROR - AMS - 2 - Installation failed:com.sun.midp.midletsuite.MIDletSuiteLockedException
com.sun.midp.midletsuite.MIDletSuiteLockedException
at com.sun.midp.midletsuite.MIDletSuiteImpl.lockMIDletSuite(), bci=0
at com.sun.midp.midletsuite.MIDletSuiteStorage.getMIDletSuite(), bci=12
at com.sun.midp.installer.Installer.checkPreviousVersion(), bci=60
at com.sun.midp.installer.Installer.installStep2(), bci=10
at com.sun.midp.installer.Installer.performInstall(), bci=132
at com.sun.midp.installer.Installer.resumeInstallation(), bci=7
at com.sun.midp.installer.MidpInstaller$StartAction.run(), bci=10
at com.sun.j2me.security.AccessController.doPrivileged(), bci=12
at com.sun.midp.installer.MidpInstaller$InstallThread.run(), bci=9
at java.lang.Thread.run(Thread.java:721)

TRACE: <at java.lang.NullPointerException:   0>, Exception caught in Display class
java.lang.NullPointerException:   0
 - mobileapp1.VisualMIDlet.commandAction(VisualMIDlet.java:180)
at javax.microedition.lcdui.Display$ChameleonTunnel.callScreenListener(), bci=39
at com.sun.midp.chameleon.layers.SoftButtonLayer.processCommand(), bci=62
at com.sun.midp.chameleon.layers.SoftButtonLayer.soft2(), bci=119
at com.sun.midp.chameleon.layers.SoftButtonLayer.keyInput(), bci=102
at com.sun.midp.chameleon.CWindow.keyInput(), bci=30
at javax.microedition.lcdui.Display$DisplayEventConsumerImpl.handleKeyEvent(), bci=43
at com.sun.midp.lcdui.DisplayEventListener.process(), bci=252
at com.sun.midp.events.EventQueue.run(), bci=130
at java.lang.Thread.run(Thread.java:721)

I don't know how to handle this one. Can anyone help me out,please?
//VisualMIDlet.java
package mobileapp1;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import org.netbeans.microedition.lcdui.LoginScreen;

public class VisualMIDlet extends MIDlet implements CommandListener {

private boolean midletPaused = false;

private java.util.Hashtable __previousDisplayables = new java.util.Hashtable();
private LoginScreen loginScreen;
private Form FallSem_Home;
private ChoiceGroup choiceGroup;
private List stud_homelist;
private Form WinterSem_Home;
private Command exit_StudList;
private Command exitCommand1;
private Command exitCommand2;
private Command backCommand;
private Command ok_StudList;
private Command okCommand;

private List menu = null;
private Display display;
Fall_Sem fall_sem;
public VisualMIDlet() {
    //fall_sem = new Fall_Sem();
}

private void switchToPreviousDisplayable() {
    Displayable __currentDisplayable = getDisplay().getCurrent();
    if (__currentDisplayable != null) {
        Displayable __nextDisplayable = (Displayable) __previousDisplayables.get(__currentDisplayable);
        if (__nextDisplayable != null) {
            switchDisplayable(null, __nextDisplayable);
        }
    }
}

private void initialize() {
    // write pre-initialize user code here

    // write post-initialize user code here
}

public void startMIDlet() {
    // write pre-action user code here
    switchDisplayable(null, getLoginScreen());
    // write post-action user code here
}

public void resumeMIDlet() {
    // write pre-action user code here

    // write post-action user code here
}

public void switchDisplayable(Alert alert, Displayable nextDisplayable) {
    // write pre-switch user code here
    Display display = getDisplay();
    Displayable __currentDisplayable = display.getCurrent();
    if (__currentDisplayable != null && nextDisplayable != null) {
        __previousDisplayables.put(nextDisplayable, __currentDisplayable);
    }
    if (alert == null) {
        display.setCurrent(nextDisplayable);
    } else {
        display.setCurrent(alert, nextDisplayable);
    }
    // write post-switch user code here
}

public void commandAction(Command command, Displayable displayable) {
    // write pre-action user code here
    if (displayable == FallSem_Home) {
        if (command == backCommand) {
            // write pre-action user code here

            // write post-action user code here
        } else if (command == exit_StudList) {
            // write pre-action user code here
            //notifyDestroyed();

            // write post-action user code here
        } else if (command == okCommand) {
            // write pre-action user code here

            // write post-action user code here
        }
    } else if (displayable == WinterSem_Home) {
        if (command == backCommand) {
            // write pre-action user code here
            switchToPreviousDisplayable();
            // write post-action user code here
        } else if (command == exitCommand2) {
            // write pre-action user code here

            // write post-action user code here
        }
    } else if (displayable == loginScreen) {
        if (command == LoginScreen.LOGIN_COMMAND) {
            // write pre-action user code here
            if(loginScreen.getUsername().equals("mohit") && loginScreen.getPassword().equals("abhi")){
                switchDisplayable(null, getStud_homelist());
            // write post-action user code here
            }
        }
    } else if (displayable == stud_homelist) {
        if (command == List.SELECT_COMMAND) {
            // write pre-action user code here
            stud_homelistAction();
            // write post-action user code here
        } else if (command == exit_StudList) {
            // write pre-action user code here
            exitMIDlet();
            // write post-action user code here
        } **else if (command == ok_StudList) {
            // write pre-action user code here
            List options = (List) display.getCurrent();
            switch(options.getSelectedIndex()){
                case 0:

                    displayable = fall_sem.getForm();
                    switchDisplayable(null, displayable);
                    //display.setCurrent(fall_sem.getForm());
            }

            // write post-action user code here
        }**
    }
    // write post-action user code here
}

public LoginScreen getLoginScreen() {
    if (loginScreen == null) {
        // write pre-init user code here
        loginScreen = new LoginScreen(getDisplay());
        loginScreen.setLabelTexts("Username", "Password");
        loginScreen.setTitle("loginScreen");
        loginScreen.addCommand(LoginScreen.LOGIN_COMMAND);
        loginScreen.setCommandListener(this);
        loginScreen.setFullScreenMode(true);
        loginScreen.setBGColor(-3355444);
        loginScreen.setFGColor(0);
        loginScreen.setPassword("");
        loginScreen.setUsername("");
        loginScreen.setUseLoginButton(true);
        loginScreen.setLoginButtonText("Login");
        // write post-init user code here
    }
    return loginScreen;
}

public Form getFallSem_Home() {
    if (FallSem_Home == null) {
        // write pre-init user code here
        FallSem_Home = new Form("form", new Item[]{getChoiceGroup()});
        FallSem_Home.addCommand(getExit_StudList());
        FallSem_Home.addCommand(getBackCommand());
        FallSem_Home.addCommand(getOkCommand());
        FallSem_Home.setCommandListener(this);
        // write post-init user code here
    }
    return FallSem_Home;
}

public Command getExit_StudList() {
    if (exit_StudList == null) {
        // write pre-init user code here
        exit_StudList = new Command("Exit", Command.EXIT, 0);
        // write post-init user code here
    }
    return exit_StudList;
}

public ChoiceGroup getChoiceGroup() {
    if (choiceGroup == null) {
        // write pre-init user code here
        choiceGroup = new ChoiceGroup("choices", Choice.EXCLUSIVE);
        choiceGroup.append("Time Table", null);
        choiceGroup.append("Exam Schedule", null);
        choiceGroup.append("Marks", null);
        choiceGroup.setFitPolicy(Choice.TEXT_WRAP_DEFAULT);
        choiceGroup.setSelectedFlags(new boolean[]{false, false, false});
        // write post-init user code here
    }
    return choiceGroup;
}

public List getStud_homelist() {
    if (stud_homelist == null) {
        // write pre-init user code here
        stud_homelist = new List("list", Choice.IMPLICIT);
        stud_homelist.append("Fall Sem 2012-13", null);
        stud_homelist.append("Winter Sem 2012-13", null);
        stud_homelist.append("Add / Drop", null);
        stud_homelist.addCommand(getExit_StudList());
        stud_homelist.addCommand(getOk_StudList());
        stud_homelist.setCommandListener(this);
        stud_homelist.setSelectedFlags(new boolean[]{false, false, false});
        // write post-init user code here
    }
    return stud_homelist;
}

public void stud_homelistAction() {
    // enter pre-action user code here
    String __selectedString = getStud_homelist().getString(getStud_homelist().getSelectedIndex());
    if (__selectedString != null) {
        if (__selectedString.equals("Fall Sem 2012-13")) {
            // write pre-action user code here

            // write post-action user code here
        } else if (__selectedString.equals("Winter Sem 2012-13")) {
            // write pre-action user code here

            // write post-action user code here
        } else if (__selectedString.equals("Add / Drop")) {
            // write pre-action user code here

            // write post-action user code here
        }
    }
    // enter post-action user code here
}

public Form getWinterSem_Home() {
    if (WinterSem_Home == null) {
        // write pre-init user code here
        WinterSem_Home = new Form("form");
        WinterSem_Home.addCommand(getBackCommand());
        WinterSem_Home.addCommand(getExitCommand2());
        WinterSem_Home.setCommandListener(this);
        // write post-init user code here
    }
    return WinterSem_Home;
}

public Command getExitCommand1() {
    if (exitCommand1 == null) {
        // write pre-init user code here
        exitCommand1 = new Command("Exit", Command.EXIT, 0);
        // write post-init user code here
    }
    return exitCommand1;
}

public Command getBackCommand() {
    if (backCommand == null) {
        // write pre-init user code here
        backCommand = new Command("Back", Command.BACK, 0);
        // write post-init user code here
    }
    return backCommand;
}

public Command getExitCommand2() {
    if (exitCommand2 == null) {
        // write pre-init user code here
        exitCommand2 = new Command("Exit", Command.EXIT, 0);
        // write post-init user code here
    }
    return exitCommand2;
}

public Command getOkCommand() {
    if (okCommand == null) {
        // write pre-init user code here
        okCommand = new Command("Ok", Command.OK, 0);
        // write post-init user code here
    }
    return okCommand;
}

public Command getOk_StudList() {
    if (ok_StudList == null) {
        // write pre-init user code here
        ok_StudList = new Command("Ok", Command.OK, 0);
        // write post-init user code here
    }
    return ok_StudList;
}

public Display getDisplay() {
    return Display.getDisplay(this);
}

public void exitMIDlet() {
    switchDisplayable(null, null);
    destroyApp(true);
    notifyDestroyed();
}

public void startApp() {
    if (midletPaused) {
        resumeMIDlet();
    } else {
        initialize();
        startMIDlet();
    }
    midletPaused = false;
}

public void pauseApp() {
    midletPaused = true;
}

public void destroyApp(boolean unconditional) {
            notifyDestroyed();

}
}

 //Fall_Sem.java
package mobileapp1;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import org.netbeans.microedition.lcdui.LoginScreen;
import org.netbeans.microedition.lcdui.SimpleTableModel;
import org.netbeans.microedition.lcdui.TableItem;

public class Fall_Sem extends MIDlet implements CommandListener {

private boolean midletPaused = false;
private Display display;

private Form form;
private ChoiceGroup choiceGroup;
private Form form1;
private TableItem tableItem;
private Command backCommand;
private Command okCommand;
private Command exitCommand;
private Command exitCommand1;
private Command backCommand1;
private SimpleTableModel simpleTableModel;
public Fall_Sem() {
    System.out.println("Fall Sem");
}

private void initialize() {
    // write pre-initialize user code here

    // write post-initialize user code here
}
public void startMIDlet() {
    // write pre-action user code here
    switchDisplayable(null, getForm());
    // write post-action user code here
}
public void resumeMIDlet() {
    // write pre-action user code here

    // write post-action user code here
}
public void switchDisplayable(Alert alert, Displayable nextDisplayable) {
    // write pre-switch user code here
    Display display = getDisplay();
    if (alert == null) {
        display.setCurrent(nextDisplayable);
    } else {
        display.setCurrent(alert, nextDisplayable);
    }
    // write post-switch user code here
}
public Form getForm() {
    if (form == null) {
        // write pre-init user code here
        form = new Form("form", new Item[] getChoiceGroup()});
        form.addCommand(getBackCommand());
        form.addCommand(getOkCommand());
        form.addCommand(getExitCommand());
        form.setCommandListener(this);
        // write post-init user code here
    }
    return form;
}
public ChoiceGroup getChoiceGroup() {
    if (choiceGroup == null) {
        // write pre-init user code here
        choiceGroup = new ChoiceGroup("Choices", Choice.EXCLUSIVE);
        choiceGroup.append("Time Table", null);
        choiceGroup.append("Exam Schedule", null);
        choiceGroup.append("Marks", null);
        choiceGroup.setSelectedFlags(new boolean[]{false, false, false});
        // write post-init user code here
    }
    return choiceGroup;
}
public void commandAction(Command command, Displayable displayable) {
    // write pre-action user code here
    if (displayable == form) {
        if (command == backCommand) {
            // write pre-action user code here

            // write post-action user code here
        } else if (command == exitCommand) {
            // write pre-action user code here
            exitMIDlet();
            // write post-action user code here
        } else if (command == okCommand) {
            // write pre-action user code here
            switchDisplayable(null, getForm1());
            // write post-action user code here
        }
    } else if (displayable == form1) {
        if (command == backCommand1) {
            // write pre-action user code here

            // write post-action user code here
        } else if (command == exitCommand1) {
            // write pre-action user code here
            exitMIDlet();
            // write post-action user code here
        }
    }
    // write post-action user code here
}
public Form getForm1() {
    if (form1 == null) {
        // write pre-init user code here
        form1 = new Form("form1", new Item[]{getTableItem()});
        form1.addCommand(getBackCommand1());
        form1.addCommand(getExitCommand1());
        form1.setCommandListener(this);
        // write post-init user code here
    }
    return form1;
}
public TableItem getTableItem() {
    if (tableItem == null) {
        // write pre-init user code here
        tableItem = new TableItem(getDisplay(), "tableItem");
        // write post-init user code here

    }
    return tableItem;
}
public Command getBackCommand() {
    if (backCommand == null) {
        // write pre-init user code here
        backCommand = new Command("Back", Command.BACK, 0);
        // write post-init user code here
    }
    return backCommand;
}
public Command getOkCommand() {
    if (okCommand == null) {
        // write pre-init user code here
        okCommand = new Command("Ok", Command.OK, 0);
        // write post-init user code here
    }
    return okCommand;
}
public Command getExitCommand() {
    if (exitCommand == null) {
        // write pre-init user code here
        exitCommand = new Command("Exit", Command.EXIT, 0);
        // write post-init user code here
    }
    return exitCommand;
}
public Command getBackCommand1() {
    if (backCommand1 == null) {
        // write pre-init user code here
        backCommand1 = new Command("Back", Command.BACK, 0);
        // write post-init user code here
    }
    return backCommand1;
}
public Command getExitCommand1() {
    if (exitCommand1 == null) {
        // write pre-init user code here
        exitCommand1 = new Command("Exit", Command.EXIT, 0);
        // write post-init user code here
    }
    return exitCommand1;
}
public SimpleTableModel getSimpleTableModel() {
    if (simpleTableModel == null) {
        // write pre-init user code here
        simpleTableModel = new SimpleTableModel(null, null);
        // write post-init user code here
    }
    return simpleTableModel;
}
public Display getDisplay() {
    return Display.getDisplay(this);
}

public void exitMIDlet() {
    switchDisplayable(null, null);
    destroyApp(true);
    notifyDestroyed();
}

public void startApp() {
    if (midletPaused) {
        resumeMIDlet();
    } else {
        initialize();
        startMIDlet();
    }
    midletPaused = false;
}

public void pauseApp() {
    midletPaused = true;
}

public void destroyApp(boolean unconditional) {
}
}

A: I wrote an example on how to do list selection based navigation in my other answer here:
Get event click list item in J2ME


text:
Q: Extract Div from returned view I an working on returning view from controller to jquery ,View is returned but i want to extract div from returned view.My Current code is like this
       public ActionResult DeleteItem(int pid)
                {
                 //my logic goes here
                    retutn View("SomeView",model);
                    }

                 Jquery

enter code here
          script type="text/javascript">
              $(document).ready(function () {

        $('.Remove').click(function () {
             var value = $(this).attr('id');
            $.ajax({
                cache:true,
                type: "POST",
                url: "@(Url.Action("DeleteItem", "ControllerName"))",
                data: "pid=" + value,
                success: function (data) {
                    $("body").html(data);

                },
                error:function (xhr, ajaxOptions, thrownError){
                    alert('Failed to subscribe.');

                },
                complete: function() {   }
           });
            return false;
                 });
                      });

        </script>

My current logic returns view and assign total view i.e html+body to body part of page ,which shows html part two times.Is there any way to retrieve div from the returned view and reload it.
thanx in advance

A: Your controller action should return a PartialViewResult otherwise it will return your layout page in the response. If you want to cater for both scenarios you can check whether the request is an AJAX request:
public ActionResult DeleteItem(int id) {
    // delete your item

    if (Request.IsAjaxRequest()) {
        // return just the partial view
        return PartialView("yourview");
    }

    // otherwise handle normally
    return RedirectToAction("list");
}

To understand the difference between returning View and returning PartialView please see What's the difference between "return View()" and "return PartialView()".

A:       script type="text/javascript">
          $(document).ready(function () {

    $('.Remove').click(function () {
         var value = $(this).attr('id');
        $.ajax({
            cache:true,
            type: "POST",
            url: "@(Url.Action("DeleteItem", "ControllerName"))",
            data: "pid=" + value,
            success: function (data) {
                     var t=$(data).find('.divtoreplacewith');
                               $('.divtoreplace').replaceWith(d);
         //Wasted my 2 days for above two lines.But satisfied with solution,
          //Both div are same but '.divtoreplacewith' is having new data,And I have replaced div with that div that's all
            },
            error:function (xhr, ajaxOptions, thrownError){
                alert('Failed to subscribe.');

            },
            complete: function() {   }
       });
        return false;
             });
                  });


text:
Q: Solve $|x^2-a^2|=a^2-x$, $a>1$
Solve $|x^2-a^2|=a^2-x$, where $a>1$.

The first line of the model answer http://image.prntscr.com/image/6da5a4db6ec740718f0a149401eaf478.png has:
$$x^2-a^2=a^2-x.$$
Why have they done this?

*

*This was part of a Model Answer to a question on inequalities in June'09 Edexcel FP2 paper.

*Question 7 on examiners report for FP2: http://qualifications.pearson.com/content/dam/pdf/A%20Level/Mathematics/2013/Exam%20materials/8371_9374_GCE_Maths_rep_20090813_UA021531.pdf does not give much further info.
Answer: There are two cases:

*

*$x^2-a^2=a^2-x$

*$x^2-a^2=-a^2+x$

I just concentrated on the first line without realising the second case

A: An equation of the form $|A|=B$ is equivalent to the set of equations
$$
A=B\qquad A=-B
$$
provided $B\ge0$.
In your case
$$
x^2-a^2=a^2-x
\qquad
x^2-a^2=x-a^2
$$
Just solve the two quadratics and consider the roots of both.
You see in the image a large white space to separate the solutions of the two quadratics.
After that, check what roots satisfy $a^2-x\ge0$.
The solutions are
$$
\frac{-1-\sqrt{1+8a^2}}{2}
\qquad
\frac{-1+\sqrt{1+8a^2}}{2}
\qquad
0
\qquad
1
$$
Which ones are good?


text:
Q: How does Oracle's TO_NUMBER() determine the return NUMBER datatype? I am currently doing some research on Oracle functions, and one thing that stumped me a bit is how Oracle determines the return datatype of TO_NUMBER().
TO_NUMBER() takes in three parameters, two of which are optional. The first parameter is the input string, with the second being a format string, and third being a NLS locale string.
The output of TO_NUMBER() is a NUMBER datatype, and Oracle has a good number of NUMBER datatypes including FLOAT, DEC, INTEGER, INT, REAL, etc.
My question is -- how does TO_NUMBER() determine which specific numeric datatype to return? Is it determined by the first optional parameter, the format string?

A: As @mathguy has pointed out, TO_NUMBER always returns a NUMBER.  You can check this out yourself with the DUMP function. It will return the datatype and the internal representation of the data, eg
SQL> select dump(to_number('1')) from dual;

DUMP(TO_NUMBER('1'
------------------
Typ=2 Len=2: 193,2

SQL> select dump(to_number('1.123')) from dual;

DUMP(TO_NUMBER('1.123'))
------------------------
Typ=2 Len=4: 193,2,13,31

Even a float when passed to TO_NUMBER will become a NUMBER
SQL> select dump(to_number(1.0e+3f)) from dual;

DUMP(TO_NUMBER(1.0E
-------------------
Typ=2 Len=2: 194,11


text:
Q: Python list + list vs. list.append() Today I spent about 20 minutes trying to figure out why
this worked as expected:
users_stories_dict[a] = s + [b]

but this would have a None value:
users_stories_dict[a] = s.append(b)

Anyone know why the append function does not return the new list? I'm looking for some sort of sensible reason this decision was made; it looks like a Python novice gotcha to me right now.

A: The append() method returns a None, because it modifies the list it self by adding the object appended as an element, while the + operator concatenates the two lists and return the resulting list
eg:
a = [1,2,3,4,5]
b = [6,7,8,9,0]

print a+b         # returns a list made by concatenating the lists a and b
>>> [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

print a.append(b) # Adds the list b as element at the end of the list a and returns None
>>> None

print a           # the list a was modified during the last append call and has the list b as last element
>>> [1, 2, 3, 4, 5, [6, 7, 8, 9, 0]]

So as you can see the easiest way is just to add the two lists together as even if you append the list b to a using append() you will not get the result you want without additional work

A: append works by actually modifying a list, and so all the magic is in side-effects. Accordingly, the result returned by append is None. In other words, what one wants is:
s.append(b)
and then:
users_stories_dict[a] = s
But, you've already figured that much out. As to why it was done this way, while I don't really know, my guess is that it might have something to do with a 0 (or false) exit value indicating that an operation proceeded normally, and by returning None for functions whose role is to modify their arguments in-place you report that the modification succeeded.
But I agree that it would be nice if it returned the modified list back. At least, Python's behavior is consistent across all such functions.


text:
Q: Image upload from iOS Swift to Node.js and Express backend Here I'm trying to upload an image using POST request. Application backend is MEAN. When I'm trying with Postman, it is uploading successfully.
But ios datatask showing undefined file.
Here is my MEAN code.
var multer  = require('multer')
var storage = multer.diskStorage({
        destination: function (req, file, cb) {
            cb(null, 'images/profile_images')
        },
        filename: function (req, file, cb) {

            var getFileExt = function(fileName){
                var fileExt = fileName.split(".");
                if( fileExt.length === 1 || ( fileExt[0] === "" && fileExt.length === 2 ) ) {
                    return "";
                }
                return fileExt.pop();
            }
            cb(null, Date.now() + '.' + getFileExt(file.originalname))
        }
    });

var upload = multer({ storage: storage})
var type = upload.single('profile_pic');

    app.post('/images' ,type ,function(req,res) {
        console.log(req.body, req.file , req);
});

output
file:     { fieldname: 'profile_pic',
       originalname: '1.png',
       encoding: '7bit',
       mimetype: 'image/png',
       destination: 'images/profile_images',
       filename: '1486012211611.png',
       path: 'images/profile_images/1486012211611.png',
       size: 144 },   __onFinished: null }

Here is my Swift code:
@IBAction func uploadImage(_ sender: Any) {
    let api = URL.init(string: "http://localhost:3000/images")
    var request = URLRequest.init(url: api!, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 5)
    request.httpMethod = "POST"

    let boundary = generateBoundaryString()

    request.setValue("multipart/form-data, boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

    let imge:Data = UIImageJPEGRepresentation(UIImage.init(named: "image1")!, 1)!;

    let body = NSMutableData()

    let fname = "profile_pic.jpg"
    let mimetype = "image/png"

    body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8, allowLossyConversion: true)!)
    body.append("Content-Disposition:form-data; name=\"profile_pic\"\r\n\r\n".data(using: String.Encoding.utf8)!)
    body.append("hi\r\n".data(using: String.Encoding.utf8)!)

    body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
    body.append("Content-Disposition:form-data; name=\"profile_pic\"; filename=\"\(fname)\"\r\n".data(using: String.Encoding.utf8)!)
    body.append("Content-Type: \(mimetype)\r\n\r\n".data(using: String.Encoding.utf8)!)
    body.append(imge)

    body.append("\r\n".data(using: String.Encoding.utf8)!)
    body.append("--\(boundary)--\r\n".data(using: String.Encoding.utf8)!)

    request.httpBody = body as Data

    let session: URLSession = URLSession.shared

    let task = session.dataTask(with: request) { (data, response, error) in
        print(data, response, error!)
    }

    task.resume()

}

func generateBoundaryString() -> String {
    return "Boundary-\(NSUUID().uuidString)"
}

Output at terminal,
undefined

and the image is not uploading.
Can you help me where I'm going wrong?

A: You are working on localhost. Alamofire cannot send image to localhost server.
Alamofire with localhost connection problems


text:
Q: Is sys.stats_columns incorrect? Let's say I have a table Foo with columns ID1, ID2 and a composite primary key defined over ID2, ID1. (I'm currently working with a System Center product that has several tables defined this way with the primary key columns listed in the opposite order they appear in the table definition.)
CREATE TABLE dbo.Foo(
  ID1 int NOT NULL,
  ID2 int NOT NULL,
CONSTRAINT [PK_Foo] PRIMARY KEY CLUSTERED (ID2, ID1)
);
GO

-- Add a row and update stats so that histogram isn't empty
INSERT INTO Foo (ID1, ID2) VALUES (1,2);
UPDATE STATISTICS dbo.Foo;

The key_ordinal column in sys.index_columns shows the index columns in the same order they were declared in the composite primary key:
SELECT t.name, i.name, c.column_id, c.name, ic.index_column_id, ic.key_ordinal
FROM sys.tables AS t
JOIN sys.indexes AS i
ON t.[object_id] = i.[object_id]
JOIN sys.index_columns AS ic
ON ic.[object_id] = i.[object_id]
AND ic.index_id = i.index_id
JOIN sys.columns AS c
ON ic.column_id = c.column_id
AND ic.[object_id] = c.[object_id]
WHERE t.name = 'Foo';

The histogram also shows the statistics in the same order:
DBCC SHOW_STATISTICS ('Foo',PK_Foo);

However, sys.stats_columns shows the columns listed in the inverse order (ID1, ID2).
SELECT s.name, sc.stats_column_id, c.name
FROM sys.stats AS s
JOIN sys.stats_columns AS sc
ON s.stats_id = sc.stats_id
AND s.[object_id] = sc.[object_id]
JOIN sys.columns AS c
ON c.[object_id] = s.[object_id]
AND c.column_id = sc.column_id
JOIN sys.objects AS o
ON o.[object_id] = c.[object_id]
WHERE o.name = 'Foo'
AND s.name = 'PK_Foo';

Books Online says stats_column_id is a "1-based ordinal within set of stats columns," so I was expecting the value 1 to point to the first column in the statistics object.
Is this a bug in sys.stats_columns or a misunderstanding on my part?
I've verified this behaviour occurs on current builds of SQL Server 2005, 2008, 2008 R2, 2012, and 2014.
sys.stats_columns seems to reflect the order within the statistics object in other situations, for example:
CREATE TABLE dbo.Foo2(
  ID1 int NOT NULL,
  ID2 int NOT NULL,
  ID3 int NULL,
  String VARCHAR(10) NULL,
CONSTRAINT [PK_Foo2] PRIMARY KEY CLUSTERED (ID2, ID1)
);

GO

INSERT INTO Foo2 (ID1, ID2, ID3, String) VALUES (1,2,3,'String');

CREATE STATISTICS ST_Test ON Foo2 (ID3, String);
CREATE STATISTICS ST_Test2 ON Foo2 (String, ID3);

DBCC SHOW_STATISTICS ('Foo2',ST_Test);
DBCC SHOW_STATISTICS ('Foo2',ST_Test2);

SELECT s.name, sc.stats_column_id, c.name
FROM sys.stats AS s
JOIN sys.stats_columns AS sc
ON s.stats_id = sc.stats_id
AND s.[object_id] = sc.[object_id]
JOIN sys.columns AS c
ON c.[object_id] = s.[object_id]
AND c.column_id = sc.column_id
JOIN sys.objects AS o
ON o.[object_id] = c.[object_id]
WHERE o.name = 'Foo2'
AND s.name LIKE 'ST_Test%';

Here is another example where sys.stats_columns appears to return the correct data, this time for statistics on an index:
--drop table dbo.Foo3
CREATE TABLE dbo.Foo3(
  ID1 int NOT NULL,
  ID2 int NOT NULL,
  ID3 int NULL,
  String VARCHAR(10) NULL,
CONSTRAINT [PK_Foo3] PRIMARY KEY CLUSTERED (ID2, ID1)
);

GO

INSERT INTO Foo3 (ID1, ID2, ID3, String) VALUES (1,2,3,'String');
UPDATE STATISTICS Foo3;

CREATE INDEX IX_Test ON Foo3 (ID3, String);
CREATE INDEX IX_Test2 ON Foo3 (String, ID3);

DBCC SHOW_STATISTICS ('Foo3',IX_Test);
DBCC SHOW_STATISTICS ('Foo3',IX_Test2);

SELECT s.name, sc.stats_column_id, c.name
FROM sys.stats AS s
JOIN sys.stats_columns AS sc
ON s.stats_id = sc.stats_id
AND s.[object_id] = sc.[object_id]
JOIN sys.columns AS c
ON c.[object_id] = s.[object_id]
AND c.column_id = sc.column_id
JOIN sys.objects AS o
ON o.[object_id] = c.[object_id]
WHERE o.name = 'Foo3'
AND s.name LIKE 'IX_Test%';

A: This seems to be a long standing error:
swasheck - March 5, 2015 posted:
https://connect.microsoft.com/SQLServer/feedback/details/1163126

MSDN notes that sys.stats_columns.stats_column_id is "1-based ordinal
within set of stats columns." However, it seems to actually reflect
table definition order. Altering index order is not reflected in
sys.stats_columns.

Hannah Vernon and James Lupolt seem to agree based on their comments/encouragement.


text:
Q: Does $X$ have countable network if it has countable extent? Let $X$ have a $\sigma$-discrete network and have countable extent.

Does $X$ have countable network?

A family $\mathcal N$ of subsets of a topological space $X$ is a network for $X$ if for every point $x\in X$ and any neighbourhood $U$ of $x$ there exists an $M \in \mathcal N$ such that $x\in M \subset U$.
A network is like a base, except that its members need not be open sets.
Another question:

How could we see that every Moore space has a $\sigma$-discrete network?

Thanks for your help.

A: Let $\mathscr{N}=\bigcup_{n\in\omega}\mathscr{N}_n$ be a $\sigma$-discrete network for $X$, where each $\mathscr{N}_n$ is discrete. Fix $n\in\omega$, and for each $N\in\mathscr{N}_n$ fix $x_N\in N$. Then $\{x_N:N\in\mathscr{N}\}$ is a closed, discrete subset of $X$, so it's countable (since $X$ has countable extent), and therefore $\mathscr{N}_n$ is countable. It follows immediately that $\mathscr{N}$ is countable.
I'll have to come back to the other question later.

A:
How could we see that every Moore space has a $\sigma$-discrete network?

See Handbook of Set-Theoretic Topology, Theorem 4.5 (p.447 of the book = p.436 of the file).


text:
Q: Why does SBT libraryDependencies %% truncate scalaVersion? In my build.sbt I have the lines
scalaVersion := "2.10.0-M6"

libraryDependencies ++= List(
    "com.typesafe" %% "slick" % "0.11.0",
    "org.slf4j" %% "slf4j-nop" % "1.6.4"
)

running sbt update shows an unresolved dependency exception.  When I look at the URL sbt is trying to retrieve for the library, I see it's looking for com.typesafe$slick_2.10;0.11.0.
Why isn't the full ScalaVersion appended?  Is there an option I can use to cause it to use the entire version instead of the truncated one?

A: This should work starting with sbt 0.12. See Cross-building at sbt wiki.
"com.typesafe" % "slick" % "0.11.0" cross CrossVersion.full


text:
Q: Calculating variability index for strings of numbers in R I have many thousands of strings of numbers in a vector, with each number representing a tone realization (fall, rise, fall-rise, etc.) in units of speech. To illustrate:
Tones <- c("2222", "1411", "112", "815", "21111522")

What I'd like to get for each string is a variability index, by

*

*comparing each number in the string to the immediately next,

*storing a "1" if that next number is different than the preceding
number,

*storing a "0" if that next number equals the preceding number,

*adding up these stored values and

*dividing them by the total number of number pairs.

For example, for "2222", the variability index would be 0 because the first number in the string equals the second number, the second equals the third, and the third equals the last; thus the variability index would be (0+0+0)/3=0. For the string "1411" the index would be (1+1+0)/3=0.6666667 because "1" differs from "4", "4" differs from "1", and "1" equals "1".
I guess one will have to start by splitting the strings:
TonesSplit <- strsplit(Tones, split="")

which gives a list, then use for loops and if clauses to address the cells in the list slices. Just how to do it I don't know. I'd be very grateful for advice on how to program this.

A: A base one-liner R solution:
vapply(Tones,function(x) length(rle(charToRaw(x))$lengths)-1,1)/(nchar(Tones)-1)
#     2222      1411       112       815  21111522
#0.0000000 0.6666667 0.5000000 1.0000000 0.4285714

Some explanation:

*

*with charToRaw I get for each string the raw byte content;

*with rle I get the number of sequences of repeating characters. The changes are just the number of sequences less one;

*with vapply I apply to each string the function;

*with nchar I get the number of characters of each string.

A: This should do it:
library(dplyr)

Tones <- c("2222", "1411", "112", "815", "21111522")

TonesSplit <- lapply(strsplit(Tones, split=""), as.numeric)

sapply(TonesSplit, function(x){
  sum(ifelse(x != dplyr::lag(x, 1), 1, 0), na.rm = T)/(length(x)-1)
})

[1] 0.0000000 0.6666667 0.5000000 1.0000000 0.4285714

In the ifelse, we use dplyr::lag() to compare each vector of split numbers with the vector [-1], therefore generating a new vector that starts with NA and then gives 0 or 1, depending on the condition. We then sum this vector, ignoring the NA, and divide it by length(x)-1, which is the number of pairs.

A microbenchmark shows that the solution by @nicola is considerably faster:
microbenchmark(nicola = vapply(Tones,function(x) length(rle(charToRaw(x))$lengths)-1,1)/(nchar(Tones)-1),
               LAP = sapply(lapply(strsplit(Tones, split=""), as.numeric), function(x){
                 sum(ifelse(x != dplyr::lag(x, 1), 1, 0), na.rm = T)/(length(x)-1)
               }),
               unit = "ms")

Unit: milliseconds
   expr      min        lq      mean    median        uq      max neval cld
 nicola 0.077654 0.0841960 0.1047870 0.0871830 0.0934405 1.684196   100   a
    LAP 0.109227 0.1194675 0.1482074 0.1230225 0.1281425 2.525868   100   a


text:
Q: go from block back to image + blockproc I need to visualize the output from blockproc. I use this function to get a label for all the blocks. I want to now set each block in the image to the corresponding label in the output.
The code is given below:
Feature = blockproc( image , [ 8 8 ] , fun );
%where image is a binary image and fun gives 1 label either 0 or 1 to each block

%% Now for each block I want to do the reverse - set the corresponding image coords to
%% the feature output

I figured I can call another blockproc which will set the images to the corresponding Feature values. But I am having trouble doing this.
%% fun = @(block_struct) block_struct.data = Feature ( counter ) // counter = block no.

Any way to do the above ?

A: If your fun takes a block and returns a single label, you can instead make it return a block of the same size as the input as shown in the documentation example.
fun = @(block_struct) ...
   std2(block_struct.data) * ones(size(block_struct.data));

Then your Feature will be the same size as the original image.
Alternatively, you can just resize the output - either use imresize with nearest or this will do it:
Feature2 = kron(Feature, ones(8));


text:
Q: When a class has some virtual methods, do all it's methods use a vtable? In this example below, Type has a virtual method so it has a vtable. However, Type::Bar() is not virtual. When calling Bar(), does the call also go through the vtable mechanism, or will it only apply to Foo()?
struct Base {
  virtual void Foo() {}
}

struct Type : Base {
  void Foo() override {}
  void Bar() {}
}

Base* b = new Type();
Type* t = static_cast<Type*>(b);
t->Bar(); // Does this use a vtable?

A:
However, Type::Bar() is not virtual. When calling Bar(), does the call also go through the vtable mechanism, or will it only apply to Foo()?

The function to call for non-virtual functions is decided at compile time. Hence, there is no good reason for an implementation to choose the vtable to dispatch a call to a non-virtual function. However, the standard doesn't prohibit an implementation from using a vtable even for non-virtual functions.
@EJP said it better:
The standard doesn't require an implementation to use vtable for virtual functions. It's an implementation detail. No sane implementation using vtables would waste space in them by including non-virtual functions

A: The concept of a vtable is an implementation detail that's not further mentioned in the c++ standard.
But if there are non virtual functions provided at a class there's certainly no need to include them there, but fully bind the calls at compile time


text:
Q: What does "Break outside Loop" mean? Beginner!
I am trying to make a program that reads in X whole numbers and outputs (1) the sum of all positive numbers, (2) the sum of all negative numbers, and (3) the sum of all positive and negative numbers. The user can enter the X numbers in any different order every time, and can repeat the program if desired.
In order to add the repeat function I have added "break" to the loop. However when I try to run it it shows an error that says "break outside loop". I am unsure what this error means and how I can go about fixing it.
while True:
    many = int(input("How many numbers would you like to enter:"))
    Sum = 0
    sumNeg = 0
    for i in range(0,many,1):
        num = float(input("Please enter number" +str(i+1)+":"))
        Sum = Sum + num
        if num < 0:
            sumNeg = sumNeg + num
    print('Sum =',Sum)
    print('sumNeg =', sumNeg)
repeat =input("Would you like to repeat? (Y/N):")
if repeat != 'Y':
    break

A: The break statement is outside the loop because it's parent if statement is outside the loop.
while True:
    many = int(input("How many numbers would you like to enter:"))
    Sum = 0
    sumNeg = 0
    for i in range(0,many,1):
        num = float(input("Please enter number" +str(i+1)+":"))
        Sum = Sum + num
        if num < 0:
            sumNeg = sumNeg + num
    print('Sum =',Sum)
    print('sumNeg =', sumNeg)
    repeat =input("Would you like to repeat? (Y/N):")
    if repeat != 'Y':
        break


text:
Q: Forwarding onActivityResult from Activity to Fragment in android I am trying to implement Facebook login for my android app. However, instead of using the LoginActivity, as suggested on the developer website, I have added the Facebook login button on a separate fragment. This fragment simply holds the button and does all the processing, which otherwise the LoginActivity would have done.
The purpose of using a separate fragment is to prevent doing everything in the LoginActivity, specially if other login options like Google+ also exist.
Now the problem is that the UiLifecycleHelper constructor accepts only Activity object for callbacks:
UiLifecycleHelper(Activity, StatusCallback)

Because of this, I am bound to do something like:
UiLifecycleHelper(getActivity(), callback)

So, eventually:
@override
onActivityResult(...)

is called in LoginActivity, instead of in my fragment which hosts the login button.
Now the authentication won't work, unless I explicitly call onActivityResult method in the fragment from onActivityResult from the LoginActivity. Because it is the fragment who has created and is maintaining the UILifecycleHelper object.
I want to avoid adding this "hack" in the LoginActivity, specially since, there's no way for me to know if the onActivityResult was called as a result of Facebook authentication process.
What's a proper way to achieve this?

A: It looks like they recognized this problem in the new Facebook SDK (v 4.0 onwards) and they now let you register a fragment on the LoginButton.
Following is the code snippet from the official Facebook Login For Android guide.
 // If using in a fragment
    loginButton.setFragment(this);


text:
Q: CSS - flexbox height 100% don't consider children's heights

div.container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

div.container div.block {
  display: flex;
  justify-content: center;
  align-items: center;
}

div.container div.advanced-items {
  display: flex;
  flex-direction: column;
  overflow-y: scroll;
  height: 100%;
}

div.container div.advanced-items span {
  height: 100px;
}

    some data here

    some data here

    1. item
    2. item
    3. item

div.advanced-items height value is setted to 100%, but it somehow equals to whole div.container height. But I need to fill the remaining height of the div.container, considering childrens height.
Please, help me, how to make it?

A: I need to fill the remaining height of the div.container, considering children height.
exactly it's what happened to see how it happened just add border to the div.advanced-items to see how much space it wrapped

div.container {
  display: flex;
  flex-direction: column;
  height: 100%;
  border: 1px solid black;
}

div.container div.block {
  display: flex;
  justify-content: center;
  align-items: center;
}

div.container div.advanced-items {
  display: flex;
  flex-direction: column;
  overflow-y: scroll;
  height: 100%;
  border: 1px solid black;
}

div.container div.advanced-items span {
  height: 100px;
}

    some data here

    some data here

    1. item
    2. item
    3. item

now you the div.advanced-items is wrapping all left height except the one wrapped by the above divs but you can make them share the height of its parent equally by set their height to 100%

div.container {
  display: flex;
  flex-direction: column;
  height: 100%;
  border: 1px solid black;
}

div.container div.block {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  border: 1px solid black;
}

div.container div.advanced-items {
  display: flex;
  flex-direction: column;
  overflow-y: scroll;
  height: 100%;
  border: 1px solid black;
}

div.container div.advanced-items span {
  height: 100px;
}

    some data here

    some data here

    1. item
    2. item
    3. item

A: Do you want like this? :

div.container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

div.container div.block {
  display: flex;
  justify-content: center;
  align-items: center;
}

div.container div.advanced-items {
  display: flex;
  flex-direction: column;
  overflow-y: scroll;
  height: 100%;
}

div.container div.advanced-items span {
  height: calc(100% / var(--item-count));
  min-height : 100px;
}

    some data here

    some data here

    1. item
    2. item
    3. item

Or maybe this? :

div.container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

div.container div.block {
  display: flex;
  justify-content: center;
  align-items: center;
}

div.container div.advanced-items {
  display: flex;
  flex-direction: column;
  justify-content: stretch;
  overflow-y: scroll;
  height: 100%;
}

div.container div.advanced-items span {
  height: 100px;
}

    some data here

    some data here

    1. item
    2. item
    3. item


text:
Q: Linq Expression Could Not Be Translated - DistinctBy Breaking Linq Whenever I run this I get the above error. I am on .NET Core 6 and EF Core.
For some reason I only get the error when the DistinctBy clause is in there.
var notifications = _context.Notifications.Where(x => x.ToUser == user.Id);

if (!getRead)
{
   notifications = notifications
      .Where(x => x.IsRead == false);
}

if (getUnique)
{
   notifications = notifications.DistinctBy(x => x.SuggestionId);
}

return await notifications
   .OrderByDescending(x => x.DateCreated)
   .ToListAsync();

The goal is to get a list of notifications that only show the latest notification about a certain Suggestion. I have tried the GroupBy ... Select way of going about it but that doesnt work either.


text:
Q: Autofac resolve list of Types of registered components Is it possible to register components as a type, and later on get a list of all their types?
Meaning:
public abstract class MyObject
{
    ..
}

public class object1 : MyObject {}
public class object2 : MyObject {}
public class object3 : MyObject {}
public class object4 : MyObject {}

public class Root : IRoot
{
    public Root(IObjectsHolder objectsHolder)
}

public class ObjectsHolder  : IObjectsHolder
{
    // This list should contain: (typeof(object1), typeof(object2))
    public ObjectsHolder(List<Type> AllTypesThatInheritMyObject)
}

builder.RegisterType<object1>().As(context => context.Resolve<IObjectsHolder>().Deserialize<object1>().InstancePerlifetimeScope();
builder.RegisterType<object2>().As(context => context.Resolve<IObjectsHolder>().Deserialize<object2>().InstancePerlifetimeScope();

builder.RegisterType<Root>().As<IRoot>().SingleInstance();
builder.RegisterType<ObjectsHolder>().As<IObjectsHolder>().SingleInstance();

var container builder.Build();

container.Resolve<IRoot>();

I want to register all MyObjects inheritances in a way so that ObjectsHolder will get a list of their types. Is this possible somehow?


text:
Q: Otimização no código PHP PDO olá, estou estudando uma forma de incrementar um valor antes de guardar no banco de dados mas preciso de ajuda, buscando no Google por partes consegui montar o código e sim funciona, objetivo dele é atualizar um valor no banco de dados, mas eu estou achando o código confuso alguém poderia me ajudar?
<?php

try{
$id = 1;

$pdo = new PDO("mysql:host=localhost;dbname=isbn_db", "root", "");

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

//busca no banco de dados
$stmt2 = $pdo->prepare("SELECT * FROM isbn ORDER BY numero_isbn");
$stmt2->execute();

//fecAll busca todos os resultados
$results = $stmt2->fetchALL(PDO::FETCH_ASSOC);
//BUSCA O VALOR NO BANCO DE DADOS
foreach ($results as $value){
    $var = $value['numero_isbn'];
}

//incrementa o valor obtido no banco
$var = $var + 10000000000;

$stmt = $pdo->prepare('UPDATE isbn SET numero_isbn = :numero_isbn WHERE id = :id');
$stmt->execute(array(
    ':id' => $id,
    ':numero_isbn' => $var
));

// echo $stmt->rowCount();

echo "ISBN: ".$var;

}catch(PDOException $e){
    echo 'Error: '. $e->getMessage();
    echo "ERRO";
}

?>

A: Muitos programadores (inclusive eu há alguns anos atrás) faria o seguinte procedimento para somar um valor a uma coluna no banco:

*

*Um Select para obter a quantidade atual

*A adição do valor

*Por último um Update para atualizar coluna

Existe uma forma mais rápida e correta de se fazer este procedimento.

    SET numero_isbn = numero_isbn + :numero_isbn

Otimização do código PHP PDO
$id = 1;
$var=10000000000;

$pdo = new PDO("mysql:host=localhost;dbname=isbn_db", "root", "");

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

stmt = $pdo->prepare('UPDATE isbn SET numero_isbn = numero_isbn + :numero_isbn WHERE id = :id');
$stmt->execute(array(
    ':id' => $id,
    ':numero_isbn' => $var
));


text:
Q: Importing a particular line in Python from a text file I am a newby to Python.
I have a source file which has 10 rows in it.
Using Python I want to import 1 particular line to a new file.
Please let me know how I should proceed with this.

A: You can use linecache if you know the number of line you are after:
import linecache
a_line = linecache.getline('/tmp/file.txt', 4)

# save it to new file
with open('new_file.txt', 'w') as f:
          f.write(a_line)

A: You can write a "for" loop to count line by line, until you're at the line you want. After that, save a copy of that line onto a variable, in this case "stringTemp":
with open("file.txt", "r") as inputStream: # open a file.txt onto a stream variable
stringTemp = ""  # initialize an empty string, where you'll save the line you want
particularLineNumber = 3
count = 0      # a variable to keep count of which line you are on
for line in inputStream:   # "for each thing in the stream variable, save it onto "line"
    if count == particularLineNumber - 1: # if we are on the line we want...
        stringTemp = line                 # ... save it to stringTemp
    count = count + 1         # if we are NOT on the line we want, increase the counter

# ... write the variable stringTemp onto another file ...

I'm assuming you want your line numbers as "1, 2, 3, 4, ... , 9, 10". If you decide to start at 0 ("0,1,2,3...10"), then remove the "- 1" on "if count == particularLineNumber - 1"

A: This will read the whole file at once:
with open(fname) as f:
    content = f.readlines()

With all the lines read, you can do whatever you like with it.
This will read the file one line at a time:
with open(fname) as f:
    for line in f:
        <do something with line>

This has been answered many times, though:
How to read large file, line by line in python
How do I read a file line-by-line into a list?


text:
Q: Can't install tree on cygwin. pwd problem I am trying to install tree 1.8.0 in my cygwin console. To do that, I downloaded the source.
Here is the content of the file
$ ls -lh
итого 185K
-rwxrwx---+ 1 Администраторы place  12K сен 11 19:00 CHANGES
-rwxrwx---+ 1 Администраторы place  17K сен 11 19:00 color.c
drwxrwx---+ 1 Администраторы place    0 сен 11 19:01 doc
-rwxrwx---+ 1 Администраторы place 7,4K сен 11 19:00 file.c
-rwxrwx---+ 1 Администраторы place 3,1K сен 11 19:00 hash.c
-rwxrwx---+ 1 Администраторы place  15K сен 11 19:00 html.c
-rwxrwx---+ 1 Администраторы place  597 сен 11 18:59 INSTALL
-rwxrwx---+ 1 Администраторы place 9,6K сен 11 18:59 json.c
-rwxrwx---+ 1 Администраторы place  18K сен 11 18:58 LICENSE
-rwxrwx---+ 1 Администраторы place 3,0K сен 11 19:04 Makefile
-rwxrwx---+ 1 Администраторы place 5,7K сен 11 18:57 README
-rwxrwx---+ 1 Администраторы place 5,2K сен 11 18:57 strverscmp.c
-rwxrwx---+ 1 Администраторы place 2,4K сен 11 18:56 TODO
-rwxrwx---+ 1 Администраторы place  39K сен 11 18:56 tree.c
-rwxrwx---+ 1 Администраторы place 5,5K сен 11 18:56 tree.h
-rwxrwx---+ 1 Администраторы place 7,5K сен 11 18:56 unix.c
-rwxrwx---+ 1 Администраторы place 8,9K сен 11 18:55 xml.c

but when i run make, i get this:
$ make
makefile:104: target 'strverscmp.o' given more than once in the same rule
gcc -O2 -Wall -fomit-frame-pointer -DCYGWIN -c -o tree.o tree.c
In file included from tree.c:20:
tree.h:34:10: fatal error: pwd.h: No such file or directory
   34 | #include <pwd.h>
      |          ^~~~~~~
compilation terminated.
make: *** [makefile:105: tree.o] Error 1

I have no idea how to fix it, help please

A: You need to install the cygwin-devel package.
$ cygcheck -p usr/include/pwd.h
Found 10 matches for usr/include/pwd.h
...
cygwin-devel-3.1.7-1 - cygwin-devel: Core development files
...

PS: The tree package is already available in Cygwin
https://cygwin.com/packages/summary/tree.html