text:
Q: How to convert (transliterate) a string from utf8 to ASCII (single byte) in c#? I have a string object
"with multiple characters and even special characters"
I am trying to use
UTF8Encoding utf8 = new UTF8Encoding();
ASCIIEncoding ascii = new ASCIIEncoding();

objects in order to convert that string to ascii. May I ask someone to bring some light to this simple task, that is hunting my afternoon.
EDIT 1:
What we are trying to accomplish is getting rid of special characters like some of the special windows apostrophes.  The code that I posted below as an answer will not take care of that.  Basically

O'Brian will become O?Brian.  where ' is one of the special apostrophes

A: For anyone who likes Extension methods, this one does the trick for us.
using System.Text;

namespace System
{
    public static class StringExtension
    {
        private static readonly ASCIIEncoding asciiEncoding = new ASCIIEncoding();

        public static string ToAscii(this string dirty)
        {
            byte[] bytes = asciiEncoding.GetBytes(dirty);
            string clean = asciiEncoding.GetString(bytes);
            return clean;
        }
    }
}

(System namespace so it's available pretty much automatically for all of our strings.)

A: Based on Mark's answer above (and Geo's comment), I created a two liner version to remove all ASCII exception cases from a string.  Provided for people searching for this answer (as I did).
using System.Text;

// Create encoder with a replacing encoder fallback
var encoder = ASCIIEncoding.GetEncoding("us-ascii",
    new EncoderReplacementFallback(string.Empty),
    new DecoderExceptionFallback());

string cleanString = encoder.GetString(encoder.GetBytes(dirtyString));

A: This was in response to your other question, that looks like it's been deleted....the point still stands.
Looks like a classic Unicode to ASCII issue. The trick would be to find where it's happening.
.NET works fine with Unicode, assuming it's told it's Unicode to begin with (or left at the default).
My guess is that your receiving app can't handle it. So, I'd probably use the ASCIIEncoder with an EncoderReplacementFallback with String.Empty:
using System.Text;

string inputString = GetInput();
var encoder = ASCIIEncoding.GetEncoder();
encoder.Fallback = new EncoderReplacementFallback(string.Empty);

byte[] bAsciiString = encoder.GetBytes(inputString);

// Do something with bytes...
// can write to a file as is
File.WriteAllBytes(FILE_NAME, bAsciiString);
// or turn back into a "clean" string
string cleanString = ASCIIEncoding.GetString(bAsciiString);
// since the offending bytes have been removed, can use default encoding as well
Assert.AreEqual(cleanString, Default.GetString(bAsciiString));

Of course, in the old days, we'd just loop though and remove any chars greater than 127...well, those of us in the US at least. ;)

A: I was able to figure it out.  In case someone wants to know below the code that worked for me:
ASCIIEncoding ascii = new ASCIIEncoding();
byte[] byteArray = Encoding.UTF8.GetBytes(sOriginal);
byte[] asciiArray = Encoding.Convert(Encoding.UTF8, Encoding.ASCII, byteArray);
string finalString = ascii.GetString(asciiArray);

Let me know if there is a simpler way o doing it.

A: If you want 8 bit representation of characters that used in many encoding, this may help you.
You must change variable targetEncoding to whatever encoding you want.
Encoding targetEncoding = Encoding.GetEncoding(874); // Your target encoding
Encoding utf8 = Encoding.UTF8;

var stringBytes = utf8.GetBytes(Name);
var stringTargetBytes = Encoding.Convert(utf8, targetEncoding, stringBytes);
var ascii8BitRepresentAsCsString = Encoding.GetEncoding("Latin1").GetString(stringTargetBytes);


text:
Q: how to set option COMPRESS in /etc/initramfs-tools I'm trying to upgrade Ubuntu to the latest version, and I get this Error:
Not enough free disk space

The upgrade has aborted. The upgrade needs a total of 430 M free space on disk '/boot'. Please free at least an additional 37.8 M of disk space on '/boot'. You can remove old kernels using 'sudo apt autoremove' and you could also set COMPRESS=xz in /etc/initramfs-tools/initramfs.conf to reduce the size of your initramfs.

From gparted I read that my /boot partition is 732 MB, with 425 free. I would have gladly allocated more space to /boot to avoid this issue, but given where I'm at now

*

*I ran sudo apt autoremove --this made no difference.

*I would gladly do some kind of compression, but it just says set COMPRESS=xz ... --what does that mean? I guess I should change the line in /etc/initramfs-tools/initramfs.conf from

COMPRESS=lz4
to
COMPRESS=gz
... and then what? I save that file and then I reboot? I log out and log back in again? I reinitialize something somewhere with some kind of command? There should really be more clarification here on this. What does it mean to "set" the COMPRESS value

A: Type in the terminal:
sudo nano /etc/initramfs-tools/initramfs.conf

It will open the file in the editor.
Change COMPRESS=zstd to COMPRESS=xz
View screenshot
Then rebuild the images using
sudo update-initramfs -u -k all

redpajama_set_name: RedPajamaStackExchange


text:
Q: This page isn't working .Localhost is currently unable to handle this request. HTTP ERROR 500
This page isn't working
localhost is currently unable to handle this request.
HTTP ERROR 500

I have published Web API project on IIS with all configurations.
Already tried things:

*

*.Net Core hosting bundle. (added)
and I can see it in IIS target website modules.

*IIS settings checked many times.

Note:

*

*API URL is just returning a method which have string return type which is
But when I hit another method which have list return type it shows the message "localhost is currently unable to handle this request".

*Without publishing project on IIS it is working perfectly fine.
Default methods controller are working perfectly fine which returns string.
But when I call other methods in the controller it shows error message "Localhost is currently unable to handle the request"
*URL not working (calling default method which returns string)

working URL (calling another method in controller)

A: Make sure this part comes on top in your Configure method in Startup file
if (env.IsDevelopment())
   {
     app.UseDeveloperExceptionPage();
     app.UseSwagger();
     app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "learning_todo_jwt v1"));
   }

A: 1- enable  app.UseDeveloperExceptionPage(); in startup.cs file.
Now execption will show in broweser instead of "Localhost is currently unable to handle the request"
Issue was with the connection string after adding userid and password in connection string my issue resolved.
Thanks for your help and guidance.

A: If the error code you get is just 500, not 500.x, then this describes what's going on:

The app starts, but an error prevents the server from fulfilling the request.
This error occurs within the app's code during startup or while creating a response. The response may contain no content, or the response may appear as a 500 Internal Server Error in the browser. The Application Event Log usually states that the app started normally. From the server's perspective, that's correct. The app did start, but it can't generate a valid response. Run the app at a command prompt on the server or enable the ASP.NET Core Module stdout log to troubleshoot the problem.

So you need to figure out what went wrong in your app.
There are more troubleshooting steps under the Troubleshoot on IIS section. In my experience, the most useful troubleshooting step is enabling the stdout log in web.config.
<aspNetCore processPath="bin\myapp.exe" stdoutLogEnabled="true" stdoutLogFile=".\stdout" />

That should hopefully show you an error message in that file and you can search for that error.


text:
Q: creating n array of objects based on dynamic number I need to create an array based on number which is my limit. So below is my input and this the expected output I am looking out
Input
3

Expected output
[{value: 3, label: 3}, {value: 2, label: 2}, {value: 1, label: 1}, {value: 0, label: 0}]

Tried this
Array(3).map((_, i) => ({value: i, label: i  }))

But this didn't worked, any help is appreciated

A: This may be one possible solution to achieve the desired objective.
Code Snippet

const n = parseInt(prompt('Enter value for n: ').toString()) ?? 3;

console.log(
  [...Array(n+1)]
  .map(
    (x, i) => ({
      value: n-i,
      label: n-i
    })
  )
);

Explanation

*

*Create an array of n + 1 elements

*Iterate over the array and hold the index as i

*For each element, .map() an object with props value & label

*In order to get the sort-order right, use n - i as the value for both props

A: Here is a way you could achieve what you want, using a for boucle:

let input = 3;
const result=[]
for(let i = input; i>=0; i--){
  result.push({value:i, label:i})
}
console.log( result)

A shorter solution :

let input =3
console.log(Array.from(Array(input+1)).map((_, i) => ({value: i, label: i})).sort((v1, v2)=>v2.value-v1.value))

A: You need to use Array.from() like this:
Array.from(Array(3)).map((_, i) => ({value: i, label: i}))

Note that this will run from 0 to 2, not 0 to 3 as per your expected output as the length of the array is 3. The easiest way to get the output you expect would be to make it into a function and add 1 to the number supplied to the function, i.e.
const generateArray = number => Array.from(Array(number + 1)).map((_, i) => ({value: i, label: i}))

generateArray(3) // [{value: 0, label: 0}, {value: 1, label: 1}, {value: 2, label: 2}, {value: 3, label: 3}]

A:

const input = 3
const answer = []
for(let i = 0; i <= input; i++){
  let obj = {'value': i, 'label': i}
  answer.push(obj)
}

console.log(answer)


text:
Q: Excel function for ranking duplicate values I have an excel sheet containing two columns of data that I'd like to rank.
Suppose we have the following:
    A        B
    Franz    58
    Daniel   92
    Markus   37
    Jörg     58

I would like a formula to rank the above data based on column B, and where there are duplicate values (Franz and Jörg) to put the alphabetical name first. What I have at the moment is simply duplicating Franz twice:
     =INDEX(Name,MATCH(A2,Points,0))

Can someone advise me of formula / code that will rank the data and arrange duplicate values alphabetically?
Thanks

A: I would add a helper column in next to your data to help out with ties.
so in column C use
=B1+1/COUNTIF($A$1:$A$4,"<="&A1)/10

This will add on a decimal ranking system based on the name. This assumes that your numbers in column B do not have decimal places, if they do then you will need to increase the 10 on the end of the formula to account for it ie: for 2 decimal places use 1000, 3 : 10000 etc
Use this formula to get the first name
=INDEX(name,MATCH(LARGE(points,1),points,0))

adjust the 1 to 2 for the second name etc
EDIT had the sign around the wrong way

A: This will rank your data and will not repeat duplicates too:
In C2:
=SUM(1*(b2>$b$2:$b$5))+1+IF(ROW(b2)-ROW($b$2)=0,0,SUM(1*(b2=OFFSET($b$2,0,0,INDEX(ROW(b2)-ROW($b$2)+1,1)-1,1))))

CTRL+SHIFT+ENTER to turn it into an array
Drag these down to C5 and it will not duplicate rank where the name is the same, it will rank them alphabetically if they are the same.
Then if you wanted to order them automatically in order of top performer/score you then do this:
Putting this in E2:
=INDEX(A2:A5,MATCH(LARGE(C2:C5,ROW()-1),C2:C5,0))

...and drag down
Then use a vlookup on your data to return the score putting this in F2:
=vlookup(E2,A2:C5,2,false)

...and drag down
This should give you a table of highest scoring people in score order.

A: Assuming A2 is the first of the ranked points scores try this version
=INDEX(Name,SMALL(IF(A2=Points,ROW(Points)-MIN(ROW(Points))+1),COUNTIF(A$2:A2,A2)))
confirmed with CTRL+SHIFT+ENTER and copied down
Requires the Name list to be sorted because names with duplicate scores will be listed in the order shown


text:
Q: Which C# IDE offers the most extensive AST access? the core part of the bachelor thesis which I am writing right now is a plugin for a C# IDE that offers a few refactorings (it comes to more than simple refactorings but I want to keep it simple for the moment).
I've always been working with Visual Studio so far. However, I've heard that their AST access is rather uncomfortable.
Alternatives are MonoDevelop and SharpDevelop. Another way to work with Visual Studios AST would be to access it via a custom ReSharper Plugin.
Does anyone of you have experience in writing Plugins for any of those target applications? What do you think? I appreciate every advice and disadvice.
Thanks,
TH

A: An advantage of using MonoDevelop or SharpDevelop is that they're open-source, so you can be sure to have full access to the AST - you can go into the core and modify things, if necessary. Another advantage is that they're 100% managed code, so much easier to develop and debug. Plus, you're more likely to be able to get hold of core developers and ask them detailed questions.
If you're interested if working with MonoDevelop, I'd recommend you implement your refactoring directly in the existing Refactoring addin. We'd love to have more refactoring features :)
The codebase has been undergoing a bit of churn in master because we switched to a new AST and a parser based on the Mono C# parser, and the refactorings have not yet been ported over. I'd recommend you head over to our mailing list or IRC and ask some more specific questions there, so we can give you some more specific pointers.

A: I believe VS 2010 has very good native support for plugins using MEF. Here's a guide:
http://msdn.microsoft.com/en-us/library/dd885242.aspx
You can also use Devexpress DXCore, it's free with CodeRush Express.

A: The best AST access for refactorings is offered by NRefactory 5, a complete rewrite of the previous NRefactory version (which is used in both SharpDevelop and MonoDevelop).
For SharpDevelop we plan to use the new NRefactory in SharpDevelop 5.0; and MonoDevelop will also migrate to it eventually (MonoDevelop is already using the new AST, but not yet the new type system/semantic analysis).
The main goal for this rewrite was to:

*

*Provide a rich AST with position information for every token, making refactorings easier to write

*Improve the semantic analysis performance

*Eliminate some bad design decisions from the previous version (IExpressionFinder, and how referenced assemblies are handled)

In the future, you might also want to look at Microsoft's Compiler-As-A-Service.

A: Also be sure to checkout ReSharper from http://www.jetbrains.com/resharper which is a plug-in for VS that adds many refactorings


text:
Q: Vue.js select dropdown option selected attribute problem I have the following code for a select dropdown in html:
<select class="form-select" name="" id="" v-model="rp">
<option v-for="(educationGroup,index) in educationGroupList" :key="index" :value='educationGroup.id' :v-if="educationGroup.id == 2" selected>{{ educationGroup.name }}</option>
</select>

My problem is how can i set selected attribute in vue.js. IN my code "selected" code doesn't work.

A: You can try calling an change event with @change
  <select class="form-select" name="" id="" v-model="rp" @change="onChange()">
    <option v-for="(educationGroup,index) in educationGroupList" :key="index" :value='educationGroup.id' :v-if="educationGroup.id == 2" selected>{{ educationGroup.name }}</option>
</select>

And then call onChange function in methods to get selected value as below:
export default {

    methods: {
    onChange: function() {
      var options = event.target.options
      if (options.selectedIndex > -1) {
        var value= options[options.selectedIndex].getAttribute('value');
        console.log(value)
      }
    }
  },
}

A: You can make the selection with two options.
Option 1: Use v-model.
In this scenario, the value assigned for v-model should match with the value for option.
Example: In my example the value for option is assigned as educationGroup.id where educationGroup is individual objects in array educationGroupList
<select class="form-select" name="" id="" v-model="rp">
  <option
    v-for="(educationGroup,index) in educationGroupList"
    :key="index"
    :value='educationGroup.id'
    :v-if="educationGroup.id == 2">
    {{ educationGroup.name }}
  </option>
</select>

Option 2: Use selected attribute for option.
Here selected is an property that accepts dynamic value. So it should be prefixed with a : and its value should be assigned with a condition on which the selection must be done. He in the below example :selected="educationGroup.id == 1". So the option with id valie 1 will be selected.
<select class="form-select" name="" id="">
  <option
    v-for="(educationGroup,index) in educationGroupList"
    :key="index"
    :value='educationGroup.id'
    :v-if="educationGroup.id == 2"
    :selected="educationGroup.id == 1">
      {{ educationGroup.name }}
  </option>
</select>

Find the working example for both.
https://codepen.io/devkr/pen/poPRdWm


text:
Q: Displaying delimited data in Java console So I'm trying to display CSV data (delimited) read by a file reader onto the console using String.format to keep the display clean.
Here is the sample data
Color, Number, Letter
Red,    1002,    X
Blue,   1769,    Y
Greed,  1769,    Z
Whereas the code I use is as follows
try {

                fr = new FileReader(filepath);
                Scanner scan = new Scanner(fr);
                scan.useDelimiter(",");
                while(scan.hasNext()) {
                    String t = scan.next();
                    t = String.format("%10s", t);
                    System.out.print(t);

What I observed was that the last string of preceding line and first string of current line (made bold and italic in sample data) are combined into one string due to the delimiter.
This happens for every line and messes up the display. I'm struggling to find a way around using only string.format method. Is this a limitation that I have to accept?

A: did you try to use "\n" also? May be  scan.useDelimiter(",\n");

A: I don't think a Scanner is how you should read the data from the csv file. Instead, use a more up-to-date way, that is java.nio.
I assume your filepath is a String, then you can read each line separately into a List<String> using this line of code (you may have to adjust the StandardCharsets value):
List<String> allLines = Files.readAllLines(Paths.get(filepath), StandardCharsets.ISO_8859_1);

In case you just want to display the data with System.out, you can do it like this,

it will work well for small files (loads all the file content into the RAM)

public static void main(String[] args) {
    // THIS HAS TO BE ADJUSTED TO YOUR PATH, OF COURSE
    String filePathString = "P:\\ath\\to\\your\\file.csv";

    Path filePath = Paths.get(filePathString);

    List<String> csvLines = new ArrayList<>();

    try {
        // This reads all the lines of the file into the List<String>
        csvLines = Files.readAllLines(filePath, StandardCharsets.ISO_8859_1);
    } catch (IOException e) {
        System.err.println("IOException while reading the csv file!");
        e.printStackTrace();
    }

    if (csvLines.size() > 0) {
        System.out.println(csvLines.size() + " lines read, here they are:\n");

        csvLines.forEach(csvLine -> {
            System.out.println(csvLine);
        });

    } else {
        System.err.println("No lines read...");
    }
}

For big files, you should be using a Stream (does not load everything into the RAM)

public static void main(String[] args) {
    // THIS HAS TO BE ADJUSTED TO YOUR PATH, OF COURSE
    String filePathString = "P:\\ath\\to\\your\\file.csv";

    Path filePath = Paths.get(filePathString);

    List<String> csvLines = new ArrayList<>();

    try {
        // This is the only difference: streaming the file content line by line
        Files.lines(filePath, StandardCharsets.ISO_8859_1).forEach(line -> {
            csvLines.add(line);
        });
    } catch (IOException e) {
        System.err.println("IOException while reading the csv file!");
        e.printStackTrace();
    }

    if (csvLines.size() > 0) {
        System.out.println(csvLines.size() + " lines read, here they are:\n");

        csvLines.forEach(csvLine -> {
            System.out.println(csvLine);
        });

    } else {
        System.err.println("No lines read...");
    }

}

You don't have to use String.format(...) at all


text:
Q: dropwizard max json body size I am using dropwizard for REST Services and would like to limit maximum body (json) size for POST request.
I tried setting org.eclipse.jetty.server.Request.maxFormContentSize to 1 but that doesn't limit body size.
If there any other way to set the limit ?

A: You can get the MutableServletContextHandler from the DropWizard environment:
environment.getApplicationContext().setMaxFormContentSize(1024);

However, the MaxFormContentSize only applies to form encoded requests.
To limit the size of the request body for a POST request, you can check the content length when you handle the request in your Resource class:
@POST
@Path("/test")
public Response test(@Context final HttpServletRequest request) {
    int contentLength = request.getContentLength();
    if (contentLength == -1 || contentLength > MAX_REQUEST_SIZE) {
        // fail the request
    }
    // do work
}


text:
Q: 'configure' failing with Android NDK standalone toolchain I'm trying to build something with the Android NDK standalone compiler toolchain, but I'm getting this error:
Updating bundled third-party dependencies...

bash -c 'mkdir -p output/{debug,release,test}/{FCollada/{FCDocument,FMath,FUtils,FColladaTest/{FCTestAssetManagement,FCTestExportImport,FCTestXRef}},FColladaPlugins/FArchiveXML}'
cp output/libFColladaSD.a ../lib/libFColladaSD.a
cp output/libFColladaSR.a ../lib/libFColladaSR.a

Building SpiderMonkey...

SpiderMonkey build options: --disable-tests
loading cache ./config.cache
checking host system type... x86_64-unknown-linux-gnu
checking target system type... x86_64-unknown-linux-gnu
checking build system type... x86_64-unknown-linux-gnu
checking for mawk... mawk
checking for perl5... no
checking for perl... /usr/bin/perl
checking for gcc... gcc
checking whether the C compiler (gcc  ) works... yes
checking whether the C compiler (gcc  ) is a cross-compiler... no
checking whether we are using GNU C... yes
checking whether gcc accepts -g... yes
checking for c++... arm-linux-androideabi-g++
checking whether the C++ compiler (arm-linux-androideabi-g++  ) works... no
configure: error: installation or configuration problem: C++ compiler cannot create executables.
ERROR: SpiderMonkey build failed

This is what the config.log says: http://pastebin.com/5AFZG4CX
My ANDROID_NDK_ROOT is set as follows:
afeder@ubuntu:~/android/0ad/build/workspaces$ echo $ANDROID_NDK_ROOT
/home/afeder/android/android-ndk-r7-crystax-4

What might be the cause or how do I debug it? Thank you.

A: It looks like it can't find arm-linux-androideabi-g++. Try searching for it in the NDK folder and adding the directory to your PATH.
Mine is here:
ndk/toolchains/arm-linux-androideabi-4.4.3/prebuilt/linux-x86/bin/arm-linux-androideabi-g++

A: To me this looks broken:
checking host system type... x86_64-unknown-linux-gnu
checking target system type... x86_64-unknown-linux-gnu
checking build system type... x86_64-unknown-linux-gnu

Here's how I'd set up the environment for my Android NDK build:
export CROSS_COMPILE=arm-linux-androideabi
export CC=${CROSS_COMPILE}-gcc
export CXX=${CROSS_COMPILE}-g++

... other binutils as needed ...
export NDK=/home/afeder/android/android-ndk-r7-crystax-4
export SYSROOT=$NDK/platforms/android-8/arch-arm
PATH=$PATH:$NDK/toolchains/arm-linux-androideabi-4.4.3/prebuilt/linux-x86/bin

Make sure and add --sysroot=$SYSROOT to CFLAGS, CPPFLAGS, and/or CXXFLAGS.
Now you need to tell the spidermonkey configure that you are cross compiling:
./configure --build=x86_64-unknown-linux-gnu --host=arm-linux-androideabi --target=arm-linux-androideabi


text:
Q: Sorting in a dropdown I'm populating a few drop downs from some JSON, it works as expected at the moment but i'm trying to sort the values in the drop downs.  For all my drop downs it works fine, except for one of them which has numbers in, in which case it lists it 1, 10, 12, 2.
Any ideas how i can keep it sorting alphabetically for everything else but get the sort to work with the numeric values too?
Here's my JS (this replicates for each field - probably should try to find a way to make this reuseable):
var populateGenres = _.map(data.genres, function (val) {
    return '<option>' + val + '</option>';
}).join();
 var target = '#genreField';
$('#genreField').html(populateGenres);
reArrangeSelect(target);

Here's the sort JS:
function reArrangeSelect(target) {
    $(target).html($(target + " option").sort(function(a, b) {
        return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
    }))
}

My HTML is in this format:

    <select id="genreField" class="form-control"></select>

    <select id="authorField" class="form-control"></select>

A: You can sort data.genres before running it through the _.map functions:
data.genres.sort(function (a, b) {
    a = parseInt(a, 10);
    b = parseInt(b, 10);
    if(a > b) {
        return 1;
    } else if(a < b) {
        return -1;
    } else {
        return 0;
    }
});

Once you sort the data then run your _.map snippet:
var populateGenres = _.map(data.genres, function (val) {
    return '<option>' + val + '</option>';
}).join();

All of your options should now be sorted before you append them to the <select>.
DEMO

A: function reArrangeSelect(target) {
  $(target).html($(target + " option").sort(function(a, b) {
    // u can use that 'getValue' function
    // for "a.text == 'some string'" it will return 'some string' (string type),
    // for "a.text == '10'" it will return 10 (number type)
    var aVal = getValue(a.text);
    var bVal = getValue(b.text);
    return aVal == bVal ? 0 : aVal < bVal ? -1 : 1;
  }));
}

function getValue(val) {
 var asNumber = parseFloat(val);
 return isNaN(asNumber) ? val : asNumber;
}


text:
Q: Finiteness of wildly ramified cohomology $\newcommand\p[1]{\left(#1\right)}\newcommand\Char{\operatorname{char}}\newcommand\Gal{\operatorname{Gal}}\newcommand\b[1]{\left\{#1\right\}}$
Let $K$ be a global field. All cohomology below is fppf-cohomology.
Say $G$ is a finite type $K$-group scheme. Call a cohomology class $\alpha\in H^1(K,G)$ unramified at a (finite) place $v$ of $K$, if $\alpha\in\ker\p{H^1(K,G)\to H^1(K_v^{\mathrm{un}},G)}$ where $K_v^{\mathrm{un}}$ is the maximal unramified extension of $K_v$ (= completion of $K$ at $v$). Given a finite set of places $S$ (which contains all archimedean places) of $K$, let $H^1_S(K,G)\subset H^1(K,G)$ be the subset of cohomology classes which are unramified at all $v\not\in S$. If $K$ is a number field, then $H^1_S(K,G)$ is always finite, but this needs not be the case if $\Char K>0$.
I would imagine that finiteness of $H^1_S(K,G)$ can be recovered in the function field case if, in addition to requiring classes to be unramified almost everywhere, one also bounds the "amount of wild ramification showing up." I will offer one way of making this precise below. My question is if there exists a reference proving finiteness of something like $H^1_S(K,G)$ for global function fields which also takes into account higher ramification.
To make things more concrete, here is one sort of statement I could imagine one making. Assume $\Char K>0$, so I don't have to worry about dealing with archimedean places in the following definitions. Let $\Omega$ denote the set of places of $K$, and call a function $T:\Omega\to\mathbb N$ a place function if $T(v)=0$ for almost all $v$. Given a place $v$, and an integer $i\ge0$, let $I_v^i\subset\Gal_{K_v}$ denote the $i$th higher ramification group with the upper numbering (in particular, $I_v^0$ is inertia at $v$ and $I_v^0/I_v^1$ is the tame quotient), and let $K_v^i:=(K_v^{\mathrm{sep}})^{I_v^i}$ be the corresponding fixed subfield (e.g. $K_v^0=K_v^{\mathrm{un}}$ and $K_v^1$ is the maximal tamely ramified extension of $K_v$). With $G$ as before and $T:\Omega\to\mathbb N$ a place function, define
$$H^1_T(K,G):=\b{\alpha\in H^1(K,G):\alpha_v\in\ker\p{H^1(K_v,G)\to H^1(K_v^{T(v)},G)}\text{ for all }v\in\Omega}\subset H^1_S(K,G),$$
where $S:=T^{-1}(0)$.
Given the above setup, I would suspect that it is the case that $\#H^1_T(K,G)<\infty$.
Does anyone know a reference for a statement similar to the above in the literature (Of course, not necessarily made with the above definitions, but just something of the form, "cohomology with everywhere bounded ramification is finite")? I am particularly interested in references from which one can extract an explicit upper bound for the size of $H^1_T(K,G)$ (or whatever analogous object is defined in the reference), e.g. in terms of properties of $G$ and of $\#T^{-1}(n)$ for all $n\in\mathbb N$. I am also fine assuming that $G$ is finite (but not necessarily smooth).
Also, alternatively, is my intuition off and is there an example showing a statement of the above form cannot hold in general?


text:
Q: Is it possible to find out who created a tag or a branch in CVS? Commits obviously have an author associated with them; but is it possible to find out which user created a tag or a branch on a CVS repository?

A: If you have history enabled (which I think is the default) and your tag was created using cvs rtag then you can use:
cvs history -a -T

If you want tags that are created from within the branch via cvs tag then you are out of luck as the history command does not support that.
One thing to bear in mind is that in CVS tags are not repository-wide. They apply at the file level. So it is entirely possible for different people to apply the same tag to different files at different times.


text:
Q: Google Sheets to transform a table into a nested tree output or hierarchical structure output I just wonder if there is an easy way to transform the Google Sheets Original Input cells into a more readable table as in Output A or even Output B?

Original Input

Output A

Output B

Group
Points

Group
Points

Points

A
BBBB

A

A

A
CCCC

BBBB

- BBBB

A
DDDD

CCCC

- CCCC

A
EEEE

DDDD

- DDDD

B
FFFF

EEEE

- EEEE

B
GGGG

B

B

B
HHHH

FFFF

- FFFF

GGGG

- GGGG

HHHH

- HHHH

I know I can do it with App Script but I am curious if there are some smart solutions like a combo of query/filter/sort without the need for the App Script solution.

A: or:
=ARRAYFORMULA(TRIM(SPLIT(FLATTEN(SPLIT(QUERY(FLATTEN(QUERY(TRANSPOSE(
 QUERY(QUERY({A3:A&"×", "¤"&B3:B&"×", B3:B},
 "select Col1,max(Col2) where Col3 is not null group by Col1 pivot Col3"),
 "offset 1", 0)),, 9^9)),,9^9), "×")), "¤")))

A: try:
=ARRAYFORMULA(TRIM(FLATTEN(SPLIT(QUERY(FLATTEN(QUERY(TRANSPOSE(
 QUERY(QUERY({A3:A&"×", "- "&B3:B&"×", B3:B},
 "select Col1,max(Col2) where Col3 is not null group by Col1 pivot Col3"),
 "offset 1", 0)),, 9^9)),,9^9), "×"))))

A: Another approach (for your preferred arrangement, given that the non-header data runs in A3:B):
=ArrayFormula(SPLIT(QUERY({VLOOKUP(UNIQUE(FILTER(A3:A,A3:A<>""))&"*",{A3:A,ROW(A3:A)&"-"&COLUMN(A3:A)},{1,2},FALSE);FILTER({"|"&B3:B,ROW(B3:B)&"-"&COLUMN(B3:B)},A3:A<>"")},"Select Col1 ORDER BY Col2"),"|",1,0))
ADDENDUM (based on additional comment from poster):
This version of the formula will work on unsorted raw data:
=ArrayFormula(SPLIT(QUERY({VLOOKUP(SORT(UNIQUE(FILTER(A3:A,A3:A<>"")))&"*",{SORT(FILTER(A3:A,A3:A<>"")),SEQUENCE(COUNTA(A3:A),1)&"-"&COLUMN(A1)},{1,2},FALSE);SORT(FILTER("|"&B3:B,A3:A<>""),1,1,2,1),SEQUENCE(COUNTA(A3:A),1)&"-"&COLUMN(B1)},"Select Col1 ORDER BY Col2"),"|",1,0))


text:
Q: Dynamic form (switch entity) symfony2 I'm making a page for adverts. An advert can be of different types and therefore have different data. For instance, a vehicle would have the make and the model as extra data.
Right now, I've got one base doctrine entity Advert which contains the data that every advert requires. Different adverts in turn innherits this data (doctrine2 discriminatormap)
I need to populate the form dynamically (with ajax and symfony2 forms) if the user choose to create a vehicle ad I want to display the options for a vehicle advert. But I also need to change the entity to be of the form AdvertVehicle.
Is this possible? I did read the cookbook entry at the symfony2 homepage

"How to Dynamically Modify Forms Using Form Events":
  This should be handled by making an AJAX call back to your application. In that controller, you can submit your form, but instead of processing it, simply use the submitted form to render the updated fields. The response from the AJAX call can then be used to update the view.

I understand how to make an ajax call back to my controller, and i understand how to use the form-events but how do I get the response of a rendered select-box (containing vehicle models for instance) back? With a new AbstractType? or formbuilder?
And then when the user actually submits the form I need to use the entity of the selected advert type. Can I change the entity according to the users choice in the form dynamically?
Edit
I checked the form innheritance out that's great, thank you. I extend the AdvertType and override the buildForm() method and before I add the items I need for the AdvertVehicleType I call the parent method.
Futher Explanation
Every advert entity contains price, description, title and category. Some adverts contains more, such as make and model. They are differentiated by the discriminatormap (doctrine2)
Example:
// -- Entity
class CarAdvert extends Advert {

    protected $model;
    protected $make;

}

// -- Entity
// -- This uses discriminator mapping
class Advert {
    protected $title;
    protected $description;
    protected $price;
    protected $category;
}

if the user selects the category cars I want to use the CarAdvert entity (for validation and persistance) if the user selects the house hold itemcategory I just want to use the normal Advert entity.
One major problem is still that I cannot figure out how to render the extended form via ajax. Any tips on this part? When the user selects car as a category, I want the form to be updated (via jQuery/ajax) but how do I make a controller that retrieves just the extended part of the form and sends the html back as a response (without using twig and rendering it in a view, is this possible)?
Solution:
See answer below!

A: Solution:
The solution to my problem was to create a few extra functions in the controller to solve the issue where I want to be able to change the entity and form "on the fly" from a selection by the user..
public function indexAction(Request $request)
{
    $form = $this->getForm($request);
    $form->handleRequest($request);

    return array(
           'form' => $form->createView(),
           'request' => $request->request,
    );
}

Where getForm retrieves the form, (e.g AdvertVehicleType for vehicles or AdvertType for a "default" advert).
The getForm method looks like this:
 private function getForm(Request $request)
{
    $categoryTitle = 'NONE';
    $categoryId = $request->request->get('advert', false)['category'];

    if ($categoryId) {
        $categoryTitle = $this->getDoctrine()->getRepository('Bundle:Category')->find($categoryId)->getTitle();
    }

    return $this->createForm($this->getFormType($categoryTitle), $this->getEntity($categoryTitle));

}
here I retrieve the categoryID (that is selected in the form in the request) and retreives the formType with getFormTypeand the entity with getEntity.
private function getEntity($categoryTitle)
{
    $entity = new Advert();
    switch ($categoryTitle) {
        case Category::CARS:
            $entity = new AdvertCar();
    }

    return $entity;
}

private function getFormType($categoryTitle)
{
    switch ($categoryTitle) {
        case Category::CARS:
            return new AdvertCarType();
        default:
            return new AdvertType();
    }
}

To be able to update this "on the fly" with ajax (but it also works if the user tries to submit the form) I created another action in the controller.
This action renders the parts of the form that I want to update (on ajax call), I do this by actually picking out what I don't need in the form with twig setting the form objects to rendered like so:
{% do form.title.setRendered %}

(this is just an example I actually do this for all the form objects that I don't want to render.
I then simply just call:
{{ form_rest(form) }}

which will retrieve the "rest" of the form which is different for different categories.
Now let's say you have state and than town to select. First select the state then you render the towns for that state in twig (but then you can actually just render the part you need, e.g {{ form_row(form.towns) }} and you return this rendered template as a json-response and just put it in the div you want with jquery.
$html = $this->renderView('@Bundle/NewAddPage/filter_area.twig', array('form' => $form->createView()));

and then returning the $html variable in the response.
I hope this helps, and that the explanation is good enough, if not just make a comment and I'll update this with my answer!


text:
Q: How do I create a dynamic average? (Don't know how else to call it) I have a 10000x1 matrix. I need to find the percentage of information contained in each case. The method of doing so is to make another matrix that contains the sum of remaining cells.
Example:
% info is a 10000x1
% info_n contains percentages of information.

info_n = zeros([10000 1]);
info_n(1)= info(1)                 /sum(info);
info_n(2)=(info(1)+info(2))        /sum(info);
info_n(3)=(info(1)+info(2)+info(3))/sum(info);

I need to do this but all the way to info_n(10000).
So far, I tried this:
for i = 1:10000

info_n(i)=(info(i))/sum(info);

end

but I can't think of a way to add previous information. Thank you for the help!

A: You can use cumsum ("cumulative sum") for this task:
info_n = cumsum(info)/sum(info);

EDIT: @LuisMendo's comment sparked my curiosity. It seems that you actually gain something by using his method if the length N of the vector is below about 2^15 but the advantage after that drops. This is because cumsum probably needs O(N^2) but sum only needs O(N) time.
On the left you see the times as well as the ratio of the times of the two methods plotted against the logarithm of the size. On the right you see the actual absolute time differences, which varies a lot depending on what else is currently running:

Testing script:
N = 2.^(1:28);
y1 = zeros(size(N));
y2 = zeros(size(N));
vec = 1:numel(N);
for k=vec;
    disp(k)
    info = zeros(N(k),1);
    % flawr's suggestion
    tic
    info_n = cumsum(info);
    info_n = info_n / info_n(end);
    y1(k) = toc;
    % LuisMendo's suggestion
    tic
    info_m = cumsum(info)/sum(info);
    y2(k) = toc;
end
subplot(1,2,1)
semilogy(vec,y1,vec,y2,vec,y1./y2,vec,vec.^0);
legend('LuisMendo','flawr','LM/f','Location','SouthEast');
subplot(1,2,2)
plot(vec,y1-y2)


text:
Q: Near a white hole, what do lightcones look like? In the vicinity of a Schwarzchild black hole, spacetime looks like this (at least according to a quick google search). Here, the centre of the black hole is supposed to be at $x=0$ and the event horizon at $x=3$. And outside the event horizon, the future light cones look pretty normal, except they kind of bend upwards.

But what would a diagram like this look like if we swapped the black hole for a white hole? Which way would the light cones bend?

A: The maximal extension of Schwarzschild spacetime geometry is the Kruskal spacetime.  It has both the Schwarzschild black hole in the future (that is, essentially everything eventually falls in) and a white hole in the past.  The white hole has exactly the form of a time-inverted black hole.  So the light cones in the vicinity of the white hole look exactly the same as those in the vicinity of the black hole, except with the past and future reversed.  While the black hole features trapped surfaces for which all directions point down the neck of the black hole, toward the singularity, the white hole has "anti-trapped" surfaces, for which all future-directed timelines point away from the singularity.


text:
Q: Is there a Disable Click listener on Android? I want to display a toast
when a disabled button click
Like "this button is disabled"
I tried
button1.setOnDisableClickListener
(new View.OnClickListener() {
@Override
public void onClick(View _view) {
    SketchwareUtil.showMessage(getApplicationContext(), "fdd");
}
});

A: Just set regular on click listener on the button, and inside it check if the button is clickable/disabled or whatever. Kotlin code may look like:
btnSelect.setOnClickListener {
        if (it.isClickable)
            doAction()
        else
            Toast.makeText(context, "The button is disabled", Toast.LENGTH_LONG).show()
    }


text:
Q: 2D Array of JButtons not getting clientProperty right Introduction
I am trying to create a cheeckers game in which I initialize an 8x8 array, fill it with white and black buttons to create the game table
then I fill in the 1,2 || 5,6 row with white and black pawns with a loop, in which I name them, as BLACK and WHITE pawns, get their index and put a clientProperty about their color.
Problem
Now comes the tricky part, in the same loop in which I create the pawns, text of buttons gets filled ok (1,2 || 5,6 row)  but the color as clientProperty gets filled to completely different index.
You can only acess the 0,1  and 4,5 row others throw a NPE.
Code demonstrating the problem
This is the loop that fills in the pawns..
for (int pos = 0; pos < bSquares.length; pos++) {
    for (int line = 0; line < bSquares[pos].length; line++) {
        if(line == 1 || line ==2){
                bSquares[pos][line].putClientProperty("pawnColor", "black");
                bSquares[pos][line].setText("BLACK PAWN ");
                bSquares[pos][line].putClientProperty("pos", pos);
                bSquares[pos][line].putClientProperty("line", line);
                bSquares[pos][line].putClientProperty("type", "normal");
                bSquares[pos][line].addActionListener(new select());
        }
        else if(line == 5 || line == 6){
                        bSquares[pos][line].putClientProperty("pawnColor", "white");
                bSquares[pos][line].setText("WHITE PAWN");
                bSquares[pos][line].putClientProperty("pos", pos);
                bSquares[pos][line].putClientProperty("line", line);
                bSquares[pos][line].putClientProperty("type", "normal");
                bSquares[pos][line].addActionListener(new select());
                bSquares[pos][line].putClientProperty("locos", "normal");

        }
            }

Additional Resources
And this is the whole class for further reading if needed
http://pastebin.com/PswKMgT5

A: There may be other errors in your code, but as the comment alluded to, you are sometimes referencing bSquares like bSquares[pos][line] and at other times as bSquares[line][pos].  Either way will work, but you need to be consistent.
Change this line from:
final String nos = bSquares[line][pos + 1].getClientProperty("pawnColor").toString();

to
final String nos = bSquares[pos + 1][line].getClientProperty("pawnColor").toString();

and I think you'll get what you want (or at least fix one error).


text:
Q: Type annotation database for Clojure.Core functions? Does anyone know of a database that lists type annotations for all or some of the functions in Clojure.Core? Ideally, functions should be grouped by type annotation.
Please let me know how I can make this question more clear if my phrasing is ambiguous.


text:
Q: Command binding to a button inside a DataTemplate not working Example:
<ListBox Name="List"
             ItemsSource="{Binding Items}"
             SelectedIndex="{Binding SelectedIndex}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <DockPanel >
                    <Button DockPanel.Dock="Left" Content="Show" Command="{Binding ShowCommand}" CommandParameter="{Binding}"/>
                    <TextBlock Text="{Binding }"/>
                </DockPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

Clicking the button does nothing. I tried to bind the command to a button outside the DataTemplate and it works. I also tried to register the button in the DataTemplate to a Click_event and this did work.
Why is the command not working inside the DataTemplate?

A: Since the Command is defined in the ListBox's DataContext, Use either a RelativeSource Binding to help the Button locate the Command:
<ListBox.ItemTemplate>
    <DataTemplate>
        <DockPanel >
            <Button DockPanel.Dock="Left" Content="Show" Command="{Binding DataContext.ShowCommand,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBox}}}" CommandParameter="{Binding}"/>
            <TextBlock Text="{Binding }"/>
        </DockPanel>
    </DataTemplate>
</ListBox.ItemTemplate>

Or use an ElementName binding:
<ListBox.ItemTemplate>
    <DataTemplate>
        <DockPanel >
            <Button DockPanel.Dock="Left" Content="Show" Command="{Binding DataContext.ShowCommand,ElementName=List}" CommandParameter="{Binding}"/>
            <TextBlock Text="{Binding }"/>
        </DockPanel>
    </DataTemplate>
</ListBox.ItemTemplate>


text:
Q: Javascript promise chain hell I'm having a problem with promise chains that I don't know how to resolve. Summary of my code: I do a mongoose query for a specific user, fetch his CarIds and then query each car for his details and return these details via JSON response.
let carsDetails = [];

  User.findById(userId)
    .then(user => {
      const carIds = user.carsDetails;
      carIds.forEach((carId) => {
        Car.findById(carId)
          .then(car => {
            console.log(car);
            carsDetails.push(car);
          })
          .catch(err => { throw err; });
        });

      return res.status(200).json({ data: carsDetails });
    })
    .catch(error => {
      throw error;
    });

The problem is that no cars get actually pushed onto carsDetails array on the carsDetails.push(car); line, because it jumps to return statement before it manages to fill up the array. Is there a workaround that could do those queries and return a result in a form of an array, object...? I tried writing everything in async await form too with self-made async forEach statement, but it doesn't help me. Any suggestions? I already tried with Promise.all(), but didn't manage to fix the issue. Thanks!

A: You'll need to collect the promises of your Car.findById(carId) calls and use Promise.all() to wait for all of them before responding. You can use array.map() to map each ID to a promise from Car.findById().
User.findById(userId)
  .then(user => {
    const carIds = user.carsDetails;
    const carPromises = carIds.map(carId => Car.findById(carId))
    return Promise.all(carPromises)
  })
  .then(cars => {
    res.status(200).json({ data: cars })
  })
  .catch(error => {
    throw error
  })

A: await/async is the way to go, with await/async you use regular for ... of loops instead of forEach.
  async function getCarDetails() {
    let carsDetails = [];

    let user = await User.findById(userId);

    const carIds = user.carsDetails;

    for (let carID of carIds) {
      let car = await Car.findById(carId)

      console.log(car);

      carsDetails.push(car);
    }

    return res.status(200).json({
      data: carsDetails
    });

  }

Or you use Promise.all and map instead of for ... of
  async function getCarDetails() {
    let user = await User.findById(userId);
    const carIds = user.carsDetails;

    let carsDetails = await Promise.all(carIds.map(carID => Car.findById(carID)));

    return res.status(200).json({
      data: carsDetails
    });
  }

Those two solutions are slightly different. The second version with the map will send all requests to the DB at once, and then waits until they are all resolved. The first one will send the request one after another. Which one is better depends on the use-case, the second one could lead to request peeks, and might be easier be abused for DDoS.

A: If you can have a lot of cars to find, you may want to do your query in a single request, no need to stack multiple promises :
User.findById(userId)
  .then(user => {
    const carIds = user.carsDetails;
    // if carsDetails is not an array of objectIds do this instead :
    // const carIds = user.carsDetails.map(id => mongoose.Types.ObjectId(id));
    return Car.find({ _id: { $in: carIds });
  })
  .then(userCars => {
    res.status(200).json({ data: userCars })
  })

A: Try to use async/await to solve this problem. It will be more readable and clean
async function getCarDetail() {
  let carsDetails = []

  try {
    const user = await User.findById(userId)
    const carIds = user.carsDetails

    for (let i = 0; i < carIds.length; i++) {
      const carId = carIds[i]

      const car = await Car.findById(carId)
      carsDetails.push(car)
    }

    return res.status(200).json({ data: carsDetails })

  } catch(error) {
    console.log(error)
  }
}


text:
Q: Android soft keyboard not panning web view The original problem I am fighting is more complex but for investigating purposes I have simplified the test case to the following:

*

*Single fullscreen activity

*Programmatically created web view that occupies roughly half of the horizontal screen space, 90% of the vertical space and is added to the root view via within the onCreate call:

ViewGroup parent = (ViewGroup) getWindow().getDecorView().getRootView();
parent.addView(myWebView);

*

*web view opens to google.com via:

loadUrl("http://google.com")

*

*AndroidManifest.xml has the property:

"android:windowSoftInputMode="adjustPan"
When clicking on the search box on the google page the keyboard pops up but the web view itself is not shifted up as adjustPan indicates should happen.  The main activity also has a native text field that when clicked will shift the entire layout (including web view) up as expected.
The behavior is present on 4.2.2 on both a Nexus 7 and Galaxy Nexus.
So the question is how can I have the windowSoftInputMode property adjustPan be applied correctly to a web view instance so that when the soft keyboard is displayed the entire web view is shifted up by the vertical space taken up by the keyboard.
Before I go down the road of trying to manipulate the layout manually within onMeasure I want to see if there is a consistent / better way to handle this.  The browser obviously handles this situation correctly so not sure why the web view is not able to handle this.
One thing to note is that making the web view fullscreen or a separate activity are not possible options due to an existing architecture that I am not able to change.

A: If we use the full screen without action bar adjustResize will not work. See this thread for details
*adjustPan not preventing keyboard from covering EditText


text:
Q: What is wrong with this richfaces menu rendering? I am trying to fix this jsf richfaces menu. Some components does not respect the height that I am giving:

Here it is my jsf code:
    <div style="background:url(#{facesContext.externalContext.request.contextPath}/images/sigelp_menubar_bg.jpg) repeat-x #4a71a5; text-align:left; height:30px; width:100%; border:0;">
        <h:form style="height:30px">
            <rich:toolbar style="width:auto; background: none; height:30px; vertical-align:middle; padding:0;" itemStyle="border-right: 1px solid red; padding:0; margin:0; height: 30px;">
                <rich:toolbarGroup style="padding:0; margin:0;">
                    <rich:dropDownMenu style="padding:0; background:none; height:30px" >
                        <f:facet name="label" style="padding:0; margin:0;">
                            <h:outputText value="Administrar" />
                        </f:facet>
                        <rich:menuGroup label="Estadios" rendered="#{seguridadBean.validarPermisoAdministrarEstadios}" iconDisabled="true">
                            <rich:menuItem label="Listar" action="#{menuBean.listarEstadios}" rendered="#{seguridadBean.validarPermisoListarEstadios}"/>
                            <rich:menuItem label="Agregar" action="#{menuBean.agregarEstadio}" rendered="#{seguridadBean.validarPermisoAgregarEstadios}"/>
                        </rich:menuGroup>
                        <rich:menuGroup label="Deportes" rendered="#{seguridadBean.validarPermisoAdministrarDeportes}">
                            <rich:menuItem label="Listar" action="#{menuBean.listarDeportes}" rendered="#{seguridadBean.validarPermisoListarDeportes}"/>
                            <rich:menuItem label="Agregar" action="#{menuBean.agregarDeporte}" rendered="#{seguridadBean.validarPermisoAgregarDeportes}"/>
                        </rich:menuGroup>
                        <rich:menuGroup label="Equipos" rendered="#{seguridadBean.validarPermisoAdministrarEquipos}">
                            <rich:menuItem label="Listar" action="#{menuBean.listarEquipos}" rendered="#{seguridadBean.validarPermisoListarEquipos}"/>
                            <rich:menuItem label="Agregar" action="#{menuBean.agregarEquipo}" rendered="#{seguridadBean.validarPermisoAgregarEquipos}"/>
                        </rich:menuGroup>
                        <rich:menuGroup label="Torneos" rendered="#{seguridadBean.validarPermisoAdministrarTorneos}">
                            <rich:menuItem label="Listar" action="#{menuBean.listarTorneos}" rendered="#{seguridadBean.validarPermisoListarTorneos}"/>
                            <rich:menuItem label="Agregar" action="#{menuBean.agregarTorneo}" rendered="#{seguridadBean.validarPermisoAgregarTorneos}"/>
                        </rich:menuGroup>
                        <rich:menuGroup label="Empleados" rendered="#{seguridadBean.validarPermisoAdministrarEmpleados}">
                            <rich:menuItem label="Listar" action="#{menuBean.listarEmpleados}" rendered="#{seguridadBean.validarPermisoListarEmpleados}"/>
                            <rich:menuItem label="Agregar" action="#{menuBean.agregarEmpleado}" rendered="#{seguridadBean.validarPermisoAgregarEmpleados}"/>
                        </rich:menuGroup>
                        <rich:menuItem label="Categorias" action="#{menuBean.administrarCategorias}" rendered="#{seguridadBean.validarPermisoAdministrarCategorias}"/>
                        <rich:menuGroup label="Seguridad" rendered="#{seguridadBean.validarPermisoAdministrarSeguridad}">
                            <rich:menuItem label="Usuarios" action="#{menuBean.listarUsuarios}" rendered="#{seguridadBean.validarPermisoListarUsuarios}"/>
                            <rich:menuGroup label="Perfiles" rendered="#{seguridadBean.validarPermisoAdministrarPerfiles}">
                                <rich:menuItem label="Listar" action="#{menuBean.listarPerfiles}" rendered="#{seguridadBean.validarPermisoListarPerfiles}"/>
                                <rich:menuItem label="Agregar" action="#{menuBean.agregarPerfil}" rendered="#{seguridadBean.validarPermisoAgregarPerfiles}"/>
                            </rich:menuGroup>
                        </rich:menuGroup>
                    </rich:dropDownMenu>
                    <rich:menuItem label="Administrar socios" action="#{menuBean.administrarSocios}" rendered="#{seguridadBean.validarPermisoAdministrarSocios}"/>
                    <rich:dropDownMenu>
                        <f:facet name="label">
                            <h:outputText value="Cuotas sociales" />
                        </f:facet>
                        <rich:menuItem label="Generar cuotas sociales" action="#{menuBean.generarCuotasSociales}"/>
                        <rich:menuItem label="Listar cuotas sociales sin rendir" action="#{menuBean.listarCuotasSocialesSinRendir}"/>
                    </rich:dropDownMenu>
                    <rich:menuItem label="Vender entradas" action="#{menuBean.venderEntradas}"/>
                </rich:toolbarGroup>
                <rich:toolbarGroup location="right">
                    <rich:menuItem label="Salir" action="#{loginBean.logout}" />
                    <ui:insert name="backButton">
                        <a4j:region>
                        <h:commandLink action="#{seguridadBean.volver}" rendered="#{seguridadBean.showBackButton}" immediate="true">
                            <h:graphicImage value="/images/arrows/arrow-left.png" alt="Volver" style="border: 0px;" width="32"/>
                        </h:commandLink>
                        </a4j:region>
                    </ui:insert>
                </rich:toolbarGroup>
            </rich:toolbar>
        </h:form>
    </div>

And some intentions to fix trough CSS:

 .rf-ddm-itm-unsel{   border:0;   }    .rf-ddm-lbl-dec{   height:100%; }

.rf-ddm-itm:hover {   margin:0;   padding:0;  background: #7BA0D2; }
.rf-tb-itm{   height: 30px; }
.rf-tb {  padding: 0;     margin:0; }
.rf-tb-itm, .rf-ddm-lbl, .rf-ddm-unsel{   line-height: 30px;  padding:
  0;    margin: 0; }

Any hint or help would be appreciated, thank you very much
The red border is defined inside <rich:toolbar itemStyle="border-right: 1px solid red; padding:0; margin:0; height: 30px;">


text:
Q: Dropdown menu and nav issues I've just tried to design a dropdown menu for my navigation. Unfortunately they whole nav and the dropdown is flickering now, when I hover the dropdown button in my nav. The dropdown menu also disappears, when I try to click it.
I can't give you pieces of my code, because Stackoverflow transforms it directly into HTML (don't know why), so I just can give you a link to my test page: http://keinkopf.de/designs/1/
EDIT:
HTML

Start

Themen

1

2

3

3s

CSS
        ul li ul{
            display: none;

            background-color: #000000;
            width: 400px;
            margin-top: 40px;
            float: left;
        }

    ul li ul li{
            margin-left: 10px;
        }

        ul li:hover ul{
            display: block; /* display the dropdown */
        }

    ul {
        padding: 0;
        list-style: none;
    }

    ul li ul hr{
            border-color: #FFFFFF;
            border-width: thin;
            border-style: solid;
        }

li {
    display: inline;
    margin-right: -1px;

}

#block1 {
    background-color: #000000;
    padding-top: 3px;
    padding-bottom: 3px;
    padding-right: 30px;
    padding-left: 30px;

}

#block1:hover {
    background-color: #FFFFFF;
     padding-top: 2px;
    padding-bottom: 2px;
    padding-right: 29px;
    padding-left: 29px;
    color: #000000;
    border-color: #000000;
    border-style: solid;
    border-width: 1px;
}

#block2 {
    background-color: #FFFFFF;
     padding-top: 2px;
    padding-bottom: 2px;
    padding-right: 29px;
    padding-left: 29px;
    color: #000000;
    border-color: #000000;
    border-style: solid;
    border-width: 1px;

}

#block2:hover {
   background-color: #000000;
    color: #FFFFFF;
}

#block3 {
    background-color: #FFFFFF;
    padding-top: 2px;
    padding-bottom: 2px;
    padding-right: 29px;
    padding-left: 29px;
    color: #000000;
    border-color: #000000;
    border-style: solid;
    border-width: 1px;
}

#block3:hover {
    background-color: #000000;
    color: #FFFFFF;
}

nav a {
    text-decoration: none;
    color: #FFFFFF;
    font-family: 'Lato', Arial;
    font-size: 15pt;
}

nav {
    margin-top: 39px;

}

hr {

    border-color: #000000;
    border-width: 2px;
}

A: If i can recommend use position absolute so it doesnt affect other objects, and instead of margin use padding.
ul li ul{
    position: absolute;
    padding-top: 40px;
}

In case you want to have some free space between bar and drop down, then just add some div around that.

A: You have to position the 'ul' (dropdown-menu) within the 'li' (menu) absolute to the parent.
Every time you hover over your menu-item the menu gets displayed and the position of the menu-item changes. That's why it is flickering.
On top of that you should remove margin-top from your 'ul li ul' and make the listitems li inline-block instead of inline, so that the dropdown gets displayed undrneath the listitem.
i've created the codesnipped here

A: I believe it has somthing to do with the placement of your tabs. What i am saying is: when your mouse hovers over the tab it shows the rest of the subtabs and therefore pushes the tab off the mouse therefore closing down the menu or in your case causing blinking.


text:
Q: General Parcelable Object (is it possible)? Hello i am trying to create a class called ParcelableObject in which i implement the Parcelable interface.
Then i will create other objects, which they will extend ParcelableObject.
I am doing it because i don't want to write the methods of Parcelable interface in each object.
As for now i have managed to do this for Objects containing other Objects (which all of them extend the ParcelableObject class) and for primitive Types.
I am having troubles doing it for Arrays and List of primitive Types and of course Arrays and Lists of Objects
I intend to expand this to cover Lists, Arrays.
The way i did it is by getting all the fields of the object given
So here is my question.
First of all
Is this possible?
Second i tried to expand it for arrays or lists of primitive types and i fail to do it.
To be more specific. Now i am trying to expand it to Arrays of Integers, or Lists of Integers.
As i see i fail to read from the parcel a List of Integers because i get cast errors etc.
So any help would be grateful.
Also the basic idea around this is to store to the ParcelableObject the object of its subclass.
Then if i get an object (not primitive type) i write its class name to parcel and then the object.
So when i want to read an object from the parcel, i read first the string with its class name, make a new instance of the class using (Class.forName() etc) and then assign the object read from parcel to the Object instantiated above. If there is any better way to get the Class Name of the ParcelableObject's subclass other than filling the parcel unnecessary Strings id like to know.
Here is the ParcelableObject.java
You can download the whole android ParcelableObject project to test it. Demonstration is included.
Tested it under virtual device Nexus S (4.2). Project is targeted to work for 4.0 and above.
https://github.com/tchar/ParcelableObject/blob/master/ParcelableObject/src/com/parcelableobject/ParcelableObject.java
UPDATE*** Added Support for primitive Object Lists.
Still having problems with primitive types (int, etc) not with Integers and list of ParcelableObjects
Thanks in advance.


text:
Q: jQM ui-hidden-accessible doesn't hide parent div

   <input type="text" id="myinput" class="ui-hidden-accessible">
   Bar

I'm trying to completely hide the input field, but jquery mobile adds an ugly div around it which is 100% width of page and 2px high (grey). Is it possible to hide it with css?

A: With jQuery:
Because jQM always wraps the input with just one dive, you can do this:
$("#myinput").parent().hide();

With data-role:
If you add data-role="none" to the input, jQM will not apply the styles.
<input type="text" id="myinput" class="ui-hidden-accessible" data-role="none">

A: Use data-wrapper-class attribute to apply any custom classes any input type.
<input type="text" data-wrapper-class="ui-hidden-accessible custom-style">

The classes will be added to parent div of the input.


text:
Q: How to authenticate sharepoint users against external site We have recently deployed a bespoke asp.net mvc solution using the built in membership system to a client.
They now wish to build a SharePoint system to sit alongside this but would like all user management to take place in the mvc app.
Is this possible and if so, what would be the simplest way to achieve this?

A: yes, you can technically use SP with the SqlMembershipProvider (assuming that's what you used before with the "built in system").
SP has no user management capabilities for the SqlMembershipProvider, so I assume it'll be handled by your other app.
But SP sits atop the .Net membership providers, so you can configure it for SQL just like you would the ASP.Net webapp.


text:
Q: record structures,arrays and finding max using a function I have a visual basic problem. I have a record structure which has 4 variables and one of them is an array.I have trouble finding the max. The function returns the same value for all champions. The days on which the champions get their best scores varies and so should the value returned by the function but it doesn't
Private Structure DebateChamps
  ' user will input the name of each debate champion
  ' the user will also input the scores of each champion
  ' the bestday---day on which a champion attained highest score,
  ' and average for each champion are for me to work out
    Public Name As String
    Public Score() As Double
    Public Average As Double
    Public BestDay As Integer

I have worked out the first three but now I am having trouble with finding the best day. I want to do this using a function. I know that finding the best day essentially means finding the max. This is what I have for finding the best day. The problem with it is that when I output it onto the grid, I get the same values every time. For example lets say Champion 1 has scores

9(day 1),8(day 2),6(day 3)

and Champion 2 has scores

7(day 1),5(day 2),9(day 3)

I will get day 3 as the best day for both. Please help.
I pass array into the function
I want it to return an array because,there are numerous days and each day may vary for each champion
Private Function ComputeBestDay(ByVal ChampAry() As DebateChamps) As Integer()

    Dim Max(nChamps, nDays) As Double
    Dim MaxIndex(nChamps) As Integer

    Dim r, c As Integer

    'I initialise the max values to zero
    'and the index as well
    For r = 1 To nChamps
        For c = 1 To nDays
            Max(r, c) = 0
            MaxIndex(r) = 0
        Next c
    Next r

    'I try to find the max
    'I store the day in MaxIndex
    For r = 1 To nChamps
        For c = 1 To nDays
            If Max(r, c) < ChampAry(r).Score(c) Then
                Max(r, c) = ChampAry(r).Score(c)
                MaxIndex(r) = c
            End If
        Next c
    Next r

    Return MaxIndex

End Function

I call the function below
Private Sub btnBestDay_Click(sender As Object, e As EventArgs) Handles btnBestDay.Click

    Dim i As Integer
    Dim ans(nChamps) As Integer

    'I call the function
    For i = 1 To nChamps
        ans = ComputeBestDay(AllChampsAry)
        AllChampsAry(i).BestDay = ans(i)
        placetext(i, nDays + 2, CStr(AllChampsAry(i).BestDay))
    Next i

End Sub

A: Try doing it using LINQ:
Private Function ComputeBestDay(ByVal ChampAry() As DebateChamps) As Integer()

    Return ChampAry _
        .Select(Function (r) _
            Enumerable _
                .Range(0, r.Score.Length) _
                .First(Function (c) r.Score(c) = r.Score.Max())) _
        .ToArray()

End Function

A: I figured it out. I was instructed to use a function that calculates the position of the max. I was confused because of the record structure. In my record structure I have the following
    Private Structure DebateChamps

    Public Name As String
    Public Score() As Double
    Public Average As Double
    Public BestDay As Integer

End Structure

Lets say a school principal wants to pick the best debate team----hence the structure name DebateChamps. To do this he will pick the names that have an average of greater than five. The records for each champion go into the array
   Private AllChampsAry() As DebateChamps

Handling the input and average was straight forward. The principal also wants to find on which day the players performed best. So I had to display the maxindex for each player.
    Dim max As Double
    Dim index(nChamps) As Integer
    Dim r, c As Integer

    For r = 1 To nChamps
        max = 0
        For c = 1 To nDays
            If max < ChampAry(r).Score(c) Then
                max = ChampAry(r).Score(c)
                index(r) = c
            End If
        Next c
    Next

First loop through each champ(candidate for debate championship) then through the days for each champ(assume each champ participated for the same number of days)...I stored the indices for each champ in an array and the returned it.
I was confused due to the record structures.I had never used them before


text:
Q: Constructive proof of approximate Brouwer's Fixed Point Theorem for $\Delta^n$ via Sperner's lemma Brouwer's Fixed Point Theorem (BFPT) is not provable in Bishop-style constructive mathematics (BISH). For quick orientation, BISH is obtained from classical mathematics by removing the Law of Excluded Middle (LEM) and replacing the full Axiom of Choice by the Axiom of Dependent Choice.
Standard classical proofs of BFPT either rely on LEM or the Bolzano-Weierstrass Theorem, which is equivalent to the Limited Principle of Omniscience, a constructively inadmissible weakening of LEM. BFPT itself is equivalent to Weak König's Lemma in BISH, and thus to the Lesser Limited Principle of Omniscience, another constructively inadmissible weakening of LEM.
However, the following approximate version of BFPT is known to be provable in BISH.
Recall that $$\Delta^n=\bigg\{\textbf{x}=(x_0,...,x_n)\mid\sum_{i=0}^{n}x_i\leq1 \land \forall i: 0\leq x_i \leq 1 \bigg\}$$ and let $d$ be the Euclidian metric on $\Delta^n$.
Approximate Brouwer Fixed Point Theorem

Let $f$ be a uniformly continuous function from $\Delta^n$ into
itself. Then for each $\varepsilon>0$ there exists $\textbf{x}\in\Delta^n$ such
that $d(f(\textbf{x}),\textbf{x})<\varepsilon$.

The assumption of uniform continuity is essential since the classical Uniform Continuity Theorem is not provable in BISH. Here's my proof attempt:
The proof in BISH proceeds via Sperner's Lemma.
Consider a uniformly continuous function $f$ from $\Delta^n$ into itself. Fix $m,k\in\mathbb{N}$ such that $2^{-k}+2^{-k-2}+2^{-k-3}<2^{-m}$ and $$d(\textbf{x},\textbf{y})<2^{-k}+2^{-k-2}\Longrightarrow d(f(\textbf{x}),f(\textbf{y}))<2^{-m}.$$
Consider a simplical subdivision $\mathcal{S}$ of $\Delta^n$ with grid size $2^{-k}$. Specify a labeling as follows. A vertex $x$ of a simplex in $\mathcal{S}$ gets assigned the label $i$ if, and only if, $f(\textbf{x})_i<x_i$ or $f(\textbf{x})_i<x_i+2^{-k-3}$. This is constructively well-defined by the Approximate Splitting Principle and constitutes a feasible labeling in the sense of Sperner's Lemma. Thus, $\mathcal{S}$ contains a subsimplex $S$ whose $n+1$ vertices are labeled with $0,1,...,n$. We must now show that for a vertex $\textbf{s}$ of $S$, $d(f(\textbf{s}),\textbf{s})<n(2^{-m+1})$ holds (cf. Scarf, 1967; van Dalen, 2011).
This is where I got stuck.
Denote the vertex of $S$ labeled by $j$ by $\textbf{s}^j$ and consider $\textbf{s}^1$. By the definition of the labeling, $f(\textbf{s}^1)_1<s^1_1+2^{-k-3}$ and for each $i\neq 1$, we have $f(\textbf{s}^i)_i<s^i_i+2^{-k-3}$. I just can't figure out how to infer from this and the uniform continuity of $f$ that $d(f(\textbf{s}^1),\textbf{s}^1)<n(2^{-m+1})$ must hold.
I'm sure the argument is fairly easy, but I just can't see it. A "visual" argument for $\Delta^2$ is in the paper by van Dalen referenced above. While it helps me see that the conclusion is true for $\Delta^1$ and $\Delta^2$, I am still unable to derive it formally, let alone generalize it to $\Delta^n$.
Any help would be greatly appreciated.
Thank you in advance!

Update
In the meantime, I worked out the details of the proof myself. I'll post the full argument as an answer here soon.


text:
Q: How can I extract data from a html tag using Python? I want to extract the translation of a word in online dictionary.
For example, the html code for 'car':

any vehicle on wheels

How can I extract "any vehicle on wheels" in Python with beautifulsoup or any other modules?

A: There are multiple ways to reach the desired element.
Probably the simplest would be to find it by class:
soup.find('span', class_='def').text

or, with a CSS selector:
soup.select('span.def')[0].text

or, additionally checking the parents:
soup.select('ol.level_1 > li.level_1 > span.def')[0].text

or:
soup.select('ol.level_1 > li[value=1] > span.def')[0].text

A: I solve it by beautifulsoup:
soup = bs4.BeautifulSoup(html)
q1=soup.find('li', class_="sense_list_item level_1",value='1').text

A: Assuming that is the only HTML code given, you can use NLTK.
import nltk

#load html chunk into variable htmlstring#
extract = nltk.clean_html(htmlstring)
print(extract)


text:
Q: Método que retornar 03 contagens de cédulas diferentes para um saque Preciso desenvolver uma interface que realiza um saque de um caixa eletrônico.
No entanto eu preciso retornar com 3 opções de contagem de cédulas.
Por exemplo.:
Considerando cédulas de $100, $50, $20, $10, $5.
Um saque de $170,00.
Opção 01
1 cédulas = $100,00
1 cédulas = $50,00
1 cédulas = $20,00
Opção 02
3 cédulas = $50,00
1 cédulas = $20,00
Opção 03
3 cédulas = $50,00
2 cédulas = $10,00
Eu consegui achar algo parecido como na pergunta do link Programa de Saque, porem neste caso passa apenas a opção com menor numero de cédulas.
Como ficaria a estrutura de código para retornar 03 opções distintas de contagem de cédulas.

A: Eu utilizei quase a mesma lógica que você mencionou aqui em
Programa de Saque
Porém, a cada opção colocada na tela, fui retirando uma cédula disponível para fazer outras combinações com o total de 3 combinações,
// Cédulas existentes
static int[] Cedulas = { 100, 50, 20, 10, 5, 1  };
public static void Main()
{
        var saque = decimal.Parse(Console.ReadLine());
        // nCedulas recebe as cedulas e é retirado uma cedula a cada opção
        int[] nCedulas = Cedulas;
        if (saque <= 0) Console.WriteLine("Valor indisponível");
        else
        {
            // esse for é o responsavel por fazer 3 opções de saque
            for (int i = 0; i <= 2; i++)
            {
                // s recebe saque e é retirada a cada valor disponivel na cedula
                var s = saque;
                Console.WriteLine("///- OPPÇÃO" + (i + 1));

                int[] Notas = new int[nCedulas.Length];

                for (int j = 0; j < (nCedulas.Length); j++)
                {
                    Notas[j] = Convert.ToInt32(Math.Floor(s / nCedulas[j]));
                    s -= (Notas[j] * nCedulas[j]);
                }

                for (int j = 0; j < (Notas.Length); j++)
                {
                    if(Notas[j] != 0)
                    Console.WriteLine("Cedula de" + nCedulas[j] + " : " + Notas[j]);
                }
                // em nCedulas[i] pode colocar 0 para sempre remover os primeiros, com isso, na opção 2 irá remover 100 depois 50 ...20
                nCedulas = nCedulas.Where(v => v != nCedulas[i]).ToArray();
            }

        }
}

Saida do console;
170
///- OPPÇÃO1
Cedula de 100 : 1
Cedula de 50 : 1
Cedula de 20 : 1
///- OPPÇÃO2
Cedula de 50 : 3
Cedula de 20 : 1
///- OPPÇÃO3
Cedula de 50 : 3
Cedula de 10 : 2


text:
Q: Default java cacerts don't work I've an SSL secured rest ws.
In my java client I've added the certificat to the cacerts store, but it work only if i set explicitly the cacerts file path in the javax.net.ssl.trustStore  parameter and the password in javax.net.ssl.trustStorePassword.
the java home is set to :
java.home : C:\ide\jdk1.7.0_45\jre
and the two parameters are set to :
  Properties pp = System.getProperties();

  Set<Object> s = pp.keySet();

  for (Object object : s) {
      System.out.println(object + " : " + pp.get(object));
  }

  System.setProperty("javax.net.ssl.trustStore", "C:\\ide\\jdk1.7.0_45\\jre\\bin\\cacerts");
  System.setProperty("javax.net.ssl.trustStorePassword", "secret");

result:
  java.runtime.name : Java(TM) SE Runtime Environment
  sun.boot.library.path : C:\ide\jdk1.7.0_45\jre\bin
  .....
  java.home : C:\ide\jdk1.7.0_45\jre
  .... other java parameters value
  WS called with success

execution with Exception:
  Properties pp = System.getProperties();

  Set<Object> s = pp.keySet();

  for (Object object : s) {
      System.out.println(object + " : " + pp.get(object));
  }

  //System.setProperty("javax.net.ssl.trustStore", "C:\\ide\\jdk1.7.0_45\\jre\\bin\\cacerts");
  //System.setProperty("javax.net.ssl.trustStorePassword", "secret");

result :
java.runtime.name : Java(TM) SE Runtime Environment
sun.boot.library.path : C:\ide\jdk1.7.0_45\jre\bin
.....
java.home : C:\ide\jdk1.7.0_45\jre
.... other java parameters value
Exception in thread "main"
Caused by: javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated
at sun.security.ssl.SSLSessionImpl.getPeerCertificates(SSLSessionImpl.java:397)
at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:128)
at org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:397)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:148)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:149)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:121)
at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:573)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:425)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:820)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:754)
at org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor.execute(ApacheHttpClient4Executor.java:182)
at org.jboss.resteasy.core.interception.ClientExecutionContextImpl.proceed(ClientExecutionContextImpl.java:39)
at org.jboss.resteasy.plugins.interceptors.encoding.AcceptEncodingGZIPInterceptor.execute(AcceptEncodingGZIPInterceptor.java:40)
at org.jboss.resteasy.core.interception.ClientExecutionContextImpl.proceed(ClientExecutionContextImpl.java:45)
at org.jboss.resteasy.client.ClientRequest.execute(ClientRequest.java:443)
at org.jboss.resteasy.client.ClientRequest.httpMethod(ClientRequest.java:677)
at org.jboss.resteasy.client.ClientRequest.post(ClientRequest.java:566)
... 2 more

A: I think that the problem is that i used the wrong cacerts file path.
the default cacerts file in java is :
\jre\lib\security\cacerts


text:
Q: Two or more PathParts chained ( Catalyst ) How can I have more than one pathpart in an action at the same time? I tried with Regex and LocalRegex but it realy doesnt work.
This is the result I want:
/typeone/*/*/something
/typetwo/*/*/something

I want to achieve this by using only one base action that captures the two args in from, and can have either the "typeone" or "typetwo" pathpart.
The "something" is just another action that is chained to that base. I don't want to have two bases with two different pathparts, that would require me to have two something chained to each of the bases, right?
Thank you

A: The common wisdom in the Catalyst community seems to be that chaining is always a better idea than regex matching, these days -- to the extent that some of the regex stuff might get moved out of core in version 6.
Do the examples here help? http://wiki.catalystframework.org/wiki/gettingstarted/howtos/chainedexamples.view
The account/org/*/edit one seems to involve matching 3 separate PathParts...
Each of the relevant subs -- the ones triggered by typeone and typetwo, in your case -- will be run. Or is that not what you're after?

A: As far as I know, there is no way to set more then one PathPart, or to have a regexp-enabled PathPart.


text:
Q: Post a form before all tests chai mocha If I need to submit a login form before all tests, how can I do this with chai and mocha;
I've looked at the beforeEach functions but cant seem to make it work
var chai = require('chai');
var chaiHttp = require('chai-http');
var app = require('../app');
var should = chai.should();
var expect = chai.expect;
chai.use(chaiHttp);

var username = 't@t.com';
var password = 'test';

before(function() {

it('should login with details to login form / POST', function(done) {
    var request = chai.request(app);
    request
        .post('/session/new')
        .field('email', username)
        .field('password', password)
        .end(function(err, res) {
            res.should.have.status(200);
            res.should.be.html;
            done();
        });
});
describe('Vouchers', function() {
    it('should list ALL vouchers on / GET', function(done) {
        var request = chai.request(app);
        request
            .get('/vouchers')
            .end(function(err, res) {
                res.should.have.status(200);
                res.text.should.match(/Welcome to the Voucher Homepage/);
                res.should.be.html;
                done();
            });
    });
});
});

A: You cannot put it inside a before hook. I've tried it to see what would happen and got various results. The behavior you get by doing that is just undefined.
Looking at your code, it looks like you want the code in the first it to initialize state and then have the stuff in describe run afterwards. To do so, just unwrap the code you've put in your first it and make it the body of your before hook. And since chai-http produces promises, you should be able to just return the request you produce. So this should work:
before(function() {
    var request = chai.request(app);
    return request
        .post('/session/new')
        .field('email', username)
        .field('password', password)
        .end(function(err, res) {
            res.should.have.status(200);
            res.should.be.html;
        });
});

A: As Luois already said, you cannot put it inside a before hook. An the Before, should go inside the describre.
describe('Vouchers', function () {
    before(function () {
        var request = chai.request(app);
        return request
            .post('/session/new')
            .field('email', username)
            .field('password', password)
            .end(function (err, res) {
                res.should.have.status(200);
                res.should.be.html;
            });
    });

    it('should list ALL vouchers on / GET', function (done) {
        var request = chai.request(app);
        request
            .get('/vouchers')
            .end(function (err, res) {
                res.should.have.status(200);
                res.text.should.match(/Welcome to the Voucher Homepage/);
                res.should.be.html;
                done();
            });
    });
});


text:
Q: Equivalent of Python's min() with lambda in Ruby In Ruby, what would be the equivalent of the Python code below?
x = [6, 7, 8, 9, 10, 2, 3, 4]
y = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

min(range(len(x)), key=lambda i: y.index(x[i]))
=> 5

Edit: I'm just looking for a direct translation from Python to Ruby, don't bother about the  semantic of the provided example.

A: Do you want to get the index of the smallest element?
x = [6, 7, 8, 9, 10, 2, 3, 4]

x.index(x.min()) # => 5
x.each_with_index.min[1] # => 5
(0...x.size).min_by {|i| x[i] } # => 5

A: Translating directly...
(0...x.length).min_by { |i| y.find_index(x[i]) }

Built-in functions that take lambdas in python tend to translate to Ruby methods that take blocks (lambdas defined in-line, essentially).
Edit: A slightly more idiomatic translation could be
obj,index = x.each_with_index.min_by { |o,i| y.find_index(o) }
index


text:
Q: What would be more appropriate for my need (XML\Json) and how do I use it? I'm making a game, in C# (MonoGame if it makes a difference), and the game has both a server and a client.
I want the client to hold some kind of textual representation of the items, so that when I load the client it will read the file and parse it into game objects so that I can easily handle items.
I thought about using XML or JSON, I know the basics of both, but I really don't know
How to use them in code.
What do you think would be more appropriate? I think XML is more appropriate but I might be wrong, this is why I'm asking...
The file would have this kind of structure
<items>
  <item>
    <id></id>
    <name></name>
    <cost></cost>
    <description></description>
    <pathofimage></pathofimage>
  </item>
  <item>
    <id></id>
    <name></name>
    <cost></cost>
    <description></description>
    <pathofimage></pathofimage>
  </item>
</items>

How, given this example structure, do I get the data from the file?

A: It depends, XML is easier to work with using builtin .NET namespaces like System.Xml or System.Xml.Linq.
JSON could be better if you'll use this data in javascript or in some public game API, but it will need some third-party library to work with it like JSON.NET (it gives better json support). Also json is more lightweight then xml and large amount of data will be smaller in json.
parsing code example using linq for xml (System.Xml.Linq namespace):
var xmlString = @"<items>
  <item>
    <id>100</id>
    <name>lance</name>
    <cost>9.99</cost>
    <description></description>
    <pathofimage></pathofimage>
  </item>
  <item>
    <id>101</id>
    <name>sword</name>
    <cost>12.50</cost>
    <description></description>
    <pathofimage></pathofimage>
  </item>
</items>";

var doc = XDocument.Parse(xmlString);
var items = doc.Root.Elements("item").Select(e => new {
                                    Id = int.Parse(e.Element("id").Value),
                                    Name = e.Element("name").Value,
                                    Cost = decimal.Parse(e.Element("cost").Value)});

results:

(I'm using LinqPad for represent results here, highly recommend it for playing with linq and linq for xml)


text:
Q: Pulling date into subtitle for tableview controller PFTableView The following is successful at pulling the "category" into the main Title until I start trying get createdAt into the subtitle.
When I start to override func tableView to import the createdAt into the subtitle, the app crashes.
Any thoughts?
import UIKit; import Parse

class UserRecordsTableViewController: PFQueryTableViewController {

    // Initialise the PFQueryTable tableview
    override init!(style: UITableViewStyle, className: String!) {
        super.init(style: style, className: className)
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        // Configure the PFQueryTableView
        self.parseClassName = "Event"
        self.textKey = "category"
        self.pullToRefreshEnabled = true
        self.paginationEnabled = false

    }

    // Define the query that will provide the data for the table view
    override func queryForTable() -> PFQuery! {
        var query = PFQuery(className: "event")
        query.orderByAscending("createdAt")
        query.whereKey("user", equalTo: PFUser.currentUser())

        return query
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject) -> PFTableViewCell {

        var cell = tableView.dequeueReusableCellWithIdentifier("Cell") as PFTableViewCell!

        if cell == nil {
            cell = PFTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
        }

        //Date for cell subtitle
        var dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        let dateForText = object["createdAt"] as? NSDate
        cell.detailTextLabel?.text =        dateFormatter.stringFromDate(dateForText!)

        return cell
    }

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

        // Get the new view controller using [segue destinationViewController].

    }

}

fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)

A: detailTextLabel will be nil in a cell of the default type. If you made the cell in the storyboard, set its type to "Subtitle". If you didn't make it in the storyboard, then change the line where you create the cell to,
cell = PFTableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell")

A: Heres what I ended up going with and this works so far. The problem was that PFTableViewCell is only intended to work with default not subtitle. So I had to create a custom cell. Next finally found the solution to the date fix on another post.
import UIKit; import Parse

class UserRecordsTableViewController: PFQueryTableViewController {

    // Initialise the PFQueryTable tableview
    override init!(style: UITableViewStyle, className: String!) {
        super.init(style: style, className: className)
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        // Configure the PFQueryTableView
        self.parseClassName = "Event"
        self.textKey = "category"
        self.title = "createdAt"
        self.pullToRefreshEnabled = true
        self.paginationEnabled = false

    }

    // Define the query that will provide the data for the table view
    override func queryForTable() -> PFQuery! {
        var query = PFQuery(className: "event")
        query.orderByAscending("createdAt")
        query.whereKey("user", equalTo: PFUser.currentUser())

        return query
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject) -> PFTableViewCell {

        var cell = tableView.dequeueReusableCellWithIdentifier("Cell") as UserRecordsTableViewCell!

        if cell == nil {
            cell = UserRecordsTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
        }

    var dateUpdated = object.createdAt as NSDate
    var dateFormat = NSDateFormatter()
    dateFormat.dateFormat = "EEE, MMM d, h:mm a"

    cell.catDate.text = NSString(format: "%@", dateFormat.stringFromDate(dateUpdated))
    cell.catTitle.text = object["category"] as String!

        return cell
    }

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

        // Get the new view controller using [segue destinationViewController].
        /*var detailScene = segue.destinationViewController as YourDetailViewController*/

        // Pass the selected object to the destination view controller.
        /*if let indexPath = self.tableView.indexPathForSelectedRow() {
            let row = Int(indexPath.row)
            detailScene.currentObject = objects[row] as? PFObject
        }*/
    }
}


text:
Q: Posts being loaded for all users in collection view firebase & swift All I'm trying to do is fetch all the posts to the collection view that are within a certain radius of the current user. Currently I'm getting all the current users posts within the location but that is all. I can't figure out how to convert it to fetch all the posts from all the users.
FetchPostUserIds Is returning a snapshot of all the users and there UID
The geoFire query is only returning the postId from the current user. It shouldn't be I assume
Note: Updated Code
var PostKey: String?
var geoFire: GeoFire?
var regionQuery: GFRegionQuery?
var foundQuery: GFCircleQuery?
var geoFireRef: DatabaseReference!

override func viewDidLoad() {
    super.viewDidLoad()

    guard let uid = Auth.auth().currentUser?.uid else { return }
    geoFireRef = Database.database().reference().child("posts").child(uid)
    geoFire = GeoFire(firebaseRef: geoFireRef)

}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    let userLocation: CLLocation = locations[0] as CLLocation
    let currentUserLocation = userLocation

    let circleQuery = geoFire?.query(at: currentUserLocation, withRadius: 100.0)
    _ = circleQuery?.observe(.keyEntered, with: { (key, location) in
        self.PostKey = key
        self.locationManager.stopUpdatingLocation()
    })
}

 fileprivate func fetchPostsWithUser(user: User) {

    guard let key = PostKey else { return }

    let ref = Database.database().reference().child("posts").child(user.uid).child(key)
    ref.observeSingleEvent(of: .value, with: { (snapshot) in
        self.collectionView?.refreshControl?.endRefreshing()

        guard let dictionary = snapshot.value as? [String: Any] else { return }

        var post = Post(user: user, dictionary: dictionary)
        post.id = key

        self.posts.append(post)
        self.posts.sort(by: { (post1, post2) -> Bool in
            return post1.creationDate.compare(post2.creationDate) == .orderedDescending
        })
        self.collectionView?.reloadData()
    }) { (error) in
        print(error)
    }

}

fileprivate func fetchPostUserIds() {

    let ref = Database.database().reference().child("users")
    ref.observeSingleEvent(of: .value, with: { (snapshot) in

        guard let userIdKey = snapshot.value as? [String: Any] else { return }

        userIdKey.forEach({ (key, value) in
            Database.fetchUserWithUID(uid: key, completion: { (user) in
                self.fetchPostsWithUser(user: user)
            })
        })

    }) { (error) in
        print(error)
    }

}

A: Try to debug and look what you got in the snapshot in your function, and also what fetchUserWithUID return
fileprivate func fetchPostUserIds() {

     let ref = Database.database().reference().child("users")
        ref.observeSingleEvent(of: .value, with: { (snapshot) in

            guard let userIdKey = snapshot.value as? [String: Any] else { return }

            userIdKey.forEach({ (key, value) in
            Database.fetchUserWithUID(uid: key, completion: { (user) in
                self.fetchPostsWithUser(user: user)
            })
        })

    }) { (error) in
        print(error)
    }

}

Maybe with some more information I can help you

A: You pass paremeter user: User to method fetchPostsWithUser, but you always use the current user
guard let uid = Auth.auth().currentUser?.uid else { return }

also note these
let ref = Database.database().reference().child("users")
ref.observe(.value, with: { (snapshot) in

will load every change so think about singleObserve


text:
Q: Comparing two columns to get value for third column I have problem comparing two columns from two different excels to fill in values to another column in the first excel.
I have two excel files:

id
con_job
idContractor

1
job1

2
job2

3
job2

4
job3

5

6
job5

The other excel file looks like this.

id
job

1
job1

2
job2

3
job3

4
job4

5
job5

5
job6

Some values might be missing.
What I want is to have idContractor filled with id from the first excel, so it looks like this:

id
con_job
idContractor

1
job1
1

2
job2
2

3
job2
2

4
job3
3

5

6
job5
6

I have been trying to create code that fills idContracor, but it doesn't work
df["idContractor"] = np.where(df["job"].isin(df2["con_job"]), df2['id'], "")

#I have also tried to do something like this, but I cannot make it work
df[df['con_job'] == df2['job'], df['idContractor']] = df2['id']

A: I would use the Pandas merge function to do this. Here is how:
df1.merge(df2, how='left', left_on='con_job', right_on='job')


text:
Q: How to check if an argument was given or not? //Checks if an argument was specified
if (argv[1] != "")
    strcpy(Buff1, argv[1]);
else
    strcpy(Buff1, "default");

If I run:
./program test

Buff1 = test

If I run:
./program

Buff1 = PACKAGES/=packages

How do I make it if nothing was specified, that Buff1 would be "default" by default?

A: Okay, if nothing is passed, argc is going to be 1 (argc gives the number of passed arguments). This means that the only argv element with anything in it will be argv[0] (which contains the name of the program). That means a call to argv[1] will be an index out of range, possibly causing a crash, or if you're lucky will just be junk data.
if(argc == 1)
   strcpy(Buff1, "default");

else if(argc == 2)
    strcpy(Buff1, argv[1]);

else
    //do something here if there is more than 1 argument passed to it

It's also worthwhile to note that the way you passed the example arguments would not work with what you're intending: "./program test Buff1 = test" would result in argc being 4, with argv[0] being "test", argv[1] being "Buff1", argv[2] being "=" and argv[3] being "test".
Simply calling "./program test helllooo" would work with the program snipit I provided, filling Buff1 with "helllooo". And calling "./program test" would also work, filling Buff1 with "default". To do anything more advanced, you're going to have to get into command line switches (like ./program test -b somethinghere -x somethinghere), which is just a more advanced way of parsing argc and argv.

A: The argc gives You the number of arguments passed to the program.
Keep in mind that argc can not be less than 1 since argv[0] is always program's name so if there were no arguments passed You should use this if(argc == 1){}

A: Use argc for knowing how main arguments are passed. Shell or process invoker feeds the program with atleast one argument in general, that is program name itself and that is always the first argument. It turns out that argc=1 atleast, and argv[0] is program name.
  int main(int argc, char **argv){
      // declarations and all here
      if(argc<2){
         strcpy(Buff1, "default");

        }
       else{
          strcpy(Buff1, argv[1]);
      }
     return 0;
  }

With out using this, you have two problems. When you use argv[1], when argc=1, you are actually going array out of bounds. Since, c++ doesn't do any bounds check for you, sometimes your program might fail silently accessing memory address next to the argv[0]. And another problem is that you are trying to compare the strings with != operator. You can't compare string literals right away with ==/!= operator. You have to use strcmp or an equivalent function.

A: Use argc to determine arguments count. It will be equal to 1 if no arguments were given, and 2 if one argument was given.
Note that you can't compare C strings using == operator. It's pointers comparasion.

A: suggestion:
use argv.size() to get the count.