Q: git push is stuck when pushing to remote When I try to push to a remote repository,
git push origin xyz
it gets stuck. I try ssh -T git@github.com and I get a success:

You've successfully authenticated, but GitHub does not
  provide shell access.

When I use the verbose option, I get a message that it is pushing:
git push -v origin xyz

Pushing to git@github.com:repo.git

and it times out after about 10 minutes with another message:

Connection to github.com closed by remote host.

And I do not get the prompt back in the shell.
I have tried the following but to no avail:

*

*including the --dry-run switch with push results the same.

*git clean -d -f -i followd by git gc --auto
I am on macOS High Sierra and using SSH authentication.

A: It turned out it was stuck due to a pre-push commit hook which was placed there (at <repository-root>/.git/hooks/pre-push) by a third-party tool.
To debug, I ran the command with GIT_TRACE on:
$ GIT_TRACE=1 git push -v origin xyz
11:47:11.950226 git.c:340               trace: built-in: git 'push' '-v' 'origin' ‘xyz’
Pushing to git@github.com:repo.git
11:47:11.951795 run-command.c:626       trace: run_command: 'ssh' 'git@github.com' 'git-receive-pack ‘\’’repo.git'\'''
11:47:13.100323 run-command.c:626       trace: run_command: '.git/hooks/pre-push' 'origin' 'git@repo.git'

Deleting the pre-push file solved the problem.


Q: Call a controller method without loading a blank view I'm trying to call a controller method to delete a record in my database and I am using an actionlink to do this but whenever I hit the delete button, it will delete the record in the database, but it redirects me to a blank page. What I am trying to do is have it not redirect to anything but I can't seem to get that to work.
HTML/Razor
@Html.ActionLink(" ", "DeleteRecord", new { id = item.JPAppId }, new { @class = "fa fa-trash"})

Controller Method
public void DeleteRecord(Guid id)
    {
        JPApplication jPApplication = db.JPApplications.Find(id);
        db.JPApplications.Remove(jPApplication);
        db.SaveChanges();
    }


Q: Multiple VU in Jmeter-Only one user able to insert data Test Plan:-
-User logs in.
-Enter details in a form and save it(Which is stored in DB).
-Logs out.

When ran with 2 Virtual Users :-
-Number Of Threads(users) = 2
-Ramp Up Period = 1
-Loop Count = 1

Only 1 user is able to successfully store the details in DB.
2nd Thread/user give some URLs in response instead of JSON Data.
When one thread is used and the script is run many times, it is successfully storing data in DB.
Elements used in the Test Plan:-
-HTTP Cookie Manager

-View Result Tree

Am I missing some elements ?
What mistake I am doing ?

A: I suppose you are replaying the recorded plan for 1 user.
Most probably your issue is due to not variabilizing (Regexp Post-Processor or CSS/Jquery Post Processor to extract and variable to inject) some dynamic data that is needed for the additionnal users.
So when you put 1, it works because IDs correspond to recorded user, but when you put more, at some step you have the second users using the IDs of the first one.
Google "correlation with jmeter" to understand and fix your issue.

A: In case you have the correct script then check the business of your application. As I have experienced some applications don't allow many users submit the form at the same time. It will lock the form for the first user and the second user cannot submit, the second user will receive the response data with messages like "This form is being used by another user..." or "The data on this form is out of date, please refresh...". In that case, I use a Logic Controller, called "Critical Section Controller". It will handle the users to make sure the transaction will be executed by only one user at a time.


Q: Migrate pinnacle cart customers data to magento1.x version I came back on stackoverflow after long time.I really need a help in migrating the pinnacle cart to magento1.x.I am migrating the customer data but I want customer can login in magento site with same credentials without reset the password.
Is it possible that customer can use the same credentials of pinnacle cart to Magento after migration.
any quick help will be appreciated.


Q: Get distinct pattern match results (substrings) from PyMongo What is the most efficient way to query a MongoDB collection for unique/distinct substrings in a given field?
Example documents:
{"_id": "1234.abc.test1", "some_key": "some_value"}
{"_id": "1234.abc.test2", "some_key": "some_value"}
{"_id": "0420.def.test3", "some_key": "some_value"}

The document IDs above follow an internal namespacing convention. I need to know what all of the distinct first elements of that namespacing are.
The desired output of the query on the above collection:
1234
0420

I am trying to avoid getting the entire dataset back only to do row['_id'].split('.')[0] on each row afterwards. Ideally, the query should return only the distinct list of those substrings.

A: The idea is actually the same as yours(i.e. splitting by . and get the first element), then $group them to get distinct records.
db.collection.aggregate([
  {
    $project: {
      first: {
        "$arrayElemAt": [
          {
            "$split": [
              "$_id",
              "."
            ]
          },
          0
        ]
      }
    }
  },
  {
    "$group": {
      "_id": "$first"
    }
  }
])

Here is the Mongo playground for your reference.
Here is the PyMongo implementation of the above query:
pipeline = [
    {"$project": {"first": {"$arrayElemAt": [{"$split": ["$_id", "."]}, 0]}}},
    {"$group": {"_id": "$first"}}
]
result = self.collection.aggregate(pipeline=pipeline, allowDiskUse=False)


Q: ajax get image from folder debug   function ajax_json(folder){
      var thumbnailbox = $('#thumbnailbox');
      $.ajax({
        url:"json_data.php",
        dataType:"json",
        type:"POST",
        data: {folder: JSON.stringify(folder)},
        contentType: "application/json; charset=utf-8",
        success:function(d){
          var temp = '';
            for (var o in d) {
                 if (d.hasOwnProperty(o) && d[o].hasOwnProperty('src') && d[o].src !== '') {
                     //create image
                     temp += "

";
                 }
            }
          }, error: function (jqXHR, textStatus, errorThrown){
            console.log("textStatus = " + textStatus + "\terrorThrown = " + errorThrown);
            alert(XMLHttpRequest.status);
            alert(XMLHttpRequest.readyState);
            alert(textStatus);
        }
      });
    }

php
<?php
header("Content-Type: application/json");
$folder = $_POST["folder"];
$jsonData = '{';
$dir = $folder."/";
$dirHandle = opendir($dir);
$i = 0;
while ($file = readdir($dirHandle)) {
    if(!is_dir($file) && preg_match("/.jpg|.gif|.png/i", $file)){
        $i++;
        $src = "$dir$file";
$jsonData .= '"img'.$i.'":{ "num":"'.$i.'","src":"'.$src.'", "name":"'.$file.'" },';
    }
}
closedir($dirHandle);
$jsonData = chop($jsonData, ",");
$jsonData .= '}';
echo $jsonData;
?>

error
textStatus = parsererror    errorThrown = SyntaxError: Unexpected token <

my intention is the get image from my folder using ajax ,it got error and i cant find what i am missing to have error , can anyone help me take a look? i cant debug it.


Q: Get Index of a Set in Swift let setOfStrings: Set<String> = ["ONE", "TWO", "THREE"];

It doesn't behave like and array, so setOfStrings[0] does not work.
Any ideas?

A: You might want to access the first element of the set as follows:
if let first = setOfStrings.first {
    print(first)
}

Assuming that you are already familiar with: Set is unordered data structure, i.e: first value is not guaranteed to be "ONE".
You cannot access an element in a set via index as an integer (setOfStrings[0]), however, since Set represents a Collection (adopted by sets), SetIndex is probably what are you looking for, by using Set.Index of your current set, as follows:
let setOfStrings: Set<String> = ["ONE", "TWO", "THREE"]
// for me, it sorted as: {"THREE", "TWO", "ONE"}

let mySetIndex = setOfStrings.index(setOfStrings.startIndex, offsetBy: 1)

let secondElemnet = setOfStrings[mySetIndex] // "TWO"

Note that:

*

*By using subscript(_:), you should be able to get e specific element.

*index(_:offsetBy:):

Returns an index that is the specified distance from the given index.

*

*mySetIndex data type is SetIndex<String>.


Q: How to build server streaming via grpc and nest.js? Need to create some "channel" to which the client can subscribe and periodically receive messages.
Within the current technology stack, I'm trying to organize something like this:
proto file:
syntax = "proto3";

package testtime;

service TimeService {
    rpc GetTimeStream(Empty) returns (stream TimeStreamResponse);
}

message Empty {
}

message TimeStreamResponse {
    string result = 1;
}

controller:
import { Controller } from '@nestjs/common';
import { GrpcMethod } from '@nestjs/microservices';
import moment from 'moment';
import { Observable, Subject } from 'rxjs';

const timeSubject = new Subject<{ result: string }>();
setInterval(() => {
    const result = moment().format('hh:mm');
    timeSubject.next({ result });
}, 5000);

@Controller()
export class TestTimeController {
    @GrpcMethod('testtime.TimeService', 'GetTimeStream')
    public getTimeStream(): Observable<{ result: string }> {
        return timeSubject.asObservable();
    }
}

when I try to call the method, I get an error:
/project/node_modules/@nestjs/microservices/server/server-grpc.js:141
             this.transformToObservable(await handler).subscribe(data => callback(null, data), (err) => callback(err));
                                                                         ^
 TypeError: callback is not a function
     at SafeSubscriber._next (/project/node_modules/@nestjs/microservices/server/server-grpc.js:141:73)
     at SafeSubscriber.__tryOrUnsub (/project/node_modules/rxjs/src/internal/Subscriber.ts:265:10)
     at SafeSubscriber.next (/project/node_modules/rxjs/src/internal/Subscriber.ts:207:14)
     at Subscriber._next (/project/node_modules/rxjs/src/internal/Subscriber.ts:139:22)
     at Subscriber.next (/project/node_modules/rxjs/src/internal/Subscriber.ts:99:12)
     at CatchSubscriber.Subscriber._next (/project/node_modules/rxjs/src/internal/Subscriber.ts:139:22)
     at CatchSubscriber.Subscriber.next (/project/node_modules/rxjs/src/internal/Subscriber.ts:99:12)
     at TapSubscriber._next (/project/node_modules/rxjs/src/internal/operators/tap.ts:125:22)
     at TapSubscriber.Subscriber.next (/project/node_modules/rxjs/src/internal/Subscriber.ts:99:12)
     at MergeMapSubscriber.notifyNext (/project/node_modules/rxjs/src/internal/operators/mergeMap.ts:162:22)
     at SimpleInnerSubscriber._next (/project/node_modules/rxjs/src/internal/innerSubscribe.ts:30:17)
     at SimpleInnerSubscriber.Subscriber.next (/project/node_modules/rxjs/src/internal/Subscriber.ts:99:12)
     at MergeMapSubscriber.notifyNext (/project/node_modules/rxjs/src/internal/operators/mergeMap.ts:162:22)
     at SimpleInnerSubscriber._next (/project/node_modules/rxjs/src/internal/innerSubscribe.ts:30:17)
     at SimpleInnerSubscriber.Subscriber.next (/project/node_modules/rxjs/src/internal/Subscriber.ts:99:12)
     at SwitchMapSubscriber.notifyNext (/project/node_modules/rxjs/src/internal/operators/switchMap.ts:166:24)

What am I doing wrong?


Q: Azure function app, service bus and return service bus I have an azure function with a service bus input attribute and service bus output attribute set.
This means that whatever I return from this function will be returned to the ‘return’ queue.
However,  i want to manually handle some messages as there is no point retrying them I just want to put them straight on the LDQ and carry on.
So i added MessageReceiver as a parameter with lockToken.
All good.
But now, if i handle the message and send to DLQ i have no way ending the function execution gracefully as it is expecting a return.  So i throw an exception.  But now i have numerous error logs in the output like ‘lock is invalid’.
I tried to set autocomplete to false but then i have a different issue; how do i ensure i can return the message AND log it in a transaction and handle rollback?
Any guidance??
Example:
  public static class Function1
    {
        [FunctionName("Function1")]
        [return: ServiceBus("returnQueueName", Connection = "myConnectionString")]
        public static async System.Threading.Tasks.Task<ReturnMessage> RunAsync([ServiceBusTrigger("mytopic", "mysubscription", Connection = "myConnectionString")]
        string mySbMsg, ILogger log,
            MessageReceiver messageReceiver, string lockToken)
        {
            log.LogInformation($"C# ServiceBus topic trigger function processed message: {mySbMsg}");

            await messageReceiver.DeadLetterAsync(lockToken);

            return new ReturnMessage();
        }
    }

    public class ReturnMessage
    {
        public string Payload { get; set; }
    }

Hopefully you can see that the input queue and output queue are handled by the hosting system - Azure.  I like this because it will look after atomcity for me.
But if I include the line:
await messageReceiver.DeadLetterAsync(lockToken);

This will move the current message to the DLQ.
GREAT!!! That's what I want.
But I am now forced to return something OR throw an exception.  Is there any way out of this as seeing the error messages is misleading as there is no error to follow.

A: As far as I can see it appears that you shouldn't use an automatic return service bus binding.  Instead, you should manually connect to the return topic/queue and handle the message logistics manually.


Q: objective-C - other methods to convert a float to string I know that you can convert a float into a string using
NSString *myString = [NSString stringWithFormat:@"%f", myFloat];

My question is what OTHER methods exist in Objective-C that can do that same?
thanks.

A: You can create your own category method.  Something like
@interface NSString (Utilities)

+ (NSString *)stringWithFloat:(CGFloat)float

@end

@implementation NSString (Utilities)

+ (NSString *)stringWithFloat:(CGFloat)float
{
    NSString *string = [NSString stringWithFormat:@"%f", float];
    return string;
}

@end

Edit
Changed this to a class method and also changed the type from float to CGFloat.
You can use it as:
NSString *myFloat = [NSString stringWithFloat:2.1f];

A: You could use NSNumber
NSString *myString = [[NSNumber numberWithFloat:myFloat] stringValue];

But there's no problem doing it the way you are, in fact the way you have in your question is better.

A: float someVal = 22.3422f;
NSNumber* value = [NSNumber numberWithFloat:someVal];
NSLog(@"%@",[value stringValue]);

A: in a simple way
NSString *floatString = @(myFloat).stringValue;


Q: How to change layers in pretrained model in Mxnet I have a pre-trained Mxnet model. I need to change last two layers and add new two layers for testing. Basically, I need to create a probability map of the image.
How can i do that ?

A: There is a tutorial on fine-tuning with MXNet. Did you check this out?
http://mxnet.incubator.apache.org/faq/finetune.html


Q: Determining the execution time of all statements in process of FPGA I'm beginner studying FPGA. I'm confusing a problem.
I have code and the data type I use is fixed-point:
process(clk)
  begin
   if(clk'EVENT and clk ='1') then
      r_amp := to_sfixed (amp,amp'HIGH,amp'LOW);
    r_Va  := resize (r_amp * to_sfixed(Va,0,-31),r_Va);
    r_Vb  := resize (r_amp * to_sfixed(Vb,0,-31),r_Vb);
    r_Vc  := resize (r_amp * to_sfixed(Vc,0,-31),r_Vc);
    V_alpha := resize(r_Va/(to_sfixed (2/3,4,-27)*Udc),V_alpha);
    V_beta  := resize(to_sfixed(0.57735026919,4,-27)*(r_Vb-r_Vc)/(to_sfixed (2/3,4,-27)*Udc),V_beta);
    tmp := resize(to_sfixed(0.57735026919,4,-27)*V_beta,tmp);
    z1x := resize(V_alpha - tmp,z1x);
    z1y := resize(to_sfixed (2,4,-27)*tmp,z1y);
    z2x := resize(z1x+z1y,z2x);
    z2y := resize(to_sfixed (-1,4,-27)*z1x,z2y);
    z3x := resize(z1y,z3x);
    z3y := resize(to_sfixed (-1,4,-27),z3y);
   end if;
   end process;

How to caculate the execution time of all statements in process? if all statements don't finish in 1 clock period, what will happen?
Thank for watching.

A: You define the clock period in ns and the synt/PR-tools tries to place the logic so this time constraint is fulfilled. If it fails you will get a timing error.
If it is not finished within 1 clk the result is undefined.


Q: How to make separate REST controllers for nested resources? Spring Boot I have a REST controller. It processes the resource "messages". And each message can contain comments inside itself.
/api/v1/messages/1
/api/v1/messages/2

/api/v1/messages/1/comments/1
/api/v1/messages/1/comments/2

Here is a code:
@RestController
@RequestMapping("/api/v1/messages/")
public class RestControllerV1 {

    @RequestMapping(value = "{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<Message> getMessage(@PathVariable("id") Long messageId) {

    }

    @RequestMapping(value = "{messageId}/comments/{commentId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<Comment> getComment(@PathVariable("messageId") Long messageId, @PathVariable("commentId") Long commentId) {

    }
}

It works fine.
But I think that it is not very good to have one big controller for two resources. So I want different controllers (SOLID, S-principle).
MessageControllerV1

and
CommentControllerV1

Is it possible to divide controllers in Spring Boot application?

A: You could have something like:
@RestController
@RequestMapping("/api/v1/messages")
public class MessageController {

    @RequestMapping(value = "{messageId}",
                    method = RequestMethod.GET,
                    produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<Message> getMessage(@PathVariable("messageId") Long messageId) {
        ...
    }
}

@RestController
@RequestMapping("/api/v1/messages/{messageId}/comments")
public class CommentController {

    @RequestMapping(value = "{commentId}",
                    method = RequestMethod.GET,
                    produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<Comment> getComment(@PathVariable("messageId") Long messageId,
                                              @PathVariable("commentId") Long commentId) {
        ...
    }
}


Q: I need some help detecting if a browser has access to the internet
Possible Duplicate:
Check if Internet Connection Exists with Javascript?

I have been working on a manual to be sent via CD to a customer.  The owner of my company requires that the manual be split into many subsections as .doc and .docx files.  The table of contents for this manual will be an HTML page, to be run by autorun when the CD is put into the computer.
I can be fairly sure that the computer is a windows computer, but that's about it.  My current thinking is to use this script to take advantage of google to display the word file, but only if the computer is actually connected to the internet.  That way I don't have to rely on the customer having a particular version of word (or having a compatibility pack installed).
From the research I've done, relying on a computer to correctly recognize that a link to a word document should be opened with word is problematic, and has to be resolved at the user end.

A: Have a look at window.navigator.onLine

A: You could try an ajax request to a reliable site.
// THIS IS OUR PAGE LOADER EVENT!
window.onload = function() {
    testConnection();
};

function testConnection(){
    var xmlhttp;

    if (window.XMLHttpRequest){
        xmlhttp=new XMLHttpRequest();
    } else {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200){
            alert(xmlhttp.responseText);
        } else if (xmlhttp.readyState==4){
            alert("NO INTERNET DETECTED!");
        }
    }

    xmlhttp.open("GET","http://www.w3schools.com/ajax/ajax_info.txt",true);
    xmlhttp.send();
}

Now you will have to play around with it for a way to use the response because it is asynchronous, but this will work to test a connection.

A: Previously discussed here: Check if Internet Connection Exists with Javascript? and here: How to know if the network is (dis)connected?.

A: GM_xmlhttpRequest({
  method: "GET",
  url: "http://www.google.com/",
  onload: function(response) {
    if(response.responseText != null) {
       alert("OK");
    } else {
      alert("not connected");
    }
  }
});

*

*second alternative
var HaveConnection = navigator.onLine;


Q: laravel artisan error while clearing config cache when I run php artisan cache:config the command throw the following error
PHP Warning:  require(): Filename cannot be empty in /home/****/public_html/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/LoadConfiguration.php on line 71
PHP Fatal error:  require(): Failed opening required '' (include_path='.:/usr/share/php') in /home/****/public_html/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/LoadConfiguration.php on line 71

I have no idea what causing this and how to fix it.

A: it turns out that there is one suspicious file inside config folder, once it's deleted the artisan command works just fine again.


Q: Select two columns from the sqlite which got unique column and ordered by Date, Time I have two tables which got same columns, examples
TableA

ID, Image, Date ,  Time
0 , 0    , 12/03,  12:33
0 , 1    , 12/03,  12:34
1 , 2    , 12/03,  12:34
1 , 3    , 12/03,  12:35

TableB

ID, Image, Date ,  Time
0 , 4    , 12/03,  12:33
0 , 5    , 12/03,  12:35
2 , 6    , 12/03,  12:34
2 , 7    , 12/03,  12:35

The results I need are
ID, Image, Date ,  Time
0 , 5    , 12/03,  12:35
1 , 3    , 12/03,  12:35
2 , 7    , 12/03,  12:35

This is easy to be done if it was one table
SELECT DISTINCT ID, Image FROM TableA GROUP BY ID ORDER BY Date DESC, Time DESC LIMIT 5

But how could I select from two tables?

A: You can use union all.  This returns the most recent image from the two tables combined for each id:
with ab as (
      select a.* from TableA a union all
      select b.* from TableB b
     )
SELECT ID, Image
FROM (SELECT ab.*,
             ROW_NUMBER() OVER (PARTITION BY id ORDER BY DATE DESC, TIME DESC) as seqnum
      FROM ab
     ) ab
WHERE seqnum = 1;
ORDER BY Date DESC, Time DESC
LIMIT 5;

A: If what you need is the rows with the latest date and time (as your expected results):
with cte as (
  select * from Tablea
  union all
  select * from Tableb
)
select * from cte
where Date || Time = (select max(Date || Time) from cte)
order by id

I assume the dates are always in the format MM/YY and the times hh:mm.
See the demo.
Results:
| ID  | Image | Date  | Time  |
| --- | ----- | ----- | ----- |
| 0   | 5     | 12/03 | 12:35 |
| 1   | 3     | 12/03 | 12:35 |
| 2   | 7     | 12/03 | 12:35 |


Q: pip and multiple python version issues in ubuntu 16.04 I'm deploying a flask server with gulp, and after the gulp command is launched, everything goes fine until the following line:
import flask

as I get the error
ImportError: No module named flask

. Adding the lines before the import command
import sys
print(sys.executable)

I get printed
/usr/bin/python

which, launched on console, corresponds to a python 2.7.12 interpreter, and the command 'import flask' within the console doesn't give any error!!
I can find many python interpreters (2, 3 and virtenvs on my machine) but it seems each of them has flask installed.


Q: take minimum between column value and constant global value I would like create new column for given dataframe where I calculate minimum between the column value and some global value (in this example 7). so my df has the columns session and note and my desired output column is minValue :
session     note     minValue
1       0.726841     0.726841
2       3.163402     3.163402
3       2.844161     2.844161
4       NaN          NaN

I'm using the built in Python method min :
df['minValue']=min(7, df['note'])

and I have this error:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

A: Use np.minimum:
In [341]:
df['MinNote'] = np.minimum(1,df['note'])
df

Out[341]:
   session      note  minValue   MinNote
0        1  0.726841  0.726841  0.726841
1        2  3.163402  3.163402  1.000000
2        3  2.844161  2.844161  1.000000
3        4       NaN       NaN       NaN

Also min doesn't understand array-like comparisons hence your error

A: The preferred way to do this in pandas is to use the Series.clip() method.
In your example:
import pandas

df = pandas.DataFrame({'session': [1, 2, 3, 4],
                       'note': [0.726841, 3.163402, 2.844161, float('NaN')]})

df['minVaue'] = df['note'].clip(upper=1.)
df

Will return:
       note  session   minVaue
0  0.726841        1  0.726841
1  3.163402        2  1.000000
2  2.844161        3  1.000000
3       NaN        4       NaN

numpy.minimum will also work, but .clip() has some advantages:

*

*It is more readable

*You can apply simultaneously lower and upper bounds: df['note'].clip(lower=0., upper=10.)

*You can pipe it with other methods: df['note'].abs().clip(upper=1.).round()


Q: Is there a development environment 'checklist' I can run through before starting to code? I am following Michael Hartl's Rails Tutorial, and have gone through setting up my Development Environment.
I want to quickly check I have everything in order i.e. RVM, Ruby, Rails, Git, etc. all installed in the right place and correctly configured.
If you were picking up a beginner's computer and wanted to understand their development environment and spot anything missing (before running into errors later on), is there a hygiene checklist you go through?
How can I do this?
Thank you!

A: Michael hartls tutorial explains well what you need, but for a short list:

Curl

is needed to get RVM and to test HTTP requests. You will need it to install some requirements also.

Git:

You need it during the tutorial, and to get some gems directly from github.

Any JS platform:

I've choosen NODEJS because it's the easiest one to install, but you can use any of your like: rubyracer, v8...

Ruby interpreter:

Then Install a ruby version. I've always install the last one as default and then install the ones needed in the project.
The gems:

If you are using Ruby > 2.0 install byebug if not install debugger. And rails, the last version as well. If you are following a tutorial install other version.
Any editor:
If you want to learn I recommend you VIM, as you will get used to develop and will learn a nice editor. Learning a nice command line editor is allways payed. So don't be afraid. You can learn sublime or gedit at any moment, but learning VIM is hardest, so start now.
Then databases.

Install whichever you want:
MySQL.
PostgreSQL
SQlite
Or mongo, just to practice.

that should be enough to start the tutorial.


Q: How do I use jQuery sortable for elements in a specific table column only? I am trying to use jQuery's draggable and sortable to sort elements listed inside of a specific column of a table.
The reason is that I essentially want to fit people into timeslots.
I have a table as such:

    1:00 PM

Person 1

    2:00 PM

Person 2

    3:00 PM

Person 3

    4:00 PM

Person 4

I want to make all the divs with the class 'personSortable' sortable into the avaliable time slots. I have looked for an answer but the closest thing i could find was to make the entire row sortable (by making the table the sortable container) - which is not ideal because I can't have the time slots change.
Another idea I had was to create two div wrappers: one with the time slots, and one containing sortable divs for the people, and using the CSS 'float' property to have them line up. Would that be a more ideal approach?

A: Found this and it seems to do the trick if anyone else was interested:
http://www.redips.net/javascript/drag-and-drop-table-content/


Q: How to send any structure as parameter to a method and return the structure? I'm new to Go and I'm seeing if there's a way to have a method that receives any structure as parameter.
I have something like this in my code that is a function that does exactly the same for 5 structures and returns the same structure,  but I don't know if I can do that. I'm wondering if I can do something like this:
type Car struct {
     Model   string `yaml:"Model"`
     Color   string `yaml:"Color"`
     Wheels  int    `yaml:Wheels"`
     Windows int    `yaml:"Windows"`
}

type Motorcycle struct {
     Model    string `yaml:"Model"`
     Color    string `yaml:"Color"`
     Wheels   int      `yaml:Wheels"`
}

type Bus struct {
     Model      string `yaml:"Model"`
     Color      string `yaml:"Color"`
     Wheels     int    `yaml:Wheels"`
     Passengers int    `yaml:"Passengers"`
}

func main () {

    car := GetYamlData(Car)
    motorcycle := GetYamlData(Motorcycle)
    Bus := GetYamlData(Bus)
}

func GetYamlData(struct anyStructure) (ReturnAnyStruct struct){

       yaml.Unmarshal(yamlFile, &anyStructure)

       return anyStructure
}

Is possible to do something like the code above? Actually what I have is something like this:
func main(){
   car, _, _ := GetYamlData("car")
    _,motorcycle,_ := GetYamlData("motorcycle")
    _,_,bus := GetYamlData("bus")
 }

func GetYamlData(structureType string) (car *Car, motorcycle *Motorcycle, bus *Bus){

 switch structureType{

        case "car":
                yaml.Unmarshal(Filepath, car)
        case "motorcycle":
                yaml.Unmarshal(Filepath, motorcycle)
        case "bus":
                yaml.Unmarshal(Filepath, bus)
 }

 return car, motorcycle, bus

}

With the time this will be increasing and it will return a lot of values and I don't want a lot of return values, is there a way to do it with the first code that I posted?

A: You can do it the exact same way yaml.Unmarshal does it, by taking in a value to unmarshal into:
func GetYamlData(i interface{}) {
    yaml.Unmarshal(Filepath, i)
}

Example usage:
func main () {
    var car Car
    var motorcycle Motorcycle
    var bus Bus
    GetYamlData(&car)
    GetYamlData(&motorcycle)
    GetYamlData(&bus)
}


Q: PHP/MYSQL query ranking using secondary tables Working with a ranking algorithm, but I'm getting frustrated with the multiple database calls and data gyrations i'm having to go through to calculate the rank of a specific item, output it in to an array, and then sort by the rank value. Is it possible in MySQL to calculate the rank of a given row based on the data found in other tables?
SELECT key_value FROM table;

Now with the result set I need to rank each item based on various other tables information about those items. So if the output was -
|key_value|
|abcd1    |
|abcd2    |
|abcd3    |

Then based on 'abcd1' values in 3 other tables, I need to rank each entry based on the value divided by total and return the rank and then output it. Is there a way to do all this in a single SQL statement? I've thought about setting up some sql variables and storing different calls and then doing the calculation, but I'm still not sure how you would assign that to the SELECT statements output and rank it accordingly. I'm good with PHP, but i'm kind of a MySQL n00b.
This is probably confusing the way I'm describing it - I can answer more questions to help better explain what I'm trying to do.
Basically each row returned in the original statement is really only relevant to each user based on information stored about that object in 3 other tables. Need to know the best way to use the data in the 3 other tables to rank the relevancy of the data from the first table.

A: The key here is that you need to JOIN your other tables, then ORDER BY some expression on their fields.
SELECT key_value
FROM table
LEFT JOIN table_b on table_b.field = table.key_value
LEFT JOIN table_c on table_c.field = table.key_value
LEFT JOIN table_d on table_d.field = table.key_value
ORDER BY table_b.some_field DESC, (table_c.another_field / table_d.something_else) ASC
;

Depending on the join conditions, you may need to GROUP BY table.key_value or even use subqueries to attain the appropriate effect.


Q: Keras custom loss function causes TypeError
*

*Why when I am trying to create my own loss function using Keras backend

def my_loss(y_true, y_pred):
    return K.mean(K.max(y_true, y_pred) / K.min(y_true, y_pred))

and pass to the Keras neural network, I get
TypeError: Value passed to parameter 'reduction_indices' has DataType float32 not in list of allowed values: int32, int64

*As far as I know, we should use Keras backend functions in custom loss because keras have to differentiate the loss function, but how do they differentiate Max and Min functions that have no derivative?


Q: Iterate over a directory and filter results based on file extensions I have a function that cycles through a directory and, for each folder within that directory, returns the most recent file. The problem is that the folders contain files of different formats, such as .xlsx and .csv. The file extensions may change per request, so I need to pass them as a parameter to the function, instead of hard-coding the values. How can I pass a list of file extensions as a parameter and select the file according to its extension? Here's what I'm trying to do:
  var extensions = new string[] { ".xlsx", ".csv" };
  var filename = FileSystemService.GetRecentFile(path,  extensions.ToList<string>);

A: If you need the most recent file having one of the extensions required, then this could be a solution:
public FileInfo GetRecent(string path, params string[] extensions)
{
    var list = new List<FileInfo>();

    // Getting all files having required extensions
    // Note that extension is case insensitive with this code
    foreach (var ext in extensions)
        list.AddRange(
          new DirectoryInfo(path)
            .EnumerateFiles("*" + ext, SearchOption.AllDirectories)
            .Where(p =>
              p.Extension.Equals(ext,StringComparison.CurrentCultureIgnoreCase))
              .ToArray());

    return list.Any()
        // If list has somm file then return the newest one
        ? list.OrderByDescending(i => i.LastWriteTime)
              .FirstOrDefault()
        // else return what you please, it could be null
        : null;
}

If you need the most recent file for each extension, then this could be a solution:
public Dictionary<string, FileInfo> GetRecents(string path, params string[] extensions)
{
    var ret = new Dictionary<string, FileInfo>();

    // Getting all files having required extensions
    // Note that extension is case insensitive with this code
    foreach (var ext in extensions)
    {
        var files = new DirectoryInfo(path)
            .EnumerateFiles("*" + ext, SearchOption.AllDirectories)
            .Where(p =>
                p.Extension.Equals(ext, StringComparison.CurrentCultureIgnoreCase))
            .ToArray();

        ret.Add(ext, files.Any()
        ? files.OrderByDescending(i => i.LastWriteTime).FirstOrDefault()
        : null);
    }

    return ret;
}

A: You could first enumerate the Sub-Directories in the provided path, using Directory.EnumerateDirectories. This enumeration excludes the root, so we can add it back to the Enumerable, if required, using the Prepend()1 or Append()1 methods.
Then iterate the collection of extensions, call DirectoryInfo.EnumerateFiles to get Date/Time information about the files in each Directory and filter using the FileInfo.LastWriteTime value and finally order by the most recent and yield return the first result.
I've used a public methods that calls a private worker method, so the public method can be used to provide some more filters or it could be more easily overloaded. Here it's used to provide an option to return the most recent file of all.
It can be called as:
string[] extensions = { ".png", ".jpg", "*.txt" };
var mostRecentFiles = GetMostRecentFilesByExtension(@"[RootPath]", extensions, false);

Specify false to get all the files by type and directory, or true to get the most recent file among all files that matched the criteria.
public IEnumerable<FileInfo> GetMostRecentFilesByExtension(string path, IEnumerable<string> extensions, bool returnSingle)
{
    var mostRecent = MostRecentFileByExtension(path, extensions).Where(fi => fi != null);
    if (returnSingle) {
        return mostRecent.OrderByDescending(fi => fi.LastWriteTime).Take(1);
    }
    else {
        return mostRecent;
    }
}

private IEnumerable<FileInfo> MostRecentFileByExtension(string path, IEnumerable<string> exts)
{
    foreach (string dir in Directory.EnumerateDirectories(path, "*", SearchOption.AllDirectories).Prepend(path))
    foreach (string ext in exts) {
        yield return new DirectoryInfo(dir)
                        .EnumerateFiles($"*{ext}")
                        .Where(fi => fi.Extension.Equals(ext, StringComparison.InvariantCultureIgnoreCase))
                        .OrderByDescending(fi => fi.LastWriteTime).FirstOrDefault();
    }
}

(1) Both Prepend() and Append() require .Net Framework 4.7.1.
  Core/Standard Frameworks all have them.


Q: Where should I cp oc binary to on MacOS? In this documentation it says

unpack the archive and move the oc binary to a directory on your PATH

I tried echo $PATH and it returns:

bin:/Library/Frameworks/Python.framework/Versions/3.4/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin

Clearly there are multiple path here, which one should I move cp oc binary to?

A: /usr/local/bin would be the usual choice for user or third-party executables. That way it won't get wiped out when you update the OS.
See also: Where do you keep your own scripts on OSX? - the question is about scripts rather than binaries, but the same logic applies.


Q: in iOS7 how do you stop the First viewcontroller autorotating? I have an app that just needs one screen to autorotate, the first and last screens should be portrait. I can get the last screen to stop rotating using:
- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

But this does not work on the first screen, I am using a storyboard with a UINavigationController (I'm thinking that may have something to do with it?)
Any help would be gratefully received. Thanks

A: you may need to subset the UINavigationController and you should use it instead of the standard UINavigationController.
I have done this in my projects, so this cares of the individual UIViewController classes' custom orientations:
.h
#import <UIKit/UIKit.h>

@interface UIOrientationController : UINavigationController { }
@end

.m
@implementation UIOrientationController

- (BOOL)shouldAutorotate {
    return [self.topViewController shouldAutorotate];
}

- (NSUInteger)supportedInterfaceOrientations {
    return [self.topViewController supportedInterfaceOrientations];
}

@end

NOTE: you can extended this class with overriding more methods, if it becomes a requirement in your final code.


Q: Get a clean extract from Wikipedia page I am currently exploring the Wikipedia API and am trying to understand it a bit more.
So I am starting with a Wikidata ID and can find my Wikipedia Title there. I extract the title and am then able to query Wikipedia like e.g. so:
https://en.wikipedia.org/w/api.php?action=query&format=json&titles=Los_Angeles&prop=extracts&exsentences=2&explaintext&exintro

The result would be something like the following:

Los Angeles (US:  (listen) lawss AN-jəl-əs; Tongva: Tovaangar; Spanish: Los Ángeles; Spanish for "The Angels"), often spoken and written as its initialism, L.A., is the largest city in California. With a 2020 population of 3,898,747, it is the second-largest city in the United States, after New York City, and the third-largest city in North America, after Mexico City and New York City.

That way I get the extract as a plain string. Good! The problem is, that it still contains "links" or "strange things", because some links/infos are removed. E.g. the pronunciation of the text ist now gone but the link to (listen) to it is still there as plain text.
I would like to display the text of the page in an iOS App as plain text somehow. Is there a way to get that from the wikipedia API or will I have to do my own magic?


Q: Nested Json using retrofit i want to read sub_category > id, name from json using retrofit
But below code give failed response.

java.lang.IllegalStateException: Expected BEGIN_OBJECT but was
  BEGIN_ARRAY at line 2 column 2 path $

My Json....
[
{
    "id": "1",
    "name": "Invamore",
    "sub_category": [
        {
            "id": "101",
            "name": "Banner"
        },
        {
            "id": "102",
            "name": "3 sided Dangler"
        },
        {
            "id": "103",
            "name": "Leaflet"
        }
    ]
},
{
    "id": "2",
    "name": "HUPS",
    "sub_category": [
        {
            "id": "103",
            "name": "Leaflet"
        },
        {
            "id": "104",
            "name": "Posters"
        },
        {
            "id": "105",
            "name": "Sunpack"
        }
    ]
},
{
    "id": "3",
    "name": "Xplore",
    "sub_category": [
        {
            "id": "101",
            "name": "Banner"
        },
        {
            "id": "103",
            "name": "Leaflet"
        },
        {
            "id": "106",
            "name": "Dangler"
        },
        {
            "id": "107",
            "name": "Vertical Streamer"
        }
    ]
},
{
    "id": "4",
    "name": "Xpress",
    "sub_category": [
        {
            "id": "101",
            "name": "Banner"
        },
        {
            "id": "103",
            "name": "Leaflet"
        },
        {
            "id": "108",
            "name": "Streamer"
        }
    ]
},
{
    "id": "5",
    "name": "Matrix",
    "sub_category": [
        {
            "id": "103",
            "name": "Leaflet"
        }
    ]
},
{
    "id": "6",
    "name": "Instabrite",
    "sub_category": [
        {
            "id": "103",
            "name": "Leaflet"
        }
    ]
},
{
    "id": "7",
    "name": "Mileage",
    "sub_category": [
        {
            "id": "107",
            "name": "Vertical Streamer"
        }
    ]
},
{
    "id": "8",
    "name": "Onam Posm",
    "sub_category": [
        {
            "id": "101",
            "name": "Banner"
        },
        {
            "id": "106",
            "name": "Dangler"
        }
    ]
}]

Backend.java
public void pos_func(String user_id) {

    ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);

    Call call = apiService.POS_MODEL_CALL(user_id);
    call.enqueue(new Callback() {
        @Override
        public void onResponse(Call call, Response response) {

        }

        @Override
        public void onFailure(Call call, Throwable t) {
            Log.d("sk_log", "Failed! Error = " + t.getMessage());

        }
    });

}

ApiInterface.java
 @FormUrlEncoded
@POST("pos_distributed.php")
Call<ValuesPos> POS_MODEL_CALL(@Field("user_id") String user_id);

Model : from pojoschema2pojo.com for above JSON
ValuesPos.java
package com.example.shkhan.myapp.model;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by shkhan on 14/11/16.
 */
public class ValuesPos {
    @SerializedName("id")
    @Expose
    public String id;
    @SerializedName("name")
    @Expose
    public String name;
    @SerializedName("sub_category")
    @Expose
    public List<SubCategory> subCategory = new ArrayList<SubCategory>();

    /**
     *
     * @return
     * The id
     */
    public String getId() {
        return id;
    }

    /**
     *
     * @param id
     * The id
     */
    public void setId(String id) {
        this.id = id;
    }

    /**
     *
     * @return
     * The name
     */
    public String getName() {
        return name;
    }

    /**
     *
     * @param name
     * The name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     *
     * @return
     * The subCategory
     */
    public List<SubCategory> getSubCategory() {
        return subCategory;
    }

    /**
     *
     * @param subCategory
     * The sub_category
     */
    public void setSubCategory(List<SubCategory> subCategory) {
        this.subCategory = subCategory;
    }

}

SubCategory.json
package com.example.shkhan.myapp.model;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

/**
 * Created by shkhan on 14/11/16.
 */

public class SubCategory {

    @SerializedName("id")
    @Expose
    public String id;
    @SerializedName("name")
    @Expose
    public String name;

    /**
     *
     * @return
     * The id
     */
    public String getId() {
        return id;
    }

    /**
     *
     * @param id
     * The id
     */
    public void setId(String id) {
        this.id = id;
    }

    /**
     *
     * @return
     * The name
     */
    public String getName() {
        return name;
    }

    /**
     *
     * @param name
     * The name
     */
    public void setName(String name) {
        this.name = name;
    }

}

A: The Json contains a list of ValuesPos
The ApiInterface.java call for a single ValuesPos

EDIT
Change the ApiInterface.java to call for a list of ValuesPos
@FormUrlEncoded
@POST("pos_distributed.php")
Call<List<ValuesPos>> POS_MODEL_CALL(@Field("user_id") String user_id);

A: Here is the entire code which work for me... ( Thanks for the help )
Modified two class
ApiInterface.java
@FormUrlEncoded
@POST("pos_distributed.php")
Call<List<ValuesPos>> POS_MODEL_CALL(@Field("user_id") String user_id);

Backend.java
public void pos_func(String user_id) {
        dataArrayList1 = new ArrayList<>();
        ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);

        Call <List<ValuesPos>> call = apiService.POS_MODEL_CALL(user_id);

        call.enqueue(new Callback<List<ValuesPos>>() {
            @Override
            public void onResponse(Call<List<ValuesPos>> call, Response<List<ValuesPos>> response) {
                Log.d("sk_log", "Status POS Code = successsss");
                dataArrayList1 = response.body();

                //ValuesPos valuesPos = (ValuesPos) response.body();
                Log.d("sk_log", "name==="+dataArrayList1.get(0).getName());
                Log.d("sk_log", "name==="+dataArrayList1.get(0).getSubCategory().get(0).getName());
                CustomerCollection.spinner_pos(dataArrayList1);

            }
            @Override
            public void onFailure(Call<List<ValuesPos>> call, Throwable t) {
                Log.d("sk_log", "Failed! Error = " + t.getMessage());

            }
        });
    }

:)


Q: Toogle slide on a tag and css proprety I'm trying to toggle box shadow property for a tag within #bj-pagination. I would like to achieve effect where box shadow slides from page 1 link to page 2 link when link for page 2 is clicked. Is this complicated?

PREV
1
2
3
4
NEXT

Here I am positioned on page 1. CSS for current page is...
#bj-pagination .current {
    -moz-box-shadow: inset 0 -4px 0 #F6E128;
    -webkit-box-shadow: inset 0 -4px 0 #F6E128;
    box-shadow: inset 0 -4px 0 #F6E128;
    background: #FFF;
    border:1px solid #E4E4E4;
    border-right:none;
}

I would like to when page 2 is clicked animate slide of boxshadow from page 1 link on to page 2 link


Q: A strange result in a simple pthread code I wrote the following code:
#include <pthread.h>
#include <stdio.h>

void* sayHello (void *x){
    printf ("Hello, this is %d\n", (int)pthread_self());
    return NULL;
}

int main (){
    pthread_t thread;
    pthread_create (&thread, NULL, &sayHello, NULL);
    printf("HERE\n");
    return 0;
}

After compiling and running I saw 3 different types of outputs.

*

*Only "Here" was printed.

*"Here" and 1 'sayHello' message.

*"Here" and 2 'sayHello' messages.

Of course I'm OK with the second option, but I don't understand why the 'sayHello' massege can be printed 0 or 2 times if I created only one thread?

A: You can't say when the thread starts to run, it might not start until
after you return from main which means the process will end and the thread with it.
You have to wait for the thread to finish, with pthread_join, before leaving main.
The third case, with the message from the thread printed twice, might be because the thread executes, and the buffer is written to stdout as part of the end-of-line flush, but then the thread is preempted before the flush is finished, and then the process exist which means all file streams (like stdout) are flushed so the text is printed again.

A: For output 1:
your main function only create a pthread, and let it run without waiting for it to finish.
When your main function return, Operating system will collect back all the resources assigned to the pprocess. However the newly created pthread might have not run.
That is why you only got HERE.
For output 2:
your newly created thread finished before main function return. Therefore you can see both the main thread, and the created thread's output.
For output 3
This should be a bug in glibc. Please refer to Unexpected output in a multithreaded program  for details.
To make the program always has the same output
pthread_join is needed after pthread_create


Q: Passing component as a function argument I have a function that take a component as argument, and return another, enhanced component:
import React from 'react';
import { compose } from 'recompose';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { Layout, DarkBar } from 'SharedComponents/Layouts';

const myCreationFunction = ({
  component,
}) => {
  const Route = (props) => {
    // Some code here
    return (
      <Layout>

<Link to={props.path}>LinkTitleHere</Link>

          {React.createElement(component, {
            ...props,
            ...someOtherPropsHere,
          })}
      </Layout>
    );
  }; // The error points here

  const mapStateToProps = () => ({});
  const enhance = compose(
    connect(mapStateToProps, someActionsHere),
  )(Route);

  return enhance;
};

I invoke that function in this way:
import MyComponent from './MyComponent';
import myCreationFunction from './HOC/myCreationFunction';

const Route = myCreationFunction({
  component: MyComponent,
});

When I run it in the development mode, it runs smoothly. But when trying to build the app using npm run build and going through webpack, I get:
Module parse failed: Unexpected token (35:47)
You may need an appropriate loader to handle this file type.
| function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
> var createListRoute = function myCreationFunction((_temp = _ref, _ref2 = <_Layouts.DarkBar>
|           <_Breadcrumbs2.default />
|           <_Layouts.RoundAddButton path={addPath} color="white" />

What am I doing wrong?
Edit #1
It seems that the <Link> is causing the problem. Removing it fixed the problem. Also, when trying to replace it with a tag, I get the same issue. Weird.
Edit #2
I have not resolved this issue because of lack of time. I was trying for 1 hour without any progress and decided to go with button tag and onClick method that uses history to push the new url.
It was and is really weird to me, that a Link or  tag can break something during the build process itself. I will definitely jump deeper into it in some free time.


Q: Why does my PartialView render outside the form tag? I have a view that displays an HTML table of "Room" objects.  Each Room is a row (which is a PartialView) in the table.
The view contains this code:

    @foreach (var item in Model)
    {
        using (Html.BeginForm())
        {
            @Html.Partial("_roomPartial", item)
        }
    }

Model is an IEnumerable<Room>, and _roomPartial is an HTML row containing the properties of a Room.
For some reason, the HTML of the Partial renders after the closing form tag (despite being inside the using block):
<form action="/Room/Index" method="post"></form>

    ...some boring markup...

Other things I tried to make this work:

*

*Used Html.RenderPartial("_roomPartial", item); instead of @Html.Partial.

*Moved the using (Html.BeginForm()) block inside the PartialView

I got the same HTML results each time.
Why does the Partial render outside the form tag?  And how can I get it to render properly?

View:
@model IEnumerable<PatientAssigner.Models.Room>

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Index

            @Html.DisplayNameFor(model => model.ID)

            @Html.DisplayNameFor(model => model.isOccupied)

            @Html.DisplayNameFor(model => model.patientComplexityLevel)

@foreach (var item in Model)
{
    using (Html.BeginForm())
    {
        @Html.Partial("_roomPartial", item)
    }
}

_roomPartial:
@model PatientAssigner.Models.Room

        @Html.DisplayFor(room => room.ID)
        @Html.HiddenFor(room => room.ID)

        @Html.EditorFor(room => room.isOccupied)
        @Html.ValidationMessageFor(room => room.isOccupied)

        @Html.DropDownListFor(room => room.patientComplexityLevel,
                                    new SelectList(Enum.GetValues(typeof(PatientAssigner.Models.PatientComplexityLevel)),
                                                    Model.patientComplexityLevel),
                                                    "")
        @Html.ValidationMessageFor(room => room.patientComplexityLevel)

        <input type="submit" value="Save" class="btn btn-default" id="saveBtn" />

A: form tags are not valid between table and tr tags. I suggest changing your view to not have the tr or td tags and do this outside:

    @foreach (var item in Model)
    {

        @using (Html.BeginForm())
        {
            @Html.Partial("_roomPartial", item)
        }

    }

If you need to have a form for every row but want your inputs spread across cells, your only option is to have nested tables like this:

      <form>

            cell1
            cell2
            cell3

      </form>

      <form>

            cell1
            cell2
            cell3

      </form>


Q: python webserver socket programming error # Import socket module
from socket import *

#from socket import AF_INET, SOCK_STREAM, socket
import sys  # In order to terminate the program

# Create a TCP server socket
#(AF_INET is used for IPv4 protocols)
#(SOCK_STREAM is used for TCP)

ipadress=socket.gethostbyname(socket.gethostname())
subnetAdress = '.'.join(ipadress.split('.')[:3]) + '.0'

print(f"ipadress : {ipaddress}")
print(f"subnetAdress : {subnetAdress}")

file = open("permit.txt", 'r', encoding="UTF-8")
permitList = file.readlines()

#

serverSocket = socket(AF_INET, SOCK_STREAM)
# Assign a port number
serverPort = 6789
# Bind the socket to server address and server port
serverSocket.bind(("", serverPort))
# Listen to at most 1 connection at a time
serverSocket.listen(1)
# Server should be up and running and listening to the incoming connections

while True:
    print('The server is ready to receive')
    # Set up a new connection from the client
    connectionSocket, addr = serverSocket.accept()
    # If an exception occurs during the execution of try clause
    # # the rest of the clause is skipped
    # # If the exception type matches the word after except
    # # the except clause is execute
    if subnetAdress+'\n' in permitList:
        print("Warning!!\n it's not permitted")
        continue
    try:
        # Receives the request message from the client
        message = connectionSocket.recv(1024).decode()
        print(message)

        # Extract the path of the requested object from the message
        # # # The path is the second part of HTTP header, identified by [1]
        # filename = message.split()[1]

        print(filename)
        # Because the extracted path of the HTTP request includes
        # # # a character '\', we read the path from the second character
        file = open(filename[1:], 'rb')
        # Store the entire contenet of the requested file in a temporary buffer
        # outputdata = file.read()
        # # Send the HTTP response header line to the connection socket
        header = 'HTTP/1.1 200 OK\n'
        if(filename.endswith(".jpg")):
            filetype = 'image/jpg'
        elif(filename.endswith(".mp4")):
            filetype = 'video/mp4'
        elif(filename.endswith(".wmv")):
            filetype = 'video/wmv'
        elif(filename.endswith(".gif")):
            filetype = 'video/gif'
        elif(filename.endswith(".html")):
            filetype = 'text/html'
        else:
            raise IOError
        header += 'Content-Type: '+str(filetype)+'\n\n'
        print(header)
        connectionSocket.send(header.encode())
        # Send the content of the requested file to the connection socket
        # # # for i in range(0, len(outputdata)):
        # # # #     connectionSocket.send(outputdata[i].encode())
        # # # connectionSocket.send(outputdata)
        connectionSocket.send("\r\n".encode())
        # Close the client connection socket
        # connectionSocket.close()
    except IOError:
        # Send HTTP response message for file not found
        header = 'HTTP/1.1 404 Not Found \n\n'
        connectionSocket.send(header.encode())
        connectionSocket.send(
        "
404 Not Found
\r\n".encode())
        # Close the client connection socket
        connectionSocket.close()
        serverSocket.close()
        sys.exit()
        #Terminate the program after sending the corresponding data

I did this for socket programming
it's hard to explain but I had this error. and I put from socket import
please help me out. I don't know why
I will be dying ..

AttributeError                            Traceback (most recent call last)
c:\Users\taek\python\탐색\네트워크\과제3\IPwebServer.py in <module>
      9 #(SOCK_STREAM is used for TCP)
     10
---> 11 ipadress=socket.gethostbyname(socket.gethostname())
     12 subnetAdress = '.'.join(ipadress.split('.')[:3]) + '.0'
     13

AttributeError: type object 'socket' has no attribute 'gethostbyname'
                                                                                **                                        **

ㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠ

A: If you use
from socket import *

then you have to use without socket.
gethostbyname(...)
gethostname()
socket(AF_INET, SOCK_STREAM)

If you use
import socket

then you have to use with socket.
socket.gethostbyname(...)
socket.gethostname()
socket.socket(AF_INET, SOCK_STREAM)

BTW: import * is not preferred - see PEP 8 -- Style Guide for Python Code


Q: problems with opening vegan I Installed the package "vegan" but cant seem to run it. When I use the command library(vegan) I get this message
.
Any ideas? I normally just use R cmdr so excuse me if this is a silly question.
Also: Is there any plugin to cmdr for NMDS ordination that I can use instead?

A: That wasn't a "problem". It was only a "message" and not even a particularly dangerous message. It was telling you that the vegan package had a function of the same name as another function in the pls package. If you know that you will be using the scores function with the syntax of the pls::scores function at a later time, then you will need to use it with that form. If you just use scores you will get the function as it exists in pkg:vegan.
I'm being mute about the second part (although it may be premised incorrectly on your anxiety about the message, in which case the question is moot). Multipart questions are discouraged on SO.

A: To answer your question about Rcmdr  plugin for NMDS: check BiodiversityR package that provides an Rcmdr GUI to a part of vegan (plus more).


Q: Using ManagementObjectSearcher to get an exact BitLocker WMI value Good Day All,
I am having an issue with ManagementObjectSearcher. I am trying to query the exact value that i want but cannot find any reference to the precise syntax requirements and I continually receive an error when trying to finish out the code to be what I need it to be.
the specific portion of code that is presenting the issue is when I check for the drives Encryption state(I know for a fact that my disk is not encrypted on this machine, which is why that is the only value i have if'd currently). Any assistance in getting this code to pull the correct value would be greatly appreciated.
I've tried both the "=" method and the "LIKE" method with no change in output.
using Microsoft.Win32;
using System;
using System.Drawing;
using System.IO;
using System.Management;
using System.Windows.Forms;

    public Form1()
    {
        InitializeComponent();

        // Check for OS Version
        string OSVer = Convert.ToString(Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", "ProductName", null));
        OSDialog.Text = OSVer;

        // Check Architecture
        if (Directory.Exists("C:\\Program Files (x86)"))
        {
            ArchitectureDialog.Text = "64 Bit";
        }
        else
        {
            ArchitectureDialog.Text = "32 Bit";
        }

        // Check Encryption
        ManagementObjectSearcher Collect = new ManagementObjectSearcher("SELECT ProtectionStatus FROM Win32_EncryptableVolume WHERE DriveLetter = 'C:'");

        string Encryption = Collect.ToString();

        if (Encryption == "0")
        {
            EncryptionDialog.Text = "Disk is not Encrypted";
            EncryptionDialog.ForeColor = Color.Green;
        }
    }

    private void Cancel_Click(object sender, EventArgs e)
    {
        Close();
    }

A: Getting BitLocker information from WMI requires elevated permissions. Your code has to be running as an admin and you have to ask for elevated privileges. So, I don't use ManagementObjectSearcher to obtain BitLocker info. Instead, I do something similar to the following (modified to your scenario - but not tested as shown):
ManagementObject GetBitLockerManager( string driveLetter )
{
    var path = new ManagementPath( );
    path.Server = string.Empty;
    path.NamespacePath = @"\ROOT\CIMV2\Security\MicrosoftVolumeEncryption";
    path.ClassName = "Win32_EncryptableVolume";

    var options = new ConnectionOptions( );
    options.Impersonation = ImpersonationLevel.Impersonate;
    options.EnablePrivileges = true;
    options.Authentication = AuthenticationLevel.PacketPrivacy;

    var scope = new ManagementScope( path, options );
    var mgmt = new ManagementClass( scope, path, new ObjectGetOptions( ) );

    mgmt.Get( );
    return mgmt
      .GetInstances( )
      .Cast<ManagementObject>( )
      .FirstOrDefault
      ( vol =>
        string.Compare
        (
          vol[ "DriveLetter" ] as string,
          driveLetter,
          true
        ) == 0
      );
}

A: OK so I figured it out, thank you for all of the assistance provided. Code is below.
ManagementObjectSearcher Encryption = new ManagementObjectSearcher(@"root\cimv2\Security\MicrosoftVolumeEncryption", "SELECT * FROM Win32_EncryptableVolume");

        foreach (ManagementObject QueryObj in Encryption.Get())
        {
            string EncryptionStatus = QueryObj.GetPropertyValue("ProtectionStatus").ToString();

            if (EncryptionStatus == "0")
            {
                EncryptionDialog.Text = "Unencrypted";
            }
            else if (EncryptionStatus == "1")
            {
                EncryptionDialog.Text = "Encrypted - SysPrep will not complete";
            }
            else if (EncryptionStatus == "2")
            {
                EncryptionDialog.Text = "Cannot Determine Encryption";
            }
        }


Q: Where i can edit this price element woocommerce? I want to replace the word "De: " of all products, but I do not know where
Link to website

A: You can change the "From" text via the woocommerce_get_price_html_from_text filter.
You would do so, like this:
add_filter( 'woocommerce_get_price_html_from_text', 'so_43054760_price_html_from_text' );
function so_43054760_price_html_from_text( $text ){
    return __( 'whatever', 'your-plugin-textdomain' );
}

Keep in mind this is WooCommerce 3.0-specific code. I'm not sure it is back-compatible with WC 2.6.x.


Q: User Registration setting missing in Joomla This is my first experience in Joomla V3.3.6
I have a requirement where there would be 2 user types.
-> User Type 1
-> User Type 2

1) I am looking out for registration module in Joomla. Searched and looks there are lots of plugins. But also understood that Joomla by default has default Registration module as per the below link:

*

*http://docs.joomla.org/Allowing_user_registration

*http://docs.joomla.org/Setting_user_registration_policy
The issue is, I do not see a place in Global Settings where there is User Settings as defined by the above link. Hence not able to see the registration page.
2) I see in admin dashboard, User Manager, User Groups. I guess, I could use these user groups to define the User Types. Please confirm if this is how it is in Joomla?
Kindly Help! Thanks in advance.

A: From the administrator, go to User Manager
At the top right, you'll see Options
That's where you set the user/registration options


Q: Chart.Js Doughnut not calculating JSON data properly When using static data, the Doughnut chart appear perfectly, example:
$.ajax({
        url: 'includes/stats.php?show',
        dataType: 'json',
        success: function (response)
        {
            console.log(response['CARS']); //I see 2
            console.log(response['MOTORS']); //I see 0
            console.log(response['BOATS']); //I see 0
            var autoData = [
                {
                    value: 2,
                    color: "#4286f4",
                    highlight: "#4d6fa5",
                    label: "Cars"
                },
                {
                    value: 0,
                    color: "#3fe276",
                    highlight: "#51a36d",
                    label: "Motor Homes"
                },
                {
                    value: 0,
                    color: "#bde234",
                    highlight: "#87964e",
                    label: "Boats"
                }
            ];
            var ctx = document.getElementById("onChart").getContext("2d");
            var myNewChart = new Chart(ctx).Doughnut(autoData);
        }
});

I'm doing the JSON call, but on the callback, I'm filling autoData variable with static data [2, 0, 0], this way the chart appears and calculate 100% for "Cars", because it is the only with some value (2), others are 0's...
When I do:
$.ajax({
        url: 'includes/stats.php?show',
        dataType: 'json',
        success: function (response)
        {
            console.log(response['CARS']); //I see 2
            console.log(response['MOTORS']); //I see 0
            console.log(response['BOATS']); //I see 0
            var autoData = [
                {
                    value: response['CARS'],
                    color: "#4286f4",
                    highlight: "#4d6fa5",
                    label: "Cars"
                },
                {
                    value: response['MOTORS'],
                    color: "#3fe276",
                    highlight: "#51a36d",
                    label: "Motor Homes"
                },
                {
                    value: response['BOATS'],
                    color: "#bde234",
                    highlight: "#87964e",
                    label: "Boats"
                }
            ];
            var ctx = document.getElementById("onChart").getContext("2d");
            var myNewChart = new Chart(ctx).Doughnut(autoData);
        }
});

I get just what looks like a 2% slice of the chart filled... What's happening here?

A: I was constructing the JSON from PHP, something like:
    $data = $autoQuery->fetch_array();
    $autoData = array('CARS' => $data['CARS'],
                    'MOTORS' => $data['MOTORS'],
                    'BOATS' => $data['BOATS']);
    echo json_encode($autoData);

This wasn't working. When I put intval() before each $data variable, it worked!


Q: I want to add list view new items (Except old ones) to array I have two list views, list one contains hotel service items that are fixed to a specific room and the other on is optional services, when i click on optional service list view item it will be added into services items. at the end all services will be viewed in list services(fixed + additional), and the price of only optional service will be saved in a db table which is optional service of the specified room
i tried on adding to delete old values and then adding optional services till the size of the added items but it doesn't work, some times it gives an error and other it prints or add only the old services and first one from the optional
`
for(int i=0;i<(lst1Count);i++){
lst1.getItems().remove(i);
    }
for(int i=0;i<(lst1.getItems().size());i++){

       try {
           String queryServicePrice = "select Serviceprice from services where ServiceName ='"+lst1.getItems().get(i)+"'";
           ResultSet rsRoomService = stmt.executeQuery(q`ueryServicePrice);
           rsRoomService.next();
           Serviceprice[i] = rsRoomService.getBigDecimal(

    "Serviceprice");
               System.out.println("price"+i+" : "+Servicepric

e[i]);}

`


Q: Enforce NTP Time Sync on boot - raspberrypi 3 I have a setup a raspberrypi to sync time from a NTP server as it does not have a HW clock on it, however this update does not happen immediately and takes a while (~15 mins). Is there a way I can enforce the NTP Client to sync datetime with the NTP server before starting up other user processes. If anyone has been able to achieve this please let me know. cheers!
Update: The rPi does not have internet connectivity

A: You might want to try this service from the NIST:
NIST Internet Time Service.  They have a list of servers here. and tips on how to engage with their system from Windows, OSX, and Linux.   The response might be quick enough to hold you over until your NTP client can receive its response.


Q: how to get running total column sir i have query that show RUNNING TOTAL but not show me exect Dr_amount and Cr_amount as per transaction how to get Dr_amount and Cr_amount as per single transaction
SELECT
V_DATE,FLAG,V_NUM,V_NARATION,
sum(DR_AMOUNT) AS DEBIT,
sum(CR_AMOUNT) AS CRIDIT,
sum(dr_amount)-sum(cr_amount) as total
FROM VOUCHARDETAIL AS VDTL
INNER JOIN VOUCHARMASTER AS VMST
ON VDTL.DTL_NUM <=VMST.MST_NUM
WHERE (V_DATE BETWEEN '12-03-2017' AND '13-03-2017') AND (FLAG='IV' OR FLAG='BR'
OR FLAG='CP' OR FLAG='CR' OR FLAG='JV') AND (AC_CODE=60030002)
GROUP BY
V_DATE,FLAG,V_NUM,V_NARATION
ORDER BY
V_DATE

Example Image


Q: Running Transient services in background (.NET Core) I am attempting to write a customer order tracker using Blazor Server.
What I'd like to do is launch on the background an order management service for every new order created. The service would keep track of various live information associated with the order, and it should be disposed of when the order is completed.
I am able to do that through registering the service as:
services.AddTransient();
I can then dependency-inject this into a razor component:
@inject OrderManagementService om_service
This creates a new instance for each order, which is good. The problem is that I can't expect the user to keep the page open in order to keep the the Transient service's scope alive.
From my observation, the instance continues to run, but its lifetime is not well-defined. It could terminate indefinitely soon (not long enough to finish the job), or run indefinitely long (thus robbing the server of resources). As I have no reference to it.
How can this problem be solved? If Transient services are not the solution, then what would it be?
Thank you!

A: Check out hosted background services in .NET Core, sounds like it could work for you.
Hosted background services continue running on your server even if the user navigates away from your site. You could have an OrderManager hosted service that guides each order through the process and keeps the order status updated in the database, email the user status updates, or push changes to the front-end.


Q: Auto refresh/reload four iframes in Wordpress I'm pretty NEW
so on the question:
I have 4 iframes on one page in WordPress showing some stats. I want to make them auto refresh (not the whole page) on certain amount of time, like every 3 second.
I've managed to do that for one only but whenever I try to add another one it  doesn't work. I hope there's a simple solution.
Here's the iframe:
<iframe id="idcw" src="http://web.ubercounter.com/charts/chart5?f=jsn&ext=1&pid=01edabc9-dd3c-41db-949b-9b6ee52e0af5&cid=&fromD=2018-06-26&toD=&fromT=16:48:14&toT=<=&lg=&r=0&fh=0&th=24&u=0&rt=">

And the JS I''ve putt in the Header:

PS: That was the only code I found on the internet working as it had to work. I tried with my very basic knowledge to add another 3 iframes to reload but only one refreshed.
Thanks in advance!

A: Try this code

setInterval(function(){ reloadIFrame2(); }, 5000);

function reloadIFrame2() {

 var elements = document.getElementsByClassName("idcw");
 for (var i = 0, len = elements.length; i < len; i++) {
  elements[i].src =  elements[i].src;
 }
}
<iframe class="idcw"  src="http://web.ubercounter.com/charts/chart5?f=jsn&ext=1&pid=01edabc9-dd3c-41db-949b-9b6ee52e0af5&cid=&fromD=2018-06-26&toD=&fromT=16:48:14&toT=<=&lg=&r=0&fh=0&th=24&u=0&rt=">

<iframe class="idcw"  src="http://web.ubercounter.com/charts/chart5?f=jsn&ext=1&pid=01edabc9-dd3c-41db-949b-9b6ee52e0af5&cid=&fromD=2018-06-26&toD=&fromT=16:48:14&toT=<=&lg=&r=0&fh=0&th=24&u=0&rt=">

<iframe class="idcw"  src="http://web.ubercounter.com/charts/chart5?f=jsn&ext=1&pid=01edabc9-dd3c-41db-949b-9b6ee52e0af5&cid=&fromD=2018-06-26&toD=&fromT=16:48:14&toT=<=&lg=&r=0&fh=0&th=24&u=0&rt=">

<iframe class="idcw"  src="http://web.ubercounter.com/charts/chart5?f=jsn&ext=1&pid=01edabc9-dd3c-41db-949b-9b6ee52e0af5&cid=&fromD=2018-06-26&toD=&fromT=16:48:14&toT=<=&lg=&r=0&fh=0&th=24&u=0&rt=">

Run this fiddle
http://phpfiddle.org/main/code/asn7-zfvq


Q: Installing Maven and creating a maven project in eclipse I am new to using maven project and i am trying to create a maven project and i followed the instructions to create one in eclipse and i gave the groupId and artifact id to it and clicked Finish, for which it gave me an error stating

"No marketplace entries found to handle
  maven-compiler-plugin:3.1:compile in Eclipse.  Please see Help for
  more information."

For this issue i tried googling and stack overflow and i saw people asking other people to change the installation directory of maven inside

Window-> Preferences -> Maven-> Installation

I tried that and tried to update the maven project but still i have some errors, i am not able to setup my project, Could someone please help?
I am attaching the errors herewith.

A: If  a Maven project is configured to use ecj compiler, the following errors appear when importing the project into eclipse:

*

*No marketplace entries found to handle maven-compiler-plugin:2.3.2:compile in Eclipse.  Please see Help for more information.

*No marketplace entries found to handle maven-compiler-plugin:2.3.2:testCompile in Eclipse.  Please see Help for more information.
A fix should be trivial.
http://git.eclipse.org/c/m2e/m2e-core.git/tree/org.eclipse.m2e.jdt/lifecycle-mapping-metadata.xml reads:
    <parameters>
      <compilerId>javac</compilerId>
    </parameters>

It should read:
    <parameters>
      <compilerId>javac</compilerId>
      <compilerId>eclipse</compilerId>
    </parameters>

Reproducible: Always
Steps to Reproduce:
1. Unpack example zip provided
2. Try to import it to Eclipse: File->Import->Maven->Existing Maven Projects

A: First you can try to install maven globaly. follow the steps.

*

*Download maven from maven download link

*Create or export M2_HOME="MAVEN ROOT LOCATION". Ex. : E:\SoftwareRepo\building tools\apache-maven-3.5.2

*Create  or export MAVEN bin folder location to PATH variable.
For example: E:\SoftwareRepo\building tools\apache-maven-3.5.2\bin

*Open terminal or cmd and run mvn --version to confirm maven is installed or not.
Then go to eclipse. and setup project.follow this steps

*

*Import existing maven project or create a maven project

*Goto project explorer and Right click on your pom.xml

*then select Run As maven install.

*and then what you want.

Hope it will serve your purpose. You can download a sample spring boot project from sample spring boot project
Or you can run a maven project from terminal or cmd. Just goto project root folder and then run a maven task like maven clean install .
Happy Coding :)

A: First install Java and then create the maven project.
Install the stable Java version in the system.
If Java is not installed then these types of errors will be displayed.

No marketplace entries found to handle
maven-compiler-plugin:3.1:compile in Eclipse.

Take a look at Help for more information.


Q: java.lang.ClassCastException: cannot cast class com.ibm.WsnOptimizedNaming._NamingContextStub to interface Created a remote EJB project and deployed in the IBM websphere server as Jar.
Now, i created a EJB Client project in my local and trying to connected as Remote call.
but it is throwing an exception: java.lang.ClassCastException
client Program:
package ejb3.test;

import java.util.Properties;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;

public class TestEJBClient {

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    Properties props = new Properties();

    props.put(javax.naming.Context.PROVIDER_URL, "iiop://(ip of remote ejb server):2809");

    ITestEJBRemoteInterface loEJB = null;
    Object lobj;

    try {

        InitialContext ctx = new InitialContext(props);
        System.out.println(ctx.getEnvironment());
        lobj = ctx.lookup("ejb3/test/ITestEJBRemoteInterface");// look up of corba
        System.out.println("--------" + lobj);

        loEJB = (ITestEJBRemoteInterface)     PortableRemoteObject.narrow((org.omg.CORBA.Object) lobj, ITestEJBRemoteInterface.class);
        String lsName = "Kevin";
        // Invoke the Method using bean object ;
        System.out.println("Is " + lsName + " present in the list:: " + loEJB.checkNames(lsName));
        System.out.println("EJB run successful");
    }
    catch (NamingException e) {
        e.printStackTrace();
    }

    }
}

exception:
{com.ibm.websphere.naming.hostname.normalizer=com.ibm.ws.naming.util.DefaultHostnameNormalizer, java.naming.factory.initial=com.ibm.websphere.naming.WsnInitialContextFactory, com.ibm.websphere.naming.name.syntax=jndi, com.ibm.websphere.naming.namespace.connection=lazy, com.ibm.ws.naming.ldap.ldapinitctxfactory=com.sun.jndi.ldap.LdapCtxFactory, com.ibm.websphere.naming.jndicache.cacheobject=populated, com.ibm.websphere.naming.namespaceroot=defaultroot, com.ibm.ws.naming.wsn.factory.initial=com.ibm.ws.naming.util.WsnInitCtxFactory, com.ibm.websphere.naming.jndicache.maxcachelife=0, com.ibm.websphere.naming.jndicache.maxentrylife=0, com.ibm.ws.naming.wsn.localonly=false, com.ibm.websphere.naming.jndicache.cachename=providerURL, java.naming.provider.url=iiop://10.176.106.207:2809, java.naming.factory.url.pkgs=com.ibm.ws.naming:com.ibm.ws.naming:com.ibm.ws.naming:com.ibm.ws.naming:com.ibm.ws.naming}
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
WARNING: WSVR0072W
Feb 18, 2016 7:39:53 PM null null
INFO: Client code attempting to load security configuration
Feb 18, 2016 7:39:53 PM null null
AUDIT: security.LoadSCI
Feb 18, 2016 7:39:53 PM null null
AUDIT: security.GettingConfig
Feb 18, 2016 7:39:53 PM null null
WARNING: ssl.default.password.in.use.CWPKI0041W
Feb 18, 2016 7:39:53 PM null null
INFO: ssl.disable.url.hostname.verification.CWPKI0027I
Feb 18, 2016 7:39:53 PM null null
AUDIT: security.AuthTarget
Feb 18, 2016 7:39:53 PM null null
AUDIT: security.ClientCSI
--------com.ibm.WsnOptimizedNaming._NamingContextStub:IOR:00bdbdbd0000003149444c3a636f6d2e69626d2f57736e4f7074696d697a65644e616d696e672f4e616d696e67436f6e746578743a312e3000bdbdbd0000000100000000000000f4000102bd0000000a6c6f63616c686f737400238c0000006b4a4d4249000000124773e3aa37643062633737336533616166633334000000240000004749454a500200f76a838007736572766572311a57736e44697374436f734f626a65637441646170746572574c4d00000016434c45564449434d2d3134334e6f6465303143656c6cbd00000007000000010000001400bdbdbd0501000100000000000101000000000049424d0a0000000800bd00011600000100000026000000020002bdbd49424d04000000050005020102bdbdbd0000001f0000000400bd0003000000200000000400bd0001000000250000000400bd0003
Exception in thread "P=592906:O=0:CT" java.lang.ClassCastException: cannot cast class com.ibm.WsnOptimizedNaming._NamingContextStub to interface ejb3.test.ITestEJBRemoteInterface
    at com.ibm.rmi.javax.rmi.PortableRemoteObject.narrow(PortableRemoteObject.java:396)
    at javax.rmi.PortableRemoteObject.narrow(PortableRemoteObject.java:148)
    at ejb3.test.TestEJBClient.main(TestEJBClient.java:38)

How could i resolve that error?
Can any one please share your thoughts.

A: ClassCastException - if narrowFrom cannot be cast to narrowTo.

Seems that corba.object and itestejbrremoteinterface are not related by inheritance

A: The relevant lines from the dumpNameSpace are:
  168 (top)/nodes/CLEVDICM-143Node01/servers/server1/ejb3.test.ITestEJBRemoteInterface
  168                                                    ejb3.test.ITestEJBRemoteInterface

  192 (top)/nodes/CLEVDICM-143Node01/servers/server1/ejb/TestEJB(1)_jar/TestEJB(1).jar/TestEJB#ejb3.test.ITestEJBRemoteInterface
  192                                                    ejb3.test.ITestEJBRemoteInterface

The root of the server context is (top)/nodes/CLEVDICM-143Node01/servers/server1/, which means you should use one of these strings:

*

*ejb3.test.ITestEJBRemoteInterface

*ejb/TestEJB(1)_jar/TestEJB(1).jar/TestEJB#ejb3.test.ITestEJBRemoteInterface


Q: How to reliably determine the width of a character in C#? I'm writing a C# program and I'm using a fixed-width font to display everything. Under this font, every Unicode character either occupies 1 character width or 2 character width. In the program, there is a feature that needs to determine a particular character occupies 1 character width or 2 character  width. At first I use the regex [^\x00-\xFF] to solve the problem. If a character matches it, it occupies 1 character width, otherwise it's 2 character width. But later I found this is not correct. For example, these characters ┌─┬┐│├┼┤┴┘ don't fall in the range of [^\x00-\xFF] but they all just occupies 1 character width. I want to know in C# how to determine a specific character occupies 1 character width or 2 when using fixed-width font?

A: I'm also searching for the same question's answer... but I haven't found it.
by the way, I finally write a library to get length of character (generate a range information which shows character length use Console.Write() and Console.CursorLeft, and then convert to C# code, when get character length, use binary search for higher speed)
nuget: NullLib.ConsoleEx
Project: https://github.com/SlimeNull/NullLib.ConsoleEx

A: According to .NET documentation, if you know the font used1, you could use the GlyphTypeface API to get the "AdvanceWidths" of each glyph of your font.
You still have to map the character with glyph index in your font. You can use CharacterToGlyphMap to do that.
var character = 'x';

GlyphTypeface glyphTypeface = new GlyphTypeface(new Uri("file:///C:\\WINDOWS\\Fonts\\Kooten.ttf"));

var index = glyphTypeface.CharacterToGlyphMap[character];
var width = glyphTypeface.AdvanceWidths[index];

[1] To get current console's font details I would recommend to read following question: Get current console font info
Related question: How to find exact size for an arbitrary glyph in WPF?


Q: Mule http connector encoding I am posting xml string use mule http connector to my client.
The xml has string "Grubišić". It works fine if I post data to client from anypoint studio. If run on production or testing server, my client received "GrubiÅ¡iÄ" instead of "Grubišić".
I tried to specify content-type = "application/xml;charset=UTF-8" from http request header, payload property.. none of them worked.
<set-payload value="#[flowVars.myXML]" encoding="UTF-8" mimeType="application/xml" doc:name="Set Payload"/>
<http:request config-ref="HTTP_Request_Configuration" path="/api/upload" method="POST" doc:name="HTTP" >
    <http:request-builder>
        <http:header headerName="Content-Type" value="application/xml;charset=UTF-8"/>
    </http:request-builder>
</http:request>

I am using 3.9CE runtime.
Am I missing any config? or it could be a bug in 39CE standalone?
Thanks
-Susan

A: There a lot of context missing in the question to be sure, but setting the encoding in the set-payload operation or in the Content-Type header doesn't actually transform the payload to or from UTF-8. A common mistake is to assume because the configurations, or even the XML declaration says UTF-8, to assume that the data is UTF-8 automatically. It is the data that is in UTF-8 or not. Most probably you are using a payload that is in a local encoding (Windows-1252 or something similar) when you test locally, but your server uses UTF-8 by default so it doesn't appear as you are expecting. "GrubiÅ¡iÄ" looks very similar to how the UTF-8 encoding of "Grubišić" would look.


Q: Does the 'Supporting Files' folder increase launch time/CPU consumption? If I have a lot of images/etc in the Supporting Files folder does that increase CPU consumption and slow the launch time of the app? Does the app have to load all these files on launch.
Thanks in Advance :)

A: No. In general these are copied into the apps bundle at compile time, letting the app access them when it needs them (by finding the files).


Q: how to make chromium/chrome only reloads the modifled files? My site has a lot of img, js, css files. If one file is modified by developer its url will be changed too, otherwise the url will not be changed.
I wish chromium/chrome only reloads the modified files according to the url, but actually it often reloads all files with some unknown rules　without using cache.
How to solve this?

A: It's a vague and broad question, but I guess you use different URLs to prevent retrieving old, cached versions of changed resources (that's one sure way anyway, although not necessarily the best way) and have a problem with Chromium-based browsers not caching resources that are unchanged.
Chromium respects caching directives as per spec, so it seems you're not sending the appropriate caching directives (headers) in the first place or have a problem testing the caching behavior (e.g. testing with caching disabled). Determine which is the problem and fix it.


Q: Update sharepoint user profile property with SPSecurity.RunWithElevatedPrivileges I try to change user profile property with next code
SPSecurity.RunWithElevatedPrivileges(delegate(){
SPSite currentSite = new SPSite(SPContext.Current.Web.Url);

SPServiceContext serviceContext = SPServiceContext.GetContext(currentSite);
UserProfileManager upm = new UserProfileManager(serviceContext);
UserProfile up1 = upm.GetUserProfile("DOMAIN\\User3");
up1["CustomProperty"].Value=10;
up1.Commit();

currentSite.Dispose();
});

And it's all right when i open page with account User1, which have permissions to change all user profiles. But when i open page with User2(with no permissions) - i get 403 error. In debugger up1["CustomProperty"].Value is null.
Why SPSecurity.RunWithElevatedPrivileges have no effect and how can i solve this problem?
Thanks

A: I found description of my problem in next article
Impersonation does not work with UserProfileManager
As a reason you can clear HttpContext each time you get or set user profile properties. For example next code works fin for me.
 SPSecurity.RunWithElevatedPrivileges(delegate()
        {
            HttpContext tempCtx = HttpContext.Current;
            HttpContext.Current = null;

            UserProfile userProfile = GetUserProfile(user);
            userProfile["SomeProperty"].Value = points;
            userProfile.Commit();

            HttpContext.Current = tempCtx;
        });


Q: How to iterate through a list of URLs and make a GET request I am trying to take a list of URLs from Google Sheets and then make an API request for each URL and return data in JSON format.  I currently am able to retrieve the list from Google sheets as well as make a Request for a single URL that I manually enter.
So far everything is working as expected.  I am more or less asking for guidance on what my next steps would be.  I am a novice in Python so not sure what to do next.
Here is an example of the output for the API request of the single URL in JSON:
{"date":"2019-02-07T00:00:00+0000","clicks":7},{"date":"2019-02-06T00:00:00+0000","clicks":7},{"date":"2019-02-05T00:00:00+0000","clicks":5}
# -*- coding: utf-8 -*-
"""
Created on Thu Dec  6 18:47:58 2018

@author: Dylan
"""

import requests
import json
import gspread
from oauth2client.service_account import ServiceAccountCredentials

#scope is just telling google what API you want to use because they have so
many
scope = ['https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile_name('Bitly Click
Data-a892fb027ee3.json', scope)
gc = gspread.authorize(credentials)

wks = gc.open("Bit.ly Links & General Links").get_worksheet(0)
values_list = wks.col_values(2)

wks = json.dumps(str(wks))

print(wks.get_all_records())

url = "https://api-ssl.bitly.com/v4/bitlinks/THIS NEEDS TO BE THE URL LIST
HERE/clicks"

payload = ""
headers = {'authorization': 'Bearer ACCESS TOKEN HERE'}

response = requests.request("GET", url, data=payload, headers=headers)

print(response.text)


Q: Having trouble wrapping my head around how to handle dates I'm working on a scheduling system for music venues.  The basic idea is that there's an "Create new schedule" page, on which there is a DatePicker calendar (using AngularUI Bootstrap).  The user selects a Date, then adds performers into timeslots. The built object looks something like this:
{
  date: 2017-6-22 00:00:00.000-5:00
  venue: VenueID
  performances: [
    {
      performer: performerID,
      time: 2017-06-22 22:00:23.231-5:00
    },{
      perfomer: performer2ID,
      time: 2017-06-22 23:00:42.523-5:00
    }
  ]
}

There's a couple of problems here.  For the original date selection, I set the time (using myDate.setHours(0,0,0,0)) to midnight because the time doesn't really matter, I only care about the actual date.  Likewise for the timeslots, their date doesn't matter (since they belong to the schedule for that day), so I only care about the time. Then in another project, we have a node/mongo app that saves these schedules, and returns them to a page in the angular project that lets you select a schedule for editing/etc.  It selects which ones to return by grabbing all the schedules for a specific venue, and doing "if (schedule.date >= new Date().setHours(0,0,0,0)) { add schedule to return list }"
Anyway, on to the actual problem.  The angular app does all of the date calculations client side.  What I mean is, I'm in CST.  If I select a Date on the calendar and save a schedule for that date, then someone in EST selects the same day on the calendar and saves a schedule, they have different dates in the database.  For example, when I make the schedule, the date in the DB is "2017-06-22 00:00:00.000-5:00".  When the EST friend makes a schedule on the same date, it gets saved as "2017-06-22 00:00:00.000-4:00".
In the "Select a schedule to view/edit" page, I do something like this:
<select ng-model="schedule" ng-options="s.date|date:'fullDate' for s in schedules" ng-show="schedules.length>=1"></select>

Of course this doesn't work because when my EST friend looks at the list, he sees the correct date.  But when I look at one that he created, the date is one day off because "2017-06-22 00:00:00.000-4:00" converted to local timezone is "2017-06-21 23:00:00.000-5:00".
I guess TL;DR is I'm not sure how to handle it since the venue and anyone creating/editing the schedules may not share the same time zone. I want all of the dates/times to show up in the timezone of the venue (which I have the address for.  I guess I could geolocate to find timezone?).  I'm just not sure how to go about it.

A: The DatePicker gives you a date object. Instead of storing the entire value string just grab the day month and year Date(value).getYear() + '-' + Date(value).getMonth()  + '-' + Date(value).getDate(). As for the times do the same as the dates. Store those values in the DB and then when you get them back you will have to convert them back to a date object so that the date picker can understand them.
Ultimately with this solution your just trying to store dates without the timezones. Make sure to state in your app that the times are for those areas.

A: You have to distinguish between the format the date/time is transported, saved vs. how the date will be shown to the user.

*

*For transportation and saving use UTC in a format that is easy computable (eg. ISO8601).

*For visualization to the user convert this value to the timezone and desired user format by using some helper library.


Q: how to poll a resource using jersey service i have a jersey service which generates a response. what i want to do is to poll a resource (in my case, a singleton class instance) for a success value, and as soon as i get the success value, perform some action
@Path("/generate")
class Generation{
    @POST
    @Produces("javax.ws.rs.core.MediaType.TEXT_PLAIN")
    public String generateAndPoll(){
        //Generate response
        /*Polling to start

        */
    return someValue;
    }
}

what may be a good way to accomplish that? Would timer be of any use?

A: As of Jersey 2.3.1, a new feature has been added to support server-sent events. For your use-case, you might want to read more into the Jersey documentation

A: If you don't mind using an external library, I have been using atmosphere for a few years and it is a great server push / comet implementation. It has support for just about ever server and yes it will depend on the server. They support long poll and websockets natively. Almost the entire service can be configured with just a couple of annotations. Here is an example of how to use it on a jersey 2 service.
https://github.com/Atmosphere/atmosphere-samples/blob/master/samples/jersey2-chat/src/main/java/org/atmosphere/samples/chat/jersey/Jersey2Resource.java


Q: Point out location in Google Map I am developing an application in PHP. I have latitude and longitute of few locations in Google Map. I want to point it those locations on google map.
How can i point it?

A: http://code.google.com/apis/maps/index.html take a look at the google api its very easy to work with


Q: Why solr RemoveDuplicatesTokenFilterFactory dont work? My schema.xml is splitting product name and then uses RemoveDuplicate to remove duplicated words after split.
    <fieldType name="type_name" class="solr.TextField">
        <analyzer type="index">
            <tokenizer class="solr.PatternTokenizerFactory" pattern="\|| " />
            <filter class="solr.LowerCaseFilterFactory"/>
            <filter class="solr.RemoveDuplicatesTokenFilterFactory"/>

And in query analyzer I see that RemoveDuplicatesTokenFilterFactory did absolutely nothing to duplicated words. Why?

A: If you read Wiki you will see that it only removes duplicates at the same position, which is not the case here.


Q: Deploying angular build utilising the azure event hub js sdk fails to run If I run the project locally with

ng serve -o

everything works as expected
However, once I build it (either dev or prod build) and deploy it to either an Azure web app or a local web server on my machine I get the error of

connectionContext.js:20 Uncaught TypeError: os__WEBPACK_IMPORTED_MODULE_2__.type is not a function - within connectionContext.js (from the azure event hubs SDK)

I performed

npm install

and all modules install but I still get the same error each time.
I am assuming something is added when running locally via the ng server but is not included within a build.
Is there anything to check for that I may have missed?
UPDATE:
I have this running now by removing the functions that were causing the issue, not a fix more a hack to try and get progression. However, if I deploy to a local web server on my machine or to a raspberry pi it runs as expected. But when I deploy it to an azure web app it does not work as expected and states it cannot find 2 files (even though they can be seen via the FTP)

A: You need to create a web.config file in your wwwroot folder and add the MIME config like below to serve the JSON and WOFF files on Azure. You can check this similar thread.
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
    <system.webServer>
        <staticContent>
            <remove fileExtension=".json" />
            <remove fileExtension=".woff" />
            <remove fileExtension=".woff2" />
            <mimeMap fileExtension=".json" mimeType="application/json" />
            <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
            <mimeMap fileExtension=".woff2" mimeType="application/font-woff" />
        </staticContent>
    </system.webServer>
</configuration>

You can check angular deployment document fore more information,