Q:

Graphs in a loop in SPSS

I have a graph that works outside of a loop, but when it is included in a loop, I get the message "running inline gpl" and the error message "GPL error: id('graphdataset') not a quoted string: 'graphdataset'." Is there a special way to run graphs in a loop that I am missing?
DEFINE !ess1 (inum=!charend ('/')
/ iname=!charend ('/')
/ iname2=!charend ('/')
/ g1=!charend ('/')
/ g2=!charend ('/')
/ g3=!charend ('/')
/ g4=!charend ('/')).

RECODE INST
    (!inum=1)
    ( !g1 = 2)
    (!g2= 3)
    (!g3=4)
    (!g4=5)
    into cgroup.
MISSING VALUES cgroup(-9).
variable labels cgroup 'Comparison Group'.
value labels cgroup 1 !iname2 2 'Thing1' 3 'Thing2' 4 'Thing3' 5 'Thing4'.
EXECUTE.

USE ALL.
VARIABLE LEVEL ALL (NOMINAL).

CTABLES
  /VLABELS VARIABLES=satisf cgroup DISPLAY=DEFAULT
  /TABLE cgroup  [ROWPCT.COUNT PCT40.1] BY satisf
  /SLABELS VISIBLE=NO
  /CATEGORIES VARIABLES=satisf cgroup ORDER=A KEY=VALUE EMPTY=INCLUDE TOTAL=YES LABEL="Overall" POSITION=AFTER
  MISSING=EXCLUDE
  /TITLES
   TITLE= 'Overall, how satisfied have you been with this example syntax?'.

RENAME VARIABLES  (sinstql sdiscus sadvising sadmresp ssoclife scampcom slivecom=Var1 Var2 Var3 Var4 Var5 Var6 Var7).

varstocases
/make Likert From Var1 to Var7
/index Question (Likert).

*I need to make a variable to panel by.
compute panel = 0.
if Likert > 2 panel = 1.

*Aggregate N per question.
AGGREGATE OUTFILE=* MODE=ADDVARIABLES
/BREAK Question
/TotalPerQ = N.

*Use trans to make a percent.
GGRAPH
/GRAPHDATASET NAME="graphdataset" VARIABLES=Question MEAN(TotalPerQ)[name="MeanTotalPerQ"] COUNT()[name="COUNT"] Likert panel
MISSING=LISTWISE REPORTMISSING=NO
/GRAPHSPEC SOURCE=INLINE.
BEGIN GPL
SOURCE: s=userSource(id("graphdataset"))
COORD: transpose(mirror(rect(dim(1,2))))
DATA: Question=col(source(s), name("Question"), unit.category())
DATA: COUNT=col(source(s), name("COUNT"))
DATA: MeanTotalPerQ=col(source(s), name("MeanTotalPerQ"))
DATA: Likert=col(source(s), name("Likert"), unit.category())
DATA: panel=col(source(s), name("panel"), unit.category())
TRANS: Perc = eval((COUNT/MeanTotalPerQ)*100)
GUIDE: axis(dim(1), label("Satisfaction"))
GUIDE: axis(dim(3), null(), gap(0px))
GUIDE: legend(aesthetic(aesthetic.color.interior), null())
SCALE: linear(dim(2), include(0))
SCALE: cat(aesthetic(aesthetic.color.interior), sort.values("1","2","4","3"), map(("1", color.red), ("2", color.lightpink), ("3", color.lightgreen), ("4", color.green)))
ELEMENT: interval.stack(position(Question*Perc*panel), color.interior(Likert),shape.interior(shape.square),transparency.exterior(transparency."1"))
END GPL.
******************************.

dataset close *.

get file= 'FilePath.sav'.

DELETE VARIABLES cgroup.

OUTPUT EXPORT
  /CONTENTS  EXPORT=VISIBLE  LAYERS=PRINTSETTING  MODELVIEWS=PRINTSETTING
  /PDF  DOCUMENTFILE=!Quote(!Concat('Y:\Surveys\ESS\2015\COFHE ESS 2015 Comparison Report ',!iname,'.pdf'))
     EMBEDBOOKMARKS=YES  EMBEDFONTS=YES.

OUTPUT SAVE
OUTFILE=!Quote(!Concat('Y:\Surveys\ESS\2015\COFHE ESS 2015 Comparison Report ',!iname,'.spv'))

OUTPUT CLOSE *.
OUTPUT NEW.

!ENDDEFINE.

!ess1 inum=1/iname=Name1/ iname2='Name1'/g1= 2,3,4,5,6,7,8,9,10,11,12,13 /g2= 21,22,23,24,25,26,27,29/g3=31,32,33,34,35,36,37,38/g4=41,42,43,44,45/.
!ess1 inum=2 /iname=Name2 /iname2='Name2'/g1= 1,3,4,5,6,7,8,9,10,11,12,13 /g2= 21,22,23,24,25,26,27,29/g3=31,32,33,34,35,36,37,38/g4=41,42,43,44,45/.
!ess1 inum=3 /iname=Name3 /iname2='Name3'/g1= 1,2,4,5,6,7,8,9,10,11,12,13 /g2= 21,22,23,24,25,26,27,29/g3=31,32,33,34,35,36,37,38/g4=41,42,43,44,45/.

A:

Macros are not supported with GPL, because the GPL syntax doesn't follow standard SPSS Statistics syntax and macro expansion would be unreliable.  Sometimes it would work, but Python programmability is the appropriate mechanism for this.
A demonstration on how to do this can be found here


Q:

Do anonymous methods consume memory?

Do Anonymous Methods, Delegates, Action, Func and alike, allocate/consume/eat memory on your computer?
If so, do they allocate same memory on each variable on captured code block?

A:

Of course they do, just like any other normal function. How can they be executed at run time if they wouldn't be "stored" somewhere in memory?
But if you are asking if they consume more memory on every call (as in allocating dynamic memory), then no, they don't do that on their own.


Q:

Would it be beneficial to list a game I'm developing on my resume?

I've been working on & off on a game for about a bit over a year in my spare time, and I'm trying to decide if it should go on my resume when applying for jobs. My thought was to show that I enjoy learning new things & being creative in my free time. However, the position is not in the games industry, but more of a general programming position.
My fear would be appearing distracted or otherwise not "devoted" to the position or company - I would do game development full time if I thought I could.

A:

It depends a lot on the industry you're in, your personality, and that of the interviewer(s).
I would include it in the Other Interests section only if it is far enough along to reflect well on you.  As an interviewer, I really don't care about your plans or what you're going to do, I care about what you've already done.
A well polished game can show attention to detail, imagination, skill, and a willingness to stand out from all the drone resumes that make hiring manager's eyes glaze over.
In your specific case, you may want to leave it off the resume until it's been released and has been in use for a couple of months.  It needs to be fairly solid.  You don't want it to crash during an interview.


Q:

Try to create an entity within Azure functions fails with "Method not found"

Hi I try to create an entity (in CRM 365) within an Azure function.
I use the following code for doing that:
     using (CrmServiceClient crmSvc = new CrmServiceClient(System.Configuration.ConfigurationManager.ConnectionStrings["MSD_Q"].ConnectionString))
     {
         if(crmSvc.IsReady)
         {

             Entity account = new Entity("account");
             account["name"] = inputJson.contactdetails.company.ToString();
             Guid response = crmSvc.Create(account);
         }
     }

but when I execute the create method I get the following error:
Exception while executing function: Functions.crmFunction. mscorlib: Exception has been thrown by the target of an invocation. f-crmCreateTicket__1492291149: Method not found: 'System.Guid Microsoft.Xrm.Tooling.Connector.CrmServiceClient.Create(Microsoft.Xrm.Sdk.Entity)'.

The project.json in azure function looks like the following:
{
 "frameworks": {
   "net46": {
     "dependencies": {
       "Microsoft.CrmSdk.CoreAssemblies": "8.2.0",
       "Microsoft.CrmSdk.XrmTooling.CoreAssembly": "8.2.0",
       "Microsoft.ApplicationInsights": "2.1.0"
   }
  }
 }
}

I try to figure out what I do wrong. Because an hour ago with the same code, it worked very well. But I dodn't change s.th. in Dynamics CRM.

A:

So I fixed the issue by using the following references.
After that it worked for now.
{
"frameworks": {
"net46": {
  "dependencies": {
    "Microsoft.CrmSdk.CoreAssemblies": "8.2.0.2",
    "Microsoft.CrmSdk.Deployment": "8.2.0.2",
    "Microsoft.CrmSdk.Extensions": "7.1.0.1",
    "Microsoft.CrmSdk.XrmTooling.CoreAssembly": "8.1.0",
    "Microsoft.ApplicationInsights": "2.1.0"
  }
}

}
}
I think that there will be missing the additional assemlbies.


Q:

Conditional JS call for IE7?

I have a complex site that incorporates alot of javascript and it is getting absolutely KILLED by IE7.  How would I go about serving this code:
HTML

JS
$(document).ready(function(){
    $('#curtain').delay(1500).fadeIn(1000);
});

In such a way that IE7 never gets the style="display: none" and therefore never hides
?

A:

You can use conditional comments to set IE7 specific styles.

But, you should take the display setting out of the style attribute, as the level of specificity is high enough that it may override the admittedly hack-y !important attribute.


Q:

How can my website app publish on facebook timeline when the user is not logged on facebook?

I would like to know if there is a posibility of publishing my actions on facebook timeline if the user is not logged on facebook, I mean through a cron job, actually my users have an extended token, but if they are not connected on facebook, it can't publish anything on their timelines

A:

I believe you have to use app access tokens.

If your app publishes on behalf of its users and requires an access token with no expiration time, you should use an App Access Token. An App Access Token is signed using your app secret and will not expire; it will be invalidated if you re-key/reset your application secret.
https://developers.facebook.com/docs/opengraph/using-app-tokens/


Q:

Animated change in Picker will run animation multiple times

I have the following code:
import SwiftUI

let names = ["John", "Betty", "Fred", "May", "Judy"]

struct ContentView: View {
    @State var selection = 0

    var body: some View {
        VStack(spacing: 20) {
            Picker("Name", selection: self.$selection.animation(.linear(duration: 0.3))) {
                ForEach(names.indices, id: \.self) { i in
                    Text(names[i]).tag(i)
                }
            }.pickerStyle(SegmentedPickerStyle())
            Text(names[self.selection])
                .font(.title)
                .fixedSize()
                .modifier(MyShake(animatableData: CGFloat(self.selection)))
        }
        .padding()
    }
}

struct MyShake: GeometryEffect {
    var animatableData: CGFloat

    func modifier(_ x: CGFloat) -> CGFloat {
        10 * sin(x * .pi * 2)
    }

    func effectValue(size: CGSize) -> ProjectionTransform {
        let transform1 = ProjectionTransform(CGAffineTransform(translationX: 10 + modifier(animatableData), y: 0))
        return transform1
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
        .previewDevice("iPhone SE")
    }
}

If you switch from John to Betty (i.e. select a segment next to the current one), the animation will run once, which is exactly what I want. However, if you switch from John to Fred, the animation will run multiple times because the selection actually doesn't move from 0 to 2, but interpolates each step in between.
How can I limit the animation such that it only runs once?

A:

As I see it needs to convert selection into just toggle. Please find below possible approach for this. Tested & works with Xcode 11.2 / iOS 13.2
Demo:

Changes are only in ContentView:
struct ContentView: View {
    @State var selection = 0
    @State var shaking = false
    var body: some View {
        let value = Binding<Int>(
            get: { self.selection },
            set: { newValue in
                withAnimation(Animation.linear(duration: 0.3)) {
                    self.shaking.toggle()
                }
                self.selection = newValue
            })
        return VStack(spacing: 20) {
            Picker("Name", selection: value) {
                ForEach(names.indices, id: \.self) { i in
                    Text(names[i]).tag(i)
                }
            }.pickerStyle(SegmentedPickerStyle())
            Text(names[self.selection])
                .font(.title)
                .fixedSize()
                .modifier(MyShake(animatableData: CGFloat(self.shaking ? 1 : 0)))
        }
        .padding()
    }
}


Q:

Не могу отправить электронное письмо

Подскажите, пожалуйста, в чем может быть причина! С помощью заполнения Электронной формы пытаюсь отправить письмо. Но почему php не хочет отправлять. Может у вас получиться найти ошибку...
php:
<?php

 // Определение некоторых констант
 define( "RECIPIENT_NAME", "John Smith" );

 define( "RECIPIENT_EMAIL", "Avtoclub-MIR@art.ru" );

 define( "EMAIL_SUBJECT", "Visitor Message" );

// Чтение формы

$success = false;
$senderName = isset( $_POST['senderName'] ) ? preg_replace( "/[^\.\-\' a-zA-Z0-9]/", "", $_POST['senderName'] ) : "";

$senderEmail = isset( $_POST['senderEmail'] ) ? preg_replace( "/[^\.\-\_\@a-zA-Z0-9]/", "", $_POST['senderEmail'] ) : "";

$phone = isset( $_POST['phone'] ) ? preg_match( '/^\d{10}$/', '', $_POST['phone'] ) : "";

$marka = isset( $_POST['marka'] ) ? preg_replace( "/[^\.\-\' a-zA-Z0-9]/", '', $_POST['marka'] ) : "";

$message = isset( $_POST['message'] ) ? preg_replace( "/(From:|To:|BCC:|CC:|Subject:|Content-Type:)/", "", $_POST['message'] ) : "";

 //Если  все значения в норме, отправляем по электронной почте
if ( $senderName && $senderEmail && $phone && $marka && $message ) {
  $recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">";

$headers = "From: " . $senderName . " <" . $senderEmail . "<" . $phone . ">" . $marka . ">";

$success = mail( $recipient, EMAIL_SUBJECT, $message, $headers );
}

 // Вернуться соответствующий ответ браузеру
if
( isset($_GET["ajax"]) ) {
  echo $success ? "success" : "error";
}
else {
?>

<title>Thanks!</title>

<?php if ( $success )
echo "
Спасибо за отправкой сообщения! Мы свяжемся с Вами в ближайшее время.
"
?>

 <?php
 if ( !$success ) echo "
Существует проблема отправке сообщения. Пожалуйста, попробуйте еще раз.
"
?>

Нажмите кнопку Назад в браузере, чтобы вернуться к странице.

<?php
}

?>

A:

Добро пожаловать в один из самых нервных языков на планете!
Код
if ( $senderName && $senderEmail && $phone && $marka && $message )

не выполнится, если хотя бы в одной из переменных содержится пустая строка.
Лично я часто специально привожу переменные к типам в коде, хоть это и выглядит как из пушки по воробьям (здесь приведение не нужно, я про ситуацию в целом). С вашей стороны я бы разделил валидацию и данные (вы проверяете валидность формы наличием самих данных, в то время как пустые строки не запрещены).
http://www.php.net/manual/ru/language.types.type-juggling.php
http://www.php.net/manual/ru/language.types.boolean.php#language.types.boolean.casting

var_dump((bool) "");        // bool(false)


Q:

How can Santa keep his lists when the GDPR is around?

For my non European readers, there is excerpt of what the GDPR means: (emphasis mine)

The General Data Protection Regulation (GDPR) is a regulation in EU law on data protection and privacy for all individuals within the European Union (EU) and the European Economic Area (EEA).
A processor of personal data must clearly disclose any data collection, declare the lawful basis and purpose for data processing, how long data is being retained, and if it is being shared with any third-parties or outside of the EU.

I haven't been notified by Santa and/or his elves that he is collecting data about me. And mind you: my name and surname are my personal data, not to mention data on whether I have been good or naughty.
Moreover, Santa also needs my full address to deliver my presents, and again, that is also my personal data
I haven't been notified by Santa whether he is updating his Privacy Policy, so my assumption is, that Santa stopped collecting these data, at least for Europeans.
Does it mean that Santa is delivering me nothing this Christmas? If there is any way around this, can you please tell me what it is and how can Santa deliver me presents while still being compliant with the GDPR?
Please assume I haven't been naughty.

A:

Santa's data collection has always been compliant with GDPR, so he has no need to change his ways. The nature of his data collection is more transparent than most companies, and he is open to updating his records if you contact one of his representatives.
For example, he makes it clear that he is operating in your town:

You better watch out
You better not cry
Better not pout
I'm telling you why
Santa Claus is coming to town

The legitimate business purpose of his data collection is to create a list of those who are naughty and nice this year:

He's making a list
And checking it twice;
Gonna find out Who's naughty and nice
Santa Claus is coming to town

He even gives some examples of what data he's collecting:

He sees you when you're sleeping
He knows when you're awake
He knows if you've been bad or good
So be good for goodness sake!

The GDPR has some other requirements to it, such as an EU-based representative being necessary for operating in the EU, allowing users to request data updates, and getting consent for data collected.
Thankfully for Santa, he's been operating compliant representative systems for decades: Just go to any mall during the holiday season to meet with a representative. To ensure open and accurate records, the representative will ask the child if they've been naughty or nice that year and what type of present they want.
As long as the child's parent/legal guardian is nearby to confirm the data change requests, Santa will be happy to update his database to ensure the naughty/nice data is accurate and that the requested presents are delivered.
As for consent, the children are obviously too young to provide consent and must rely on their parent/guardian to consent to Santa's data collection. I doubt there's a single house that is receiving presents from Santa without the parent's explicit consent, and I'm sure we've all been told by our parents at some point to "be good or Santa won't give you presents this year!".

A:

Santa is Christian priest (bishop as far as I remember). As you can see here he is covered by exemption:

The new Regulation will maintain the existing exemption which allows churches and other bodies with a 'religious... aim' to process sensitive data:

'in the course of its legitimate activities...';
'...with appropriate safeguards';
'...on condition that the processing relates solely to the members or to former
  members of the body or to persons who have regular contact with it in connection with its purposes'; and
on condition that 'the data are not disclosed outside that body without the
  consent of the data subject'.

As no one ever saw his lists, and we don't know about any other activities, we can safely assume above bullets are met.

A:

Well you are making a fundamental misunderstanding about the GDPR (as many have), that consent is the only basis for holding and processing information.
There are actually six legal bases for holding data (you have to scroll down a little as the link doesn't work properly).
Those six bases are:

Consent
Contract
Legal obligation
Vital interests
Public task
Legitimate interests

So let's look at each of them and see if Santa has any basis for collecting our information.
Consent - Actually this one may not even be as troublesome as it first seems. Presumably we're all writing letters to Santa asking for presents, this could potentially be seen as a form of consent for collecting our data, though I think that's a little iffy.
Contract - The letter to Santa could also form the basis for a contract for the provision of services (present delivery), so I think this works.
Legal Obligation - Unless you want to argue that Santa is legally obligated to perform his duties I don't think this one works.
Vital Interests - No one is going to die if Santa doesn't do his job, probably doesn't work either.
Public Task - I think this is a strong contender. From the website I linked above; "the processing is necessary for you to perform a task in the public interest or for your official functions, and the task or function has a clear basis in law." I would say the worldwide provision of joy and happiness is in the public interest, and the processing of our information is definitely required for Santa's official functions.
Legitimate Interests - This is a little of a grey area and many businesses have used it as the basis for continuing to hold and process information, I see no reason why Santa couldn't do the same.
So in short, there is no real issue at all and Santa can continue doing what he needs to do as long as he properly deals with our information and updates his privacy policies.


Q:

Using mRMRe in R

I am currently working on a project where I have to do some feature selection for building a predictive model. I was lead to a package in R called mRMRe. I am just trying to work the example but cannot get it working. The example can be found here - http://www.inside-r.org/packages/cran/mRMRe/docs/mRMR.ensemble.
Here is my code -
data(cgps)
data <- data.frame(target=cgps.ic50, cgps.ge)
mRMR.ensemble(data, 1, rep.int(1, 30))

When I run this code I get the error -
Error in .local(.Object, ...) : data must be of type mRMRe.Data.

I dug a litter further and found that you actually have to convert the data to mRMR.Data type. So I did this update -
# Update
data <- mRMR.data(data = data.frame(target=cgps.ic50, cgps.ge))
mRMR.ensemble(data, 1, rep.int(1, 30))

but I still get the same error. When I look at the class I have -
> class(data)
[1] "mRMRe.Data"
attr(,"package")
[1] "mRMRe"

So the data is the requested type but the code is still not functional.
My question is if anyone has experience using this package or any help or comments would be appreciated!
Also want to note that in the example from the link - when I load the data
cgps_ic50 -> cgps.ic50
cgps_ge -> cgps.ge

so the names of the data aren't the same as the same in the example.

A:

With the code you wrote:
data(cgps)
data <- mRMR.data(data = data.frame(target=cgps.ic50, cgps.ge))
mRMR.ensemble(data, 1, rep.int(1, 30))

The function mRMR.ensemble is getting the data as the first parameter, but the default first parameter in this function is solution_count.
I understand that your intentions executing that example are finding 30 relevant and non-redundant features using the classic mRMR feature selection algorithm so try this:
data(cgps)
data <- mRMR.data(data = data.frame(target=cgps.ic50, cgps.ge))
mRMR.ensemble(data = data, target_indices = 1,
              feature_count = 30, solution_count = 1)

The target_indices are the positions in the original data.frame of the features used to maximize the relevance (correlation or other quality measure for this issue), so features selected in the end will be good for explaining the features indicated in the target_indices.
For example, in a classification problem, we would choose the position of the class variable as the value for the target_indices parameter.
The feature_count parameter indicates the number of variables to be chosen.
The solution_count is not a parameter of the classic mRMR. It indicates the number of mRMR algorithms to be ensembled to get a final feature selection, so if set to 1 it performs only one classic mRMR.


Q:

Error when running jekyll new command

when trying to run the following command I receive an error:
jekyll new myblog

And the error is as follows:
/var/lib/gems/1.8/gems/commander-4.1.5/lib/commander/runner.rb:365:in `require_program': program version required (Commander::Runner::CommandError)
from /var/lib/gems/1.8/gems/commander-4.1.5/lib/commander/runner.rb:364:in `each'
from /var/lib/gems/1.8/gems/commander-4.1.5/lib/commander/runner.rb:364:in `require_program'
from /var/lib/gems/1.8/gems/commander-4.1.5/lib/commander/runner.rb:52:in `run!'
from /var/lib/gems/1.8/gems/commander-4.1.5/lib/commander/delegates.rb:7:in `run!'
from /var/lib/gems/1.8/gems/commander-4.1.5/lib/commander/import.rb:10
from /usr/local/bin/jekyll:19
/usr/lib/ruby/vendor_ruby/1.8/rubygems/custom_require.rb:36:in `gem_original_require': no such file to load -- json (LoadError)
from /usr/lib/ruby/vendor_ruby/1.8/rubygems/custom_require.rb:36:in `require'
from /var/lib/gems/1.8/gems/jekyll-1.3.0/bin/../lib/jekyll/filters.rb:2
from /usr/lib/ruby/vendor_ruby/1.8/rubygems/custom_require.rb:36:in `gem_original_require'
from /usr/lib/ruby/vendor_ruby/1.8/rubygems/custom_require.rb:36:in `require'
from /var/lib/gems/1.8/gems/jekyll-1.3.0/bin/../lib/jekyll.rb:43
from /usr/lib/ruby/vendor_ruby/1.8/rubygems/custom_require.rb:36:in `gem_original_require'
from /usr/lib/ruby/vendor_ruby/1.8/rubygems/custom_require.rb:36:in `require'
from /var/lib/gems/1.8/gems/jekyll-1.3.0/bin/jekyll:7
from /usr/local/bin/jekyll:19:in `load'
from /usr/local/bin/jekyll:19

I run ElementaryOS, and have ruby-dev (1.9.1) also installed.

A:

I had the same problem and as commented above I installed the json gem with
sudo gem install json

to fix the problem.
My platform is Ubuntu Precise


Q:

Calculating the number of neutrons in a sample

Which of the following contains one mole of neutrons?
A. $\pu{1 g}$ of $\ce{^1_1H}$
B. $\pu{1 g}$ of $\ce{^{12}_6C}$
C. $\pu{2 g}$ of $\ce{^{24}_{12}Mg}$
D. $\pu{2 g}$ of $\ce{^{23}_{10}Ne}$

Here's a question which I don't know how to answer. I tried using the equation:
moles=mass/mr
but that did not match the answer given, which is (C). I keep doing 2/24 which doesn't appear to equal 1 mole.

A:

The formula
$$\text{amount of substance} = \frac{\text{mass}}{\text{molar mass}}$$
tells you that you have 1/12 moles of magnesium, since you are taking the mass of magnesium (2 g) and dividing by the molecular mass of magnesium (24 g/mol). However, the question is not asking about the number of moles of magnesium.
Each magnesium atom has 24 - 12 = 12 neutrons. Consequently, 1/12 moles of magnesium has (1/12)(12) = 1 mole of neutrons.


Q:

Simplifying Subformulas in Coq

I'm trying to solve an equation of the form
A * B * C * D * E = F

where * some complicated left associative operation.
At the moment, everything is opaque (including * and A through F), and can be made transparent via autounfold with M_db.
The problem is that if I globally unfold the definition in the formula, simplification will take forever. Instead, I want to first unfold A * B, apply some tactics to reduce it to a normal form X, and then do the same with X * C and so forth.
Any idea how I would accomplish this? Here's my current approach but the in A or at A doesn't work. Also, it's not clear to me whether this is the right structure, or reduce_m ought to return something.
Ltac reduce_m M :=
  match M with
  | ?A × ?B => reduce_m A;
              reduce_m B;
              simpl;
              autorewrite with C_db
  | ?A      => autounfold with M_db (* in A *);
              simpl;
              autorewrite with C_db
  end.

Ltac simpl_m :=
  match goal with
  | [|- ?M = _ ] => reduce_m M
  end.

A minimalish example:
Require Import Arith.

Definition add_f (f g : nat -> nat) :=  fun x => f x + g x.

Infix "+" := add_f.

Definition f := fun x => if x =? 4 then 1 else 0.
Definition g := fun x => if x <=? 4 then 3 else 0.
Definition h := fun x => if x =? 2 then 2 else 0.

Lemma ex : f + g + h = fun x => match x with
                             | 0 => 3
                             | 1 => 3
                             | 2 => 5
                             | 3 => 3
                             | 4 => 4
                             | _ => 0
                             end.

A:

You can put your term in a hypothesis and autounfold in that.  That is, you can replace
autounfold with M_db (* in A *)

with
let Aterm := fresh in
set (Aterm := A);
autounfold with M_db in Aterm;
subst Aterm

If your A is too big, this will be slow, because set is slightly complicated and does some sort of reduction.  If this is the case, you can set up your goal so that you have:
HA     : A' = A
HB     : B' = B
HC     : C' = C
HD     : D' = D
HE     : E' = E
HAB    : AB = A' * B'
HABC   : ABC = AB * C'
HABCD  : ABCD = ABC * D'
HABCDE : ABCDE = ABCD * E'
------------------------
ABCDE = F

and then you can do something like
Ltac reduce H :=
  autounfold with M_db in H; simpl in H; autorewrite with C_db in H.

reduce HA; reduce HB; reduce HC; reduce HD; reduce HE;
subst A' B'; reduce HAB;
subst AB C'; reduce HABC;
subst ABC D'; reduce HABCD;
subst ABCD E'; reduce HABCDE;
subst ABCDE.

Update to account for the example:
To do the reduction on your function, you do indeed need either function extensionality, or to use a relation other than =.  However, you don't need function extensionality to do the modularization bits:
Require Import Arith.

Definition add_f (f g : nat -> nat) :=  fun x => f x + g x.

Infix "+" := add_f.

Definition f := fun x => if x =? 4 then 1 else 0.
Definition g := fun x => if x <=? 4 then 3 else 0.
Definition h := fun x => if x =? 2 then 2 else 0.

Ltac save x x' H :=
  remember x as x' eqn:H in *.

Lemma ex : f + g + h = fun x => match x with
                                | 0 => 3
                                | 1 => 3
                                | 2 => 5
                                | 3 => 3
                                | 4 => 4
                                | _ => 0
                                end.
Proof.
  save f f' Hf; save g g' Hg; save h h' Hh;
  save (f' + g') fg Hfg; save (fg + h') fgh Hfgh.
  cbv [f g] in *.
  subst f' g'.
  cbv [add_f] in Hfg.
  (* note: if you want to simplify [(if x =? 4 then 1 else 0) +
      (if x <=? 4 then 3 else 0)], then you need function
      extensionality.  However, you don't need it simply to
      modularize the simplification. *)

Alternatively, if you set up your goal a bit differently, you can avoid function extensionality:
Require Import Arith Coq.Classes.RelationClasses Coq.Setoids.Setoid Coq.Classes.Morphisms.

Definition add_f (f g : nat -> nat) :=  fun x => f x + g x.

Infix "+" := add_f.

Definition f := fun x => if x =? 4 then 1 else 0.
Definition g := fun x => if x <=? 4 then 3 else 0.
Definition h := fun x => if x =? 2 then 2 else 0.

Ltac save x x' H :=
  remember x as x' eqn:H in *.
Definition nat_case (P : nat -> Type) (o : P 0) (s : forall n, P (S n)) (x : nat) : P x
  := match x with
     | 0 => o
     | S n' => s n'
     end.
Lemma nat_case_plus (a a' : nat) (b b' : nat -> nat) (x : nat)
  : (nat_case _ a b x + nat_case _ a' b' x)%nat = nat_case _ (a + a')%nat (fun x => b x + b' x)%nat x.
Proof. destruct x; reflexivity. Qed.
Lemma nat_case_plus_const (a : nat) (b : nat -> nat) (x : nat) (y : nat)
  : (nat_case _ a b x + y)%nat = nat_case _ (a + y)%nat (fun x => b x + y)%nat x.
Proof. destruct x; reflexivity. Qed.
Global Instance nat_case_Proper {P} : Proper (eq ==> forall_relation (fun _ => eq) ==> forall_relation (fun _ => eq)) (nat_case P).
Proof.
  unfold forall_relation; intros x x' ? f f' Hf [|a]; unfold nat_case; auto.
Qed.
Global Instance nat_case_Proper' {P} : Proper (eq ==> pointwise_relation _ eq ==> forall_relation (fun _ => eq)) (nat_case (fun _ => P)).
Proof.
  unfold forall_relation, pointwise_relation; intros x x' ? f f' Hf [|a]; unfold nat_case; auto.
Qed.
Global Instance nat_case_Proper'' {P} {x} : Proper (pointwise_relation _ eq ==> eq ==> eq) (nat_case (fun _ => P) x).
Proof.
  intros ??? a b ?; subst b; destruct a; simpl; auto.
Qed.
Global Instance nat_case_Proper''' {P} {x} : Proper (forall_relation (fun _ => eq) ==> eq ==> eq) (nat_case (fun _ => P) x).
Proof.
  intros ??? a b ?; subst b; destruct a; simpl; auto.
Qed.
Ltac reduce :=
  let solve_tac := unfold nat_case; repeat match goal with |- context[match ?x with O => _ | _ => _ end] => destruct x end; reflexivity in
  repeat match goal with
         | [ H : context[if ?x =? 4 then ?a else ?b] |- _ ]
           => replace (if x =? 4 then a else b) with (match x with 4 => a | _ => b end) in H by solve_tac
         | [ H : context[if ?x =? 2 then ?a else ?b] |- _ ]
           => replace (if x =? 2 then a else b) with (match x with 2 => a | _ => b end) in H by solve_tac
         | [ H : context[if ?x <=? 4 then ?a else ?b] |- _ ]
           => replace (if x <=? 4 then a else b) with (match x with 0 | 1 | 2 | 3 | 4 => a | _ => b end) in H by solve_tac
         | [ H : context G[match ?x as x' in nat return @?T x' with O => ?a | S n => @?s n end] |- _ ]
           => let G' := context G[@nat_case T a s x] in
              change G' in H
         | [ H : context G[fun v => match @?x v as x' in nat return @?T x' with O => ?a | S n => @?s n end] |- _ ]
           => let G' := context G[fun v => @nat_case T a s (x v)] in
              change G' in H; cbv beta in *
         | [ H : context[(nat_case _ _ _ _ + nat_case _ _ _ _)%nat] |- _ ]
           => progress repeat setoid_rewrite nat_case_plus in H; simpl in H
         | [ H : context[(nat_case _ _ _ _ + _)%nat] |- _ ]
           => progress repeat setoid_rewrite nat_case_plus_const in H; simpl in H
         end.
Lemma ex : forall x, (f + g + h) x = match x with
                                     | 0 => 3
                                     | 1 => 3
                                     | 2 => 5
                                     | 3 => 3
                                     | 4 => 4
                                     | _ => 0
                                     end.
Proof.
  intro x; cbv [add_f].
  save (f x) f' Hf; save (g x) g' Hg; save (h x) h' Hh; save (f' + g')%nat fg Hfg; save (fg + h')%nat fgh Hfgh.
  cbv [f g] in *.
  subst f' g'; reduce.
  cbv [h] in *; reduce.
  subst fg h'; reduce.
  subst fgh.
  unfold nat_case.
  reflexivity.
Qed.


Q:

Access CGImageRef underlying bytes and modify?

I am working on an OSX app that does some pixel-level image manipulation.  I am using the following code to access the pixel color components (RGBA) as regular bytes cast as uint8 pointers.
NSImage *image = self.iv.image;
NSRect imageRect = NSMakeRect(0, 0, image.size.width, image.size.height);
CGImageRef cgImage = [image CGImageForProposedRect:&imageRect context:NULL hints:nil];
NSData *data = (NSData *)CFBridgingRelease(CGDataProviderCopyData(CGImageGetDataProvider(cgImage)));
   uint8 *pixels = (uint8 *)[data bytes];

At this point I apply some byte level changes in:
 for (int i = 0; i < [data length]; i += 4) { ... }

Changing this region of memory does not appear to have any effect on the original CGImageRef (which is at the time displayed in an NSImageView).  I must do the following to see the image update accordingly:
 CGImageRef newImageRef = CGImageCreate (width,
                                           height,
                                           bitsPerComponent,
                                           bitsPerPixel,
                                           bytesPerRow,
                                           colorspace,
                                           bitmapInfo,
                                           provider,
                                           NULL,
                                           false,
                                           kCGRenderingIntentDefault);

   NSSize size = NSMakeSize(CGImageGetWidth(newImageRef),
                            CGImageGetHeight(newImageRef));

   NSImage * newIm = [[NSImage alloc] initWithCGImage:newImageRef size:size];

   self.iv.image = newIm;

In other words, the bytes I get back to modify are just a copy of the original bytes, presumably as a result of CGDataProviderCopyData(CGImageGetDataProvider(cgImage).
My question is as follows. Is there is a way to access the underlying bytes of the CGImageRef directly such that when I modify them the image is updated on screen as I manipulate them?

A:

No. CGImages are immutable. You can't change them once they are created.
In your code, the call to [data bytes] gives a pointer to const void. You have cast away the const which gets it to compile without warnings, but that's a violation of the design contract. Writing to the buffer backing the data provider is not legal and not guaranteed to work, even if you create a new CGImage from it.
I will also point out that the format of the data in the buffer may be quite different from what you were expecting. There's no good reason to expect the data to be 32 bits per pixel, RGBA vs. BGRA vs. ARGB vs. …, or anything.
I strong recommend that you read the sections about the various image objects in the 10.6 AppKit release notes. Scroll down to "NSImage, CGImage, and CoreGraphics impedance matching" and read through all of the following image-related sections until you hit "NSComboBox". The section "NSBitmapImageRep: CoreGraphics impedance matching and performance notes" is one of the more important for your purposes.
Beyond what that says, you could just maintain a pixel buffer that you allocated yourself in whatever format you prefer. Then, when you want a CGImage of that, create it from the buffer, draw with it, and discard it. Any pixel manipulations would be done on that buffer.


Q:

How to release a string created inside a method?

I have declared a local string inside the method. I am releasing the string inside the same method. I found my code crashing if  release that object. If I don't release the string, code runs successfully.
I have called that method in viewdidappear so that method is called while pushing and poping. Nothing gets printed in the console. Here is my code
-(void)appendString{
NSString  *locStr = [[NSString alloc] initWithString:@""];
for (int i=0;i<[result count]; i++)
{
locStr=[locStr stringByAppendingFormat:@"%@",[result objectAtIndex:i]];
}
[str setString:locStr];
[locStr release];
}

I am calling the "appendString" method from "viewDidAppear"."str" is a NSMutable string declared in .h class.How should I release the "locStr".
What went wrong in my code? This isn't the normal way to release it?

A:

Try this:
-(void)appendString{
//stringWithString returns an autorelease object
//so you don't need to worry about its memory management
NSString  *locStr = [NSString stringWithString:@""];
for (int i=0;i<[result count]; i++)
{
//if your locstr is created by initWithString instead,
//the following line is going to cause memory leak
locStr=[locStr stringByAppendingFormat:@"%@",[result objectAtIndex:i]];
}
[str setString:locStr];
//[locStr release];
}

And make sure that the string property in your str instance is set to retain


Q:

Exception "No such Table : Table_Name"

My code raises an exception:

No such Table : Table_Name

I spent a whole day trying to resolve it but had no success so far.
I used SQLite3.exe to create the database, create the table person and insert the data. When I query the content of table person it shows me the positive result.
Unfortunately, when I use this code to show the table content the exception is raised.
This is the code:
procedure TForm1.connectButtonClick(Sender: TObject);
begin
  // Set the path of your database file.
  // Replace "full_path_to_your_database_file" with the absolute path
  // to your SQLite database file.
  SQLConnection1.Params.Add('Database=D:\testdb.db');
  try
    // Establish the connection.
    SQLConnection1.Connected := true;
    executeButton.Enabled := true;
    outputMemo.Text := 'Connection established!';
  except
    on E: EDatabaseError do
      ShowMessage('Exception raised with message' + E.Message);
  end;
end;

procedure TForm1.executeButtonClick(Sender: TObject);
var
  results: TDataSet;
  query: String;
begin
  outputMemo.Clear;
  // A random query
  query := 'SELECT * FROM person;';

  try
  // Execute the query on the database.
    SQLConnection1.Execute(query, nil, results);
  except
    on E: Exception do
      outputMemo.Text := 'Exception raised with message: ' + E.Message;
  end;
  // Show the results of the query in a TMemo control.
  ShowSelectResults(results);
end;

procedure TForm3.ShowSelectResults(results: TDataSet);
var
  names: TStringList;
  i: Integer;
  currentField: TField;
  currentLine: string;
begin
  if not results.IsEmpty then
  begin
    results.First;
    names := TStringList.Create;
    results.GetFieldNames(names);
    while not results.Eof do
    begin
      currentLine := '';
      for i := 0 to names.Count - 1 do
      begin
        currentField := results.FieldByName(names[i]);
        currentLine := currentLine + ' ' + currentField.AsString;
      end;
      outputMemo.Lines.Add(currentLine);
      results.Next;
    end;
  end;
end;

A:

Either your database and/or table is corrupt or there is a mistake in some part of your code which is executing but you are not showing us.
The following code, which creates and populates a new table, runs perfectly on Delphi Seattle and produces the expected result, namely one data row in outputMemo.
I suggest you close & restart Delphi and close any other app which might be using the same Sqlite3.Dll as DB does, before trying it.
(I have moved outputMemo and ShowSelectResults to Form1)
procedure TForm1.executeButtonClick(Sender: TObject);
var
  results: TDataSet;
  query: String;
begin
  outputMemo.Clear;

  query := 'CREATE TABLE TESTTABLE (ID BIGINT, NAME NVARCHAR(80) )';
  SQLConnection1.Execute(query, nil, Nil);

  query := 'INSERT INTO TESTTABLE(ID, NAME) VALUES(1, ''One'')';
  SQLConnection1.Execute(query, nil, Nil);

  query := 'SELECT * FROM TESTTABLE';

  try
  // Execute the query on the database.
    SQLConnection1.Execute(query, nil, results);

  except
    on E: Exception do
      outputMemo.Text := 'Exception raised with message: ' + E.Message;
  end;
  // Show the results of the query in a TMemo control.
  ShowSelectResults(results);

  query := 'DROP TABLE TESTTABLE';
  SQLConnection1.Execute(query, nil, Nil);

end;

procedure TForm1.ShowSelectResults(results: TDataSet);
var
  names: TStringList;
  i: Integer;
  currentField: TField;
  currentLine: string;
begin
  if not results.IsEmpty then
  begin
    results.First;
    names := TStringList.Create;
    try
      results.GetFieldNames(names);
      while not results.Eof do
      begin
        currentLine := '';
        for i := 0 to names.Count - 1 do
        begin
          currentField := results.FieldByName(names[i]);
          currentLine := currentLine + ' ' + currentField.AsString;
        end;
        outputMemo.Lines.Add(currentLine);
        results.Next;
      end;
    finally
      names.Free;
    end;
  end;
end;


Q:

Creating a Django form from a dictionary of objects

I feel like this must be really simple, but after a couple of days of trying I'm officially clueless.
I have a dictionary where the keys are objects and the values are lists of objects. Here's how I want to use that info to construct a form:
for object in dictionary:
    name_of_field = object.slug
    name_of_field = forms.ModelMultipleChoiceField(widgets=forms.CheckboxSelectMultiple, queryset=dictionary[object])

Of course, just putting name_of_field in there twice doesn't work to generate dynamically named fields. What this actually does is create a single field called "name_of_field" using the final object it iterates over. I wish it would create a field for every key in the dictionary, named using the key object's slug and with a choice set of that key's values.
Is there a way to loop through this dictionary and create the form fields I want? I feel like the answer lies in superclassing __init__, but I still can't wrap my head around how to get multiple fields with different names.

A:

You don't say where you are using this code. You should be putting it into the form's __init__ method, from where you can reference self.fields:
class DynamicForm(forms.Form):
    def __init__(self, *args, **kwargs):
        dynamic_fields = kwargs.pop('dynamic_fields')
        super(DynamicForm, self).__init__(*args, **kwargs)
        for key, value in dynamic_fields:
            self.fields[key.slug] = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=value)


Q:

How can you deserialize a JSON array containing different types in .Net?

I'm trying to deserialize a JSON object array in C#. The array represents a row of a table, mainly consisting of plain strings. However, one or more of the items in the array may not be a string but infact a JSON object in itself, e.g.
"rows":[[{"date":"20140521","category":"one"},"data","moredata","evenmoredata"],...]

or on a different response from the server, the order may be different
"rows":[["data","moredata",{"date":"20140521","category":"one"},"evenmoredata"],...]

I'm trying to just treat this as a list of objects, with a known type called RowObject below:
[DataContract]
[KnownType(typeof(RowObject))]
public class Table
{
    // other members to deserialize

    [DataMember(Name = "rows")]
    public List<List<object>> Rows { get; set; }
}

[DataContract]
public class RowObject
{
    [DataMember(Name = "date")]
    public DateTime date { get; set; }

    [DataMember(Name = "category")]
    public string category { get; set; }
}

This approach kind of worked in that the plain strings in the row were deserialized, however the RowObjects do not seem to be recognised even though I have tried to put them down as a KnownType. When I look at my deserialized List<object> Row, the RowObject just seems to be a blank object shown as {object} in the debugger.
I've managed to do this with known types and derived types elsewhere in the project but this problem dealing with plain strings has got me stuck. I've had a look at this question which seems pretty similar, but my problem with this answer is that I don't know which elements in the list are going to be the complex type. Also, I'm just using the .Net DataContractJsonSerializer throughout the project so would like to avoid third party libraries if at all possible.
Is it possible to deserialize a JSON array of different types like this?

A:

Set EmitTypeInformation in DataContractJsonSerializerSettings to EmitTypeInformation.Always on the server side. That way you will get information about the types of your objexts, inside the json string.


Q:

Las extendedProps sólo se muestran en la vista de mes en fullcalendar

Necesito mostrar algunos datos con extendedProps, pero cuando trato de mostrarlo con info.event.extendedProps.description en timeGridWeek o timeGridDay no lo hace (pone "undefined"), sólo lo muestra en dayGridMonth.
Los eventos los cargo con dos php que me traen correctamente los eventos, ya que se muestran correctamente en el calendar. Ya he probado muchas cosas y no termino de dar con la tecla...
Pego el código que tengo para el calendar:
<script>
      document.addEventListener('DOMContentLoaded', function() {
        var calendarEl = document.getElementById('calendar');

        var calendar = new FullCalendar.Calendar(calendarEl, {
          plugins: [ 'dayGrid', 'interaction', 'bootstrap', 'timeGrid', 'rrule' ],
          height: 'parent',
          header: {
            left: 'prev,next today',
            center: 'title',
            right: 'timeGridDay,timeGridWeek,dayGridMonth'
          },
          titleFormat: {
            year: 'numeric',
            month: 'long',
            day: '2-digit'
          },
          defaultView: 'timeGridWeek',
          themeSystem: 'bootstrap',
          selectable: true,
          editable: true,
          navLinks: true,
          weekNumbers: true,
          nowIndicator: true,
          locale: 'es',
          minTime: '08:00:00',
          maxTime: '22:00:00',
          weekends: false,
          eventOrder : 'color',
          eventSources: [
            'carga_citas.php',
            'carga_sesiones.php'
          ],
          eventClick: function(info) {
            alert(info.event.extendedProps.description);
          }
        });

        calendar.render();
      });
    </script>

Gracias por vuestras respuestas.
EDITO para añadir:
Los datos los mando codificados con json_encode, si hago print_r:
Array
(
    [0] => Array
        (
            [id] => 30939
            [title] => David Fernández Fernández
            [start] => 2019-11-26 00:00:00
            [end] => 2019-11-26 01:00:00
            [color] => #A47AE2
            [textColor] => #000000
            [description] => 3
        )

    [1] => Array
        (
            [id] => 30963
            [title] => Pedro Fernández Fernández
            [start] => 2019-11-27 00:00:00
            [end] => 2019-11-27 01:00:00
            [color] => #A47AE2
            [textColor] => #000000
            [description] => 3
        )
)

Hay cientos, esto es un extracto. Espero que ayude.

A:

Finalmente el problema lo tenía en la respuesta de uno de los evenSources, precisamente en el que traía los eventos más recientes, que eran los que yo estaba comprobando. Al mirar en el modo mes, los primeros que me aparecían eran de primeros de mes, que los traía el otro archivo, por lo que no daba ningún problema y me hacía pensar que el problema estaba en el tipo de vista. Esto es lo que tenía en ese archivo:
<?php
require_once('conexionPDO.php');
header('Content-Type: application/json');

$db=conectar();
$consulta="SELECT citas_prox.id as id, paciente.nombre as title, citas_prox.fecha as start, ADDTIME(citas_prox.fecha,'01:00:00') as end, usuarios.color as color, usuarios.letra_color as textColor FROM citas_prox, paciente, usuarios WHERE citas_prox.paciente=paciente.numero AND citas_prox.usuario=usuarios.id";
$result=$db->prepare($consulta);
$result->execute();

$resultado=$result->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($resultado);
?>

Y esto el archivo correcto:
<?php
require_once('conexionPDO.php');
header('Content-Type: application/json');

$db=conectar();
$consulta="SELECT citas_prox.id as id, paciente.nombre as title, citas_prox.fecha as start, ADDTIME(citas_prox.fecha,'01:00:00') as end, usuarios.color as color, usuarios.letra_color as textColor, citas_prox.usuario as description FROM citas_prox, paciente, usuarios WHERE citas_prox.paciente=paciente.numero AND citas_prox.usuario=usuarios.id";
$result=$db->prepare($consulta);
$result->execute();

$resultado=$result->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($resultado);
?>

Esto: citas_prox.usuario as description estaba bien puesto en el otro archivo, en este se me había olvidado... Muchas gracias por la pista a  Paulo Urbano Rivera


Q:

Proof of Double Expectation of a Conditional Expectation

There is a proof of
$$
E(E(Y|x)) = E(Y)
$$
$Proof:$
WLOG, suppose X and Y are two continuous random variables.
Let $E(Y|x)=m(x) =\int_{-\infty}^{\infty} yf(y|x)\, dy$
Then
$$
E(E(Y|x))=E(m(x))= \int_{-\infty}^{\infty} m(x) f(x) \, dx =\int_{-\infty}^{\infty} \Big(\int_{-\infty}^{\infty} yf(y|x)\, dy\Big) f(x)\, dx
$$
$$
=\int_{-\infty}^{\infty} \int_{-\infty}^{\infty} y\frac{f(x,y)}{f(x)}f(x)\, dy \, dx
=\int_{-\infty}^{\infty} \int_{-\infty}^{\infty} yf(x,y)\, dy \, dx = E(Y)
$$
My question is why $$\int_{-\infty}^{\infty} \int_{-\infty}^{\infty} yf(x,y)\, dy \, dx=\int_{-\infty}^{\infty} yf(y)\, dy=E(Y)$$

A:

Change the order of integration and use that the marginal density can be obtained via
$$
f(y)=\int_{-\infty}^\infty f(x,y)\,\mathrm dx.
$$
The "WLOG" statement is however a bit odd, since there is lost a lot of generality by assuming $(X,Y)$ to be continuous (which by the way is different from assuming that $X$ and $Y$ marginally are continuous random variables).


Q:

Shortest path from single source to single destination in a graph

My graph contains no such edges which connect a vertex to itself. There is only one edge between two vertices. From Wikipedia i got to know about some algorithm which are used for calculating shortest path based on the given conditions. One of the most famous algorithm is Dijkstra's algorithm, which finds a shortest paths from source vertex to all other vertices in the graph.
But by using Dijkstra's algorithm, i am unnecessary exploring all the vertices, however my goal is just to find shortest path from single source to single destination. Which strategy should i use here? So that i need not to explore all other vertices.
One of my approach is to use bidirectional bfs. By bidirectional bfs i mean to apply two bfs one from source node, another one from destination node. As soon as for the first time when i find any same child in both tree,i can stop both bfs .Now the path from source to that child union path from child to destination would be my shortest path from source to destination.
But out of all the approaches described by Wikipedia and  bidirectional bfs, which one suits best for my graph?

A:

It depends if there's any apparent heuristic function that you could use or if you don't have any further usable information about your graph.
Your options are:

BFS: in general case or if you don't care about computation time that much.
Dijkstra (Dijkstra "is" BFS with priority queue): if your edges have weights/prices (non negative) and you care about CPU time.
A* (A* "is" Dijkstra with heuristic function - e.g. distance on a city map): if you want it to be really fast in average case, but you have to provide good heuristic function.

For some graph problems it may be possible to use Dynamic programming or other algorithmic tools. It depends on a situation. Further information can be found in tutorials from http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=alg_index ...


Q:

What specific modules are included in Drupal Commerce Kickstart?

Drupal Commerce Kickstart is a project built on Drupal Commerce that bundles Drupal 7, Commerce and a host of additional modules with some preset settings to speed up Commerce-based development.
I'm trying to find out what specific modules are actually included in this bundle, but all I can find is uninformative advert pages like this.
There's nothing about what exactly is included in the Kickstart documention. The closest I can find elsewhere online is this list of modules not included.
Is there any simple list of the modules that are bundled in the Commerce Kickstart package?

A:

Here's the actual makefile that builds the latest version of Commerce Kickstart.
http://cgit.drupalcode.org/commerce_kickstart/tree/drupal-org.make
Within it, you can find every module that is built in. It includes the machine name of the project and the version number used.
For example, the entry "projects[ctools][version] = 1.9" shows you the machine name ctools, which is the Chaos Tools module, and the version is 1.9. You can look up the modules on drupal.org by substituting the machine name into the following URL: http://drupal.org/project/MACHINENAME.


Q:

How to create multiple vertex in SAP HANA Graph

I'm trying to create 2 (multiple) vertex in SAP HANA like -
Create two table for vertex ITEM and DATASET
CREATE COLUMN TABLE "GREEK_MYTHOLOGY"."ITEM" (
"ITEM_ID" VARCHAR(100) PRIMARY KEY,
"ITEM_NAME" VARCHAR(100)
);

CREATE COLUMN TABLE "GREEK_MYTHOLOGY"."DATASET" (
"DATASET_ID" VARCHAR(100) PRIMARY KEY,
"DATASET_NAME" VARCHAR(100)
);

And creating edge as REFERENCES
CREATE COLUMN TABLE "GREEK_MYTHOLOGY"."REFERENCES" (
"REF_ID" INT UNIQUE NOT NULL,
"SOURCE" VARCHAR(100) NOT NULL
REFERENCES "GREEK_MYTHOLOGY"."ITEM" ("ITEM_ID")
ON UPDATE CASCADE ON DELETE CASCADE,
"TARGET" VARCHAR(100) NOT NULL
REFERENCES "GREEK_MYTHOLOGY"."DATASET" ("DATASET_ID")
ON UPDATE CASCADE ON DELETE CASCADE,
"TYPE" VARCHAR(100)
);

Now i would like to connect both vertex (ITEM and DATASET) with edge  REFERENCES like below
CREATE GRAPH WORKSPACE "GREEK_MYTHOLOGY"."GRAPH"
EDGE TABLE "GREEK_MYTHOLOGY"."DATASET"
SOURCE COLUMN "SOURCE"
TARGET COLUMN "TARGET"
VERTEX TABLE "GREEK_MYTHOLOGY"."ITEM" KEY COLUMN "ITEM_ID"
VERTEX TABLE "GREEK_MYTHOLOGY"."DATASET"KEY COLUMN "DATASET_ID"
KEY COLUMN "REF_ID";

But it throws exception at line
VERTEX TABLE "GREEK_MYTHOLOGY"."DATASET"KEY COLUMN "DATASET_ID"
sql syntax error: incorrect syntax near "VERTEX": line 6 col 1 (at pos 200)

Is it possible to create multiple vertex in SAP HANA graph ? If yes then what is the right way to do this.

A:

There's a misunderstanding here. The REFERENCES clause in the CREATE TABLE statement has nothing to do with the graph structure you want to represent.
Instead, it defines a foreign key constraint between the two tables.
The CREATE GRAPH WORKSPACE command only accepts one EDGE TABLE and one VERTEX TABLE as parameters.
However, you can also pass in synonyms or views here.
That way, you could create a view "ALL_ITEMS" like this:
CREATE VIEW "GREEK_MYTHOLOGY"."ALL_ITEMS" as
  SELECT "ITEM_ID" as "ID", "ITEM_NAME" as "NAME"  FROM "GREEK_MYTHOLOGY"."ITEM"
  UNION
  SELECT "DATASET_ID" as "ID", "DATASET_NAME" as "NAME" FROM "GREEK_MYTHOLOGY"."DATASET";

and then reference this view:
CREATE GRAPH WORKSPACE "GREEK_MYTHOLOGY"."GRAPH"
       EDGE TABLE "GREEK_MYTHOLOGY"."DATASET"
            SOURCE COLUMN "SOURCE"
            TARGET COLUMN "TARGET"
       VERTEX TABLE "GREEK_MYTHOLOGY"."ALL_ITEMS"
            KEY COLUMN "NAME";

Using this approach is possible, but you now have to make sure that the "NAME" values are unique and not NULL across both tables.


Q:

How to fit the text inputs in div using Bootstrap?

I am creating a form using Bootstrap and the text input widths are too long. I tried to set the width = 35% of class form-control in bootstrap.css and it looks ok, but when I resized the screen it overlapped the other
. As of now I changed it back to 100%. And it is too long and it overlap the other
.
Here is my code:

LOGIN

                                <form role="form">

REGISTER

Please login to take advantage of promotions and benefits reserved to registered users.

EMAIL ADDRESS*

                                        <input type="text" class="form-control" />

PASSWORD*

                                        <input type="password" class="form-control" />

                                        <input type="checkbox" style="margin-top: 20px" /> Remember me next time

                                            <button type="button" class="btn btn-default" onclick="location.href='register.html'" >REGISTER NOW</button>

                                            Forgot your password?

                                </form>

NEW USER

Register now and enjoy the benefits of My Account. Only registered users can:

- Access to your personal information through My Account

- Use the Wish List to save their favorite products

- Complete the checkout process more quickly

                        <input type="button" value="REGISTER NOW"  class="register-button" onclick="location.href='register.html'" />

A:

Change the class of the div tag to col-sm-6. This should do the trick.

        <form role="form">

Check out the demo here.


Q:

If a page does not exist, include a different page?

I'm setting up a website for a client where they want several different sections, like so:
Regular Site (/)
  - Section 1 (/section_1/)
  - Section 2 (/section_2/)
     ...
  - Section X

The regular site will have all of the main content, but I want to be able to override certain pages if they exist in the specified section.
Let's say the user visits domain.com/section_1/features. If a /section_1/features page exists, I would like to display that; however, if the page does not exist, I would like it to display /features without redirecting or changing the URL in the address bar. It should be completely seamless and behind the scenes.
I think I need to add a function to the parse_request hook, something like:
function check_section_page( &$wp ) {
    $requested_path = $wp->request;

    if ( ! get_page_by_path($requested_path) ) {
        $new_requested_path = preg_replace("/^(.*?)\//", "", $requested_path);
        // do something here to make it read $new_requested_path
    }
}

add_filter("parse_request", "check_section_page");

It runs the function properly, and echoing out $new_requested_path shows that it does have the new required page. I've been fighting with this for about 2 hours and my head's done in. Help?

A:

I managed to solve the problem. Here's how to do it, in case anyone else ever needs this solution.
** Updated Mar 10 3:30am EST **
The previous function that I had here was displaying the page properly, but was returning a 404 error code. I've replaced the bad code example with a working one that does not return a 404.
function check_section_page( $posts ) {

    if (is_admin()) { return $posts; }

    global $wp, $wp_query;

    $requested_path = $wp->request;

    if ( $requested_path == "" ) { return $posts; }

    preg_match("/^([a-z\-]+)\//", $requested_path, $matches);

    if ( count($matches) > 1 ) {
        if ( get_page_by_path( $matches[1] ) ) { $section = $matches[1]; }
    }

    $wp_query->set("saleslink_section", $section);

    $this_page = get_page_by_path( $requested_path );
    $new_requested_path = preg_replace("/^(.*?)\//", "", $requested_path);
    $requested_page = get_page_by_path($new_requested_path);

    if ( $requested_page->ID and ! $this_page->ID ) {

        $posts = NULL;

        $posts[] = $requested_page;
        $wp_query->is_page = true;
        $wp_query->is_singular = true;
        $wp_query->is_home = false;
        $wp_query->is_archive = false;
        $wp_query->is_category = false;
        unset($wp_query->query["error"]);
        $wp_query->query_vars["error"]="";
        $wp_query->is_404=false;

    }

    return $posts;

}

remove_filter('template_redirect','redirect_canonical');
add_filter("the_posts", "check_section_page");

The remove_filter line will turn off the automatic-url-guessing-redirect behaviour of Wordpress, when a requested URL does not exist and a similar one does and it redirects to the similar URL.


Q:

Docker run a container with static html file

Could I run a container with only static html file and use a Nginx container to proxy the request to it? My idea is use an Nginx container to proxy the request to multiple website but those websites only contain static html file, is that possible?
I already build a docker image with static file

FROM alpine:3.7
COPY /build/ /srv/www/web/

there is only an index.html in the build folder then I run this image then got  status with Exited (0)

A:

When you run a docker image, it will run a single process - see CMD instruction in the Dockerfile documentation. Your static file container does not have any process to run, so it will exit immediately.
You can use the nginx image to serve static files - search for nginx on dockerhub: the howto section of that image will tell you how. (Basically either mount the static files as a volume, or create a derivative image by adding the files to it)
edit
To serve multiple sites, you have to configure nginx. The nginx docker image documentation "complex configuration" section shows an example how to mount a custom nginx.conf. You have to read the nginx documentation how to set up multiple sites.
So from docker perspective you only need the nginx image. In the simplest case all your sites files are under a single directory which you have to mount as a docker volume. And you need to mount your custom nginx.conf.
edit2
However, if you only want to run nginx on one server, then it is probably not worth to use docker. Just install nginx on the server.


Q:

How to make a fetch API in Javascript to be modular

I'm building an APP in React where I would like to consume an API for comments which allows crud rules. What I'm trying to build is a modular fetch that is implemented once and all the CRUD rules use the same fetch in one place where the base URL of the API is defined. Via the CRUD functionalities, I will just pass the endpoint I need and the related params and method. That will make life easier to use it around the APP when need it.
What I built first was my BaseAPI functionality as follow:
import { COMMENT_USER, COMMENT_PASS } from "./ConstAPI";

export const createCommentAPIQUery = urlGenerator => async (...params) => {
  try {
    const url = urlGenerator(...params);
    const token = btoa(COMMENT_USER + ":" + COMMENT_PASS);
    const credentials = {
      method: "GET",
      headers: new Headers({
        Authorization: "Basic " + token,
        "Content-Type": "application/json",
        Accept: "application/json"
      })
    };
    const response = await fetch(url, credentials);
    const json = response.json();
    return {
      success: true,
      ...json
    };
  } catch {
    return {
      success: false,
      result: [],
      message:
        "There is an issue to get data from server. Please try again later."
    };
  }
};

The issue above is that that will work when I use the GET but for the other CRUD will not as I need to pass a method and in case of a POST and PUT also stringify(). So the following CRUD functionalities were my attempt but as you will see that works only for the GET method and I need to find a solution for the rest of the methods:
import { createCommentAPIQUery } from "./BaseCommentAPI";
import { COMMENT_URL } from "./ConstAPI";

export const getAllComments = createCommentAPIQUery(
  asin => `${COMMENT_URL}/comments/${asin}`
);

export const addComment = createCommentAPIQUery(body => {
  `${COMMENT_URL}/comments`, (this.credentials.method = "POST");
  this.credentials.body = JSON.stringify(body);
});

export const updateComment = createCommentAPIQUery((id, body) => {
  `${COMMENT_URL}/comments/${id}`, (this.credentials.method = "PUT");
  this.credentials.body = JSON.stringify(body);
});

export const deleteComment = createCommentAPIQUery(id => {
  `${COMMENT_URL}/comments/${id}`, (this.credentials.method = "DELETE");
});

What I need is a good idea to make that work as I thought about it but actually I stack in it.
As it is now is generating an error as:
Expected an assignment or function call and instead saw an expression  no-unused-expressions

So I need to figure out a good way to complete this idea and to avoid issues and bugs.

A:

Pass your body and method as arguments not part of your url generator code, method with the outer function and body with the inner
export const createCommentAPIQUery = (urlGenerator,method='GET') => async (body,...params) => {
  try {
    const url = urlGenerator(...params);
    const token = btoa(COMMENT_USER + ":" + COMMENT_PASS);
    const credentials = {
      //use passed method and body accordingly
      method: method,
      body:body,
      headers: new Headers({
        Authorization: "Basic " + token,
        "Content-Type": "application/json",
        Accept: "application/json"
      })
    };

Example use:
export const getAllComments = createCommentAPIQUery((asin)=>{
  return `${COMMENT_URL}/comments/${asin}`;
});
//calling, pass null as no body is needed, and 'theAsin' will become part of 'params'
getAllComments(null,theAsin).then(...);

export const addComment = createCommentAPIQUery(()=>{
  return `${COMMENT_URL}/comments`;
},"POST");
//calling, pass in body, and no other arguments are needed for 'params'
addComment(JSON.stringify(body)).then(...);

export const updateComment = createCommentAPIQUery((id)=>{
  return `${COMMENT_URL}/comments/${id}`;
},"PUT");
//calling, pass in body, and 'theId' will end up as part of 'params'
updateComments(JSON.stringify(body),theId);


Q:

Bash jobs in the background

Is there a way to allow a background job in bash to modify variables? for ex:
[bash]# a=1
[bash]# a=2 &
[1] 14533
[bash]# echo $a
1

I'd like the value of a to be 2 not 1

A:

Variables can't be sent back to a parent process from a child, so what you're trying to do is impossible.  It's the same reason that cd has to be a shell builtin rather than an executable in its own right.  If it were an executable, it would run, change the directory, and then exit, leaving you back in the shell which hasn't had its directory changed.


Q:

error CS0234: Microsoft.Azure.EventHubs assembly/metadata file missing in azure function 2.0

I am trying to create EventHub trigger azure function with many as cardinality for event message batching.
Following is code in run.csx
#r "Microsoft.Azure.EventHubs"

using System.Text;
using System;
using Microsoft.ServiceBus.Messaging;
using Microsoft.Azure.EventHubs;

public static void Run(EventData[] eventMessage, ILogger logger)
{
    logger.LogInformation("Event: {Encoding.UTF8.GetString(eventMessage.Body)}");
    logger.LogInformation("EnqueuedTimeUtc={eventMessage.SystemProperties.EnqueuedTimeUtc}");
    logger.LogInformation("SequenceNumber={eventMessage.SystemProperties.SequenceNumber}");
    logger.LogInformation("Offset={eventMessage.SystemProperties.Offset}");

}

along runtime config host.json is
{
  "version": "2.0"
}

and function's config file function.json
{
  "bindings": [
    {
    "type": "eventHubTrigger",
    "name": "eventMessage",
    "direction": "in",
    "eventHubName": "myEventHub",
    "connection": "consumer_hub",
    "consumerGroup": "$Default",
    "cardinality": "many"
    }
  ]
}

After getting error on compilation regarding assemply is missing
2018-11-27T09:36:54.325 [Error] run.csx(1,1): error CS0006: Metadata file 'Microsoft.Azure.EventHubs' could not be found
2018-11-27T09:36:54.389 [Error] run.csx(5,17): error CS0234: The type or namespace name 'ServiceBus' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?)
2018-11-27T09:36:54.425 [Error] run.csx(6,23): error CS0234: The type or namespace name 'EventHubs' does not exist in the namespace 'Microsoft.Azure' (are you missing an assembly reference?)
2018-11-27T09:36:54.522 [Error] run.csx(9,24): error CS0246: The type or namespace name 'EventData' could not be found (are you missing a using directive or an assembly reference?)

Could you please help me why dependency is not available in azure function? Even azure documentation has reference for this.That means this assemplies should already be present in runtime environment provided by azure.
https://docs.microsoft.com/en-us/azure/azure-functions/functions-bindings-event-hubs

A:

The doc is somehow inconsistent, have a try at code below.
#r "../bin/Microsoft.Azure.EventHubs.dll"

using System.Text;
using System;
using Microsoft.Azure.EventHubs;

public static void Run(EventData[] eventMessage, ILogger logger)
{
    foreach (var message in eventMessage)
    {
        logger.LogInformation($"Event: {Encoding.UTF8.GetString(message.Body)}");
        logger.LogInformation($"EnqueuedTimeUtc={message.SystemProperties.EnqueuedTimeUtc}");
        logger.LogInformation($"SequenceNumber={message.SystemProperties.SequenceNumber}");
        logger.LogInformation($"Offset={message.SystemProperties.Offset}");
    }
}

Besides, in function.json, cardinality is for js function to receive events in a batch. For c#, EventData[] is enough.


Q:

Ratings using HTML radio buttons and javascript

I am trying to change the default behavior of a Magento Reviews extension such that it will allow a no-vote but only if there is a review attached.  I have done enough research to know where to change the code, and I have added a "Cancel Rating" function, but it isn't working exactly as expected, and I can't seem to figure out how to check if a rating is present.
Here is the HTML part where the radios are defined.

    <?php $countRatings = count($this->getRatings()); ?>
    <?php foreach ($this->getRatings() as $_rating): ?>
        <?php if ( $countRatings > 1 ): ?>
        <div class="rating-code" id="ratings-code[<?php echo $_rating->getRatingCode(); ?>]"

        <?php endif; ?>

        <?php $sizeOptions = sizeof($_rating->getOptions()); $index=0; ?>

            <input type="radio" value="0" name="cancel[<?php echo $_rating->getId() ?>]" id="<?php echo $this->escapeHtml($_rating->getRatingCode()) ?>C<?php echo $_rating->getId() ?>" class="radio" />

        <?php foreach ($_rating->getOptions() as $_option): $index++;?>

                <input type="radio" <?php if ( $sizeOptions ==  $index ) :?><?php endif; ?>name="ratings[<?php echo $_rating->getId() ?>]" id="<?php echo $this->escapeHtml($_rating->getRatingCode()) ?>_<?php echo $_option->getValue() ?>" value="<?php echo $_option->getId() ?>" class="radio" />

       <?php endforeach; ?>

    <?php endforeach; ?>
    <input type="hidden" name="validate_rating" class="validate-rating" value="" />

And here is the JavaScript portion where validation and resetting occur
Validation.addAllThese(
[
    ['validate-rating', '<?php echo $this->__('Please select a rating above OR write your Review below') ?>', function(v) {
        var ratingContainer = document.getElementById('ratings-right');
        var ratings = ratingContainer.getElementsByClassName('rating-code');
        var values;
        var star;
        var error = 1;
        window.console&&console.log("START");
        for (r=0;r < ratings.length; r++ ) {
            values = ratings.getElementsByClassName('value');
            stars = values.getElementsByTagName('radio');
            for (s=0; s < stars.length; s++ ) {
                console.log("Checking star %d.", s);
                if (stars[s].checked == true) {
                    error = 0;
                    window.console&&console.log("Radio %d is checked.\n", s);
                    }
                }
            var review = $('review_field').length;
            window.console&&console.log("Review size %d.", review);
            if ( review > 5 ) {
                error = 0;
                window.console&&console.log("Review size (%d) greater than 5.", review);
                }
            if( error != 0 ) {
                window.console&&console.log("Failed.\n");
                return false;
            } else {
                 window.console&&console.log("Passed.\n");
                 error = 1;
                 }
            }
        return true;
        }]
    ]
);
$(".overall-raiting ul li").click(
    function(){
        var tthis = this;
        var done = 0;
        var $li = $(tthis).parent().children('li');
        $li.removeClass('active');
        $li.each(function(){
            if( done < 1 ) $(this).addClass('active');
            if ( tthis == this ) done++;
            if( done != 1 ) $(this).prop('checked', false);
            })
        if ( done > 0 ) return false;
        $(this).find('input.radio').attr('checked',true);
        }
    );

I can't get the console to consistently report values despite reading questions here about using the delete window['console']; method in firefox with firebug and Chrome.  But it appears that my .onclick function is changing all radios to unchecked, including the one that should be checked.  And as near as I can tell I am not selecting the radios in the validation portion, I've tried using the .val() and .value properties, but this code is my most recent attempt.
All I want is the radio that is clicked to stay checked with all others unchecked and to validate by determining if any is checked (including the cancel) OR if the textarea 'review_field' contains anything.
My final answer is provided below.  It is more elegant than my first solution, but I hope this helps someone in the future.

A:

First, my Javascript logging problem was resolved by an answer to this question: JavaScript console log in Magento
jQuery(document).ready(function(){
   window.console = jQuery('').hide().appendTo('body')[0].contentWindow.console;
});

This obviously only works if you are using jQuery.
The remainder of my question was resolved by implementation of a variation of bbird's code:
var rated = 0;
var ratingValue = $('#ratings-right input:radio:checked');
var reviewArea = $('#review_field');
var reviewContents = "";
for (i=0; i<reviewArea.length; i++) {
    reviewContents += reviewArea[i].value;
    }
for (i=0; i<ratingValue.length; i++) {
    if (ratingValue[i].value.length == 1 )
    rated = 1;
    }
console.log("%s", rated);
console.log("%s", reviewContents);
var isValid = rated > 0 || reviewContents != '';
console.log("%s", isValid);
return isValid;

As for the radio buttons themselves, in Magento's database, I added a zero star value with an optionId of 99999.  This rating is displayed first among the rating options and in the controller for this, I check for a value less than 9999.  This ensures that a zero star rating won't be calculated into the aggregate.
This also allowed all radio buttons to be the same class and name so there is no longer any need to programmatically uncheck anything.  Radio buttons' default behavior is that only one radio among a group with the same name is allowed to be checked.
here's the implementation of the radio buttons now:
<div <?php if ($_option->getValue() == "0" ) echo "class=\"rating-cancel\""; else echo "class=\"separate-rating-star\"" ?>>

<input type="radio" <?php if ( $sizeOptions ==  $index ) :?><?php endif; ?>name="ratings[<?php echo $_rating->getId() ?>]" id="<?php echo $this->escapeHtml($_rating->getRatingCode()) ?>_<?php echo $_option->getValue() ?>" value="<?php echo $_option->getId() ?>" class="radio" />

This way the first option, which has a value of 0, can by stylized with css to be a cancel button of some sort, and the rest will be stars.


Q:

Chef best practices - assessing/picking a cookbook

Obviously, one of the nicest things about Chef is re-using proven components via cookbooks, especially via the wrapper cookbook approach.
However, how do you choose the cookbook to wrap?  Some examples which have wasted a ton of my time.

a cookbook that has a configuration erb with hardcoded obsolete, not just deprecated, flags.  The service rejects the configuration file.  Note:  far as I understand, wrapping a corrected template erb is not trivial unless you clone & maintain the whole thing.
a cookbook that checks for Ubuntu versions up to 9.0.4, seems to do nothing above that and refers to the obsolete /etc/event.d/ directory.
cookbooks have heavy coupling to process supervision tools like runit or bluepill.  That's also a cause of headaches if your preferred tool is not on the list and you can't adjust for that.

I have tended to use supermarket.chef.io cookbooks to date, and those mostly worked.  Except its cookbook for the service I want seems un-maintained and is up for adoption.
Some ideas:

check for recent github commits/last update times.  But, what if it just works?  Then it shouldn't be updated.
stars.  but what if the stars were all issued a long time ago, while the cookbook was up-to-date?
check for github issues that aren't being closed.  Might be better.
look at recipes and attributes ahead of time.  Works better if you know the target software's setup already however.
look at the number of contributors and assess whether its a quick side project or it's likely to stay maintained.
running it and looking at the types of errors. The ones I picked above all look to me like cookbooks that are not tracking recent updates on either the OS or the program they are managing but do not have attribute-based flexibility to allow for it.
is there a rating site somewhere?  Googling that got me food cooking sites

Sorry, I realize that this question is broad in nature. But surely, if re-use is a goal of the Chef ecosystem, then judiciously picking the best community cookbook to wrap is a key ingredient for success for an end user.  Aside from any technical skills in using Chef itself.
How do you do it?  What are your heuristics?
The large number of me-too cookbooks on github makes me think that this is not a solved problem.

A:

Personally, I start by looking at the amount of downloads on supermarket and then looking at the github page directly. If the source isn't in public version control, I move along.
When looking through the code, I really just quickly skim through asking myself the following questions :
a) does this cookbook do one thing only
If it's a cookbook that installs an application, that's all I want it to do. I don't want it to mess around with the rest of the system. ( ex.: touch physical disks, ebs volumes, etc... )
b) if I use this cookbook, will it be extensible
If it's a library cookbook exposing resources, I want those resources to provide an adequate amount of control on whatever subresources it employs. I can't stand a resource that creates a template for a narrow use case, but won't let me modify the template source or template variables adequately.
If it's a recipe based cookbook, then I want most of the relevant bits to be configurable through attributes. I don't altogether mind wrapper cookbooks, but I'll be damn well happier if I can set a few attributes rather than have to much around wrapping other's resources.


Q:

Triad improvisation, Key centers

Below is a paragraph that attempts to explain what happens when non-diatonic tones are introduced into a melody. I'm copying it word for word:

While the key signature does establish the rules we must use when
playing a melody, strange things happen when we begin to improvise.
Writers and arrangers frequently incorporate non-diatonic tones,
accidentals (sharps-flats) in order to move a melody along in a
desired direction. This in turn can create chords out side the
original scale. This occurs because individual chords appear in more
than one key. The use of accidentals also creates non-diatonic harmony
which in turn requires non-diatonic chords to be used. The chords  are
created by adding a note not within the scale specified by the key
signature.

I'm confused about what the sentence: "This occurs because individual chords appear in more than one key" has to do with the rest of the paragraph. I'm unable to see the connection between this sentence and the rest of the paragraph. I'm hoping someone can show me what I'm missing here. Anyone?

A:

While the key signature does establish the rules we must use when playing a melody, strange things happen when we begin to improvise. Writers and arrangers frequently incorporate non-diatonic tones, accidentals (sharps-flats) in order to move a melody along in a desired direction. This in turn can create chords out side the original scale

It might be possible to debate some of those points, but so far, that basically sounds coherent.

This occurs because individual chords appear in more than one key.

That reasoning makes little sense to me either. It might make sense if the author was talking previously about chords that bridge two keys, but they aren't - they're already talking about being out of key at that point.
I agree with the comments that it might be a result of badly editing a longer original text. As it is, it's too damaged to learn much from. Ignore it and move on!

A:

„This occurs because individual chords appear in more than one key" ...

I think this sentence is referring to secondary dominants and borrowed chords that are introduced by improvisation, ornamentation or melodic and harmonic variations.
Such chords are often used as links to modulate  from key to key.
Ex. Bruckner Symph. 7

2nd theme (piano and rhythm reduction):

L = lead tone, P = parallel chord, R = relative chord (source: Bruckner’s Symphonies - Julian Horton)


Q:

List the movies I haven't seen

I am new to programming and have been taking the time to learn C# by reading, doing some classes online for Unity, and using Youtube. I think you learn more from doing your own projects so I decided to write a program that asked the user to enter a movie they have not seen and then store the movie titles into a list and print out the movies they listed. I had problems getting it to take multiple movies but finally figured a way to do it but I believe there is a better way to write the program. So just asking general advice to improve upon what I have already written. Thank you.
 using System;
 using System.Collections.Generic;

 namespace MovieListProjectWithSwitch
 {
  internal class Program
  {
    private static void Main(string[] args)
    {
        Console.WriteLine("Enter a movie you want to see but have not seen it");
        var movieNotSeen = new List<string>();
        movieNotSeen.Add(Console.ReadLine());

        Console.WriteLine("Do you want to enter another movie? Y/N?");

        const string answerYes = "y";
        const string answerNo = "n";
        string userInput;

        while (true)
        {
            userInput = Console.ReadLine().ToLower();

            switch (userInput)
            {
                case answerYes:
                    {
                        Console.WriteLine("Enter your next movie you wish to add to the list");
                        movieNotSeen.Add(Console.ReadLine());
                        Console.WriteLine("Now the movies on your list are:");
                        Console.WriteLine();
                        foreach (var movie in movieNotSeen)
                            Console.WriteLine(movie);
                        Console.WriteLine();

                        Console.WriteLine("Enter another movie? Y/N?");
                        var userInput2 = Console.ReadLine().ToLower();
                        if (userInput2 == "y")
                        {
                            goto case answerYes;
                        }
                        else
                        {
                            goto case answerNo;
                        }
                    }

                case answerNo:
                    {
                        Console.WriteLine("Your movies in your list are:\n");
                        foreach (var movies in movieNotSeen)
                            Console.WriteLine(movies);
                        return;
                    }
            }
        }
    }
  }
 }

A:

Welcome to codereview. Here are my suggestions:
Functional decomposition and Naming
The trickiest part of programming is to decouple your complex problem into smaller easier (sub)problems. It is easier to tackle small and focused problems than one large and vague. So, my first suggestion would be to try to find small and independent pieces of functionalities.
In your case here is one way to decompose:

Ask for a movie and store it
Ask for continuation
Print out the already gathered movies

You can directly map these to functions:
void EnterANewMovieAndStoreIt()
bool WishToContinue()
void PrintOutMovies()

Then you can compose them like this:

Ask for a movie and store it then
Print out the already gathered movies until
the consumer Answers with yes for continuation
when (s)he Answers with no then Print out already gathered movies

With that in hand your Main function will look like this:
static void Main(string[] args)
{
    do
    {
       EnterANewMovieAndStoreIt();

       PrintOutMovies();

    } while (WishToContinue());

    PrintOutMovies();
}

Store and Retrieve functionalities
Because we have separated storage and retrieval functionalities that's why they can be really small and concise functions:
private static void EnterANewMovieAndStoreIt()
{
    Console.WriteLine();
    Console.WriteLine("Please enter a movie you want to see but have not seen it yet.");
    var movieName = Console.ReadLine();
    ToBeWatchedMovies.Add(movieName);
}

private static void PrintOutMovies()
{
    Console.WriteLine();
    Console.WriteLine("Your haven't seen but to be watched movies:");
    foreach (var movie in ToBeWatchedMovies)
        Console.WriteLine(movie);
}

As you can see they rely on a shared resource called ToBeWatchedMovies. It is defined on a class level like this: static readonly List<string> ToBeWatchedMovies = new List<string>();
Error handling
Your current implementation does not handle that case when the user enters something different then Y or N. It is a good practice to assume that a userInput can be anything and handle that accordingly. In this example we can easily ask them nicely to try to provide the answer again.
So, the WishToContinue would look like this:
private static bool WishToContinue()
{
    while(true)
    {
        Console.WriteLine();
        Console.WriteLine("Do you want to enter another movie? Y/N?");
        var userInput = Console.ReadLine();

        if (string.Equals(userInput, AnswerYes, StringComparison.OrdinalIgnoreCase))
            return true;

        if (string.Equals(userInput, AnswerNo, StringComparison.OrdinalIgnoreCase))
            return false;

        Console.WriteLine($"Please provide either '{AnswerYes}' or '{AnswerNo}' ");
    }
}

Obviously this code could be further optimized but my main point here is that you should try to handle the wrong inputs as well.

Let's put everything together:
class Program
{
    static readonly List<string> ToBeWatchedMovies = new List<string>();
    const string AnswerYes = "y", AnswerNo = "n";
    static void Main(string[] args)
    {
        do
        {
           EnterANewMovieAndStoreIt();

           PrintOutMovies();

        } while (WishToContinue());

        PrintOutMovies();
    }

    private static void EnterANewMovieAndStoreIt()
    {
        Console.WriteLine();
        Console.WriteLine("Please enter a movie you want to see but have not seen it yet.");
        var movieName = Console.ReadLine();
        ToBeWatchedMovies.Add(movieName);
    }

    private static void PrintOutMovies()
    {
        Console.WriteLine();
        Console.WriteLine("Your movies in your list are:");
        foreach (var movie in ToBeWatchedMovies)
            Console.WriteLine(movie);
    }

    private static bool WishToContinue()
    {
        while(true)
        {
            Console.WriteLine();
            Console.WriteLine("Do you want to enter another movie? Y/N?");
            var userInput = Console.ReadLine();

            if (string.Equals(userInput, AnswerYes, StringComparison.OrdinalIgnoreCase))
                return true;

            if (string.Equals(userInput, AnswerNo, StringComparison.OrdinalIgnoreCase))
                return false;

            Console.WriteLine($"Please provide either '{AnswerYes}' or '{AnswerNo}' ");
        }
    }
}

I hope this helped you a bit.

A:

One of the things you might want to consider as an extension to this program is to store the list of movies in a file and read the list back from a file. Also there should be a way to delete movies once they have been seen. Any other suggestions I would give have already been given in another review.


Q:

Separate city name from address sql query

I want to separate city name from the addresses in the Data base.
addresses are in different formats
e.g
835 street no.3  Jalabad D.I. Khan ................ here city name is D.I khan
Ho. No. 102 St. No. 85  RawalPindi   ..........here city name is RawalPindi
h no.944 St. No.74  Karkhana road Gujrat   ......here city name is Gujrat
Ho. no.241 S No.26  I-8/3 Isb              .........here city name is isb

I am doing this but it is only working for few... I need a general query which can work for every format of address
SELECT DISTINCT REVERSE
(
  LEFT( REVERSE(All_Students.Address), CHARINDEX(' ', REVERSE(All_Students.Address))-1 )
) as Addresses
from All_Students
order by addresses

A:

What do we know about Cities in these address strings? City is in the end of the string but it can contain more than 1 word. So I think there is no way to formalize a method to cut a City name from the Address line using only this table.
I think the one way to do it is to find an universal City table for your area/country in the Internet for example in any format (ZIP codes, government statistics,...) and use this table to cut Cities from this table from the Address line.
For MySQL
SELECT TRIM(TRIM(TRAILING Cities.Name FROM Address) ), Cities.Name
from All_Students left join Cities
     on All_Students.Address like CONCAT('% ',Cities.Name)

For MS SQL Server
SELECT LEFT(Address,LEN(Address)-LEN(Cities.Name)), Cities.Name
from All_Students left join Cities
     on All_Students.Address like '% '+Cities.Name

To update in MS SQL as required in the comment use this :
UPDATE
    A
SET
    A.address = B.NewAddress,
    A.City = B.City
FROM
    Transformed_All_Student A
    JOIN
    (
      SELECT Student_id,
             LEFT(Address,LEN(Address)-LEN(Cities.Name)) as NewAddress,
             Cities.Name as City
      from All_Students left join Cities
         on All_Students.Address like '% '+Cities.Name

    ) B
ON A.Student_ID = B.Student_id


Q:

jruby rubygems update breaks jgem

Has anyone seen this: ??  No jgem command works at all??  Though jruby -S gem list does work.  I'm using jruby 1.3.1 and Sun Java6 jre
root@test:/usr/local: jgem --version
1.3.3

root@test:/usr/local: jgem update --system
JRuby limited openssl loaded. gem install jruby-openssl for full support.
http://wiki.jruby.org/wiki/JRuby_Builtin_OpenSSL
Updating RubyGems
Updating rubygems-update
Successfully installed rubygems-update-1.3.6
/usr/local/jruby/lib/ruby/site_ruby/1.8/rubygems/commands/update_command.rb:103:Warning: Gem::SourceIndex#search support for String patterns is deprecated
Updating RubyGems to 1.3.6
Installing RubyGems 1.3.6
RubyGems 1.3.6 installed

root@test:/usr/local: jgem list
/usr/local/jruby/bin/jgem: line 8: require: command not found
/usr/local/jruby/bin/jgem: line 9: require: command not found
/usr/local/jruby/bin/jgem: line 10: require: command not found
/usr/local/jruby/bin/jgem: line 12: required_version: command not found
/usr/local/jruby/bin/jgem: line 14: unless: command not found
/usr/local/jruby/bin/jgem: line 15: abort: command not found
/usr/local/jruby/bin/jgem: line 16: end: command not found
/usr/local/jruby/bin/jgem: line 18: args: command not found
/usr/local/jruby/bin/jgem: line 20: begin: command not found
/usr/local/jruby/bin/jgem: line 21: Gem::GemRunner.new.run: command not found
/usr/local/jruby/bin/jgem: line 22: rescue: command not found
/usr/local/jruby/bin/jgem: line 23: exit: e.exit_code: numeric argument required

A:

Note that this only seemed to happen on Linux (not OSX)  And I fixed it by replacing the line at the top of the jgem script from:
#!/mnt/java/jruby-1.4.0/bin/jruby

to
#!/usr/bin/env jruby


Q:

Android center and adjust image in webview

I've been working on programming a basic webcomic app lately and have been having issues with how webview is displaying the comics. The images themselves load fine, however there is always excess whitespace above or to the side of the image, with the image always being positioned at the top left corner of the webview. Also, typically the webview is zoomed into the image a certain degree, which is a problem as the comics vary in dimensions.
I would like to have the image load so that it is centered, adjusted based on height or width (whichever is appropriate) so that the entire image is visible, and if possible eliminate the whitespace. Unfortunately I cannot provide any screenshots of the problem because for whatever reason none of the emulators can run the app.
As far as code goes I have just the following:
    <WebView
    android:id="@+id/webView1"
    android:layout_width="wrap_content"
    android:layout_height="300dp"
    android:layout_below="@+id/textView1"
    android:layout_gravity="center"
    android:layout_centerHorizontal="true" />

In the class my code is as such with image being a string that contains the image URL which I pulled from the page's HTML:
        WebView myWebView = (WebView) findViewById(R.id.webView1);
    myWebView.loadUrl(image);

A:

Try setting the android:layout_height="wrap_content"
and about the whitespace issue, try looking into This Link


Q:

Is there a way to query a VB Script Array?

I'd like to be able to query an array (multi and single dimensional ) with something like SQL.  Is there a way to do this?
It just seems extraordinarily wasteful to step through it one record at a time.

A:

Nope.  Do you wasteful in terms of having to write the loop, or performance wise?  I'd expect heaping a layer of abstraction over the array would hinder performance.
If you need to search your arrays in something other than linear time (ie., one at a time), you'll need to organize them so that you can so a binary search over them (or any number of other algorithms).


Q:

Blank screen on Xamarin

I have a Xamarin portable project.
The Xaml pages I debug are totally blank and I cannot see any components on the pages on both Android and IOS.
How can I fix this?
Note: It gets no error messages, the pages are opening and I cannot see anything on them.
The problem occured after this error. When I fixed it the pages I debug become opening empty,
although they were working before InitializeComponent error.
Any help would be greatly appreciated.
This is my xaml :
<?xml version="1.0" encoding="utf-8" ?>
    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="AcikAkademi3.Layoutlar.GridOrnek3">

<Grid>
  <Grid.RowDefinitions>
    <RowDefinition Height="*"></RowDefinition>
    <RowDefinition Height="*"></RowDefinition>
  </Grid.RowDefinitions>

  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="*"></ColumnDefinition>
    <ColumnDefinition Width="*"></ColumnDefinition>
    <ColumnDefinition Width="Auto"></ColumnDefinition>
  </Grid.ColumnDefinitions>

  <Label BackgroundColor="Red" Text="0,0" Grid.Column="0" Grid.Row="0">
  </Label>
  <Label BackgroundColor="Blue" Text="1,0" Grid.Column="1" Grid.Row="0">
  </Label>
  <Label BackgroundColor="Yellow" Text="Açık Akademi" Grid.Column="2" Grid.Row="0"></Label>

  <Label BackgroundColor="White" Text="0,1" Grid.Column="0" Grid.Row="1">
  </Label>
  <Label BackgroundColor="Silver" Text="1,1" Grid.Column="1" Grid.Row="1">
  </Label>
  <Label BackgroundColor="Lime" Text="2,1" Grid.Column="2" Grid.Row="1">
  </Label>

</Grid>
</ContentPage>

This is my cs :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace AcikAkademi3.Layoutlar
{
    public partial class GridOrnek3 : ContentPage
    {
        public GridOrnek3()
        {
            Padding = new Thickness(0, 20, 0, 0);
        }
    }
}

App.cs :
using AcikAkademi3.Layoutlar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xamarin.Forms;

namespace AcikAkademi3
{
    public class App : Application
    {
        public App()
        {
            MainPage = new GridOrnek3();
        }

        protected override void OnStart()
        {
        }

        protected override void OnSleep()
        {
        }

        protected override void OnResume()
        {
        }
    }
}

A:

You should call InitializeComponent() in ctor.
Otherwise UI elements will not init from xaml file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace AcikAkademi3.Layoutlar
{
    public partial class GridOrnek3 : ContentPage
    {
        public GridOrnek3()
        {
            InitializeComponent();
            Padding = new Thickness(0, 20, 0, 0);
        }
    }
}

Okay,
Looks like there is a mistake in xaml file
<Label BackgroundColor="Brown" Text="0,1" Grid.Column="0" Grid.Row="1">
  </Label>

There is no Brown color, try to chose something from this table
This works for me
<Grid>
  <Grid.RowDefinitions>
    <RowDefinition Height="*"/>
    <RowDefinition Height="*"/>
  </Grid.RowDefinitions>

  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="*"/>
    <ColumnDefinition Width="*"/>
    <ColumnDefinition Width="Auto"/>
  </Grid.ColumnDefinitions>

  <Label    Grid.Column="0"
            Grid.Row="0"
            BackgroundColor="Red"
            Text="0,0" />

  <Label    Grid.Column="1"
            Grid.Row="0"
            BackgroundColor="Blue"
            Text="1,0" />

  <Label    Grid.Column="2"
            Grid.Row="0"
            BackgroundColor="Yellow"
            Text="Açık Akademi"/>

  <Label    Grid.Column="0"
            Grid.Row="1"
            BackgroundColor="Olive"
            Text="0,1" />

  <Label    Grid.Column="1"
            Grid.Row="1"
            BackgroundColor="Silver"
            Text="1,1" />

  <Label    Grid.Column="2"
            Grid.Row="1"
            BackgroundColor="Lime"
            Text="2,1" />

</Grid>