text:
Q: Cross validation in CATBOOST Regressor: ValueError: Classification metrics can't handle a mix of binary and continuous targets I have a dataframe  which has no null values, and has only numerical values (I have done necessary transformations)
CATBOOST implementation
from catboost import CatBoostRegressor
from sklearn.model_selection import cross_val_score
CatBoost_clf=CatBoostRegressor()
CatBoost_clf.fit(X, y)
print('Train Accuracy',cross_val_score(CatBoost_clf, X_train, y_train,
    cv=3, scoring='accuracy'))
print('Test Accuracy',cross_val_score(CatBoost_clf, X_test, y_test, cv=3,
    scoring='accuracy'))

Error
> ----> 5 print('Accuracy:',cross_val_score(CatBoost_clf, X, y, cv=3, scoring='accuracy'))

> ValueError: Classification metrics can't handle a mix of binary and continuous targets

How to calculate cross validation accuracy (cv=3 or 3 iterations of validation sets) on CATBOOST?( output y has values 0 and 1 )

A: What you should use is CatBoostClassifier.
You are using CatBoostRegressor, which is designed to minimize the error based on continuous values (e.g., 0.43823). A classifier, for instance CatBoostClassifier, takes categorical input values(e.g., 0 or 1), which is what you have. In your example, the y is:
0    1
1    0
2    0
3    0
4    0
5    0
6    1

Which is definitely categorical, and not continuous.


text:
Q: Get currency exchange rate using bash I would like to display the current exchange rate from the currency euro to us dollar in the command line using bash shell script. I'm using the website market insider.
I saw on someone's blog to use wget command
wget -qO- https://markets.businessinsider.com/currencies/eur-usd

But how can I display only the rate? Desired output (example for current rate 1.1347) --> 1.1347 $
PS: I would prefer not to use API
Any help would be appreciated

A: Do this cleanly using their API:
#!/usr/bin/env bash

API='https://markets.businessinsider.com/ajax/'

ExchangeRate_GetConversionForCurrenciesNumbers() {
  isoCodeForeign=$1
  isoCodeLocal=$2
  amount=$3
  date=$4
  cacheFile="/tmp/$date-$amount-$isoCodeForeign-$isoCodeLocal.json"

  # Check if we have cached the result to avoid front-running the API
  if ! [ -e "$cacheFile" ]; then
    post_vars=(
      isoCodeForeign="$isoCodeForeign"
      isoCodeLocal="$isoCodeLocal"
      amount="$amount"
      date="$date"
    )
    method='ExchangeRate_GetConversionForCurrenciesNumbers'
    IFS='&' url="$API$method?${post_vars[*]}"
    curl -s -X POST "$url" > "$cacheFile"
  fi
  jq -r '.ConvertedAmountFourDigits' "$cacheFile"
}

getRateEURO_USToday() {
  ExchangeRate_GetConversionForCurrenciesNumbers EUR USD 1 "$(date '+%Y-%m-%d')"
}

# Set LC_NUMERIC=C because the float format returned is using . as decimal
LC_NUMERIC=C printf 'The exchange rate for EUR to USD today is: %.4f\n' \
"$(getRateEURO_USToday)"

redpajama_set_name: RedPajamaStackExchange


text:
Q: Trouble writing to csv file with scrapy spider I wrote a simple spider and get an error when I try to write data to csv file. The error I get it ERROR: Spider must return Request, BaseItem, dict or None, got 'str'
When I try to print my results, everything seems fine, I just don't know how to write it to csv. I used scrapy crawl mmadness -o file.csv but nothing besides that error happens. Csv file is created but it's empty.
The problem is I'm not really sure what should I do with last statement or how do I return "table_rows" correctly.
Thanks
# -*- coding: utf-8 -*-
import scrapy

class MmadnessSpider(scrapy.Spider):
    name = 'mmadness'
    allowed_domains = ['ncaa.com/standings/basketball-men/d1']
    start_urls = ['http://ncaa.com/standings/basketball-men/d1/']

    def parse(self, response):
        rows = response.css('tbody tr')
        for row in rows:
            table_rows = row.css('td::text').extract()
            print(table_rows)

A: print(table_rows)

you are printing your data while you should use :
yield(table_rows)


text:
Q: Validation of null against Regex I am trying to validate a String in Java to see if it matches the randomUUID format using the following regex
^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$

Now this works fine and picks up invalid strings and so on – however, if I pass a null String to the regex, it returns true, so when I perform validation on the Pattern annotation, no constraint violations are reported. Is this expected behaviour, since the String is null it is not performing any validation?
As a way around this, on the getter method that I have annotated with the Pattern annotation, I have used this
return id != null ? id : "null"

This works, however it seems a bit... hacky to me :)

A: If you want to exclude nulls, use a 'not null' annotation, such as @NotNull.

PatternValidator returns true if the argument is null (a weird choice, IMHO); it says so right in the source. I've seen different versions, and they all did this, so it's really part of the contract (and should be documented better).

public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
    if ( value == null ) {
        return true;
    }
    Matcher m = pattern.matcher( value );
    return m.matches();
}


text:
Q: Laravel 5.5 using different email setting other than ENV for sending email In laravel 5.5.4 i want a specific function to send mail via different mail setting other then mentioned in .env file.
I've tried searching but most of the places it's mentioned with swift which is now deprecated.

A: Before sending the email, simply call config()->set("mail.driver", $driver):
public function sendNonEnvEmail(){
  // If you want to log this email instead of sending it
  config()->set("mail.driver", "log");
  \Mail::send(...);
}

Now I'm not sure if you need to reset the email driver following this, but if that's the case, you can call do the following:
\Mail::send(...);
config()->set("mail.driver", env("MAIL_DRIVER", "smtp"));

That will reset the driver back to it's default value from the .env file, or smtp it's MAIL_DRIVER isn't set.
-- Edit --

Configuration values that are set at run-time are only set for the current request, and will not be carried over to subsequent requests.

So you don't need to reset it, but if you need to send more than one email in a request, it may become necessary, depending on the order of emails.


text:
Q: Can't open .mdb links in Adobe Reader Today I tried to open a database link (.mdb) in a pdf file, and I received this error message:

This has never happened before, so I began my research. I found out it was a security feature added by Adobe that would disallow users from opening internet links, eliminating the risk of acquiring a virus through embedded hyperlinks.
The only way I found to turn this feature off was to edit the policy settings in the registry.
I went to - HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Adobe\Acrobat Reader\DC\FeatureLockDown\cDefaultLaunchAttachmentPerms
I navigated to tBuiltInPermList and found the .mdb extension, changing the 3, to a 2.
Changing the 3 to a 2 allows .mdb files to be opened in Reader after prompting the user to make sure they really want to open the file.
Is there another way around this that anyone else has found? I find it odd that Adobe would blame system admins for this issue, when its totally not.


text:
Q: Avoid auto checked in other roles in role permission when i cheked the authenticate user role in drupal 7? I have create a role "Unapproved".
Purpose of this role is to stop some authenticate user to access some specific page, But the problem is when i select authenticate user, then unapproved role also automatically checked and Un-editable,
how can i checked and unchecked this role when authenticate user role activate?
sample of my problem


text:
Q: "at this stage" Vs. "in this stage" Going through a document for proof reading, I came across the phrase "In this stage, the model is put into operation" and was kind of confused. Mostly I had heard "At this stage ...", i.e. "at" instead of "in". I had a quick look over the net, and could find "In this stage ..." has been also used, however, I am doubtful about:

*

*This particular usage

*What is the proper use cases of these two phrases

A: The choice of preposition here is a subtle one. It's useful to look at the relevant definitions:

at (1)

*Expressing the time when an event takes place.

*

*'the children go to bed at nine o'clock'

*'his death came at a time when the movement was split'
[Oxford Dictionaries]

In this particular context, "at" identifies a specific moment in the process/timeline. Compare this with:

in (1)

*Expressing a period of time during which an event happens or a situation remains the case.

*

*'at one o'clock in the morning'

*'Nobody who is associated with the bank in that period can come out with any credit.'
[Oxford Dictionaries]

Thus, "in" is more general and, in the context of your sentence, covers anything that happened during that stage.
To some degree the choice of preposition is also influenced by the broader context. If the discussion is about the stage itself, then the action happens in (during) that stage. If the discussion is focused on the model itself, then you would describe at what point it's put into operation.

A: At this stage: While used in a conversation, specifying to the on-going window of time.
In this stage: While used in a conversation, specifying to a physical platform.
Depending on the context, use of the right preposition. If the explanation is about the model in specific, then use "in this stage'. If the explanation is about a certain process or system, use "at this stage".
EDIT: Blunder, Blunder...Shower and Thunder! |Typing error|


text:
Q: Dynamic initialization phase of static variables The standard specifically states that dynamic initialization of static duration variables (namespace scope and class static members) does not have to occur before main is executed:
 "It is implementation-defined whether or not the dynamic initialization (8.5, 9.4, 12.1, 12.6.1) of an object of namespace scope is done before the first statement of main." IS 3.6.2(3)
Is it not how dynamic initialization is [always?] implemented? What better/easier way to guarantee that the objects are initialized before use?

A: The answer to your question is in the next sentence (in 3.6.2 of ISO/IEC 14882-2003) after the one you've quoted.

It is implementation-defined whether
or not the dynamic initialization
(8.5, 9.4, 12.1, 12.6.1) of an object
of namespace scope is done before the
first statement of main. If the
initialization is deferred to some
point in time after the first
statement of main, it shall occur
before the first use of any function
or object defined in the same
translation unit as the object to be
initialized.

Obviously to make sure that some variable X is initialized you just have to use in function main (directly or indirectly) any function or variable defined in the same translation unit as the variable X (e.g. if you directly or indirectly use X in function main then you may be sure it is already initialized).
EDIT:
If in addition to the assurance that the variable you use is already initialized (it always is - as guaranteed by the standard text quoted above) you also want to know why standard contains the provision that initialization may be delayed after main execution start.
I mean if the question is also: Why not just demand that all initialization is performed before main starts?
Well it is definitely not about dynamically linked libraries - no problem to initialize all their objects before starting main. Also it is not about dynamically loaded libraries (LoadLibrary/dlopen) - they are not within a realm of C++ standard obviously (they are not subject to One Definition Rule for example and in general they may even be not C++).
In theory this provision allows lazy initialization to avoid unnecessary runtime overhead - e.g. unless you actually use some function or object from a specific translation unit (C++ source file) you don't have to do its runtime initialization. But it is unlikely that any implementation actually do lazy initialization in runtime - multi-threading synchronization is challenging for this kind of initialization and is itself a runtime overhead.
BUT what every single implementation actually do is linking only those modules (translation units) that are actually used. So even if you link with some static library that contain some dynamically initialized object (maybe with side effect - like file creation or user interaction) but don't use anything from the same translation unit - implementation is not obliged to run initialization of this object at all. So this provision allows avoiding inclusion of any unused translation units in final executable - even if they are formally part of the program.

A: I believe the intention here is to allow dynamic load libraries.
Static variables defined in the libraries are not guaranteed to be initialized before main, but must happen before anything in the specific library is used.

A: This isn't a direct answer, but it might be interesting for comparison's sake to go over how a similar language (Ada) handles this same situation.
In Ada packages (the rough equivalent to namespaces) can have data with initializations which effectively have the same lifetime as the program, much like Cish statics (for simplicity we will ignore generic packages, which like templates may be created in lower scopes). The process of doing these initializations is called "elaboration".
Ada guarantees that all packages will be elaborated at the start of the main routine. However, it is quite possible to create "elaboration" code that will not work if another package has not yet been elaborated yet. In general, the compiler gets to pick the elaboration order. So writing code that will not work unless the compiler happens to pick the order you need is considered a "Bounded Error".
Obviously this isn't ideal, as it is often desirable to use non-builtin data types in other packages, and sometimes this will include some with initializations that will need to be elaborated. So Ada provides some pragmas to allow you to ask the compiler to elaborate some or all of your dependencies before the current package.
It isn't perfect. It is quite possible to write code for which there really is no valid elaboration order. If you do this (or don't get the pragma's right and the compiler can't figure it out either), you get a Program_Error exception raised during elaboration. Some debuggers have trouble stepping through elaboration code, so these errors can be a major PITA to track down. Nonetheless, I really miss this facility in C++. It is the difference between being able to use complex objects in "static" declarations if you are careful, and having to avoid them altogether.

A: The dynamic initialization of static duration variables (namespace scope and class static members) ALWAYS occurs before main is executed.
The order in which these static duration variables get initialized is not defined.


text:
Q: Jest unit test "Cannot find control with unspecified name attribute" I'm doing some simple components for my "dynamic-ish" automated form creator and I've just made a component for dropdown:
<div>
  <select [name]="propertyName" [formControl]="customControl" [id]="propertyName">
    <option *ngFor="let option of options" [value]="option.id">
      {{ option.label }}
    </option>
  </select>
</div>

Code is also bare simple:
export class DropdownComponent {
  @Input() public customControl: AbstractControl;
  @Input() public propertyName: string;
  @Input() public options: any[];
}

Now when I run jest to test this component (which test is created by ng cli, so default, I only added ReactiveFormsModule as an import) it fails with the component creation.
  × should create (363 ms)

  ● DropdownComponent › should create

    Cannot find control with unspecified name attribute
      at _throwError (../packages/forms/src/directives/shared.ts:150:9)
      at setUpControl (../packages/forms/src/directives/shared.ts:37:19)
      at ...

Versions:
Angular: 10.1.6
Jest: 26.6.3
Angular CLI: 10.1.7
Node: 14.4.0
OS: win32 x64

A: Since google gave me 10 results (all misleading or impossible), I tried adding/removing parts of the code, came out that customControl needs to be initialized with a value despite it will receive a formcontrol from the outside (as being @Input). This is not a problem with <input> tags but is a problem with <select> tags!
  @Input() public customControl: AbstractControl = new FormControl('');


text:
Q: How to resize structure array in C# struct UurroosterKlasStruct
{
   public int Vak;
   public int Lkr;
}
UurroosterKlasStruct[,] UurroosterKlas;`

I need to resize this array later on, but the array.resize function does not seem to work.. I want to change the array to [10,10]. can anyone one put me on my way?

A: Array's can not be resized once a size is specified. They are fixed at the point you give their size. If you want something dynamic try using something like a List or Dictionary. You would have to create a new array and of larger size and copy existing data into it.
So your code could be like:
struct UurroosterKlasStruct
{
   public int Vak;
   public int Lkr;
}
UurroosterKlasStruct[,] UurroosterKlas;`
UurroosterKlas = new UurroosterKlasStruct[10,10];


text:
Q: Generating sequential ID using MySQL I need to generate a barcode reference for each order received. The first barcode is 200000 and increases by 1 for each subsequent order.  I have to be absolutely certain that I don't assign the same barcode to more than one order.  The project receives lots of orders and often many in very quick succession.
To overcome this issue I have created a MySQL database table called barcodes with an auto increment primary key. The ID of the first row is 200000.
Each time I need to generate a barcode I do an insert into the barcodes table and then use PHP's mysqli_insert_id() to get the ID inserted. I then update the orders table so the barcode is set to this value.
This works well and prevents me from being able to assign the same barcode to more than one order.
Is there a better way? Ideally I would have one table where I store the next available ID and then run two queries:
select next_barcode from barcodes where id=1

And then
update barcodes set next_barcode=next_barcode+1 where id=1

My concern here is that my code could call the function that performs the SELECT at exactly the same time (i.e. before the UPDATE) has run and two orders are given the same barcode.
Perhaps there is some reliable table locking approach? Or maybe my current approach is the best way to go?

A: As far as concerns, auto_increment, which you are currently using, is the best way to go for your use case. Uniqueness is guaranteed by design, and the database does the heavy lifting for your under the hood.
The only possible downside is that you might experience gaps in the ids - for example when an insert fails for some reason, a sequence id might be lost, and the following insert will increment the id again, leading to a gap in the sequence.
If that's a problem for you, then one option is to use the insert ... select syntax to get the latest id and the new id in a single query when inserting, like:
insert into barcodes (id, ...)
select coalesce(max(id), 0) + 1, ...
from barcodes

This prevents two rows from getting the same id. But again, I would not recommend that; using auto_increment is more efficient, and simpler.

A: What you're doing is pretty good. You will guaranteed not get the same id twice.
If you're inventing your own system for this, you will need to lock many tables, destroying concurrency or do everything via transactions. It's definitely possible to accomplish what you're doing with transactions, but the best way to go about this would probably mostly replicated what AUTO_INCREMENT already does.. it's just harder.
One thing to keep in mind that in some circumstances MySQL might skip an id in AUTO_INCREMENT, but you'll guaranteed never get the same number twice.


text:
Q: How to find out what Property's a trigger accepts In XAML we can perform the following trigger
<ControlTemplate.Triggers>
        <Trigger Property="IsSelected" Value="True">
        <Trigger.Setters>
            <Setter Property="Opacity" Value="1.0" />
        </Trigger.Setters>
        </Trigger>
</ControlTemplate.Triggers>

My question is how does some one know what property it accepts. How could I know if it accepts MouseOver or OnMouseOver (without testing every combination).
So, in case the above is too broad,  if you wanted to know what triggers were accepted for the LIstBoxItem, how would you find out?


text:
Q: Adobe Air: draw vector graphics Does Air supports SVG and if it not possible is there another way to event sensitive graphics draw via JavaScript.

A: But I found a way to draw vector graphics, using flash, over the html
air.Shape = window.runtime.flash.display.Shape;
this.shape = new air.Shape();
this.shape = new air.Shape();
this.shape.graphics.lineStyle(1,0);
this.shape.graphics.drawCircle(0,0,200);
this.shape.graphics.endFill();
window.nativeWindow.stage.addChild(this.shape);

A: Adobe Air has an embedded WebKit which partially supports SVG 1.1 As an alternative rendering engine in Adobe Air application you can use Flash, which is much based on vector graphics.


text:
Q: How can I findout what's my MSSQL server collation? Is there a SQL I can execute to find out?

A: The server default collation:
select serverproperty('collation')

Which is the same as
select databasepropertyex('master','collation')

Check SERVERPROPERTY in Books Online for other information you can get about the server (instance).

A: SELECT DATABASEPROPERTYEX('AdventureWorks', 'Collation') SQLCollation;

Just substitute your DB name for 'AdventureWorks'. Or use DB_NAME:
SELECT DATABASEPROPERTYEX(DB_NAME(), 'Collation') SQLCollation;

A: This is the official doc given by MS, hope it helps.
http://msdn.microsoft.com/en-us/library/hh230914.aspx#TsqlProcedure


text:
Q: KDE Plasma Colors are not changing correctly I installed KDE Plasma Version 5.12.9 on Linux Mint 19.3
It's working fine excpet the colors
After a few problems with themes I managed to get them working, but not all colors are correct.
The System Settings Windows is a QT5 window themed
but some colors like the text in this window is not reading the correct color
In this Image you can see the Window Text set to White, but in the System Settings Window next to it the Text on the Window is black


text:
Q: How to use the Ruby "self" keyword I'm having trouble understanding the self keyword.
I understand how it's used to distinguish between instance methods and class methods but what about when it's used from inside a method?
Something like:
def self.name
  self.name = "TEXT"
end

or
def name2
  self.name = "TEXT2"
end

or
class Array
  def iterate!(&code)
    self.each_with_index do |n, i|
      self[i] = code.call(n)
    end
  end
end

A: Usually, self as a receiver can be omitted, and in such cases, it is usually preferable to do so. However, there are a few cases when omitting self make the code mean something else.

*

*One such case is, as in your example self.name = ..., using a setter method. Ruby's syntax is ambiguous between method and variable call, and when  something that can be interpreted either as a variable or a method is followed by =, its interpretation as a local variable assignment has priority.

*Another case is when you want to call the method class. There is also the keyword class, and interpretation of class as the keyword has priority over it as the method.

*Still another case is when you want to use the method []. This notation is also used for array literal, and interpretation of it as an array has priority over it as a method.
In each of these cases, you have to make the expression be unamgiguously a method call. One way is to explicitly write the receiver even when it is self. The other way is to write () after the method.
Regarding your example self.each_with_index ..., the self can be omitted, and not doing so is not a recommended practice.

A: self has absolutely nothing whatsoever to do with the difference between instance methods and class methods. In fact, there isn't even a difference between them, because Ruby doesn't have class methods. Ruby only has instance methods.
self in Ruby is exactly the same as self (or sometimes called this) in every other object-oriented language: it is a reference to the current object. That's all it is. It literally is just a pointer to "myself".

A: self actually defines your scope in Ruby. The scope keeps changing when you switch from module to class, class to method and so on....

A: Class method (because self references to the class):
class MyClass
  def self.myMethod
    "hello"
  end
end

MyClass.myMethod

Whereas a method without self is an instance method:
class MyClass
  def myMethod
    "hello"
  end
end

c = MyClass.new
c.hello

For variables, it also is a scope thing. If your class has an accessor, you access it with self. Not using self would usually mean that you want to access a local variable from your method's scope (assuming no magic is given).
class MyClass
  attr_accessor :var

  def myMethod
    self.var # => "hello"
    var # => undefined
  end
end


text:
Q: Marketing Cloud - duplicate primary key on event data update I have set up a Data Extension that contains my custom data for Accounts, with a field 'ContactID' that is set as a primary key and mapped to SubscriberKey. I have then created a Journey Builder Event that maps to this DataExtension.
When the Account data changes on the back-end I do a POST /events API call to Marketing Cloud. e.g.
ContactKey='myself@example.com', body={"ContactId": "myself@example.com", "AccountStatus": "account_pending"}

The first time this works fine, but the second time I post an event on the same Account e.g.
ContactKey='myself@example.com', body={"ContactId": "myself@example.com", "AccountStatus": "account_ready"}

I get the error:

"The event data contains duplicate value for an existing primary key"

How can I work around this error to get a second event triggered on the same Account?

A: The solution we came up with was simply to remove the primary key constraint. This doesnt seem to cause any adverse effects.


text:
Q: Water in the bunker problem We have a bunker(Like a Cylinder), full of water with height $H$ initially, there is a whole at the bottom of the bunker. The pressure of the air outside is $P_0$. The surface of the bunker is $A$ and the surface of the whole is $a$. I want to calculate the decrease rate of the height of water in the bunker, with respect to time.
I tried using Bernoulli's theorem, but my answer is wrong. This is my attempt:
$P+\dfrac{1}{2}\rho v^2+\rho gh = const$
For the top section of the bunker I wrote:
$\dfrac{1}{2}\rho v^2+\rho gh+P_0$
And for the hole in the bottom:($n$ is the speed of the water going out of the hole)
$\dfrac{1}{2}\rho n^2+\rho g\times(0)+P_0=\dfrac{1}{2}\rho n^2+P_0$
So: $n^2=v^2+2gh$
Since: $n \times a = v \times A$, (I'm not sure about this part) so:
$gh=n^2-v^2=v^2 \times \dfrac{A^2-a^2}{a^2}$
I take the derivatives with respect to time:($w$ is the acceleration)
$gv = 2v \times w \times \dfrac{A^2-a^2}{a^2} => w = g \times \dfrac{a^2}{A^2-a^2}$
$\therefore v(t) = wt = gt \times \dfrac{a^2}{A^2-a^2}$

A: If you consider the hole to be very small ,i.e. $A>>a$
Then you can simply conclude:
$$-\frac{dy}{dt}=\sqrt{2gy}$$ where $y$ is the height of water calculated from the base.
And further simply solve$$-\int_H^0\frac{dy}{\sqrt{y}}=\sqrt{2g}\int_0^t dt$$


text:
Q: Jhipster deploy frontend separate from backend Hi I want to deploy the jhipster frontend separated , can I do it ? or the correct way is to put it back in the same project with the backend.I can't find info on how to deploy it after been separated

A: Yes you can do it separately, you just need a web server to serve your frontend bundle and if you want to avoid CORS issues you should also configure it as a reverse proxy to your backend.
The web server could also be a CDN.
The reason why you don't find any JHipster doc on this is that it's not specific to JHipster.


text:
Q: Excel 2007 Stacked Column Chart Display Subvalues So I have the following set of values in my excel sheet:

The values on the first column (very low, low, medium, high) are simply socio-economic layer indicators.
As you can see, everything is pretty simple here. I want to make a stacked column chart out of these, displaying the totals not as another layer but as mere totals. To do this, I apply the 'hack' found here
Which leaves me with this:

So far so good. What I don't know how to do though is break down the yellow area, the 'did not wish pregnancy' category, in other words, I want to add, within it's yellow area, which represents the 100%, the entirety of the value itself, relatively speaking, a subvalue, which in this case is called 'interrupted pregnancy'. To make matters clear, this is how our excel tables would look with the added column of values, which I highlighted:

So, with this in mind... I'm lost as to how to show a portion of that yellow area, without modifying the value of yellow, blue or even the totals, with the tiny percentage that represents 'interrupted pregnancy'.
This is HOW the chart SHOULD look if I knew how to do it:

All help is greatly appreciated. For the record, I'm using excel 2007

A: This may call for a stacked clustered column chart, where the value for "interrupted pregnancy" can be shown as a separate bar besides the stacked bars. The technique and its application without code is explained in detail on Jon Peltier's page.
http://peltiertech.com/WordPress/clustered-stacked-column-bar-charts/
The technique involves laying out your data in a specific way and "fudging" (technical term!) the chart settings to display the final result.
He also offers a paid tool to automate the creation of such charts.

A: Do you want to show the subvalues as 2.09% and 20.91%? Then you need a column that calculates the difference between "didn't wish pregnancy" and "interrupted pregnancy", and just stack them. Use two shades of the same color to indicate they are related.
If you want to show "didn't wish pregnancy" as 23.00% as well as the 2.09% for "interrupted pregnancy", then the clustered-stacked approach mentioned by Teylyn might help show it. The left stack would show the categories, while the right stack would show subcategories.


text:
Q: Load shared memory in C So I'm making a Load.c file, that basically will load a bunch of "students" into shared memory.
The students are stored in a struct that looks like this:
struct StudentInfo{
char fName[20];
char lName[20];
char telNumber[15];
char whoModified[10];
};

Anyway, I need to load this in shared memory.  We were given some sample code and we are reading the code from a data file that will look like this:
John Blakeman

111223333

560 Southbrook Dr. Lexington,  KY 40522

8591112222

Paul S Blair

111223344

3197 Trinity Rd. Lexington,  KY 40533

etc....

Here's my idea for the code: (header.h just has struct info/ and semaphore count....I'm unsure of what it needs to be, right now it's labeled as 5)
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include "header.h"

main()
{
    int i,id;
    struct StudentInfo *infoptr;
    int sema_set;

    id = shmget(KEY, SEGSIZE,IPC_CREAT|0666); /* get shared memory to store data */
    if (id < 0){
        perror("create: shmget failed");
        exit(1);
}

    infoptr=(struct StudentInfo *)shmat(id,0,0); /* attach the shared memory segment to the process's address space */

    if(infoptr <= (struct StudentInfo *) (0)) {
        perror("create: semget failed");
        exit(2);
    }

/* store data in shared memory segment */
//here's where I need help

That's about as far as I got. now I know I can store data using strcpy(infoptr->fName,"Joe"); (for example)
but I need to read an X number of names? How would I go about storing them? Using some sort of push/pop vector of structs? how would it look like?
And do I adjust semaphores based on how many "entries" there are I assume? I'm a little bit confused how to adjust my number of semaphores.
Oh BTW here's my header file just in case (SSN's are fake obviously)
/* header.h */
#define KEY ((key_t)(10101)) /* Change to Last 5 digits of SSN */
#define SEGSIZE sizeof(struct StudentInfo)

#define NUM_SEMAPHS 5
#define SEMA_KEY ((key_t) (1010)) /* Last 4 digits of SSN */

struct StudentInfo{
char fName[20];
char lName[20];
char telNumber[15];
char whoModified[10];
};

void Wait(int semaph, int n);
void Signal(int semaph, int n);
int GetSemaphs(key_t k, int n);

A: Uhm... I'm not sure here, but this is what I understood:
You're loading struct StudentInfo blocks into a shared memory space, and you want to be able to access it from other processes?
First, consider that your structure is fixed-size. If you want to read 10 names, you need to get sizeof(struct StudentInfo) * 10 bytes, if you want 400, make that * 400 -- so you don't need to push and pop your students from any kind of queue, since you can just use math to calculate from where and up to where you need to read. Getting students 10 to 20 is just reading the shared memory space from sizeof(struct StudentInfo) * 10 to sizeof(struct StudentInfo) * 10
As for mutual exclusion (if you're going to have multiple readers or writers, which I assume is what you wanted the semaphores for), I do not recommend semaphores. They are adequate for simpler kinds of exclusion, like "don't use this function if I'm using it", but not for locking large sets of data.
I'd use file locking. In Unix, you can use file locking primitives to create advisory locks over specific bytes in a file, even if the file is 0-bytes-long. What does this mean?
Advisory means you don't enforce them, other processes must respect them willingly. 0-byte-long means you can open a file that doesn't exist, and lock portions of it corresponding to your student structure positions in shared memory. You don't need the file to actually have data, you can use it to represent your shared memory database without writing anything to it.
What's the advantage of this over semaphores? You have fine-grained control of your locks with a single file descriptor!
Wheh, that got long. Hope I helped.


text:
Q: Relation between girth and induced subgraph In the book, Introduction to Graph Theory by Douglas West, section 1.3.10 has an example on Petersen Graph. There is a statement in the example which states "Since G has girth 5, every 6 cycle F is an induced subgraph". I have understood that girth of Petersen graph is 5, and that it has ten 6 cycles... but have not understood the sentence in bold and italics.In the book, I could not find any relation between girth and sub-graph.  I would request for some easy explanation.

A: Take any $6$-cycle in the Petersen graph with vertices $v_1, v_2, \dots, v_6$. Aside from the six edges $(v_1, v_2), (v_2, v_3), \dots, (v_6,v_1)$ forming the cycle, no other edges $(v_i, v_j)$ can be present, because then they'd form two cycles, at least one of which would be shorter than $5$.
(For example, if the edge $(v_4, v_6)$ were present, then we'd get a $5$-cycle formed by $v_1, v_2, v_3, v_4, v_6$, which is possible, and a $3$ cycle formed by $v_4, v_5, v_6$, which is not possible. This is directly related to girth: the Petersen graph has girth $5$, meaning it contains no cycles shorter than $5$-cycles.)
In other words, if we take the subgraph of the Petersen graph induced by the vertices $\{v_1, v_2, \dots, v_6\}$, that subgraph must be isomorphic to $C_6$, because it contains no edges other than the ones that form the cycle.


text:
Q: Return to the previous activity preventing come back the the initial activity I'm trying to implement a common behavior (I think).
I have 2 activities:
LoginActivity and MainActity.
The MainActiviy contains a menu with 3 fragments to navigate through them: RequestFragment, DetailFragment and VisualizationFragment.
But, I have one issues that I have not solved yet:
The first one, if the flow is similar to:
LoginActivity -> MainActivity -> RequestFragment -> DetailFragment
And also, you can navigate
LoginActivity -> MainActivity -> VisualizationFragment
But once, you are logged, remove the LoginActivity from the flow, just now I'm using:
LoginActivity
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_login);
   //...some extra code...

   intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
//..start the activity

}

Ok, that is working ok, but in my MainActivity I have the issue:
MainActivity
@Override
    public void onBackPressed() {
        if (getFragmentManager().getBackStackEntryCount() > 0) {
            getFragmentManager().popBackStack();
        } else {
            super.onBackPressed();
        }
    }

Taking in consideration that I have a menu in my MainActivity replacing that one for my fragment, how I can navigate through my application closing the app (as is natural) when the MainActivity is open and come back to the previous when a Fragment is displayed?
Just now, my code is not doing anything with the navigation through the fragments, it's taking all as the MainActivity is open without taking in consideration the fragments

A: Use backpressed code like below. I showed alert box if it meets the last fragment.
@Override
    public void onBackPressed() {
        if (getFragmentManager().getBackStackEntryCount() > 0) {
            showAlertDialog(Constants.EXIT_APP, Constants.APP_NAME);
        } else {
            getFragmentManager().popBackStackImmediate();
        }
    }

//add this method to navigate. Write in a common java file
public void showFragment(Fragment fragment, String back_stack_name, boolean save_back) {
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        transaction.replace(R.id.container, fragment);
        if(save_back) {
            transaction.addToBackStack(back_stack_name);
        }
        transaction.commit();
    }

//call this method wherever u need for fragment by:
Classname obj = new Classname();
showFragment(obj,"FRAGMENT_NAME_IN_STRING",true);

Note: If you want to add the fragment to backstack, set 3rd parameter as true otherwise set false.
As like Intent for calling a class, showFragment is used for calling a fragment.


text:
Q: How can I use HTMLHelpCtrl.ocx ActiveX control on a x64 platform Actually we are running a x86 Windows Desktop C++ Qt application with HTMLHelpCtrl.ocx ActiveX control (all modules x86) in order to call the .chm HtmlHelp of the application.
Now we want to port our application to x64. Unfortunately it is not possible to use the current x86 HTMLHelpCtrl.ocx directly. Is there a 64 bit version of HMTLHelpCtrl.ocx available? Or what is needed to be able to use the x86 ActiveX control in x64?
We already tried to do it this way: Using a 32-bit COM Object from a 64-bit Application. But this is not an option, because we have the requirement to make it work without administrative rights. Therefore we cannot change the registry values mentioned in the article.

A: The solution is rather simple: you need to perform the steps that you refer to in your installer. That's where you will have the administrative rights needed, and that's where such things are meant to be handled.
If you can't, then you need to split your application into two processes: one that is 32 bit, and another that is 64 bit. Host the 32 bit object in the 32 bit process, and run the stuff that needs large memory in the 64 bit process.


text:
Q: Pinch to zoom with CCParallaxNode How do I implement pinch to zoom to a parallax scrolling node?

A: Here's the solution:
- (void)handlePitchZoom:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch* touch1 = [[[event allTouches] allObjects] objectAtIndex:0];
    UITouch* touch2 = [[[event allTouches] allObjects] objectAtIndex:1];

    // calculate scale value
    double prevDistance = ccpDistance([touch1 previousLocationInView:[touch1 view]], [touch2 previousLocationInView:[touch2 view]]);
    double newDistance  = ccpDistance([touch1 locationInView:[touch1 view]], [touch2 locationInView:[touch2 view]]);

    CGFloat relation = newDistance / prevDistance;
    CGFloat newScale = self.scale * relation;

    if ((newScale >= minScale) && (newScale <= maxScale)) {

        CGPoint touch1Location = [parallaxNode convertTouchToNodeSpace:touch1];
        CGPoint touch2Location = [parallaxNode convertTouchToNodeSpace:touch2];

        // calculate center point between two touches
        CGPoint centerPoint = ccpMidpoint(touch1Location, touch2Location);

        // store center point location (ScrollableView space)
        CGPoint centerPointInParentNodeSpace = [self convertPoint:centerPoint fromNode:parallaxNode];
        CGPoint oldPoint = ccp(centerPointInParentNodeSpace.x * (self.scale), centerPointInParentNodeSpace.y * (self.scale));
        self.scale = newScale;

        CGPoint newPoint = ccp(centerPointInParentNodeSpace.x * (self.scale), centerPointInParentNodeSpace.y * (self.scale));
        CGPoint diff = ccp(oldPoint.x - newPoint.x , oldPoint.y - newPoint.y);

        [parallaxNode setPosition:ccp(parallaxNode.position.x + (diff.x*(1/self.scale)), parallaxNode.position.y + (diff.y*(1/self.scale)))];
    }

Hope it will help someone...


text:
Q: UL is not the height it should be I have a nav that includes a drop down.

Nav 1

Nav 2

Nav 3

DropDown 1

DropDown 2

DropDown 3

I wish to add spacing below the nav, so I use margin-bottom.
But the margin is not correct, it's like the UL is not it's full height, I fix this with:
overflow: hidden

But then the hidden drop down gets cut off.
Any ideas on a fix?

A: You can try using padding. That will allow you some extra room around each element.


text:
Q: Numpy array subtraction creates a matrix with different dimension. How to correct that? I am attempting to create a simply neuronetwork using Python (I know there are libraries, but I'm building a simple one from scratch to get more familiar with each step taken), and one part of it is to calculate the difference between the true label and the predicted label.
I have the true label in dim <2059 x 1>, and the predicted label also in <2059 x 1>
Both are in np.array
I would expect a simple
l2_error=tag_train-l2

would do the job. (l2 is the predicted label, tag_train is the true label)
but what I got in return is a <2059x2059> matrix. It seems like this operation is doing a subtraction of every possible combination of elements. Why would this happen? I know I can probably run a for loop to get the job done, for I'm wondering why the program would produce this result?
Both dtypes are float64, btw. I don't think it matters, but just in case this info is needed.

A: As you indicated in the comments, what is happening is that tag_train is a one dimensional array with length 2059 , whereas l2 is supposedly a 2 dimensional array with 2059 rows and 1 column.
So when you try to do subtraction it leads to a 2 dimensional array with 2059 rows and 2059 columns.
If you are 100% sure that l2 would only be one column then you can reshape that array to make it one dimensional before doing the subtraction. Like -
l2.reshape((l2.shape[0],))

Example/Demo -
In [1]: import numpy as np

In [2]: l1 = np.array([1,2,3,4])

In [3]: l2 = np.array([[5],[6],[7],[8]])

In [7]: l2.shape
Out[7]: (4, 1)

In [8]: l2-l1
Out[8]:
array([[4, 3, 2, 1],                 #Just to show that you get the behaviour when arrays are in
       [5, 4, 3, 2],                 #different dimensions.
       [6, 5, 4, 3],
       [7, 6, 5, 4]])

In [19]: l2 = l2.reshape((l2.shape[0],))

In [25]: l2 = l2.reshape((l2.shape[0],))

In [26]: l2-l1
Out[26]: array([4, 4, 4, 4])


text:
Q: Outputcache and 410 status response not working I would like to throw a 410 status code for a page that does some database lookups.  However it seems that outputcache only caches 200 status code pages. Is there anyway around this? I want to cache 410 pages for a while so the database doesn't get it, but it just skips the cache and hits the database again.
[OutputCache(Duration = 3600, VaryByParam = "eventid,teamid,v,r")]
    public virtual ActionResult Team(int? teamId, int? eventId)
    {

A: OutputCache and almost all HTTP level caches are designed to ignore failed responses, anything other more than 399, all status code above 399 are error codes.
You can manually set Response Headers like
context.Response.Headers.CacheControl = "public, max-age=3600"

This is what OutputCache does internally, however, OutputCache might also provide server level cache if setup.
But if you use CDN, I doubt they will respect cache control in case of failed response status codes.
But it is not recommended. Lets say for some reason user deletes the cookies or cookie gets corrupted. And user receives 410 error. And user goes back to login and logs in correctly, and now for same request user will continue to receive 410 for one hour.
Or otherwise let's say your database is unavailable and database throws 410 error, so even with valid cookie or valid authorization, user will receive cached error response. Caching layer doesn't know when not to cache.
Instead, you can use MemoryCache, to cache error results in your memory for couple of seconds without going to database each time. Though the results will still hit the web servers.
CloudFlare and Azure provides web application firewall, which allows intelligently blocking errornous traffic if you are worried about DDOS kind of attacks. This approach seems better than using HTTP Cache, as you will have no control over user's cache. And you can't programmatically clear cache after successful login.


text:
Q: how to redirect certain url to port using .htaccess I am trying to redirect url as  abc.xyz.org to 192.168.xx.yy:abcd using htaccess.
tried using following in htaccess.
RewriteRule ^(.*)$ 192.168.xx.yy:abcd [P,R=301,L]

but this rule isn't taking the port number.What should I do?
i tried
RewriteRule ^(.*)$ 192.168.xx.yy:abcd[b] [P,R=301,L]

A: Try this
RewriteEngine on
RewriteRule ^(.*)$ http://192.168.0.1:1234/$1 [R=301,L]

A: RewriteRule ^(.*)$ http://192.168.xx.yy:abcd [P,R=301,L]

Your using [P] flag. Make sure mod_proxy is enabled. In this doc it says Note: mod_proxy must be enabled in order to use this flag. To enable mod_proxy give command
sudo a2enmod proxy

Then restart apache
If you can not enable mod_proxy [P] flag is of no use. Then your rewrite rule will be
RewriteRule ^(.*)$ http://192.168.xx.yy:abcd [R=301,L]

A: RewriteEngine On

RewriteRule ^(.*)$ index.php$1 [R=301, L]


text:
Q: Create table to count visits per hour I need to count hoy many visits have an application when my customers create an account and show there info, so my customers can see how many visits they have
I have created a table to store integers but Im not sure if this is the right choice
CREATE TABLE tbHit(
intHit INT IDENTITY(1,1) NOT NULL,
intClient INT,
intYear INT,
intMonth INT,
intDay INT,
hr00 INT,
hr01 INT,
hr02 INT,
hr03 INT,
hr04 INT,
hr05 INT,
hr06 INT,
hr07 INT,
hr08 INT,
hr09 INT,
hr10 INT,
hr11 INT,
hr12 INT,
hr13 INT,
hr14 INT,
hr15 INT,
hr16 INT,
hr17 INT,
hr18 INT,
hr19 INT,
hr20 INT,
hr21 INT,
hr22 INT,
hr23 INT
)

Should I store all visits in the same table or shoul I create another table or another way to have all this hits?

A: Every time they visit you should insert a row into a table like this:
create table hits (id1 identity,
customer_id  int,
visited_on datetime)

There are date and time functions that will allow you to slice and dice hits in any angle you want(By day, hour, day of week) if you store it this way.

A: Use computed columns and split to date and time to simplify query at future
CREATE TABLE tbHit ( intHit    INT IDENTITY(1,1) NOT NULL
,                    intClient INT
,                    enter_date as convert(varchar(10),getdate(),113)
,                    enter_time as convert(varchar(10),getdate(),108) )


text:
Q: Blackout text for an art project I want to make an interactive blackout poem for a class. This is a blackout poem btw, and I can see when I inspect the element they have a {. blackout editor style. Is this something I can borrow?
I have been through the basic tutorials on W3 Schools for HTML and CSS text and link styling and I can't find anything that works the way I want it to.
I want to use a standard text and for each word to "blackout" when the user clicks on it and the end result be that the user is just able to see the non-blacked out words onscreen.
Any ideas? TIA, I'm very new to coding.

A: The Example:
Here
are
some
words
for
a
poem

In action: https://jsfiddle.net/kylemartin/f16okqsq/
Granted, my example doesn't have a mechanism to un-do the blackout, but that's just as easy as checking the background color of the span and if it's black, then make it not black.
I think this does what you're looking for.  If not, let me know and I can improve it.  It's a little bit ugly, but it achieves the goal.
What this code does:
What we do is we put all the words into their own s.  We need this so that each word is its own clickable "unit".  Then we create our Javascript click handler that listens for any click on one of the s.  When someone clicks on one of the s, we change the background color of that  to black.  I just added the CSS for good measure.  By the way, the CSS


text:
Q: Failing to pass a very long string as parameter in an ajax call to an asp.net controller In my api controller, I need to pass two parameters: an integer + a string. This string is a json variable so it's a very long string, I can't pass as part of the URL.
I tried passing it as POST parameter (in the data attribute of the ajax call), but I get an error: only the first parameter is read, so the URL passed is not the right one.
How should I do this?
EDIT
JS code:
    function SavingFloor(FloorId, Json) {
        $.ajax({
            beforeSend: function (xhr) {
                xhr.setRequestHeader('verifySession', verifySession());
                xhr.setRequestHeader('Authorization', '@HttpContext.Current.Session["BaseAuth"]');
            },
            url: "/api/Floor/SaveFloor?FloorID=" + FloorId, //api: error in decoding json (the json can't be passed as parameter)
            type: "POST",
            data: {
                jsonstring: Json
            },
            dataType: 'text/html',
            success: function (data) {
                alert('success');
            }
        });
    }

Controller:
    [HttpPost]
    public void SaveFloor(int floorID, string jsonstring)
    {
        Floor floor = db.FloorSet.Find(floorID);
        JavaScriptSerializer ser = new JavaScriptSerializer();
        Dictionary<string, object> dict = ser.Deserialize<Dictionary<string, object>>(jsonstring);
        floor.SavedJson = jsonstring;
        floorRepository.Update(floor);
        floorRepository.Save();
    }

A: You could try adding [FromUri] and [FromBody] attributes to the SaveFloor method. You can send floorID in regular GET and send the long jsonstring as the POST body. Currently, Web API can only read a single parameter from a POST body. You either need to encapsulate both variables in a single object, or try this:
public void SaveFloor([FromUri]int floorID, string jsonstring)

You don't need to specify [FromBody] to jsonstring as it's the default one in a POST request.
After this, don't forget to change your client-side code to send the floorID in the query string too.


text:
Q: lower level heading tags before top level heading tags? Best practice? What is the best practice if you need to do a lower level heading in your web page before a top level heading?
In your DOM, h1 should always be before h2, then h3, etc... right? But what if you need to do some kind of h2 tag at the top of your document before the h1? Is this bad practice? I'm thinking about building for accessibility.


text:
Q: Reading # of vowels from String in java there. I need some assistance. I'm working on having the user input text, reverse the text, then read the number of vowels in the text and tell them how many vowels were in the reversed text.
public static void main(String[] args)
{
 System.out.println ("Please type in whatever you want ");
 Scanner type_input = new Scanner (System.in);
 Scanner type_input = new Scanner (System.in);
 StringBuilder type_output = new StringBuilder();
 type_output.append(type_hold);
 type_output=type_output.reverse();
 System.out.println("Is this what you types in? " + type_output);

 for(int vowel_num = 0; vowel_num< type_hold.length(); vowel_num++)
    {
        if((type_hold.charAt(vowel_num) =='a')||(type_hold.charAt(vowel_num) =='e')||
            (type_hold.charAt(vowel_num) =='o')||(type_hold.charAt(vowel_num) =='i')||
            (type_hold.charAt(vowel_num) =='u')){

        System.out.println("There are " + vowel_num + " vowels in " + type_hold);
    }

But when I get it to typing in to running it i get the following. I'm not sure where I'm messing up.
run:
Please type in whatever you want
hello
Is this what you types in? olleh
There are 1 vowels in hello
There are 4 vowels in hello

Edit: I figured it out. Thank you to everyone for the help!

A: *

*What is type_hold? Didn't see you instantiate it, and you are using it.

*What vowel_num? The index you are looping through the string? or the number of vowels you have counted?

What you should have done to count vowels in a string:
Assuming index is the index of the string we are currently scanning, vowel_count is the count of vowels you have encountered.
int vowel_count = 0;
for(int index = 0; index < type_hold.length(); index++) {
    if((type_hold.charAt(index) =='a') ||
       (type_hold.charAt(index) =='e') ||
       (type_hold.charAt(index) =='o') ||
       (type_hold.charAt(index) =='i') ||
       (type_hold.charAt(index) =='u')){

         // character at vowel_index is a vowel.
         // you have encountered 1 more vowel!
         System.out.println("Character at " + index + " is a vowel.");
         vowel_count ++;
     }
}

System.out.println("There are " + vowel_count + " vowels in " + type_hold);

A: Java 8 streams can be used on the character array inside the String.
StringBuilder type_hold = new StringBuilder();
long vowel_num = type_hold.toString().toLowerCase().chars()
        .filter(it -> "aeiou".indexOf(it) != -1).count();

A: Modified your code a bit; take a look;
public static void main(String[] args)
{
  System.out.println ("Please type in whatever you want ");
  Scanner type_input = new Scanner (System.in);
  Scanner type_input = new Scanner (System.in);
  StringBuilder type_output = new StringBuilder();
  type_output.append(type_hold);
  type_output=type_output.reverse();
  System.out.println("Is this what you types in? " + type_output);

  int count=0;
  for(int vowel_num = 0; vowel_num< type_hold.length(); vowel_num++)
  {
    if((type_hold.charAt(vowel_num) =='a') ||(type_hold.charAt(vowel_num) =='e')||
        (type_hold.charAt(vowel_num) =='o')||(type_hold.charAt(vowel_num) =='i')||
        (type_hold.charAt(vowel_num) =='u')){

    //System.out.println("There are " + vowel_num + " vowels in " + type_hold);                      Instead of this

    count++;
   }

System.out.println("There are " + count + " vowels in " + type_hold);
}

This should done your work.


text:
Q: Usage of "Who" and "whom" in the given sentence In the given sentence,"There's Mr. Som, who they say is the best singer in the country" is "who" is the correct word to be used or "whom"

A: Geoffrey Pullum has given this question his full consideration on Language Log.
Here's his conclusion:

It's the neatest case I know of in which a dispute about what's
  correct turns out to have no possible resolution, because there are
  two perfectly defensible rules that have slightly different
  consequences, and the evidence from literature says that different
  writers make different choices of rule.

A: Use the he/him method to decide which word is correct.
he = who
him = whom

Who/Whom wrote the letter?

He wrote the letter. Therefore, who is correct.

For who/whom should I vote?

Should I vote for him? Therefore, whom is correct.

We all know who/whom pulled that prank.

This sentence contains two clauses:
We all know and who/whom pulled that prank.
We are interested in the second clause because it contains the who/whom. He pulled that prank. Therefore, who is correct. (Are you starting to sound like a hooting owl yet?)

We want to know on who/whom the prank was pulled.

This sentence contains two clauses:
We want to know and the prank was pulled on who/whom.
Again, we are interested in the second clause because it contains the who/whom.
The prank was pulled on him.
Therefore, whom is correct.
Now...
Consider the following sentence:

Who do you consider the best composer?

Should it be who or whom?
Figure it out by turning the sentence around and replacing the who or whom with he or him. If he is wrong, so is who. If him is wrong, so is whom.
Do you consider him the best composer?
*Do you consider he the best composer?
Since him is correct, use whom. Whom do you consider the best composer?

It was Corelli, you'll find, who composed that piece.

Turning the sentence around, which is correct?
He composed that piece.
*Him composed that piece.
Since he is correct, use who in the sentence.


text:
Q: RLC band stop vs. RC low pass filter for switching noise in DC-DC converter I'm working with a DC-DC switching IC that has a fixed switching frequency of 10kHz. I'd like to filter out that switching noise. The load is just an instrumentation amplifier, so the peak current will be under 1mA at ±30V.
Given that I know where the majority noise is likely to be on the frequency spectrum, and that I'll be including the usual decoupling capacitors anyway, are there any benefits in adding an RLC or RC filter to the power path? If so, is there a benefit to using one type over the other, assuming that the series resistance I select is roughly the same (say 3Ω) in both cases? For example, I can see that for similar attenuation at the same fc the capacitor is smaller for the RLC filter, so that'd be a potential cost saving if it weren't for the added inductor.

A: The are differences in the time response for the two filters which makes one of them unsuitable for this application. To exemplify, consider the two transfer functions:
$$\begin{align}
H_{LP}(s)&=\dfrac{3}{s^2+3s+3}\tag{1} \\
H_{BS}(s)&=\dfrac{s^2+9}{s^2+s+9}\tag{2}
\end{align}$$
The notch (2) has infinite attenuation at 3 rad/s, whereas the lowpass only ~0.277:

The first impression would be that the notch is superior to the lowpass when a certain bandwidth is to be attenuated. But this is frequency domain, and the power supply is considered in the time domain due to the dynamic nature of the load: there's always some variation. Which means that the time domain response is to be considered (left step, right impulse):

Note I have left aside the implicit Dirac that comes out for the impulse response of the notch filter, due to the lowpass + highpass. You certainly don't want a differentiator in the path of your supply. Most of the noise may come only from a certain range, the switching frequency, but it's not the only source, and a differentiator will amplify high frequencies. So the frequency domain is only a small part of the whole aspect.
This is why I would recommend the lowpass. Use the bandpass if you have to analyze the signal, not to filter a power supply.


text:
Q: groovy how to test for environment existence inside config.groovy best practice for testing for existence in tree structure?  For example testing for environment existence within a config file.  Current working example below.  Tried .hasProperty but couldn't get right object reference with in a tree structure like config.
def config = new ConfigSlurper(myenvironment).parse(new File('cfg.groovy').toURL())
def results = config.admin.server
 try {
    assert results.size != 0
    } catch...

cfg.groovy
environments {
    dev01 {
        admin {
            server = 'http://'
            port = '1'
        }
    }
    test {
        admin {
            server = 'http://'
            port = '1'
        }
    }
}

A: I don't know if there is a better way to do so, but you can check if the generated config object for the passed environment is empty:
def environments = '''
environments {
    dev01 {
        admin {
            server = 'http://'
            port = '1'
        }
    }
    test {
        admin {
            server = 'http://'
            port = '1'
        }
    }
}
'''

def noExists = new ConfigSlurper('noExistEnv').parse(environments)
assert !noExists.isEmpty()

Since noExistEnv doesn't exists this execution shows:
Assertion failed:

assert !noExists.isEmpty()
       ||        |
       |[:]      true
       false

Trying with an existent environment all works correctly:
def environments = '''
environments {
    dev01 {
        admin {
            server = 'http://'
            port = '1'
        }
    }
    test {
        admin {
            server = 'http://'
            port = '1'
        }
    }
}
'''

def testCfg = new ConfigSlurper('test').parse(environments)
def result = testCfg.admin.server
// check that string is not empty
assert !result.isEmpty()
println result // prints "http://"

Hope it helps,


text:
Q: Protractor Not able to click the element While iterating the list of Elements clickClaimIDFromList(claimId) {
   element.all(by.xpath('//*[@data-qa="dashboard.claim"]')).then(async (items) => {
            // console.log(items[0].getText());
            await expect(items[0].getText()).to.eventually.equal('12345');

            items.forEach(item => {
                     item.getText().then(async (text) => {
                            if (text === '12345') {
                                await console.log(item.getText());
                                await this.wait(10000);
                                return item.click();
                            }
                        }
                    );
                }
            );
        }

     );

}

This code is getting executed successfully with out clicking the element. Could some one help me to rewrite it?

A: As you are using async/await keywords I am assuming your have the control flow disabled in your framework (by setting SELENIUM_PROMISE_MANAGER: false in conf.js).
If that is the case there is no need to be using so many .then's as await provides a much easier way to handle them.
Your test could be passing because it is hitting the failing the text === '12345' check in your if and therefore never attempting to click.
//Make function async
async clickClaimIDFromList(claimId) {

  let allElems = await element.all(by.xpath('//*[@data-qa="dashboard.claim"]'));

  //don't await expects, await what is occuring inside them if you need to
  expect(await allElems[0].getText()).to.eventually.equal('12345');

  for (let i = 0; i < allElems.length; i++) {
    let item = allElems[i];

    //Save the result of the getText to a variable
    let itemText = await item.getText();
    console.log(itemText);

    if (itemText === '12345') {
      await this.wait(10000);

      //No need to return the click, we can await it here
      await item.click();
    } else {
      console.log('else is being hit');
  }
}

Note: I have not tested this code but the logic should be correct

A: Executable code:
async clickClaimIDFromList() {
    const allElems = await element.all(by.xpath('//*[@data-qa="dashboard.claim"]'));

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

        // Save the result of the getText to a variable
        const itemText = await item.getText();
        console.log(itemText);

        if (itemText === '123124214') {
            await this.wait(10000);

            // No need to return the click, we can await it here
            await item.click();
        } else {
            console.log('else is being hit');
        }

    }
}


text:
Q: Pip could not find a version that satisfies the requirement I'm having problems with installing a package using pip. I tried :
pip install jurigged

Causing these errors :
    ERROR: Could not find a version that satisfies the requirement jurigged (from versions: none)
    ERROR: No matching distribution found for jurigged

I checked if pip was up to date which was the case. I'm on Python 3.7.4.
Does anyone know a solution to this problem?

A: 1 - You had installed python3 but your python in /usr/bin/python may be still the older version so run the following command to fix it
python3 -m pip install <pkg>

2 - The other possible reason could be initial forgot the -r: Use pip install -r requirements.txt the -r is essential for the command.
3 - If still not working, there is one way to fix this error. try this but first, get the version of ur package
python3 -m pip install --pre --upgrade PACKAGE==VERSION.VERSION.VERSION

4 - You know sometimes the package already exists then also we get this error,so try to check if u are able to import or not.
5 - Try pipwin instead of pip sometimes if the problem is with pip this works as a magic
6 - Don't forget to turn on your internet, strange but happens sometimes.
lemme know if the problem persists. But as per my guess, it should work now. Best of luck !!!

A: From PyPI, jurigged is only supported as of Python >= 3.8 (see also here)
pip doesn't find anything to install because you do not meet the requirements.
Upgrade to Python >= 3.8 and do the same: pip install jurigged

A: You can solve this problem by typing
 pip install pandas --trusted-host pypi.org --trusted-host files.pythonhosted.org

to cmd
AND
If you want to fix this setting, in window, make file %HOME%\pip\pip.ini and add code below to the file,
    [global]trusted-host = pypi.org
                           files.pythonhosted.org


text:
Q: Difference between year 2018 and date 2018-01-01 I have a table responsible for storing dates. I want to be able to input there 2018-01-01 which represents month (January) and I want to store there 2018 which represents year. Is this possible?

A: you would have to use an integer datatype for date column that store year.
 insert into #tbltest1 values(datepart(year, getdate() ))


text:
Q: got error in authenticating a login from Discord When i made a loging with discord button via discord own site [https://discordjs.guide/oauth2/#implicit-grant-flow][1]
The Code I copied from here works well and I did not got any code stuck but when I tried login to app via my second discord to check then all the authorization worked but in console I got error at the .style.display
it gives error: Code.js:47 Uncaught TypeError: Cannot read properties of null (reading 'style')  the code is copied from official site so i was not expecting error.
[1]: https://discordjs.guide/oauth2/#implicit-grant-flow
I was expecting the string including user name etc from the memebrs authorization but i didnot got.   The code is:
Identify Yourself

I got error at:   return (document.getElementById('login').style.display = 'block');


text:
Q: Zend Framework 2, vhosts and MAMP I think I've configured all files properly, but when I access the url: myapp.local, it points to the MAMP/htdocs/ directory instead of /MAMP/htdocs/ZendSkeletonApplication-master/public/ (going to this public directory displays correctly de zf2 example webpage), here is my configuration:
httpd-vhosts.conf
<VirtualHost *:8888>
    ServerName myapp.local
    DocumentRoot "/Applications/MAMP/htdocs/ZendSkeletonApplication-master/public/"
    <Directory "/Applications/MAMP/htdocs/ZendSkeletonApplication-master/public/">
        DirectoryIndex index.php
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

hosts
127.0.0.1 myapp.local

Can someone tell me what I'm doing wrong? I want my base url to point at the /Applications/MAMP/htdocs/ZendSkeletonApplication-master/public/ directory, not at htdocs.
Similar question here, but I can't get the answer. Vhost Zend Framework configuration MAMP - redirected to the index page of the server
Thanks

A: Just try this in the httpd.conf file (where you must have enabled to include the httpd-vhosts.conf file) -
<VirtualHost myapp.local>
    DocumentRoot "/Applications/MAMP/htdocs/ZendSkeletonApplication-master/public/"
</VirtualHost>

There should be no need to enable the httpd-vhosts.conf file.


text:
Q: Highcharts - How can I decrease space between categories?
I need to reduce that space, ... How can I do it?
"Planificación", "prioridad" and "gerencia" are categories, the numbers inside are series by person.

A: To do this pointPadding and pointWidth are what you want.
Try this.
The important bits are:
plotOptions: {
            series: {
                stacking: 'normal',
                pointWidth: 50,
                pointPadding: 0
            }
        },


text:
Q: How to upload image to postgreSQL database using ember and RESTful api I have an ember app to list the details about alumni using django rest framework and postgreSQL. I need to upload image(stored in the my storage) along with other details. How can I achieve this in ember?
Can I do it by converting to base64 from ember and storing the encoded string? If possible, how?

A: you can use this module for this image-base64

A: I was able to upload the image to PostgreSQL by using base64 encoding. I used the ember-image-drop addon to convert the image to base64 code.
I used these codes in my add route(Note that I am using pod-structure):
template.hbs
<form {{action "submitAlumni" on="submit"}} class="alumniForm">
    <div>{{image-drop image=selectedImage placeholder="Image" helpText="Drop your image here, or click to select"}}</div>
    <button class="btn btn-primary" {{action "submitAlumni"}}>Submit</button>
</form>

route.js
import Route from '@ember/routing/route';

export default Route.extend({
});

controller.js
import Controller from '@ember/controller';
import { set } from '@ember/object';

export default Controller.extend({
    image: null,

    actions: {
        submitAlumni() {
            let image = this.get('selectedImage');
            var onFail = function(response) {
                alert(response);
            };
            const alumni = this.get('store').createRecord('alumni', {
                image: image,
            });
            alumni.save().then(() => {
                this.transitionToRoute('alumnis.show', alumni.id)
            }, onFail);
        },
    }
});


text:
Q: rails 6 form validation errors even when criteria is met I am trying to add form validation to a simple blog post form.  Currently I am testing for presence of title and description and if I submit an empty form it gives me the errors, but if I fill out the form it still gives me the errors.  When I use byebug in my create action for the post_controller it shows the contents of the title and description that I enter but says permitted false.
Here is the form partial:
<%= form_with(model: post, local: true) do |f| %>
  <% if post.errors.any? %>

          <%= pluralize(post.errors.count, "error") %>
          occured:

            <% post.errors.full_messages.each do |message| %>

<%= message %>

            <% end %>

  <% end %>

    <%= f.label :title %>
    <%= f.text_field :title, class: 'form-control' %>

    <%= f.label :description %>
    <%= f.text_area :description, class: 'form-control' %>

    <%= f.label :header_image %>
    <%= f.file_field :header_image %>

    <% if post.header_image.present? %>
      Current Image
      <%= image_tag(post.header_image, width: '100%') %>
    <% end %>

    <%= f.submit class: 'btn btn-primary mt-1 form-control' %>

<% end %>

Here is the post_controller:
module Authors

  class PostsController < AuthorsController
    before_action :set_post, only: [:edit, :update, :destroy]

    # GET /posts
    def index
      @posts = current_author.posts
    end

    # GET /posts/new
    def new
      @post = current_author.posts.build
    end

    # GET /posts/1/edit
    def edit
      @element = @post.elements.build
    end

    # POST /posts
    def create
      @post = current_author.posts.build

      if @post.save
        redirect_to edit_post_path(@post), notice: 'Post was successfully created.'
      else
        render :new
      end
    end

    # PATCH/PUT /posts/1
    def update
      if @post.update(post_params)
        redirect_to edit_post_path(@post), notice: 'Post was successfully updated.'
      else
        render :edit
      end
    end

    # DELETE /posts/1
    def destroy
      @post.destroy
      redirect_to posts_url, notice: 'Post was successfully destroyed.'
    end

    private
      # Use callbacks to share common setup or constraints between actions.
      def set_post
        @post = current_author.posts.find(params[:id])
      end

      # Only allow a list of trusted parameters through.
      def post_params
        params.require(:post).permit(:title, :description, :header_image)
      end
  end
end

And her is the post.rb:
class Post < ApplicationRecord
  belongs_to :author
  has_many :elements

  has_one_attached :header_image

  validates :title, :description, presence: true
end

The post form was working fine until I tried adding the validations.
When I add buy but and test it I get the following when I run params:
#<ActionController::Parameters {"authenticity_token"=>"1hQyn6kWCiCwAaeaUa1PD9q76D29RF-56LKof1uC64auGtNvA2VCZ-mDLdY7EjCYP9zWpLLvfkgkE33AUZP7Ng", "post"=>{"title"=>"Testing", "description"=>"test"}, "commit"=>"Create Post", "controller"=>"authors/posts", "action"=>"create"} permitted: false>
(byebug)

A: In the create method, you're not instantiating the Post object with post_params. So, @post.title and @post.description are nil causing the validations to fail.
@post = current_author.posts.build(post_params)


text:
Q: Pythonic way to access HDF5 data structures similar to pointers I've a project that is utilizing HDF5. There are file structures as well as HDF5 data structures for each dataset.
Think of a large video. Each frame is divided up equally and written to multiple files as well as multiple HDF5 data chunks. A single 'video' may have 20+ files (representing temporal and slices), and then more files to represent additional slices. The datasets aren't very large- under 30gb- but are still cumbersome.
My initial dive to associate (stitch) the pieces back together was to put together an array of pointers to the individual frames, and then stack them for the temporal aspect of the video. This would be (fairly) small since I would be pointing to the locations on disk where everything was. This would also limit the amount of data I'd have to hold into memory- always a bonus- for when I scale to the 'larger' datasets.
However the way to accomplish this in Python eludes me- especially when considering I want to tie in the metadata for each frame (pixels, their locations, etc).

Is there a method I should be following to better reference the data and 'stitch' it back together? My current method was to create numpy arrays of the raw data. This has the detriment of reading all of the data in and storing it in memory (and disk).


text:
Q: LNK2001 Unresolved external symbol error for variable defined in a namespace I'm having an unresolved external symbol error for two variables defined in a namespace. This is the code I have in my header and source file defining and declaring my variables.
header file
#include "States.h"

namespace acro {
    namespace states {
        extern States_t feedback;
        extern States_t down;
    }
}

source file
namespace acro {
    namespace states {
        States_t feedback;
        States_t down;
    }
}

In my main file I'm calling this.
printf("Iteration: %lld\n", acro::states::feedback.i);

But I receive this error.
Error   LNK2001 unresolved external symbol "class States_t acro::states::feedback" (?feedback@states@acro@@3VStates_t@@A)   simple_acrophobe    C:\Users\...\main.obj

States_t is class defined in the "Stated.h" an "States.cpp" file which I know works and is properly included in the project. I tested it by declaring an object in the main function.
I'm quite certain I've included my header and source files properly. I created them using the Visual Studio UI. There is nothing else in these files except for a header guard and some comments with documentation.
I've ran out of ideas on what could be going wrong here.


text:
Q: Package biblatex Error: Patching 'babel' package failed. \begin{document} I am getting following error when trying to use external bibliography library:
Package biblatex Error: Patching 'babel' package failed. \begin{document}

From what I know, this is probably caused by a bug. However, I didn't find any suitable solutions. I am using TeXstudio (Windows) and installing packages is quite difficult. Whenever I find out I need a new package, I need to install it before the document can be compiled. Basically I am installing new packages on the fly. Could it be caused by incomplete libraries? Should I reinstall TeXstudio?
This is how TeXstudio looks like on Windows:

This is my preamble in lab01.tex (before \begin{document}):
\documentclass[12pt,twoside,a4paper]{article}
\usepackage[czech]{babel}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{float}
\usepackage{lmodern}
\usepackage{graphicx}
\usepackage{attachfile}
\usepackage{subcaption}
\usepackage{cleveref}
\usepackage[document]{ragged2e}
\usepackage{textcomp}
\usepackage{gensymb}

\usepackage[
backend=biber,
style=alphabetic,
citestyle=authoryear
]{biblatex}
\addbibresource{lab01.bib}

\usepackage{siunitx}
\sisetup{
    detect-mode,
    detect-family,
    detect-inline-family=math,
    group-separator={.},
    group-minimum-digits={3},
    output-decimal-marker={,}
}

\captionsetup[subfigure]{subrefformat=simple,labelformat=simple}
\renewcommand\thesubfigure{(\alph{subfigure})}

\title{Výkonové polovodičové systémy~I \textemdash\ Laboratorní úloha č.~1\\ \large \emph{Řízený dvoupulzní usměrňovač}}
\author{Marek Poláček (POL0423)\\ VŠB \textendash\ Technická univerzita Ostrava,\\ Fakulta elektrotechniky a~informatiky.}
\date{\today}

This is content of lab01.bib:
@book{book:ZČU,
    author = {VONDRÁŠEK, František},
    title = {Výkonová elektronika},
    date = {1998},
    volume = {svazek~II},
    publisher = {Západočeská univerzita},
    location = {Plzeň},
    isbn = {80-7082-485-9},
}

@book{book:ČVUT,
    author = {PAVELKA, Jiří a~ÚČEŘOVSKÝ Zdeněk},
    title = {Výkonová elektronika},
    date = {2000},
    edition = {Vydání~2.},
    publisher = {ČVUT},
    location = {Praha},
    isbn = {80-01-02094-0},
}


text:
Q: How can I edit ORB parameters in OpenCV 3.0.0 and higher OR use different OpenCV versions in the same app in Android/Java I am implementing an algorithm for which I require CLAHE and to change ORB parameters. The ORB parameters I change in Java/android for version below 3.0 as described here. The OpenCV library doesn't have a constructor implementation for CLAHE in version lower than 3.0. for android. So, unfortunately, I don't know how to do it. What I can think of is doable is writing one part in C++ and port it to Java but that is pretty complex. May be changing the function names in OpenCV library is also possible, but I would prefer not to mess with the libraries. Can anyone suggest a possible method/solution?

A: Just for someone who might bump into this problem in future and/or doesn't want to use C++ on android, from OpenCV 3.0 the parameters in Java (android sdk) can't be changed. As described here


text:
Q: Solve a sequence of incomplete sum My uni is closed because of the pandemic and I'm home learning calculus. There is one problem I am really not sure how is supposed to be solved:
$$\log(x)+\log(\sqrt[3]{x})+\log(\sqrt[9]{x})+\log(\sqrt[27]{x})+\ldots=6$$
I know that I am supposed to show my attempts, but this is the first time I am seeing a problem like this and I have no idea how to solve it.
Could you please help me?

A: Hint :
$$log (x)+log(\sqrt[3]{x})+log(\sqrt[9]{x})+log(\sqrt[27]{x})+...= log (x)+ \frac 1 3 log(x)+ \frac 1 9log(x)+ \frac 1 {27} log(x)+... $$

Full answer :
Let's massage the expression. This equality is given by geometric sum, and taking the limit of the expression.
$$ log (x)+log(\sqrt[3]{x})+ ...  = \log(x) \sum_0^{\infty} \frac 1 {3^n} =  \frac 3 2 \log(x)   $$
so finally, you're simply searching for $$  \log(x) = 4 $$
Can you find the answer to that ?

A: Use properties of log to rewrite the equation as
$$\log x + \frac{1}{3}\log x  + \frac{1}{9}\log x + \frac{1}{27}\log x + \dots = 6.$$
Equivalently,
$$\log x \sum_{k=0}^\infty \left(\frac{1}{3}\right)^k = 6.$$
Next sum the geometric series to obtain
$$\log x \cdot\frac{1}{1-1/3} = 6.$$
Now $\log x = 4$, so $x = e^4$ (or $x=10^4$ if your $\log$ means $\log_{10}$).


text:
Q: Why the resolution of my custom softkeyboard does not increase on Android Tablets? I am customizing the softkeyboard sample of android SDK. The resolution of this keyboard is low and ugly when I install it on the 10in tablet. I mean it uses the resolution of PocketPc on the Tablet Pc. I get the width of softkeyboard using method getMaxWidth() and in both pocketpc (android 2.3) and tablet (android 3.2) it returns 545.
How can I increase the resolution of my keyboard depending on the resolution of my device?

A: I found the answer:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    <supports-screens
        android:anyDensity="true"
        android:largeScreens="true"
        android:normalScreens="true"
        android:smallScreens="true" />

</manifest>

My reference is this link.


text:
Q: PostgreSQL remote access I added remote host info on pg_hba.conf as:
host db1 all 10.6.169.88/27 trust

and also I did
listen_addresses = '*'
tcpip_socket = true

on postgresql.conf.
But still the remote client can not connect to db. What is the missing part about this? Remote client and host server is in different locations but with IT policies adjusted with correct ports and routes. So remote client is normally accessible to host server.
Here is what remote client gets as error:

A: It worked after editing the correct pg-hba.conf file. Well, earlier our customer asked us to move postgresql data to other drive partition. So there are two copies of conf files. One is inside postgresql program folder and the other is in data folder. To achieve what I want I needed to edit the one inside data folder.


text: Q: How do I change the console output language in Sphinx>=4.0 when using VS Code? I'm looking for a way to change Sphinx's console output language. After upgrading from 3.5.4 to 4.0.2, I noticed that the console output that's displayed when the documentation is building, is displayed in my native language, instead of in English like it was before. I'd prefer the English output language back. Is there a way to change it?


text:
Q: Johansen-Procedure: Values of teststatistic and critical values of test? I am trying to run a Johansen-Procedure in a set of macroeconomic variables (GDP, credit outstanding and industrial production). I am working with them in level.
How should I interpret the following result? Which "r" should I use next to run the model?
######################
# Johansen-Procedure #
######################

Test type: maximal eigenvalue statistic (lambda max) , without linear trend and constant in cointegration

Eigenvalues (lambda):
[1]  6.999273e-01  3.188663e-01  1.303763e-01  5.099467e-02 -6.157574e-17

Values of teststatistic and critical values of test:

          test 10pct  5pct  1pct
r <= 3 |  3.04  7.52  9.24 12.97
r <= 2 |  8.10 13.75 15.67 20.20
r <= 1 | 22.27 19.77 22.00 26.81
r = 0  | 69.82 25.56 28.14 33.24

[...]

My goal is to estimate the best VEC model so I can forecast those variables. I choose the number of lags from the VARselect function (saved as def), AIC(n) criteria, and then run a vec model.
jo.eigen <- ca.jo(training, type='eigen', K=def$selection[1],
                ecdet='const',
                spec='transitory',
                season=4)

vec <- cajorls(jo.eigen, r= ???)
vec.level <- vec2var(jo.eigen, r= ???)

Thank you very much!

A: The maximum eigenvalue test is used to determine the rank of the coefficient matrix associated with the cointegration term. It is a sequential test starting from the hypothesis $$H_0: r=0 \\ H_1: r=1.$$ The test statistic at r=0 is 69.82 and the 1% critical value is 33.24, meaning we reject $H_0$. Now we test $$H_0: r=1 \\ H_1: r=2.$$ Now the test statistic is rejected at the 5% level, but not at the 1% level. If you find this threshold 'acceptable' you move on to $$H_0: r=2 \\ H_1: r=3.$$ Here the test breaks down, we cannot reject $H_0$ at any of the typically used significant levels (1%, 5%, or 10%), and accept r=2.


text:
Q: Ruby on rails installation - Getting past welcome aboard I have followed the instructions found at installrails.com however i am now at the page below.

I am not sure how to continue from here and have struggled to find any answers. If any one could help it would be appreciated, thanks.

A: You have successfully install rails on you machine, now create your model and controller and enjoy the beauty of rails. you can follow rails tutorial for further reference.

A: Hey Dont worry, you are safely landed on the new Ruby On Rails Platform, of a new project that you have just created.
The shown page is the default display page for any Rails project we create, we have to design and set our on Index page or something instead of this page by creating new static or dynamic pages by creating new views, controllers and model associated with it. If you know the MVC frame work it is easy for you to begin with.
If you are beginner to both MVC and Ruby on Rails, I suggest you to follow the railstutorial.org website to start with creating sample projects step by step, it is an easy and explained tutorial for beginners in Ruby On Rails by the Author Michael Hartl
Learn Web Development with Ruby On Rails: Michael Hartl

A: If you want to change that page, just use the following code:
#config/routes.rb
root "application#index"

#app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
   def index
      #renders app/views/application/index.html.erb
   end
end

#app/views/application/index.html.erb
Hello world!

This will literally get you off that "Welcome Aboard" page and into a real Rails environment.
--
However...
If you want to get into the thick of Rails, here's a little bit more info on how to create a simple blog app. You may also wish to check out Michael Hartl's "Rails Tutorial":

*

*You'll need a "model", "database" and "controller"

*You'll need to learn about the backend structure of Rails

Here's how it works:

Rails is built around the MVC (Model View Controller) programming pattern. I won't go into details, but it means that whatever you develop in rails needs to have a model, view and controller action to support it.
Without that pattern, you'll not get anywhere with the system.

Thus, to make a simple blog app, you should create the following:
#config/routes.rb
root "posts#index"
resources :posts #-> url.com/posts/:id

#app/controllers/posts_controller.rb
class PostsController < ApplicationController
   before_action :find_post, only: [:show, :edit, :update, :destroy]

   def index
      @posts = Post.all
   end

   def new
      @post = Post.new
   end

   def create
      @post = Post.new post_params
      @post.save
   end

   def show
   end

   def edit
   end

   def update
      redirect_to @post, notice: "Post Updated" if @post.update
   end

   def destroy
      redirect_to root_path, notice: "Post Destroyed" if @post.destroy
   end

   private

   def find_post
      @post = Post.find params[:id]
   end

   def post_params
      params.require(:post).permit(:title, :body)
   end
end

This will allow you to use the following views:
#app/views/posts/index.html.erb
<%= render @posts %>

#app/views/posts/show.html.erb
<%= render @post %>

#app/views/posts/edit.html.erb
<%= render "form", locals: {post: @post} %>

#app/views/posts/new.html.erb
<%= render "form", locals: {post: @post} %>

#app/views/posts/_post.html.erb
<%= post.title %>
<%= post.body %>

#app/views/posts/_form.html.erb
<%= form_for post do |f| %>
  <%= f.text_field :text %>
  <%= f.text_area :body %>
  <%= f.submit %>
<% end %>

--
Finally, the model:
#app/models/post.rb
class Post < ActiveRecord::Base
end

You'll also need a database table, which you create using migrations:
$ rails g migration CreatePosts

#db/migrate/create_posts_______.rb
class CreatePosts < ActiveRecord::Migration
   def change
      create_table :posts do |t|
         t.string :title
         t.text :body
         t.timestamps
      end
   end
end

$ rake db:migrate

A: Don't forget to delete the public/index.html.  This happened to me when I copied a site into a blank website.


text:
Q: UITableViewCell with prepareForReuse does not work I have created a custom UITableViewCell where I add a bunch of buttons loaded dynamically to its contentView. These display properly.
When the data which controls what buttons are loaded change and I call reloadData I can see that prepareForReuse is called:
- (void) prepareForReuse {
    NSLog(@"prep for reuse");
    [self clearButtons];
}

- (void) clearButtons {
    NSLog(@"clearButtons called");
    self.buttons;
    for (UIView* v in buttons) {
        NSLog(@"clearing a button.");
        [v removeFromSuperview];
        [v dealloc];
    }
    buttons = [[NSMutableArray alloc] init];
}

The buttons are not removed from the superview though, the "clearing a button." message is never logged.
I then added an explicit call to clearButtons in tableView:cellForRowAtIndexPath:
CustomCell *cell = (CustomCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[CustomCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}

[cell clearButtons];

And this time I can see that "clearing a button." is logged and everything displays correctly.
What gives? Why aren't the buttons removed when called from prepareForReuse?

A: You must specify a reuse identifier when the cell is created or UITableView will not call your 'prepareForReuse' method.
Per documentation, you must also call [super prepareForReuse];

A: It might not related, but there are few things you should fix in createButtons:

*

*Use [v release] instead of [v dealloc]

*Release the buttons as well before init new one.

I would also ask that if you remove everything but NSLog, does it works?


text:
Q: how can I grey out and show loading in the web page when user clicks on those items that are linked to next page? I created a php-html website with many pages, in these pages there are ,,, and other html elements, but not all of them linked to other pages, it means they do a job into the current page, but other elements are linked to other pages, how can I set when user clicks on those elements(,,...) that are linked to other pages,before going to next page the page be grey and loading.gif is shown.
I see this code
http://hungred.com/how-to/tutorial-simple-screen-grey-effect-jquery/
but in this jQuery code we need to set $('#button').click(pop); for thoese elements one by one,that I think it is not good job, what is the good idea, that works for whole pages?

A: A quick solution could be to apply the same class to all the buttons that need to act in this way:
<button class="externalLink">Button 1</button>
<button class="externalLink">Button 2</button>
<button class="externalLink">Button 3</button>
<button class="externalLink">Button 4</button>
<button class="externalLink">Button 5</button>

And then write something like this in javascript:
$('.externalLink').click(pop);

This will apply the same behavior to all the buttons with that class


text:
Q: Best way to call a javascript function like 'window.open()' in Smart Mobile Studio I'm evaluating SMS and really enjoying the experience. I need to open a new window/tab on the browser using window.open(). I have got this working using an asm block but I can't help but feel that there is a better way which I don't know about. So, is there a more SMS way of doing the following?
  asm
    window.open('MyPDF.pdf');
  end;

Many thanks.
 Regards,
  Will.

A: Traditionally that was the only way, but in recent Smart releases you can also use the BrowserAPI entry point.
uses SmartCL.System;

BrowserAPI.Window.open('MyPDF.pdf');


text:
Q: How can I deprecate a route in a Sinatra app? I'm writing a API mock server by Sinatra, it looks like below
require 'sinatra/base'

class APIMockServer < Sinatra::Base

  post '/mock' do
    _body = params[:body]
    _status = params[:status] || 200
    APIMockServer.send params[:method], params[:action] do
      body _body
      status _status
    end
    'success'
  end

  run! if app_file == $0

end

I send a post request to /mock, the Sinatra App will generate a route dynamically.
require 'restclient'

RestClient.post(
    '127.0.0.1:4567/mock',
    {
        action: '/sayhi',
        method: 'get',
        body: 'hello world'
    }
)

So far it works as expected, but when I send another post request with same action, it doesn't take effect.
require 'restclient'

RestClient.post(
    '127.0.0.1:4567/mock',
    {
        action: '/sayhi',
        method: 'get',
        body: 'hello world, hello Sinatra' # the body is changing
    }
)

I guess because I defined two routes with same name, so the Sinatra take the first matched one to response. How can I deprecate the first one, so that the last one could take effect?

A: That is an interesting app. It's a metaprogramming API.
I think the issue is that once the route is defined, it is not being redefined.
So, perhaps you need to remove the route using something like
remove_method params[:method]

or
APIMockServer.remove_method params[:method], params[:action]

I'm not sure how Sinatra manages the defined routes, but you may want to look into that. Perhaps How do you remove a route from Sinatra? would be of some help.


text:
Q: Getting real time coordinates of ImageView while it is in Translate Animation on android I have an ImageView, set to Translate animation. I want real time coordinates of the ImageView when it is moving.
My code here:
ImageView myimage = (ImageView)findViewById(R.id.myimage);

  Animation animation = new TranslateAnimation(100, 200, 300, 400);
  animation.setDuration(1000);
  myimage.startAnimation(animation);
  animation.setRepeatCount(Animation.INFINITE);

  int x = myimage.getLeft();
  int y = myimage.getTop();

Variables x and y don't updatee real time and only give original static coordinate of the ImageView.
How can I get the real time coordinates as the ImageView is in motion ?

A: You can try like this,
   ImageView myimage = (ImageView)findViewById(R.id.myimage);

  Animation animation = new TranslateAnimation(100, 200, 300, 400);
  animation.setDuration(1000);
  myimage.startAnimation(animation);
  animation.setRepeatCount(Animation.INFINITE);
    int[] firstPosition = new int[2];
    myimage.measure(View.MeasureSpec.EXACTLY, View.MeasureSpec.EXACTLY);
        myimage.getLocationOnScreen(firstPosition);
        int r = myimage.getMeasuredWidth() + firstPosition[1];
        int rr = myimage.getMeasuredWidth() + firstPosition[0];

A: int[] imageCordinates = new int[2];
                imgv1.getLocationOnScreen(imageCordinates);

                x = imageCordinates[0] + (imgv1.getWidth() / 2);
                y = imageCordinates[1] + (imgv1.getHeight() / 2);


text:
Q: Google Cloud regionInstanceGroups seem to be unusable, API doesn't have insert method Trying to see if someone can shed light on this for me. I stumbled upon this API object in documentation when trying to find something that would allow me to use a region-wide unmanaged instance group. This API object suggests that it's possible, but there's no API insert method, only get and list.
Can someone help me understand what this API object does, it's purpose and how to use it?

A: I believe it would be this method
From the overview page the instranceGroups category represents an unmanaged Instance Group resource
As suggested by John not all API calls are available if you are looking for any feature not available in GCP you can open a Feature Request with Google for evaluation


text:
Q: how to cancel download of iOS7 on iPhone I started to download iOS7 from my iPhone 4, and then I read about lots of lag and battery issues. I'd love to try iOS7 but since I won't be able downgrade to iOS6 I'd like to cancel the download. The problem is I don't know how.
I've only been able to stop the download by disabling Wi-Fi.
How can I cancel the download of iOS7? Am I doomed to never be able to use Wi-Fi again?

A: You can probably back up your iPhone with iTunes and then restore that backup, and that should cancel the update.
Restore Back Up and not Restore iPhone
**There is another way too, which just worked for me: your iPhone can't install the update if it doesn't have the free space available, and this is a pretty big update.  You can simply copy a bunch of large files to your iPhone (e.g., lots of music or audiobooks) and the update will stop and you will get a message saying that the download cannot finish installing due to lack of space.  This essentially stops the update (and then you can go back in and immediately remove the big files that you moved on there).