text:
Q: Bitwise Operation in json array I have a json file input.json with data in the following format:
{"userid":"04f","clients":[1,2]}
{"userid":"07f","clients":[1,6,7]}
{"userid":"082","clients":[2,6,1]}
{"userid":"0c1","clients":[3,9,8]}
{"userid":"13f","clients":[4]}

The clients array can contain numbers from 1-10 and there could be multiple elements but no duplicates. I would like to perform bitwise operation on this file.
I am expecting an output something like this (for bitwise OR operation on the elements of client array):
{"userid":"04f","clients":3}  #$((1|2))=3
{"userid":"07f","clients":7}  #$((1|6|7))=7
{"userid":"082","clients":7}  #$((1|6|2))=7
{"userid":"0c1","clients":11} #$((3|9|8))=11
{"userid":"13f","clients":4}  #$((4))=4

My file is huge around 250 million lines. I am looking for a solution in bash. What would be the fastest and the most optimal way to achieve this?

A: Unfortunately jq doesn't support bitwise operations yet. I'd recommend to write a small Python program:
from collections import OrderedDict
from functools import reduce
import json

with open('file.json', 'r') as fd:
    for line in fd:
        data = json.loads(line, object_pairs_hook=OrderedDict)
        data['clients'] = reduce(lambda x,y : x|y, data['clients'])
        print(json.dumps(data))

Output:
{"userid": "04f", "clients": 3}
{"userid": "07f", "clients": 7}
{"userid": "082", "clients": 7}
{"userid": "0c1", "clients": 11}
{"userid": "13f", "clients": 4}

A: The following builds on the two generic filters (convert/1 and to_i/1) available at https://rosettacode.org/wiki/Non-decimal_radices/Convert#jq
Their definitions are included below for completeness and ease of reference.
# input: an array of decimal numbers
def bitwise_or:
   map(convert(2) | explode | reverse | map(.-48))
   | transpose | map(max)
   | reverse
   | join("")
   | to_i(2) ;

.clients |= bitwise_or

convert and to_i
# Convert the input integer to a string in the specified base (2 to 36 inclusive)
def convert(base):
  def stream:
    recurse(if . > 0 then ./base|floor else empty end) | . % base ;
  if . == 0 then "0"
  else  [stream] | reverse | .[1:]
  | if   base <  10 then map(tostring) | join("")
    elif base <= 36 then map(if . < 10 then 48 + . else . + 87 end) | implode
    else error("base too large")
    end
  end;

# input string is converted from "base" to an integer, within limits
# of the underlying arithmetic operations, and without error-checking:
def to_i(base):
  explode
  | reverse
  | map(if . > 96  then . - 87 else . - 48 end)  # "a" ~ 97 => 10 ~ 87
  | reduce .[] as $c
      # state: [power, ans]
      ([1,0]; (.[0] * base) as $b | [$b, .[1] + (.[0] * $c)])
  | .[1];

A: Here is a stand-alone, efficient solution that only assumes the availability of jq 1.4 or later. It defines two generic functions: elementwise/1 and bitwise_or/0:
# transpose | map(f)
def elementwise(f):
  reduce .[1:][] as $a (.[0];
    reduce range(0; $a|length) as $i (.; .[$i] |= ([$a[$i], . ] | f) )) ;

# input: an array of decimal integers
def bitwise_or:

  # Input: an integer
  # Output: a stream of 0s and 1
  def stream:
    recurse(if . > 0 then ./2|floor else empty end) | . % 2 ;

  # Input: a 0-1 array
  def toi:
    reduce .[] as $c ( {power:1, ans: 0};
      .ans += ($c * .power) | .power *= 2 )
    | .ans;

  map([stream])
  | elementwise(max)
  | toi ;

# The problem at hand:
.clients |= bitwise_or

Invocation:
$ jq -f program.jq input.json

A: One way(since you said bash) would be to use awk.
tr -d "[]}" <input.json | awk -F ":" '{split($3,a,",") ;o=0;for (i in a)  {o = or(o,a[i])};print $1":"$2":"o"}"  }'

awk has bitwise OR function - which is used as or(arg1,arg2,..argn).
tr -d "[]}" is used to eliminate extra characters before performing operations.
split() stores a delimiter (,)  separated values into arrays.
This gives :
{"userid":"04f","clients":3}
{"userid":"07f","clients":7}
{"userid":"082","clients":7}
{"userid":"0c1","clients":11}
{"userid":"13f","clients":4}

Note:This might not work for some other json formats.

A: Here is a jq solution.  The constant 128 in twopowers can be changed to whatever makes sense for your data (or you could even replace it with a simpler function that returns a constant stream)
def twopowers:               # return sequence of powers of 2
      128                    # largest power (change as desired)
    | log2 as $maxp          # e.g.   7
    | $maxp - range($maxp+1) #        7, 6, 5, 4, 3, 2, 1, 0
    | pow(2; .)              #        128, 64, 32, 16, 8, 4, 2, 1
;

def base2powers:             # e.g 81 -> [0,64,0,16,0,0,0,1]
    [
      foreach twopowers as $p (
          { v: . }
        ;   .diff = .v - $p
          | .v    = if .diff >= 0 then .diff else .v end
          | .bit  = if .diff >= 0 then 1     else  0 end
        ; .bit * $p
      )
    ]
;

def combine:                 # given an array of base2powers arrays
      reduce .[] as $a (     # compute the element-wise max array
         []                  # and return its sum
       ; [ . as $b
           | $a
           | range(length)
           | [ $a[.], $b[.] ]
           | max
         ]
      )
    | add
;

.clients = (.clients | map(base2powers) | combine)

Thinking a little more, we can eliminate the constant in twopowers by using the largest value from the .clients array to calculate the powers to use for each input.  Here is a version which does this.
def twopowers_v2:             # return sequence of powers of 2 less than given value
      .                       # e.g. 129
    | log2                    #        7.011227255423254
    | floor as $maxp          #        7
    | $maxp - range($maxp+1)  #        7, 6, 5, 4, 3, 2, 1, 0
    | pow(2; .)               #        128, 64, 32, 16, 8, 4, 2, 1
;

def base2powers_v2($powers):  # e.g 81 -> [64,0,16,0,0,0,1]
    [
      foreach $powers[] as $p (
          { v: . }
        ;   .diff = .v - $p
          | .v    = if .diff >= 0 then .diff else .v end
          | .pow  = if .diff >= 0 then $p    else  0 end
        ; .pow
      )
    ]
;

.clients = (
      .clients
    | [max|twopowers_v2] as $powers
    | map(base2powers_v2($powers))
    | combine
 )

Nishant Kumar observes that if .clients
is [0] the final result is null.  This is because 0 | twopowers_v2 returns no values.  To compensate for this we can add an explicit check:
def twopowers_v3:             # return sequence of powers of 2 less than given value
    if . > 0 then             # e.g. 129
      log2                    #        7.011227255423254
    | floor as $maxp          #        7
    | $maxp - range($maxp+1)  #        7, 6, 5, 4, 3, 2, 1, 0
    | pow(2; .)               #        128, 64, 32, 16, 8, 4, 2, 1
    else                      #
      0                       # but if input is 0, return 0
    end                       #
;

.clients = (
      .clients
    | [max|twopowers_v3] as $powers
    | map(base2powers_v2($powers))
    | combine
 )

Looking at peak's second solution I notice two things:

*

*combine is the same as elementwise(max) | add

*elementwise(max) is the same as transpose | map(max)
Here is a version without combine
.clients = (
      .clients
    | [max|twopowers_v3] as $powers
    | map(base2powers_v2($powers))
    | transpose
    | map(max)
    | add
 )

Also using a "little-endian" representation for the bit array is simpler then this approach.


text:
Q: Replacing dotnet core binary with private How do I replace a dotnet core binary with a private build of the same binary?
I have an application (that I own all the source code to) and I want to replace just a single dll with once that has a fix. Whenever I replace the binary I get the exception
Unhandled exception. System.IO.FileLoadException: Could not load file or assembly '<my dll>, Version=2020.3.1.0, Culture=neutral, PublicKeyToken=null'.
The located assembly's manifest definition does not match the assembly reference. (0x80131040)

File name: '<my dll>, Version=2020.3.1.0, Culture=neutral, PublicKeyToken=null'

at <call stack>

I've tried calling gacutil.exe -i  but it didn't work.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Any possibility that I can provide configuration details at run time to producer and consumer in spring-kafka? We are migrating our project to microservices using spring boot. I have a requirement where I should be able to run producer and consumer using the configuration details such as bootstrap servers and key-value serdes provided by the user at run-time.
I was able to do this using java Apache Kafka API in the earlier project but I don't see any way to do this using spring-kafka API as it allows to define the producer or consumer related configuration only via Spring java configuration class or application.properties.

A: You can override whatever properties you want at runtime for both consumers and producers.
Use the ConcurrentKafkaListenerContainerFactory to create the listener container:
@Autowired
ConcurrentKafkaListenerContainerFactory<String, String> factory;

...

    ConcurrentMessageListenerContainer<String, String> container = factory.createContainer("someTopic");
    container.getContainerProperties()
            .getKafkaConsumerProperties()
            .setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "...");
    ...
    container.getContainerProperties().setMessageListener(someListener);
    container.start();

On the producer side, use this constructor:
/**
 * Create an instance using the supplied producer factory and properties, with
 * autoFlush false. If the configOverrides is not null or empty, a new
 * {@link DefaultKafkaProducerFactory} will be created with merged producer properties
 * with the overrides being applied after the supplied factory's properties.
 * @param producerFactory the producer factory.
 * @param configOverrides producer configuration properties to override.
 * @since 2.5
 */
public KafkaTemplate(ProducerFactory<K, V> producerFactory, @Nullable Map<String, Object> configOverrides) {
    this(producerFactory, false, configOverrides);
}


text:
Q: Is it thread safe to reset and copy shared_ptr simultaneously? Boost documentation describes shared pointer's behavior when accessing it from multiple threads simultaneously. Particularly they give some examples:
shared_ptr<int> p(new int(42));

//--- Example 1 ---

// thread A
shared_ptr<int> p2(p); // reads p

// thread B
shared_ptr<int> p3(p); // OK, multiple reads are safe

//--- Example 2 ---

// thread A
p.reset(new int(1912)); // writes p

// thread B
p2.reset(); // OK, writes p2

//--- Example 3 ---

// thread A
p = p3; // reads p3, writes p

// thread B
p3.reset(); // writes p3; undefined, simultaneous read/write
...

But they do not say (or I cannot see) what will happen if the same shared_ptr object is written and read at the same time. Say:
shared_ptr<int> p(new int(42));

//--- My Example ---

// thread A
p.reset(new int(1912));

// thread B
shared_ptr<int> p1 = p;

So my question is whether the last example is OK or not?
NOTE: Boost's third example explains that it is not safe to read and write the same object in parallel. But in their example they assign p3 to p, which is a copy of p3. So it is not clear to me whether the safety of that example depends on the fact that p3 gets assigned to its copy or whether something else is unsafe.

A:
But they does not say (or I cannot see) what will happen if the same shared_ptr object will be written and read at the same time.

Yes they do:

A shared_ptr instance can be "read" (accessed using only const operations) simultaneously by multiple threads. Different shared_ptr instances can be "written to" (accessed using mutable operations such as operator= or reset) simultaneously by multiple threads (even when these instances are copies, and share the same reference count underneath.)
Any other simultaneous accesses result in undefined behavior.

(emphasis mine)
Seems pretty clear to me.

So my question is whether the last example OK or not?

No, because what you are doing is not reading simultaneously from a single instance, nor writing to separate instances. You are simultaneously reading and writing a single instance. That's a data race, and undefined behaviour.

A: Now that we have C++11 (and 14/17), you may use the atomic shared pointer classes to atomically handle shared pointers in your threads.
http://en.cppreference.com/w/cpp/memory/shared_ptr/atomic
Simply put, if you may end up modifying a shared pointer, you should use the atomic functions everywhere (all reads and all writes.) Then your threads should not crash because of the shared pointer.


text:
Q: Handling a custom exception without changing the test class (java) I need to throw a couple times a custom exception. A test class is checking if my solution works but I'm not allowed to make any changes to this class which leads me to my problem.
I simplified the problem here, because the whole code is not needed here
public class Test{
    public static final String s = "0test";

    @Test
    public void testZero(){
        Solver sol = new Solver(Parser.run(s));
        //IntelliJ is underlining "run" because "Unhandled exception: ParseException", a
        //simple solution could be adding "throws ParseException" in the head, but I'm not
        //allowed to change the test class
    }
}
public class Parser{
    public static Pars run(String input) throws ParseException{
        if(input.charAt(0) == '0'){
            throw new ParseException("...");
        }
    }
}
public class ParseException extends Exception{
     public ParseException(String mess){
         super(mess);
     }
}

A:
I'm not allowed to make any changes to this class which leads me to my problem.

There is no way that you can throw an Exception to the Test class without catching it over there.
BUT you can prematurely just catch it inside the Parser#run(String input).
Instead of this:
public static Pars run(String input) throws ParseException{
    if(input.charAt(0) == '0'){
        throw new ParseException("...");
    }
}

You could (as I said) catch it in the method instead.
public static Pars run(String input) {
    try {
        if(input.charAt(0) == '0'){
            throw new ParseException("...");
        }
    } catch (ParseException e) {
        // System.out.println(e.toString());
        // Just handle it over here if you can't edit Test.java ...
    }
}

A: I have found the solution for my problem.
In my ParseException class, I need to change it  to:
public class ParseException extends IllegalArgumentException{...}

Further into the task, the test class didnt accept my exception because there was a IllegalArgumentException exspected.
Changing it into "extends IllegalArgumentException" solves the problem, so I dont need "throws ParseException" in the headings and no try,catch statements


text:
Q: Java Enum methods - switch vs Overriding for each object Let's consider an enum.
What's the difference between creating one method with "switch(this)" for each object
and creating one abstract method and overriding it for each object in enum?

A: There isn't necessarily a difference while you don't change the enum. However, let's look at an example:
enum MyEnum {
    FIRST
    {
        @Override
        void foo() {
            //Do something
        }
    },
    SECOND
    {
        @Override
        void foo() {
            //Do something else
        }
    };

    abstract void foo();
}

Now, if we were to add a new element THIRD to this enum, then the compiler would ensure that we actually implement this method.
Let's look at the switch case instead:
enum MyEnum {
    FIRST,
    SECOND;

    void foo() {
        switch (this) {
        case FIRST:
            //Do something
            break;
        case SECOND:
            //Do something else
            break;
        default:
            break;
        }
    }
}

If we were to add a new element THIRD, then we would be able to forget adding an additional case to the switch statement, meaning we need to be more careful.
One more difference is then simply that switch can be used for external functionality with these enum objects, while we can't add additional methods to the enum itself.

A: with a switch you can share code, many combinations of case labels for the same code.
If every enum is different (or mostly they are), I would use an override.
Note: you can have a default implementation and override the ones which are different.

A: The enum method has the advantage of following the Open/Closed principle. If you need to expand the enum, all you have to do is to implement the method for the new enum member and you are good; otherwise you have to go finding through your codes where your enum is used to cover all the possibilities.
The disavantage is that, if you are too strict about it, you may putting way too much things in your code. Imagine that you have an enum covering age ranges in your business level and you wish, at the UI level, to present a different layout based on the age of the user... obviously, adding a method to the enum specifying HTML details would break many abstraction levels.
I tend to use enum methods for issues that are related to the "core" functions of the enum, and using switches elsewhere.


text:
Q: Trap on DEBUG signal for the Alpine Shell (ash)? With the bash shell, you can install a trap on the synthetic DEBUG signal. This is useful and will execute your function or bit of code on every shell command, not so in ash, however. E.g.

$ trap 'echo hi' DEBUG
-ash: trap: DEBUG: invalid signal specification

How do you trap the DEBUG signal in ash?


text:
Q: Bash regex find replace I have a json file with lots of timestamps in it.  This file can contain thousands upoin thousands of timestamps.  Currently these timestamps are in the format dd/MM/yyyy HH:mm:ss.microseconds (6 digits after the decimal point).
I am trying to index these into elasticsearch but I really have no idea how to get this in without converting the date format to miliseconds not microseconds.
How can I write something in bash which can search and replace all occurances of dates in the format mentioned and replace it by the same timestamp truncated to 3 digits rather than 6?  I am not really even sure where to start.

A: Use sed:
sed 's-\([0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]\)[0-9][0-9][0-9]-\1-g' file

You might want to add the argument -i for an in-place edit (update file directly), but I'd suggest to check the results first.

A: Use sed:
d2='[0-9]\{2\}'
sed -e "s=\($d2/$d2/$d2$d2 $d2:$d2:$d2\.[0-9]\{3\}\)[0-9]\{3\}=\1=g"

A: You can use Bash.
while read line; do
    if [[ $line =~ [0-9]{2}/[0-9]{2}/[0-9]{4}\ [0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{3} ]]; then
        echo $BASH_REMATCH
    fi
done < file


text:
Q: Can´t find pptx module when I import pptx I get the error:
ModuleNotFoundError: No Module named 'pptx'

is that an issue with python 3?

A: You need to install it
pip -U install pptx

It is not a standard Python package as far as I know


text:
Q: Sharing methods between base classes for LinkButton, ImageButton, and Button So I want to add some javascript to the onclick event of several controls in my web site.  They are all of the Button, LinkButton, and ImageButton class.
I've created a class called CustomLinkButton that inherits from LinkButton and works perfectly.  It makes use of the OnLoad method and has some properties that use ViewState.  Great.  Now I'd like to use that code for Button and ImageButton.
Problem is, all three of those classes inherit from System.Web.UI.WebControls.WebControl, which is missing some important methods and properties common to all three of these controls.
So what to do?  Duplicating code in all the classes means poor maintainability.  I've tried making another class and writing the methods there but I run into the same problem - I can't have a method that accepts all three types but I can't write a generic method with more than one constraint.
Ideas?  Or do I just need to write three classes with duplicate code?  I've done a good deal of searching and can't find a solution.  This could apply to a lot of situations, hence my asking.  Thanks guys.
EDIT: Examples of relevant properties they share are CausesValidation and ValidationGroup.

A: Although they share similar functionality and needs they are indeed different controls for different purposes.  I recommend you keep them separate.  With enough time, energy and testing you could have one control that renders anything, but is that really what you want?
You would think LinkButton and ImageButton should inherit from Button, but that is just semantics.  You should think about them in terms of what they render, which is HTML:

*

*asp:button is a <input type="button">

*asp:linkbutton is a <a>

*asp:imagebutton is a <input type="image">


text:
Q: What is meant by "T" and "aT" here? https://ctms.engin.umich.edu/CTMS/index.php?example=BallBeam&section=ControlFrequency
I am trying to learn about lead compensator from above link
But i have bit confusion regarding two terms,"T" and "aT" here, as shown higlighted in attached snapshot?
What do they denote?
They are related to some time parameters but it is not exactly clear, whose those parameters are?

A: These are time constants and the formula would more advantageously be written as \$C(s) = K\frac{1+\tau s}{1+\alpha\tau s}\$ where \$\tau\$ is a time constant and has a dimension of time while \$\alpha\$ is unitless. \$K\$ represents the gain of this compensator for \$s=0\$.
In a first-order system, the pole is the inverse of the time constant and this expression can be reformulated as follows: \$C(s)=C_0\frac{1+\frac{s}{\omega_z}}{1+\frac{s}{\omega_p}}\$ with \$\omega_z=\frac{1}{\tau}\$ and \$\omega_p=\frac{1}{\alpha\tau}\$. I replaced \$K\$ by \$C_0\$ indicating that this is the gain of \$C\$ when \$s=0\$.
This type of compensator involves a zero \$f_z\$ and pole \$f_p\$ linked by the coefficient \$\alpha\$. If \$\alpha\$ is 1, then the pole and zero are coincident and cancel each other in magnitude and phase. If the zero is now lower than the pole (\$\alpha < 1\$), then you can determine the phase of the system and see that it increases: we say the compensator boosts the phase between the zero and the pole. As you spread them (the zero goes down the frequency axis while the pole runs opposite towards higher frequency), the phase boost increases and peaks to 90° as a maximum. You will actually organize the zero and pole so that it produces the expected phase boost at the point you need it the most which is usually the crossover frequency \$f_c\$. And if you do the maths ok, you'll find that the phase boost peaks at \$f_c=\sqrt{f_zf_p}\$. If you now add a pole at the origin (with an op-amp based circuit), you have created a type 2 compensator, extremely popular in switching converters.


text:
Q: No acceptable C compiler found in $PATH So here's the situation. I want to setup a portable programming environment by installing my programming stuff (Vim, Clang, Git, GCC) in a single folder that I can create on any Mac. I am installing everything in /opt, which isn't there by default and I should have write permissions to create. I got Vim, Clang, and Git working by downloading the Xcode Command Line Tools and a program that can extract the contents of the PKG's. I put everything in their respective folders in /opt, e.g /opt/usr/bin. They are all doing dandy.
Here's the problem. I am trying to get GCC to work. I downloaded the OSX GCC Installer and did the same technique with GCC-4.2. The problem is that when I do a test compile, I run this. Edit: I get the same error message if I do CC=gcc-4.2
./configure --prefix=/opt/usr/bin

and receive
checking build system type... x86_64-apple-darwin11.4.2
checking host system type... x86_64-apple-darwin11.4.2
checking target system type... x86_64-apple-darwin11.4.2
checking for a BSD-compatible install... /usr/bin/install -c
checking whether ln works... yes
checking whether ln -s works... yes
checking for a sed that does not truncate output... /usr/bin/sed
checking for gawk... no
checking for mawk... no
checking for nawk... no
checking for awk... awk
checking for libatomic support... yes
checking for libcilkrts support... yes
checking for libitm support... yes
checking for libsanitizer support... yes
checking for libvtv support... no
checking for gcc... no
checking for cc... no
checking for cl.exe... no
configure: error: in `/opt/gcc-master':
configure: error: no acceptable C compiler found in $PATH
See `config.log' for more details.

This is strange because GCC-4.2 is in my $PATH
echo $PATH
/opt/usr/bin:/opt/usr/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin

cd /opt/usr/bin ; ls | grep gcc
gcc
gcc-4.2
i686-apple-darwin11-gcc-4.2.1

FYI: 'gcc' is a symlink that doesn't point to anything.
which gcc-4.2
/opt/usr/bin/gcc-4.2

A: I solved this by adding this to my .zshrc. It forces any configure script to look for gcc-4.2 instead of gcc.
CC=/opt/usr/bin/gcc-4.2

A: configure: error: no acceptable C compiler found in $PATH
Before executing the ./configure command, i used the command:
sudo apt install gcc
And the error 'no acceptable ...' is solved.


text:
Q: Example of divisible module that is not injective We know that every injective module is divisible, but I can't find an example of divisible module such that it is not injective.

A: Hint
Joseph Rotman in the book An Introduction to Homological Algebra says

"a domain $R$ is a dedekind ring if and only if every divisible module is injective" (Theorem 4.24)

so you can consider a domain that is not a dedekind ring


text:
Q: Convert ordered levels to numeric in pandas I was wondering is there any function in pandas that allows me to do this.
I have a column with levels [low, medium, high].
I would like to translate them to [1,2,3] to perform linear regression. However, what i am currently doing is df[df['interest_level'] == 'low'] = 1. is there a better way of doing this?
Thanks.

A: use pd.factorize() method:
df['interest_level'] = pd.factorize(df['interest_level'])[0]

you can also categorize your new numerical values (this might save a lot of memory):
Sample DataFrame:
In [34]: df = pd.DataFrame({'interest_level':np.random.choice(['medium','high','low'], 10)})

In [35]: df
Out[35]:
  interest_level
0           high
1            low
2         medium
3           high
4            low
5           high
6           high
7            low
8            low
9         medium

Solution:
In [36]: df['interest_level'], cats = pd.factorize(df['interest_level'])

In [37]: df['interest_level'] = pd.Categorical(df['interest_level'], categories=np.arange(len(cats)))

In [38]: df
Out[38]:
  interest_level
0              0
1              1
2              2
3              0
4              1
5              0
6              0
7              1
8              1
9              2

In [39]: cats      # this can be used for the backtracing ...
Out[39]: Index(['high', 'low', 'medium'], dtype='object')

In [40]: df.memory_usage()
Out[40]:
Index             80
interest_level    34   # <---- NOTE: only 34 bytes used for 10 integers
dtype: int64

In [41]: df.dtypes
Out[41]:
interest_level    category
dtype: object

A: You can use map:
d = {'low':1,'medium':2,'high':3}

df['interest_level'] = df['interest_level'].map(d)

Sample:
df = pd.DataFrame({'interest_level':['medium','high','low', 'low', 'medium']})
print (df)
  interest_level
0         medium
1           high
2            low
3            low
4         medium

d = {'low':1,'medium':2,'high':3}
df['interest_level'] = df['interest_level'].map(d)
print (df)
   interest_level
0               2
1               3
2               1
3               1
4               2

Another solution is cast to Categorical and then use cat.codes:
categories = ['low','medium','high']
df['interest_level'] = df['interest_level'].astype('category',
                                                    categories=categories,
                                                    ordered=True).cat.codes + 1
print (df)
   interest_level
0               2
1               3
2               1
3               1
4               2


text:
Q: Changing the properties of elements in Office Ribbon using VBA I am a beginner in VBA and Office Ribbon UI. I am using Office 2007 and used Custom UI to develop a Ribbon in PPTM. I have added a set of XML like the one below:
<group id="myGroup" label="Hello World" visible="false">
    <labelControl id="lblUsername" label="Your Username: " />
    <labelControl id="lblFullname" label="" />
</group>

So, in this Hello World tab, I would like to change its visibility to true and change the the values of lblUsername and lblFullname. Currently this has to be done after the previous call by this button:
<button id="signin" label="Sign In" image="signin" size="large"
    supertip="Click this button to sign in."
    onAction="ribbon_SignIn" tag="SignIn" />

Right now the code in the ribbon_SignIn is as follows:
Sub ribbon_SignIn()
    SignIn.Show
End Sub

This opens the SignIn form and gets the Username and Password from the user. After the username and password are validated, everything goes fine, but I am not sure what is the procedure to get the properties of controls lblUsername and lblFullname to change their values with the signed in user's details.

Clarification
In the SignIn form I have the below code for the Sign In button.
Private Sub btnSignIn_Click()
    ' Authentication Mechanism
    MsgBox "You have successfully signed in!"

    ' Show the Ribbon group.
    ' What am I supposed to do here to make the group visible?
    ' Also how do I change the text of the label?
End Sub

So, here what should I put to make the group visible? Also how do I change the text of the label?

Update #1
When I use the two attributes getVisible and getLabel in the Custom UI, the add-in itself is not getting displayed. :( The code that I used was:
<group id="myGroup" label="Hello World" getVisible="VisibleGroup">
    <labelControl id="lblUsername" label="Your Username: " getLabel="lblUsername" />
    <labelControl id="lblFullname" label="" getLabel="lblFullname" />
</group>

If I remove those two attributes, Weird. BTW, I am using Office 2007.

A: You can use something called the getLabel property in your xml.
e.g.
getLabel = "GetLabelMacro"

Now in your GetLabelMacro you can put in code as
Sub GetLabelMacro(control As IRibbonControl, ByRef label)
    if control.id = "MyLabel" then
        label = "New Label"
    end if
End Sub

You can modify this sample code for your purposes. More info on the syntax of getLabel can be found by googling about the getLabel callback.

A: Here is a simple, functional example. I substitute simple InputBox prompts instead of trying to recreate your UserForm code, but the general principal should still apply.
I create public variables for username and fullname and bAuthenticated (have your form assign to these variables, or reference the form directly).  Set bAuthenticated = True once you have authenticated the user.
Use the getLabel callback and refresh the ribbon.  I create two separate callbacks, one for username, one for fullname, these are getUserName and getFullName.  I also add the vba for VisibleGroup which is called from the getVisible XML property.
Note when making changes to your VBA you will likely have to save, close & re-open the file, because making these changes may clear all public variables, including the variable which represents the ribbon itself. This is why you might be getting errors from the RefreshRibbon procedure.
Your xml might look like this.
Updated to include the getVisible callback
<customUI xmlns="http://schemas.microsoft.com/office/2009/07/customui" onLoad="RibbonOnLoad">
    <ribbon startFromScratch="false" >
        <tabs>
            <tab id="customTab" label="Custom Tab">
                      <group id="myGroup" label="Hello World" getVisible="VisibleGroup" >
                          <labelControl id="lblUsername" getLabel="getUserName" />
                          <labelControl id="lblFullname" getLabel="getFullName" />
                      </group>
                      <group id="mySignin" label="SignIn" visible="true" >
                          <button id="signin" label="Sign In" size="large"
                              supertip="Click this button to sign in."
                              onAction="ribbon_SignIn" tag="SignIn" />
                      </group>
            </tab>
        </tabs>
    </ribbon>
</customUI>

Note: I have set the visible property of myGroup to True so that I could more easily test this. You can use the getVisible callback similarly, if you need to change this property at run-time.
And then the callbacks in VBA module will look more or less like:
Option Explicit
Public Rib As IRibbonUI
Public xmlID As String
Public username As String
Public fullName As String
Public bAuthenticated As Boolean

'Callback for customUI.onLoad
Sub RibbonOnLoad(ribbon As IRibbonUI)
    'MsgBox "onLoad"
    Set Rib = ribbon
End Sub

Sub ribbon_SignIn(control As IRibbonControl)

    username = InputBox("enter your username", "Your username?")
    fullName = InputBox("enter your full name", "Your full name?")

    'Authenticate
    bAuthenticated = True

    VisibleGroup control, bAuthenticated
End Sub
Sub VisibleGroup(control As IRibbonControl, ByRef returnedVal)
    returnedVal = bAuthenticated
    Call RefreshRibbon("myGroup")
End Sub
Sub getUserName(control As IRibbonControl, ByRef returnedVal)
    returnedVal = username
    Call RefreshRibbon(control.id)
End Sub
Sub getFullName(control As IRibbonControl, ByRef returnedVal)
    returnedVal = fullName
    Call RefreshRibbon(control.id)
End Sub
Sub RefreshRibbon(id As String)
    xmlID = id
    'MsgBox "Refreshing ribbon for " & Id, vbInformation
    If Rib Is Nothing Then
        MsgBox "Error, Save/Restart your Presentation"
    Else
        Rib.Invalidate
    End If
End Sub


text:
Q: Intellij IDEA not running gradle install I am somewhat new to IDEA, having only used Android Studio for a few months. I imported a maven project into the IDEA community edition and it seems to build well. However, it doesn't seem to be running gradle install. I need the artifacts in my local maven repository. I can run gradle install from the command line and it publishes to my local maven repo.
Here is my build.gradle for reference.
plugins {
    id 'java'
    id 'maven'
    id 'maven-publish'
}

repositories {
    mavenLocal()
    maven {
        url = 'http://repo.maven.apache.org/maven2'
    }
}

dependencies {
}

group = 'org.secomm'
version = '1.4.0'
description = 'seComm JSON messages'
sourceCompatibility = '1.8'

tasks.withType(JavaCompile) {
    options.encoding = 'UTF-8'
}

Any help is appreciated.


text:
Q: What's this column [Bmk1002] in the table scan operator of my execution plan? I have a simple script.
IF OBJECT_ID('dbo.Customers', 'U') IS NOT NULL
    DROP TABLE dbo.Customers;
GO
CREATE TABLE dbo.Customers
(
 custid INT NOT NULL,
 companyname VARCHAR(125) NOT NULL,
 phone VARCHAR(120) NOT NULL,
 address VARCHAR(150) NOT NULL
);
INSERT  INTO dbo.Customers
        (custid, companyname, phone, address)
VALUES  (1, 'cust 1', '(111) 111-1111', 'address 1'),
        (2, 'cust 2', '(222) 222-2222', 'address 2'),
        (3, 'cust 3', '(333) 333-3333', 'address 3'),
        (4, 'cust 4', '(444) 444-4444', 'address 4'),
        (5, 'cust 5', '(555) 555-5555', 'address 5');
IF OBJECT_ID('dbo.CustomersStage', 'U') IS NOT NULL
    DROP TABLE dbo.CustomersStage;
GO
CREATE TABLE dbo.CustomersStage
(
 custid INT NOT NULL,
 companyname VARCHAR(125) NOT NULL,
 phone VARCHAR(120) NOT NULL,
 address VARCHAR(150) NOT NULL
);
INSERT  INTO dbo.CustomersStage
        (custid, companyname, phone, address)
VALUES  (2, 'AAAAA', '(222) 222-2222', 'address 2'),
        (1, 'cust 1111111111', '(111) 111-11111111111111', 'address 111111111'),
       -- (1, 'cust 1111111112222222222', '(111) 111-1111111112222222222', 'address 1111111112222222222'),
        (3, 'cust 3', '(333) 333-3333', 'address 3'),
        (5, 'BBBBB', 'CCCCC', 'DDDDD'),
        (6, 'cust 6 (new)', '(666) 666-6666', 'address 6'),
        (7, 'cust 7 (new)', '(777) 777-7777', 'address 7');

SELECT  *
FROM    dbo.Customers;
SELECT  *
FROM    dbo.CustomersStage;

SET STATISTICS XML ON;
MERGE INTO dbo.Customers d
USING dbo.CustomersStage s
ON d.custid = s.custid
WHEN MATCHED THEN
    UPDATE SET d.companyname = s.companyname,
               d.phone = s.phone,
               d.address = s.address
WHEN NOT MATCHED THEN
    INSERT (
            custid,
            companyname,
            phone,
            address
           )
    VALUES (
            s.custid,
            s.companyname,
            s.phone,
            s.address
           );
SET STATISTICS XML OFF;

SELECT  *
FROM    dbo.Customers;

The execution plan of the MERGE statement looks like this.

You can download the execution plan here at https://drive.google.com/file/d/0B4xMAUd6DN6XdkZyTmJkdF9TY3c/view?
My question is, what exactly is this [Bmk1002]? Hope someone can help to explain it.

A: It is the "bookmark" (also referred to in the phrase "bookmark lookup").
This is the physical location of the row (File:Page:Slot).
Customers is a heap
SELECT %%lockres%%
FROM Customers

Will show you these values (if it had a clustered index you could use %%physloc%% instead but the raw output from this is not as friendly).
It is needed in this execution plan because the specification of merge requires it to throw an error if there is an attempt to update or delete the same row more than once.
As there is no other unique key available SQL Server uses this bookmark instead as a value guaranteed to be able to uniquely identify a row.
The plan calculates ROW_NUMBER() OVER (PARTITION BY Bmk1002 ORDER BY Bmk1002) * and the assert operator raises an error if this is ever >1 (which would happen if there were multiple rows in dbo.CustomersStage that join to the same one in dbo.Customers).

* Actually the plan calls conditional_row_number rather than row_number. This is an internal undocumented function. I imagine that it uses the conditional version rather than straight row_number as it needs to ignore rows with an action of "insert" in the check for duplicates.

A: The Bmkxxxx is an additional column, not referenced in the query.
It's the key value from the tablescan and it will be used in the later parts of the query execution. Check out this excellent ebook from Red-gate to learn more about execution plans. http://download.red-gate.com/ebooks/SQL/eBOOK_SQLServerExecutionPlans_2Ed_G_Fritchey.pdf
And download this tool from SQL Sentry to help you navigate execution plans.
http://www.sqlsentry.com/products/plan-explorer/sql-server-query-view
And this course at Pluralsight is excellent.
https://www.pluralsight.com/courses/sqlserver-query-plan-analysis


text:
Q: How to migrate a git project from using master as the default branch to main? I'm the maintainer of a project that's hosted on github/gitlab and has a number of contributors. I want to migrate from using master as the default branch to main. How do I do that without messing up?
I've read some blog-posts on the topic, but would prefer a discussion over here at StackOverflow where comments might point out issues that a single person could have overlooked.

A: Github offers a migration option, so it's trivial. But even with any other service like gitlab that doesn't have something like that (yet), as long as you're doing the right steps it's relatively straight-forward, at least from a technical point of view.
Either way, unless your project is quite small, the biggest hassle will surely be getting all your contributors to apply fixes to work-in-progress correctly.
What you need to do
Github
On your project page, navigate to settings, and in the section "Default branch", press the edit button and change it from master to main.
Gitlab, aka migrating manually
I'm assuming that your remote/upstream is called origin - if it's called something different, replace origin with that name in all commands accordingly.

*

*Rename the most recent master to main, and push it upstream:

git fetch origin
git branch --move master main
git push --set-upstream origin main

*Tell your upstream that main is the new default:

*

*Navigate to settings/repository, section "Default branch", select main and press "Save Changes". Then, on the same page, go the the section "Protected branches", and protect main and unprotect master, and press "Save Changes".

*Delete master on upstream - not strictly necessary, but does reduce confusion:
git push origin --delete master

*Migrate open merge/pull requests that wanted to be pushed into master to be pushed into main instead:

*

*On an open merge request, press "edit". On the top, it should say "From <branch_name> into master". Change the drop-down from master to main.

What your collaborators/colleagues need to do
git fetch origin --prune && git branch -m master main && git branch --set-upstream-to=origin/main main

As far as I know, that's it - the &&s are a good idea to protect you in case something doesn't add up.

Please leave a comment if you ran into issues following this advice. git fuckups are hellish to untangle, so the least we can do is to try and not reinvent the wheel any more than we need to.

A: I'm managing a self-hosted gitlab instance (v13.x.y), and you don't have to do it manually - there's a similar solution to this as the one mentioned by Arne for github.
First, copy your master branch to main branch.
Then, go to project Settings, click Repository, and change the default branch.

After that, you can use the above snippet to update your local repository (change the branch names if you need to), or if you're worried that you might mess something up, you can delete the project and clone it again.


text:
Q: Selenium Java process called from c# not starting properly on CCNET build server I'm setting up CCNET server to run Selenium tests. In my test code I use the following to start the Selenium RC server if its not running:
var proc = new Process();
proc.StartInfo.WorkingDirectory = Path.Combine(Directory.GetParent(Assembly.GetExecutingAssembly().Location).FullName, @"..\..\..\..\..\lib\SeleniumRC\selenium-server-1.0-beta-2");
proc.StartInfo.FileName = "java"; //have also tried with "java.exe"
proc.StartInfo.Arguments = @"-jar selenium-server.jar -multiWindow -trustAllSSLCertificates -firefoxProfileTemplate ""..\Firefox Profiles\Relaxed Security""";
proc.StartInfo.UseShellExecute = true;
proc.Start();

This works great on my development machine. However, when I run it from CCNET.exe (under a user context), I can see that instead of executing the java.exe process, an explorer window pops up for "c:\windows\java". I think my path settings are messed up but I'm not sure how. Can you help?

A: Have you tried going to that working directory in a Command prompt under the user context you are running it under and trying the command line?
If the path settings are messed up, you can adjust them by right clicking the My computer, properties, Advanced, Environment Variables...

A: I did this to start the server in the background:
// Start the java server
Process seleniumServer;
String javaFileLocation = @"C:\Program Files\Java\jre6\bin\java.exe";
String jarFileLocation = @"C:\SeleniumRC\selenium-remote-control-1.0.1\selenium-server-1.0.1\selenium-server.jar";
seleniumServer = new Process();
seleniumServer.StartInfo.FileName = javaFileLocation;
seleniumServer.StartInfo.Arguments = "-jar " + jarFileLocation;
seleniumServer.StartInfo.WorkingDirectory = jarFileLocation.Substring(0, jarFileLocation.LastIndexOf("\\"));
seleniumServer.StartInfo.UseShellExecute = true;
seleniumServer.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
seleniumServer.Start();

then just did
seleniumServer.Kill()

to stop it after all went well.
Not sure this will help the CCNET situation but may help people looking for this in future?

A: i use this one
public class Navegador : DefaultSelenium
    {
       private static int contadorPorta = 4444;
    private int porta;

    private delegate string OperacaoSelenium();

    // Variável para a URL Base
    private string urlBase;
    public string UrlBase
    {
        get { return urlBase; }
    }

    public Navegador(string urlBase)
        : base("localhost", contadorPorta, "*firefox", urlBase) // ou *firefox ou *chrome *safari, *opera , *iexplore etc.
    {
        this.urlBase = urlBase;

        porta = Navegador.contadorPorta;
        // Deve sempre abrir o Selenium RC-Server antes (instância única - Singleton)
        this.IniciarSeleniumRCServer();
        Navegador.contadorPorta++;

        this.Start();
        this.Open("/");
    }

    /// <summary>
    /// Inicia o Selenium RC-Server, que é o arquivo JAR que vem no pacote do Selenium RC
    /// </summary>
    private void IniciarSeleniumRCServer()
    {
        string seleniumParameters = "..\\..\\..\\ExternalLibraries\\selenium-remote-control-1.0-beta-1\\selenium-server-1.0-beta-1\\selenium-server.jar -Dhttp.proxyHost=10.100.100.24 -port " + porta + "";
        procSeleniumServer = System.Diagnostics.Process.Start("java.exe", " -jar " + seleniumParameters);
        System.Threading.Thread.Sleep(1000);
    }

works good.. but not under a proxy -.-'

A: SeleniumProcess Class
public class SeleniumProcess
    {
        private static Process _seleniumServer;

        public static void Start()
        {
            _seleniumServer = new Process
                                  {
                                      StartInfo =
                                          {
                                              FileName = "java",
                                              Arguments =
                                                  "-jar ../../../References/" +
                                                  "selenium-remote-control-1.0.3/" +
                                                  "selenium-server-1.0.3/" + "selenium-server.jar -port 4444"
                                          }
                                  };
            _seleniumServer.Start();
        }

        public static void Stop()
        {
            _seleniumServer.Kill();
        }
    }

region Setup/Teardown
    [SetUp]
    public void SetupTest()
    {
        SeleniumProcess.Start();
    }

    [TearDown]
    public void TeardownTest()
    {
        try
        {
            _selenium.Stop();
        }
        catch (Exception)
        {
            // Ignore errors if unable to close the browser
        }
        SeleniumProcess.Stop();
        Assert.AreEqual("", _verificationErrors.ToString());
    }

    #endregion


text:
Q: Building iOS apps without mac
Possible Duplicate:
Starting iPhone app development in Linux?
Development of iPhone application in linux
Alternatives For iOS Development Under Windows

I want to learn how to build iOS apps but I dont really have a Mac with me, (but I can use one for testing and stuff).
So is there any alternative for Xcode IDE in linux(ubuntu-debain) or windows that could be used to get some sort of similar environment as Xcode ?
I know that we can run Mac in VM, but I dont want to use that(its slow,sluggish and painful to use).
Also If you guys happen to know how to compile Objective-C code on Linux,pls share !

A: I compiled a 4.2 version of the GNU toolchain for 64-bit linux. http://xsellize.com/topic/111034-toolchain-for-ios-42/

A: The iOS SDK is only available with Xcode, which is only available to use on a Mac. So while you can certainly compile Objective-C with gcc on other platforms, you won't be able to compile and link code that uses any iOS SDK APIs on anything but a Mac.


text:
Q: Why are my httpd mpm_prefork processes being reaped so quickly? [EDIT]
Bad question, mostly - see my answer
[/EDIT]
We've got a system running RHEL6, x64.  We are using a local installation of apache 2.2.22 from source.  we serve primarily:

*

*mod_perl applications (with a local installation of perl 5.16.0)

*tomcat applications proxied with mod_jk

Here is some context; the main question is below.
All of this talks to an Oracle backend.
We are having issues with Oracle becoming unresponsive.  We think this is because we're hitting the maximum process limit in oracle.  We've upped the process limit, but now we are hitting memory pressure on the oracle server.  We have tons of oracle sessions sitting idle.    I can trace a bunch of them back to the httpd processes.
We have mod_perl's Apache::DBI start up a new connection to the database with each httpd child that's spawned.  We are concerned that these are not always getting closed out properly when the httpd's exit...and the httpd's are exiting very frequently.  I know that it would be good to modify the mod_perl applications to use some better form of db connection pooling; we plan to pursue that but would like to solve our immediate problem sooner.
So here's the main question.
We are using the prefork MPM.
The apache child processes are lasting at most a few minutes.  Log analysis shows that each one is serving fewer than 50 clients before exiting; the last request each child serves is OPTIONS * HTTP/1.0 on some sort of internal connection; I'm under the impression that this is a "ping" from the master process.
I've adjusted the MPM config as follows.  I didn't want to raise MinSpareServers too high, because, after all, i'm trying to minimize the number of sessions to oracle.
MinSpareServers       5
MaxSpareServers       30
MaxClients            150
MaxRequestsPerChild   10000

Right now we're serving 250-300 requests per minute.
We've got 21 httpd's running, the eldest (other than the master, owned by root) being 3 minutes old.
This rate of reaping of the apache children really seems excessive.  What could be causing it?
Apache was built with:
  $ ./configure --prefix=/opt/apache --with-ssl=/usr/lib --enable-expires --enable-ext-filter --enable-info --enable-mime-magic --enable-rewrite --enable-so --enable-speling --enable-ssl --enable-usertrack --enable-proxy --enable-headers --enable-log-forensic

Apache config info:
% /opt/apache/bin/httpd -V
Server version: Apache/2.2.22 (Unix)
Server built:   Jul 23 2012 22:30:13
Server's Module Magic Number: 20051115:30
Server loaded:  APR 1.4.5, APR-Util 1.4.1
Compiled using: APR 1.4.5, APR-Util 1.4.1
Architecture:   64-bit
Server MPM:     Prefork
  threaded:     no
    forked:     yes (variable process count)
Server compiled with....
 -D APACHE_MPM_DIR="server/mpm/prefork"
 -D APR_HAS_SENDFILE
 -D APR_HAS_MMAP
 -D APR_HAVE_IPV6 (IPv4-mapped addresses enabled)
 -D APR_USE_SYSVSEM_SERIALIZE
 -D APR_USE_PTHREAD_SERIALIZE
 -D SINGLE_LISTEN_UNSERIALIZED_ACCEPT
 -D APR_HAS_OTHER_CHILD
 -D AP_HAVE_RELIABLE_PIPED_LOGS
 -D DYNAMIC_MODULE_LIMIT=128
 -D HTTPD_ROOT="/opt/apache"
 -D SUEXEC_BIN="/opt/apache/bin/suexec"
 -D DEFAULT_PIDLOG="logs/httpd.pid"
 -D DEFAULT_SCOREBOARD="logs/apache_runtime_status"
 -D DEFAULT_LOCKFILE="logs/accept.lock"
 -D DEFAULT_ERRORLOG="logs/error_log"
 -D AP_TYPES_CONFIG_FILE="conf/mime.types"
 -D SERVER_CONFIG_FILE="conf/httpd.conf"

modules are compiled into apache rather than shared libs:
% /opt/apache/bin/httpd -l
Compiled in modules:
  core.c
  mod_authn_file.c
  mod_authn_default.c
  mod_authz_host.c
  mod_authz_groupfile.c
  mod_authz_user.c
  mod_authz_default.c
  mod_auth_basic.c
  mod_ext_filter.c
  mod_include.c
  mod_filter.c
  mod_log_config.c
  mod_log_forensic.c
  mod_env.c
  mod_mime_magic.c
  mod_expires.c
  mod_headers.c
  mod_usertrack.c
  mod_setenvif.c
  mod_version.c
  mod_proxy.c
  mod_proxy_connect.c
  mod_proxy_ftp.c
  mod_proxy_http.c
  mod_proxy_scgi.c
  mod_proxy_ajp.c
  mod_proxy_balancer.c
  mod_ssl.c
  prefork.c
  http_core.c
  mod_mime.c
  mod_status.c
  mod_autoindex.c
  mod_asis.c
  mod_info.c
  mod_cgi.c
  mod_negotiation.c
  mod_dir.c
  mod_actions.c
  mod_speling.c
  mod_userdir.c
  mod_alias.c
  mod_rewrite.c
  mod_so.c

One final note - the red hat httpd, apr, and perl packages are all installed, but ldd shows that none of those libraries are linked with the running httpd.

A: aaargh
the answer in this case turns out to be that i hadn't configured apache with those maxrequestsperchild, minspareservers, and maxspareservers options.
I modified a config file that I believed was Included in the primary file, but wasn't. New to this site, and crufty old config.  sigh.
So, the behavior I describe is the compiled-in default (i triple checked; it is not getting set anywhere else).  The documentation suggests that these are the compiled-in defaults:
http://httpd.apache.org/docs/2.2/mod/mpm_common.html#maxrequestsperchild
http://httpd.apache.org/docs/2.2/mod/prefork.html
MaxRequestsPerChild 10000
MaxSpareServers 10
MinSpareServers 5

I think the behavior I saw was not consistent with these defaults.  I'll file a bug with apache.
I guess this is still a useful question to leave on the site, because the default behavior doesn't match the documentation.  If others disagree I'll gladly close my question.


text:
Q: Is there a reason why a try-catch nested within a do-while loop not actually loop? I have a simple switch-case nested onto a do while loop. in my code, so the input for the switch case is through the user. So I have tried to have an InputMismatchException caught then the loop to continue {loop back again} yet it stops everything. How do I make it continue looping?
   public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Equation Solver");
        char ch;
        do
        {
            try{
            System.out.println("\nPlease choose\n");
            System.out.println("1. Suvat Equations");
            System.out.println("2. Energy Equations");
            System.out.println("3. The Doppler Effect Calculations");
            System.out.println("4. Gravitational Force Equation");
            System.out.println("5. Support");
            System.out.println("6. Graph");

            int choice = scan.nextInt();

            switch (choice)
            {
             case 1 :
                System.out.println("\nPlease choose according to the variable you want to find\n");
                System.out.println("1. Initial Velocity");
                System.out.println("2. Final Velocity");
                System.out.println("3. Acceleration");
                System.out.println("4. Distance Travelled");
                System.out.println("5. Time Taken");
                System.out.println("6. Otherwise Cancel");

                try{
                    int choiceCase1 = scan.nextInt();

                    switch(choiceCase1){
                        case 1 :
                            System.out.println("Please ");
                            Equation1();
                            break;
                        case 2 :
                            Equation1();
                            break;
                        case 3 :
                            Equation1();
                            break;
                        case 4 :
                            Equation1();
                            break;
                        case 5 :
                            Equation1();
                            break;
                        case 6 :
                            break;
                        default :
                            System.out.println("Wrong Entry \n ");
                            break;
                    }

                }catch (InputMismatchException e){
                        System.out.println("please stop");
                 }

            case 2 :
                Equation1();
                break;
            case 3 :
                System.out.println("Enter integer element to insert");

                break;
            case 4 :
                System.out.println("Enter integer element to insert");

                break;
            case 5 :

                break;
            case 6 :

                break;
            default :
                System.out.println("Wrong Entry \n ");
                break;
            }
            } catch (InputMismatchException s){
                System.out.println("Caught Exception")
            } finally{

            System.out.println("\nDo you want to continue (Type y or n) \n");
            ch = scan.next().charAt(0);
            }
        } while (ch == 'Y'|| ch == 'y');

        }

I expected for the user to be able to input y then repeat the loop yet does not allow it

A: From: https://www.tutorialspoint.com/java/java_break_statement.htm

When the break statement is encountered inside a loop, the loop is
  immediately terminated and the program control resumes at the next
  statement following the loop.

Your break statement at:
    } catch (InputMismatchException s){
        break;
    }

is ending the loop.
Edit: This try/catch statement is outside of the switch statement. So the break is not exiting the switch statement, it is exiting the loop.

A: It looks like when you catch the exception you break out of the Do-While loop.  I think you could probably remove that break command and it would do nothing with the exception but continue with the loop.  By having the break in there if you catch the exception it will terminate the loop.


text:
Q: how to assign arbitrary values to multiple variables My task is to code some functions to evaluate postfix, prefix and infix expressions. This is fine and dandy, and I've finished that portion of the task, however my problem arises when I take in the expression. If the user inputs a string lead by 'V', I have to assign the integers that come after 'V' to as many variables as needed. To try and be more clear, if the input was 'V 1 2 4 9', I would have to assign 1 to the letter A, 2 to the letter B, 4 to the letter C, and 9 to the letter D. I can do this if I assign each, variable by variable. But that is a long and arduous process, and I'm sure there's a better way to do it. The reason I need to assign the integer values to variables is because when the user wants to evaluate an expression, it has to be in the form '-+AB*CF', for example, if it was a prefix notation expression. Of course the form changes if the users wants infix or postfix, but the values to be evaluated are still in alphabet form, much like mathematics I guess.
My apologies if this question in unclear. Obviously this is homework, however I don't need code or people to do it for me, just some clarification about the best method would more than suffice. Thanks all.

A: Store the values in a dictionary instead:
import string

keys = string.ascii_uppercase
values = # make list of the values

variables = {keys[i]: val for i, val in enumerate(values)}

Now you can address the values in V 1 3 4 as variables['A'], variables['B'], etc.


text:
Q: Python compare 3 text files and append to the original I would like to build a relationship between multiple text files using python to combine into one.  You can see that the 3-5 character are the same in both text files.  I want to get the third and fourth column for matches and add to the end of file one.  These are comma delimeted text files.
FILE 1
03**005**001,NAME,573.641235,0

03**022**001,NAME,-4.740656,58

03**023**001,NAME,-750,32

03**024**001,NAME,-1.937901,51

03**025**001,NAME,-1.327531,0

FILE 2
01**005**001,Name,1,0

01**022**001,Name,0,7

01**023**001,Name,0,21

01**024**001,Name,0,12

01**025**001,Name,0,0

Output.txt
03**005**001,NAME,573.641235,0,1,0

03**022**001,NAME,-4.740656,58,0,7

A: Try this script:
# compare.py
oneDict = {}
twoDict = {}

with open("file1.txt", "r") as one:
    for line in one:
        cells = line.split(",")
        oneDict[cells[0][2:5]] = cells

with open("file2.txt", "r") as two:
    for line in two:
        cells = line.split(",")
        twoDict[cells[0][2:5]] = cells

for match in set(oneDict.keys()).intersection(set(twoDict.keys())):
    oneRow = oneDict[match]
    twoRow = twoDict[match]
    print(oneDict[match][0],
          oneDict[match][1],
          oneDict[match][2],
          oneDict[match][3][:-1],
          twoDict[match][2],
          twoDict[match][3][:-1],
          sep=",")

And this command:
python compare.py > output.txt


text:
Q: Compare two list - check if one list contains value of second I'm trying to compare one list of string (list1) with next list (list2) values (next list of string). I found plenty of solution with sequence ordering but in my case it does not matter.
My list of string will be for example:
List<string> myList1 = new List() {'123', '234','345'}

Right now I need to create a method which will take list "1" as a parameter and then loops (?) through the list "2" to check if values from list 1 are in the list 2
public bool IsValueInsideTheList(string[] orderNumbersToFindInTheList)
{
 //Here I suppose I need to do the looping with foreach/ for to check if value of list1 are in the list2
}

A: IEnumerable<string> list1;
IEnumerable<string> list2;

// ...
var containsMatches = list1.Any(item => list2.Contains(item));

I used IEnumerable<string> here because this will work for any lists of that type, not just a List<string> and a string[].

A: You can use LINQ to achive this:
var commonList = list1.Intersect(list2)

A: EDIT
I am not sure if this is what you wanted, but i will post anyways. This algorithm lets you compare the values from List 1 with the values AHEAD from List 2.
Example: List 1 Index 2 compared from List 2 Index 2 to the last value.
Even if this is not what you needed, i hope it helps someone.
using System;
using System.Collections.Generic;
using System.Linq;

namespace ListCompareItems
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> myList1 = new List<string>{ "123", "234", "345" };
            List<string> myList2 = new List<string> { "987", "123", "345", "112" };
            var comparisonLogic = (from item1 in myList1
                                  where (myList2.GetRange(
                                            myList1.IndexOf(item1),
                                            myList2.Count() - 1 - myList1.IndexOf(item1)).ToList().Contains(item1)
                                  )
                                  select item1).ToList();

            foreach (var output in comparisonLogic)
                Console.WriteLine(output);
        }
    }
}

Output:
123
345
Extras
You can edit this algorithm to return another answers.
If you want to know if there is at least one match, Count() the comparisonLogic. If it is greater than 0, there is a match.
You can return the Count() itself to know how many times there was a match.

A: You can also use Intersect...Any(might be more efficient than Any...Contains):
bool intersectsWith = list1.Intersect(list2).Any();


text:
Q: Resources mentioned in preload link headers are not pre-loading I'm trying to flatten some waterfalls for a web service. Currently, I'm seeing this ugly pattern:
document: WWWWWWWWDDDDD
resource:              WWWWWWWWWDDDDD
resource:              WWWWWWWWWDDDDD

W = Waiting (TTFB)
D = Content Download

To flatten this somewhat, I'm trying to get the sub-resources downloading sooner. To do this, I'm using the Link header and stuffing it with preload directives. Also, I'm flushing the headers before sending content. As I understood it, this should allow the preloads to be discovered in the first received chunk of bytes before waiting for the entire document to be downloaded. Sample Link header:
link: <https://some.domain.com/foo.min.js>; rel=preload; as=script; crossorigin,<//some.other.com/script.js>; rel=preload; as=script; crossorigin

I'm pretty sure the browser is seeing these links, because it complained before I had all those attributes correct, like crossorigin. However, the waterfall remains as before; none of the sub-resources that are set to be preloaded are downloaded until the entire document is downloaded. I'd expect something more like this:
document: WWWWWWWWDDDDD
resource:         WWWWWWWWWDDDDD
resource:         WWWWWWWWWDDDDD

What is causing the link header to be ignored by Chrome?


text:
Q: Rails 3 - Customizing resourceful routes I have resourceful routes set up for a blog (model name: Article).
I want to customize my resourceful route to point to
articles/show/title-of-my-article

Now I read through this:
http://edgeguides.rubyonrails.org/routing.html#customizing-resourceful-routes
But it didn't seem to explain how to overwrite the params not just the :controller or :action. The thing is I could do a singular resource or match a GET request but I'd like to overwrite my resourceful routes so I can still use all the resource helpers (i.e. article_path(@article.title) ) etc.
Can Anyone help me out here, any and all help is much appreciated!

A: You should override the to_param method on your model:
class Article
  def to_param
    self.title
  end
end

If you want to get a little bit trickier you should read up on generating custom slugs.

A: In addition to jonni's answer.
Overwriting the to_param method will produce the title when you call the resource helpers like article_path(@article) and it will be passed as the params[:id] to the controller.
Thereafter you will need to find the article more or less manually, i.e. instead of doing
Article.find(params[:id])

You will need to do
Article.find_by_title(params[:id])

I don't remember if that one creates a NotFound exception if the record is not found as the find method do so in that case you will have to check manually if a record was found and raise the exception yourself if it were not in order to trigger the 404-page.
One problem with doing this is that the title might consist of characters that is not allowed or recommended in a URL, so a better approach would be to store a slug based on the title in the database and find it by that.
(You can create the slug automatically by having a filter in the Model and create it by title.parameterize)
Easiest would of course be to use one of the many gems and plugins that already takes care of these things.


text:
Q: select only rows if its value in a particular column is more than 5 times its value in the other colum I have started to learn the the R very recently so forgive me if it's a novice question for someone. I want to extract the row from column "Bladder" which value is more than 5 times higher in compare to other column.
gene     Adrenal    Amygdala    Bladder BoneMarrow
1007_s_at   10.46973369 11.26483864 100.43303178    9.907426976
1053_at 6.446570421 6.462840464 6.570665594 7.068326351
117_at  8.018137441 7.738652705 7.604989675 8.38937883
121_at  10.78168853 10.3223056  10.38043102 10.73936285
1255_g_at   5.625038847 6.132930765 5.526885199 5.448521716
1294_at 8.37142904  8.1019947   8.549260758 8.697436419
1316_at 6.237386633 6.429011484 6.083330287 6.295933456
1320_at 6.206410651 6.139873183 6.328348899 6.251521738
1405_i_at   6.588370219 5.949622255 7.420451672 8.823058974

Expected result
gene     Adrenal    Amygdala    Bladder BoneMarrow
1007_s_at   10.46973369 11.26483864 100.43303178    9.907426976

I got this answer useful but I don't know how to apply for multiple columns
select only rows if its value in a particular column is less than its value in the other column
Thanks.

A: You want to perform a subset of your data based on your condition. Here, I assume your data is in a data frame named df:
df[df$Bladder > apply(5 * subset(df, select=-c(gene, Bladder)), 1, max),]

This will select the rows of df for which the Bladder column is more than 5 times the max of the other columns. We select all columns other than Bladder and gene using the subset command, and we compute the row-wise max using apply with the MARGIN set to 1 (i.e., the first margin or rows).
Using the updated data in your post, we get:
##       gene  Adrenal Amygdala  Bladder BoneMarrow
##1 1007_s_at 10.43303 11.26484 100.4697   9.907427

The data is:
df <- structure(list(gene = structure(1:9, .Label = c("1007_s_at",
"1053_at", "117_at", "121_at", "1255_g_at", "1294_at", "1316_at",
"1320_at", "1405_i_at"), class = "factor"), Adrenal = c(10.43303178,
6.446570421, 8.018137441, 10.78168853, 5.625038847, 8.37142904,
6.237386633, 6.206410651, 6.588370219), Amygdala = c(11.26483864,
6.462840464, 7.738652705, 10.3223056, 6.132930765, 8.1019947,
6.429011484, 6.139873183, 5.949622255), Bladder = c(100.46973369,
6.570665594, 7.604989675, 10.38043102, 5.526885199, 8.549260758,
6.083330287, 6.328348899, 7.420451672), BoneMarrow = c(9.907426976,
7.068326351, 8.38937883, 10.73936285, 5.448521716, 8.697436419,
6.295933456, 6.251521738, 8.823058974)), .Names = c("gene", "Adrenal",
"Amygdala", "Bladder", "BoneMarrow"), class = "data.frame", row.names = c(NA,
-9L))

A: This question was not asked terribly well, so my answer may not be quite what you are expecting, but I think what you're trying to get at is important and simple enough. My example makes use of the dplyer library which simplifies the filtering and selection of values from the data frame. Please note that I changed the value of BoneMarrow in the first row so that Bladder would be more than five times larger.
Most of the code is just to set up the example so that it is reproducible; the first and last lines are the actual answer to the question.
library(dplyr)

txt=
"gene,Adrenal,Amygdala,Bladder,BoneMarrow
1007_s_at,100.46973369,11.26483864,10.43303178,1.907426976
1053_at,6.446570421,6.462840464,6.570665594,7.068326351
117_at,8.018137441,7.738652705,7.604989675,8.38937883
121_at,10.78168853,10.3223056,10.38043102,10.73936285
1255_g_at,5.625038847,6.132930765,5.526885199,5.448521716
1294_at,8.37142904,8.1019947,8.549260758,8.697436419
1316_at,6.237386633,6.429011484,6.083330287,6.295933456
1320_at,6.206410651,6.139873183,6.328348899,6.251521738
1405_i_at,6.588370219,5.949622255,7.420451672,8.823058974"

df = read.table(textConnection(txt), header=TRUE, sep=',')

filter(df, Bladder >= BoneMarrow * 5) %>% select(Bladder)


text:
Q: Error #2007: Parameter child must be non-null. When Child is added within for loop I am having this error, not sure why it appears, i believe its something with scope problem. Because i have added Child already. I can't even remove Child, the child is added within the loop, and i am not sure how to manipulate the childs that were added within the loop from the outside(after the loop has ended).
I am trying to add the child from within the loop to a viewport, but i am demonstrating the problem with removeChild to reduce the complication. Because i am trying to locate the reason of why it is giving me this error, and trying to learn what i should do.
Thanks for your time!
for (var j:int = 5; j < somedata.length; j++)
                {
                    if(somedata[j]){
                    var myLoader:Loader = new Loader();
                    var image:Bitmap;
                    var url:URLRequest = new URLRequest("http://www.rentaid.info/rent/"+somedata[j]);
                    myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onImageLoaded);
                    myLoader.load(url);

                    function onImageLoaded(e:Event):void {
                    image = new Bitmap(e.target.content.bitmapData);

                    var mw:Number = bf.width*2;
                    var mh:Number = bf.height*1.2;
                        image.y = bf4.y+25;
          /* if you set width and height image same with the stage use this */
                    image.width = mw;
                    image.height = mh;
                    var _contentHolder: Sprite;
                    addChild(_contentHolder);
                    _contentHolder.addChild(image);
                    }
            }

                    removeChild(_contentHolder);
            }

Edit:
function LoadImages() : void {
    for (var j:int = 5; j < somedata.length; j++)  {
        var image:Bitmap;
        myLoader = new Loader;
        var urlRequest : URLRequest = new URLRequestfor ("http://www.rentaid.info/rent/"+somedata[j])
        myLoader.load(urlRequest);
        myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, LoadComplete);
    }

}

function LoadComplete(event : Event) {

            _contentHolder.addChild(image);
}

Or something like this?
var loadedArray:Array = new Array();
            var counter:int=0;

            function loadImage():void{

             var loader:Loader = new Loader();
                var image:Bitmap;
            loader.contentLoaderInfo.addEventListener(Event.COMPLETE,  onImageLoaded);
                loader.load(new URLRequest("http://www.rentaid.info/rent/"+somedata[counter]));

                function onImageLoaded(e:Event):void {
                image = new Bitmap(e.target.content.bitmapData);

                 loadedArray.push(e.target.content);

   if(counter == somedata.length-1){

       for(var i:uint = 5; i < somedata.length; i++){
           image[i].x = 0 + i * 100;

           addChild(_contentHolder);
            _contentHolder.addChild(image[i]);
                currentY += _contentHolder.height + 10;
       }
   }

   else{
       counter++;
       loadImage();

A: You don't define _contentHolder. You also do not, currently, addChild(_contentHolder). This will be why the removeChild line is throwing an error.
Also, you do not need to addChild(image) and then add image as a child of _contentHolder. One or the other will do. In fact a DisplayObject can only be in ONE place on the display 'tree'. If you want image as a child of _contentHolder only _contentHolder.addChild(image) is necessary.
If you want all of your image instances added to the SAME _contentHolder, it would be best to declare and instantiate _contentHolder OUTSIDE the for loop; Each foor loop iteration will then be adding your images to the same Sprite object. When you remove _contentHolder, the child images will also disappear (although they will still be children of _contentHolder).
Ideally, you should not have more than one Loader operating asynchronously, as you do in your for loop. Instead of using a for loop, create a variable to track which index value you are up to and, when each image loads, increment that value and use it to check if all images are loaded. If not, load the next. This will require the Loader section of your code to be in it's own function, which gets called initially AND from onImageLoaded, if another image needs to be loaded.
The variable that tracks which index you are up to will, likewise, need to be set initially and incremented when each image loads.
In response to your edited question:
Your first new example of code does not attempt to load the NEXT image once the current image is loaded. Also, just as a tip: Function names are not normally written starting with capital letters; This prevents confusion with Class definitions.
Also your first new example of code does not call the 'LoadImages' function to initially load the first image.
Your second example looks like it should work to me. Have you actually tried this version?
The only thing I'd suggest is defining your Loader with the other variables and removing the Event.COMPLETE listener in the 'loaded' function. When adding the event listener you could also add a:
loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgress);

listener and trace out the progress of each image.
I'd also recommend adding trace statements throughout you code to see where it's getting stuck.


text:
Q: grep specific number of consequtive lines that follow a pattern from a file Would it be posible to use awk to extract only
consecutive lines that contain "A 0", "A 1", "A 2", "A 3", "A 4" and "A 5"
from a file that has a structure as below:
..........................................................................
LINE  6295  A 0  LESS L6179     214.617 184.380  50.086  1.00  0.00      L
LINE  6296  A 1  LESS L6179     215.525 185.163  49.136  1.00  0.00      L
LINE  6297  A 2  LESS L6179     215.265 186.663  49.269  1.00  0.00      L
LINE  6298  A 3  LESS L6179     217.012 184.776  49.298  1.00  0.00      L
LINE  6299  A 4  LESS L6179     217.659 185.089  50.654  1.00  0.00      L
LINE  6300  A 5  LESS L6179     219.029 184.429  50.766  1.00  0.00      L
LINE  6316  A 0  LESS L6180     222.617 184.380  50.086  1.00  0.00      L
LINE  6317  A 1  LESS L6180     223.525 185.163  49.136  1.00  0.00      L
LINE  6320  A 4  LESS L6180     225.659 185.089  50.654  1.00  0.00      L
LINE  6344  A 0  LESS L6222     158.617 192.380  50.086  1.00  0.00      L
LINE  6345  A 1  LESS L6222     159.525 193.163  49.136  1.00  0.00      L
LINE  6346  A 2  LESS L6222     159.265 194.663  49.269  1.00  0.00      L
LINE  6347  A 3  LESS L6222     161.012 192.776  49.298  1.00  0.00      L
LINE  6348  A 4  LESS L6222     161.659 193.089  50.654  1.00  0.00      L
LINE  6349  A 5  LESS L6222     163.029 192.429  50.766  1.00  0.00      L
LINE  6367  A 2  LESS L6223     167.265 194.663  49.269  1.00  0.00      L
LINE  6368  A 3  LESS L6223     169.012 192.776  49.298  1.00  0.00      L
LINE  6369  A 4  LESS L6223     169.659 193.089  50.654  1.00  0.00      L
LINE  6370  A 5  LESS L6223     171.029 192.429  50.766  1.00  0.00      L
..........................................................................

Something that would provide an output of this type:
LINE  6295  A 0  LESS L6179     214.617 184.380  50.086  1.00  0.00      L
LINE  6296  A 1  LESS L6179     215.525 185.163  49.136  1.00  0.00      L
LINE  6297  A 2  LESS L6179     215.265 186.663  49.269  1.00  0.00      L
LINE  6298  A 3  LESS L6179     217.012 184.776  49.298  1.00  0.00      L
LINE  6299  A 4  LESS L6179     217.659 185.089  50.654  1.00  0.00      L
LINE  6300  A 5  LESS L6179     219.029 184.429  50.766  1.00  0.00      L
LINE  6344  A 0  LESS L6222     158.617 192.380  50.086  1.00  0.00      L
LINE  6345  A 1  LESS L6222     159.525 193.163  49.136  1.00  0.00      L
LINE  6346  A 2  LESS L6222     159.265 194.663  49.269  1.00  0.00      L
LINE  6347  A 3  LESS L6222     161.012 192.776  49.298  1.00  0.00      L
LINE  6348  A 4  LESS L6222     161.659 193.089  50.654  1.00  0.00      L
LINE  6349  A 5  LESS L6222     163.029 192.429  50.766  1.00  0.00      L

A: In awk, since you can look at specific columns, rather than a more general grep how about checking that column 3 is "A" and column 4 cycles from 0 to 5? That would be
awk 'BEGIN{seek=0} $3=="A" && $4==seek {print; seek +=1; if (seek>5) seek=0}' file.txt

A: awk '$3=="A" && $4==s {A[s]=$0; s++; if (s<6) next;}
      s==6 {for(i=0; i in A; i++) print A[i]; s=0; next;}
      {s=0}' input.txt

Output:
LINE  6295  A 0  LESS L6179     214.617 184.380  50.086  1.00  0.00      L
LINE  6296  A 1  LESS L6179     215.525 185.163  49.136  1.00  0.00      L
LINE  6297  A 2  LESS L6179     215.265 186.663  49.269  1.00  0.00      L
LINE  6298  A 3  LESS L6179     217.012 184.776  49.298  1.00  0.00      L
LINE  6299  A 4  LESS L6179     217.659 185.089  50.654  1.00  0.00      L
LINE  6300  A 5  LESS L6179     219.029 184.429  50.766  1.00  0.00      L
LINE  6344  A 0  LESS L6222     158.617 192.380  50.086  1.00  0.00      L
LINE  6345  A 1  LESS L6222     159.525 193.163  49.136  1.00  0.00      L
LINE  6346  A 2  LESS L6222     159.265 194.663  49.269  1.00  0.00      L
LINE  6347  A 3  LESS L6222     161.012 192.776  49.298  1.00  0.00      L
LINE  6348  A 4  LESS L6222     161.659 193.089  50.654  1.00  0.00      L
LINE  6349  A 5  LESS L6222     163.029 192.429  50.766  1.00  0.00      L


text:
Q: jquery remove removing from another element According to here, jquery's remove function should work like so..
$('div').remove('selector');

Which I'm trying in this example.
HTML:

This should be removed

This will remain

JavaScript:
jQuery(document).ready(function($) {
    $('div').remove('p.unwanted'); //not working
    //$('p.unwanted').remove(); //this works
});

It's not working. What am I doing wrong?

A: You've misunderstood what the documentation is saying. It's not looking for elements that are descendants of the matched elements that match the selector, it's simply filtering down the set of already matched elements to those that match the selector, and then removing them.
If you have this HTML:

Some text

Some more text

Some unwanted text

and then executed this jQuery:
$('div').remove('.unwanted');

then it would only remove that third
 (the one with the unwanted class on it), because it first selects all
 elements, and then only removes those that match the selector.
Example jsFiddle

A: You're trying to remove something that is both div and p.unwanted. The filter in remove() is applied to the current set of nodes, which in this case is all div elements.
Use the children set instead:
$('div').children().remove('p.unwanted');

A: You should use the following:
$('p').remove('.unwanted');

Argument in remove works as a filter. So here, you first select all
 elements and then remove only those which have class unwanted.
DEMO: http://jsfiddle.net/qwXSw/1/

A: try this
 $(document).ready(function() {
    $('div').find('p.unwanted').attr('class', '');
});


text:
Q: "no branch" on git submodule I'm working on a git project relying on a git submodule pointing to an outdated commit which is not usable for the main project. After successfully updating the master branch of this submodule to the commit I would like to use, grabbed from an external repository, I go back to the parent of the submodule, the main project, and issue git submodule update as I understood this is the correct way to make the parent know about the update. However, if I now move back to the submodule folder I see I'm on (no branch) which is still the branch of the old unusable commit. In the submodule I do see the updated master branch to version I would like to use. This leads me to think that I did not manage to correctly update the submodule to my preferred commit. Or should I not update the submodule from the main project?
Thank you!

A: It's a simple mistake:

After successfully updating the master branch of this submodule to the commit I would like to use, grabbed from an external repository, I go back to the parent of the submodule, the main project,

Good so far, but then:

and issue git submodule update

No: this yanks the submodule back to the recorded old snapshot.
What you want to do after getting the submodule into the desired state is go back into the superproject as you did, and then run:
git add path/to/submodule

This updates your index / staging-area, in the same way that git add copies a regular file into your index.
Eventually—when all files and submodule hashes are correct—you should then run git commit to make a new commit.  The new commit saves the new snapshot, which includes the new hash ID for the submodule to be in "no branch / detached HEAD" mode on whenever this commit is the one checked out.
Note that, unlike with regular files, checking out a commit doesn't put the submodule onto the correct commit; it's only git submodule update that does that.


text:
Q: mysql query with SELECT IN SELECT in more efficient way Please help me optimize query about getting reccomended (rec) for movies. I have many records and query run quite slow. The following query run for 2 mins
   SELECT rec.toMovieID, sum(rec.score)
   FROM rec
   WHERE movieID in
      (SELECT movieid as movieID FROM userFavorites as ufv WHERE ufv.userid = 29)
   GROUP BY rec.toAMovieID
   ORDER BY rec.score DESC
   LIMIT 10

Do you think I can optimize it more?

A: You can use an inner join instead of a subselect
SELECT
    rec.toMovieID,
    sum(rec.score)
FROM rec INNER JOIN userFavorites ON rec.movieID = userFavorites.movieid
WHERE
    userid = 29
GROUP BY rec.toAMovieID
ORDER BY rec.score DESC
LIMIT 10

You should set indexes on rows in where clause, at least for movieid and userid. (If not allready done)

A: You can use exists:
   SELECT rec.toMovieID, sum(rec.score)
   FROM rec r
   WHERE EXISTS (SELECT 1 FROM userFavorites as ufv WHERE ufv.userid = 29 and ufv.MovieId = r.MovieId)
   GROUP BY rec.toAMovieID
   ORDER BY rec.score DESC
   LIMIT 10;

You have to be careful using a join because of duplicate records.


text:
Q: Expo Updates Custom Server I have been trying to implement the custom server for expo updates as explained in this repo for my App
https://github.com/expo/custom-expo-updates-server
The expo-updates-server code I haven't touched, just changed the path in sripts/publish.sh and scripts/exportClientExpoConfig.js to point to my App rather than expo-updates-client
The issue which I am facing is that when my app is loading I am not sure whether or not its calling the server running at http://localhost:3000/api/manifest because its not logging any request in logs
Is there a way to debug this thing to be completely sure about whether or not this is the issue.
In my client app I have done the following things before making the release version of my App using eas build

*

*I have installed expo-updates in my client app

*Added runtimeVersion=1 in my app.json

*Also I have copied the updates block in my client app from expo-update-client app

I am attaching screenshots of my app.json file

Please note that my dist folder is successfully created and update is being copied in expo-updates-server/updates/1 folder
Has anyone implemented this before? Any Kind of help is appreciated
Thanks


text:
Q: Use java to render a jpg file I am trying to write a simple code to write a red 100x100 jpg
For some reason the colors are not right,
I am only setting the color RED :
renderdImg.setRGB(x, y, Color.RED.getRGB());

but the fnal image comes out purplish, what am I doing wrong?
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class ImageWriter {

    public static void main(String[] args) throws IOException {
     String fileName = "red_100.jpg";
     String filePath = "c:\\temp\\";
     int width = 100;
     int height = 100;
     BufferedImage renderdImg = new BufferedImage(width,height, BufferedImage.TYPE_INT_ARGB);
      for(int x=0;x< width; x++) {
          for(int y=0;y<height; y++) {
              renderdImg.setRGB(x, y, Color.RED.getRGB());
          }}
       File fileToWrite  = new File(filePath + fileName);
       ImageIO.write(renderdImg, "jpg", fileToWrite);
    }
}

A: Set the image type to BufferedImage.TYPE_INT_RGB and it should become reddish:
BufferedImage renderdImg = new BufferedImage(width,height, BufferedImage.TYPE_INT_RGB);


text:
Q: Cant seem to find the Syntax error Can somebody tell me what I am doing wrong here, I am getting incorrect syntax near where. Whats wrong with the statement?
INSERT INTO dbo.a1
    select x1 as id, x2 as enc_id, x3 as dev,x4 as mang, x4 as sre, x5 as phase,x6, x7, x8
    from
    (select *,
    row_number() over(partition by x2 order by x8)  as rank
    from ccsm.n9 where xx=1 and xx_pat=1 and xx_encz='Tesz')
     where rank=1;

A: You never told us what version of SQL you are using, but one possibility is that your derived table needs an alias:
INSERT INTO dbo.a1
SELECT t.x1, t.x2, t.x3, t.x4, t.x4, t.x5, t.x6, t.x7, t.x8
FROM
(
    SELECT *,
        ROW_NUMBER() OVER (PARTITION BY x2 ORDER BY x8) AS rank
    FROM ccsm.n9
    WHERE xx = 1 and xx_pat = 1 and xx_encz = 'Tesz'
) t
WHERE t.rank = 1;

I know that Oracle enforces the derived table alias rule, and possibly other databases as well.  Note that the aliases you had in the SELECT statement serve no purpose because the values are just being inserted.  If you wish to insert x4 twice then just repeat it twice.


text:
Q: How to find time complexity of an algorithm when given number of iterations and total time? I understand how to find the time complexity of an algorithm when I've been presented with an algorithm, but I can't seem to get my head around how to work it out when I've been given the number of times the algorithm is executed, and the time taken.
I can sometimes get it, when it's obvious things like O(n), O(n) or O(n^2) but take this question for example:
An algorithm runs a given input of size n.
If n is 4096 the run time is 512 milliseconds.
If n is 16384 the run time is 1024 milliseconds.
If n is 36864 the run time is 1536 milliseconds.
What is the time complexity?
I see that as n * 2, t * 1.5, but I'm not quite sure how to work it out.
Thank you for your help :)

A: I would say you need more than just three datapoints for this kind of question, because of complexities in the system rather than just the algorithm.
What I would do is compare the iterations and the elapsed time and see if you can find a pattern that matches one of the standard time complexities:

*

*Constant: O(c) where c is a constant.

*Linear: O(n)

*Polynomial: O(n^c) where c is a constant (or even something complicated like O(n^2 + n^6))

*Exponential: O(c^n) where c is a constant.

*Logarithmic: O(log|n|)

*Whatever this is called: O(n log|n| )

Let's go through your problem:
n     | time
4096  | 512 ms
16384 | 1024 ms
36864 | 1536 ms

When n goes up by a factor of 4 (from 4096 to 16384), the time goes up by a factor of 2 (from 512 to 1024 ms).
When n goes up by a factor of 9 (from 4096 to 36864), the time goes up by a factor of 3 (from 512 to 1536 ms).
A function that matches this is f(n) = n^(1/2). When n goes up by a factor of 4, f(n) goes up by a factor of sqrt(4), etc...
So this is of order O(n^.5), which is polynomial
TLDR: Graph it out and match it to a common function for time-complexity. In the real-world you would probably need more than three datapoints.
edit: I'd like to add that that this should really be more complex. There is likely a constant term in every kind of time complexity. I.e. O(n^c) is more likely O(n^c + K) where K is a constant. We ignore the constant for simplicity when writing this out, but it would show up in your graph.

A: If you're unsure of the actual algorithm, then you would create a line graph, n would be on the bottom of the graph, and y would be the time it took that number to execute.
If the slope of the line is 0, then it's O(1), if it's linear, then it's O(n), if it's curved, then it's either O(n^2), O(log n), or some other non-linear time complexity.

A: If the time complexity of an algorithm is n^x, then the quotient t_2 / t_1 for the times for inputs n_1 and n_2 is
(t_2 / t_1) = (n_2 / n_1)^x

and if you take logarithms, you get
log (t_2 / t_1) = x * log (n_2 / n_1)

and can solve for x:
x = log (t_2 / t_1) / log (n_2 / n_1)

In your examples, with n_1 = 4096 and t_1 = 512ms, you get the quotients
16384 / 4096 = 4        36864 / 4096 = 9
 1024 / 512  = 2         1536 / 512  = 3

so x = 1/2.
If the complexity doesn't follow a pure power law, you can estimate the power by evaluating a sufficiently large number of such quotients. If the complexity is actually exponential (or super-exponential), the quotients will grow linearly or super-linearly. The rate of growth can then be used to find the base for the exponential in the exponential case.


text:
Q: concept for c# web server for browser game client As an IT student, I have recieved the task of making a Connect Four game.
My task is to code a simple c# web server that listens to http requests so 2 players can play against eachother, one in the c#c form, one in the website.
But I'm confused on how such thing would work. We will have a web client that will just be the design of the game and will get it's behaviour and data out of the c# code. the c# server should use the httpListener, httpListenerrequest and the httpListenerContext classes.
I'm unsure on how to do such thing. any help would be appreciated on how to start this task, as I'm unclear to see to accomplish it.
greetings,
Durneztj

A: You will need six projects
1: winforms - connect 4 client
2: web application - connect 4 client
3: winforms - connect 4 server (for extra points make this a windows service or web api project)
4: class library - connect four game logic and models
5: test project for 4
6: class lib - client code for connecting to 3
do the class lib first. put all the models and game logic in here expose a single class with methods for starting a game, making a move and working out if someone won. make an interface for this class.
write tests in the test project to make sure you have the basic game logic right, you can start a game and make moves etc it all works
then move on to the server. this should refernce the class lib and just handle the http listening and response etc. you'll need to put your connection handling and deserializing of the model objects in here, but essentially you are just exposing the same methods as the class lib
now do six. reference the model class lib again and inherit the same interface, but this time instead of starting a game or making a move with teh game logic, you connect to the server and call its start and game, make a move etc. you will again have to deserialize the response into model objects.
now do 1 and 2. these will both be similar in that they will reference the models class lib and the client code lib. you will haev to present the board to the user differntly of course, but when they make a move, start a game etc you will just call the methods in your client class lib, the server will execute the logic and return the result
for extra points use async Task methods ON EVERYTHING
if it doesn't work, write integration tests for your server. these will save you hours of working out whether its the client or the server which is buggy
another extra point tip, use Microsoft unity framework for dependency injection


text:
Q: NameError: name 'BookAdmin' is not defined - Django I'm using Django and Python 3.6 I had this Error: NameError: name 'BookAdmin' is not defined and
this my code (models.py) in 'store' app.
from django.db import models
from django.utils import timezone

class Book(models.Model):
     title = models.CharField(max_length=200)
     author = models.CharField(max_length=200)
     description = models.TextField()
     publish_date = models.DateField(default=timezone.now)

and in admin.py
from django.contrib import admin

from .models import Book

class BookAdmin(admin.ModelAdmin):
    list_display = ('title', 'author')

    admin.site.register(Book, BookAdmin)

And the Error is
    File "C:\venv\lib\site-packages\django\__init__.py", line 27, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\venv\lib\site-packages\django\apps\registry.py", line 115, in populate
    app_config.ready()
  File "C:\venv\lib\site-packages\django\contrib\admin\apps.py", line 23, in ready
    self.module.autodiscover()
  File "C:\venv\lib\site-packages\django\contrib\admin\__init__.py", line 26, in autodiscover
    autodiscover_modules('admin', register_to=site)
  File "C:\venv\lib\site-packages\django\utils\module_loading.py", line 50, in autodiscover_modules
    import_module('%s.%s' % (app_config.name, module_to_search))
  File "C:\venv\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 978, in _gcd_import
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
  File "C:\venv\bookstore\store\admin.py", line 5, in <module>
    class BookAdmin(admin.ModelAdmin):
  File "C:\venv\bookstore\store\admin.py", line 8, in BookAdmin
    admin.site.register(Book, BookAdmin)
NameError: name 'BookAdmin' is not defined

A: class BookAdmin(admin.ModelAdmin):
    list_display = ('title', 'author')

admin.site.register(Book, BookAdmin)

Register your admin outside of your class definition. Not inside it!
Or do this:
@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
    list_display = ('title', 'author')


text:
Q: Ruby YouTube Data API v3 insert caption always returns error I am trying to use the Ruby SDK to upload videos to YouTube automatically.  Inserting a video, deleting a video, and setting the thumbnail for a video works fine, but for some reason trying to add captions results in an invalid metadata client error regardless of the parameters I use.
I wrote code based on the documentation and code samples in other languages (I can't find any examples of doing this in Ruby with the current gem).  I am using the google-apis-youtube_v3 gem, version 0.22.0.
Here is the relevant part of my code (assuming I have uploaded a video with id 'XYZ123'):
require 'googleauth'
require 'googleauth/stores/file_token_store'
require 'google-apis-youtube_v3'

def authorize [... auth code omitted ...] end

def get_service
  service = Google::Apis::YoutubeV3::YouTubeService.new
  service.key = API_KEY
  service.client_options.application_name = APPLICATION_NAME
  service.authorization = authorize
  service
end

body = {
  "snippet": {
    "videoId": 'XYZ123',
    "language": 'en',
    "name": 'English'
  }
}

s = get_service
s.insert_caption('snippet', body, upload_source: '/path/to/my-captions.vtt')

I have tried many different combinations, but the result is always the same:

Google::Apis::ClientError: invalidMetadata: The request contains invalid metadata values, which prevent the track from being created. Confirm that the request specifies valid values for the snippet.language, snippet.name, and snippet.videoId properties. The snippet.isDraft property can also be included, but it is not required. status_code: 400

It seems that there really is not much choice for the language and video ID values, and there is nothing remarkable about naming the captions as "English".  I am really at a loss as to what could be wrong with the values I am passing in.
Incidentally, I get exactly the same response even if I just pass in nil as the body.

A: I looked at the OVERVIEW.md file included with the google-apis-youtube_v3 gem, and it referred to the Google simple REST client Usage Guide, which in turn mentions that most object properties do not use camel case (which is what the underlying JSON representation uses).  Instead, in most cases properties must be sent using Ruby's "snake_case" convention.
Thus it turns out that the snippet should specify video_id and not videoId.
That seems to have let the request go through, so this resolves this issue.
The response I'm getting now has a status of "failed" and a failure reason of "processingFailed", but that may be the subject of another question if I can't figure it out.


text:
Q: How to change color of ListView Item in a ListFragment I would like to change the background color of each item in the ListView. I am using a ListFragment instead of a ListActivity so when I import the getView() method I get the following:
    @Override
public View getView() {
    // TODO Auto-generated method stub
    return super.getView();
}

So I cannot use the typical
view.setBackGroundColor(myColors[position]);

since the method does not have a position or view passed through it. Do I need to put those values into the method, remove the @Override and then call the method myself? If so where do I need to call it?
Can I accomplish this by setting up some type of listselector where the selector.xml file has a pressed state and an unpressed state that I can control in my java class?