Q: How do I conditionally add with boost MPL? I am trying to evaluate a bitset's value based on the type arguments provided. The function I have right now is this:
template <class Set, class PartialSet>
constexpr auto tupleBitset() {
    using type =
        typename mpl::fold<
            PartialSet,
            mpl::integral_c<unsigned long long, 0>,
            mpl::eval_if<
                mpl::has_key<Set, mpl::_2>,
                mpl::plus<
                    mpl::_1,
                    mpl::integral_c<unsigned long long, 1ull << getIndex<Set, mpl::_2>()>
                >,
                mpl::_1
            >
        >::type;
    return std::bitset<mpl::size<Set>::value>(type::value);
}

Basically the gist of the function's intent is to be able to create a bitset whose bits are created based off the intersection of Set and PartialSet, both of which are mpl::sets. The function getIndex is also provided:
template <class Set, class Index>
constexpr auto getIndex() {
    return mpl::distance<
            typename mpl::begin<Set>::type,
            typename mpl::find<Set, Index>::type
        >::type::value;
}

This approach doesn't seem to work, with the compile errors evaluating down to the following:
'value' is not a member of 'boost::mpl::same_as<U1> in 'not.hpp'
'C_': invalid template argument for 'boost::mpl::aux::not_impl', expected compile-time constant expression in not.hpp

Is it possible that the left shift is not a compile time constant?

It seems that the problem is with the call to getIndex, as the mpl::_2 is not being substituted. Unfortunately, I cannot figure out how to force the substitution.

A: Problem is that you pass the place_holder to the function getIndex.
You may transform your function in struct like that
template< typename Set, typename Index > struct getIndex
    : mpl::integral_c<unsigned long long, ( mpl::distance<
            typename mpl::begin<Set>::type,
            typename mpl::find<Set, Index>::type
        >::type::value )>
{
};

template <class Set, class PartialSet>
constexpr auto tupleBitset() {
    using type =
        typename mpl::fold<
            PartialSet,
            mpl::integral_c<unsigned long long, 0>,
            mpl::eval_if<
                mpl::has_key<Set, mpl::_2>,
                mpl::plus<
                    mpl::_1,
                    mpl::shift_left<mpl::integral_c<unsigned long long, 1ull>,
                                    getIndex<Set, mpl::_2>>
                >,
                mpl::_1
            >
        >::type;
    return std::bitset<mpl::size<Set>::value>(type::value);
}

Demo


Q: Write a String Message to Remote Server Using Socket in Android I am trying to write a simple message to a remote Server using Socket in Android, The remote server was provided to me, here is my attempt, it stops at out.write
@Override
protected String doInBackground(String... params) {
    String comment = params[0];
    Log.i(TAG_STRING, "Comment is " + comment);
    String response = null;
    Socket socket = null;
    try {
        socket = new Socket("www.regisscis.net", 8080);
        DataOutputStream out = new DataOutputStream(socket.getOutputStream());
        DataInputStream in = new DataInputStream(socket.getInputStream());
        Log.i(TAG_STRING, "Calling Write");
        out.writeBytes(comment);
        out.flush();
        String resposeFromServer = in.readUTF();
        out.close();
        in.close();
        response = resposeFromServer;
        socket.close();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return response;
}

Would anyone know what I am doing wrong,

A: Turns out that I to use out.println("message") instead of out.write("message") when I post to this server. So I have updated my method like so
@Override
protected String doInBackground(String... params) {
    String comment = params[0];
    String response = null;
    Socket socket = null;
    try {
        socket = new Socket("www.regisscis.net", 8080);
        if (socket.isConnected()) {
            PrintWriter out = new PrintWriter(new BufferedWriter(
                    new OutputStreamWriter(socket.getOutputStream())), true);
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(socket.getInputStream()));
            Log.i(TAG_STRING, "Calling Write");
            out.println(comment);
            String resposeFromServer = in.readLine();
            out.close();
            in.close();
            response = resposeFromServer;
            socket.close();
        } else {
            Log.i(TAG_STRING, "Socket is not connected");
        }

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

    return response;
}


Q: Video Container for 1080p video for SD DVD (using Apple suite) This may be a bit of a stretch to post here (in terms of whether people will have an answer), since this is a fairly specific question about video work, although I am performing the entirety of this work within FCP 7, Compressor, and DVD Studio Pro.
I have 2 hours of footage edited from a HD Camcorder in FCP 7, and I need to get it onto a DVD. I want to use the highest quality container I can, and I want to be able to author and preferably burn the DVD within DVD Studio Pro. Unfortunately, DVDSP doesn't support MPEG-4, which is one of the nicest containers to put 1080p video into. It supports MPEG, which offers considerably less options for compression, and data rates.
Ultimately, my question is HOW can I export my video out of FCP (or Compressor) so that I'm sitting on a high quality file that will fit on one DVD and be compatible with DVD Studio Pro (4.7GB)? I just finished a 24 hour Compressor job with the default setting "HD DVD 60 minutes", but it gave me a 5.1GB file, which is of no use to me. The aspect ratio is also forced and it looks terrible.
HELP!

A: Just to get this 'answered' for anyone else who might come across this question.
There is no way to get 1080p or 1080i video onto a DVD. DVD's only support SD images (this goes for the disks themselfs, and the players).
You can however use BluRay to burn HD video, though this would require a BluRay burner and a BluRay player.
Have a look here for more info: http://en.wikipedia.org/wiki/DVD-Video

A: SD dvd only works with mpeg-2, and doesn't support HD signal, export your video as SD 16:9 from compressor, if you want HD on a disk has to be blu-ray


Q: Rails API + MongoDB passing parameters to the url i have simple API example with simple GET routing.
I have MongoDB and my document from collection look's like this:
{
"_id" : ObjectId("51411cf11b4cb1b19a7115c0"),
"name" : "some_name",
"type" : "some_type",
"services" : [
    "service_one",
    "service_two"
],
"location" : {
    "type" : "some_type",
    "description" : "Some  description",
},
"address" : {
    "street" : "some_street",
    "building" : "building",
    "post_code" : "some_post_code",
    "city" : "some_city",
    "province" : "some_province"
  }
}

My controller:
class V1::DataController < V1::ApplicationController

  def index
    @data = Data.all
    render 'v1/data/index'
  end

  def show
    @data = Data.find_by(name: params[:id])
    render json: @data
  end
end

I use jbuilder to render my output.
Now, my question is, how to make that parameter passed in the url, was reflected in the json result ? For example, my Mongo document have "name", so i wanna sort result by name.
http://api.loc:3000/data?name=some_name
Can you write a simple example?
Thanks.

A: Some of the naming conventions used in your example are a little weird. If all you want to do is sort I would consider changing the "name" parameter to something more descriptive. Keeping with your example the following might help.
class V1::DataController < V1::ApplicationController
  ...
  def index
    #ASC
    if data_params[:order].eql?('asc')
      @data = Data.asc(data_params[:name])
    else
      #DESC
      @data = Data.desc(data_params[:name])
    end
    render 'v1/data/index'
  end

  def data_params
    params.permit(:name, :order)
  end
end


Q: WCF Large SOAP Request Exception 400 Bad Request I am looking for solution to my WCF Error 400 Bad Request with SOAP request longer than 64K. I know there are a lot of solutions out there when I google it. However, I am still not successful in fixing my site to work. Hence, I am seeking for professional advice here.
Client Side Code:
Private Sub Calculate()
    Dim svc As New XXXService.XXXServiceClient
    Dim i As Integer
    Dim attributes As List(Of XXXService.AttributesStruct)
    Dim calculateSingleResponse As XXXService.SingleXXXResponseStruct

    Try
        attributes = New List(Of XXXService.AttributesStruct)
        attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_One", .AttributesValue = "1"})
        attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Two", .AttributesValue = "XXX"})
        attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Three", .AttributesValue = "1"})
        attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Four", .AttributesValue = "0"})
        attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Five", .AttributesValue = "1"})
        attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Six", .AttributesValue = "70"})
        attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Seven", .AttributesValue = "80"})
        attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Eight", .AttributesValue = "09.12.2012"})
        attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Nine", .AttributesValue = "12.12.2012"})
        attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Ten", .AttributesValue = "15.11.2012"})
        i = 0
        While i < 80
            attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Eleven[" & i.ToString & "]", .AttributesValue = "2"})
            attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Twelve[" & i.ToString & "]", .AttributesValue = "5"})
            attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Thirteen[" & i.ToString & "]", .AttributesValue = "1"})
            attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Fourteen[" & i.ToString & "]", .AttributesValue = "NA"})
            attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Fifteen[" & i.ToString & "]", .AttributesValue = "0"})
            attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Sixteen[" & i.ToString & "]", .AttributesValue = "0"})
            i = i + 1
        End While
        attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Seventeen", .AttributesValue = "0"})
        attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Eighteen", .AttributesValue = "0"})
        attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Nineteen", .AttributesValue = "0"})
        calculateSingleResponse = _
            svc.Calculate("Test", True, "XXX", attributes.ToArray(),{"P_XXX"})
        svc.Close()
        Response.Write("********************************************
")
        Response.Write("[ErrorCode: " & calculateSingleResponse.ErrorCode & "]
")
        Response.Write("[ErrorDescription: " & calculateSingleResponse.ErrorDescription & "]
")

    Catch ex As Exception
        Response.Write("EXCEPTION:" & "
" & ex.Message & "
" & ex.StackTrace & "
")
        If Not ex.InnerException Is Nothing Then
            Response.Write("INNER EXCEPTION:" & "
" & ex.InnerException.Message & "
" & ex.InnerException.StackTrace)
        End If
    End Try

End Sub

Client Side Config:
<system.web>
  <compilation debug="true" strict="false" explicit="true" targetFramework="4.0" />
  <httpRuntime maxRequestLength="2147483647" />
</system.web>
<system.webServer>
   <modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
<system.serviceModel>
<bindings>
  <basicHttpBinding>
    <binding name="BasicHttpBinding_IXXXService" closeTimeout="10:01:00"
      openTimeout="10:01:00" receiveTimeout="10:10:00" sendTimeout="10:01:00"
      allowCookies="false" bypassProxyOnLocal="true" hostNameComparisonMode="StrongWildcard"
      maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"
      messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true">
      <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
        maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
      <security mode="None">
        <transport clientCredentialType="None" proxyCredentialType="None"
          realm="" />
        <message clientCredentialType="UserName" algorithmSuite="Default" />
      </security>
    </binding>
  </basicHttpBinding>
</bindings>
<behaviors>
  <endpointBehaviors>
      <behavior name="BasicHttpBehaviour_IXXXService">
          <dataContractSerializer maxItemsInObjectGraph="2147483646" />
      </behavior>
    </endpointBehaviors>
</behaviors>
<client>
  <endpoint address="http://127.0.0.1:999/XXXService.svc"
    behaviorConfiguration="BasicHttpBehaviour_IXXXService" binding="basicHttpBinding"
    bindingConfiguration="BasicHttpBinding_IXXXService" contract="XXXService.IXXXService"
    name="BasicHttpBinding_IXXXService" />
</client>
</system.serviceModel>

Server Side Config:
<system.serviceModel>
    <services>
        <service name="WcfClient.XXXService">
            <endpoint address="" binding="wsHttpBinding" bindingConfiguration="BasicHttpBinding_IXXXService"
                contract="WcfClient.IXXXService" />
            <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
            <host>
                <timeouts closeTimeout="00:01:10" openTimeout="00:01:00" />
            </host>
        </service>
    </services>
    <bindings>
        <wsHttpBinding>
            <binding name="BasicHttpBinding_IXXXService" closeTimeout="00:01:00"
                openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                bypassProxyOnLocal="true" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
                maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"
                messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
                allowCookies="false">
                <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
                    maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
            </binding>
        </wsHttpBinding>
    </bindings>
    <behaviors>
        <serviceBehaviors>
            <behavior>

                <serviceMetadata httpGetEnabled="true"/>

                <serviceDebug includeExceptionDetailInFaults="false"/>
                <dataContractSerializer maxItemsInObjectGraph="2147483646"/>
            </behavior>
        </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
</system.serviceModel>

A: I have found the issue myself:

*

*Binding between server side and client side must be the same, hence I change both to basicHttpBinding

*Service name is case sensitive, I changed "WcfClient.XXXService" to "wcfClient.XXXService" and it works now.

Hope this can help others with the same difficulties =)


Q: Internacionalización - Error a ejecutar "django-admin compilemessages" ¿Cual es el error? ¿Cómo se puede solucionar?
A veces sucede que tengo que traducir la misma palabra o frase varias veces en el mismo sitio web. No se si ese puede ser el problema. ¿Qué solución tiene?
Error:
django-admin makemessages -l en
CommandError: errors happened while running msgmerge
/home/Documents/proyect/locale/en/LC_MESSAGES/django.po:121: duplicate message definition...
/home/Documents/proyect/locale/en/LC_MESSAGES/django.po:32: ...this is the location of the first definition
msgmerge: found 1 fatal error

django-admin makemessages -l eu
CommandError: errors happened while running msgmerge
/home/retegi/Documents/proyect/locale/eu/LC_MESSAGES/django.po:121: duplicate message definition...
/home/retegi/Documents/proyect/locale/eu/LC_MESSAGES/django.po:32: ...this is the location of the first definition
msgmerge: found 1 fatal error

en/LC_MESSAGES/django.po
30 #: applications/home/templates/base.html:143
31 msgid "Cider houses"
32 msgstr "Cider houses"

118 #: applications/home/templates/home/home.html:207
119 #, fuzzy
120 #| msgid "Cider houses"
121 msgid "Cider houses"
122 msgstr "Cider houses"

eu/LC_MESSAGES/django.po
30 #: applications/home/templates/base.html:143
31 msgid "Cider houses"
32 msgstr "Sagardotegiak"

118 #: applications/home/templates/home/home.html:207
119 #, fuzzy
120 #| msgid "Cider houses"
121 msgid "Cider houses"
122 msgstr "Sagardotegiak"

Gracias.

A: En cada archivo de traducción .po debería aparecer cada msgid una sola vez.
Si en tus fuentes utilizas "Cider houses", será traducido siempre como "Sagardotegiak", aunque lo hagas en diferentes zonas de tu web. Pero en el .po debe aparecer una sola vez.
Quítalo y fíjate cómo al hacer makemessages deberá salirte encima del msgid todos los sitios donde se utiliza.


Q: Is there any online .plist editor? I'm interested in an online application like the tool that comes with XCode, that shows the keys and values as rows, in an editable manner and handles xml plists (I don't care if it handles binary ones as well).

A: So, I was wondering the exact same thing, and when I saw this question and its answer, I said "Screw it, I'm making one!" And so I did. Two days later, here's my answer to you:
http://tustin2121.github.io/jsPlistor/
jsPListor (version 1 as of Aug 8th, 2013) will allow you to paste in the contents of an xml plist into it (via the Import button) and edit it with drag and drop and the like. When you're done, hit Export and it will package it all up into a valid plist for you to copy and paste back into the file.
There's still some bugs and glaring vacancies (like the Data Editing Dialog), but it functions. Future versions will attempt to allow saving via html5 download, and loading of files into data rows.
Feel free to examine, contribute, and submit bugs at the github repo: https://github.com/tustin2121/jsPlistor

A: I have resigned myself to the fact that there probably isn't one I will ever find.  What I have found, however, is that JSON format and text PList format are very similar, and there are plenty of JSON editors available online and for windows and mac both.  It may not be suitable for your needs, but it suited my needs just fine.  By using nothing more than a couple of find & replaces in Notepad you can get 90% of the way to a plist file.  The only big issue is semicolons vs. commas.
If you're working on a small enough file, that could be done manually.  With larger files, a simple utility app to convert JSON to PList files would probably be pretty simple to whip up if you've got the urge.
Again, this all applies only to text formatted plist files.  Most plist editors on mac at least can save a plist in text format.

A: There's Plistinator - its a native C++/Qt app for Mac, Windows and Linux desktop.  So not an online tool, but it is at least portable and runs cross-platform (in case that is what the request for a web-based editor was about).
I'm not sure if the JS version handles binary files (Plistinator does).  If you have a Mac you could edit them via the JS editor if you convert binary to XML via
plutil -convert xml myfile.plist

Note that will over-write myfile.plist with the XML version, which may not represent all the same information that the binary version can.
Full-disclosure: I am the author of Plistinator and the $12.99 goes to pay for my ramen & rent.

A: I don't think there are any plist editors online, at least not as functional as Plist Editor with Xcode.
You could use an online XML-editor, like Xmlia2.0, and code it yourself.
Why would you ever want an online tool for editing XML-files when you've got Plist Editor from xcode?

A: I wrote one once back in the day (for the old non-XML plist files). The structure is very regular, so it's not hard to create something that looks and acts more or less like the XCode plist editor.
I don't know off-hand of any online XML editors, but they must exist. Given a DTD-savvy XML editor, you ought to be able to edit plist files pretty easily.

A: Any web app that accepts .txt documents will edit plists just fine. Likewise for .xml


Q: How to display Arraylist of type String in a dialogue  I have a Arraylist of String type. How can i display it on a dialogue to a user and him select the one.also the need is to highlight the earlier selection in the made by the user.
Some code example will be helpful.
thanks

A: Try this code in ur onCreate
protected CharSequence[] Months = { "January", "February", "March", "April", "May","June", "July", "August", "September","October","November","December" };
Button selected_month = ( Button ) findViewById( R.id.button );
selected_month.setOnClickListener(new View.OnClickListener(){
                       new AlertDialog.Builder( <Classname>.this )
                  .setTitle( "Months" )
                      .setSingleChoiceItems( Months, 0, new DialogInterface.OnClickListener(){

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                Toast.makeText(<Classname>.this, Months[which], Toast.LENGTH_SHORT).show();
            }

        })
        .setPositiveButton( "OK", new DialogButtonClickHandler() )
        .setNegativeButton("No", new DialogButtonClickHandler() )
        .create();
});


Q: What's the most idiomatic way of working with an Iterator of Results? I have code like this:
let things = vec![/* ...*/]; // e.g. Vec<String>
things
    .map(|thing| {
        let a = try!(do_stuff(thing));
        Ok(other_stuff(a))
    })
    .filter(|thing_result| match *thing_result {
        Err(e) => true,
        Ok(a) => check(a),
    })
    .map(|thing_result| {
        let a = try!(thing_result);
        // do stuff
        b
    })
    .collect::<Result<Vec<_>, _>>()

In terms of semantics, I want to stop processing after the first error.
The above code works, but it feels quite cumbersome. Is there a better way? I've looked through the docs for something like filter_if_ok, but I haven't found anything.
I am aware of collect::<Result<Vec<_>, _>>, and it works great. I'm specifically trying to eliminate the following boilerplate:

*

*In the filter's closure, I have to use match on thing_result. I feel like this should just be a one-liner, e.g. .filter_if_ok(|thing| check(a)).

*Every time I use map, I have to include an extra statement let a = try!(thing_result); in order to deal with the possibility of an Err. Again, I feel like this could be abstracted away into .map_if_ok(|thing| ...).

Is there another approach I can use to get this level of conciseness, or do I just need to tough it out?

A: There are lots of ways you could mean this.
If you just want to panic, use .map(|x| x.unwrap()).
If you want all results or a single error, collect into a Result<X<T>>:
let results: Result<Vec<i32>, _> = result_i32_iter.collect();

If you want everything except the errors, use .filter_map(|x| x.ok()) or .flat_map(|x| x).
If you want everything up to the first error, use .scan((), |_, x| x.ok()).
let results: Vec<i32> = result_i32_iter.scan((), |_, x| x.ok());

Note that these operations can be combined with earlier operations in many cases.

A: filter_map can be used to reduce simple cases of mapping then filtering. In your example there is some logic to the filter so I don't think it simplifies things. I don't see any useful functions in the documentation for Result either unfortunately. I think your example is as idiomatic as it could get, but here are some small improvements:
let things = vec![...]; // e.g. Vec<String>
things.iter().map(|thing| {
     // The ? operator can be used in place of try! in the nightly version of Rust
    let a = do_stuff(thing)?;
    Ok(other_stuff(a))
// The closure braces can be removed if the code is a single expression
}).filter(|thing_result| match *thing_result {
        Err(e) => true,
        Ok(a) => check(a),
    }
).map(|thing_result| {
    let a = thing_result?;
    // do stuff
    b
})

The ? operator can be less readable in some cases, so you might not want to use it.
If you are able to change the check function to return Some(x) instead of true, and None instead of false, you can use filter_map:
let bar = things.iter().filter_map(|thing| {
    match do_stuff(thing) {
        Err(e) => Some(Err(e)),
        Ok(a) => {
            let x = other_stuff(a);
            if check_2(x) {
                Some(Ok(x))
            } else {
                None
            }
        }
    }
}).map(|thing_result| {
    let a = try!(thing_result);
    // do stuff
    b
}).collect::<Result<Vec<_>, _>>();

You can get rid of the let a = try!(thing); by using a match in some cases as well. However, using filter_map here doesn't seem to help.

A: Since Rust 1.27, Iterator::try_for_each could be of interest:

An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error.
This can also be thought of as the fallible form of for_each() or as the stateless version of try_fold().

A: You can implement these iterators yourself. See how filter and map are implemented in the standard library.
map_ok implementation:
#[derive(Clone)]
pub struct MapOkIterator<I, F> {
    iter: I,
    f: F,
}

impl<A, B, E, I, F> Iterator for MapOkIterator<I, F>
where
    F: FnMut(A) -> B,
    I: Iterator<Item = Result<A, E>>,
{
    type Item = Result<B, E>;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.iter.next().map(|x| x.map(&mut self.f))
    }
}

pub trait MapOkTrait {
    fn map_ok<F, A, B, E>(self, func: F) -> MapOkIterator<Self, F>
    where
        Self: Sized + Iterator<Item = Result<A, E>>,
        F: FnMut(A) -> B,
    {
        MapOkIterator {
            iter: self,
            f: func,
        }
    }
}

impl<I, T, E> MapOkTrait for I
where
    I: Sized + Iterator<Item = Result<T, E>>,
{
}

filter_ok is almost the same:
#[derive(Clone)]
pub struct FilterOkIterator<I, P> {
    iter: I,
    predicate: P,
}

impl<I, P, A, E> Iterator for FilterOkIterator<I, P>
where
    P: FnMut(&A) -> bool,
    I: Iterator<Item = Result<A, E>>,
{
    type Item = Result<A, E>;

    #[inline]
    fn next(&mut self) -> Option<Result<A, E>> {
        for x in self.iter.by_ref() {
            match x {
                Ok(xx) => if (self.predicate)(&xx) {
                    return Some(Ok(xx));
                },
                Err(_) => return Some(x),
            }
        }
        None
    }
}

pub trait FilterOkTrait {
    fn filter_ok<P, A, E>(self, predicate: P) -> FilterOkIterator<Self, P>
    where
        Self: Sized + Iterator<Item = Result<A, E>>,
        P: FnMut(&A) -> bool,
    {
        FilterOkIterator {
            iter: self,
            predicate: predicate,
        }
    }
}

impl<I, T, E> FilterOkTrait for I
where
    I: Sized + Iterator<Item = Result<T, E>>,
{
}

Your code may look like this:
["1", "2", "3", "4"]
    .iter()
    .map(|x| x.parse::<u16>().map(|a| a + 10))
    .filter_ok(|x| x % 2 == 0)
    .map_ok(|x| x + 100)
    .collect::<Result<Vec<_>, std::num::ParseIntError>>()

playground


Q: escape characters in Swift I specifically am wondering how you could escape a newline in Swift, but generic escape characters would be great too.
In Python you can do this:
print("Dear grandma, \nHow are you?")

How can you do this in Swift?

A: Newlines as \n work in Swift string literals too.
Check out the docs: Special Unicode Characters in String Literals

A: Here is an example replacing a unicode character in a string with a comma (to give you a sense of using escaped unicodes).
address = address.stringByReplacingOccurrencesOfString("\u{0000200e}", withString: ",", options: nil, range: nil)


Q: ASIFormDataRequest upload video works in iPhone simulator but fails with iPhone for files over 1.5 MB I am using ASIHTTPFormDataRequest to upload a video file. I know my code works because when I upload a video under 1.5 MB (low quality under 1 minute 40 seconds) on the iPhone it successfully posts. I was convinced it was a server issue so we did every test ever and came back with no success. It wasn't until the other day that I was able to successfully upload a large file within the iPhone simulator. The file was over 5 MB and high quality. So I am forced to belive that it has something to do with the iPhone device itself. I've googled up a storm and came back with the same stupid response: its a server issue. Well its not...
Here is my code:
-(void) post:(NSData *) pVideoData progressBarView:(UIProgressView *) pProgressBarView{

    pVideoData = [NSData dataWithContentsOfFile: m_pAppDelegate.m_pAppData.m_pPhotoURL];
  NSString *urlAddress = [NSString stringWithString:@"https://api.sitename.com/action/upload"];
NSURL *url = [NSURL URLWithString:urlAddress];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];

[request setPostValue:API_KEY forKey:@"api_key"];
[request setPostValue: m_pAppDelegate.m_pAppData.m_sTokenKey forKey:@"user_token"];

[request setPostValue: @"somename" forKey:@"tag"];
[request setPostValue: [AppData getIPAddress] forKey:@"ip"];

[request setData:pVideoData forKey:@"file"];

request.numberOfTimesToRetryOnTimeout = 3;
[request setDelegate:self];
  [request showAccurateProgress];

[request setShouldStreamPostDataFromDisk:YES];
[request setDidFinishSelector:@selector(postRequestSuccess:)];
[request setDidFailSelector:@selector(postRequestFailed:)];
[request startAsynchronous];
    [request setUploadProgressDelegate: pProgressBarView];}

Everything works fine. Please note that I have already tried the following: synchronous download, & setfile. But I don't belive that the problem lies in my code or my server.
Here is the data I get while uploading: please note the differences between the two.
SUCCESSFUL VIDEO UPLOAD:
2012-03-13 14:31:06.413 MYAPP[7805:707] [STATUS] Starting asynchronous request <ASIFormDataRequest: 0xb9bc00>
2012-03-13 14:31:06.543 MYAPP[7805:8c07]
==== Building a multipart/form-data body ====
--0xKhTmLbOuNdArY-26765320-0965465416-4395-BA24-AA5CF2B58A66
Content-Disposition: form-data; name="api_key"

*SECRET    --0xKhTmLbOuNdArY-26765320-0916-4395-BA24-AA5CF2B58A66
Content-Disposition: form-data; name="user_token"

Br300MCw4P-l06SFITFCHdiifBHdOCPczX0Y830Yfabox3wLMPs2s7MlWTAS7F2TlwuhL2kiZ7mEXeDWkmDi5g
--0xKhTmLbOuNdArY-26765320-0916-4395-BA24-AA5CF2B58A66
Content-Disposition: form-data; name="tag"

NPSH Live
--0xKhTmLbOuNdArY-26765320-0916-4395-BA24-AA5CF2B58A66
Content-Disposition: form-data; name="ip"

61.197.151.129
--0xKhTmLbOuNdArY-26765320-0916-4395-BA24-AA5CF2B58A66
Content-Disposition: form-data; name="longitude"

-122.357832
--0xKhTmLbOuNdArY-26765320-0916-4395-BA24-AA5CF2B58A66
Content-Disposition: form-data; name="latitude"

47.781178
--0xKhTmLbOuNdArY-26765320-0916-4395-BA24-AA5CF2B58A66
Content-Disposition: form-data; name="file"; filename="file"
Content-Type: application/octet-stream

[920870 bytes of data]
--0xKhTmLbOuNdArY-26765320-0916-4395-BA24-AA5CF2B58A66--
==== End of multipart/form-data body ====
2012-03-13 14:31:06.550 MYAPP[7805:8c07] [CONNECTION] Request <ASIFormDataRequest: 0xb9bc00> will not use a persistent connection
2012-03-13 14:31:06.819 MYAPP[7805:8c07] [THROTTLING] ===Used: 238 bytes of bandwidth in last measurement period===
wait_fences: failed to receive reply: 10004003
2012-03-13 14:31:07.992 MYAPP[7805:8c07] [THROTTLING] ===Used: 327680 bytes of bandwidth in last measurement period===
2012-03-13 14:31:09.053 MYAPP[7805:8c07] [THROTTLING] ===Used: 655360 bytes of bandwidth in last measurement period===
2012-03-13 14:31:09.820 MYAPP[7805:8c07] [STATUS] Request <ASIFormDataRequest: 0xb9bc00> finished uploading data
2012-03-13 14:31:10.070 MYAPP[7805:8c07] [THROTTLING] ===Used: 860720 bytes of bandwidth in last measurement period===
2012-03-13 14:31:11.320 MYAPP[7805:8c07] [THROTTLING] ===Used: 0 bytes of bandwidth in last measurement period===
2012-03-13 14:31:11.835 MYAPP[7805:8c07] [STATUS] Request <ASIFormDataRequest: 0xb9bc00> received response headers
2012-03-13 14:31:11.843 MYAPP[7805:8c07] [STATUS] Request <ASIFormDataRequest: 0xb9bc00> finished downloading data (105 bytes)
2012-03-13 14:31:11.854 MYAPP[7805:8c07] [STATUS] Request finished: <ASIFormDataRequest: 0xb9bc00>

FAILED UPLOAD:
[STATUS] Starting asynchronous request <ASIFormDataRequest: 0xb8e200>
wait_fences: failed to receive reply: 10004003
2012-03-13 14:21:03.093 MYAPP[7805:8c07]
==== Building a multipart/form-data body ====
--0xKhTmLbOuNdArY-E6B28382AE4C-F123-499E-8076-19CC8D41F46E
Content-Disposition: form-data; name="api_key"

*secret
--0xKhTmLbOuNdArY-E6B2AE4C-F123-499E-8076-19CC8D41F46E
Content-Disposition: form-data; name="user_token"

Br300MCw4P-l06SFITFCHdiifBHdOCPczX0Y830Yfabox3wLMPs2s7MlWTAS7F2TlwuhL2kiZ7mEXeDWkmDi5g
--0xKhTmLbOuNdArY-E6B2AE4C-F123-499E-8076-19CC8D41F46E
Content-Disposition: form-data; name="tag"

test
--0xKhTmLbOuNdArY-E6B2AE4C-F123-499E-8076-19CC8D41F46E
Content-Disposition: form-data; name="ip"

81.197.151.699
--0xKhTmLbOuNdArY-E6B2AE4C-F123-499E-8076-19CC8D41F46E
Content-Disposition: form-data; name="longitude"

-122.357874
--0xKhTmLbOuNdArY-E6B2AE4C-F123-499E-8076-19CC8D41F46E
Content-Disposition: form-data; name="latitude"

47.781192
--0xKhTmLbOuNdArY-E6B2AE4C-F123-499E-8076-19CC8D41F46E
Content-Disposition: form-data; name="file"; filename="file"
Content-Type: application/octet-stream

[3280300 bytes of data]
--0xKhTmLbOuNdArY-E6B2AE4C-F123-499E-8076-19CC8D41F46E    --
==== End of multipart/form-data body ====
2012-03-13 14:21:03.099 MYAPP[7805:8c07] [CONNECTION] Request <ASIFormDataRequest: 0xb8e200> will not use a persistent connection
2012-03-13 14:21:03.354 MYAPP[7805:8c07] [THROTTLING] ===Used: 2500 bytes of bandwidth in last measurement period===
2012-03-13 14:21:04.605 MYAPP[7805:8c07] [THROTTLING] ===Used: 0 bytes of bandwidth in last measurement period===
2012-03-13 14:21:05.698 MYAPP[7805:8c07] [THROTTLING] ===Used: 458752 bytes of bandwidth in last measurement period===
2012-03-13 14:21:06.744 MYAPP[7805:8c07] [THROTTLING] ===Used: 688128 bytes of bandwidth in last measurement period===
2012-03-13 14:21:07.755 MYAPP[7805:8c07] [THROTTLING] ===Used: 1114112 bytes of bandwidth in last measurement period===
2012-03-13 14:21:08.855 MYAPP[7805:8c07] [THROTTLING] ===Used: 950272 bytes of bandwidth in last measurement period===
2012-03-13 14:21:09.897 MYAPP[7805:8c07] [THROTTLING] ===Used: 458752 bytes of bandwidth in last measurement period===
2012-03-13 14:21:11.050 MYAPP[7805:8c07] [THROTTLING] ===Used: 393216 bytes of bandwidth in last measurement period===
2012-03-13 14:21:12.085 MYAPP[7805:8c07] [THROTTLING] ===Used: 917504 bytes of bandwidth in last measurement period===
2012-03-13 14:21:13.104 MYAPP[7805:8c07] [THROTTLING] ===Used: 458752 bytes of bandwidth in last measurement period===
2012-03-13 14:21:13.858 MYAPP[7805:8c07] [STATUS] Request <ASIFormDataRequest: 0xb8e200> finished uploading data
2012-03-13 14:21:14.354 MYAPP[7805:8c07] [THROTTLING] ===Used: 1123122 bytes of bandwidth in last measurement period===
2012-03-13 14:21:15.014 MYAPP[7805:8c07] [STATUS] Request <ASIFormDataRequest: 0xb8e200> received response headers
2012-03-13 14:21:15.017 MYAPP[7805:8c07] [STATUS] Request <ASIFormDataRequest: 0xb8e200> finished downloading data (76 bytes)
2012-03-13 14:21:15.034 MYAPP[7805:8c07] [STATUS] Request finished: <ASIFormDataRequest: 0xb8e200>

So what do you guys think the problem could be. Another note: I have tried using other wifi connections as well as turning off wifi, using 3g and turning off 3g and only using wifi. Do you think there are limits to how much a user can upload on the iPhone?
ONE LAST NOTE:
The upload apparently is successful, but I guess the file I upload becomes invalid all together. My server responds successful by telling my that everything was set and okay but the video file itself. The video file is invalid. Yet it works in the simulator...
EDIT!!
I JUST FINISHED TRYING OUT A DIFFERENT METHOD FOR MY UPLOADING, AND I GET THE EXACT SAME ERRORS FOR THE EXACT SAME CIRCUMSTANCES SO I AM STARTING TO THINK THAT IT HAS SOMETHING TO DO WITH MY CORE FILES? MAYBE ITS A MEMORY THING?
 NSURL *remoteUrl = [NSURL URLWithString:@"http://api.mysite.com/upload"];

NSURL *myfile = [NSURL URLWithString:m_pAppDelegate.m_pAppData.m_PendingInfo.m_pMovieURL];

NSData * photoImageData = [NSData dataWithContentsOfFile: m_pAppDelegate.m_pAppData.m_PendingInfo.m_pMovieURL];
NSError **error;

  // [photoImageData writeToFile:filePath atomically:YES];

   AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:remoteUrl];
NSMutableURLRequest *afRequest = [httpClient multipartFormRequestWithMethod:@"POST"
                                                                       path:@""
                                                                 parameters:nil
                                                  constructingBodyWithBlock:^(id <AFMultipartFormData>formData)
                                  {
                                      [formData appendPartWithFormData:[API_KEY dataUsingEncoding:NSUTF8StringEncoding]
                                                                  name:@"api_key"];
                                      [formData appendPartWithFormData:[m_pAppDelegate.m_pAppData.m_sTokenKey dataUsingEncoding:NSUTF8StringEncoding]
                                                                  name:@"user_token"];

                                      [formData appendPartWithFileData:photoImageData
                                                                  name:@"file"
                                                              fileName:@"test.mov"
                                                              mimeType:@"video/quicktime"];
                                      [formData appendPartWithFileURL:myfile name:@"file" error:error];
                                  }
                                  ];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:afRequest];
[operation setUploadProgressBlock:^(NSInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite) {

    NSLog(@"Sent %d of %d bytes", totalBytesWritten, totalBytesExpectedToWrite);

}];

[operation setCompletionBlock:^{
    NSLog(@"%@", operation.responseString); //Gives a very scary warning
}];

[operation start];

A: You need to increase the timeOutSeconds of your request.The default time of a request is 60 seconds.You might increase to 10 mins(600 seconds).
[request setTimeOutSeconds:600];

You also need to check that max upload file size that is specified in your php.Please go through this link this might help you.
http://drupal.org/node/97193

A: Turned out to be a problem in my .htpconfig file. I had a hard set limit set on it. Adjusting it worked like a charm!


Q: Is case-insensitive comparison of string possible for 'where' clause in vuex ORM? While filtering data from the store, I need to check whether 'name' field of the data is 'stackoverflow'. So I use:
data() {
 myname: 'stackoverflow'
},
computed: {
  user() {
   return this.$store.getters['entities/users/query']().where('name', myname).first();
  }
}

It works perfectly if the name is given as 'stackoverflow', but not for 'StackOverflow'. Can the 'where' clause be modified so that it checks case insensitive?

A: I have never used the vuex-orm but i think this should work, according to the docs
https://vuex-orm.github.io/vuex-orm/guide/store/retrieving-data.html#simple-where-clauses
computed: {
  user() {
   return this.$store.getters['entities/users/query']().where(user => user.name.toUpperCase() === this.myname.toUpperCase()).first();
  }
}

Or even
computed: {
  user() {
   return this.$store.getters['entities/users/query']().where('name', value  => value.toUpperCase() === this.myname.toUpperCase()).first();
  }
}


Q: mysql query array counter Apologies if I have the terminology wrong.
I have a for loop in php which operates a mysql query...
for ($i = 0; $i <count($user_id_pc); $i++)
{
$query2 = " SELECT job_title, job_info FROM job_description WHERE  postcode_ss = '$user_id_pc[$i]'";

$job_data = mysqli_query($dbc, $query2);

$job_results = array();

    while ($row = mysqli_fetch_array($job_data))
        {
            array_push($job_results, $row);
        }

}

The results that are given when I insert a...
print_r ($job_results);

On screen -> Array()

If I change the query from $user_id_pc[$i] to $user_id_pc[14] for example I receive one set of results.
If I include this code after the query and inside the for loop
echo $i;
echo $user_id_pc[$i] . "
";

I receive the number the counter $i is on followed by the data inside the array for that counter position.
I am not sure why the array $job_results is empty from the query using the counter $i but not if I enter the number manually?
Is it a special character I need to escape?
The full code
        <?php
print_r ($user_id_pc);

  //Select all columns to see if user has a profile
     $query = "SELECT * FROM user_profile WHERE user_id = '" . $_SESSION['user_id'] . "'";

      //If the user has an empty profile direct them to the home page

  $data = mysqli_query($dbc, $query);

  if (mysqli_num_rows($data) == 0)
    {
        echo '

Your appear not to be logged on please visit the home page to log on or register. Thank you.

';
    }
//Select data from user and asign them to variables
    else
    {
          $data = mysqli_query($dbc, $query);
      if (mysqli_num_rows($data) == 1)
      {
          $row = mysqli_fetch_array($data);
          $cw_job_name = $row['job_description'];
          $cw_rate = $row['hourly_rate'];
          $job_mileage = $row['mileage'];
          $job_postcode = $row['postcode'];
          $response_id = $row['user_profile_id'];
      }
    }

    for ($i = 0; $i <count($user_id_pc); $i++)
        {
            $query2 = " SELECT job_title, job_info FROM job_description WHERE  postcode_ss = '{$user_id_pc[$i]}'";
    $job_data = mysqli_query($dbc, $query2);
    $job_results = array();
        while ($row = mysqli_fetch_array($job_data))
            {
                array_push($job_results, $row);
            }

    echo $i;
?>

<?php

}
print ($query2);
print $user_id_pc[$i];
         ?>

A: This is primarily a syntax error, the correct syntax should be:
$query2 = " SELECT job_title, job_info FROM job_description WHERE  postcode_ss = '{$user_id_pc[$i]}'";

Note that this is correct syntax but still wrong!! For two reasons the first is that it's almost always better (faster, more efficient, takes less resources) to do a join or a subquery or a simple IN(array) type query rather than to loop and query multiple times.
The second issue is that passing parameters in this manner leave your vulnerable to sql injection. You should use prepared statements.
The correct way
if(count($user_id_pc)) {
    $stmt = mysqli_stmt_prepare(" SELECT job_title, job_info FROM job_description WHERE  postcode_ss = ?");
    mysqli_stmt_bind_param($stmt, "s", "'" . implode("','",$user_id_pc) . "'");
    mysqli_stmt_execute($stmt);
}

Note that the for loop has been replaced by a simple if

A: You have to check the query variable, instead of:
$query2 = " SELECT job_title, job_info FROM job_description WHERE  postcode_ss = '$user_id_pc[$i]'"

have you tried this:
$query2 = " SELECT job_title, job_info FROM job_description WHERE  postcode_ss = '" . $user_id_pc[$i] . "' ";

And another thing, try something different like this:
while ($row = mysqli_fetch_array($job_data))
    {
        $job_results[] = array("job_title" => $row["job_title"], "job_info" => $row["job_info");
    }

Then try to print the values.

A: Sorry but I like foreach(), so your working code is:
<?php

 // To store the result
 $job_results = [];

 foreach($user_id_pc as $id ){
   // selecting matching rows
   $query2 ="SELECT job_title, job_info FROM job_description WHERE postcode_ss = '".$id."'";
   $job_data = mysqli_query($dbc, $query2);
   // checking if query fetch any result
   if(mysqli_num_rows($job_data)){
      // fetching the result
      while ($row = mysqli_fetch_array($job_data)){
        // storing resulting row
        $job_results[] = $row;
     }
   }
}
// to print the result
var_dump($job_results);


Q: Open file for Appending with is new indication I need to append data to a file, but if the file does not exist I need to add a header before appending.
If I open the file with FileMode.Append, I cannot see a way to work out if the file is new or not.
If I open the file with
FileStream file;
boolean isNew;
try
{
    file = File.Open(path, FileMode.CreateNew);
    isNew = true;
}
catch (IOException ex)
{
    file = File.Open(path, FileMode.Append);
    isNew = false;
}

I run into the risk of another process deleting the file between the the 2 open calls and not detecting the creation of the new file.
What is the recommended way of opening for appending and detecing if create or append?

A: Does this do what you need?
try
{
    var file = File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite);

    if (file.Length == 0)
    {
        // do header stuff
    }

    // do the rest
}
catch (IOException ex)
{
    // handle io ex.
}

A: Try something like this:
if (!File.Exists(path))
{
     file = File.Open(path, FileMode.CreateNew);
     isNew = true;
     return;
}
// otherwise append to existing file
file = File.Open(path, FileMode.Append);
isNew = false;


Q: Special characters æøå in Table I have the problem that whenever I set the preamble right so that I can use the characters æ ø å in the text of the document with no problem, the special characters in tables that are entered look weird. Like in the following example:
\documentclass[12pt,a4paper]{article}
\usepackage[T1]{fontenc}
\usepackage[english, norsk]{babel}
%\usepackage[utf8]{inputenc}

\begin{document}

\section{Introduction}

æ

ø

å

\begin{table}
\caption[c]{æ ø å}
\begin{tabular}{l r r r r r r r r }
\hline
\input{testtable.tex}
\end{tabular}
\end{table}

\end{document}

The table looks like this:
\hline
åÅå   &       0.875&        3192 \\
æÆæ &      0.0793&        3192 \\
øØø &       30.61&        1671 \\
\hline

Including
\usepackage[utf8]{inputenc}

in the preamble makes the characters in the table look fine, but then texworks can't compile due to the special characters used in the text of the article.
Anyone understand why?
Thanks!
Sara
Edit:

The image above is what my output looks like when I do not include the
% !TeX encoding = utf8
suggested by @Sveinung.

The image above shows how it looks when I do include that line: Now also the characters in the text are wrong.
My settings look like this:

I have encoded both the main file and the input file to UTF-8 using Notepad.

A: First check that Texworks is set up to use UTF8. Click the Edit-menu, choose Preference, and you get a window that shall look like the screenshot below regarding character set.

Then add to both files:
% !TeX encoding = utf8

Then ensure that both file actually are saved as UTF8-files. Texworks does not convert an ANSI-file to UTF8 on saving, even if you have set up the UTF8 option. Therefore, you have to copy the file content and paste it into a brand new file, and save it again as UTF8. Or you can runt the file through a stand alone filter.
For unknown reasons, the file did not compile as long \hline was the first commands in the testtable.tex. Therefore, I moved that line to the main file.

MWE:
% !TeX encoding = utf8  %% Add this string
\documentclass[12pt,a4paper]{article}
\usepackage[T1]{fontenc}
\usepackage[english, norsk]{babel}
%\usepackage[utf8]{inputenc}

\begin{document}

\section{Introduction}

æ

ø

å

\begin{table}
\caption[c]{æ ø å}
\begin{tabular}{l r r}
\hline
\input{testtable.tex}
\end{tabular}
\end{table}

\end{document}

% testtable.tex
% !TeX encoding = utf8  %% Add this string
%\hline
åÅå & 0.875& 3192 \\
æÆæ & 0.0793& 3192 \\
øØø & 30.61& 1671 \\
%\hline


Q: Is there any way to return the element that does not pass a filter in stream? I have a list of string elements and I want to apply a filter to divide the list into two sub list, elements that start with "el" and others.
is there any way to divide the list using just one filter?
List elements = List.of("e1", "el2", "el3", "4 el", "5 el")

example:
elements.stream()
        .filter(s -> s.startWith("el))
        .collect( /* something that hold both the element that pass the filter and element that does not */ )

A: You can do it like so.

*

*use groupingBy and create a Map<String, List<String>>

*if the string starts with "el" group using the els key

*otherwise, use the others key

List<String> elements = List.of("e1", "el2", "el3", "4 el", "5 el");
Map<String, List<String>> map = elements.stream().collect(
        Collectors.groupingBy(str -> str.startsWith("el") ?
                "els" : "others"));

map.entrySet().forEach(System.out::println);

prints
els=[el2, el3]
others=[e1, 4 el, 5 el]

A: Since you have a threshold condition which determine if an item will go to group A, otherwise B, I suggest using partitioningBy for this.
For example:
    List<String> elements = List.of("e1", "el2", "el3", "4 el", "5 el");
    //create the partition map
    Map<Boolean,List<String>> partitionMap = elements.stream()
            .collect(Collectors.partitioningBy(s-> s.startsWith("el")));

    //getting the partitions
    List<String> startsWithEl = partitionMap.get(true);
    List<String> notStartingWilEl = partitionMap.get(false);

Now each list will hold its partition .


Q: complex number with high powers The question:
$\frac{(-1-\sqrt{3}i)^{73}}{2^{73}}$
I really do not even know where to begin. Am I suppose to expand $(-1-\sqrt{3}i)$ 73 times?

A: Hint:
$$\frac{(-1-\sqrt{3}i)^{73}}{2^{73}}=(-\frac{1}{2}-\frac{\sqrt{3}}{2}i)^{73}$$
and
$$(-\frac{1}{2}-\frac{\sqrt{3}}{2}i)^{3}=1$$

A: Hint:
$$\frac{-1-\sqrt{3} i}{2} = r e^{i \theta}$$
for some real number $\theta$ and nonnegative number $r$. Can you find what $\theta$ and $r$ are? Euler's formula may be helpful. Raising $r e^{i \theta}$ to the $73$rd power is a bit easier.

A: Hint: $\quad\dfrac{-1-i\sqrt 3}2=\mathrm e^{\tfrac{4i\pi}3}.$

A: A systematic approach goes like this.
1) Represent any complex number $z\in\mathbb{C}$, your example being $z=\frac{-1-\sqrt{3} i}{2}$ in polar coordinates
$$z = r e^{i \theta},$$
where $$r=\sqrt{\textrm{Re}{z}^2+\textrm{Im}{z}^2}$$ and $$\theta = \arg{z} = \arctan{\frac{\textrm{Re}{z}}{\textrm{Im}{z}}}$$ unless $\textrm{Im}{z}=0$.
In your example, we find $r=\sqrt{\frac{1}{4}+\frac{3}{4}}=1$ and $\theta=-\frac{2}{3}2\pi$
2) Take the power $$z^n=r^ne^{i\theta n}$$ for $n\in\mathbb{Z}$. In your example, we obtain
$z^{73}=1^{73}e^{-i73\frac{2}{3}2\pi}=e^{-i\frac{2}{3}2\pi}=z$, because $e^{-i72\frac{2}{3}2\pi}=e^{-i48\times 2\pi}=1$.

A: Ok, what I got was:
$(-\frac{1}{2}-\frac{\sqrt{3}}{2}i)^{73}$
$|z| = \sqrt{(-1/2)^2+\sqrt{3}/2} = \sqrt{1} = 1$
tan$^{-1}$ ($-.5/ \sqrt{3}/2) = \frac{-2}{3}2\pi$
$z^{73} = 1($cos$(\frac{-2}{3}2\pi)+i$sin$(\frac{-2}{3}2\pi)$)
$z = 1^{73}($cos$(\frac{-2}{3}2\pi*73)+i$sin$(\frac{-2}{3}2\pi8*73)$)
= $-.5 + \frac{\sqrt{3}}{2}$ which is the same answer had I not multiplied by 73


Q: IIS redirect rules to multiple 500 error page I need to return a different static page, for the 500 response type, depending on the language particle of the request (fr, es, pt, etc)
Is it possible to have one static page for each language (500-fr.aspx, 500-es.aspx, 500-pt.aspx) and somehow, depending on the language particle to return the necesary static page?
Eg:  mysite.com/fr/somepage is broken and returns a 500 response, and then IIS redirects the user to 500-fr.aspx page.
Thank you

A: There is a very simple and fast way, that does not even require you to manually write url rewriting rules.
In the Error Pages module, IIS has defined the same error to display different pages according to different languages.

You can see that it has checked "Try to return the error file in the client languag". And if you enter the file path.

Error pages of different languages already exist in different language folders.
So if you want to response custom page, just change these pages or create new error pages store into different folder and change the file name in file path.


Q: I am converting a python/kivy project to apk in google colab and some extension are not working so what extension I should use for audio/font file? I use jpg file for image but when I run my app in phone it won't open but it works for PNG file.
And also for audio file I use mp3, OGG file my app won't open but when I use wav file my app works but the sound doesn't come.
And for font file, both TTF and OTF extension won't work i.e. my app won't work

A: I solve my problem a bit, now the wav file is working correctly because I add the extension of wav file in the google colab file which  created after the compilation of my files (Buildozer.spec) but the problem with jpg is still there and for mp3 also


Q: Problem 1.2 (E&M Purcell & Morin) Zero force from a triangle, multiple solutions? Problem 1.2 of the E&M text of Purcell & Morin reads:

"Two positive ions and one negative ion are fixed at the vertices of an equilateral triangle. Where can a fourth ion be placed, along the symmetry axis of the setup, so that the force on it will be zero? Is there more than one such place? You will need to solve something numerically."

The solution then says: "Let the sides of the triangle be 2 units long. Consider a point $P$ that lies a distance
$y$ (so $y$ is defined to be a positive number) beyond the side containing the
two positive ions. $P$ is a distance $y + \sqrt{3}$ from the negative ion and $\sqrt{1+y^2}$ from each of the positive ions. If the electric field equals zero at $P$, then the upward field due to the negative ion must cancel the downward field due to the two positive ions. This gives (ignoring the factor of ${e}/{4 \pi \epsilon_0}$)
$$\frac{1}{(y+\sqrt{3})^2} = 2 \cdot \frac{1}{1+y^2} \left( \frac{y}{\sqrt{1+y^2}} \right)$$
where the $y/ \sqrt{1 + y^2}$ factor in the first equality arises from taking the vertical component of the titled field lines due to the positive ions."
This equation has to be solved numerically and there is only one solution, which turns out to be $y\approx 0.1463$.
To find the other point (beyond the negative ion) where the force vanishes, all we have to do is to exchange the $\sqrt{3}$ by $-\sqrt{3}$ in the above equation and it is claimed that the solution now is $y_1\approx 6.2045$ but it seems to me there are two other solutions to this equation, namely $y_2 = \sqrt{3}$ and $y_3 \approx 0.2486$.
I can accept that there are multiple solutions to the equation but how can you figure out that $y_1$ is the one that makes sense from the point of view of physics?


Q: Rails variables not working in JavaScript code In one of my Rails partials, in which I have access to the Folder model, some JavaScript is strangely enough not working. The Folder model has instances of the Submission model which belong to it. Example JSON for a folder instance looks like this:
{"created_at":"2013-09-24T18:55:54Z","id":2,"parent_id":null,"title":"Tumblr Drafts","updated_at":"2013-09-24T18:55:54Z","user_id":1,
"submissions":
[{"content":"This is a test.","created_at":"2013-09-30T23:00:00Z","folder_id":2,"id":93,"parent_id":null,"title":null,"updated_at":"2013-09-30T23:00:00Z","user_id":1}],"children":[]}

As you can see, the submissions are included in the JSON. The controller action looks like this:
    def show
        respond_to do |format|
            format.html
            format.js
            format.json {render :json => @folder.as_json( :include => [:submissions, :children])}
        end
    end

However, when I try to run this JavaScript, it doesn't return a console.log:
<script type="text/javascript">
      var wordCount = 0;
      <% @folder.submissions.each do |submission| %>
        var words = <%= submission.content %>.split(' ');
        wordCount += words.length;
      <% end %>
      console.log(wordCount);
    </script>

I use the @folder variable everywhere else in the partial in question, and it works. I can even output the titles of all the submissions into <p> tags. Is it may because the content field can be left empty, so sometimes it returns null?

A: Your problem is right here:
var words = <%= submission.content %>.split(' ');

That will dump your submission.content value into your JavaScript without any quoting so you'll end up saying things like:
var words = blah blah blah.split(' ');

and that's not valid JavaScript. You need to quote that string and properly escape it:
// You may or may not want submission.content HTML encoded so
// you might want submission.content.html_safe instead.
var words = '<%=j submission.content %>'.split(' ');

Or better, just do it all in Ruby rather than sending a bunch of throw-away text to the browser:
<script type="text/javascript">
  var wordCount = <% @folder.submissions.map { |s| submission.content.split.length }.sum %>
  console.log(wordCount);
</script>

That assumes that your JavaScript .split(' ') is really intended to split on /\s+/ rather than just single spaces of course.


Q: rebar3 doesnt compile erlydtl file I have a problem which my rebar3 does not compile the erlydtl files (.dtl) and I have looking around for a while but not solution. Previously it worked, but after I upgrade erlang to the newest version, the *.dtl file is not compiled and sync:on_sync does not work neight.
Anyone here have any idear on that?
Here is my rebar.conf file
{erl_opts, [debug_info]}.
{deps, [
    {sync, {git, "https://github.com/rustyio/sync.git" , {branch, "master"}}},
    {erlydtl, {git, "https://github.com/erlydtl/erlydtl.git", { branch, "master"}}},
    {jsx, {git, "https://github.com/talentdeficit/jsx.git", {branch, "main"}}},
    {epgsql, {git, "https://github.com/epgsql/epgsql.git"}},
    {gen_smtp, {git, "https://github.com/gen-smtp/gen_smtp.git", {branch, "master"}}},
    {cowboy, { git, "https://github.com/ninenines/cowboy.git", {branch, "master"}}},
    poolboy
]}.

{erlydtl_opts, [
    {doc_root, "src/templates"}
    %{outdir, "ebin"},
    %{compiler_options, [report, return, debug_info]},
    %{source_ext, ".dtl"}
    %% {module_ext, "_view"}
]}.

{provider_hooks, [
    {pre_hooks, [{compile, {erlydtl, compile}}]}
]}.

{relx, [
    {release, {core, "0.1.0"}, [
        core, poolboy, erlydtl,
        account, realestate, realestate_admin,
        sync, sasl, epgsql, jsx, gen_smtp
    ]},
    {mode, dev},

    %% automatically picked up if the files
    %% exist but can be set manually, which
    %% is required if the names aren't exactly
    %% sys.config and vm.args
    {sys_config, "./config/sys.config"},
    {vm_args, "./config/vm.args"}

    %% the .src form of the configuration files do
    %% not require setting RELX_REPLACE_OS_VARS
    %% {sys_config_src, "./config/sys.config.src"},
    %% {vm_args_src, "./config/vm.args.src"}
]}.

{profiles, [
    {prod, [
        {relx, [
            %% prod is the default mode when prod
            %% profile is used, so does not have
            %% to be explicitly included like this
            {mode, prod}

            %% use minimal mode to exclude ERTS
            %% {mode, minimal}
        ]}
    ]}
]}.

{dialyzer, [
    %% Warns the undefined type or unknown function
    {warnings, [ unknown ]}
]}.

{xref_checks, [
    %% enable most checks, but avoid 'unused calls' which is often
    %% very verbose
    undefined_function_calls, undefined_functions, locals_not_used,
    deprecated_function_calls, deprecated_functions
]}.

{plugins, [
    % {rebar3_auto, {git, "https://github.com/xuchaoqian/rebar3-auto.git", {branch, "master"}}}
]}.

Thanks,


Q: Converting .pb to coreml I'm new to coreml and I'm trying to convert my tiny-yolov3 model to a coreml model, but I keep getting this error.
[SSAConverter] [78/170] Converting op type: 'Conv2D', name: 'yolov3-tiny/convolutional1/Conv2D', output_shape: (-1, 16, 416, 416).
Traceback (most recent call last):
  File "/Users/ryanyang/Desktop/DW2TF/env/lib/python3.7/site-packages/coremltools/converters/tensorflow/_tf_converter.py", line 95, in convert
    optional_inputs=optional_inputs)
  File "/Users/ryanyang/Desktop/DW2TF/env/lib/python3.7/site-packages/coremltools/converters/nnssa/coreml/ssa_converter.py", line 149, in ssa_convert
    converter.convert()
  File "/Users/ryanyang/Desktop/DW2TF/env/lib/python3.7/site-packages/coremltools/converters/nnssa/coreml/ssa_converter.py", line 567, in convert
    convert_func(node)
  File "/Users/ryanyang/Desktop/DW2TF/env/lib/python3.7/site-packages/coremltools/converters/nnssa/coreml/ssa_converter.py", line 1493, in _convert_conv2d
    '[SSAConverter] Dynamic weights in convolution not implemented')
NotImplementedError: [SSAConverter] Dynamic weights in convolution not implemented

UPDATE: I have added minimum_ios_deployment_target="13" to the converter, but now it is giving me a different error.
My code is
import tfcoreml as tf_converter
tf_converter.convert(tf_model_path = 'data/yolov3-tiny-one-class.pb',
                     mlmodel_path = 'TinyYOLO.mlmodel',
                     output_feature_names = ['yolov3-tiny/convolutional13/BiasAdd'],
                     input_name_shape_dict = {'yolov3-tiny/net1' : [1, 416, 416, 3]},
                     image_input_names = ['yolov3-tiny/net1'],
                     image_scale = 1 / 255.0,
                     minimum_ios_deployment_target="13"
                     )

and my visualizer for my pb model from tf-coreml is
---------------------------------------------------------------------------------------------------------------------------------------------
0: op name = import/yolov3-tiny/net1, op type = ( Placeholder ), inputs = , outputs = import/yolov3-tiny/net1:0
@input shapes:
@output shapes:
name = import/yolov3-tiny/net1:0 : (?, 416, 416, 3)
---------------------------------------------------------------------------------------------------------------------------------------------
1: op name = import/yolov3-tiny/convolutional1/kernel/Initializer/random_uniform/shape, op type = ( Const ), inputs = , outputs = import/yolov3-tiny/convolutional1/kernel/Initializer/random_uniform/shape:0
@input shapes:
@output shapes:
name = import/yolov3-tiny/convolutional1/kernel/Initializer/random_uniform/shape:0 : (4,)
---------------------------------------------------------------------------------------------------------------------------------------------
2: op name = import/yolov3-tiny/convolutional1/kernel/Initializer/random_uniform/min, op type = ( Const ), inputs = , outputs = import/yolov3-tiny/convolutional1/kernel/Initializer/random_uniform/min:0
@input shapes:
@output shapes:
name = import/yolov3-tiny/convolutional1/kernel/Initializer/random_uniform/min:0 : ()
---------------------------------------------------------------------------------------------------------------------------------------------
3: op name = import/yolov3-tiny/convolutional1/kernel/Initializer/random_uniform/max, op type = ( Const ), inputs = , outputs = import/yolov3-tiny/convolutional1/kernel/Initializer/random_uniform/max:0
@input shapes:
@output shapes:
name = import/yolov3-tiny/convolutional1/kernel/Initializer/random_uniform/max:0 : ()
---------------------------------------------------------------------------------------------------------------------------------------------
4: op name = import/yolov3-tiny/convolutional1/kernel/Initializer/random_uniform/RandomUniform, op type = ( RandomUniform ), inputs = import/yolov3-tiny/convolutional1/kernel/Initializer/random_uniform/shape:0, outputs = import/yolov3-tiny/convolutional1/kernel/Initializer/random_uniform/RandomUniform:0
@input shapes:
name = import/yolov3-tiny/convolutional1/kernel/Initializer/random_uniform/shape:0 : (4,)
@output shapes:
name = import/yolov3-tiny/convolutional1/kernel/Initializer/random_uniform/RandomUniform:0 : (3, 3, 3, 16)
---------------------------------------------------------------------------------------------------------------------------------------------

......
......

358: op name = import/yolov3-tiny/convolutional12/dilation_rate, op type = ( Const ), inputs = , outputs = import/yolov3-tiny/convolutional12/dilation_rate:0
@input shapes:
@output shapes:
name = import/yolov3-tiny/convolutional12/dilation_rate:0 : (2,)
---------------------------------------------------------------------------------------------------------------------------------------------
359: op name = import/yolov3-tiny/convolutional12/Conv2D, op type = ( Conv2D ), inputs = import/yolov3-tiny/route2:0, import/yolov3-tiny/convolutional12/kernel/read:0, outputs = import/yolov3-tiny/convolutional12/Conv2D:0
@input shapes:
name = import/yolov3-tiny/route2:0 : (?, 26, 26, 384)
name = import/yolov3-tiny/convolutional12/kernel/read:0 : (3, 3, 384, 256)
@output shapes:
name = import/yolov3-tiny/convolutional12/Conv2D:0 : (?, 26, 26, 256)
---------------------------------------------------------------------------------------------------------------------------------------------
360: op name = import/yolov3-tiny/convolutional12/BatchNorm/gamma/Initializer/ones, op type = ( Const ), inputs = , outputs = import/yolov3-tiny/convolutional12/BatchNorm/gamma/Initializer/ones:0
@input shapes:
@output shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/gamma/Initializer/ones:0 : (256,)
---------------------------------------------------------------------------------------------------------------------------------------------
361: op name = import/yolov3-tiny/convolutional12/BatchNorm/gamma, op type = ( VariableV2 ), inputs = , outputs = import/yolov3-tiny/convolutional12/BatchNorm/gamma:0
@input shapes:
@output shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/gamma:0 : (256,)
---------------------------------------------------------------------------------------------------------------------------------------------
362: op name = import/yolov3-tiny/convolutional12/BatchNorm/gamma/Assign, op type = ( Assign ), inputs = import/yolov3-tiny/convolutional12/BatchNorm/gamma:0, import/yolov3-tiny/convolutional12/BatchNorm/gamma/Initializer/ones:0, outputs = import/yolov3-tiny/convolutional12/BatchNorm/gamma/Assign:0
@input shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/gamma:0 : (256,)
name = import/yolov3-tiny/convolutional12/BatchNorm/gamma/Initializer/ones:0 : (256,)
@output shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/gamma/Assign:0 : (256,)
---------------------------------------------------------------------------------------------------------------------------------------------
363: op name = import/yolov3-tiny/convolutional12/BatchNorm/gamma/read, op type = ( Identity ), inputs = import/yolov3-tiny/convolutional12/BatchNorm/gamma:0, outputs = import/yolov3-tiny/convolutional12/BatchNorm/gamma/read:0
@input shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/gamma:0 : (256,)
@output shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/gamma/read:0 : (256,)
---------------------------------------------------------------------------------------------------------------------------------------------
364: op name = import/yolov3-tiny/convolutional12/BatchNorm/beta/Initializer/zeros, op type = ( Const ), inputs = , outputs = import/yolov3-tiny/convolutional12/BatchNorm/beta/Initializer/zeros:0
@input shapes:
@output shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/beta/Initializer/zeros:0 : (256,)
---------------------------------------------------------------------------------------------------------------------------------------------
365: op name = import/yolov3-tiny/convolutional12/BatchNorm/beta, op type = ( VariableV2 ), inputs = , outputs = import/yolov3-tiny/convolutional12/BatchNorm/beta:0
@input shapes:
@output shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/beta:0 : (256,)
---------------------------------------------------------------------------------------------------------------------------------------------
366: op name = import/yolov3-tiny/convolutional12/BatchNorm/beta/Assign, op type = ( Assign ), inputs = import/yolov3-tiny/convolutional12/BatchNorm/beta:0, import/yolov3-tiny/convolutional12/BatchNorm/beta/Initializer/zeros:0, outputs = import/yolov3-tiny/convolutional12/BatchNorm/beta/Assign:0
@input shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/beta:0 : (256,)
name = import/yolov3-tiny/convolutional12/BatchNorm/beta/Initializer/zeros:0 : (256,)
@output shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/beta/Assign:0 : (256,)
---------------------------------------------------------------------------------------------------------------------------------------------
367: op name = import/yolov3-tiny/convolutional12/BatchNorm/beta/read, op type = ( Identity ), inputs = import/yolov3-tiny/convolutional12/BatchNorm/beta:0, outputs = import/yolov3-tiny/convolutional12/BatchNorm/beta/read:0
@input shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/beta:0 : (256,)
@output shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/beta/read:0 : (256,)
---------------------------------------------------------------------------------------------------------------------------------------------
368: op name = import/yolov3-tiny/convolutional12/BatchNorm/moving_mean/Initializer/zeros, op type = ( Const ), inputs = , outputs = import/yolov3-tiny/convolutional12/BatchNorm/moving_mean/Initializer/zeros:0
@input shapes:
@output shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/moving_mean/Initializer/zeros:0 : (256,)
---------------------------------------------------------------------------------------------------------------------------------------------
369: op name = import/yolov3-tiny/convolutional12/BatchNorm/moving_mean, op type = ( VariableV2 ), inputs = , outputs = import/yolov3-tiny/convolutional12/BatchNorm/moving_mean:0
@input shapes:
@output shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/moving_mean:0 : (256,)
---------------------------------------------------------------------------------------------------------------------------------------------
370: op name = import/yolov3-tiny/convolutional12/BatchNorm/moving_mean/Assign, op type = ( Assign ), inputs = import/yolov3-tiny/convolutional12/BatchNorm/moving_mean:0, import/yolov3-tiny/convolutional12/BatchNorm/moving_mean/Initializer/zeros:0, outputs = import/yolov3-tiny/convolutional12/BatchNorm/moving_mean/Assign:0
@input shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/moving_mean:0 : (256,)
name = import/yolov3-tiny/convolutional12/BatchNorm/moving_mean/Initializer/zeros:0 : (256,)
@output shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/moving_mean/Assign:0 : (256,)
---------------------------------------------------------------------------------------------------------------------------------------------
371: op name = import/yolov3-tiny/convolutional12/BatchNorm/moving_mean/read, op type = ( Identity ), inputs = import/yolov3-tiny/convolutional12/BatchNorm/moving_mean:0, outputs = import/yolov3-tiny/convolutional12/BatchNorm/moving_mean/read:0
@input shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/moving_mean:0 : (256,)
@output shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/moving_mean/read:0 : (256,)
---------------------------------------------------------------------------------------------------------------------------------------------
372: op name = import/yolov3-tiny/convolutional12/BatchNorm/moving_variance/Initializer/ones, op type = ( Const ), inputs = , outputs = import/yolov3-tiny/convolutional12/BatchNorm/moving_variance/Initializer/ones:0
@input shapes:
@output shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/moving_variance/Initializer/ones:0 : (256,)
---------------------------------------------------------------------------------------------------------------------------------------------
373: op name = import/yolov3-tiny/convolutional12/BatchNorm/moving_variance, op type = ( VariableV2 ), inputs = , outputs = import/yolov3-tiny/convolutional12/BatchNorm/moving_variance:0
@input shapes:
@output shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/moving_variance:0 : (256,)
---------------------------------------------------------------------------------------------------------------------------------------------
374: op name = import/yolov3-tiny/convolutional12/BatchNorm/moving_variance/Assign, op type = ( Assign ), inputs = import/yolov3-tiny/convolutional12/BatchNorm/moving_variance:0, import/yolov3-tiny/convolutional12/BatchNorm/moving_variance/Initializer/ones:0, outputs = import/yolov3-tiny/convolutional12/BatchNorm/moving_variance/Assign:0
@input shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/moving_variance:0 : (256,)
name = import/yolov3-tiny/convolutional12/BatchNorm/moving_variance/Initializer/ones:0 : (256,)
@output shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/moving_variance/Assign:0 : (256,)
---------------------------------------------------------------------------------------------------------------------------------------------
375: op name = import/yolov3-tiny/convolutional12/BatchNorm/moving_variance/read, op type = ( Identity ), inputs = import/yolov3-tiny/convolutional12/BatchNorm/moving_variance:0, outputs = import/yolov3-tiny/convolutional12/BatchNorm/moving_variance/read:0
@input shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/moving_variance:0 : (256,)
@output shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/moving_variance/read:0 : (256,)
---------------------------------------------------------------------------------------------------------------------------------------------
376: op name = import/yolov3-tiny/convolutional12/BatchNorm/FusedBatchNorm, op type = ( FusedBatchNorm ), inputs = import/yolov3-tiny/convolutional12/Conv2D:0, import/yolov3-tiny/convolutional12/BatchNorm/gamma/read:0, import/yolov3-tiny/convolutional12/BatchNorm/beta/read:0, import/yolov3-tiny/convolutional12/BatchNorm/moving_mean/read:0, import/yolov3-tiny/convolutional12/BatchNorm/moving_variance/read:0, outputs = import/yolov3-tiny/convolutional12/BatchNorm/FusedBatchNorm:0, import/yolov3-tiny/convolutional12/BatchNorm/FusedBatchNorm:1, import/yolov3-tiny/convolutional12/BatchNorm/FusedBatchNorm:2, import/yolov3-tiny/convolutional12/BatchNorm/FusedBatchNorm:3, import/yolov3-tiny/convolutional12/BatchNorm/FusedBatchNorm:4
@input shapes:
name = import/yolov3-tiny/convolutional12/Conv2D:0 : (?, 26, 26, 256)
name = import/yolov3-tiny/convolutional12/BatchNorm/gamma/read:0 : (256,)
name = import/yolov3-tiny/convolutional12/BatchNorm/beta/read:0 : (256,)
name = import/yolov3-tiny/convolutional12/BatchNorm/moving_mean/read:0 : (256,)
name = import/yolov3-tiny/convolutional12/BatchNorm/moving_variance/read:0 : (256,)
@output shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/FusedBatchNorm:0 : (?, 26, 26, 256)
name = import/yolov3-tiny/convolutional12/BatchNorm/FusedBatchNorm:1 : (256,)
name = import/yolov3-tiny/convolutional12/BatchNorm/FusedBatchNorm:2 : (256,)
name = import/yolov3-tiny/convolutional12/BatchNorm/FusedBatchNorm:3 : (256,)
name = import/yolov3-tiny/convolutional12/BatchNorm/FusedBatchNorm:4 : (256,)
---------------------------------------------------------------------------------------------------------------------------------------------
377: op name = import/yolov3-tiny/convolutional12/BatchNorm/Const, op type = ( Const ), inputs = , outputs = import/yolov3-tiny/convolutional12/BatchNorm/Const:0
@input shapes:
@output shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/Const:0 : ()
---------------------------------------------------------------------------------------------------------------------------------------------
378: op name = import/yolov3-tiny/convolutional12/Activation, op type = ( LeakyRelu ), inputs = import/yolov3-tiny/convolutional12/BatchNorm/FusedBatchNorm:0, outputs = import/yolov3-tiny/convolutional12/Activation:0
@input shapes:
name = import/yolov3-tiny/convolutional12/BatchNorm/FusedBatchNorm:0 : (?, 26, 26, 256)
@output shapes:
name = import/yolov3-tiny/convolutional12/Activation:0 : (?, 26, 26, 256)
---------------------------------------------------------------------------------------------------------------------------------------------
379: op name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/shape, op type = ( Const ), inputs = , outputs = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/shape:0
@input shapes:
@output shapes:
name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/shape:0 : (4,)
---------------------------------------------------------------------------------------------------------------------------------------------
380: op name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/min, op type = ( Const ), inputs = , outputs = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/min:0
@input shapes:
@output shapes:
name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/min:0 : ()
---------------------------------------------------------------------------------------------------------------------------------------------
381: op name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/max, op type = ( Const ), inputs = , outputs = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/max:0
@input shapes:
@output shapes:
name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/max:0 : ()
---------------------------------------------------------------------------------------------------------------------------------------------
382: op name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/RandomUniform, op type = ( RandomUniform ), inputs = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/shape:0, outputs = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/RandomUniform:0
@input shapes:
name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/shape:0 : (4,)
@output shapes:
name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/RandomUniform:0 : (1, 1, 256, 18)
---------------------------------------------------------------------------------------------------------------------------------------------
383: op name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/sub, op type = ( Sub ), inputs = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/max:0, import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/min:0, outputs = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/sub:0
@input shapes:
name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/max:0 : ()
name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/min:0 : ()
@output shapes:
name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/sub:0 : ()
---------------------------------------------------------------------------------------------------------------------------------------------
384: op name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/mul, op type = ( Mul ), inputs = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/RandomUniform:0, import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/sub:0, outputs = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/mul:0
@input shapes:
name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/RandomUniform:0 : (1, 1, 256, 18)
name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/sub:0 : ()
@output shapes:
name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/mul:0 : (1, 1, 256, 18)
---------------------------------------------------------------------------------------------------------------------------------------------
385: op name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform, op type = ( Add ), inputs = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/mul:0, import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/min:0, outputs = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform:0
@input shapes:
name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/mul:0 : (1, 1, 256, 18)
name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform/min:0 : ()
@output shapes:
name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform:0 : (1, 1, 256, 18)
---------------------------------------------------------------------------------------------------------------------------------------------
386: op name = import/yolov3-tiny/convolutional13/kernel, op type = ( VariableV2 ), inputs = , outputs = import/yolov3-tiny/convolutional13/kernel:0
@input shapes:
@output shapes:
name = import/yolov3-tiny/convolutional13/kernel:0 : (1, 1, 256, 18)
---------------------------------------------------------------------------------------------------------------------------------------------
387: op name = import/yolov3-tiny/convolutional13/kernel/Assign, op type = ( Assign ), inputs = import/yolov3-tiny/convolutional13/kernel:0, import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform:0, outputs = import/yolov3-tiny/convolutional13/kernel/Assign:0
@input shapes:
name = import/yolov3-tiny/convolutional13/kernel:0 : (1, 1, 256, 18)
name = import/yolov3-tiny/convolutional13/kernel/Initializer/random_uniform:0 : (1, 1, 256, 18)
@output shapes:
name = import/yolov3-tiny/convolutional13/kernel/Assign:0 : (1, 1, 256, 18)
---------------------------------------------------------------------------------------------------------------------------------------------
388: op name = import/yolov3-tiny/convolutional13/kernel/read, op type = ( Identity ), inputs = import/yolov3-tiny/convolutional13/kernel:0, outputs = import/yolov3-tiny/convolutional13/kernel/read:0
@input shapes:
name = import/yolov3-tiny/convolutional13/kernel:0 : (1, 1, 256, 18)
@output shapes:
name = import/yolov3-tiny/convolutional13/kernel/read:0 : (1, 1, 256, 18)
---------------------------------------------------------------------------------------------------------------------------------------------
389: op name = import/yolov3-tiny/convolutional13/bias/Initializer/zeros, op type = ( Const ), inputs = , outputs = import/yolov3-tiny/convolutional13/bias/Initializer/zeros:0
@input shapes:
@output shapes:
name = import/yolov3-tiny/convolutional13/bias/Initializer/zeros:0 : (18,)
---------------------------------------------------------------------------------------------------------------------------------------------
390: op name = import/yolov3-tiny/convolutional13/bias, op type = ( VariableV2 ), inputs = , outputs = import/yolov3-tiny/convolutional13/bias:0
@input shapes:
@output shapes:
name = import/yolov3-tiny/convolutional13/bias:0 : (18,)
---------------------------------------------------------------------------------------------------------------------------------------------
391: op name = import/yolov3-tiny/convolutional13/bias/Assign, op type = ( Assign ), inputs = import/yolov3-tiny/convolutional13/bias:0, import/yolov3-tiny/convolutional13/bias/Initializer/zeros:0, outputs = import/yolov3-tiny/convolutional13/bias/Assign:0
@input shapes:
name = import/yolov3-tiny/convolutional13/bias:0 : (18,)
name = import/yolov3-tiny/convolutional13/bias/Initializer/zeros:0 : (18,)
@output shapes:
name = import/yolov3-tiny/convolutional13/bias/Assign:0 : (18,)
---------------------------------------------------------------------------------------------------------------------------------------------
392: op name = import/yolov3-tiny/convolutional13/bias/read, op type = ( Identity ), inputs = import/yolov3-tiny/convolutional13/bias:0, outputs = import/yolov3-tiny/convolutional13/bias/read:0
@input shapes:
name = import/yolov3-tiny/convolutional13/bias:0 : (18,)
@output shapes:
name = import/yolov3-tiny/convolutional13/bias/read:0 : (18,)
---------------------------------------------------------------------------------------------------------------------------------------------
393: op name = import/yolov3-tiny/convolutional13/dilation_rate, op type = ( Const ), inputs = , outputs = import/yolov3-tiny/convolutional13/dilation_rate:0
@input shapes:
@output shapes:
name = import/yolov3-tiny/convolutional13/dilation_rate:0 : (2,)
---------------------------------------------------------------------------------------------------------------------------------------------
394: op name = import/yolov3-tiny/convolutional13/Conv2D, op type = ( Conv2D ), inputs = import/yolov3-tiny/convolutional12/Activation:0, import/yolov3-tiny/convolutional13/kernel/read:0, outputs = import/yolov3-tiny/convolutional13/Conv2D:0
@input shapes:
name = import/yolov3-tiny/convolutional12/Activation:0 : (?, 26, 26, 256)
name = import/yolov3-tiny/convolutional13/kernel/read:0 : (1, 1, 256, 18)
@output shapes:
name = import/yolov3-tiny/convolutional13/Conv2D:0 : (?, 26, 26, 18)
---------------------------------------------------------------------------------------------------------------------------------------------
395: op name = import/yolov3-tiny/convolutional13/BiasAdd, op type = ( BiasAdd ), inputs = import/yolov3-tiny/convolutional13/Conv2D:0, import/yolov3-tiny/convolutional13/bias/read:0, outputs = import/yolov3-tiny/convolutional13/BiasAdd:0
@input shapes:
name = import/yolov3-tiny/convolutional13/Conv2D:0 : (?, 26, 26, 18)
name = import/yolov3-tiny/convolutional13/bias/read:0 : (18,)
@output shapes:
name = import/yolov3-tiny/convolutional13/BiasAdd:0 : (?, 26, 26, 18)
---------------------------------------------------------------------------------------------------------------------------------------------
OPS counts:
Placeholder : 1
ResizeNearestNeighbor : 1
ConcatV2 : 1
BiasAdd : 2
Fill : 4
MaxPool : 6
FusedBatchNorm : 11
LeakyRelu : 11
RandomUniform : 13
Sub : 13
Mul : 13
Add : 13
Conv2D : 13
VariableV2 : 59
Assign : 59
Identity : 60
Const : 116

Any help would be Greatly Appreciated !!!


Q: GoBack get called 3times uwp If i press the backbutton on my phone the GoBack method get called 3 times and i go to the start page insted of the previous page (but it works 1 time of 20). But on the PC it workes every time with only one call and Always get to the previous page.
This is the startMethod in the class:
 public DetailPageFavorites()
        {
       this.InitializeComponent();
        // If on a phone device that has hardware buttons then we hide the app's back button.
        if (ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))
        {
            this.BackButton.Visibility = Visibility.Collapsed;
            this.button_like.Margin = new Thickness(0, 0, 0, 0);
        }
        SystemNavigationManager.GetForCurrentView().BackRequested += SystemNavigationManager_BackRequested;
}

Method used if hardwareButton is pressent:
   private void SystemNavigationManager_BackRequested(object sender, BackRequestedEventArgs e)
    {
        Frame frame = Window.Current.Content as Frame;
        e.Handled = true;
        if (frame.CanGoBack)
        {
            frame.GoBack();
        }

    }

Methods used on the PC:
 private void BackButton_Click(object sender, RoutedEventArgs e)
        {
            GoBack();
        }
        private void GoBack()
        {
            Frame frame = Window.Current.Content as Frame;
            if (frame == null)
            {
                return;
            }
            if (frame.CanGoBack)
            {
                frame.GoBack();
            }
        }

A: Make sure you remove SystemNavigationManager.GetForCurrentView().BackRequested event handler before navigate to other page.
Either atPage.Unloaded event or OnNavigatedFrom method.
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
            base.OnNavigatedFrom(e);
            SystemNavigationManager.GetForCurrentView().BackRequested -= SystemNavigationManager_BackRequested;
}


Q: R: Substitute multiple unwanted variables with NAs across multiple columns Having a tough time with some data wrangling. I am trying to keep only certain author institutional affiliations in a bibliographic data frame and replace the many unwanted affiliations with NAs. I need to do this across multiple columns since papers have multiple authors (up to 68).
reproducible code:
so <- data.frame(inst_1=c("FC1","FC2","Uni1","lab3","lab2"),
                 inst_2=c("FC1","FC5","college4","laboratory1","lab2"),
                 inst_3=c("FC2","FC2","University2","lab5","lab5"),
                 inst_4=c("FC3","FC6","dept2","lab3.2","lab1"),
                 inst_5=c("FC1","FC2","Uni3","labB","lab5"))

Example data frame:
 inst_1      inst_2      inst_3 inst_4 inst_5
1    FC1         FC1         FC2    FC3    FC1
2    FC2         FC5         FC2    FC6    FC2
3   Uni1    college4 University2  dept2   Uni3
4   lab3 laboratory1        lab5 lab3.2   labB
5   lab2        lab2        lab5   lab1   lab5

I want to select every column that has the prefix "inst" (likely using str_detect), and in those selected columns replace any institution that does not contain the characters "FC" with NAs. This is necessary because this sheet has 68 institution columns (inst prefix) and hundred of rows (individual scientific articles). I can't just select which institutions to replace with NAs because there are hundreds of different institutions, while I am just interested in keeping the institutions that contain "FC".

A: 1) dplyr Use mutate/across like this
library(dplyr)

so %>%
  mutate(across(starts_with("inst"), ~ replace(., !grepl("FC", .), NA)))

giving:
  inst_1 inst_2 inst_3 inst_4 inst_5
1    FC1    FC1    FC2    FC3    FC1
2    FC2    FC5    FC2    FC6    FC2
3   <NA>   <NA>   <NA>   <NA>   <NA>
4   <NA>   <NA>   <NA>   <NA>   <NA>
5   <NA>   <NA>   <NA>   <NA>   <NA>

2) Base R or using only base R:
ok <- startsWith(names(so), "inst")
repl <- function(x) replace(x, !grepl("FC", x), NA)
replace(so, ok, lapply(so[ok], repl))

3) collapse or using the collapse package with repl from (2)
library(collapse)

tfmv(so, startsWith(names(so), "inst"), repl)

4) data.table  With data.table we define a vector of inst names and use it with repl from (2).
library(data.table)

DT <- as.data.table(so)
inst <- grep("^inst", names(so))
DT[, (inst) := lapply(.SD, repl), .SDcols = inst]


Q: Diode Bridge Rectifier using Dual Schottkey Diode Bridge I am trying to develop the first stage circuitry of a kinetic energy harvester from that is made using  magnets and a coil. I attach a photo of the harvester taken during development.

My intention is to efficiently convert the voltage coming out of the coil to a DC voltage so that I can power up a TI energy harvester IC ( hopefully BQ25505 or similar) at a later state to charge a Lithium Battery.
The very first step assigned to me is to develop a good rectifier bridge. I would like to ask from the community if I can use the following IC that has a set of schottkeys integrated by TI for my purpose.
IC : http://www.ti.com/lit/ds/symlink/uc2610.pdf
Internal Schematic of IC

I have gone through the IC and it claims to give a ~0.3V drop for 1mA current.
I have measured my harvester to not exceed 10mA of generation. It is also one of my requirements to simulate my results soon and thats why I have chosen such an IC.
My first question is Can I use this IC for my low voltage dropout rectification perpose?
My second question is that i can notice that there are two rectifier bridges. Therefore, can i provide the same AC output of the harvester coil to both bridges to with the hope of obtaining a lower voltage drop?
Finally, what are the disadvantages of following this type of an approach? Is there a better way I can rectify the generated AC energy waveform?

A:
simulate this circuit – Schematic created using CircuitLab
Figure 1. Centre-tapped energy harvester.
If you double the coil windings you can halve the diode losses as shown in Figure 1. Only one diode will be conducting at any time compared with two on a full-wave bridge.
Since each winding conducts only half the time the wire gauge can be reduced for the same total output power.
It won't hurt to parallel the diodes and may result in ever-so-slightly lower voltage drop.

A: Both of your assertions seem to be accurate. However, if you are still unsure, try it out. There is no replacement for hands on experiementation.
As for other ways to rectify, I believe this is the most efficient way to provide rectification in this circuit.


Q: How to get part of the string? I have this string:
 var MapId ='Library://London/Maps/Main-Mobile.MapDefinition'

From string above I need to get this part:
 MapId ='Library://London/'

How can I do it with help of regex or jquery?

A: You can use split() and slice() operations:

var MapId ='Library://London/Maps/Main-Mobile.MapDefinition';
MapId = MapId.split(/\//).slice(0,3).join('/') + '/';
console.log(MapId);


Q: Android Studio illegal state exception: cannot find method (view) for android:onClick I'm using radio buttons to switch the colors in a project. When the user clicks one of the radio buttons, I want the associated theme to be saved to SharedPreferences. The necessary themes are set up, but upon clicking a radio button, this error is thrown:
    java.lang.IllegalStateException: Could not find method onThemeRadio(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.widget.RadioButton with id 'theme2'

The relevant XML and Java blocks are shown below.
Java:
    public void onThemeRadio(View view){
    SharedPreferences themeStorage = PreferenceManager.getDefaultSharedPreferences(this);
    SharedPreferences.Editor themeStorageEditor = themeStorage.edit();
    boolean checked = ((RadioButton)view).isChecked();
    int themeId = themeStorage.getInt("themeId",1);
    switch(view.getId()) {
        case R.id.theme1:
            if (checked)
                themeId = 1;
            break;
        case R.id.theme2:
            if (checked)
                themeId = 2;
            break;
        case R.id.theme3:
            if (checked)
                themeId = 3;
            break;
    }
    themeStorageEditor.putInt("themeId",themeId);
    themeStorageEditor.apply();
}

XML:
            <RadioGroup
        android:id="@+id/themeRadio"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:checkedButton="@+id/theme1"
        android:orientation="horizontal">

        <RadioButton
            android:id="@+id/theme1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="onThemeRadio"
            android:text="Default Theme" />

        <RadioButton
            android:id="@+id/theme2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="onThemeRadio"
            android:text="Alternate Theme" />

        <RadioButton
            android:id="@+id/theme3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="onThemeRadio"
            android:text="Combined Theme" />
    </RadioGroup>

I've read a few similar issues, but none of the fixes worked or applied.
Thanks in advance!

A: It's difficult to tell based on the limited code you provided. But based on the error message, it would seem that you do not have the onThemeRadio(View) method in the right place. It needs to be a method on the Activity class that uses that XML layout. Use Android Studio to help figure it out. For example, does Android Studio highlight onThemeRadio(View) as an unused method? Or does the onclick attribute in XML get flagged that the method is missing or has the wrong signature? These are signs that the method is in the wrong place. You can also use the light bulb that pops up next to a highlighted onclick attribute to automatically create the method in the right place.