text:
Q: Wifiwizard is added to my config and package.json file but I can't find the import in my module.ts file

Prerequisites
Check all boxes if you have done the following:
- [x] Checked that your issue isn't already filed: https://github.com/tripflex/wifiwizard2/issues
- [x] Make sure you fill out the Issue Type below
Issue type
Select all that apply
- [x] Bug
- [ ] Enhancement
- [ ] Task
- [x] Question
- [ ] Other
Description
I'm using ionic framework. When I want to install the wifiwizard2 plugin I get no errors but i'm not able to use the plugin. The wifiwizard is added to my config and package.json file but I can't find the import in my module.ts file. Thanks in advance.
Steps to Reproduce

*

*run  sudo cordova plugin add https://github.com/tripflex/wifiwizard2

*run  sudo npm i cordova-plugin-wifiwizard2  or sudo ionic cordova plugin add cordova-plugin-wifiwizard2

*[and so on...]

Expected behavior: Use the plugin
Actual behavior: cannot find import
Reproduces how often: 100%
Versions
Ionic:
ionic (Ionic CLI)             : 4.10.3 (/usr/local/lib/node_modules/ionic)
   Ionic Framework               : @ionic/angular 4.1.1
   @angular-devkit/build-angular : 0.13.6
   @angular-devkit/schematics    : 7.2.4
   @angular/cli                  : 7.3.6
   @ionic/angular-toolkit        : 1.4.0
Cordova:
cordova (Cordova CLI) : 8.1.2 (cordova-lib@8.1.1)
   Cordova Platforms     : android 7.1.4
   Cordova Plugins       : cordova-plugin-ionic-keyboard 2.1.3, cordova-plugin-ionic-webview 3.1.2, (and 4 other plugins)
System:
Android SDK Tools : 26.1.1 (/Users/nathancriel/Library/Android/sdk)
   NodeJS            : v10.15.1 (/usr/local/bin/node)
   npm               : 6.7.0
   OS                : macOS Mojave
   Xcode             : Xcode 10.1 Build version 10B61
Additional Information
config.xml
https://github.com/tripflex/wifiwizard2.git" /
package.json

dependencies
"cordova-plugin-wifiwizard2": "git+https://github.com/tripflex/wifiwizard2.git",

A: WifiWizard is available as a global and does not need to be imported.
Try this :
declare var WifiWizard2: any;

EDIT
I try to use the plugin on my app and it work.
What i do :
cordova plugin add cordova-plugin-wifiwizard2
npm i cordova-plugin-wifiwizard2
On Home.ts :
declare var WifiWizard2: any;
After the platform is ready :
WifiWizard2.getConnectedSSID()
And the method is recognize on build.


text:
Q: Unicode Error when importing a csv file in python? Hi I am using following code to remove duplicate records from my csv file:
inFile = open('I:\SIT\Monthly\LatestMonthly\source\Network1.csv','r')
outFile = open('I:\SIT\Monthly\LatestMonthly\source\Network2.csv','w')

listLines = []

for line in inFile:

    if line in listLines:
        continue

    else:
        outFile.write(line)
        listLines.append(line)

outFile.close()
inFile.close()

When I run the script I am getting an error:

unicodeescape' codec can't decode bytes in position 35-36: malformed \N character escape.

Why do I get this error?

A: Your error occurs before you even open the file!
You are not escaping the backslashes in your filename
'I:\SIT\Monthly\LatestMonthly\source\Network1.csv'

and thus \N is interpreted as a Unicode escape character (\N inserts a Unicode character by name, e.g. '\N{MUSICAL SYMBOL G CLEF}')
You can try using a raw literal here:
r'I:\SIT\Monthly\LatestMonthly\source\Network1.csv'

The prefix r tells Python to treat all backslashes as literal backslashes. Alternatively, you can remember to always escape your backslashes:
'I:\\SIT\\Monthly\\LatestMonthly\\source\\Network1.csv'

or finally, you can use forward-slashes:
'I:/SIT/Monthly/LatestMonthly/source/Network1.csv'

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sentences What for/For What need Both sentences sound right? And do they have a different meaning?

For what needs life?

or

What is life for?

A: Both sentences sound right? And do they have a different meaning?
I presume you mean
Do both sentences sound right? And do they have a different meaning?
Item 1 Sounds wrong and is wrong. For what needs life?
Item 2 is good. What is life for?
The definition of ;

needs plural noun US; the things you must have for a satisfactory life:Link C.E.D.

I can only make a guess at what you are trying to say, so, as item 1 is wrong I cannot compare them.


text:
Q: naming a finance management / tracking application I am about to start develop a finance/expenses tracking/management/statistics webapplication, somewhat similar to xpenser.com , mint.com (except bank integration), for a college project and I am looking for a name
credit will be given in the documentation if the name will be used
if this turns later into a real-life project the name will be changed
...
unsure if this belongs on stackoverflow, but I figured that since it is a programming project here is a place to ask for ideas
Is your question about programming? - It is related to programming
We prefer questions that can be answered, not just discussed. - there many answers, they don't need discussion

A: *

*Scrooge

*pennypincher

*frugality

*moolah

*dough

*bling

*inmymattress

A: MyMoney, ISpent, ImBroken... It depends from what are you looking for.

A: Some ideas off the top of my head:

*

*BigSpender

*st@tement

*Fiscality

*My Online Money - It's as safe as Mom!

*ManEx - Manage Expenses

*you could call it Dave and say that "Dave is your own personal accountant" (Or Doug or any "accountant sounding name")

*Ponzi/Madoff etc.

*BudgeIT

Dodgy Abbreviations:

*

*F.U.N - Financial Upkeep (unification/utility etc) Notepad

*C.A.S.H - Comprehensive Allocations and Spending Hub (or Homepage etc)

*S.P.E.N.D - Secure Personal Expense Needs Database

As this is a homework product, I wouldn't worry too much if you infringe on an existing trademark.
you mention XPenser, so why not eXpenserER - The expense tracking application for Economic Reliability. Or, a common mispelling of something in the related field (like XPenser is Expenser).
Whenever naming things for Uni, I tended to try and be humorous and serious at the same time. Whilst the name would be funny, I would then treat it as a normal name and the Branding was normally conservative.
Good Luck1

A: Off the top of my head:
 - MoneyWatcher
 - MoneyFlow
 - The Honest Accountant
Also I am mad for recursive acronyms so something like:
SOFT Online Financial Tracker


text:
Q: Configuring External LDAP - I can see users but they can't log in I am working on a fresh install of WSO2 Identity Server 5.10 with the Ellucian addons.
I have everything almost working, just one thing is keeping me back.  I have added my LDAP users and I can list them under Users & Roles -> List -> Users.
When I log in to my test CAS site as the internal admin user, it works fine.
What I'm running into is that when I try to log in to my test CAS site as one of my domain users, I get a Login Failed message in my browser and the entries in:
audit.log:
TID: [-1234] [2022-05-09 14:35:02,627] [28898f11-9fa1-4abe-ba42-2082a4799d87]  INFO {AUDIT_LOG} - Initiator : null | Action : Login | Target : ApplicationAuthenticationFramework | Data : { "ContextIdentifier" : "a968d23b-e6c2-4526-9a59-7b4b68a62fc4","ServiceProviderName" : "Test-CASTEST","RequestType" : "cas","RelyingParty" : "Test-CASTEST","StepNo" : "1" } | Result : Failed

and wso2carbon.log
TID: [-1234] [] [2022-05-09 14:35:02,624] [28898f11-9fa1-4abe-ba42-2082a4799d87] DEBUG {org.wso2.carbon.user.core.tenant.TenantIdCache} - TENANT_ID_CACHE which is under TENANT_ID_CACHE_MANAGER, doesn't contain the key : org.wso2.carbon.user.core.tenant.TenantDomainKey@b667606

It doesn't matter whether I login with username@domain.com  or domain\username  or just username. It simply doesn't let me log in.
We aren't doing any multitenancy here.
Any ideas of some things I can check?
Thanks!
~Brant


text:
Q: How to annotate a method that returns tuple to enable null-state static analysis I have a few methods like this.
public static (bool, Type?) GetType(string name)
{
    if (NameToTypeMap.TryGetValue(name, out var type))
    {
        return (true, type);
    }

    return (false, null);
}

(the internal implementation does not always fall back to the TryGetValue. It differs from case to case. Important here is the shape of the method)
Question: is it possible to annotate the method so that when the first value of the tuple is true, then the second value of the tuple is not null?
I'm looking for something similar to what we have for TryXYZ methods (with the attribute [NotNullWhen(true)]) e.g.
bool TryGetMessage(string key, [NotNullWhen(true)] out string? message)
{
    if (_messageMap.ContainsKey(key))
        message = _messageMap[key];
    else
        message = null;
    return message is not null;
}

I have tried a few attributes from https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/attributes/nullable-analysis, but without success.


text:
Q: django.core.exceptions.ImproperlyConfigured: Error importing form class pages.custom_sign_up_form: "cannot import name 'BaseSignupForm'" I am trying to extend SignupForm of django allauth for customizing my signup form. The need is because i want to check if submitted email is accepted for signup or not and it is done by checking if the invite from that email is accepted or not by admin.
I have not define my form in forms.py instead i have used another name 'custom_sign_up_form.py'. Below is my full code with import.
settings.py
ACCOUNT_SIGNUP_FORM_CLASS = 'pages.custom_sign_up_form.CustomSignupForm'

custom_sign_up_form.py
from allauth.account.adapter import DefaultAccountAdapter, get_adapter
from allauth.account.forms import SignupForm
from allauth.account import app_settings
# from django import forms

from invitation.models import Invitation

class CustomSignupForm(SignupForm):
    errors = {
        'not_invited': "Sorry! You are not yet invited.",
    }
    def __init__(self, *args, **kwargs):
        super(CustomSignupForm, self).__init__(*args, **kwargs)

    def clean(self):
        super(CustomSignupForm, self).clean()
        email = self.cleaned_data.get('email')
        email = get_adapter().clean_email(email)
        if email and app_settings.UNIQUE_EMAIL:
            email = self.validate_unique_email(email)
        try:
            Invitation.objects.get(email=email, request_approved=True)
        except Invitation.DoesNotExist:
            # raise forms.ValidationError(errors['Sorry! you are not yet invited'])
            self.add_error('email','Sorry! You are not yet invited')
        return email

A: ACCOUNT_SIGNUP_FORM_CLASS is the parent class of SignupForm (BaseSignupForm)...
https://github.com/pennersr/django-allauth/blob/master/allauth/account/forms.py#L197
If you want to change the Form validation logic, you need to use ACCOUNT_ADAPTER.
# project/settings.py:
ACCOUNT_ADAPTER = 'project.users.adapter.MyAccountAdapter'

# project/users/adapter.py:
from django.conf import settings
from allauth.account.adapter import DefaultAccountAdapter

class MyAccountAdapter(DefaultAccountAdapter):

    def clean_email(self, email):
        """
        Validates an email value. You can hook into this if you want to
        (dynamically) restrict what email addresses can be chosen.
        """
        try:
            Invitation.objects.get(email=email, request_approved=True)
        except Invitation.DoesNotExist:
            raise forms.ValidationError('Sorry! you are not yet invited')
        return email

see also https://stackoverflow.com/a/23328414/7724457


text:
Q: Problem encoding string to ISO8859-1 I'm using this code to convert string to ISO8859-1
baseurl = "http://myurl.com/mypage.php"
                client = New WebClient
                client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)")
                client.QueryString.Add("usuario", user)
                client.QueryString.Add("password", pass)
                client.QueryString.Add("ruta", 2)
                client.QueryString.Add("remitente", Me.txtRemite.Text)
                If Me.chkPRefijo.Checked = True Then
                    client.QueryString.Add("destinatarios", Me.LookUpEdit1.EditValue & Me.dtsMvl.Tables(0).Rows(x).Item("movil"))
                Else
                    client.QueryString.Add("destinatarios", Me.dtsMvl.Tables(0).Rows(x).Item("movil"))
                End If
                textoSms = Me.mmTexto.Text
                textoSms = System.Web.HttpUtility.UrlEncode(textoSms, System.Text.Encoding.GetEncoding("ISO-8859-1"))
                client.QueryString.Add("mensaje", textoSms)
                client.QueryString.Add("reporte", 1)
                data = client.OpenRead(baseurl)
                reader = New StreamReader(data)
                s = reader.ReadToEnd()
                data.Close()
                reader.Close()

But the problem is when an user writes this caracter: +

EXAMPLE:
user writes in my app:
price 80+VAT
encoded string in my app and this string is sent to provider:
price+80%2bVAT
sms received in the mobile:
price 80 VAT

EDIT
Ineed to pass to URL some variables. Because I have a program to send sms, And I need to send variables to URL (URL provider SMS system). The string (message mobile that the user writes in my program) must be sent encoded (ISO 8859-1).
For example, this code in PHP runs fine:
$texto=urlencode($textoOriginal);

This code returns this string converted:
price+80%2BVAT

EDIT 2
I think that my code is wrong. Because if I send the same string encoded "price+80%2BVAT", Why in VB.NET code not runs and in PHP runs fine? Is the same encoded string.

A: I see that you're passing the string to the querystring, so this is the method that you want to use.
What you need to do when you request the querystring back is use System.Web.HttpUtility.UrlDecode
Basically you do the following

*

*UrlEncode the original text

*Pass it to the QueryString

*Request the QueryString

*UrlDecode it to get the original text back.

Here's a test that I ran that seemed to work.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim str As String = "This is My STRING with a + symbol."
    Dim encoded As String = Server.UrlEncode(str)
    Dim decoded As String = Server.UrlDecode(encoded)

    Dim sb As New StringBuilder
    sb.Append("Original String: ")
    sb.Append(str)
    sb.Append("
")
    sb.Append("Encoded String: ")
    sb.Append(Replace(encoded, "%2b", "%2B"))
    sb.Append("
")
    sb.Append("Decoded String: ")
    sb.Append(decoded)

    Response.Write(sb.ToString)
End Sub

And here's my results

Original String: This is My STRING with a + symbol.
  Encoded String: This+is+My+STRING+with+a+%2B+symbol.
  Decoded String: This is My STRING with a + symbol.

EDIT:
After seeing your edit,  Try this bit below...
textoSms = Replace(System.Web.HttpUtility.UrlEncode(Me.mmTexto.Text, System.Text.Encoding.GetEncoding("ISO-8859-1")), "%2b", "%2B")

Instead of using what you have here...
    textoSms = Me.mmTexto.Text
    textoSms = System.Web.HttpUtility.UrlEncode(textoSms, System.Text.Encoding.GetEncoding("ISO-8859-1"))

A: That's part of URL encoding - + means a space in a URL.
In other words, this is correct behaviour if you actually want URL encoding. If you don't, please explain exactly what you're trying to do.


text:
Q: How to change color using Javascript based on value? I'm trying turn this using Javascript. If total @1 = change color into green on the circle 1-7, total @4 = change color into yellow on the circle 8-14, total @7 = change color into blue on the circle 15-21, total @10 = change color into red on the circle 22-31.

  <title>Major Incident Timeline</title>

                    22-31

Total: @10

@11&nbsp P1

@12&nbsp P2

                    15-21

Total: @7

@8&nbsp P1

@9&nbsp P2

                    8-14

Total: @4

@5&nbsp P1

@6&nbsp P2

                    1-7

Total: @1

@2&nbsp P1

@3&nbsp P2

Please help me to make it happen.

A:

$(document).ready(function(){
  var contentDateRange = ['1-7','8-14','15-21','22-31'];
  var colorRange = ['green','yellow','blue','red'];

  $('.meta-date').each(function(index, elem){

    var dateRange = $(this).prev().find('span').text();

    //console.log(dateRange);

    var dateRangeIndex = contentDateRange.indexOf(dateRange);
    //console.log(dateRangeIndex);

    if(dateRangeIndex!==-1){
      $(this).css({
        'background-color': colorRange[dateRangeIndex],
        'border': '1px solid '+ colorRange[dateRangeIndex]
      });
    }
  });

});

  <title>Major Incident Timeline</title>

                    22-31

Total: @10

@11&nbsp P1

@12&nbsp P2

                    15-21

Total: @7

@8&nbsp P1

@9&nbsp P2

                    8-14

Total: @4

@5&nbsp P1

@6&nbsp P2

                    1-7

Total: @1

@2&nbsp P1

@3&nbsp P2


text:
Q: Time lap between mapM function calls In my function:
mapM accessInternetFunc [a list of arguments]

The accessinternetFunc will access a web page with simpleHttp from Http.conduit. I find my program relatively slow and i suspect that it's because of the internet access time. So i wonder if the web server don't react immediately to my accessinternetFunc will my haskell program wait and then re call the function?
How much time will it wait before calling it again ?
To make myself clearer, if the list has 5 elements and after map accessInternetFunc applied to the first element, the web server wont react until 3 secs later, will my map accessInternetFunc wait ?


text: Q: Is it possible classic in vf page and lightning in aura components Here we are using the same UI in both Classic and Lightning. But the issue is, on the lightning page we have to display the aura component only, and we have to hide the VF page.  but In our org, both are displayed. Simply, we want aura components in lightning and VF pages on a classic. Is this possible?


text:
Q: Why does Transmission BitTorrent client say "could not connect to tracker"? I recently cannot download anything via transmission and the download process remains idle("downloading from 0 of 0 connected peers").
Going through properties> trackers, I see "could not connect to tracker" or "tracker gave HTTP respond 404" messages in red.
I also use a VPN connection and I didn't have this problem on 11.04.
Is there a way to get rid of this issue?

A: I installed "Vuze" and all the torrents downloaded. It had something to do with connecting to peers.
Follow the full discussion Here.

A: I think you might have a broken torrent file. Delete any active torrents and re-download them. See if the problem persists.

A: Click on torrent (in bitcomet), and choose updade tracker. This solved my problem.

A: I had this problem when i first downloaded 10.10 so i had to download another bittorrent application since I was not able to fix this problem. But you can try to let it through the firewall manually.
In summary, you can:

*

*Go to your router's setup page and set up manual port forwarding for bittorrent on your machine.

*If that doesn't work, try using some bittorrent application other than Transmission, such as qBittorrent.


text:
Q: MVC Drop Down list with entity framework I've created an MVC project using entity framework code first.  My model is simply a form that gathers information.
public class Application
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string MiddleInitial { get; set; }
    public string LastName { get; set; }
    public int SSN { get; set; }
    public DateTime DOB { get; set; }
    public string Street { get; set; }
    public string City { get; set; }
    public string State {get; set; }
    public string Zip { get; set; }
    public int HomePhone { get; set; }
    public int BusinessPhone { get; set; }
    public int MobilePhone { get; set; }

}
My goal is to create a drop down list with all of the states, but I'm finding this to be very difficult given that I've already created the database via scaffolding with views and controllers.  Is there a simple way to do this and tie it in with the existing database?  I've searched for almost the entire day with no luck.  An overview/explanation of what to include for the model/controller/view would be amazing!

Update: I've created a new model named "State" with properties "Id" and "StateName" and have created some states in the database. In my "Application" controller inside the Create action method I have:
Controller
public ActionResult Create()
    {

        ApplicationDbContext db = new ApplicationDbContext();
        this.ViewData["Id"] = new SelectList(db.States.ToList(), "Id", "StateName");
        return View();
    }

View
@Html.DropDownList("Id")

Now the problem is I'm getting this error " There is no ViewData item of type 'IEnumerable' that has the key 'Id'." Would really appreciate help!

A: Its quite simple. Add an IEnumerable<SelectListItem> property to your model(Here I suggest you make a ViewModel that can have the exact same properties as Application with the below code included as a property). Then you just need to build the list and send it to your view
public IEnumerable<SelectListItem> States{ get; set; }

I will assume you want to retrieve the State values from the db. Here is how you will do it:
private IEnumerable<SelectListItem> GetAllStates()
{
    IEnumerable<SelectListItem> list = from s in db.Applications
                                       select new SelectListItem
                                       {
                                           Selected = false,
                                           Text = s.State,
                                           Value = s.State
                                       };
    return list;
}

Or this...
private IEnumerable<SelectListItem> GetAllStates()
{
    IEnumerable<SelectListItem> list = db.Applications.Select(s => new SelectListItem
                                       {
                                           Selected = false,
                                           Text = s.State,
                                           Value = s.State
                                       });

    return list;
}

Then do something like this in your action:
var app = new Application
{
    States = GetAllStates()
};

return View(app);

Then finally, use Razor on the view to display the Dropdown list like this
@Html.DropDownListFor(m => m.State, Model.States, "--Select a State--")

The 1st parameter is the property of the model to update, the 2nd is the list of data, and 3rd is the default message that will be displayed
Hope this helps.

A: Create a data layer that retrieves a list of what you want.  Then use EF to get all the states.
//assuming you have a table of states..
var states = db.States();

The states table should be a Unique list of states.
var selectList = new List<SelectListItem>();
foreach(var thing in states){
    //if you got everything, thus the ID field for the value...
   selectList.Add(new SelectListItem {Text =thing.State, Selected = false, Value = thing.ID);
}

Make sure in your Viewmodel class that selectlist is a public property.....and set to what you did above. You also need to provied a string for the view selection post back.
StatesSelectList = selectList;
public IEnumberable<SelectListItem> StatesSelectList {get;set;}
public string SelectedState {get;set;}

In your view, do this:
@Html.DropDownListFor(p=>Model.SelectedState, Model.StatesSelectList)

A: Very simple Code step by step
1) In Entity Framework Class
var productsList = (from product in dbContext.Products
                     select new ProductDTO
                     {
                       ProductId = product.ProductId,
                       ProductName = product.ProductName,
                       }).ToList();

2) In Controller
ViewBag.productsList = new EntityFrameWorkClass().GetBusinessSubCategoriesListForDD();

3) In View
@Html.DropDownList("Product_ProductId", new SelectList(ViewBag.productsList, "ProductId", "ProductName"), new { @class = "form-control" })

OR
@Html.DropDownListFor(m=>m.Product_ProductId, new SelectList(ViewBag.productsList , "ProductId", "ProductName"), new { @class = "form-control" })

A: I assume there is a States model that has a Id and a StateName property.
Change to the list to ViewData["State"] to ensure easy binding on POST.
Id is the value that will be sent in the POST data ie.. State = Id.  The StateName is what will be displayed in the Select list.  So for your model this is not correct as State is a string.  So needs to be
this.ViewData["State"] = new SelectList(db.States.ToList(), "StateName", "StateName");

Then in your view
@Html.DropDownList("State")


text:
Q: Action in TFS after completing pull request Is it possible to trigger some action after completing a pull request in TFS ?
Let's say for exemple that a product backlog item is attached as a "related work items" in a pull request.
Could you change it's state automatically after validating the pull request ?

A: This can be achieved using TFVC as source control. Work item will be resolved after the check in action. However, it's not support for GIT in TFS now.
You can submit a feature request in uservoice, TFS admin will kindly review it:

Uservoice Site:
https://visualstudio.uservoice.com/forums/330519-team-services


text:
Q: Error when cross compiling Python for ARM I'm trying to compile Python (version 3.1.3) for ARM, following this guide.
These are the commands I am issuing (on Ubuntu 12):
CC=arm-linux-gnueabi-gcc CXX=arm-linux-gnueabi-g++ AR=arm-linux-gnueabi-ar RANLIB=arm-linux-gnueabi-ranlib ./configure --host --build=x86_64-linux-gnu --prefix=/python

make HOSTPYTHON=./hostpython HOSTPGEN=./Parser/hostpgen BLDSHARED="arm-linux-gnueabi-gcc -shared" CROSS_COMPILE=arm-linux-gnueabi- CROSS_COMPILE_TARGET=yes HOSTARCH=x86_64-linux-gnu BUILDARCH=x86_64-linux-gnu

make install HOSTPYTHON=./hostpython BLDSHARED="arm-linux-gnueabi-gcc -shared" CROSS_COMPILE=arm-linux-gnueabi- CROSS_COMPILE_TARGET=yes prefix=~/Python-2.7.2/_install

A few things to notice.

*

*When executing the first command, if --host is set to arm-linux, the command won't execute, telling me that I should use '--host' for cross-compiling. This is why I did not set it to anything.

*When running the second line, I get

configure: WARNING: Cache variable ac_cv_host contains a newline.
  Failed to configure _ctypes module
Python build finished, but the necessary bits to build these modules
  were not found:
  _curses            _curses_panel      _dbm
  _gdbm              _hashlib           _sqlite3
  _ssl               bz2                ossaudiodev      readline           zlib                                To find the necessary bits, look
  in setup.py in detect_modules() for the module's name.
Failed to build these modules:
  _tkinter

I get a similar error when running the third line, but I guess it's due to the fact that the command above did not work.
I'm trying to  see if anyone can help me fix it.

A: It's much easier to compile natively under QEMU than cross-compile.
Unpack an arm chroot from whichever project you like, e.g. arch linux arm, raspbian, etc.
You already get binary python for arm, but if you really want to compile your own:
Download qemu-user-static (e.g. debian package), unpack that.
Install that single static binary into root of your arm chroot.
Add magic hex to binfmt in proc. Instructions for Debian, Gentoo, genric, List of magic hex sequences. Below are my settings:
mount -t binfmt_misc none /proc/sys/fs/binfmt_misc
echo ':arm:M::\x7fELF\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x28\x00:\xff\xff\xff\xff\xff\xff\xff\x00\xff\xff\xff\xff\xff\xff\xff\xff\xfe\xff\xff\xff:/qemu-arm-static:' > /proc/sys/fs/binfmt_misc/register
export QEMU_CPU=arm926

Optionally, mount --bind /tmp, /proc, /sys, as required.
Enjoy your virtual arm!

A: I got the same error and just ignored it and carried on with the procedure suggested by
http://randomsplat.com/id5-cross-compiling-python-for-embedded-linux.html
It worked with a hello_world program. You can also run a testall.py file from the _install/lib/Python2.7/ folder.
You can also refer to
http://whatschrisdoing.com/blog/talks/PyConTalk2012.pdf


text:
Q: Value set to undefined when setting variable from result of fetch from within useEffect Here is the code snippet:
 export default function GetWeather(props) {
 const [weather, setWeather] = useState([]);

 const apiKey = "xxxxx";
 const apiUrl = `https://api.openweathermap.org/data/2.5/weather?lat=44.34&lon=10.99&appid=${apiKey}`

 useEffect(() => {
    console.log("In useeffect")
    const data = fetch(apiUrl)
      .then((res) => res.json())
      .then((data) =>  data)

      setWeather({data : data})
      console.log(weather.data)

  }, [apiUrl]);

}

The console.log statement prints 'undefined' in the console on browser when I check.
I've checked the network tab and there is data in the response section.

A: Here is your mistake:
 useEffect(() => {
    console.log("In useeffect")
    const data = fetch(apiUrl)
      .then((res) => res.json())
      .then((data) =>  {
        // here you do what you want with data
        setWeather(data)
        // ... other things to do
      })

  }, [apiUrl]);


text:
Q: Regex to find any tag inside curly braces in a string I am struggling to find out which regex could I use to clean up this string:
{1}WH{/1}{2}A{/2}{3}T{/3}{4} {/4}{5}I{/5}{6}T{/6}{7} {/7}{8}I{/8}{9}S{/9}

So that I read only the text?
thanks a lot,
M

A: You can use string replace:
import re
line = "{1}WH{/1}{2}A{/2}{3}T{/3}{4} {/4}{5}I{/5}{6}T{/6}{7} {/7}{8}I{/8}{9}S{/9}"
line = re.sub(r"[^a-zA-Z\s]", "", line)
print(line)# WHAT IT IS

Where:
[^a-zA-Z\s] -> Catch all char other than alphabets and whiteSpace
Demo: https://regex101.com/r/YioUF5/1


text:
Q: Performance comparison Fortran, Numpy,Cython and Numexpr I have following function:
def get_denom(n_comp,qs,x,cp,cs):
'''
len(n_comp) = 1 # number of proteins
len(cp) = n_comp # protein concentration
len(qp) = n_comp # protein capacity
len(x) = 3*n_comp + 1 # fit parameters
len(cs) = 1

'''
    k = x[0:n_comp]
    sigma = x[n_comp:2*n_comp]
    z = x[2*n_comp:3*n_comp]

    a = (sigma + z)*( k*(qs/cs)**(z-1) )*cp
    denom = np.sum(a) + cs
    return denom

I compare it against a Fortran implementation (My first Fortran function ever):
subroutine get_denom (qs,x,cp,cs,n_comp,denom)

! Calculates the denominator in the SMA model (Brooks and Cramer 1992)
! The function is called at a specific salt concentration and isotherm point
! I loops over the number of components

implicit none

! declaration of input variables
integer, intent(in) :: n_comp ! number of components
double precision, intent(in) :: cs,qs ! salt concentration, free ligand concentration
double precision, dimension(n_comp), INTENT(IN) ::cp ! protein concentration
double precision, dimension(3*n_comp + 1), INTENT(IN) :: x ! parameters

! declaration of local variables
double precision, dimension(n_comp) :: k,sigma,z
double precision :: a
integer :: i

! declaration of outpur variables
double precision, intent(out) :: denom

k = x(1:n_comp) ! equlibrium constant
sigma = x(n_comp+1:2*n_comp) ! steric hindrance factor
z = x(2*n_comp+1:3*n_comp) ! charge of protein

a = 0.
do i = 1,n_comp
    a = a + (sigma(i) + z(i))*(k(i)*(qs/cs)**(z(i)-1.))*cp(i)
end do

denom = a + cs

end subroutine get_denom

I compiled the .f95 file by using:
1) f2py -c -m get_denom get_denom.f95 --fcompiler=gfortran
2) f2py -c -m get_denom_vec get_denom.f95 --fcompiler=gfortran --f90flags='-msse2' (The last option should turn on auto-vectorization)
I test the functions by:
import numpy as np
import get_denom as fort_denom
import get_denom_vec as fort_denom_vec
from matplotlib import pyplot as plt
%matplotlib inline

def get_denom(n_comp,qs,x,cp,cs):
    k = x[0:n_comp]
    sigma = x[n_comp:2*n_comp]
    z = x[2*n_comp:3*n_comp]
    # calculates the denominator in Equ 14a - 14c (Brooks & Cramer 1992)
    a = (sigma + z)*( k*(qs/cs)**(z-1) )*cp
    denom = np.sum(a) + cs
    return denom

n_comp = 100
cp = np.tile(1.243,n_comp)
cs = 100.
qs = np.tile(1100.,n_comp)
x= np.random.rand(3*n_comp+1)
denom = np.empty(1)
%timeit get_denom(n_comp,qs,x,cp,cs)
%timeit fort_denom.get_denom(qs,x,cp,cs,n_comp)
%timeit fort_denom_vec.get_denom(qs,x,cp,cs,n_comp)

I added following Cython code:
import cython
# import both numpy and the Cython declarations for numpy
import numpy as np
cimport numpy as np

@cython.boundscheck(False)
@cython.wraparound(False)
def get_denom(int n_comp,np.ndarray[double, ndim=1, mode='c'] qs, np.ndarray[double, ndim=1, mode='c'] x,np.ndarray[double, ndim=1, mode='c'] cp, double cs):

    cdef int i
    cdef double a
    cdef double denom
    cdef double[:] k = x[0:n_comp]
    cdef double[:] sigma = x[n_comp:2*n_comp]
    cdef double[:] z = x[2*n_comp:3*n_comp]
    # calculates the denominator in Equ 14a - 14c (Brooks & Cramer 1992)
    a = 0.
    for i in range(n_comp):
    #a += (sigma[i] + z[i])*( pow( k[i]*(qs[i]/cs), (z[i]-1) ) )*cp[i]
        a += (sigma[i] + z[i])*( k[i]*(qs[i]/cs)**(z[i]-1) )*cp[i]

    denom = a + cs

    return denom

EDIT:
Added Numexpr, using one thread:
def get_denom_numexp(n_comp,qs,x,cp,cs):
    k = x[0:n_comp]
    sigma = x[n_comp:2*n_comp]
    z = x[2*n_comp:3*n_comp]
    # calculates the denominator in Equ 14a - 14c (Brooks & Cramer 1992)
    a = ne.evaluate('(sigma + z)*( k*(qs/cs)**(z-1) )*cp' )
    return cs + np.sum(a)

ne.set_num_threads(1)  # using just 1 thread
%timeit get_denom_numexp(n_comp,qs,x,cp,cs)

The result is (smaller is better):

Why is is the speed of Fortran getting closer to Numpy with increasing size of the arrays? And how could i speed up Cython? Using pointers?

A: Sussed It.
OK, finally, we were permitted to install Numpy etc on one of our boxes, and that has allowed what may be a comprehensive explanation of your original post.
The short answer is that your original questions is, in a sense, "the wrong question".  In addition, there has been much vexatious abuse and misinformation by one of the contributors, and those errors and fabrications deserve attention, lest anyone make the mistake of believing them, and to their cost.
Also, I have decided to submit this answer as a separate answer, rather than editing my answer of Apr 14, for reasons seen below, and propriety.
Part A: The Answer to the OP
First things first, dealing with the question in the original post:  You may recall I could only comment wrt to the Fortran side, since our policies are strict about what software may be installed and where on our machines, and we did not have Python etc to hand (until just now).  I had also repeatedly stated that the character of your result was interesting in terms of what we can call its curved character or perhaps "concavity".
In addition, working purely with "relative" results (as you did not post the absolute timings, and I did not have Numpy to hand at the time), I had indicated a few times that some important information may be lurking therein.
That is precisely the case.
First, I wanted to be sure I could reproduce your results, since we don't use Python/F2py normally, it was not obvious what compiler settings etc are implied in your results, so I performed a variety of tests to be sure we are talking apples-to-apples (my Apr 14 answer demonstrated that Debug vs Release/O2 makes a big difference).
Figure 1 shows my Python results for just the three cases of: your original Python/Numpy internal sub-program (call this P, I just cut/pasted your original), your original Do based Fortran s/r you had posted (call this FDo, I just copy/pasted your original, as before), and one of the variations I had suggested earlier relying on Array Sections, and thus requiring Sum() (call this FSAS, created by editing your original FDo).  Figure 1 shows the absolute timings via timeit.

Figure 2 shows the relative results based on your relative strategy of dividing by the Python/Numpy (P) timings.  Only the two (relative) Fortran variants are shown.

Clearly, those reproduce the character in your original plot, and we may be confident that my tests seem to be consistent with your tests.
Now, your original question was "Why is is the speed of Fortran getting closer to Numpy with increasing size of the arrays?".
In fact, it is not.  It is purely an artefact/distortion of relying purely on "relative" timings that may give that impression.
Looking at Figure 1, with the absolute timings, it is clear the Numpy and Fortran are diverging.  So, in fact, the Fortran results are moving away from Numpy or vice versa, if you like.
A better question, and one which arose repeatedly in my previous comments, is why are these upward curving in the first place (c.f. linear, for example)?  My previous Fortran-only results showed a "mostly" flat relative performance ratio (yellow lines in my Apr 14 chart/answer), and so I had speculated that there was something interesting happening on the Python side and suggested checking that.
One way to show this is with yet a different kind of relative measure.  I divided each (absolute) series with its own highest value (i.e. at n_comp = 10k), to see how this "internal relative" performance unfolds (those are referred to as the ??10k values, representing the timings for n_comp = 10,000).  Figure 3 shows these results for P, FDo, and FSAS as P/P10k, FDo/FDo10k, and FSAS/FSAS10k.  For clarity, the y-axis has a logarithmic scale.  It is clear that the Fortran variants preform relatively very much better with decreasing n_comp c.f. the P results (e.g. the red circle annotated section).

Put differently, Fortran is very very (non-linearly) more efficient for decreasing array size.  Not sure exactly why Python would do so much worse with decreasing n_comp ... but there it is, and may be an issue with internal overhead/set-up etc., and the differences between interpreters vs compilers etc.
So, it's not that Fortran is "catching up" with Python, quite the opposite, it is continuing to distance itself from Python (see Figure 1).  However, the differences in the non-linearities between Python and Fortran with decreasing n_comp produce "relative" timings with apparently counter-intuitive and non-linear character.
Thus, as n_comp increases and each method "stabilises" to a more or less linear mode, the curves flatten to show that their differences are growing linearly, and the relative ratios settle to an approximate constant (ignoring memory contention, smp issues, etc.) ... this is easier to see if n_comp is allowed > 10k, but the yellow line in my Apr 14 answer already show this for the Fortran-only s/r's.
Aside:  My preference is to create my own timing routines/functions.  timeit seems convenient, but there is much going on inside that "black box".  Setting your own loops and structures, and being certain of the properties/resolution of your timing functions is important towards a proper assessment.

A: Being named in the other answer, I have to respond.
I know this does not really answer the original question, but the original poster encouraged pursuing this direction in his comments.
My points are these:
1. I do not believe the array intrinsic are better optimized in any way. If one is lucky, they are translated to the same loop code as the manual loops. If one is not, performance problems can arise. Therefore, one has to be careful. There is a potential to trigger temporary arrays.
I translated the offered SAS arrays to usual do loop. I call it DOS. I demonstrate the DO loops are in no way slower, both subroutines result in more or less the same code in this case.
qsDcs = qs/cs

denom = 0
do j = 1, n_comp
  denom = denom + (x(n_comp+j) + x(2*n_comp+j)) * (x(j)*(qsDcs)**(x(2*n_comp+j)-1))*cp(j)
end do

denom = denom + cs

It is important to say that I don't believe this version is less readable just because it has one or two more lines. It is actually quite straightforward too see what is happening here.
Now the timings for these
f2py -c -m sas  sas.f90 --opt='-Ofast'
f2py -c -m dos  dos.f90 --opt='-Ofast'

In [24]: %timeit test_sas(10000)
1000 loops, best of 3: 796 µs per loop

In [25]: %timeit test_sas(10000)
1000 loops, best of 3: 793 µs per loop

In [26]: %timeit test_dos(10000)
1000 loops, best of 3: 795 µs per loop

In [27]: %timeit test_dos(10000)
1000 loops, best of 3: 797 µs per loop

They are just the same. There is no hidden performance magic in the array intrinsics and array expression arithmetic. In this case they are just translated to loops under the hood.
If you inspect the generated GIMPLE code, both the SAS and DOS are translated to the same main block of optimized code, no magical version of SUM() is called here:
  <bb 8>:
  # val.8_59 = PHI <val.8_49(9), 0.0(7)>
  # ivtmp.18_123 = PHI <ivtmp.18_122(9), 0(7)>
  # ivtmp.25_121 = PHI <ivtmp.25_120(9), ivtmp.25_117(7)>
  # ivtmp.28_116 = PHI <ivtmp.28_115(9), ivtmp.28_112(7)>
  _111 = (void *) ivtmp.25_121;
  _32 = MEM[base: _111, index: _106, step: 8, offset: 0B];
  _36 = MEM[base: _111, index: _99, step: 8, offset: 0B];
  _37 = _36 + _32;
  _40 = MEM[base: _111, offset: 0B];
  _41 = _36 - 1.0e+0;
  _42 = __builtin_pow (qsdcs_18, _41);
  _97 = (void *) ivtmp.28_116;
  _47 = MEM[base: _97, offset: 0B];
  _43 = _40 * _47;
  _44 = _43 * _42;
  _48 = _44 * _37;
  val.8_49 = val.8_59 + _48;
  ivtmp.18_122 = ivtmp.18_123 + 1;
  ivtmp.25_120 = ivtmp.25_121 + _118;
  ivtmp.28_115 = ivtmp.28_116 + _113;
  if (ivtmp.18_122 == _96)
    goto <bb 10>;
  else
    goto <bb 9>;

  <bb 9>:
  goto <bb 8>;

  <bb 10>:
  # val.8_13 = PHI <val.8_49(8), 0.0(6)>
  _51 = val.8_13 + _17;
  *denom_52(D) = _51;

the code is functionally identical to the do loop version, just the name of the variables are different.

2. They assumed shape array arguments (:) have a potential to degrade performance. Whereas the argument received in the assumed size argument (*) or explicit size (n) is always simply contiguous, the assumed shape one theoretically does not have to be and the compiler must be prepared for that. Therefore I always recommend to use the contiguous attribute to your assumed shape arguments wherever you know you will call it with contiguous arrays.
In the other answer the change was quite pointless because it did not use any of the advantages of assumed shape arguments. Namely, that you do not have to pass the arguments with the array sizes and you can use the intrinsics such as size() and shape().

Here are the results of a comprehensive comparison. I made it to be as fair as possible. Fortran files are compiled with -Ofast as shown above:
import numpy as np
import dos as dos
import sas as sas
from matplotlib import pyplot as plt
import timeit
import numexpr as ne

#%matplotlib inline

ne.set_num_threads(1)

def test_n(n_comp):

    cp = np.tile(1.243,n_comp)
    cs = 100.
    qs = np.tile(1100.,n_comp)
    x= np.random.rand(3*n_comp+1)

    def test_dos():
        denom = np.empty(1)
        dos.get_denomsas(qs,x,cp,cs,n_comp)

    def test_sas():
        denom = np.empty(1)
        sas.get_denomsas(qs,x,cp,cs,n_comp)

    def get_denom():
        k = x[0:n_comp]
        sigma = x[n_comp:2*n_comp]
        z = x[2*n_comp:3*n_comp]
        # calculates the denominator in Equ 14a - 14c (Brooks & Cramer 1992)
        a = (sigma + z)*( k*(qs/cs)**(z-1) )*cp
        denom = np.sum(a) + cs
        return denom

    def get_denom_numexp():
        k = x[0:n_comp]
        sigma = x[n_comp:2*n_comp]
        z = x[2*n_comp:3*n_comp]
        loc_cp = cp
        loc_cs = cs
        loc_qs = qs
        # calculates the denominator in Equ 14a - 14c (Brooks & Cramer 1992)
        a = ne.evaluate('(sigma + z)*( k*(loc_qs/loc_cs)**(z-1) )*loc_cp' )
        return cs + np.sum(a)

    print 'py', timeit.Timer(get_denom).timeit(1000000/n_comp)
    print 'dos', timeit.Timer(test_dos).timeit(1000000/n_comp)
    print 'sas', timeit.Timer(test_sas).timeit(1000000/n_comp)
    print 'ne', timeit.Timer(get_denom_numexp).timeit(1000000/n_comp)

def test():
    for n in [10,100,1000,10000,100000,1000000]:
        print "-----"
        print n
        test_n(n)

Results:
            py              dos             sas             numexpr
10          11.2188110352   1.8704519272    1.8659651279    28.6881871223
100         1.6688809395    0.6675260067    0.667083025     3.4943861961
1000        0.7014708519    0.5406000614    0.5441288948    0.9069931507
10000       0.5825948715    0.5269498825    0.5309231281    0.6178650856
100000      0.5736029148    0.526198864     0.5304090977    0.5886831284
1000000     0.6355218887    0.5294830799    0.5366530418    0.5983200073
10000000    0.7903120518    0.5301260948    0.5367569923    0.6030929089

You can see that there is very small difference between the two Fortran versions. The array syntax is marginally slower, but nothing to speak about, really.
Conclusion 1: In this comparison overhead for all should be fair and you see that for  ideal vector length Numpy and Numexpr CAN almost reach Fortran's performance, but when the vector is too small or perhaps even too large the overhead of the Python solutions prevails.
Conclusion 2: The higher performance SAS version in the other comparison is caused by comparing to the orginal OP's version which is not equivalent. The equivalent optimized DO loop version is included above in my answer.

A: Further to my previous answer, and Vladimir's weak speculation, I set up two s/r's:  one as the original given, and one using array sections and Sum().  I also wished to demonstrate that Vladimir's remarks on Do loop optimisation as weak.
Also, a point I usually make for benchmarking, the size of n_comp in the example shown above is TOO small.  The results below put each of the "original" and the "better" SumArraySection (SAS) variation into loops repeated 1,000 times inside the timing calls, so the results are for 1000 calcs of each s/r.  If your timings are fractions of a second, they are likely unreliable.
There are a number of variations worth considering, none with explicit pointers.  The one variation used for this illustrations is
subroutine get_denomSAS (qs,x,cp,cs,n_comp,denom)

! Calculates the denominator in the SMA model (Brooks and Cramer 1992)
! The function is called at a specific salt concentration and isotherm point
! I loops over the number of components

implicit none

! declaration of input variables
integer, intent(in) :: n_comp ! number of components
double precision, intent(in) :: cs,qs ! salt concentration, free ligand concentration
double precision, Intent(In)            :: cp(:)
double precision, Intent(In)            :: x(:)

! declaration of local variables
integer :: i

! declaration of outpur variables
double precision, intent(out) :: denom
!
!
double precision                        :: qsDcs
!
!
qsDcs = qs/cs
!
denom = Sum( (x(n_comp+1:2*n_comp) + x(2*n_comp+1:3*n_comp))*(x(1:n_comp)*(qsDcs) &
                                            **(x(2*n_comp+1:3*n_comp)-1))*cp(1:n_comp) ) + cs
!
!
end subroutine get_denomSAS

The key differences are:
a) passed arrays are (:)
b) no array assignments in s/r, instead use array sections (equivalent to "effective " pointers).
c) Use Sum() instead of Do
Then also try two different compiler optimisations to demonstrate implications.
As the two charts show, the orig code (blue diamonds) is much slower c.f. SAS (red squares) with low optimisation.  SAS is still better with high optimisation, but they are getting close.  This is in part explained by Sum() being "better optimised" when low compiler optimisation is used.

The yellow lines show the ratio between the two s/r's timings.  Ignore the yellow line value at "0" in the top image (n_comp too small caused one of the timings to go wonky)
Since I don't have the user's original data to ratio against Numpy, I can make only the statement that the SAS curve on his chart should lie below his current Fortran results, and possibly be flatter or even down trending.
Put differently, there may not actually exist the divergence seen in the original posting, or at least not to that extent.
... though more experimentation may be helpful to demonstrate also the other comments/answers already provided.
Dear Moritz: oops, I forgot to mention, and pertaining to your question about pointers.  As per earlier, a key reason for the improvement with the SAS variation is that it makes better use of "effective pointers" in that it obviates the need to reassign array x() into three new local arrays (i.e. since x is passed by ref, using array sections is a kind of pointer approach built into Fortran, and thus no need for explicit pointers), but then requires Sum() or Dot_Product() or whatever.
Instead, you can keep the Do and achieve something similar by changing x either to an n_compx3 2D array, or pass the three explicit 1D arrays of order n_comp directly.  This decision would be, likely, driven by the size and complexity of your code, since it would require rewriting the calling/sr statements etc, and anywhere else x() is used.  Some of our projects are > 300,000 lines of code, so in those case it is much much less expensive to change the code locally, such as to SAS etc.
I am still waiting to obtain permission to install Numpy on one of our boxes.  As noted earlier, it is of some interest why your relative timings imply that Numpy improves with increasing n_comp  ...
Of course, the comments about "proper" benchmarking etc, as well as the question of what compiler switches are implied by your use of fpy, still apply, as those may greatly alter the character of your results.
I would be interested to see your results if they were updated for these permutations.

A: There is not sufficient information in the notes, but some of the following may help:
1) Fortran has optimised intrinsic functions such as "Sum()" and "Dot_Product", which you may wish to use in place of the Do loop for summations etc.
In some cases (not neccessiraly here), it may be "better" to use a ForAll or whatever to create "meta" arrays to be summed, and then apply the summation on the "meta" arrays.
However, Fortran allows array sections so you don't need to create the automatic/intermediate arrays sigma, k, and z, and the releated overhead.  Instead can have something like
n_compP1 = n_comp+1
n_compT2 = n_comp*2
a = Sum( x(1:n_comp)+2*x(n_compP1,n_compT2) )   ! ... just for example

2) Sometimes (depends on compiler, machine, etc), there can be "memory contentions" if the array sizes are not at certain "binary intervals" (e.g. 1024 vs. 1000) etc.
You may wish to repeat your experiments at a few more points in your chart (i.e. at various other "n_comps"), and particularly near such "boundaries".
3) Can't tell if you are using the full compiler optimsation (flags) for compiling your fortran code.  You may wish to look up the various "-o" flags, etc.
4) You may wish to include OpemMP directive (or at least include openmp in your flags etc).  That can sometimes improve certain overhead issues, even if not relying explicitly on OpenMP directives in your loops etc.
5) General:  This would likely apply to each of your methods where loops are used
a) "constant operations" in the "summation" formula can be performed outside of the loop, eg. create something like qsDcs = qs/cs, and use qsDcs in the loop.
b) Similarly, sometimes it is useful to create something like zM1(:) = z(:) - 1, and use zM1(:) in the loop instead.


text:
Q: Overload resolution based on template parameter I'm unsure if what I want to do is possible in C++, so asking here.
I have a templated class MyClass that has an optional template argument idx. I have another non-templated class OtherClass. What I want to do is to do some sort of overload resolution based on idx:

*

*If idx is provided (has a value other than -1), I want to call the templated version of OtherClass::otherMethod.

*Otherwise, I want to call the non-templated version of OtherClass::otherMethod.
Note that if T==SomeType the user of MyClass would provide idx. In other cases, no idx is needed. Also, the two different versions of OtherClass::otherMethod are guaranteed to take different input types. Seems to me that I somehow need to disable overload resolution for OtherClass::otherMethod<>  when idx == -1 and enable it only if idx!= -1.
The code below outlines what I have:
template <typename T, int32_t idx=-1>
class MyClass
{
    OtherClass m_other;

    void myMethod(T arg)
    {
        // If idx == -1
        // m_other.otherMethod<idx>(arg);

        // else
        // m_other.otherMethod(arg);
    }
}

class OtherClass
{

    template<int32_t idx>
    void otherMethod(SomeType arg)
    {
        // Some operation that depends on idx
    }

    void otherMethod(YetAnotherType arg)
    {

    }
}

EDIT:
One obvious solution is to template void otherMethod(YetAnotherType arg) with some default (and unused) argument. I'm looking for solutions other than that.
EDIT2:  (in response to comments)
I'm using C++11. A simple if doesn't always work, as demonstrated here. Thus, I need to know whether what I need to do is possible with compile-time constructs.

A: Something along these lines, perhaps:
template <typename T, int32_t idx=-1>
class MyClass {
  OtherClass m_other;

  void myMethodHelper(T arg, std::true_type) {
       m_other.otherMethod<idx>(arg);
  }
  void myMethodHelper(T arg, std::false_type) {
       m_other.otherMethod(arg);
  }

public:
  void myMethod(T arg) {
    myMethodHelper(arg, std::integral_constant<bool, (idx >= 0)>{});
  }
};

Demo


text:
Q: Cannot seem to get read_batch_examples working alongside an Estimator EDIT: I'm using TensorFlow version 0.10.0rc0
I'm currently trying to use tf.contrib.learn.read_batch_examples working while using a TensorFlow (SKFlow/tf.contrib) Estimator, specifically the LinearClassifier. I create a read_batch_examples op feeding in a CSV file with a tf.decode_csv for the parse_fn parameter with appropriate default records. I then feed that op to my input_fn for fitting the Estimator, but when that's run I receive the following error:
ValueError: Tensor("centered_bias_weight:0", shape=(1,), dtype=float32_ref) must be from the same graph as Tensor("linear/linear/BiasAdd:0", shape=(?, 1), dtype=float32).

I'm confused because neither of those Tensors appear to be from the read_batch_examples op. The code works if I run the op beforehand and then feed the input instead as an array of values. While this workaround exists, it is unhelpful because I am working with large datasets in which I need to batch in my inputs. Currently going over Estimator.fit (currently equivalent to Estimator.partial_fit in iterations isn't nearly as fast as being able to feed in data as it trains, so having this working is ideal. Any ideas? I'll post the non-functioning code below.
def input_fn(examples_dict):
    continuous_cols = {k: tf.cast(examples_dict[k], dtype=tf.float32)
                       for k in CONTINUOUS_FEATURES}
    categorical_cols = {
    k: tf.SparseTensor(
        indices=[[i, 0] for i in xrange(examples_dict[k].get_shape()[0])],
        values=examples_dict[k],
        shape=[int(examples_dict[k].get_shape()[0]), 1])
    for k in CATEGORICAL_FEATURES}
    feature_cols = dict(continuous_cols)
    feature_cols.update(categorical_cols)
    label = tf.contrib.layers.one_hot_encoding(labels=examples_dict[LABEL],
                                               num_classes=2,
                                               on_value=1,
                                               off_value=0)
    return feature_cols, label

filenames = [...]
csv_headers = [...] # features and label headers
batch_size = 50
min_after_dequeue = int(num_examples * min_fraction_of_examples_in_queue)
queue_capacity = min_after_dequeue + 3 * batch_size
examples = tf.contrib.learn.read_batch_examples(
    filenames,
    batch_size=batch_size,
    reader=tf.TextLineReader,
    randomize_input=True,
    queue_capacity=queue_capacity,
    num_threads=1,
    read_batch_size=1,
    parse_fn=lambda x: tf.decode_csv(x, [tf.constant([''], dtype=tf.string) for _ in xrange(csv_headers)]))

examples_dict = {}
for i, header in enumerate(csv_headers):
    examples_dict[header] = examples[:, i]

categorical_cols = []
for header in CATEGORICAL_FEATURES:
    categorical_cols.append(tf.contrib.layers.sparse_column_with_keys(
        header,
        keys  # Keys for that particular feature, source not shown here
    ))
continuous_cols = []
for header in CONTINUOUS_FEATURES:
    continuous_cols.append(tf.contrib.layers.real_valued_column(header))
feature_columns = categorical_cols + continuous_cols

model = tf.contrib.learn.LinearClassifier(
            model_dir=model_dir,
            feature_columns=feature_columns,
            optimizer=optimizer,
            n_classes=num_classes)
# Above code is ok up to this point
model.fit(input_fn=lambda: input_fn(examples_dict),
          steps=200) # This line causes the error ****

Any alternatives for batching would be appreciated as well!

A: I was able to figure out my mistake through the help of the great TensorFlow team! read_batch_examples has to be called within input_fn, otherwise the op has to be run beforehand as it'll be from a different graph.
Edit
Here is the modified code that functions properly for those who are interested:
def input_fn(file_names, batch_size):
    examples_dict = read_csv_examples(file_names, batch_size)

    # Continuous features
    feature_cols = {k: tf.string_to_number(examples_dict[k], dtype=tf.float32)
                       for k in CONTINUOUS_FEATURES}
    # Categorical features
    feature_cols.update({
        k: tf.SparseTensor(
            indices=[[i, 0] for i in range(examples_dict[k].get_shape()[0])],
            values=examples_dict[k],
            shape=[int(examples_dict[k].get_shape()[0]), 1])
        for k in CATEGORICAL_FEATURES})

    # Change out type for classification/regression
    out_type = tf.int32 if CLASSIFICATION else tf.float32
    label = tf.string_to_number(examples_dict[LABEL], out_type=out_type)

    return feature_cols, label

def read_csv_examples(file_names, batch_size):

    def parse_fn(record):
        record_defaults = [tf.constant(['']), dtype=tf.string] * len(FEATURE_HEADERS)
        return tf.decode_csv(record, record_defaults)

    examples_op = tf.contrib.learn.read_batch_examples(
        file_names,
        batch_size=batch_size,
        reader=tf.TextLineReader,
        parse_fn=parse_fn)

    # Important: convert examples to dict for ease of use in `input_fn`
    # Map each header to its respective column (FEATURE_HEADERS order
    # matters!
    examples_dict_op = {}
    for i, header in enumerate(FEATURE_HEADERS):
        examples_dict_op[header] = examples_op[:, i]

    return examples_dict_op

This code is near minimal for producing a generic input function for your data. Also note that if you would like to pass num_epochs to read_batch_examples, you'll need to do something different for your categorical features (see this answer for details). Disclaimer: I wrote that answer. Hope this helps!


text:
Q: Convert string of 0 and 1 to it's binary equivalent python I have a string of 6 characters (only 0s and 1s)on which I have to use binary operations. I came across a few pages but most mentioned converting characters to binary and appending them to give the final result.
I have to use it in this function
def acmTeam(topic):
    global finalCount
    for i in range(len(topic)-1):
        for j in range(i+1,len(topic)):
            final=toBinary(topic[i])|toBinary(topic[j])
            print(final)

One example value of topic is
['10101', '11100', '11010', '00101']

and i want 10101 and 11100 binary values
Here I can create my own function toBinary to convert it to binary equivalent and return, but is there any inbuilt function or more efficient way to do so in python?
Thanks in advance :)

A: Try this:
int(s, base=2)

for example,
for i in ['10101', '11100', '11010', '00101']:
    print(int(i, base=2))

@metatoaster also mentioned this.


text:
Q: How to set up bidirectional association between two objects in OO Java I have a basic assignment to do but am very new to OOP and struggling with it. Other online resources are starting to add to my confusion.
I am required to:

*

*Write code for a class Person. A Person object is to have attributes name, age and address.

*Write code for a class Dog. A Dog object is to have attributes name and age.

*Give any additional code in the Person and Dog classes that is required to setup a bidirectional association between a Person object and a Dog object. A Person object acts as an owner for a Dog object and the Dog object acts as a pet for the Person object.

*Modify your Person class so that a Person object can act as owner for up to 20 Dog objects.
Obviously this is  a very simple example.
My code so far:
Person Class :
    public class Person
{
    // instance variables - replace the example below with your own
    private String name;
    private int age;
    private String address;

    /**
     * Constructor for objects of class Person
     */
    public Person()
    {
       this.name = name;
       this.age = age;
       this.address = address;
    }

    //Set Methods:
    public void setName () {
            this.name = name;
    }

    public void setAge () {
            this.age = age;
    }

    public void setAddress () {
            this.address = address;
    }

    //Get Methods:
    public String getName () {
            return name;
    }

    public int getAge () {
            return age;
    }

    public String getAddress () {
            return address;
    }
}

Dog Class:
    public class Dog
{
    // instance variables - replace the example below with your own
    private String name;
    private int age;

    public Dog()
    {
       this.name = name;
       this.age = age;
    }

    //Set Methods:
    public void setName () {
        this.name = name;
    }

    public void setAge () {
        this.age = age;
    }

    //Get Methods:
    public String getName () {
        return name;
    }

    public int getAge () {
        return age;
    }

}

Main:
public class Main
{
   //Blank
}

I know this code is currently useless and doesn't do anything but I am unsure of how to 'associate' the objects & where to do it. The assignment spec specifies a person acts as an 'owner' for the dog.
This is where my problem lies. Setting up the relationship between the objects.

A: The main problem here is consistency: if a Dog d1 is a pet for a Person p1, then p1 must be owner of d1, and vice versa. If, as many suggested, we have 2 methods (Person.addDog() and Dog.setOwner()), then a user can easily make a mistake and fail to call both methods (or call with wrong arguments). Since a Dog can have only one owner, a simple and safe interface would be using single method Dog.setOwner(Person p), where p may be null if we want the dog to have no owner. This method, besides setting the field Dog.owner, must remove this dog from the pet list of previous owner and (if p != null) add itself to the pet list of the new owner. The methods of class Person to add and remove pets should be visible for the class Dog but not visible to the user (they should be package private), while the method Dog.setOwner should be public.
UPDT
We can consider value of Dog.owner as a primary datum, and value of Person.dogs as secondary data, similar to database indexes.

A: This is a common problem with bidirectional relationships; you can't pass them in the constructor because one will not exist yet when the other is initialised. For this reason you must "wire them up from the outside"
Your mention of 20 dogs suggests they want you to use an array to hold the dogs, but an arraylist would be better. I will use the arraylist but can show you how this would work with an array if you'd like
public class Person
    {
    ArrayList<Dog> dogs=new ArrayList<Dog>(); //this will hold all the dogs that the Person has as pets

    public void giveDog(Dog dog){
       dogs.add(dog)
    }
    .....
    .....

Equally the dog class is given an owner
public class Dog
    {
    Person owner;

    public void setOwner(Person owner){
       this.owner=owner;
    }
    .....
    .....

Using these two methods you can create the bidirectional relationship.
Notes
This is obviously an assignment so you have no choice but for the future; bidirectional relationships like this can be useful. But they are also dangerous when used incorrectly; the most important thing is that after initialisation an object must work without error. It must not rely on setOwner() or giveDog() being called: in other words a petless person and an ownerless dog must behave "correctly" (what ever that means in this context. Failing to achieve this can lead to bug prone code. If this is impracticle then it must be impossible for ownerless dogs or dogless people to be exposed to the rest of the program; factory methods can be useful for this, but that is beyond the scope of this question

A: What you are required to do looks like a circular dependency issue. So what you can do is to use the object composition.
Simply add to your classes a instance variable of the second type:
public class Person
{
    private Dog myDog;

    private String name;
    private int age;
    private String address;
    ...etc.

and respectively in the Dog class, every Dog will have its owner:
public class Dog
{
    private Person myOwner;

    private String name;
    private int age;

Don't forget setters and getters.
As for the point 4):

4) Modify your Person class so that a Person object can act as owner for up to 20 Dog objects.

Instead of having every Person object have one Dog member, use an array, or some Collection (List, Set, etc.):
So instead of
private Dog myDog;

do
private Dog[] dogArray = new Dog[20];
OR
private Collection<Dog> dogList = new ArrayList(20); //for example

A: Because both objects can't be created at the same time you can't pass references to each other in the constructor. You must create getter and setter methods so you can create this relationship after the objects are created. An example of this is as follows:
public class Person
   Set<Dog> dogs = new HashSet<Dog>();

   public void addDog(Dog dog){
      if(dogs.size()>20){
           throw new IllegalArgumentException("exceeded the limit: ");
      }
      dogs.add(dog);
   }
}

public class Dog
{
    Person person;

    public void setPerson(Person person){
        this.person=person;
    }
}

A: Try this one:
    Person person = new Person();
    Dog dog1 = new Dog();
    dog1.setAge(12);

    Dog dog2 = new Dog();
    dog2.setAge(34);

    person.addDog(dog1); //dog 1
    person.addDog(dog2); //dog 2
    person.listDogs(); //list of all dogs

//PERSON
public class Person {
 // instance variables - replace the example below with your own
    private String name;
    private int age;
    private String address;
    private ArrayList<Dog> dogs = new ArrayList<Dog>();

    /**
     * Constructor for objects of class Person
     */
    public Person()
    {
       this.name = name;
       this.age = age;
       this.address = address;
    }

    public void addDog(Dog dog) {
        this.dogs.add(dog);
    }

    public void listDogs() {
        for(Dog item : this.dogs) {
            System.out.println(item.getAge());
        }
    }

    //Set Methods:
    public void setName () {
            this.name = name;
    }

    public void setAge () {
            this.age = age;
    }

    public void setAddress () {
            this.address = address;
    }

    //Get Methods:
    public String getName () {
            return name;
    }

    public int getAge () {
            return age;
    }

    public String getAddress () {
            return address;
    }
}

//DOG
public class Dog {

    // instance variables - replace the example below with your own
    private String name;
    private int age;

    public Dog()
    {
       this.name = name;
       this.age = age;
    }

    //Set Methods:
    public void setName () {
        this.name = name;
    }

    public void setAge (int age) {
        this.age = age;
    }

    //Get Methods:
    public String getName () {
        return name;
    }

    public int getAge () {
        return age;
    }

}


text:
Q: Conditionally start GenServer in tests I have implemented a GenServer that listens to an external message queue via long polling. For that, I am starting the GenServer with the start of the application, i.e. within the start/2 function of my application.ex file I specified an extra child in the supervisor list:
children = [
    supervisor(MyApp.Repo []),
    supervisor(MyAppWeb.Endpoint, []),
    supervisor(MyApp.MessageQueueGenServer, [])
]

This list is then started with:
Supervisor.start_link(children, [strategy: :one_for_one, name: MyApp.Supervisor])

Now I have the problem that the GenServer is of course also started when I am running some (1) database setup with mix ecto.reset or (2) tests with mix test.
For the tests (2) I could, e.g. only add MyApp.MessageQueueGenServer to the children list if Mix.env != :test.
But what about (1)? How to avoid starting my GenServer when running mix ecto.reset/mix ecto.setup/etc.?

A: I had the same issue and I have it resolved with a configuration parameter.
config/config.exs
config :myapp, :children, [
  MyApp.Repo, MyAppWeb.Endpoint, MyApp.MessageQueueGenServer]

config/dev.exs
# config :myapp, :childen [] # tune it for dev here

config/test.exs
config :myapp, :children, [
  MyApp.Repo, MyAppWeb.Endpoint]

your server file
children = [
  :myapp
  |> Application.get_env(:children)
  |> Enum.map(&supervisor(&1, [])
]

Sidenote: you might want to consider using modern style of children declaration, since Supervisor.Spec is deprecated, that way it would be even cleaner:
children = Application.get_env(:myapp, :children)


text:
Q: Can I ask MySQL to do a "double" search? I was wondering if this is possible to make MySQL do a "double search"; I don't really know how to say it well so here's an example:
I have a table of songs information (title,album, etc etc ...). I want to get the next song in the album. I have the ID of the current song. Currently I get the row, check the album and track field, then do another MySQL query based on album field and check if there is another track after the current one.
Could I, in one query, tell MySQL that I want all rows of the album contained in the row of the id I have?
Since I really don't know if this is possible or how to describe it, I didn't find anything useful on Stack Overflow, so sorry if there is already something similar.

A: You could use a JOIN to get what you want. Assuming your table has an ID that links to an album something like this would work to get everything that comes after the track currently being listened to.
select *
  from songs a
  join songs b
    on a.album_id = b.album_id
 where a.song_id = 1
   and b.song_id > a.song_id

Obviously, if you want everything in the album then remove the second condition. If you want to include the track being listened to change > to >=.

You've just commented:

i should have mentionned it but the id is not relevant to the order of
  tracks , it's juste the primary key in the table.

If this is the case then then b.song_id > a.song_id is probably incorrect. You haven't given us your full schema but I would highly recommend if your songs table contained the order the tracks should be played in, so it would look something like (SONG_ID, ALBUM_ID, ALBUM_ORDER, ... more song level info ). Your query would then become:
select *
  from songs a
  join songs b
    on a.album_id = b.album_id
 where a.song_id = 1
   and b.album_order > a.album_order

A: It looks like you need subqueries
SELECT * FROM song_table WHERE album =
    (SELECT album FROM song_table WHERE id = 12)

This query get all rows that share the same album with the row having id = 12
If your subquery may return more than one row, you need IN:
SELECT * FROM song_table WHERE album IN
    (SELECT album FROM song_table WHERE genre = "Techno")

This query get all rows that have an album which (the album) contains genre = "Techno" (All songs in any album that contains (at least one) Techno songs)

A:
Currently I get the row, check the album and track field, then do another MySQL query based on album field and check if there is another track after the current one.

What's the problem with it? Is it slow, or inconvenient, or too complicated?
Do you have any practical reason to look for another solution?

I was wondering if this is possible to make MySQL do a "double search"

Even if there is a positive answer, not everything that is "possible" deserves an implementation.
Your current setup is plain and simple, you can maintain it yourself.
While every proposed solution being complex, require more knowledge to maintain and may lead to some problems, as Mysql have difficulties with interpreting complex queries and easily make things worse.


text:
Q: Trying to check for 3 of a kind with arrays (Yahtzee) C++ I am trying to check for if the kept dice rolls (which can be up to 5) are 3 of a kind or not, so I'm trying to compare the dice roll values to each other.
The first value of R is showing as 0 of course, but the second value of R after the code is run is showing as 8191 every time, and I'm not entirely sure why.
I've also tried using
r++ instead of r += r+1, but of course that didn't change anything.
int r = 0;
          cout << "first value of R is " << r << endl;
          for(int t = 0; t < 5; t++) {
            for(int w = 0; w < 5; w++) {
              if(keptDice[t] == keptDice[w] ) {
                r += r + 1;
              }
            }
          }
          cout << "Value of R is " << r << endl;

A: r += r + 1

is the same as writing
r = r + r + 1

r is doubling every time.  Interestingly, it's always 1 less than 2^n
r = 0 + 0 + 1 (1)
r = 1 + 1 + 1 (3)
r = 3 + 3 + 1 (7)
r = 7 + 7 + 1 (15)
r = 15 + 15 + 1 (31)
r = 31 + 31 + 1 (63)
r = 63 + 63 + 1 (127)
r = 127 + 127 + 1 (255)
r = 255 + 255 + 1 (511)
r = 511 + 511 + 1 (1023)
r = 1023 + 1023 + 1 (2047)
r = 2047 + 2047 + 1 (4095)
r = 4095 + 4095 + 1 (8191)

Your program is counting 13 matches.  For yahtzee, you probably want an array that counts matches, otherwise you're doubling up on each die.  For example, if you had
1 2 3 4 1

It would count the first 1 matching the last die AND the last die matching the first (2 matches).
What would be more sensible is to count how many 1's you have, how many 2s you have, and store in an array
int diceCount[6];
for(int num = 1; num <= 6; num++) {
        for(int w = 0; w < 5; w++) {
          int count = 0;
          if(keptDice[w] == num ) {
            count++;
          }
          diceCount[num-1] = count;
        }

This way when it's done, if you had two 1's, then diceCount[0] will be 2

A: The point is that in the second for loop yo have tor start from t (int w = t;...) otherwise you would compare each dice with itself which will be naturally equal. Plus use r++ instead of r += r + 1 which is definitely wrong but I think that is just a misspelling.
int r = 0;
cout << "first value of R is " << r << endl;
for(int t = 0; t < 5; t++) {
    for(int w = t; w < 5; w++) {
        if(keptDice[t] == keptDice[w] ) {
            r++;
        }
    }
}
cout << "Value of R is " << r << endl;

A: Based on your approach, but generalized to N-of-a-kind:
int N = 3; // N in [1;5]
bool isNOfAKind = false;
for(int t = 0; t < 6-N; t++) { // skip searches with less elements than N
    int r = 0; // r must be reset for each count
    for(int w = t+1; w < 5; w++) { // avoid comparing to self
        if(keptDice[t] == keptDice[w]) {
            r++;
        }
    }
    // found a solution already? then bail out.
    if(r == N) {
        isNOfAKind = true;
        break;
    }
}
cout << N << " of a kind? " << isNOfAKind << endl;


text:
Q: What is the true difference between set.seed(n) and set.seed(n+1) I am trying figure out how the set.seed() function works in R.
I am curious whether if set.seed( 3 ) and set.seed( 4 ) these are more likely to generate duplicate samples than if set.seed( 3 ) and set.seed( 100 )?
If yes, how many unique samples a set.seed( 3 ) can generate, before a match in the samples generated by set.seed( 4 ) appears?
If not, can I conclude that a different n in set.seed( n ) does not mean anything as long as they are different?
I heard something related to independent random stream? Is this n related to that?
If yes, how can I define an independent random stream?
I have already read What does the integer while setting the seed mean?, but it looks does not answer my questions.

A: Let me also try to give a brief easy answer. I do believe the two comments are useful.
We sometimes need random numbers in our programs. Computer rely on an algorithm to generate random numbers. Because of this, we have the option to re-create the sequence of random numbers generated. This is quite useful in reproducing someones work. In R, if we use
sed.seed(42)
runif(5)

at any point, it will always give the same sequence of random numbers.
It is not expected that there be a relationship between set.seed(n) and set.seed(n+1),  or set.seed(n1) and set.seed(n2). Or, it is expected that set.seed(3) is not going to generate stream of set.seed(4) after a number of iterations, and vice versa.
So, in general, one can treat sequences of random numbers generated by different seeds to be independent.

A: I think it's a bad idea to make any assumptions about the relationship between streams of random numbers that are produced by two different seeds unless the underlying random number generator documents the relationship. For example, I was surprised to learn that the default Mersenne-Twister RNG acts like this:
> set.seed(0)
> x <- runif(10)
> set.seed(1)
> y <- runif(10)
> x[2:10] == y[1:9]
[1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE

I haven't noticed this kind of behavior for any other pair of seed values, but that was enough to scare me away from making assumptions.
If you care about these issues, you should read about the nextRNGStream and nextRNGSubStream functions in the parallel package. These are intended to generate .Random.seed values that result in independent streams of random numbers.


text:
Q: Can't use .toPandas() or .collect() after applying pandas udf: IndexError I am using pandasUDF to apply standard ML python libraries to pyspark DataFrame. After defining the schema and making predictions I get the pyspark DF as an output.
Now, I want to do some stuff with this predictions dataframe, e.g. I try to sum up all the values in the column "weekly_forecast_1". When I apply .collect() or .toPandas() methods, I get the following error in .fit()
IndexError: too many indices for array:array is 0-dimensional, but 1 were indexed

I get the above error whenever I try to apply .collect() or .toPandas() methods to the whole DataFrame or to some of its columns. I tried to make a copy of DF and the apply the methods, but it results in the same error.
P.S. the error is the same for different ML libraries (e.g. statsmodels.ExponentialSmoothing, fbprophet, sklearn RandomForestRegressor etc)

A: The error
IndexError: too many indices for array:array is 0-dimensional, but 1 were indexed

means that you are trying to index an array with too many indices for its dimensions. Here, it seems that your array is 0-dimensional (meaning it is a scalar) and you try to index it.
Since the error is the same for multiple different libraries I think your problem comes from the UDF, and I would guess it is not returning what you expect. It probably return just a scalar inside the DF instead of a regular matrix.


text:
Q: SyncAdapter: setDeviceApps ERROR I have got this error in logcat file multiple times in a row, what is it?
Is it a problem in my code?!
E/SyncAdapter: setDeviceApps ERROR
    <title>503 Service Temporarily Unavailable</title>

503 Service Temporarily Unavailable

nginx/1.10.0 (Ubuntu)


text:
Q: error parsing 'Gemfile', unexpected <<, I started a new rails project yesterday and everything worked fine.  When I tried to run rails server or bundle install.

[!] There was an error parsing Gemfile: syntax error, unexpected <<,
  expecting end-of-input - <<<<<<< HEAD   ^. Bundler cannot continue.
#  from /home/jhyatt/code/portfolio/Gemfile:10  #
  -------------------------------------------  #  # Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
  <<<<<<< HEAD  #  gem 'rails', '~> 5.1.3'

Gemfile:
source 'https://rubygems.org'

git_source(:github) do |repo_name|
  repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
  "https://github.com/#{repo_name}.git"
end

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
<<<<<<< HEAD
gem 'rails', '~> 5.1.3'
=======
gem 'rails', '~> 5.1.1'
>>>>>>> 7eea851168152eafdda270b0524cef1d563dc203
# Use sqlite3 as the database for Active Record
gem 'sqlite3'
# Use Puma as the app server
gem 'puma', '~> 3.7'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

<<<<<<< HEAD
#Bootstrap-sass
gem 'bootstrap-sass', '~> 3.3.6'

=======
>>>>>>> 7eea851168152eafdda270b0524cef1d563dc203
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  # Adds support for Capybara system testing and selenium driver
  gem 'capybara', '~> 2.13'
  gem 'selenium-webdriver'
end

group :development do
  # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
  gem 'web-console', '>= 3.3.0'
  gem 'listen', '>= 3.0.5', '< 3.2'
  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

A: Clean your Gemfile, removing the merge conflicts and try again. Also verify the Rails version you need:
source 'https://rubygems.org'

git_source(:github) do |repo_name|
  repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
  "https://github.com/#{repo_name}.git"
end

gem 'rails', '~> 5.1.3'
gem 'sqlite3'
gem 'puma', '~> 3.7'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'bootstrap-sass', '~> 3.3.6'
gem 'coffee-rails', '~> 4.2'
gem 'turbolinks', '~> 5'
gem 'jbuilder', '~> 2.5'

group :development, :test do
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  gem 'capybara', '~> 2.13'
  gem 'selenium-webdriver'
end

group :development do
  gem 'web-console', '>= 3.3.0'
  gem 'listen', '>= 3.0.5', '< 3.2'
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end

gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]


text:
Q: How to import node-js dependency in webpack project if package already includes types definitions? chalk library already includes types definitions, and there is no need to use deprecated @types/chalk package. However, I got error TS2307: Cannot find module 'chalk'.

The chalk library project structure is:

What I did wrong? I tried colors.js library instead - same error.
Node: my project is build by Webpack for Node.js. Off course, webpack has been configured for node (includes target: 'node' option and nodeExternals plugin usage).

Link to project with problem reproduction:
https://drive.google.com/file/d/1Aro46dXM9rTw6IsaTv5TEzzXEp_sCJTQ/view?usp=sharing
Node.js installation required, and as always, npm i command before run project building.

A: You need to fix it manual by following command:
npm install chalk
npm install each-async
npm install indent-string

in case it doesn't work you need to clear cash and check the config in webpack.

A: In my case, "moduleResolution": "node" was missed in tsconfig.json.


text:
Q: CSS div border shows up, but is transparent I am trying to apply a border to only the left and right sides of a div with a solid color. When I look at the page, the elements within (which are set to fill the div width) shift over the proper number of pixels, but the border itself (a solid color) appears to not exist, or the border itself is transparent. How I get the solid color border to actually appear? Here is the CSS segment:
#menu {
border-left: 10px solid #490707;
border-right: 10px solid #490707;
}

A: The border isn't appearing because #menu height has "collapsed" due to having floated descendants (the list-items) .. you can establish a new block formatting context for #menu's descendants by adding overflow: hidden; so that the floats are respected.
http://jsfiddle.net/rtqAq/1/
Eventually, when the CSS Intrinsic & Extrinsic Sizing Module Level 3 is adopted by browsers, you'll be able to use the contain-floats value for the min-height and min-width properties so you don't have to use overflow: hidden; anymore.

*

*contain-floats

Equivalent to 'min-content' except that when applied to the extent of a block box it forces the inner extent to be large enough to contain the margin boxes of any floats that originate inside the block and that participate in the same block formatting context as the block's immediate contents.


text:
Q: Getting the value of an image field in Plone 3.x with FSS I'm trying to migrate an old Plone 3.3 site that uses
FileSystemStorage using Mikko's Simple JSON export script.
Everything runs fine, except for the absence of a value on the image fields, which are returned as empty strings (''):
[
    ...
    {
        "allowDiscussion": false,
        "contributors": [],
        "creation_date": "2009-11-04T15:15:36-02:00",
        "creators": [
            "johndoe"
        ],
        "description": "",
        "effectiveDate": null,
        "excludeFromNav": false,
        "expirationDate": null,
        "id": "banner_vertical.jpg",
        "image": "",
        "language": "",
        "location": "",
        "modification_date": "2009-11-04T15:15:37-02:00",
        "portal_type": "Image",
        "relatedItems": [],
        "rights": "",
        "subject": [],
        "title": "Banner vertical",
        "urlLegend": "http://"
    },
    ...
 ]

Any hint?
(iw.fss version used is 2.8.0rc5).

A: FSS was not known or used by the site for which the script has been made.
You might want to retrofit convert() and other methods to support your use case.


text:
Q: Mongo Error E11000 get key name using node.js I am creating an index whose having a unique index and I am trying to insert documents in that collection but using the insertMany option. I am also using Mongo Transaction also. When I am trying to insert a duplicate document in MongoDB it giving me the following index error:
MongoError: E11000 duplicate key error collection: demo.unique_values index: unique_name dup key: { : "1234", : "testing", : "en-us", : "number", : 400, : false }

  operationTime: Timestamp { _bsontype: 'Timestamp', low_: 1, high_: 1623229996 },
  ok: 0,
  errmsg: 'E11000 duplicate key error collection: demo.unique_values index: unique_name dup key: { : "1234", : "testing", : "en-us", : "number", : 400, : false }',
  code: 11000,
  codeName: 'DuplicateKey',
  '$clusterTime': {
    clusterTime: Timestamp { _bsontype: 'Timestamp', low_: 1, high_: 1623229996 },
    signature: { hash: [Binary], keyId: 0 }
  },
  [Symbol(mongoErrorContextSymbol)]: {}
}

it is giving me information about my unique index but I want the error key number field here so How I can get this?
Also as I am using MongoDB Transaction with insertMany query with ordered: false option but still it is showing error for a single field, not all fields which having duplicate values for e.g: https://docs.mongodb.com/manual/reference/method/db.collection.insertMany/#unordered-inserts.
I need all errors of Insert Many and in a proper format. I am using Transaction.
When I am using insertMany without transaction and order false it gives me error like
{
    "name": "BulkWriteError",
    "driver": true,
    "code": 11000,
    "writeErrors": [{
        "code": 11000,
        "index": 0,
        "errmsg": "E11000 duplicate key error collection: demo.unique_values index: unique_name dup key: { : \"1234\", : \"testing\", : \"en-us\", : \"number\", : \"400\", : false }",
        "op": {
            "key": "1234",
            "type_uid": "testing",
            "locale": "en-us",
            "path": "number",
            "value": "400",
            "deleted_at": false,
            "_id": "60c08ad651ab70014397dbab"
        }
    }, {
        "code": 11000,
        "index": 1,
        "errmsg": "E11000 duplicate key error collection: demo.unique_values index: unique_name dup key: { : \"1234\", : \"testing\", : \"en-us\", : \"title\", : \"tiger\", : false }",
        "op": {
            "key": "1234",
            "content_type_uid": "testing",
            "locale": "en-us",
            "path": "title",
            "value": "tiger",
            "deleted_at": false,
            "_id": "60c08ad651ab70014397dbac"
        }
    }],
    "result": {
        "ok": 1,
        "writeErrors": [{
            "code": 11000,
            "index": 0,
            "errmsg": "E11000 duplicate key error collection: demo.unique_values index: unique_name dup key: { : \"1234\", : \"testing\", : \"en-us\", : \"number\", : \"400\", : false }",
            "op": {
                "key": "1234",
                "type_uid": "testing",
                "locale": "en-us",
                "path": "number",
                "value": "400",
                "deleted_at": false,
                "_id": "60c08ad651ab70014397dbab"
            }
        }, {
            "code": 11000,
            "index": 1,
            "errmsg": "E11000 duplicate key error collection: demo.unique_values index: unique_name dup key: { : \"1234\", : \"testing\", : \"en-us\", : \"title\", : \"tiger\", : false}",
            "op": {
                "key": "1234",
                "ype_uid": "testing",
                "locale": "en-us",
                "path": "title",
                "value": "tiger",
                "deleted_at": false,
                "_id": "60c08ad651ab70014397dbac"
            }
        }],
        "writeConcernErrors": [],
        "insertedIds": [{
            "index": 0,
            "_id": "60c08ad651ab70014397dbab"
        }, {
            "index": 1,
            "_id": "60c08ad651ab70014397dbac"
        }],
        "nInserted": 0,
        "nUpserted": 0,
        "nMatched": 0,
        "nModified": 0,
        "nRemoved": 0,
        "upserted": [],
        "lastOp": {
            "ts": "6971724857717293057",
            "t": 606
        }
    }
 }

it showing all failed fields details so How I get this using Transaction
Code sample
try{
let session = await adaptor.startSession({});
await session.withTransaction(async () => {
    await adaptor.updateMany("unique_values",
                    {
                        key:{{key}},
                        uid:{{uid}},
                        locale:{{locale}},
                        type_uid:{{type_uid}},
                        deleted_at:false
                    }, {
                        $set:{
                        deleted_at:true
                    }},{session})
                    await adaptor.insertMany("unique_values",[{

"key":"1234",
"type_uid": "testing",
"locale": "en-us",
"path": "number",
"value": "400",
"deleted_at": false,
}],
{
                        ordered: false
                    },

                    );
                    await adaptor.deleteMany("unique_values",{
                        key:{{key}},
                        uid:{{uid}},
                        locale:{{locale}},
                        type_uid:{{type_uid}},
                        deleted_at:false
                    },{session})
})
}catch(error){

}

Kindly help me!

A: This is from Mongo Documenation:

Excluding Write Concern errors, ordered operations stop after an
error, while unordered operations continue to process any remaining
write operations in the queue.
Write concern errors are displayed in the writeConcernErrors field,
while all other errors are displayed in the writeErrors field. If an
error is encountered, the number of successful write operations are
displayed instead of a list of inserted _ids. Ordered operations
display the single error encountered while unordered operations
display each error in an array.

You can see in the documentation that in unordered ops the mongo drive keeps the updating the other operations and respond with write Concern what is causing an issue. In your case _id: 1234 is duplicate.
Try to add writeConcerns and you will be able to see all the duplicate Ids in a form of an array. Check this link.


text:
Q: Why doesn't $xa = x$ for all $x \in R$ imply that $a$ is the unit of $R$? We have a ring $R$ as follows:

Why is it not enough to conclude that $a$ is a unity if $xa = x$ for all $x$ in $R$?
Is it because it is by definition that the unity satisfies $ax = xa = x$ for all $x$ in $R$?
So to say $a$ in the table above is the unity is incorrect because $ba = b$ but $ab = 0$?
I'm not sure if I'm doing this right. Can somebody please help?
Thank you.

A: Note, if $R$ has a unit, then the condition $xa = x$ for all $x \in R$ implies that $a$ is the unit. To see this, let $x = 1_R$ be the unit of $R$, then $a = 1_Ra = 1_R$.
An example of a ring $R$ and a non-unit element $a \in R$ with $xa = x$ for all $x \in R$ is
$$R = \left\{\begin{bmatrix}r & 0\\ s & 0\end{bmatrix} \mid r, s \in \mathbb{R}\right\},\qquad a = \begin{bmatrix} 1 & 0\\ 0 & 0\end{bmatrix}.$$
Note that
$$\begin{bmatrix}r & 0\\ s & 0\end{bmatrix}\begin{bmatrix}1 & 0\\ 0 & 0\end{bmatrix} = \begin{bmatrix}r & 0\\ s & 0\end{bmatrix},$$
but
$$\begin{bmatrix}1 & 0\\ 0 & 0\end{bmatrix}\begin{bmatrix}r & 0\\ s & 0\end{bmatrix} = \begin{bmatrix}r & 0\\ 0 & 0\end{bmatrix} \neq \begin{bmatrix}r & 0\\ s & 0\end{bmatrix}$$
so $a$ is not a unit of $R$. In fact, as the initial discussion shows, any such example cannot have a unit.
One could also describe this ring as $\mathbb{R}^2$ with usual vector addition and product given by $(r, s)*(t, u) = (rt, st)$. In this description, the element $a$ is $(1, 0)$.

A: Right: by definition, the identity of a ring has to act as an identity on both sides of any element.


text:
Q: Problem Xvfb using python 2.7 and selenium I have a problem using "Xvfb" with Selenium. In my requirement i have to open python with a bash script. if i execute it normally python like
python file.py

it doesn't have any problem, but if i execute it directly from bash the following error happens
start error <EasyProcess cmd_param=['Xvfb', '-help'] cmd=['Xvfb', '-help'] oserror=[Errno 2] No such file or directory return_code=None stdout="None" stderr="None" timeout_happened=False>

I don't know what happends, my code in python (where the error appears)
display = Display(visible=0, size=(800, 600))
display.start()

and bash script
#!/bin/bash
PYTHON="/usr/bin/python"
MODULE="/home/user/file.py"
$PYTHON $MODULE

I will be grateful for any response
Edit:
Full message in Except
Problem to open browser: start error <EasyProcess cmd_param=['Xvfb', '-help'] cmd=['Xvfb', '-help'] oserror=[Errno 2] No such file or directory return_code=None stdout="None" stderr="None" timeout_happened=False>
EXCEPTION IN (main.py, LINE 2148 "display = Display(visible=0, size=(800, 600))"): start error <EasyProcess cmd_param=['Xvfb', '-help'] cmd=['Xvfb', '-help'] oserror=[Errno 2] No such file or directory return_code=None stdout="None" stderr="None" timeout_happened=False>


text:
Q: Using DataView as a dynamic search result table in Wicket 1.4 I'm fairly new to Wicket but I've already run into a very strange problem.
I'm creating a page with a pretty basic search form and a results table (a DataView) which is initially empty. When the user enters data into the fields and clicks "Search", the app calls some backend services which are then used to populate the DataView.
However the user has to click "Search" twice for the data to be displayed.
I finally tracked this down, and it's because Wicket is using zero for the number of items to be displayed for the first "Search" click. At the second click, the rows have already been added and Wicket has already calculated the proper number of rows to display, so it decides it will show the data.
In AbstractPageableView.getItemModels(), the size of the results to display is initially zero, because I don't load the table with any initial data probably.
I got around this problem by loading the DataView with empty rows on page load. This seems to trick the DataView into using the displaying the data for the first "Search" click.
My question is: am I doing this right? Is there another repeater that is better for this task? Is this a bug or something?

A: Finally cracked it: it was because I was loading the data in my data provider only in the iterator() method, and the data provider's size() method is usually called before the iterator() method is. I should have been loading the data in its own method and calling that method from iterator() and size(). Doing that fixed it.
Data Provider before (Splc is the DTO):
SearchResultsDataProvider implements IDataProvider<Splc> {

  /**
   * The list of search results
   */
  private List<Splc> models;

  @Override
  public void detach() {
    // Do nothing
  }

  @Override
  public Iterator<Splc> iterator(int first, int count) {
    // load the data into the list of models
    models = service.getSplcModels();
    return models.subList(....).iterator();
  }

  @Override
  public IModel<Splc> model(Splc object) {
    return new Model<Splc>(object);
  }

  @Override
  public int size() {
    return models.size();
  }
}

Data Provider after:
SearchResultsDataProvider implements IDataProvider<Splc> {

  private List<Splc> getModels() {
    // load the data into the list of models
    return service.getSplcModels();
  }

  @Override
  public void detach() {
    // Do nothing
  }

  @Override
  public Iterator<Splc> iterator(int first, int count) {
        return getModels().subList(....).iterator();
  }

  @Override
  public IModel<Splc> model(Splc object) {
    return new Model<Splc>(object);
  }

  @Override
  public int size() {
    return getModels().size();
  }
}