Q: Error at backbone model fetch to slim framework I'm trying to get a simple app working. It uses backbone, the slim framework and cordova. For now, all i'm trying to do is fetch user models from a MySQL database. Client side code looks like:
// Cordova is ready
function onDeviceReady()
{
    // This little code snippet prepends our root to any Ajax call.
    $.ajaxPrefilter( function( options, originalOptions, jqXHR ) {
        options.url = 'http://localhost/~nmeibergen/IBMI/www/' + options.url;
    });

    var profileView = new ProfileView();

    var Router = Backbone.Router.extend({
        routes: {
          "": "home"
        }
    });

    var router = new Router();
    router.on('route:home', function() {
        profileView.render();
    });

    Backbone.history.start();
}

var Users = Backbone.Collection.extend({
    url: 'index.php/users',
    model: User
});

var User = Backbone.Model.extend({
    urlRoot: 'index.php/users',

    defaults: {
        user_id: 1,
        name: 'Nathan',
    }
});

var ProfileView = Backbone.View.extend({

    el: '#home',

    render: function () {
        var users = new Users();
        alert('all fine');
        users.fetch();
    }
});

Whenever I simply go to http://localhost/~nmeibergen/IBMI/www/index.php/users, I get the expected JSON object:
[{"user_id":"1","name":"Jhonathan "},{"user_id":"0","name":"Nathan"}]

However when running the above code it hits the alert 'all fine', but then gives me the following error and stack trace:
TypeError: 'undefined' is not an object (evaluating 'targetModel.prototype') in backbone.js:1:689
            set        backbone.js:1:689
            success    backbone.js:1:686
            fire       jquery-1.11.1.js:3119
            fireWith   jquery-1.11.1.js:3231
            done       jquery-1.11.1.js:9275
            callback   jquery-1.11.1.js:9685

I can't seem to find out what is wrong with the code, it should be pretty basic. Thank you for looking!

A: When you say this:
var x = 6;

The var x declaration will be hoisted to the top of the current scope. However, the assignment part will not be hoisted. The result is that you're saying this:
var x;
// Everything from the top of the scope to your `var x = 6` goes here.
x = 6;

In your case, you're doing this:
var Users = Backbone.Collection.extend({
    url: 'index.php/users',
    model: User
});

var User = Backbone.Model.extend({
    urlRoot: 'index.php/users',

    defaults: {
        user_id: 1,
        name: 'Nathan',
    }
});

so var User is hoisted to the top of the scope but User = Backbone.Model.extend(...) happens after Users = Backbone.Collection.extend(...). Rearranging the code to match what really happens, we have:
var Users, User;

Users = Backbone.Collection.extend({
    //...
    model: User
});
User = Backbone.Model.extend({
    //...
});

What do you think the value of User will be when it is used in the definition of Users? User will be undefined just like any other uninitialized variable.
Demo: http://jsfiddle.net/ambiguous/xYkmc/
You need to define your User before Users:
var User = Backbone.Model.extend({
    urlRoot: 'index.php/users',

    defaults: {
        user_id: 1,
        name: 'Nathan',
    }
});

var Users = Backbone.Collection.extend({
    url: 'index.php/users',
    model: User
});

Demo: http://jsfiddle.net/ambiguous/E7V84/


Q: Issue with 'ResidualGraph' in FindMaximumFlow I try to get the residual graph of the flow
weithsToEdgesV={0.2, 0.2, 0.2, 0.2, 0.2, 0.8, 0.2, 0.8, 0.8, 0.2,0.2, 0.8, 0.8, 0.2, 0.2, 0.8, 0.2, 0.8, 0.2, 0.2, 0.8, 0.2, 0.8,0.2, 0.2,0.8};

testGrap = Graph[DirectedEdge @@@ {{1, 2}, {1, 4}, {1, 5}, {1, 8}, {2, 1}, {2, 4}, {2, 6}, {2, 8}, {3, 6}, {3, 8}, {4, 1}, {4, 2}, {4, 8}, {5, 1}, {5, 6}, {5, 8}, {6, 2}, {6, 3}, {6, 5}, {6, 8}, {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}}];

FindMaximumFlow[testGrap, n + 1, n + 2, "ResidualGraph",EdgeCapacity -> weithsToEdgesV]

But I get the next result:
 FindMaximumFlow[testGrap, 7, 8, "ResidualGraph",
 EdgeCapacity -> {0.2, 0.2, 0.2, 0.2, 0.2, 0.8, 0.2, 0.8, 0.8, 0.2,0.2, 0.8, 0.8, 0.2, 0.2, 0.8, 0.2, 0.8, 0.2, 0.2, 0.8, 0.2, 0.8,0.2, 0.2,0.8}]]

How can I get the residual graph?


Q: Unknown Xeon processor model Any help would be appreciated.
I'm trying to get the model number of a IBM server I found. I'm trying to see what model Xeons it has. The conventional methods aren't working for me. Here's what if done.
Q1: What Processor models are these CPUs? Please. Am I correct in saying it could be this processor on ARK?
Q2: Are there any specific drivers I need to download for this platform to run Ubuntu Server? This is a clean install ontop of a HW RAID config LVM.
Here's the FULL LSHW report on pastebin.
So, from opening the chassis I know it has 2 physical Xeons, and 8GB RAM (strange 2x2GB, 2x1GB en 4x512MB RAM modules config)
The Cats in /proc/cpuinfo
dev@teamserver:~$ cat /proc/cpuinfo | grep CPU
model name  : Intel(R) Xeon(TM) CPU 3.60GHz
model name  : Intel(R) Xeon(TM) CPU 3.60GHz
model name  : Intel(R) Xeon(TM) CPU 3.60GHz
model name  : Intel(R) Xeon(TM) CPU 3.60GHz
dev@teamserver:~$ cat /proc/cpuinfo | grep process
processor   : 0
processor   : 1
processor   : 2
processor   : 3
dev@teamserver:~$ cat /proc/cpuinfo  | grep 'name'| uniq
model name  : Intel(R) Xeon(TM) CPU 3.60GHz
dev@teamserver:~$

...from lshw
dev@teamserver:~$ sudo lshw | head
teamserver
    description: System
    product: eserver xSeries 346 -[8840EHY]-
    vendor: IBM
    serial: KDPLTV7
    width: 64 bits
    capabilities: smbios-2.3 dmi-2.3 vsyscall32
    configuration: chassis=server uuid=FA66A32B-EF1D-B211-A01D-D19AA860369E

dev@teamserver:~$ sudo lshw | grep -i cpu
     *-cpu:0
          description: CPU
          product: Intel(R) Xeon(TM) CPU 3.60GHz
          bus info: cpu@0
          slot: Socket 1 CPU 1
          capabilities: fpu fpu_exception wp vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx x86-64 constant_tsc pebs bts nopl pni dtes64 monitor ds_cpl est tm2 cid cx16 xtpr lahf_lm cpufreq
     *-cpu:1
          description: CPU
          product: Intel(R) Xeon(TM) CPU 3.60GHz
          bus info: cpu@1
          slot: Socket 2 CPU 2
          capabilities: fpu fpu_exception wp vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx x86-64 constant_tsc pebs bts nopl pni dtes64 monitor ds_cpl est tm2 cid cx16 xtpr lahf_lm cpufreq

A: Perhaps try using cpuid, this provides more information.
to install it open a terminal and issue the command sudo apt-get install cpuid then cpuid to run it.

A: Try this:
cat /proc/cpuinfo | grep "model name"


Q: Turing a monolithic application into a Microservice based architecture and keeping the GIT history I'm planning to split a monolithic application into a micro service based architecture, but I want to keep the GIT history.
The monolit should be split into three micro services.
My first approach would be, copying the GIT Repository three times and removing all non domain specific parts from the new micro service which should keep the most parts of the git history alive. But I am not shure if this is the best way keeping the version control history.

A: You can use git filter-branch with the --subdirectory-filter option to filter a subdirectory of your repository and thus make the repository contain the subfolder as root directory. This is described in step 5 here, documentation here might also help. You would have to clone your repository three times and run filter-branch in each of those for a different part of your project.
Since (with said --subdirectory-filter) only subdirectories can be treated this way, you may have to rearrange your repository before. The advantage over the naive deletion of other parts is, however, that by using filter-branch you will only preseve history that concerns the actual content of your repository, and do not have any history of the parts filtered out.


Q: SignalR Hub hosted in azure misses to send message to few connections - AspNetCore.SignalR I am using Microsoft.AspNetCore.SignalR to broadcast a message to all connected clients. The Hub is hosted in Azure as App Service.
I am able to see the connected client's Connection IDs by inserting them to a table in DB.
When I hit broadcast the messages are send only to 8 out of 10 clients(Always misses few clients). The status of the missed out clients are logged as connected in DB.
My Hub Code:
public class NotificationHub : Hub
{
   public override async Task OnConnectedAsync()
   {
     ****Here I insert the connection IDs to DB with connected status***
     await Groups.AddToGroupAsync(Context.ConnectionId, "SignalRUsers_" + Context.ConnectionId);
     await base.OnConnectedAsync();
   }
}

I am calling the HubContext from outside the Hub as I need to broadcast the message on external process completion.
My Broadcaster Code:
public class SignalBroadcaster : ISignalBroadcaster
{
  private readonly IHubContext<NotificationHub> _hubContext;

  public class SignalRConnections
  {
    public string ConnectionId { get; set; }
    public DateTime ConnectedOn { get; set; }
    public string Status { get; set; }

  }

  public SignalBroadcaster(IHubContext<NotificationHub1> hubContext)
  {
    _hubContext = hubContext;
  }

  public async void BroadcastToAll(ISignal signal, TelemetryClient log)
  {
    List<SignalRConnections> lstsignalRConnections = new List<SignalRConnections>();

    try
    {
        using (SqlConnection conn = new SqlConnection(Environment.GetEnvironmentVariable("XXXXXXX")))
        {
            using (SqlCommand command = new SqlCommand("", conn))
            {
                try
                {
                    conn.Open();

                    command.CommandText = "SELECT * FROM SignalRXXXXXXX WHERE SignalRStatus = 'CONNECTED'";

                    using (var reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            SignalRConnections signalRConnections = new SignalRConnections()
                            {
                                ConnectionId = reader.GetString(0),
                                ConnectedOn = reader.GetDateTime(1),
                                Status = reader.GetString(2),

                            };

                            lstsignalRConnections.Add(signalRConnections);
                        }
                    }

                }
                catch (Exception ex)
                {
                    //command.CommandText = "INSERT INTO SignalRConnections (ConnectionId,ConnectedOn,SignalRStatus) VALUES ('" + Context.ConnectionId + "',GETDATE(),'DISCONNECTED')";
                    //command.ExecuteNonQuery();
                }
                finally
                {
                    conn.Close();
                }
            }
        }

        foreach (var item in lstsignalRConnections)
        {
            try
            {
                await _hubContext.Clients.Client(item.ConnectionId).SendAsync("ReceiveMessage", signal.JobId, signal.QuantificationResult, signal.JobType);
                log.TrackTrace("SignalR sent: " + item.ConnectionId);
            }
            catch(Exception ex)
            {
                log.TrackTrace("SignalR send failed: " + item.ConnectionId + " Exception :" + ex.ToString());
            }
        }
    }
    catch (Exception ex)
    {
      Exception exp=  new Exception(String.Format(Constants.GETDATAEXCEPTIONMESSAGE, "BroadcastToAll ", ex.InnerException));
    }

}
}

Please ignore the DB connection mess here as I am doing it for testing purpose. Will refactor later.
My client Code:
connection.on("ReceiveMessage", (user, message,msg1) => {

var msg = message.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
var encodedMsg = user + " says " + msg + msg1;
var li = document.createElement("li");
li.textContent = encodedMsg;
document.getElementById("messagesList").appendChild(li);
});
connection.start().catch(err => console.log(err));

Please help me why it is missing few clients randomly. I tried searching lot of articles and help but could not find something specific to this issue.


Q: Facebook Graph for URLs - Getting the number of shares for a group of pages How can we know the sum of all Facebook shares for all URLs that start with:
http://www.guardian.co.uk/artanddesign/
There's an API method for a specific URL that is:
https://graph.facebook.com/?ids=http://www.guardian.co.uk/artanddesign/2012/feb/19/frank-gehry-new-york-interview
But I can't make it sum all the URLs that start with
http://www.guardian.co.uk/artanddesign/.
Notes:

*

*I can't iterate trough all the URL's in the directory "artsanddesign".

*Please note that the URL's above are just examples.

*I can't access insights because I don't have permissions to add a meta-tag on the root directory of the site

*Maybe the solution is using the Facebook Query Language (FQL)? How could it work?

A: I don't believe there's any way to get information for all URLs that match a certain pattern, I think you have to specify the individual URLs manually - this shouldn't be a bug problem if it's your own site, as you'll already have a database of all possible article URLs, but if you're checking someone else's site it could be difficult.


Q: "He told me he had seen Charlie the day before" -- What's its direct speech? How can I change these sentences to direct speech?

He told me he had seen Charlie the day before.
  He said you wanted to have lunch with him the following day.

A: *

*
He said, "I saw Charlie yesterday".

*
He said, "He/She wants to have lunch with me tomorrow".

He/she refers to the participant who gets it told. The day before turns to yesterday, and the following day turns to tomorrow. Tenses are shifted one step towards future tense because of past tense in he said.


Q: cannot run the cardboard demo on iOS device I have done everything google developer website told,but the problem is Xcode still has some problems when compiling the demo project.
The problem is:ld:

/Users/Day1/Desktop/temp files/New Unity Project 3/cardboarddeomsave2/Libraries/Plugins/iOS/libvrunity.a(unity-6C9520564923BB79.o)
      does not contain bitcode. You must rebuild it with bitcode enabled (Xcode setting ENABLE_BITCODE),
      obtain an updated library from the vendor, or disable bitcode for this target. for architecture arm64
      clang: error: linker command failed with exit code 1 (use -v to see invocation)

Another thing I have realize is that, before I compile the project, the right side of the Xcode scene has one area which is red. (libiconv.2.dylib is red) Is there any correlations here?
(By the way I have upgraded my OS X to OS X EI Captian beta and my Xcode is Xcode 7.0 beta)

A: I was reaching this problem as well and this seemed to solve my problem. (It builds for me and deploys the application, but then fails to run while still connected. If I stop the connection and restart the app so that it is only running from the phone, it runs perfectly fine.)

*

*In Xcode, select the folder view in the left pane top menu and
select your project in the left pane.

*Then in the menu above the main panel, select Build Settings.

*In Build Settings, make sure that "All" is selected (not "Basic")

*Scroll down to Build Options and set "Bitcode Enabled" to NO.


Q: If $\Gamma$ is $\Lambda$-projective and $C$ is $\Gamma$-injective, then $C$ is $\Lambda$-injective. This is a problem I ran into while reading Cartan Eilenberg's Homological algebra pg 30.
Given a unital ring homomorphism $\varphi:\Lambda\to\Gamma$, I want to prove the underlined statement.

I tried to mimic the proof of 6.2, but to no avail. For convenience I cite the proof here.

My thoughts:
Because of natural isomorphism
$$\hom_\Lambda(A,C) = \hom_\Gamma(A_{(\varphi)},C),$$
where $A_{(\varphi)} = A\otimes_\Lambda \Gamma$, we only need to prove that $A_{(\varphi)}$ is an exact functor in $A$. It follows that $\hom_\Gamma(-_{(\varphi)},C) = \hom_\Lambda(-,C)$ is exact, therefore $C$ is $\Lambda$-injective. We already know that $A_{(\varphi)}$ is right exact, all that is left is to show that $i:A'\to A$ injective implies that
$$i\otimes \Gamma: A'\otimes_\Lambda \Gamma\to A\otimes_\Lambda \Gamma$$
 is injective using the fact that $\Gamma$ is $\Lambda$-projective.

A: Maybe it's helpful to explain the general principle here, because it is likely that you will encounter statements like this in many other contexts as well:
If a functor $U:{\mathscr A}\to{\mathscr B}$ between abelian categories has an exact left adjoint, then it preserves injectives. This applies to the forgetful functor $U: \Gamma\text{-Mod}\to\Lambda\text{-Mod}$ here, since its left adjoint $(-)_{(\varphi)} := \Gamma\otimes_\Lambda -$ is exact if $\Gamma$ is $\Lambda$-projective (and in fact, flatness would suffice, as user26857 said).
The dual of this statement (which is now really a formal consequence and need not be reproven) is: If $U:{\mathscr A}\to{\mathscr B}$ has an exact right adjoint, then is preserves projectives. This applies to $U$ and its right adjoint $\text{Hom}_\Lambda(\Gamma,-)$, which is exact if and only if $\Gamma$ is $\Lambda$-projective.
Also, note that relative projectivity and injectivity can be formalized in this generality: given $U: {\mathscr A}\to{\mathscr B}$ exact, call $X\in{\mathscr A}$ $U$-injective or $U$-projective if it is injective resp. projective relative to all monomorphisms resp. epimorphisms in ${\mathscr A}$ that split upon application of $U$. Then any ${\mathscr B}$-injective/projective object that is also $U$-injective/projective is also ${\mathscr A}$-projective/injective.

A: This is just a proof of the last thing you wrote.
Since $\Gamma$ is $\Lambda$-projective, $\Lambda^n \simeq \Gamma \oplus \Gamma'$ for some $n$ (possibly infinite). Thus considering $\Gamma$ as a sub-module of $\Lambda^n$, $i\otimes \Gamma$ is the restriction to $A'\otimes_\Lambda \Gamma$ of the map $i \otimes A^n: A'\otimes_\Lambda \Lambda^n \rightarrow A\otimes_\Lambda \Lambda^n$. This map is naturally identified with $i^{\oplus n}: (A')^n \rightarrow A^n$, which is injective if $i$ is. Hence its restriction to $A' \otimes_\Lambda \Gamma$ is also injective.


Q: WHat is the use of @Valid when @NonNull does the job for us? Code in controller -
@PostMapping("/employees")
    public Employee saveEmployee(@Valid @RequestBody Employee employee) {
        return employeeService.saveEmployee(employee);
    }

Entity Object -
@NotNull(message = "Department must not be null")
@Column(name = "department")
private String department;

Suppose I pass an item with a null department field. @NonNull will throw an exception in that case. But I have seen @Valid being used for the same purpose. Can somebody elaborate why @Valid needs to be used in addition to @NonNull?

A: If you omit the @Valid Spring will omit the validation on the web layer. Which basically means your controller, will not trigger validation. Validation is done by the RequestMappingHandlerAdapter when an @Valid(adted) annotation is found on an @ModelAttribute or @RequestBody annotated method argument.
JPA will also use a configured validator and trigger validation as well. So a validation exception will be thrown upon writing into the database.  You can disable this with spring.jpa.properties.javax.persistence.validation.mode=none in your application.properties (or the YAML equivalent). When disabling both no validation will be done. In that case you only hope is a database constraint that the column isn't allowed to be null.
So validation is still done but the location where the validation is done is different. Due to the difference you will also get a different exception.
You have to wonder do you really want to do this somewhere upon persisting the entity with the risk of having executed some complex/time consuming business logic, or quickly upon submission of the form.

A: So that the object can be validated in the Controller layer you need @Valid (or @Validated) to trigger its validation.
You can read more about this on the following online resources:

*

*https://www.baeldung.com/spring-boot-bean-validation

*https://www.baeldung.com/spring-valid-vs-validated
On which you can read:

Of course, the most relevant part is the use of the @Valid annotation.
When Spring Boot finds an argument annotated with @Valid, it
automatically bootstraps the default JSR 380 implementation —
Hibernate Validator — and validates the argument.


Q: LSTM Text Generation Applied on a Time Series with Keras I am currently working on time series prediction. LSTM for Regression with Time Steps subsection in the link gets me going pretty well. However, I want to predict into the further future, not only one-step ahead (i.e. predict every step into the future up to 30th step -- so a sequence generation), and text generation on LSTM networks sounds like the thing I am looking for.
To give an example for my ultimate goal, think of the famous Shakespeare text generators. I am trying to either feed all of Shakespeare's works and get a new Shakespeare "play," or complete an unfinished Shakespeare play (because he died without completing this particular work). Is there a way to translate this feature of sequence generation to time series, if so, can you point me towards any resources or examples.
Thank you.


Q: Using ostream overloading on pointers to objects So, I have a struct Bike, which looks like this
struct Bike {
    std::string brand;
    std::string model;
    bool is_reserved;

    friend std::ostream& operator<<(std::ostream out, const Bike& b);
};
std::ostream& operator<<(std::ostream out, const Bike& b) {
    return out
        << "| Brand: " << b.brand << '\n'
        << "| Model: " << b.model << '\n';
}

And another class BikeRentalService, which has a std::vector<Bike*> called bikes_m. This class also has a method print_available_bikes(), which is supposed to iterate over said std::vector<Bike*> and print each Bike by using the overloaded operator<< shown above. This method looks like that:
void BikeRentalService::print_available_bikes(std::ostream& out) {
    if (bikes_m.empty()) {
        out << "| None" << '\n';
    }
    else {
        for (auto bike : bikes_m) {
            if (!bike->is_reserved) {
                out << bike;
            }
        }
    }
}

The problem is that using this function just prints out the addresses of those Bike objects. Dereferencing the objects before using out << does not work either, Visual Studio says it can't reference std::basic_ostream because it is a "deleted function".
Writing the for loop as (auto *bike : bikes_m) does not change anything.

A: The rigth way to overload the ostream operator is as follows:
struct Bike {
    std::string brand;
    std::string model;
    bool is_reserved;

    friend std::ostream& operator<<(std::ostream& out, const Bike& b); // <- note passing out by reference
};
std::ostream& operator<<(std::ostream& out, const Bike& b) {
    return out
        << "| Brand: " << b.brand << '\n'
        << "| Model: " << b.model << '\n';
}

Also, as noted by @KyleKnoepfel you should change out << bike; to out << *bike; too.


Q: Why can I retrieve environment variable in one part of my code, but not another? I've stored an API token as an environment variable in my wsgi file. I'm able to retrieve it in one instance in my Django app, but not another.
I'm able to use the token successfully during a save_model operation in my admin. When I use nearly identical code in a management command I get an auth error.
My wsgi.py file:
import os
import sys
from django.core.wsgi import get_wsgi_application

os.environ['SLACK_TOKEN'] = '12344567890qazxswedcvfrtgbnhyujmkiolp'
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings')
application = get_wsgi_application()

Working admin.py usage:
import os
from slacker import Slacker

    def save_model(self, request, obj, form, change):
            if obj.condition == True:
                super().save_model(request, obj, form, change)
                token = os.getenv('SLACK_TOKEN')
                slack = Slacker(token)
                slack.chat.post_message('#test-channel', 'mymessage')

Not working management command usage:
import os
from slacker import Slacker

    def handle(self, *args, **options):
        try:
            #test condition
        except:
            token = os.getenv('SLACK_TOKEN')
            slack = Slacker(token)
            slack.chat.post_message('#newsflow-test', 'mymessage')

Troubleshooting indicates the env variable isn't loading -- print(token) produces None response when I run the management command or try to retrieve the token in the Django shell.

A: wsgi.py is imported by your Python application server, e.g. gunicorn. Management commands are executed directly and bypass importing wsgi.py. You should use some mechanism, e.g. django-dotenv to load environment variables from a .env file both in your manage.py script and wsgi.py application initializer.


Q: junk after document element Firefox Error Loading Content With JQuery Get I have a page (which is unfortunately behind a login system), which basically has a nav bar down the left of a list of articles, and when you click on an article, it loads the content from a .inc file stored on the server, using a provided file path.
This works fine on Google Chrome.
However, on Firefox, when the page loads, I get this weird javascript error:
"junk after document element" - When I click the error, it takes me to line 2 of the content from the first article being loaded.
Let me show you some code.
This is the last JS function which is run when the page has finished loading, and it's purpose is to load the initial article.
function initialise_family_center_page()
{
    if (current_element_id == "" || current_element_id == "family_center_general_info") //If this is the first article to be loaded
    {
        //Get the file path of the inc file to load

        var content_directory = file path....;

        jQuery.get(content_directory, function(data)
        {
            $('#family_center_main_content').html(data);    //Load the content
        });
    }
}

The content in the .inc file being loaded is as follows:

Some text

Some text

It's worth mentioning at this point, that in Chrome and Firefox, the content loads. However in firefox, because of the JS error, you can no longer use the rest of the page because the JS has stopped working.
Interesting point, which I discovered from googling the problem, is if I change the content of the file to:

Some Text

Some Text

Then the error does not appear and the page works (until you load the next content file without the  tags.
However, this is not a suitable fix because there are thousands and thousands of files.
Can anyone help?

A: I had this same problem. I had created a base page where clicking on a nav element triggered an $.ajax() fetch of an inc file that would populate the main div on the page - as follows:
$(document).ready(function(){
  // Set trigger and container variables
  var trigger = $('nav.primary ul li a'),
      container = $('#se-main');
  trigger.on('click', function(){
    // Set click target from data attribute
    target = this.target;
    $.ajax({
        url:'../inc/'+target + '.inc',
        success: function(data){
            // Load target page into container
            container.html(data);
        },
        dataType: "text" // this seems to be ignored in Firefox
    });
// snip other stuff
});

The Firefox console always logged the 'junk after document element' error unless I edited the INC files and wrapped the text in . (The page content still updated, though - so the user wasn't held up by it).
To fix this: add inc to the text/html line in the apache mime.types config file.
Find the line with
text/html                   html htm

change to
text/html                   html htm inc

Then restart apache.
That worked for me.
Default file locations:
Linux: /etc/mime.types;
WAMP: [wampdir]\bin\apache\[apacheversion]\conf\mime.types
XAMPP: [xamppdir]\apache\conf\mime.types
Where [wampdir] is wherever you installed WAMP/XAMPP, and [apacheversion] is the version of apache that WAMP is using.
This solution is no use if you don't have access to the mime.types file, or if you're running on shared hosting.
In that case - assuming that you have access to .htaccess - adding the following to .htaccess might work -
AddType text/html .html .htm .inc


Q: Can't get image from camera with intent chooser on 4.2.2 AVD I'm working on a part of my application that allows a user to select an image either from camera or from  gallery, using an Intent chooser.
It's working fine on my 2.2.1 android phone, but when i compile it on a 4.2.2 AVD it returns a null pointer error when i use the camera,
 public void onClick(View View)
{
    Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT,null);
    galleryIntent.setType("image/*");
    galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
    galleryIntent.addCategory(Intent.CATEGORY_OPENABLE);

    Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

    Intent chooser = new Intent(Intent.ACTION_CHOOSER);
    chooser.putExtra(Intent.EXTRA_INTENT, galleryIntent);
    chooser.putExtra(Intent.EXTRA_TITLE, "Chooser");

    Intent[] intentArray =  {cameraIntent};
    chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
    startActivityForResult(chooser,REQUEST_CODE);
}

protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK)
    {
    try
            {
            if (bitmap != null)
                {
                    bitmap.recycle();
                }

            InputStream stream = getContentResolver().openInputStream(data.getData());
            bitmap = BitmapFactory.decodeStream(stream);
            stream.close();
            imageView.setImageBitmap(bitmap);
            }

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

        catch (IOException e)
            {
                e.printStackTrace();
            }
    super.onActivityResult(requestCode, resultCode, data);
    }
}

this is the error i get:
05-05 05:03:31.730: E/AndroidRuntime(820): Caused by: java.lang.NullPointerException
And it said that the problem is in this line :
InputStream stream = getContentResolver().openInputStream(data.getData());

What am i doing wrong?
Updated:
Now it's working and here is the solution:
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK)
    {
        if(data.getData()!=null)
        {
            try
            {
            if (bitmap != null)
                {
                    bitmap.recycle();
                }

            InputStream stream = getContentResolver().openInputStream(data.getData());
            bitmap = BitmapFactory.decodeStream(stream);
            stream.close();
            imageView.setImageBitmap(bitmap);
            }

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

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

        else
        {
            bitmap=(Bitmap) data.getExtras().get("data");
            imageView.setImageBitmap(bitmap);
        }

        super.onActivityResult(requestCode, resultCode, data);
    }
}

Thank you for you help!

A: Hi have a try with this code.
following code is for camera button click works :
imgviewCamera.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                 //define the file-name to save photo taken by Camera activity
                String fileName = "new-photo-name.jpg";
                //create parameters for Intent with filename
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.TITLE, fileName);
                values.put(MediaStore.Images.Media.DESCRIPTION,"Image capture by camera");
                //imageUri is the current activity attribute, define and save it for later usage (also in onSaveInstanceState)
                imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                //create new Intent
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                startActivityForResult(intent, PICK_Camera_IMAGE);
            }
        });

OnActivityresult code will be like below

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Uri selectedImageUri = null;
        String filePath = null;
        switch (requestCode) {
                case PICK_Camera_IMAGE:
                     if (resultCode == RESULT_OK) {
                        //use imageUri here to access the image
                        selectedImageUri = imageUri;

                    } else if (resultCode == RESULT_CANCELED) {
                        Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show();
                    }
                     break;
            }

            if(selectedImageUri != null){
                    try {
                        // OI FILE Manager
                        String filemanagerstring = selectedImageUri.getPath();

                        // MEDIA GALLERY
                        String selectedImagePath = getPath(selectedImageUri);

                        if (selectedImagePath != null) {
                            filePath = selectedImagePath;
                        } else if (filemanagerstring != null) {
                            filePath = filemanagerstring;
                        } else {
                            Toast.makeText(getApplicationContext(), "Unknown path",
                                    Toast.LENGTH_LONG).show();
                            Log.e("Bitmap", "Unknown path");
                        }

                        if (filePath != null) {

                            Toast.makeText(getApplicationContext(), " path" + filePath,
                                    Toast.LENGTH_LONG).show();

                        Intent i = new Intent(getApplicationContext(), EditorActivity.class);
                            // passing array index
                            i.putExtra("id", filePath);
                            startActivity(i);

                        }
                    } catch (Exception e) {
                        Toast.makeText(getApplicationContext(), "Internal error",
                                Toast.LENGTH_LONG).show();
                        Log.e(e.getClass().getName(), e.getMessage(), e);
                    }
            }

    }

     public String getPath(Uri uri) {
            String[] projection = { MediaStore.Images.Media.DATA };
            Cursor cursor = managedQuery(uri, projection, null, null, null);
            if (cursor != null) {
                // HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
                // THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
                int column_index = cursor
                        .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                return cursor.getString(column_index);
            } else
                return null;
        }

dont forget to add camera permission in manifest file.
hope this will help you.


Q: In AVD emulator how to see sdcard folder and install an APK to the AVD? I have created an Android emulator (Android Virtual Device), but I am unable to find out the SD card I have built during creation of this.
How can I find the SD card and its content and also how to install APK files to the AVD?

A: These days the location of the emulated SD card is at /storage/emulated/0

A: On linux sdcard image is located in:
~/.android/avd/<avd name>.avd/sdcard.img

You can mount it for example with (assuming /mnt/sdcard is existing directory):
sudo mount sdcard.img -o loop /mnt/sdcard

To install apk file use adb:
adb install your_app.apk

A:
DDMS is deprecated in android 3.0. "Device file explorer"can be used to browse files.

A: Drag & Drop
To install apk in avd, just manually drag and drop the apk file in the opened emulated device
The same if you want to copy a file to the sd card

A: if you are using Eclipse. You should switch to DDMS perspective from top-right corner  there after selecting your device you can see folder tree. to install apk manually you can use adb command
adb install apklocation.apk

A: I have used the following procedure.
Android Studio 3.4.1
View>Tool Windows>Device File Explorer

A: *

*switch to DDMS perspective

*select the emulator in devices list, whose sdcard you want to explore.

*open File Explorer tab on right hand side.

*expand tree structure. mnt/sdcard/
refer to image below

To install apk manually:
copy your apk to to sdk/platform-tools folder and run following command in the same folder
adb install apklocation.apk

A: I have used the following procedure.
Procedure to install the apk files in Android Emulator(AVD):
Check your installed directory(ex: C:\Program Files (x86)\Android\android-sdk\platform-tools), whether it has the adb.exe or not). If not present in this folder, then download the attachment here, extract the zip files. You will get adb files, copy and paste those three files inside tools folder
Run AVD manager from C:\Program Files (x86)\Android\android-sdk and start the Android Emulator.
Copy and paste the apk file inside the C:\Program Files (x86)\Android\android-sdk\platform-tools

*

*Go to Start -> Run -> cmd

*Type cd “C:\Program Files (x86)\Android\android-sdk\platform-tools”

*Type adb install example.apk

*After getting success command

*Go to Application icon in Android emulator, we can see the your
application

A: //in linux
// in your home folder .android hidden folder is there go to that there you can find the avd folder open that and check your avd name that you created open that and you can see the sdcard.img that is your sdcard file.
//To install apk in linux
$adb install ./yourfolder/myapkfile.apk

A: Adding to the usefile DDMS/File Explorer solution, for those that don't know, if you want to read a file you need to select the "Pull File from Device" button on the file viewer toolbar. Unfortunately you can't just drag out, or double click to read.


Q: Saving variables in swing Text field I know how to make a text field but I have no idea how to take the info inputted un the text field and save it into a variable. also be able to save only after pressing enter.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

class scratch1 {
    public static void main(String args[]) {

        JFrame frame = new JFrame("Chat Frame");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);

        JPanel panel = new JPanel(); // the panel is not visible in output
        JLabel label = new JLabel("Enter Base:");
        JTextField tf = new JTextField(2); // accepts upto 2 characters
        panel.add(label); // Components Added using Flow Layout
        panel.add(tf);

        frame.getContentPane().add(BorderLayout.SOUTH, panel);
        frame.setVisible(true);
    }

A: Try this code, read the comments to understand the code. I hope this code helps you.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

class main {

    static String var; // The text input gets stored in this variable

    public static void main(String args[]) {

        JFrame frame = new JFrame("Chat Frame");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);

        JPanel panel = new JPanel();
        JLabel label = new JLabel("Enter Base:");
        JTextField tf = new JTextField(2);
        panel.add(label);
        panel.add(tf);

        frame.getContentPane().add(BorderLayout.SOUTH, panel);
        frame.setVisible(true);

        tf.addActionListener(new ActionListener() { // Action to be performed when "Enter" key is pressed
            @Override
            public void actionPerformed(ActionEvent e) {
                var = tf.getText(); // Getting text input from JTextField(tf)
            }
        });
    }
}


Q: Allow others to develop plugins for my app I'm developing a home screen replacement for Android with search functionality in the app drawer. I not only want to allow (not force) users to search for installed apps, but also other content like Stack Overflow, Wikipedia or their local files.
Currently I'm developing these so-called "Lenses" myself, but I thought it'd be a cool idea if others could develop them as well. So what I'm wondering is if there's any way to allow other developers to do just that; Developing additional lenses for my app.
All lenses should inherit from the following class;
Lens.java
public abstract class Lens
{
    protected Context context;

    protected Lens (Context context)
    {
        this.context = context;
    }

    public abstract List<LensSearchResult> search (String str) throws IOException, JSONException;

    public abstract String getName ();

    public abstract String getDescription ();

    public void onClick (String url)
    {
        if (url.startsWith ("http://") || url.startsWith ("https://"))
        {
            Intent intent = new Intent (Intent.ACTION_VIEW);
            intent.setData (Uri.parse (url));

            this.context.startActivity (intent);
        }
        else
        {
            throw new UnsupportedOperationException ();
        }
    }

    public void onLongPress (String url)
    {
    }

    protected String downloadStr (String url) throws IOException, JSONException
    {
        // Not important. Provided for convenience.
    }

    protected Drawable downloadImage (String url) throws IOException, JSONException
    {
        // Not important. Provided for convenience.
    }
}

The developer should pass Context from their constructor to the superclass, implement List<LensSearchResult> search (String str), String getName (), and String getDescription (). If we're talking about a URL, that's all they need to do. Otherwise they should also override void onClick (String url) and if they wish to do so void onLongPress (String url).
That's basically what a "Lens" would consist of.
So what would I have to do (if at all possible) to make it possible for other developers to create "Lenses" for my app? Ideally they would be able to distribute them in, for example, the Google Play Store, but if necessary I can develop my own platform where others could upload their lenses. Either way I'd still need some way to run someone else's code from within my app.

A:
If you can think of a better way (perhaps like what DashClock does) I'm all ears :)

Design your API around IPC. Have third-party plugins implement a Service, a ContentProvider, and/or a BroadcastReceiver that your host app works with. While a bound service using AIDL would seem to be the most natural way of converting your existing API to one that uses IPC, bound services for plugins have all sorts of issues (e.g., API versioning) that are messy to deal with over time.
In your own app, you might wrap the low-level IPC plumbing in some classes that resemble your existing API. And if you wanted to have third-party developers use some library that you publish to have them create their plugins, you're welcome to do that too. You'll want to create a few plugins yourself, to test out your API and provide samples for third-party developers.
Given all of that, there are any number of ways that you can discover when plugins are installed and removed. ACTION_PACKAGE_ADDED and ACTION_PACKAGE_REMOVED broadcasts, for example, can tell you when other apps are added and removed. You can then use PackageManager to see if they are one of your plugins (e.g., do they implement your IPC endpoint?). Or, use methods on PackageManager like queryIntentServices() to poll for plugin implementations, if that makes more sense.

A: An actual app that uses plugins might give you ideas. Here is the plugin developer page of an app that uses them:
http://www.twofortyfouram.com/developer


Q: Factorial with names Ok so, I have had an argument with my teacher over 1 quiz question that was marked wrong in my data management class.
Question.
Determine the number of ways that 12 members of the boys' baseball team can be lined up if Joe, Tanner, Josh must all be together.
I wrote the answer as 10! x 3 so 10,886,400.
My teacher had it as 10! x 3 x 2 so 21,772,800
If my answer is wrong, can someone explain to me how he got that 'x 2'?

A: The $10!$ comes from treating the three boys as one and so we are now considering 10 boys and asking how to line them up. However, in the grouping of the three boys, they can be permuted among themselves in $3! = 3 \times 2$ ways.

A: You would be right if Joe and Josh were identical twins.  One way to think about it is you have a block of $3$ boys who can be placed in any of the $10$ spaces between or to either side of the other $9$, so the answer is $3! \cdot 9! \cdot 10$.


Q: AVR USART Not Receiving I have connected my AVR USART to file stream so as to make it easy to send formatted strings on ATmega8
From the AVR, I can send(TX) just fine. However, I am not receiving anything. Can't put my hand on it but it looks like I'm overlooking something very basic.
uart.c
#define FOSC 8000000
#define BAUD_RATE 38400
#define UBRR_VALUE (uint16_t)(FOSC/16/BAUD_RATE-1)

#include "uart.h"

FILE uart0_str = FDEV_SETUP_STREAM(UARTSendByte, UARTReceiveByte, _FDEV_SETUP_RW);

void UART_INIT(void)
{
    UBRRH = (uint8_t)(UBRR_VALUE>>8); //set UBRR register
    UBRRL = (uint8_t)UBRR_VALUE;
    UCSRC = (1<<URSEL) | (1<<UCSZ1) | (1<<UCSZ0) | (1<<USBS);//set frame format: asynchronous,8data,2 stop,no parity
    UCSRB = (1<<TXEN) | (1<<RXEN) ;
    _delay_ms(10);

    stdin=&uart0_str;
    stdout=&uart0_str;
}

void UART_WRITE_STRING(char* str)
{
    printf("%s",str);

}

int UARTSendByte(char u8data, FILE *stream)
{
    if(u8data=='\n')
    {
        UARTSendByte('\r',stream);
    }
    while(!(UCSRA&(1<<UDRE))){};
    UDR = u8data;
    return 0;
}

int UARTReceiveByte(FILE *stream)
{
    printf("hello1\r");
    UART_WRITE_STRING("hello1\r");
    uint8_t data;
    // Wait for byte to be received
    while(!(UCSRA&(1<<RXC))){};
    data=UDR;
    //echo input data
    UARTSendByte(data,stream);
    // Return received data
    return data;
}

main.c
#include "uart.h"
#include "twi.h"
#include "ds1307.h"

void bootCode(void);

int main (void)
{
    DDRC = 0x01; //set PC0 as output
    PORTC = 0x01; //turn on PC0
    DDRD = 0x02; //PD0 = RXD = INPUT,PD1 = TXD = OUTPUT

    UART_INIT(); //initialize UART
    TWI_INIT(); //initialize TWI

    UART_WRITE_STRING("ANKIT.*****@GMAIL.COM\r");
    UART_WRITE_STRING("JUNE 16, 2014\r");
    UART_WRITE_STRING("####################################\r\r\r\r");

    while(1)
    {

    };
}

When I run this, I get the printed strings, but there is no response whatsoever to the text I input.
when I send the text, ideally it should be echoed back on the terminal + I should also get the "hello1" strings hard-coded in the UARTReceiveByte function
UPDATE
While looking at my code I had another thought.
Since I am binding my USART input and output to the standard file streams => if in order to TX from AVR I need to use "printf". By the same logic, the data entered from my PC terminal will not be valid unless there is a "scanf" call in my code.
So as a test, I added a line in my main.c before the infinite loop
unit8_t d;
scanf("%c",&d);

Now when I enter something at the terminal i do get "hello1" 2 times printed on the terminal (as coded in the UARTReceiveByte function).
As a side question, while I am using FILE streams, can I also use USART interrupts?

A: As suggested in the comments, there was no call to the USARReceiveByte function for the lack of any scanf statement. This solved the issue.


Q: Collating multiple images into one, programmatically I have 41 PDF pages converted into PNGs that I need to collate as one long vertical image, in order.
I can't do this manually because I have roughly a thousand other sets of 41 images, I need to create an automated procedure.

A: Install the package named imagemagick:
sudo apt-get install imagemagick

Now you can use the tool called convert:
convert -append input1.jpg input2.jpg inputn.jpg out.jpg

or you can use to append all images
convert -append *.jpg out.jpg

A: I had the same issue, but I used
convert -adjoin *.jpg outputfile.pdf

I hope this help another users.


Q: Google Play is showing wrong API level After uploading my APK in Google Play it shows in APK details :

API levels : 14-17

and publicly showing "4.0 and up" in play store.
Although my previous version has API levels 14+ but i changed my app and set following minSDK and targetSDK:
<uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="12"
        android:maxSdkVersion="17"/>

But after uploading new APK GOOGLE PLAY is showing wrong API level. It shows "API levels : 14-17". I am tired about this fact. Why not it shows 11-17 and publicly "3.0 and up".
Would anybody knows the real fact ?


Q: How do I convert list to table in Excel 2003 I have a list:
    date  item name    quantity
1.7.2014    A              5
1.7.2014    B              2
1.7.2014    C              10
2.7.2014    B              5
3.7.2014    A              1
4.7.2014    A              7

I want this list as below table in excel
ITEM NAME    1.7.2014     2.7.2014     3.7.2014       4.7.2014
A               5                        1               7
B               2            5
C               10

How do I do this?

A: As suggestes by @Sathya, use pivot tables as explained by Microsoft in this article.
Long story short:

*

*Select your list

*Insert a pivot table (Insert --> Pivot table or Data --> Pivot table, depending on your Excel version).

*With your cursor inside the pivot table, put the Item name in the Column labels, Date in Row labels and Quantity in Values (select Sum to sum all quantities for the same date/item name combination).

A: I would use the Power Query Add-In for this. It has a Pivot command that should achieve what you want:
http://www.microsoft.com/en-us/powerBI/bi-blog.aspx?blog=91d46819-8472-40ad-a661-2c78acb4018c%3A10553536&WT.mc_id=OO_PowerQuery_Update#pivot
I've built a solution to a similar problem which you can view or download - its "Power Query demo - Pivot rows into columns.xlsx" in my One Drive:
https://onedrive.live.com/redir?resid=4FA287BBC10EC562%21398


Q: D8: Program type already present: com.MyCompany.Game.BuildConfig I get this error after i add GoogleMobileAds plugin into my project. I have shared codes of AndroidManifest.xml of GoogleMobileAds plugin. Can anyone please help ?
(UnityEngine.GUIUtility:processEvent(Int32, IntPtr) (at C:/buildslave/unity/build/Modules/IMGUI/GUIUtility.cs:179))

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools"
          package="com.MyCompany.Game" android:versionName="1.0" android:versionCode="1">
  <uses-permission android:name="android.permission.INTERNET" />
  <uses-sdk android:minSdkVersion="19" android:targetSdkVersion="28" />
  <application>
    <uses-library android:required="true" android:name="org.apache.http.legacy" />
    <activity
      android:isGame="true"
      android:hardwareAccelerated="true"
      android:name="com.unity3d.player.UnityPlayerNativeActivity" android:label="@string/app_name">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
      <meta-data android:name="unityplayer.UnityActivity" android:value="true" />
      <meta-data android:name="unityplayer.ForwardNativeEventsToDalvik" android:value="true" />
    </activity>
    <meta-data android:name="com.google.android.gms.ads.APPLICATION_ID" android:value="ca-app-pub-1010101010101010~1010101010" />
  </application>
</manifest>


Q: For Azure Data Factories is there a way to 'Validate all' using powershell rather than the GUI?
*

*A working Azure Data Factory (ADF) exists that contains pipelines with activities that are dependent on database tables

*The definition of a database table changes

*The next time the pipeline runs it fails

*Of course we can set up something so it fails gracefully but ...

*I need to proactively execute a scheduled Powershell script that iterates through all ADFs (iterating is easy) to do the equivalent of the 'Validate All' (validating is impossible?) functionality that the GUI provides

*I do realise that the Utopian CI/CD DevOps environment I dream about will one day in the next year or so achieve this via other ways

*I need the automation validation method today - not in a year!

I've looked at what I think are all of the powershell cmdlets available and short of somehow deleting and redeploying each ADF (fraught with danger) I can't find a simple method to validate an Azure Data Factory via Powershell.
Thanks in advance

A: In the ".Net" SDK, each of the models has a "Validate()" method.  I have not yet found anything similar in the Powershell commands.
In my experience, the (GUI) validation is not foolproof.  Some things are only tested at runtime.

A: I know it has been a while and you said you didn't want the validation to work in an year - but after a couple of years we finally have both the Validate all and Export ARM template features from the Data Factory user experience via a publicly available npm package @microsoft/azure-data-factory-utilities. The full guidance can be found on this documentation.


Q: how to delete a saved project in Advanced REST client standalone app? I'm trying to delete unused projects in ARC as they are stacking up. I couldn't find any setting related to this.
I found deleting an API call in ARC standalone app(how to delete a saved request in chrome's arc (Advanced REST Client) extension?) but not for saved project

A: I found it upon clicking kebab menu (vertical ellipsis) next to the project I want to delete and selected 'open details' and then there is 'delete project' button


Q: How to open specific web browsers using hyperlinks? I have a simple app which contains a link, I want on mobile apps eg LinkedIn  people to click this link and open it in a browser eg safari
I tried this
May open on Safari'

When I click this link it opens in a native LinkedIn app browser in iPhone
what do I need to change to get this working?

A: The browser that gets used is a user setting on the device based on what they have installed, not something you can control.  Best you can do is recommend that it works best in Safarior or whichever browser.

A: Excerpt from Quora:
The short answer you can't specify that a specific browser will be opened by a hyperlink.
If you are viewing a web page or an app or something that shows a hyperlink and you click on that link then the operating system will receive an event that indicates a hyperlink was launched. It will then look for the default browser, launch that browser and then pass the URL to the browser.
You can change the default browser at any time but the operating system will only open that specify browser.
If you were really determined you might be able to write multiple browser launcher browsers that you would register with the operating system. Then any time you clicked on a link your browser would launch and you could present yourself with a list of alternative browsers to open the link with.
FYI Safari has an option to open the current web page in another browser. It is in menu bar near developer tools.

A: you can configure the edge browser such way- but i couldnt found any solution for other browsers
May open on edge'


Q: Set builder modular arithmetic I have a set C which is defined as: $$ C= \{ (x|x\in \mathbb  Z^+) \land ( x \pmod 3 < 2)    \} $$
To find such an x, we have: $x = 3n + 1$
But what am I limited to in this case? if $ n=1  $ then $x=4$. But am I limited to positive integers less than two? Meaning:  $C=\{4\}$
I'm a little confused here.

A: $C=\{1,3,4,6,7,9,10,12,13,15,16,18,19,21,22,24,25,\dots\}$,
all positive integer $x$ belongs there which is of the form $3n$ or $3n+1$, i.e. $x \ {\tt mod}\, 3=0$ or $1$.


Q: Django: How to show the updated information on the page without reloading I am working in Djnago and I want to update the information without reloading the page. At first, I have used Ajax for post method so that the page should not reload after submitting the form, and it is working properly. Then I used Ajax for get method, and it is working too but to see the new information on the page, I have to refresh the page.
The view.py file:
def bfs_view(request):
    form = BFSForm(request.POST or None)
    if form.is_valid():
        form.save()
        form = BFSForm()
    try:
        image_url_info = None
        num_states_explored = None
        final_solution = None

        text_file = open("BFS\outputs\maze.txt", "w")
        field_name = 'description'
        input_value = BFS.objects.latest('id')

        field_object = BFS._meta.get_field(field_name)
        field_value = field_object.value_from_object(input_value)

        field_string_value = str(field_value).split("\n")

        text_file.writelines(field_string_value)
        text_file.close()

        m = Maze("BFS\outputs\maze.txt")
        print("Maze:")
        m.print()
        print("Solving...")
        m.solve()
        print("States Explored:", m.num_explored)
        print("Solution:")
        m.print()

        image_url_info = "/../../../static/search/bfs/maze.png"
        num_states_explored = m.num_explored

        # final_solution = ''.join(m.end_result)
        final_solution = str(''.join(m.end_result))
        print(''.join(m.end_result))

        # BFS.objects.latest('id').delete()
    except:
        print("BFS ERROR: Error in the try session of BFS in view.py")

    context = {
        'form': form, 'image_url': image_url_info, 'states_explored': num_states_explored,
        'solution': final_solution}

    return render(request, "BFS/bfs.html", context)

def post_bfs_view(request):
    if request.method == "POST" and request.is_ajax():
        bfs_view(request)
        return JsonResponse({"success":True}, status=200)
    return JsonResponse({"success":False}, status=400)

def get_bfs_view(request):
    if request.method == "GET" and request.is_ajax():
        try:
            image_url_info = None
            num_states_explored = None
            final_solution = None

            text_file = open("BFS\outputs\maze.txt", "w")
            field_name = 'description'
            input_value = BFS.objects.latest('id')

            field_object = BFS._meta.get_field(field_name)
            field_value = field_object.value_from_object(input_value)

            field_string_value = str(field_value).split("\n")

            text_file.writelines(field_string_value)
            text_file.close()

            m = Maze("BFS\outputs\maze.txt")
            m.print()
            m.solve()
            print("States Explored:", m.num_explored)
            print("Solution:")

            # final_solution = ''.join(m.end_result)
            final_solution = str(''.join(m.end_result))
            print(''.join(m.end_result))
            # bfs_view(request)

            # BFS.objects.latest('id').delete()
            bfs_view(request)
        except:
            print("BFS ERROR: Error in the try session of BFS in view.py")
    return HttpResponse(final_solution)

The main bfs.html file:
 <form id = "contactForm" method='POST' >{% csrf_token %}
   {{ form.as_p }}
   <input type='submit' value='Search' class="submit-btn poppins"/>
</form>

"The value is: "

The Ajax for post operation:

The Ajax for get operation:

The urls.py file:
app_name = 'BFS'

urlpatterns = [
    path('bfs/', bfs_view),
    # path('ajax/get_user_info', get_bfs_view, name='get_user_info'),
    path('ajax/contact', post_bfs_view, name ='contact_submit'),
    path('ajax/get_user_info', get_bfs_view, name = 'get_user_info'),
]

The models.py file:
from django.db import models
from django.urls import reverse
# Create your models here.

class BFS(models.Model):
    description = models.TextField(blank=True, null=True)

    def __str__(self):
        return self.description

The forms.py file:
from django import forms
from .models import BFS

class BFSForm(forms.ModelForm):
    description = forms.CharField(
                        required=False,
                        label=False,
                        widget=forms.Textarea(
                                attrs={
                                    'id': 'TA1',
                                    'rows': '10vh',
                                    'cols': '8vw',
                                    'placeholder': 'Enter Your Map Here',
                                    'class': 'textfield-style',
                                    'style': 'max-width: 100%; max-height: 100%;outline: none; border: none; background-color: white; width: 100%; padding: 12px 20px; margin: 8px 0; box-sizing: border-box; font-size: 20px; spellcheck="false";',
                                }
                            )
                        )

    class Meta:
        model = BFS
        fields = [
            'description'
        ]

    def __init__(self, *args, **kwargs):
        super(BFSForm, self).__init__(*args, **kwargs)
        for field in self.fields:
            self.fields[field].widget.attrs.update({
            'class': 'form-control'})

A: I'd suggest you wrapping what you have used to get the update in a function then do the function call after you hit the success method after submitting the form...
In your js for example:
$(document).ready(function(){
     $("#contactForm").submit(function(e){
         // prevent from normal form behaviour

         e.preventDefault();
         // serialize the form data

         var serializedData = $(this).serialize();
         $.ajax({
             type : 'POST',
             url :  "{% url 'BFS:contact_submit' %}",
             data : serializedData,

             success : function(response){
                 //reset the form after successful submit
                 $("#contactForm")[0].reset();

                 // This will then call for the get request to update the id "myText"
                 live_update();
             },

             error : function(response){
                console.log(response)
             }
        });
    });

    function live_update(){
        $.ajax({
            url: "{% url 'BFS:get_user_info' %}",
            type: 'get', // This is the default though, you don't actually need to always mention it

            success: function(data) {
                var number = data;
                document.getElementById("myText").innerHTML = number;
            },

            error: function() {
                alert('Got an error dude');
            }
       });
    }
 });

Also, for the success method within the live_update function... You could also use,
success: function(data) {
    $("#myText").hide();
    $("#myText").html(data);
    $("#myText").fadeIn(1000);
},

That should give it a nice little fade in effect as it updates. :)

A: This might be the time to introduce a frontend framework to your pipeline as it will make life easier to refresh pages upon DOM state changes. I had challenges myself trying to implement similar functionality with Django alone some years back until i introduced React Js.
Here is something that could help you without learning another software altogether:
Update DOM without reloading the page in Django
However, you will notice that the marked answer there still uses Javascript i.e jQuery. So there is no denying the fact that you will need to implement javascript to achieve what you want.
Which is why i mentioned React Js.
Good luck!


Q: MAAS: Failing commissioning (Ubuntu 14.04 MAAS 1.8.3) I have spent days on this. It's likely something simple. I've tried booting from ISO and creating MAAS, I've tried clean installing and following the openstack instructions for a clean install of ubuntu. Never any luck. When I go to commission a node, the machine turns on, and sits at commissioning.  When I look at the node it PXE boots but that's about it. I've confirmed DNS appears to be ok (though there is no dns entry for the node-1 but a query for maas returns the correct IP) This is all running under vSphere 6.
First and foremost... here are the logs from the node:
cloud-init.log: http://pastebin.com/4XbcnbZB
clout-init.output.log: http://pastebin.com/nWZEc56r
Here are the warnings I see in cloud-init.log:

2016-01-03 22:00:01,156 - util.py[WARNING]: Failed accessing user data.
2016-01-03 22:00:03,398 - util.py[WARNING]: Running seed_random () failed
2016-01-03 22:00:03,523 - cc_resizefs.py[WARNING]: Device 'overlayroot' did not exist. cannot resize: dev=overlayroot mnt_point=/ path=/

Now for the controller... I see a bunch of WARNINGS in maas.log:

Jan  3 15:52:47 head maas.start-up: [WARNING] Database error during start-up (PostgreSQL error 40P01); pausing for 3 seconds.
Jan  3 15:52:47 head maas.import-images: [WARNING] I/O error while syncing boot images. If this problem persists, verify network connectivity and disk usage.
Jan  3 15:52:47 head maas.import-images: [WARNING] Finished importing boot images, the region does not have any boot images available.
Jan  3 15:52:49 head maas.start-up: [WARNING] Database error during start-up (PostgreSQL error 40P01); pausing for 3 seconds.
Jan  3 15:57:42 head maas.import-images: [WARNING] I/O error while syncing boot images. If this problem persists, verify network connectivity and disk usage.
Jan  3 15:57:42 head maas.import-images: [WARNING] Finished importing boot images, the region does not have any boot images available.
Jan  3 16:02:41 head maas.import-images: [WARNING] I/O error while syncing boot images. If this problem persists, verify network connectivity and disk usage.
Jan  3 16:02:41 head maas.import-images: [WARNING] Finished importing boot images, the region does not have any boot images available.

Now on the MAAS web page, it shows a valid image. On the clusters page it says connected and images are synced so those warnings could just be boot warnings? I'm really not sure what to try next.

A: This seems like a network communication issue. Looking at cloud-init logs:
Jan  3 22:00:03 ubuntu pollinate[750]: ERROR: Network communication failed [60]\n22:00:02.333112 * Hostname was NOT found in DNS cache
Also, looking at maas.log:
Jan 3 16:02:41 head maas.import-images: [WARNING] I/O error while syncing boot images. If this problem persists, verify network connectivity and disk usage.
If you are behind a proxy, this could be an issue. Can you verify that you have access to archive.ubuntu.com as well?


Q: Bash running python inline in shell script still not working I am on Windows and using GitBash to run shell scripts in bash that run python scripts.
I'm trying to run python inline in a bash shell script using the answer from How to execute Python inline from a bash shell.
I'm using a specific python environment, and the path is defined with an alias.
This is a file called .pyalias:
alias mypython='C:/users/name/mypath/python.exe test.sh'

This is a file called test.sh:
# misc notes at top, like a docstring
print("Hello")
# real file will instead say myPyScript.py etc.

Here is the problem: This is a file called main_run_all.sh:
# misc notes at top, like a docstring

shopt -s expand_aliases
source ./.pyalias

mypython test.sh

mypython -c print("Hello Again")

When I run sh main_run_all.sh, it prints "Hello" to the console (good, it is successfully running the test.sh script), but then it doesn't run the inline command, returning the following error:
test.sh: line 8: syntax error near unexpected token `('
test.sh: line 8: `mypython -c print("Hello Again")'

A: You need to put the python code in quotes so the shell doesn't try to parse it like shell code:
mypython -c 'print("Hello Again")'
# ..........^....................^

If you get python code that contains both double and single quotes, quoting can be a real pain. That's the point when you use a quoted here-doc:
python <<'END_PYTHON'
print("Hello")
print('World')
END_PYTHON


Q: Code I have written for Burger, Coca and Salad price calculation doesn't work I have written a code to calculate Burger, Coca and Salad price. The code should return a number (or a factor) based on the number or each ordered item. I can't figure out which part of the code is not right. it doesn't work when I change the number of items.

var BurgNum = document.getElementById('Bnum').value,

  CocNum = document.getElementById('Cnum').value,

  SalNum = document.getElementById('Snum').value,

  Totalprice;

function getValue(n) {
  return n >= 2 && n < 5 ? n * 0.9 : n == 0 ? 0 : n == 1 ? 1 : n - 1;
}
var XBurgNum = getValue(BurgNum);
var XCocNum = getValue(CocNum);
var XSalNum = getValue(SalNum);

Totalprice = XBurgNum * 10 + XCocNum * 5 + XSalNum * 4
document.getElementById('price').value = Totalprice;

How many Burgers you want to order? <input type="number" id="Bnum" value="0" onchange="getValue(n);"></input>

 How many Cocas you want to order? <input type="number" id="Cnum" value="0" onchange="getValue(n);"></input>

 How many Salads you want to order? <input type="number" id="Snum" value="0" onchange="getValue(n);"></input>

 Price: <input type="number" id="price" readonly="readonly"></input>

A: That is because you are not calling right statement on 'onchange' event. You just call the getVAlue(n) function which does nothing except return a value that you also use for
 var XBurgNum = getValue(BurgNum);
 var XCocNum = getValue(CocNum);
 var XSalNum = getValue(SalNum);

But you are not updating the output on change event.

A: You are calling a function onchange which returns a value, but does nothing with it.  Instead, your onchange function can get the values needed for the calculation and update the price accordingly.

var burg = document.getElementById('Bnum'),
    coc = document.getElementById('Cnum'),
    sal = document.getElementById('Snum'),
    totalPrice = 0;

document.getElementById('price').value = totalPrice;

var updatePrice = function() {

    var burgNum = burg.value,
    cocNum = coc.value,
    salNum = sal.value;

    var xNums = [];

    [burgNum, cocNum, salNum].forEach(function(n, i) {
       xNums[i] = (n >= 2 && n < 5) ? n * 0.9 : n == 0 ? 0 : n == 1 ? 1 : n - 1;
    });

    totalPrice = xNums[0]*10 + xNums[1]*5 + xNums[2]*4;

    document.getElementById('price').value = totalPrice;
}
How many Burgers do you want to order?
<input type="number" id="Bnum" value ="0" onchange="updatePrice()"/>

How many Cocas do you want to order?
<input type="number" id="Cnum" value ="0" onchange="updatePrice()"/>

How many Salads do you want to order?
<input type="number" id="Snum" value="0" onchange="updatePrice()"/>

Price:
<input type="number" id="price" readonly="readonly"/>

A: Try this, It will help you...

function getValue(val)
{
 var BurgNum = parseInt(document.getElementById('Bnum').value);
 var CocNum = parseInt(document.getElementById('Cnum').value);
 var SalNum = parseInt(document.getElementById('Snum').value);
 BurgNum = (BurgNum>=2 && BurgNum<5)?BurgNum*0.9:(BurgNum<2)?BurgNum:BurgNum-1;
 CocNum = (CocNum>=2 && CocNum<5)?CocNum*0.9:(CocNum<2)?CocNum:CocNum-1;
 SalNum = (SalNum>=2 && SalNum<5)?SalNum*0.9:(SalNum<2)?SalNum:SalNum-1;
 Totalprice = BurgNum*10 + CocNum*5 + SalNum*4;
 document.getElementById('price').value = (Totalprice>0 && Totalprice!=='NaN')?Totalprice:0;
}

 How many Burgers you want to order? <input type="number" id="Bnum" value ="0" onChange="getValue(this.value);"></input>

 How many Cocas you want to order? <input type="number" id="Cnum" value ="0" onChange="getValue(this.value);"></input>

 How many Salads you want to order? <input type="number" id="Snum" value="0" onChange="getValue(this.value);"></input>

    Price: <input id="price" readonly="readonly"></input>

Happy Coding...


Q: No hard drive detected on compaq presario m2000 (IDE hard disk) My laptop crashed. At first I thought it was a hard disk problem. I bought a new one but the computer keeps telling me that no hard drive is detected.
I have tried to install Windows XP SP2/3, windows7, Ubuntu and Fedora but I still get the same problem.
I have a tough time with this laptop and I just can't figure out what is wrong with it.  Every other component seems to be working just fine.

A: check very carefully how the hard drive is plugged in.
the hard drive plugs into a connector which plugs into the motherboard.
i have a similar problem all the time.
in the end i bought some double sided sticky tape
and just taped the hard drive to the motherboard.


Q: Compare integers by using for loop I'm python newbie and got a problem while doing some practices.
Below is the code that I've got so far:
def gt(nums, n):
    for c in nums:
        if n < c:
            return True
        elif c < n:
            return False
        else:
            break

With above code, it does not return properly.
The examples of correct answers here:
gt([1,2,3],3) => False
gt([1,2,3],2) => True

A: A simpler and more readable solution would be the following:
def gt(lst, n):
    return max(lst) > n

A: using a one liner
def gt(nums, n):
    return any(e > n for e in nums)

this breaks when the first element bigger than n is found.

A: Long-ish response to Niklas B.'s comment:
I decided to test this, and here are the results. Blue dots are your function, green are Mario's; y axis is runtime in seconds, x axis is len(nums).

As you said, both are O(n). Yours is faster up to about 45 items; for anything over 100 items, his is roughly twice as fast.
It's mostly irrelevant - this seems to be more of a beginner syntax question than anything else - and, as you say, Python isn't a speed demon to begin with. On the other hand, who doesn't like a bit more speed (so long as readability doesn't suffer)?
For those interested, here's the code I wrote to test this:
from random import randint
from timeit import Timer
import matplotlib.pyplot as plt

def gt1(nums, n):
    # based on Niklas B.'s answer - NOTE comparison is corrected
    return n < max(nums)

def gt2(nums, n):
    # based on Mario Fernandez's answer
    return any(e > n for e in nums)

def make_data(length, lo=0, hi=None):
    if hi is None:
        hi = lo + length - 1
    elif lo > hi:
        lo,hi = hi,lo
    return [randint(lo, hi) for i in xrange(length)]

def make_args(d):
    nums = make_data(d)
    n = randint(0,d)
    return "{}, {}".format(nums, n)

def time_functions(fns, domain, make_args, reps=10, number=10):
    fns = [fn.__name__ if callable(fn) else fn for fn in fns]
    data = [[] for fn in fns]
    for d in domain:
        for r in xrange(reps):
            args = make_args(d)
            for i,fn in enumerate(fns):
                timer = Timer(
                    setup='from __main__ import {}'.format(fn),
                    stmt='{}({})'.format(fn, make_args(d))
                )
                data[i].extend((d,res) for res in timer.repeat(number=number))
    return data

def plot_data(data, formats=None):
    fig = plt.figure()
    ax = fig.add_subplot(111)
    if formats is None:
        for d in data:
            ax.plot([x for x,y in d], [y for x,y in d])
    else:
        for d,f in zip(data, formats):
            ax.plot([x for x,y in d], [y for x,y in d], f)
    plt.show()

def main():
    data = time_functions([gt1, gt2], xrange(10, 501, 10), make_args)
    plot_data(data, ['bo', 'g.'])

if __name__=="__main__":
    main()

A: This could be better
def gt(nums, n):
    for c in nums:
       if n < c:
            return True

    return False


Q: How can I give an interval for a react application I am using react with antd framework. I have created a form and handling the submit:
My forms.js:
import React from 'react';
import { Form, Input, Button, notification } from 'antd';
import axios from 'axios';

class CustomForm extends React.Component {

    handleFormSubmit  = (event, requestType, articleId) => {
        const title = event.target.elements.title.value;
        const content = event.target.elements.content.value;

 notification.open({

        message: 'Success',
    description:
    'Your Response is submitted',
            onClick: () => {
              console.log('Notification Clicked!');
    },
    onCancel: () => {

   }
});

        // eslint-disable-next-line
        switch (requestType) {
            case 'post':
                return axios.post('http://localhost:8000/api/', {
                    title:title,
                    content:content
                }
                )
                .then (res => console.log(res))
                .catch(err => console.error(err))
            case 'put':
                return axios.put(`http://localhost:8000/api/${articleId}/`, {
                    title:title,
                    content:content
                })
                .then (res => console.log(res))
                .catch(err => console.error(err))
        }
    }

    render(){
        return (
            <div>
                <Form onSubmitCapture={(event) => this.handleFormSubmit(event, this.props.requestType, this.props.articleId)} >
                    <Form.Item label="Title">
                    <Input name='title' placeholder="Input some title" />
                    </Form.Item>
                    <Form.Item label="Content">
                    <Input name='content' placeholder="Input some content" />
                    </Form.Item>
                    <Form.Item>
                    <Button type="primary" htmlType='submit' >{this.props.btntext}</Button>
                    </Form.Item>
                </Form>
            </div>
        )
    }
};

export default CustomForm;

Using this I can get input from the user and show a success notification. But I want to reload my page after 5 seconds when I get the notification when I try to use this code window.location.reload(true)  in my handleFormSubmit it is not allowing the notification to take place.

A: You can use setTimeout(() => window.location.reload(true), 5000); this code


Q: There is any way to encapsulate a SOAP object using WebClient framework?   <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <soapenv:Header>
      <ns1:Security xmlns:ns1="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" soapenv:actor="http://schemas.xmlsoap.org/soap/actor/next" soapenv:mustUnderstand="0">
         <ns1:UsernameToken>
            <ns1:Username>XXXXX</ns1:Username>
            <ns1:Password>XXXXXX</ns1:Password>
         </ns1:UsernameToken>
      </ns1:Security>
   </soapenv:Header>
   <soapenv:Body>
      <consultarPosicaoCotistaOnOfflineFundoRequest>
         <filtro>
            <cdCotista>2780008158</cdCotista>
            <icSnUltimaPosicao>S</icSnUltimaPosicao>
            <ictpSaldo>F</ictpSaldo>
         </filtro>
      </consultarPosicaoCotistaOnOfflineFundoRequest>
   </soapenv:Body>
</soapenv:Envelope>

I am trying to consume a webservice and I need to send in the body of my request this soap object above ... but I got this error below:
Content type 'text/xml;charset=UTF-8' not supported for bodyType=com.sun.xml.messaging.saaj.soap.ver1_1.Message1_1Impl

And that's the function I am trying to use:
Mono<String> monoResponse =  webClient()
                .post()
                .header("SOAPAction", "")
                .header("User-Agent", "Apache-HttpClient/4.5.5 (Java/12.0.1)")
                .header("Content-Type", "text/xml;charset=UTF-8")
                .accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML)
                .acceptCharset(Charset.forName("UTF-8"))
                .bodyValue(soapMessage)
                .retrieve()
                .bodyToMono(String.class);

        monoResponse.block();

By any chance Do I can send this object through this way?!

A: The namespace https://www.w3.org/2003/05/soap-envelope/ is SOAP 1.2, for which the correct content-type is application/soap+xml. Try changing the specified content type to this value. Content type text/xml is correct for SOAP 1.1.


Q: Get value of INT for a "STRING" variable I need output like
0 - os.O_APPEND     - 1024
1 - os.O_CREATE     - 64
2 - os.O_EXCL       - 128
3 - os.O_RDONLY     - 0
4 - os.O_RDWR       - 2
5 - os.O_SYNC       - 1052672
6 - os.O_TRUNC      - 512
7 - os.O_WRONLY     - 1

I am able to to do half of it with
func main() {
        a := []int{os.O_APPEND,os.O_CREATE,os.O_EXCL,os.O_RDONLY,os.O_RDWR,os.O_SYNC,os.O_TRUNC,os.O_WRONLY}
        for index, value := range a {
                fmt.Printf("%d -  - %d\n", index, value)
        }
}

which gave me output
0 -  - 1024
1 -  - 64
2 -  - 128
3 -  - 0
4 -  - 2
5 -  - 1052672
6 -  - 512
7 -  - 1

and the other half of it with
func main() {
        a := []string{"os.O_APPEND","os.O_CREATE","os.O_EXCL","os.O_RDONLY","os.O_RDWR","os.O_SYNC","os.O_TRUNC","os.O_WRONLY"}
        for index, value := range a {
                fmt.Printf("%d - %-15s -\n", index, value)
        }
}

which gave me the output
0 - os.O_APPEND     -
1 - os.O_CREATE     -
2 - os.O_EXCL       -
3 - os.O_RDONLY     -
4 - os.O_RDWR       -
5 - os.O_SYNC       -
6 - os.O_TRUNC      -
7 - os.O_WRONLY     -

How can I get the desired output ?
Update
As I'm thinking about it, I'm getting an idea for solving it with an array of empty interface and then type asserting on each element of the array of empty interface, once with string to get the string, and once with int to get the value of int, but I don't know how to do that.

A: you could use map.
func main() {
    var m map[string]int
    m = make(map[string]int)
    b := []int{os.O_APPEND,os.O_CREATE,os.O_EXCL,os.O_RDONLY,os.O_RDWR,os.O_SYNC,os.O_TRUNC,os.O_WRONLY}
    a := []string{"os.O_APPEND","os.O_CREATE","os.O_EXCL","os.O_RDONLY","os.O_RDWR","os.O_SYNC","os.O_TRUNC","os.O_WRONLY"}
    for index, value := range a {
        m[value] = b[index]
    }
    var i =0
    for index,mapValue := range m{
        fmt.Println(i," - ",index,"-",mapValue )
        i++
    }
}

out put will be:
0  -  os.O_RDWR - 2
1  -  os.O_SYNC - 1052672
2  -  os.O_TRUNC - 512
3  -  os.O_WRONLY - 1
4  -  os.O_APPEND - 1024
5  -  os.O_CREATE - 64
6  -  os.O_EXCL - 128
7  -  os.O_RDONLY - 0

or you could define custom struct
type CustomClass struct {
    StringValue string
    IntValue int
}
func main() {

    CustomArray:=[]CustomClass{
        {"os.O_APPEND",os.O_APPEND},
        {"os.O_CREATE",os.O_CREATE},
        {"os.O_EXCL",os.O_EXCL},
        {"os.O_RDONLY",os.O_RDONLY},
        {"os.O_RDWR",os.O_RDWR},
        {"os.O_SYNC",os.O_SYNC},
        {"os.O_TRUNC",os.O_TRUNC},
        {"os.O_WRONLY",os.O_WRONLY},
    }
    for k, v := range CustomArray {
        fmt.Println(k," - ", v.StringValue," - ", v.IntValue)
    }
}


Q: JavaScript: shorthand for conditionally adding something to an array I am writing a Mocha test for a server at work.
I get two potential phone numbers for a customer, at least one of which will be defined.
    var homePhone = result.homePhone;
    var altPhone = result.altPhone;

I want to use underscore's _.sample function to pick one of these at random. However, one of them may be undefined.
So what I was thinking was something like:
//pseudocode
var phone = _.sample([homephone || (doNothing), altphone || (doNothing)]);

the _.sample function looks like this:
http://underscorejs.org/#sample
the problem of course, is there is no shorthand syntax that I know of to conditionally add something to an array.
The verbose way to do what I want is:
var phoneArray = [];

if(homePhone){
 phoneArray.push(homePhone);
}
if(altPhone){
 phoneArray.push(homePhone);
}

var phoneSelection = _.sample(phoneArray);

is there a more elegant way to do this in JavaScript?

A: You could use .filter:
_.sample([homephone, altphone].filter(_.identity))

Another way would be:
_.sample([homephone, altphone]) || homephone || altphone;

A: What about:
  var phone = (homephone && altphone)? _.sample([homephone, altphone]) : (homephone || altphone);

A: Since you're already using underscore, I would suggest leveraging compact:
var phone = _.sample(_.compact([homephone, altphone]));

This is basically a shortened version of dave's answer, since compact is literally implemented as function(array) { return _.filter(array, _.identity); }.

A: Array literals in JavaScript:
[ 1, 2, 3 ]

...are a way to statically declare which things go in which positions in an array. In other words, when you write the code, you already know where things will go.
In your scenario, the positions are only known dynamically. In other words, you don't know where they'll go until you run the program on a given set of inputs.
So basically what you're asking for is impossible, barring any radical changes to how array literals work in future versions of JS. However, if all you want is to save typing, @dave's answer is pretty nice. I'm mainly just clarifying that array literals by themselves don't have this capability.


Q: Consul KV data store http api write acquire lock and release session I'm using this command to store key value using session lock in Consul data store.
curl -X PUT -d 300 http://10.0.0.10:8500/v1/kv/my-key-value?acquire=$session

How can I release the lock acquired and can I do so in the same command line?

A: consul kv put -release -session=sessionid my-key-value


Q: Facing Issue while configuring Fedex shipping method Tried to configure fedex with magento 2 and refered the following url:
http://inchoo.net/magento/how-to-set-fedex-shipping-in-magento/
Shipping method for fedex is visible on front end but not being enable even after disabling the soap cache.
Log exception is :
main.CRITICAL: SoapFault exception: [HTTP] Could not connect to host in
\Magento_13\vendor\magento\module-fedex\Model\Carrier.php:491
Stack trace:
0 [internal function]: SoapClient->__doRequest('https://wsbeta....', 'getRates', 1, 0)

A: Actually, i am finding something related to FedEx itself as I am facing the same issue in Magento 1.9 for my client and came up with a post with the same question as you have.
It was suggested there to try on the different network.It may be of blocked I.P issue
Hope it will help you.Sorry, i am not getting that question link but only this is suggested there .
Hope it help you at least.


Q: Style Listviews Selector.SelectedItem I have ListView with SelectionMode=extended and style for ListViewItem thus:
MainWindow.xaml:
<Window x:Class="ListViewSelection.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <Style TargetType="{x:Type ListViewItem}">
            <Style.Resources>
                <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Aqua"/>
            </Style.Resources>
            <!--<Style.Triggers>
                <Trigger Property="IsSelected" Value="True">
                    <Setter Property="Background" Value="Aqua" />
                </Trigger>
            </Style.Triggers>-->
        </Style>
    </Window.Resources>
    <StackPanel>
        <ListView Name="MyListView" ItemsSource="{Binding MyList}" SelectionChanged="SelectionChanged" SelectionMode="Extended" />
        <Label Name="MyLabel" />
    </StackPanel>
</Window>

MainWindow.xaml.cs:
using System.Windows;
using System.Windows.Controls;
using System.Collections.ObjectModel;

namespace ListViewSelection
{
    public partial class MainWindow : Window
    {

        public ObservableCollection<string> MyList { get; set; }

        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = this;
            MyList = new ObservableCollection<string>();
            MyList.Add("Jane");
            MyList.Add("Paul");
            MyList.Add("Sally");
            MyList.Add("Ian");
        }

        private void SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            MyLabel.Content = (sender as ListBox).SelectedItem;
        }
    }
}

This sets the color fine for all selected items. But I need to also style the Selector.SelectedItem, which is the 'active' or first item in the selection. This is the one that the label displays.
Any help? Thanks!

A: You could expose IsFirstInSelection property in your ViewData class (I suppose you have it).
Then you could place DataTrigger for monitoring changes like this:
        <Style.Triggers>
            <DataTrigger Binding="{Binding IsFirstInSelection}">
                <Setter Property="Background"
                        Value="Blue"/>
            </DataTrigger>
        </Style.Triggers>

Also in your case I'd recommend to avoid changing HighlightBrushKey, but achieve your goal via changing Background property. You could also expose IsSelected property in ViewData class, so it looks this:
public class ViewData: ObservableObject
{
    private bool _isSelected;
    public bool IsSelected
    {
        get
        {
            return this._isSelected;
        }
        set
        {
            if (this._isSelected != value)
            {
                this._isSelected = value;
                this.OnPropertyChanged("IsSelected");
            }
        }
    }

    private bool _isFirstInSelection;
    public bool IsFirstInSelection
    {
        get
        {
            return this._isFirstInSelection;
        }
        set
        {
            if (this._isFirstInSelection != value)
            {
                this._isFirstInSelection = value;
                this.OnPropertyChanged("IsFirstInSelection");
            }
        }
    }
}

And your style sets Background based on both properties:
        <Style x:Key="TreeItemStyle"
               TargetType="{x:Type TreeViewItem}">
            <Setter Property="IsSelected"
                    Value="{Binding Path=IsSelected, Mode=TwoWay}"/>
            <Setter Property="IsFirstInSelection"
                    Value="{Binding Path=IsFirstInSelection}"/>
            <Setter Property="Background"
                    Value="Green"/>
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsSelected}"
                             Value="True">
                    <Setter Property="Background"
                            Value="Red"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding IsFirstInSelection}">
                    <Setter Property="Background"
                        Value="Blue"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>

Of course in model or in view code behind you should monitor IsSelected property changed notifications and set/reset IsFirstInSelection according to selected items.
I hope you understand my idea.
------- EDITED --------
At first I continue to insist that you should develop proper ViewData class:
public class ViewData : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string propertyName)
    {
        var ev = this.PropertyChanged;
        if (ev != null)
        {
            ev(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public ViewData(string name)
    {
        this._personName = name;
    }

    private string _personName;
    public string PersonName
    {
        get
        {
            return this._personName;
        }
        set
        {
            if (this._personName != value)
            {
                this._personName = value;
                this.OnPropertyChanged("PersonName");
            }
        }
    }

    private bool _isFirstSelected;
    public bool IsFirstSelected
    {
        get
        {
            return this._isFirstSelected;
        }
        set
        {
            if (this._isFirstSelected != value)
            {
                this._isFirstSelected = value;
                this.OnPropertyChanged("IsFirstSelected");
            }
        }
    }
}

During handling SelectionChanged event you should modify property IsFirstSelected like this:
public ObservableCollection<ViewData> MyList { get; set; }
private void SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    var lb = sender as ListBox;
    if (lb != null)
    {
        MyLabel.Content = lb.SelectedItem;
        foreach (var item in this.MyList)
        {
            if (item == lb.SelectedItem)
            {
                item.IsFirstSelected = true;
            }
            else
            {
                item.IsFirstSelected = false;
            }
        }
    }
}

But default ListViewItem template doesn't react on Background setters so you should override its template in style:
<Style TargetType="{x:Type ListViewItem}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ListViewItem">
                <Grid Background="{TemplateBinding Background}">
                    <ContentPresenter Content="{Binding PersonName}"/>
                </Grid>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsSelected"
                                Value="True">
                        <Setter Property="Background"
                                Value="Yellow"/>
                    </Trigger>

                    <DataTrigger Binding="{Binding IsFirstSelected}"
                                    Value="True">
                        <Setter Property="Background"
                                Value="Aqua" />
                    </DataTrigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

If this solution isn't acceptable, please tell me. I've some ideas but have no enough time to check them in code right now.


Q: convert HTML code from page source to regular page source - PHP I have a web page, that include another web page source. It looks like
<html>
....
<div id="content">
{"note":"\n<!DOCTYPE html>\n<html>\n\t<head>\n\t\t<!--[if IE 9]>\n\t\t\t<script src=\"\/js\/PIE\/PIE_IE9.js\"><\/script>\n\t\t\t<link rel=\"stylesheet\"...
</div>

so I have a string like
<!DOCTYPE html>\n<html>\n\t<head>\n\t\t<!--[if IE 9]>\n\t\t\t<script src=\"\/js\/PIE\/PIE_IE9.js\"><\/script>\n\t\t\t<link rel=\"stylesheet\"...

and I would like to get
<!DOCTYPE html><html><head><!--[if IE 9]><script src="\js\PIE\PIE_IE9.js"></script><link rel="stylesheet".

Is there any PHP function that can remove this special chars like" \n, \t, \"...
I just need a regular HTML code.
Sorry for my english

A: As has been pointed out, there are better ways to do this, however:
$string = "<!DOCTYPE html>\n<html>\n\t<head>\n\t\t<!--[if IE 9]>\n\t\t\t<script src=\"\/js\/PIE\/PIE_IE9.js\"><\/script>\n\t\t\t<link rel=\"stylesheet\"";
echo preg_replace('/\r|\n|\t|\\\/', '', $string);

this will replace the special chars \n, \t, \r and \


Q: Use columns in a file as output file variable names head testregions.bed
21      15390708
21      15890068        16388793
21      16390041        16888505
21      16889055        17388185
21      17388731        17886839

I wanted to use each line of the .bed file as outputname
e.g:
while readline
do zip.sh > 21_15390708_ 15889554.zip
            21_16390041-16888505.zip

I read a bit about xargs being able to do this.
But I am stuck on how it can output each line to unique output file name.
xargs -a testregions.bed -I {} zip inputfile {} >> outputfile_{}.zip

and so on.
Any help is much appreciated.

A: Here is an easy-to-understand way you can do this for every line in your testregions.bed. First, delete all the whitespace in your original file testregions.bed and save just the numbers into a new file new.txt like this:
cat testregions.bed | tr -d "[:blank:]" > new.txt
Then, you will create a new file for each line in your new.txt like this:
cat new.txt | while read line
do
        touch "$line".zip
done
And then you can delete the new.txt:
rm new.txt
So your script test.sh to create .zip files of testregions.bed would look like this:
#!/bin/sh

cat testregions.bed | tr -d "[:blank"]" > new.txt
cat new.txt | while read line
do
        touch "$line".zip
done
rm new


Q: Where does mozilla sync / weave save its passphrase I've uninstalled the mozilla sync addon and forgot to save my passphrase. Maybe the passphrase is stored somewhere in the config files or the registry so I can recover my bookmarks.
Does anyone know where mozilla saves the configuration for its addons?

A: Open Firefox's Error Console from Tools menu (or Ctrl + Shift + J).
Click on Clear and type in the following code inside the code box:
Components.utils.import("resource://services-sync/service.js"); Weave.Service.passphrase

When you hit Enter, your passphrase will appear. If you change "passphrase" to "password" and hit Enter again, then your password will appear.