text:
Q: Criar controles dinamicamente Tenho o seguinte jquery
function MontaTraslado() {

    resultado = jQuery.parseJSON('{"txtDestino": "' + $("#txtGeoTo").val() + '" , "datIda": "' + $("#txtDateStart").val() +
                                '", "datVolta": "' + $("#txtDateEnd").val() + '", "intAdultos": "' + $("#txtAdulto").val() +
                                '", "intCriancas": "' + $("#txtCrianca").val() + '", "quaAdulto": "' + $("#txtQuaAdulto").val() +
                                '", "quaCrianca": "' + $("#txtQuaCrianca").val() + '", "quaMaisCinco": "' + $("#txtQuaMaisCinco").val() +
                                '", "idGeoAreDestino": "' + $("#idGeoAreDestino").val() + '" }');

    var str = "";

    $.ajax({

        url: "/Servico/MontaTraslado",
        datatype: 'json',
        contentType: "application/json; charset=utf-8",
        type: "POST",
        data: JSON.stringify({ _servico: resultado }),
        success: function (data) {

            if (data.searchResult != "") {

                $(data.searchResult).each(function () {

                    //str += '
';
                    str += '
';
                    str += '
';

                    str += '<input type="checkbox" value="1" />';
                    str += '
';
                    str += '
';
                    str += '
';

                    str += this.ProductName + '
';
                    //str += 'Aeroporto - Hotel
';
                    //str += 'Hotel Aeroporto';

                    str += '
';
                    str += '
';
                    str += '
';
                    str += '
+ R$ 0,00
';
                    str += '
';
                    str += '
';

                    str += '
';
                    str += '<button value="novaPesquisa" class="btn-pular-passo pull-right">Continuar</button>';
                    str += '
';
                    //str += '
';

                    $('#translados').html(str);

                    str = "";

                });
            }
            else
            {
                $('#translados').html("
Nenhum registro encontrado.
");
            }

        },
        error: function (error) {

            loading(0, "LoadbuscaServico");
        }
    });

No atual contexto meu, o each dessa função se repete 19 vezes, ou seja, possuo 19 registros nessa situação. Eu preciso ir criando checkboxes e ir adicionando a ele um texto que eu trago de this.ProductName. Acontece se eu deixar como está, ele irá sobreescrevendo o atual description e no final terei apenas um checkbox com o último description, ou seja, somente o último registro. Se eu fizer um for, ele se repetirá 19 vezes na primeira passada(correto e é o que eu quero) e mais 19 vezes em cada outra iteração do each do jquery(isso não quero). A pergunta é: Como eu faço para ter os 19 checkboxes que eu preciso dinamicamente na minha página? Acho que é aqui que eu deveria fazer meu for:
str += '<input type="checkbox" value="1" />';
                    str += '
';
                    str += '
';
                    str += '
';

                    str += this.ProductName + '
';
                    //str += 'Aeroporto - Hotel
';
                    //str += 'Hotel Aeroporto';

                    str += '
';
                    str += '
';
                    str += '
';
                    str += '
+ R$ 0,00
';
                    str += '
';
                    str += '
';

A: Você tem o  $('#translados').html(str); dentro do for each, isso vai fazer com que o conteúdo seja re-escrito a cada vez que o for faz um loop. Você devia usar o .append() (que acrescenta ao html que já existe), ou usar o .html() fora do loop.
Dê uma olhada a este exemplo
for (var i = 0; i < 20; i++) {
    $('#translados').html('Usando .html(): ' + i);                 // esta linha sobrepôe os valores
    $('#translados2').append('Usando .append(): ' + i + '
'); // esta linha mantem o que já havia e acrescenta
}

portanto se quiser usar o .html() coloque depois do fecho da função .each() e antes do fecho do if:
    });
    $('#translados').html(str);
}
else


text:
Q: How to solve $xy'+x=y\ln(xy)$? i.e. $x\frac{\mathrm{d}y}{\mathrm{d}x}+x=y\ln(xy)$.
The MATHEMATICA can't solve this problem.
DSolve[x*y'[x]+x==y[x]*Log[y[x]*x],y[x],x]

leads
Solve::ifun: Inverse functions are being used by Solve, so some solutions may not be found; use Reduce for complete solution information.

redpajama_set_name: RedPajamaStackExchange


text:
Q: mysql order by votes but newer post has more value My table exists of posts.id, vote and posttime (when the posts was added). When displaying on page, I ORDER BY vote DESC. The thing is, I need to make new posts have more value than older post.
Meaning if:post A was added 3rd April and has 12 votes, post B was added 4th April and has only 5 votes.
Post B should be displayed higher than post A. Do you understand?
My query:
$query = "SELECT
                posts.id,
                rubrik,
                link,
                name,
                userid,
                posttime
              FROM `posts`
              INNER JOIN `user`
              ON posts.userid = user.id
              ORDER BY vote DESC";

Now, I need to do something with posttime, but I can't understand how.
I feel I was a bit unclear, still thanks for the answers.
What the final result would be, is that top voted posts that are 2 days old should make way for newer posts with a lot of votes but still lower than the old posts.
Does that make sense?

A: If you want to order by posttime and then vote you can do this:
$query = "SELECT
            posts.id,
            rubrik,
            link,
            name,
            userid,
            posttime
          FROM `posts`
          INNER JOIN `user`
          ON posts.userid = user.id
          ORDER BY posttime, vote DESC";


text:
Q: How do I use JQuery to create an onclick javascript link in HTML with quote-including-string parameters? I'm trying to create a link as follows in HTML:

I'm doing this using JQuery as follows:
html = ''
However, I run into problems when string itself contains a single quotation mark. Is there any way that I can do something of this sort regardless of the characters contained in string? The main ones I'm trying to figure out are both single and double quotation marks.
Best, and thanks for any advice,
Sami

A: I'm not sure if I understood your problem, but have you already tried the escape function?
Like this:
html = ''

A: You could do this quite easily by simply encoding the string as a URIComponent before placing it in and then decoding it when you need it.
ie.
var NoQuotesString = encodeURIComponent(string);
//to encode the string without quotes

var BringBackMyQuotes = decodeURIComponent(NoQuotesString);
//decodes the string back to the original

A: Since your using jQuery why not use the event listeners it provides?
Give your link an id value:
anchor

Define the desired behavior with jQuery:
$('#someID').click(function(e) {
    e.preventDefault();// prevent the default anchor behavior
    $('#someID').text('New anchor text');// this is an example of the functionality
});

An example: http://jsfiddle.net/BfHrW/


text:
Q: how to create an array for the settings (Obj C)? I would like to be inspired by an application to create a table with settings for my application. But I do not know how to use the charts in Objective C.
Can someone help me please?
There are pictures to help you see the interface.
Settings Tab 1

SettingsTab 2

A: Here is a very quick example demonstrate how to make a table view look exactly the same as your images:
First, let design our UI:

*

*Set Style of UITableView to Grouped

*Set Prototype Cells value to 1, drag an UIImageView & UILabel to newly added prototype cell, then set appropriate constraints as you wish.

*Let assign Cell Icon with a value of 100 in its tag attribute & do the same but 101 for Cell Title

*Create dataSource & delegate outlets for your UITableView
Now, back to coding stuff.
Tell your view to implement UITableView's delegates:
@interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
@end

Then implement appropriate delegates:
@implementation ViewController {
    NSArray *images;
    NSArray *titles;
    NSArray *sections;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    images = @[@"history", @"profile", @"quote", @"search", @"post_count", @"star"];
    titles = @[@"General", @"Format", @"Unit", @"Import/Export", @"Update", @"Support"];
    sections = @[@"Preferences", @"Data", @""];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 2;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];

    UIImageView *imageView = [cell viewWithTag:100];
    UILabel *label = [cell viewWithTag:101];

    int index = (int)(indexPath.item + (indexPath.section * 2));
    imageView.image = [UIImage imageNamed:[images objectAtIndex:index]];
    label.text = [titles objectAtIndex:index];

    return cell;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return [sections objectAtIndex:section];
}

-(NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
    if (section == 2) {
        return @"This is the section's footer title\nCoded by RyanB@StackOverflow";
    }

    return nil;
}

All done. Now build the project & run it to see the result.


text:
Q: vba compiling error: not correct implements interface I am learning vba class.
just while i want to compile below simple code, it always shows a error message saying not correct implements interface.
i am stucking at this point, someone can help on this?
i tried office 2K10 64bit and 2k16 32bit and both version has some problem when setting implements class.
picture of error
    Option Explicit

    Implements cInterestType

    Private amount As Double

    Public Function cInterestType_CalculateInt() As Double
        ' <some code>

    End Function

Just for another test.
i put a simple class code to returning a message, it still get the error, and seems it always stops and high light at "implements" when compiling.
I used other computer to do the same code and it shows the same error message.
error message

A: Your class module is also called cInterestType, and does not need to implement itself.
Ref:

*

*https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/implements-statement


text:
Q: laravel ORM relations : left Join like query with optional condition on the right table i have two table, tutorial:id,title and tutorial_tags:id,tutorial_id,title
the relation in tutorial model is defined like this :
function TutorialTag(){
        return $this->hasMany('App\TutorialTag');
    }

i want to left join tutorials with tutorial_tags , like (please ignore syntax errors):
select tutorials.* , tutorial_tags.* from `tutorials` left Join
`tuotrial_tags` ON tutorials.id = tutorial_tags.tutorial_id

but i want to be able to use Conditions on tutorial_tags in case user want to search a particular tags:
select tutorials.* , tutorial_tags.* from `tutorials` left Join
`tuotrial_tags` ON tutorials.id = tutorial_tags.tutorial_id
where tutorial_tags.title = 'ABC'

if i use whereHas like this :
    $tutorials = Tutorial::whereHas('TutorialTag',function ($query){
        if(isset($_GET['tag']))
            $query->where('title',$_GET['tag']);
    })->get();

i dont get tutorials that are without any tag, basically it works like inner Join.
and if i use with :
    $tutorials = Tutorial::with(['TutorialTag'=>function($query){
        if(isset($_GET['tag']))
            $query->where('title',$_GET['tag']);
    }])->get();

then ill get two separate queries with no effect on eachother, basically the where condition on tutorial_tags has no effect on tutorials and i get all the tutorials even the ones without sreached tag, here is the query log :
Array
(
    [0] => Array
        (
            [query] => select * from `tutorials`
            [bindings] => Array
                (
                )

            [time] => 0
        )

    [1] => Array
        (
            [query] => select * from `tutorial_tags` where `tutorial_tags`.`tutorial_id` in (?, ?, ?) and `title` = ?
            [bindings] => Array
                (
                    [0] => 1
                    [1] => 2
                    [2] => 3
                    [3] => ABC
                )

            [time] => 2
        )

)

how can i get left Join like query with optional condition on the right table

A: This is not an efficient sql query, but you can solve the issue with laravel collections and an extra query.
Grab all the intersections:
$tutorials1 = Tutorial::whereHas('TutorialTag',function ($query){
    if(isset($_GET['tag']))
        $query->where('title',$_GET['tag']);
})->get();

Grab the rest:
$tutorials2 = Tutorial::doesntHave('TutorialTag')->get();

Merge both collections:
$tutorials = $tutorials1->merge($tutorials2);

A: To get the left join query do the following
$tutorials = Tutorial::leftJoin('tutorial_tags', 'tutorials.id', '=', 'tutorial_tags.tutorial_id')
                 ->where(function($query){
                      if(isset($_GET['tag']) {
                          $query->where('tutorial_tags.title' , $_GET['tag'];
                      }
                 });

This will give you the following outputs:
Case 1: If tag parameter was provided
SELECT * FROM tutorials LEFT JOIN tutorial_tags ON tutorials.id = tutorial_tags.tutorial_id WHERE tutorial_tags.title = 'ABC';

Case 2: When no tag parameter has been provided
SELECT * FROM tutorials LEFT JOIN tutorial_tags ON tutorials.id = tutorial_tags.tutorial_id;

A: After spending a while I'm able to fix this with Lazy Eager Loading
$tutorials = Tutorial::all();

$tutorials->load(['TutorialTag' => function ($query) {
    $query->where('title', $_GET['tag']);
}]);

A: The whereHas() method returns only those models where any relationship matches the condition in the closure. The with() method only returns relationships that match the condition in the closure. What you need to do is use them both. You can also use the when() method to filter on the boolean condition of the input value being filled.
$tag = $request->input('tag');
$tutorials = Tutorial->when($tag, function ($query) use ($tag) {
        $query
            ->whereHas('tutorialTags', fn ($q) => $q->where('title', $tag)
            ->with(['tutorialTags' => fn ($q) => $q->where('title', $tag]);
    })
    ->get();

You also should be following proper Laravel conventions that will make your life easier, especially when sharing code with others.
You should never see $_GET used in your code anywhere. I've removed it in favour of getting it from the request object, but it should properly be set as a route parameter. Relationship methods that return more than one model (such as a HasMany) should have plural names. Relationships names should be in camel case.


text:
Q: sql запрос добавление второй таблицы Написать запрос по w3schools.com
Вывести все продукты, у которых код продукта >= 64 или продукты, у которых поставщик = "Tokyo Traders" (подзапрос).
Помогите начало понял
SELECT ProductName FROM [Products]
WHERE ProductID >=64
а как к нему добавить еще вторую таблицу(продукты, у которых поставщик = "Tokyo Traders")?
https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all
Спасибо зарание!

A: написано же - с помощью подзапроса
AND supplier_id = (select id form suppliers where name = 'xxx')


text:
Q: gl_Color is undeclared identifier on WebGL I am looking at http://www.swiftless.com/tutorials/glsl/3_glcolor.html which has the following code snippet:
void main() {
// Set the output color of our current pixel
gl_FragColor = gl_Color;}

I tried to use gl_Color on my WebGL. I got an error that gl_Color is undeclared identifier.
What did I do wrong?
Thanks in advance for your help.

A: WebGL uses Open GL ES 2.0 as its base, therefore you should be using GLSL ES 1.0 for the shaders. GLSL ES does not have a gl_Color, and therefore you will have to rewrite this shader.

A: My guess is that you're trying to compile GLSL code using a regular C compiler.
It looks like it's supposed to be C code, but it is actually GLSL source - deisgned to be compiled by the OpenGL GLSL compiler, not your machine C compiler.
The fragment shader has a pre-defined variable 'gl_Color' which is the output from the vertex shader.
The sample you reference has the code inside a shader.frag file, which is referenced by shader.init().  The OpenGL library itself will handle compiling it into GPU instructions for your machine.  Put the code in that file, and hopefully the example will work :)


text:
Q: If a quantum state occupied by an electron has a $m^*_e>0$, will the same state if unoccupied have $m_h^*<0$ and vice-versa? For electrons in a periodic potential, the effective mass of an electron in an energy band can be positive or negative depending on its quantum state specified by $n,k$ i.e. its energy $E_n(k)$ and crystal momentum $\hbar k$ in the band or in short, where it lies in the band. This is because the effective mass is given by $$m^*=\frac{\hbar^2}{\Big(\frac{d^2E_n(k)}{dk^2}\Big)}$$ which changes from point to point.
If the same quantum state is unoccupied, we'll get a hole, with same quantum numbers. Can we say that the effective mass of the corresponding hole is negative? And when electron effective mass is negative, corresponding hole mass is positive?
My reasoning is like this. Since the hole moves opposite to the electron, and since the motion in presence of an electric field is semiclassically described by Newton's law $$F=-eE=m^*a,$$ the hole mass must be opposite to the electron mass. But if we assume hole has a positive charge $q=+e=-(-e)$, then there is a compensating negative sign, it will make effective mass of hole to be positive.


text:
Q: Curved Path Constant Speed and End Points I'm trying to move at a constant speed over a curved path in a given amount of time. I calculated the average speed needed to travel the curve by taking the derivative at various points along the curve and averaging them. Then I multiply the path's position (t) by a ratio of the average derivative and the derivative at the current location of the curve. This method for setting constant speed works great.
The problem I'm having occurs when multiple control points (3 or more) are put in the same location. Then the speed (or derivative) at this point is 0 and dividing the average speed by a speed of 0 obviously causes problems in the calculations.
BSpline requires three control points to be placed at the ends in order to have the curve actually reach the start and end at the end points. If I only put 1 or 2 control points at the ends the path starts after the first control point and ends before the last control point. For my application it is important that the motion reaches the end points because I will be linking together multiple BSplines and it's important for them to line up correctly and to not have any time gaps between them either.
I've tried a few different attempts at fixing it, but none of them were successful.
Here is my sample code and I've included comments to indicate where the problem is.
NOTE: I used CatmullRomSpline in my example instead of BSpline only because I found a bug in the BSpline's derivative method, which has been fixed but is not yet in the stable version of LibGDX.
Test.java
public class Test extends Game {
    private Stage stage;
    private MyPath path;

    @Override
    public void create () {
        Gdx.graphics.setDisplayMode(1000, 1000, false);
        stage = new Stage();
        stage.setViewport(new ScreenViewport(stage.getViewport().getCamera()));
        Gdx.input.setInputProcessor(stage);
        path = new MyPath(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
        stage.addActor(path);
    }
    @Override
    public void render () {
        Gdx.gl.glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        stage.act(Gdx.graphics.getDeltaTime());
        stage.draw();
    }
    @Override
    public void dispose(){
        path.dispose();
        stage.dispose();
        super.dispose();
    }
}

MyPath.java
public class MyPath extends WidgetGroup implements Disposable {
    private Path<Vector2> path;
    private Vector2 result=new Vector2(), derivative=new Vector2();
    private float time, t, tPrev, dt, tConst, tConstPrev, derivativeAverage;
    private Array<Texture> textures = new Array<Texture>(Texture.class);
    private Array<Image> points = new Array<Image>(Image.class);
    private Image dot;

    private final float CYCLE = 4;  // path cycle time (in seconds)

    private Vector2[] pointsData = {
            new Vector2(100, 100),
            new Vector2(100, 100),
//          new Vector2(100, 100),  // << UN-COMMENT TO PRODUCE BUG

            new Vector2(350, 800),
            new Vector2(550, 200),
            new Vector2(650, 400),
            new Vector2(900, 100),
            new Vector2(900, 100)
    };

    public MyPath(int width, int height){
        this.setSize(width, height);
        path = new CatmullRomSpline<Vector2>(pointsData, false);
        // create and add images
        createImages();
        for (int i=0; i<points.size; i++){
            points.items[i].setPosition(pointsData[i].x - points.items[i].getWidth()/2, pointsData[i].y - points.items[i].getHeight()/2);
            addActor(points.items[i]);
        }
        addActor(dot);

        // calculate derivative average
        derivativeAverage();
    }

    @Override
    public void act(float delta){
        result = getValue(delta);
        dot.setPosition(result.x - dot.getWidth()/2, result.y - dot.getHeight()/2);
    }
    private Vector2 getValue(float delta){
        // set t in the range [0,1] for path
        time += delta;
        if (time > CYCLE){
            time = tPrev = dt = tConst = tConstPrev = 0;
        }
        t = time / CYCLE;
        dt = t - tPrev;
        tPrev = t;

        // constant speed (tConst)
        path.derivativeAt(derivative, tConstPrev);
        tConst += dt * (derivativeAverage / derivative.len());  // << ERROR when derivative.len() is 0
        tConstPrev = tConst;

        path.valueAt(result, tConst);

        return result;
    }

    private void derivativeAverage(){
        float segmentCount = 20000;
        derivativeAverage = 0;
        for (float i=0; i<=1; i+=1.0/segmentCount) {
            path.derivativeAt(result, i);
            derivativeAverage += result.len();
        }
        derivativeAverage /= segmentCount;
        if (derivativeAverage==0){ throw new GdxRuntimeException("ERROR: derivative average is zero"); }
    }

    private void createImages(){
        dot = getImage(Color.GREEN, true);
        for (int i=0; i<pointsData.length; i++){
            points.add(getImage(Color.WHITE, false));
        }
    }
    private Image getImage(Color color, boolean fillCircle){
        Pixmap pixmap = new Pixmap(50, 50, Pixmap.Format.RGBA8888);
        pixmap.setColor(color);
        if (fillCircle){
            pixmap.fillCircle(pixmap.getWidth()/2, pixmap.getHeight()/2, pixmap.getWidth()/2-1);
        } else {
            pixmap.drawCircle(pixmap.getWidth()/2, pixmap.getHeight()/2, pixmap.getWidth()/2-1);
        }
        textures.add(new Texture(pixmap));
        pixmap.dispose();
        return new Image(textures.peek());
    }
    @Override
    public void dispose(){
        while (textures.size > 0){
            textures.pop().dispose();
        }
    }
}

===================================================================
EDIT
===================================================================
Here is my latest attempt at increasing t until the dot is moving.
This method does occasionally work on some frames (moving smoothly past the zero derivative). But other times the dot does weird things lie starting over at the beginning of the curve when it hits the zero derivative or extending beyond the end of the curve moving a different direction or disappearing completely (because the position gets set to negative values).
So it seems like this method is really close as it does occasionally work on some frames, but it glitches and does weird things on other frames.
Vector2 lastPoint = new Vector2();
float minSpeed = 1;
float minDerivative = 1;
float temp;

...

private Vector2 getValue(float delta){
    // set t in the range [0,1] for path
    time += delta;
    if (time > CYCLE){
        time = tPrev = dt = tConst = tConstPrev = 0;
    }
    t = time / CYCLE;

    // CONSTANT SPEED
    dt = t - tPrev;
    path.derivativeAt(derivative, tConstPrev);
    temp = dt * (derivativeAverage / derivative.len());
    path.valueAt(result, tConst + temp);

    //**************************************
    //  FIX FOR ZERO SPEED
    //  increase t in loop until speed > 0
    //**************************************
    while (result.dst(lastPoint)<minSpeed || derivative.len()<minDerivative){
        // set t in the range [0,1] for path
        time += delta;
        if (time > CYCLE){
            time = tPrev = dt = tConst = tConstPrev = 0;
            lastPoint.set(0,0);
        }
        t = time / CYCLE;

        // CONSTANT SPEED
        dt = t - tPrev;
        // new derivative
        path.valueAt(derivative, t);
        derivative.sub(lastPoint);

        temp = dt * (speedAverage / derivative.len());
        path.valueAt(result, tConst + temp);
    }

    tConst += temp;

    lastPoint.set(result);
    tPrev = t;
    tConstPrev = tConst;

    return result;
}

I also do a similar thing when calculating the average speed to keep the zero derivatives from affecting it. I also tried using the commented out sections with the "addedSegmentCount" variable when calculating the average, but that actually caused more glitches for some reason...even though theoretically this seems like the "correct" way to calculate the average since some segments don't get added if the distance is too small.
private void pathLength_SpeedAverage(){
    float segmentCount = 20000;
//  float addedSegmentCount = 0;
    pathLength = 0;

    path.valueAt(lastPoint, 0);
    for (float i=0; i<=1; i+=1.0/segmentCount){
        path.valueAt(result, i);
        if (result.dst(lastPoint) >= minSpeed){
            path.derivativeAt(result, i);
            if (result.len() >= minDerivative){
                pathLength += result.len();

                lastPoint.set(result);
//              ++addedSegmentCount;
            }
        }
    }
    speedAverage = pathLength / segmentCount;
//  speedAverage = pathLength / addedSegmentCount;
    lastPoint.set(0,0);
}

A: You cannot completely avoid zero first derivatives if control points could be coincident. So, what I suggest is to not use the first derivatives at all. Your purpose is to traverse the path at a constant speed, which is equivalent to sample points along the path with equal arc length. The theoretical approach to solve this involves calculus to compute arc length numerically, but we can go with an approximation approach as in the following:
Suppose you would like to traverse the path in N steps,
1) Sample M points along the path uniformly in parameter domain (i.e., t=0.0, 0.1, 0.2, 0.3, ....) where M is preferred to be greater than N. Denoting these points as P0, P1, P2,....
2) Compute the distance between P0P1, P1P2, P2P3,....
3) Compile a look-up table that maps from parameter t(i) to the cumulative chord length |P0P1|+|P1P2|+.....+|P(i-1)P(i)|. At the end, you will also obtain the overall length of the path, denoted as L.
4) Now, for each value of kL/N (where k=0 to N), you can compute the corresponding t value from the look-up table by linear interpolating the two parameter values in which the kL/N falls on.


text:
Q: Problem compiling self-created header file using Dev-C++? I am using Dev-C++ on windows vista. I have 3 files located in the same directory. They are:
- math_functions.h
- math_functions.c
- test3.c

math_functions.h code:
int   sum       (int x, int y);
float average   (float x, float y, float z);

math_functions.c code:
int sum (int x, int y)
{
  return (x + y);
}

float average (float x, float y, float z)
{
  return (x + y + z) / 3;
}

test3.c code:
#include <stdio.h>
#include "math_functions.h"

main ()
{
  int   theSum     = sum (8, 12);
  float theAverage = average (16.9, 7.86, 3.4);

  printf ("the sum is: %i ", theSum);
  printf ("and the average is: %f \n", theAverage);
  printf ("average casted to an int is: %i \n", (int)theAverage);
}

It fails to compile. The error message I get is:
C:\Users\eSum\AppData\Local\Temp\ccKmdaaa.o(.text+0x3a) In function `main':
[Linker error] undefined reference to `sum'
[Linker error] undefined reference to `average'
C:\Users\eSum\AppData\Local\Temp\ccKmdaaa.o(.text+0x3a) ld returned 1 exit status

I use the same exact code compile in ubuntu(I run ubuntu using virtual machine i,e. vmplayer), it compiled without errors.
Do I need to set anything in Dev-C++ to compile the files?

A: Dev-C++ seems not to be linking math_function.c with test3.c when making text3.exe this is a configuration problem in Dev-C++ you most likely need to add math_function.c to the Dev-C++ project

A: The problem isn't with the header-file, but with your project settings. You have to add math_functions.c to the project so it gets compiled and linked with test3.c.


text:
Q: What is the meaning of class collapsed in bootstrap 4? I have noticed that while using accordions, the class "collapsed" is being used, not to be confused with the data-toggle="collapse". When I test what happens if I remove the collapsed class, well, the accordion works just as well even without the collapsed class issued to the buttons. For example you can look at the accordion example in the following link:
https://getbootstrap.com/docs/4.0/components/collapse/
<button class="btn btn-link collapsed"...

Can someone explain what is the class "collapsed" and what it does please?
I have noted the following question in SO, but there is no explanation on the collapsed class functionality.
Bootstrap collapse menu arrows at initial state

A: By reviewing Bootstrap v4.0 cdn, the collapsed class is only in the JavaScript file bootstrap.min.js and not present on any other file. Meaning it has no CSS style. It is used inside of loops and conditional statement and it does not matter if the user adds it or not, Bootstrap JavaScript will toggle that class supposedly to give the accordion the correct functionality, but I really don't see anything major related to that class, it may be something not having a real utility.


text:
Q: Partition problem with APFS containers in macOS High Sierra As always I'm so impatient and migrating with my main devices to the first developer previews the day they are available.
Which as always bring me only problems but I just cannot help myself.
So this time I wanted to see High Sierra before going all in. So I made a second partition and installed High Sierra in there. However after roughly 10 minutes I felt like I need to update my main partition anyway.
So I did. But now there is the catch. I have 2 partitions and I'm not able to merge them. And in an attempt to fix this situation I converted the second APFS container back to HFS+ and actually split it into two and converted only one back to APFS.
So now I have two APFS containers and one HFS+. Any ideas how to get this back to one and only APFS?
diskutil list:
  /dev/disk0 (internal):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:      GUID_partition_scheme                         251.0 GB   disk0
   1:                        EFI EFI                     314.6 MB   disk0s1
   2:                 Apple_APFS Container disk2         211.3 GB   disk0s2
   3:                  Apple_HFS Untitled                5.7 GB     disk0s3
   4:                 Apple_Boot                         134.2 MB   disk0s4
   5:                 Apple_APFS Container disk1         32.8 GB    disk0s5
   6:       Apple_KernelCoreDump                         655.4 MB   disk0s6

/dev/disk1 (synthesized):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:      APFS Container Scheme -                      +32.8 GB    disk1
                                 Physical Store disk0s5
   1:                APFS Volume Untitled                962.6 KB   disk1s1

/dev/disk2 (synthesized):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:      APFS Container Scheme -                      +211.3 GB   disk2
                                 Physical Store disk0s2
   1:                APFS Volume Macintosh HD            167.8 GB   disk2s1
   2:                APFS Volume Preboot                 29.3 MB    disk2s2
   3:                APFS Volume Recovery                521.1 MB   disk2s3
   4:                APFS Volume VM                      1.1 GB     disk2s4

diskutil apfs list:
APFS Containers (2 found)
|
+-- Container disk1 B254A72D-19C5-4D2C-B461-3C23F298E454
|   ====================================================
|   APFS Container Reference:     disk1
|   Capacity Ceiling (Size):      32750391296 B (32.8 GB)
|   Capacity In Use By Volumes:   78757888 B (78.8 MB) (0.2% used)
|   Capacity Available:           32671633408 B (32.7 GB) (99.8% free)
|   |
|   +-< Physical Store disk0s5 7F1CDC13-0E37-44CC-B96C-45EF55BA8410
|   |   -----------------------------------------------------------
|   |   APFS Physical Store Disk:   disk0s5
|   |   Size:                       32750391296 B (32.8 GB)
|   |
|   +-> Volume disk1s1 BDE7AAD6-A3D1-3561-B5C0-39FA6C46CCB1
|       ---------------------------------------------------
|       APFS Volume Disk (Role):   disk1s1 (No specific role)
|       Name:                      Untitled
|       Mount Point:               /Volumes/Untitled 1
|       Capacity Consumed:         962560 B (962.6 KB)
|       Capacity Reserve:          None
|       Capacity Quota:            None
|       Encrypted:                 No
|
+-- Container disk2 70F0772D-B309-405E-9ABE-6D99097B7E16
    ====================================================
    APFS Container Reference:     disk2
    Capacity Ceiling (Size):      211335577600 B (211.3 GB)
    Capacity In Use By Volumes:   169482776576 B (169.5 GB) (80.2% used)
    Capacity Available:           41852801024 B (41.9 GB) (19.8% free)
    |
    +-< Physical Store disk0s2 BDFDDFAF-CC5C-4ACC-9127-A5A5A33FF4CD
    |   -----------------------------------------------------------
    |   APFS Physical Store Disk:   disk0s2
    |   Size:                       211335577600 B (211.3 GB)
    |
    +-> Volume disk2s1 179EB384-BAEF-3A8D-8190-4EBE624E6DF9
    |   ---------------------------------------------------
    |   APFS Volume Disk (Role):   disk2s1 (No specific role)
    |   Name:                      Macintosh HD
    |   Mount Point:               /
    |   Capacity Consumed:         167724068864 B (167.7 GB)
    |   Capacity Reserve:          None
    |   Capacity Quota:            None
    |   Encrypted:                 Yes (Unlocked)
    |
    +-> Volume disk2s2 128F2113-D584-4534-B5FC-81330EA8510A
    |   ---------------------------------------------------
    |   APFS Volume Disk (Role):   disk2s2 (Preboot)
    |   Name:                      Preboot
    |   Mount Point:               Not Mounted
    |   Capacity Consumed:         29270016 B (29.3 MB)
    |   Capacity Reserve:          None
    |   Capacity Quota:            None
    |   Encrypted:                 No
    |
    +-> Volume disk2s3 092D2B6E-5DF9-4333-8B77-117E4A9994B0
    |   ---------------------------------------------------
    |   APFS Volume Disk (Role):   disk2s3 (Recovery)
    |   Name:                      Recovery
    |   Mount Point:               /Volumes/Recovery
    |   Capacity Consumed:         521072640 B (521.1 MB)
    |   Capacity Reserve:          None
    |   Capacity Quota:            None
    |   Encrypted:                 No
    |
    +-> Volume disk2s4 932E7677-4A65-4D9F-9C0D-F5C890E0BD13
        ---------------------------------------------------
        APFS Volume Disk (Role):   disk2s4 (VM)
        Name:                      VM
        Mount Point:               /private/var/vm
        Capacity Consumed:         1073766400 B (1.1 GB)
        Capacity Reserve:          None
        Capacity Quota:            None
        Encrypted:                 No

I would really appreciate any help.

A: Well for anyone interested in a solution, it's now possible.
I've followed this guide and managed to reclaim all available space and resize my main partition back to full disk space.
Thanks everyone for help and suggestions.

A: It seems you can't merge two containers to one container. There is no command for this operation. I tried on my external SSD. Here is another article for your reference: https://www.macobserver.com/tips/deep-dive/macos-sierra-delete-apfs-partition-right-way/


text:
Q: Two lists sort according to the ordering of one of the lists I have a dictionary:
       d = {'Dartmouth': 'Peter Smith',
            'Harvard': 'Karen Samuels',
            'Stanford': 'Sam Peters',
            'UCLA': 'Frank Holland',
            'Brown': 'Michelle Lee}

And suppose I have a function called orderList(list) that takes in a list of students names and sorts it (doesn't matter how its sorted).
If I create a list out of the values of the dictionary and pass it in into orderList, i.e.
orderList(['Peter Smith', 'Karen Samuels', 'Sam Peters', 'Frank Holland', 'Michelle Lee'])
it returns:
['Karen Samuels', 'Sam Peters', 'Michelle Lee', 'Peter Smith', 'Frank Holland']

How do I get the corresponding keys in my dictionary to also be in the same order as what was outputted from orderList? i.e. if I were to take my keys and put it in a list it should look like:
['Harvard', 'Stanford', 'Brown', 'Dartmouth', 'UCLA']

So for instance, Harvard should go first because Karen Samuels is first in the returned list and Karen Samuels maps to Harvard in the dictionary.

A: So you basically want to "invert" the key-value pairs in the dictionary?
This is fairly easy:
new_dict = {v:k for k, v in old_dict.items()}

output = {(expression 1):(expression 2) for (expression 3) in (expression 4)} is a dict comprehension; and is equivalent to
output = {}
for (expression 3) in (expression 4):
    output[(expression 1)] = (expression 2)

and then just use it:
inverted_dictionary = {v:k for k, v in original_dictionary.items()}

out = [inverted_dictionary[i] for i in orderList(original_list))

This is a list comprehension, and works similarly to the dict comprehension:
output = [(expression 1) for (expression 2) in (expression 3) will get
output = []
for (expression 2) in (expression 3):
    output.append((expression1))

(Although (expression 3) in the dict comprehension and (expression 2) in the list comprehension are valid expressions, not all valid expressions will yield valid results in this place. (expression 3) has to be a tuple of names (",".join(names)); with whitespaces added around the comma if needed)

A: You can create an inverse lookup table, then do a lookup on the keys for each value in the new order:
>>> d = {'Dartmouth': 'Peter Smith',
            'Harvard': 'Karen Samuels',
            'Stanford': 'Sam Peters',
            'UCLA': 'Frank Holland',
            'Brown': 'Michelle Lee'}
>>> dinv = {v: k for k,v in d.items()}
>>> order = ['Karen Samuels', 'Sam Peters', 'Michelle Lee', 'Peter Smith', 'Frank Holland']
>>> [dinv[v] for v in order]

Output:
['Harvard', 'Stanford', 'Brown', 'Dartmouth', 'UCLA']

You want to create the lookup table ahead of time as we have done here (O(n) extra memory and O(n) time) rather than scanning the key:value pairs for each value (O(n^2) time).


text:
Q: How can I change the date modified/created of a file? Is there a way to change the date when a file was modified/created (which is shown in Nautilus or with the ls -l command)? Ideally I am looking for a command which can change the date/time stamps of a whole bunch of files to a certain amount of time earlier or later (e.g. +8 hours or -4 days etc.).

A: Thanks for the help.
This worked for me:
In the terminal go to the directory for date-edit.
Then type:
find -print | while read filename; do
    # do whatever you want with the file
    touch -t 201203101513 "$filename"
done

You wil see a ">" after you hit enter, exept for the last time -> "done".
Note:
You may want to change "201203101513"
"201203101513" = is the date you want for all the files in this directory.

A: As long as you are the owner of the file (or root), you can change the modification time of a file using the touch command:
touch filename

By default this will set the file's modification time to the current time, but there are a number of flags, such as the -d flag to pick a particular date.  So for example, to set a file as being modified two hours before the present, you could use the following:
touch -d "2 hours ago" filename

If you want to modify the file relative to its existing modification time instead, the following should do the trick:
touch -d "$(date -R -r filename) - 2 hours" filename

If you want to modify a large number of files, you could use the following:
find DIRECTORY -print | while read filename; do
    # do whatever you want with the file
    touch -d "$(date -R -r "$filename") - 2 hours" "$filename"
done

You can change the arguments to find to select only the files you are interested in.  If you only want to update the file modification times relative to the present time, you can simplify this to:
find DIRECTORY -exec touch -d "2 hours ago" {} +

This form isn't possible with the file time relative version because it uses the shell to form the arguments to touch.
As far as the creation time goes, most Linux file systems do not keep track of this value.  There is a ctime associated with files, but it tracks when the file metadata was last changed.  If the file never has its permissions changed, it might happen to hold the creation time, but this is a coincidence.  Explicitly changing the file modification time counts as a metadata change, so will also have the side effect of updating the ctime.

A: This little script at least works for me:
#!/bin/bash

# find specific files
files=$(find . -type f -name '*.JPG')

# use newline as file separator (handle spaces in filenames)
IFS=$'\n'

for f in ${files}
do
 # read file modification date using stat as seconds
 # adjust date backwards (1 month) using date and print in correct format
 # change file time using touch
 touch -t $(date -v -1m -r $(stat -f %m  "${f}") +%Y%m%d%H%M.%S) "${f}"
done

A: It's been a long time since I wrote any kind of Unix program, but I accidentally set the year incorrectly on a bunch of Christmas photos, and I knew if I didn't change the date from 2015 to 2014 it would be a problem later on.
Maybe, this is an easy task, but I didn't find any simple way to do it.
I modified a script I found here, which originally was used to modify the date by minus one month.
Here's the original script:
#!/bin/bash

# find specific files
files=$(find . -type f -name '*.JPG')

# use newline as file separator (handle spaces in filenames)
IFS=$'\n'

for f in ${files}
do
 # read file modification date using stat as seconds
 # adjust date backwards (1 month) using date and print in correct format
 # change file time using touch
 touch -t $(date -v -1m -r $(stat -f %m  "${f}") +%Y%m%d%H%M.%S) "${f}"
done

Here's my modified script that forced the date to the year "2014":
#!/bin/bash

# find specific files
#files=$(find . -type f -name '*.JPG')

# use newline as file separator (handle spaces in filenames)
IFS=$'\n'

for f in $*
do
 # read file modification date using stat as seconds
 # adjust date backwards (1 month) using date and print in correct format
 # change file time using touch
 touch -t $(date -v +1y -r $(stat -f %m  "${f}") +2014%m%d%H%M.%S) "${f}"
done

I now realize I could have done a more generic version:
#!/bin/bash

# find specific files
#files=$(find . -type f -name '*.JPG')

# use newline as file separator (handle spaces in filenames)
IFS=$'\n'

for f in $*
do
 # read file modification date using stat as seconds
 # adjust date backwards (1 month) using date and print in correct format
 # change file time using touch (+1y adds a year "-1y" subtracts a year)
 # Below line subtracts a year
 touch -t $(date -v -1y -r $(stat -f %m  "${f}") +%Y%m%d%H%M.%S) "${f}"
 # Below line adds a year
 # touch -t $(date -v +1y -r $(stat -f %m  "${f}") +%Y%m%d%H%M.%S) "${f}"
done

To use this file you would need to write it and
chmod +x fn

to execute:
./fn files-to-change

fn=your-file-name-that-is-your-command
Example
./fn *.JPG

will change the date by minus one year in the directory where you are.

A: Touch can reference a file's date all by itself, no need to call date or use command substitution. Here's a bit from touch's info page:
`-r FILE' `--reference=FILE'
     Use the times of the reference FILE instead of the current time.
     If this option is combined with the `--date=TIME' (`-d TIME')
     option, the reference FILE's time is the origin for any relative
     TIMEs given, but is otherwise ignored.  For example, `-r foo -d
     '-5 seconds'' specifies a time stamp equal to five seconds before
     the corresponding time stamp for `foo'.  If FILE is a symbolic
     link, the reference timestamp is taken from the target of the
     symlink, unless `-h' was also in effect.

For example, to add 8 hours to a file's date (filename of file quoted just in case of spaces, etc):
touch -r "file" -d '+8 hour' "file"

Using a loop over all files in the current dir:
for i in *; do touch -r "$i" -d '+8 hour' "$i"; done

I've heard that using a * and letting for pick the filenames itself is safer, but using find -print0 | xargs -0 touch ...  should handle most crazy characters like newlines, spaces, quotes, backslashes in a filename. (PS. try not to use crazy characters in filenames in the first place).
For example, to find all files in thatdir whose filenames start with an s, and add one day to those file's modified timestamp, use:
find thatdir -name "s*" -print0 | xargs -0 -I '{}' touch -r '{}' -d '+1 day' '{}'

A: Easiest way - accessed and modified will be the same:
touch -a -m -t 201512180130.09 fileName.ext

Where:
-a = accessed
-m = modified
-t = timestamp - use [[CC]YY]MMDDhhmm[.ss] time format

If you wish to use NOW just drop the -t and the timestamp.
To verify they are all the same:
stat fileName.ext
See: man touch


text:
Q: How to get program to not throw "Error: Can't load Floyd's algorithm library" another question for all of you-
So i am trying to get a program called Pysomap to work (its basically ISOMAP but for python[http://web.vscht.cz/spiwokv/pysomap/]), i follow the directions best as i can, building it on Ubuntu, Windows, and Fedora (prebuilt libraries), but cant seem to get it to work. On windows (which is the preferred implementation platform), every time i go to python and import pysomap, it gives me the above error. Anybody know how to solve this?
Thanks
-J

A: I had a look at the code because Isomap is a cool algorithm. The code doesn't look like it was written  by someone familiar with Python, and the whole floyd extension module compilation is sort of shoddy - it actually didn't build for me, and I'm pretty sure that's your problem (they catch the import exception for the module and print out the error that you give).
I changed some hard-coded stuff in build_floyd.sh to different hard-coded values for my system. (A proper build system would make this unnecessary). Here's what worked in my Ubuntu system. I tested and it ran ok.
#!/bin/sh
# run this script to generate library for Floyd's
# algorithm library

echo "generating input files using SWIG ..."
swig -python floyd.i

echo "compiling ..."
# change compiler if you use other than gcc
gcc -c floyd.c floyd_wrap.c -I/usr/include/python2.6 -fPIC

echo "linking ..."
ld -shared floyd.o floyd_wrap.o -o _floyd.so

#echo "for SELinux you must run chcon ..."
#chcon -t textrel_shlib_t _floyd.so

You may also have to change the first line in demo.py to #!/usr/bin/env python.

A: In the pysomap directory, create a setup.py file with the following content:
from distutils.core import setup, Extension

setup(name="pysomap",
      version="2007.07",
      url ="http://web.vscht.cz/spiwokv/pysomap/",
      description="A library for isometric feature mapping.",
      license='Unknown',
      author="Vojtech Spiwok",
      py_modules=["floyd", "pysomap"],
      ext_modules=[Extension('_floyd', ["floyd_wrap.c", "floyd.c"])]
      )

Build the _floyd extension (assuming you have a Python distutils compatible C compiler installed):
python setup.py build_ext --inplace

Run demo.py:
python demo.py

Calculating distance matrix ............    2.24 s
Using epsilon-isomap, epsilon = 0.500000, calculating 2-dimensional embedding
Calculating graph matrix ...............    1.21 s
Calculating the shortest path matrix ...    2.22 s
Multidimensionally scalling ............    7.11 s
--------------------------------------------------
Total procedure ........................   12.79 s

A: This source code is over 5 years old and the build script for floyd looks to assume hard-coded python2.4.
It seems pretty clear that your floyd module did not build. You will most likely have to go back to the build step and ensure that you are properly generating a _floyd.so.
If you built it correctly, then this should not fail for you:
python -c "import _floyd"


text:
Q: What changes does an object undergo during a cast in .net? I would like to know what happens to the object when we do a cast. Does the layout of the object gets restructured or does the method table changes or is it only to ensure my assignments don't break during runtime ?

A: The honest answer is it depends.  Some conversions types just involve boxing and unboxing, which just changes the way the code is interpreted at runtime.  The underlying object doesn't actually change.  This type of casting is involved with casts between, for example, from string to object (as a string is an object, as is everything in C#).
http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx
Alternatively, if there's custom/user-defined cast operators involved, then anything could happen.  The cast could create a completely new object that is a representation of the original that was cast.  An example of this kind of cast would be an int to a string.
http://msdn.microsoft.com/en-us/library/09479473.aspx

A: As all others have pointed out a cast by itself doesn't change the object being cast.
That said, there is a point worth making about the ability to overload the behavior of explicit conversions, which appear at first glance as casts. If a type overloads an explicit conversion operator then it could (although it really shouldn't) change the object being converted.
 public class EvilClass
 {
     public int SomeProperty { get; set; }

     public static explicit operator SomeOtherType(B bObj)
     {
         obj.SomeProperty = -1;

         return SomeOtherType.CreateFromEvilClass(bObj);
     }
 }

Then, to the user, this looks like a cast:
 EvilClass evilClass = new EvilClass();
 evilClass.SomeProperty = 42;

 SomeOtherType sot = (SomeOtherType)evilClass;   // looks like cast..

 Console.WriteLine(evilClass.SomeProperty);     // Will print -1, not 42

A: Nothing. A cast changes the logical assumption what a pointer points to.
Nothing in the object does change - all what happens is that a check is done whether the objet is of the assumed type.
If you have A and B : A, and a = new A()
Then basically
var B = (B) a
asks the compiler to check that A is actually a B.
Now, if a is ever created as instance of C (C:A) then - this can and will blow at this point.

A: If you cast a reference type, nothing happens. It is just a runtime check that the object is actually of the specified type. In some situations - like Byte to Double - the value will change to match the new data type. Actually it will not change but you will get a new value of the new data type that represents the same value. If it comes to user defined conversions it is up to the implementation what happens.

A: Usually nothing happens to the underlying data - it just determines how the code is interacting with the object.
However - some "casts" actually do a conversion, meaning they change the underlying data of an object.
For example:
(double)(int)1.1;

converts 1.1 to an integer (which truncates to 1), then converts back to a double, which in this case would return 1.0.
You can also define explicit conversions for reference types:
public static explicit operator Celsius(Fahrenheit fahr)
{
    return new Celsius((5.0f / 9.0f) * (fahr.degrees - 32));
}

Fahrenheit fahr = new Fahrenheit(100.0f);
Console.Write("{0} Fahrenheit", fahr.Degrees);
Celsius c = (Celsius)fahr;

Note that technically the original data didn't change in either case - the cast returns a new object with new data.

A: None!
All you are doing is "pretending" that it is a different type. Of course, if it doesn't inherit from that type (or is actually an instance of the type when downcasting) the cast fails and you get nothing (null) when using the "as" operator to cast, and explicit (C-Style) cast will throw.
Unless, that is, you are dealing with value types (especially number types). If you do the following:
double myDouble = 1.5f;
int myInt = (int)myDouble;
double myOtherDouble = (double)myInt;

You will get 1 for myInt and myOtherDouble, because the number is truncated when performing the conversion. Most of the other value types don't even support this kind of casting, because the conversion is not defined.


text:
Q: Session variable not being picked up in meteor helper I have a select drop down. A change event triggers session variable to be set. I want to use this session variable to populate a table, however, the session variable is not being read by the template. Where am I going wrong?
<template name ='defaultTemplate'>
        Select the Schema
        <select required="true"  class="form-control" id="schemaNameId">

            {{ #each schemaNames}}
            <option value="{{schemaName}}">{{schemaName}}</option>
            {{/each}}
        </select>

The console log at this point, indicate undefined. After I select something from the drop-down, that value gets set as the session variable.
This table below is in continuation to the above template. However, the console log does not seem to print anything pertaining to schemaLabel helper

                Label
                Current Value
                New Value

            {{#each schemaLabels}}

                {{this.label}}
                {{this.value}}

        {{/each}}

</template>

Event:
At first, the session variable value is undefined. As I keep changing the selected element in the drop down, the session variable value keeps changing, this is good.
Template.defaultTemplate.events({
  "change #schemaNameId": function(event, template){
    var selectValue = template.$("#schemaNameId").val();
    // console.log(selectValue +" is selected from dropdown - message logged in events");
    Session.set("selectedSchema",selectValue);
    console.log(Session.get("selectedSchema")+ " is session variable set - message logged in events");
  }
});

Helpers:
As I keep changing the drop down, console log below also keeps changing, this is again a good sign since my session variable is reachable within the helper.
Template.defaultTemplate.schemaNames({
   schemaNames: function () {
               console.log(Session.get("selectedSchema")+ " is session variable - message logged in defaultTemplate:schemaNames");
       return Defaults.find({},{schemaName:1}).map(function(c) {return {schemaName : c.schemaName};
       });
   },

However, for this below function, the console log doesn't print anything at all! meaning that control never gets to this point, even though all of this is in the same helper class.
schemaLabels: function() {
       var selectedSchema = Session.get("schemaName");
       console.log(Session.get("schemaName") +"is the selectedSchema - message logged in defaultTemplate:schemaLabels");
       return Defaults.find({schemaName:selectedSchema},{_id:0,schemaName:0}).map(function(c) {return {label : c.label, value: c.value};});

   }
});

UPDATE:
Upon further tinkering, I noticed that the session variable is called from within schemaLabels helper function only once at the very beginning. It's set to undefined. After that, call to this is never made. So no matter what dropdown I select, the table does not populate anything.

A: I don't understand why you think that schemaLabels helper should be call.
You are using two different Session variables (selectedSchema and schemaName), so these helpers are separated.
So if you want that everytime you change selectedSchema(Session), schemaLabels helpers called, you have to modify schemaLabels like this:
schemaLabels: function() {
       var foo = Session.get("selectedSchema");
       var selectedSchema = Session.get("schemaName");
       console.log(Session.get("schemaName") +"is the selectedSchema - message logged in defaultTemplate:schemaLabels");
       return Defaults.find({schemaName:selectedSchema},{_id:0,schemaName:0}).map(function(c) {return {label : c.label, value: c.value};});

   }


text:
Q: How to evaluate $\displaystyle \lim_{x \to \infty}\frac{8-\sqrt{x}}{8+\sqrt{x}}$ $$\displaystyle \lim_{x \to \infty}\dfrac{8-\sqrt{x}}{8+\sqrt{x}}$$
I tried rationalizing the numerator:
$$\lim_{x \to \infty}\dfrac{8-\sqrt{x}}{8+\sqrt{x}} \times \dfrac{(8-\sqrt{x})}{(8-\sqrt{x})}$$
$$\lim_{x \to \infty}\dfrac{64-16\sqrt{x}+x}{64-x}$$
Is this correct? how do I proceed from here?

A: We can rewrite the expression as $$\lim \limits_{x \to \infty} (-1 + \frac{16}{8 + \sqrt x})$$
The second term goes to zero, thus the limit is $-1$.

A: Another approach, although this may not be rigorous:
As $x\to \infty$, $\sqrt{x}$ dominates, being the highest power in both  the numerator and denominator, hence
$$\require{cancel}\lim_{x\to\infty}\frac{8−\sqrt{x}}{8+\sqrt{x}}=\lim_{x\to\infty}\frac {-\cancel{\sqrt{x}}}{+\cancel{\sqrt{x}}}=−1$$

A: Try dividing each term by $\sqrt{x}$ instead. Intuitively, it is the dominating term as $x$ gets large:
$$
\lim_{x \to \infty}\dfrac{8-\sqrt{x}}{8+\sqrt{x}}
= \lim_{x \to \infty}\dfrac{\frac{8}{\sqrt x}-1}{\frac{8}{\sqrt x}+1}
= \dfrac{0-1}{0+1}
= -1
$$

A: First of all get rid of the square root: since squaring is a continuous function and $\lim_{t\to\infty}t^2=\infty$, you have
$$
\lim_{x\to\infty}\frac{8-\sqrt{x}}{8+\sqrt{x}}=
\lim_{t\to\infty}\frac{8-\sqrt{t^2}}{8+\sqrt{t^2}}=
\lim_{t\to\infty}\frac{8-t}{8+t}
$$
Now you have reduced to the limit at infinity of a rational function, for which there's an easy criterion. Suppose $a_m\ne0$ and $b_n\ne0$; then
$$
\lim_{t\to\infty}
  \frac{a_mt^m+a_{m-1}t^{m-1}+\dots+a_0}{b_nt^n+b_{n-1}t^{n-1}+\dots+b_0}
$$
can be rewritten as
$$
\lim_{t\to\infty}
  \frac{t^m\left(a_m+\dfrac{a_{m-1}}{t}+\dots+\dfrac{a_0}{t^m}\right)}
       {t^n\left(b_n+\dfrac{b_{n-1}}{t}+\dots+\dfrac{b_0}{t^n}\right)}
=\lim_{t\to\infty}\frac{a_mt^m}{b_nt^n}
$$
So this limit is

*

*$\infty$ if $m>n$ and $\frac{a_m}{b_n}>0$;

*$-\infty$ if $m>n$ and $\frac{a_m}{b_n}<0$;

*$0$ if $n>m$

*$\dfrac{a_m}{b_n}$ if $m=n$.

In your case $m=n=1$, $a_1=-1$ and $b_1=1$.

A: I'll add two more ways of solving.

*

*L'Hôpital's rule states that if $\lim_{x \to \infty}{f(x)} = \lim_{x
    \to \infty}{g(x)} = \infty$ then
$$ \lim_{x \to \infty} \frac{f(x)}{g(x)} = \lim_{x \to \infty}
    \frac{f'(x)}{g'(x)} $$
In this case
$$
    \lim_{x \to \infty} \frac{8-x^{1/2}}{8+x^{1/2}} = \lim_{x \to \infty}
    \frac{-\frac 1 2 x^{-1/2}}{\frac 1 2 x^{-1/2}} = \lim_{x \to \infty} (-1) = -1
    $$

*Let $t^2=x$. Then, $\lim_{x \to \infty} t = \lim_{x \to \infty} \sqrt{x} = \infty $. Consequently:
$$
    \lim_{x \to \infty} \frac{8-\sqrt x}{8+\sqrt x} = \lim_{t \to \infty} \frac{8-\sqrt {t^2}}{8+\sqrt {t^2}} = \lim_{t \to \infty} \frac{8-|t|}{8+|t|} = \lim_{t \to \infty} \frac{8-t}{8+t} = -1
    $$


text:
Q: Scrapy - how to manage cookies/sessions I'm a bit confused as to how cookies work with Scrapy, and how you manage those cookies.
This is basically a simplified version of what I'm trying to do:

The way the website works:
When you visit the website you get a session cookie.
When you make a search, the website remembers what you searched for, so when you do something like going to the next page of results, it knows the search it is dealing with.

My script:
My spider has a start url of searchpage_url
The searchpage is requested by parse() and the search form response gets passed to search_generator()
search_generator() then yields lots of search requests using FormRequest and the search form response.
Each of those FormRequests, and subsequent child requests need to have it's own session, so needs to have it's own individual cookiejar and it's own session cookie.

I've seen the section of the docs that talks about a meta option that stops cookies from being merged. What does that actually mean? Does it mean the spider that makes the request will have its own cookiejar for the rest of its life?
If the cookies are then on a per Spider level, then how does it work when multiple spiders are spawned? Is it possible to make only the first request generator spawn new spiders and make sure that from then on only that spider deals with future requests?
I assume I have to disable multiple concurrent requests.. otherwise one spider would be making multiple searches under the same session cookie, and future requests will only relate to the most recent search made?
I'm confused, any clarification would be greatly received!

EDIT:
Another options I've just thought of is managing the session cookie completely manually, and passing it from one request to the other.
I suppose that would mean disabling cookies.. and then grabbing the session cookie from the search response, and passing it along to each subsequent request.
Is this what you should do in this situation?

A: from scrapy.http.cookies import CookieJar
...

class Spider(BaseSpider):
    def parse(self, response):
        '''Parse category page, extract subcategories links.'''

        hxs = HtmlXPathSelector(response)
        subcategories = hxs.select(".../@href")
        for subcategorySearchLink in subcategories:
            subcategorySearchLink = urlparse.urljoin(response.url, subcategorySearchLink)
            self.log('Found subcategory link: ' + subcategorySearchLink), log.DEBUG)
            yield Request(subcategorySearchLink, callback = self.extractItemLinks,
                          meta = {'dont_merge_cookies': True})
            '''Use dont_merge_cookies to force site generate new PHPSESSID cookie.
            This is needed because the site uses sessions to remember the search parameters.'''

    def extractItemLinks(self, response):
        '''Extract item links from subcategory page and go to next page.'''
        hxs = HtmlXPathSelector(response)
        for itemLink in hxs.select(".../a/@href"):
            itemLink = urlparse.urljoin(response.url, itemLink)
            print 'Requesting item page %s' % itemLink
            yield Request(...)

        nextPageLink = self.getFirst(".../@href", hxs)
        if nextPageLink:
            nextPageLink = urlparse.urljoin(response.url, nextPageLink)
            self.log('\nGoing to next search page: ' + nextPageLink + '\n', log.DEBUG)
            cookieJar = response.meta.setdefault('cookie_jar', CookieJar())
            cookieJar.extract_cookies(response, response.request)
            request = Request(nextPageLink, callback = self.extractItemLinks,
                          meta = {'dont_merge_cookies': True, 'cookie_jar': cookieJar})
            cookieJar.add_cookie_header(request) # apply Set-Cookie ourselves
            yield request
        else:
            self.log('Whole subcategory scraped.', log.DEBUG)

A: Three years later, I think this is exactly what you were looking for:
http://doc.scrapy.org/en/latest/topics/downloader-middleware.html#std:reqmeta-cookiejar
Just use something like this in your spider's start_requests method:
for i, url in enumerate(urls):
    yield scrapy.Request("http://www.example.com", meta={'cookiejar': i},
        callback=self.parse_page)

And remember that for subsequent requests, you need to explicitly reattach the cookiejar each time:
def parse_page(self, response):
    # do some processing
    return scrapy.Request("http://www.example.com/otherpage",
        meta={'cookiejar': response.meta['cookiejar']},
        callback=self.parse_other_page)

A: def parse(self, response):
    # do something
    yield scrapy.Request(
        url= "http://new-page-to-parse.com/page/4/",
        cookies= {
            'h0':'blah',
            'taeyeon':'pretty'
        },
        callback= self.parse
    )

A: Scrapy has a downloader middleware CookiesMiddleware implemented to support cookies. You just need to enable it. It mimics how the cookiejar in browser works.

*

*When a request goes through CookiesMiddleware, it reads cookies for this domain and set it on header Cookie.

*When a response returns, CookiesMiddleware read cookies sent from server on resp header Set-Cookie. And save/merge it into the cookiejar on the mw.

I've seen the section of the docs that talks about a meta option that stops cookies from being merged. What does that actually mean? Does it mean the spider that makes the request will have its own cookiejar for the rest of its life?
If the cookies are then on a per Spider level, then how does it work when multiple spiders are spawned?

Every spider has its only download middleware. So spiders have separate cookiejars.
Normally, all requests from one Spider shares one cookiejar. But CookiesMiddleware have options to customize this behavior

*

*Request.meta["dont_merge_cookies"] = True tells the mw this very req doesn't read Cookie from cookiejar. And don't merge Set-Cookie from resp into the cookiejar. It's a req level switch.

*CookiesMiddleware supports multiple cookiejars. You have to control which cookiejar to use on the request level. Request.meta["cookiejar"] = custom_cookiejar_name.

Please the docs and relate source code of CookiesMiddleware.

A: I think the simplest approach would be to run multiple instances of the same spider using the search query as a spider argument (that would be received in the constructor), in order to reuse the cookies management feature of Scrapy. So you'll have multiple spider instances, each one crawling one specific search query and its results. But you need to run the spiders yourself with:
scrapy crawl myspider -a search_query=something

Or you can use Scrapyd for running all the spiders through the JSON API.

A: There are a couple of Scrapy extensions that provide a bit more functionality to work with sessions:

*

*scrapy-sessions allows you to attache statically defined profiles (Proxy and User-Agent) to your sessions, process Cookies and rotate profiles on demand

*scrapy-dynamic-sessions almost the same but allows you randomly pick proxy and User-Agent and handle retry request due to any errors


text:
Q: Keeping result data in same order as inserted I've data inserted into table dept like this
Dept  Deptname
1     '1  dept'
5     '5   dept'
10     '10 dept'
20     '20 dept'
4      '4  DEPT'
3      '3 DEPT'

And after matching dept from Dept table to Emp table i want to display the matched results in the same deptname order along with avg sal of dept.
Result should be like this
Deptname  avgsal
'1  dept'   1000
'5  dept'   1100
'10  dept'  2000
'20  dept'  1500

How to achieve result in same order with displaying only deptname and avg sal

A: use order by , there is no way without using order by to show result any particular order
  order by Dept asc

A: You can try the following code:
select dept.deptname,
       (select avg(emp.sal) from emp where emp.dept = dept.dept) as avgsal
  from dept

By calculating average salary inside SELECT clause you will retain the order of data shown as you see them when you simply select from your dept table (and NOT ordered by dept or deptname). If I am correct, that's exactly what you want.
I hope I helped!


text:
Q: What is the difference between launch.json and task.json in visual studio code? Why do we have two configurations to setup the build environment in Visual Studio Code? What is the difference between them?

A: They are not both used to setup the build configuration.
launch.json is used for to launch an app for debugging. It has settings geared for things like mapping to your workspace source code or defining the Chrome port to use.
To use a configuration from launch.json, you select it on the Debug panel and click the run button.
tasks.json is used to execute anything else you may want, be that source code formatters, bundlers or a SASS compiler.
To use a configuration from tasks.json, you select Run Task from the command list.
Here's an example of how they differ in purpose:
I have an Angular 5 application that connects to a .NET web service.
I have one task configured to run the web service, using a command that fires up IISExpress. I have another task configured to run the Angular app using ng serve, which recompiles the app when files change. I execute these two tasks whenever I reopen VS Code, or when the web service changes.
I have two launch configurations as well: One to launch Chrome and start the debugger, and another to debug a page already loaded in Chrome. These I execute whenever I start a debug session.


text:
Q: FetchXML Filter out Duplicate Values I have a program that pulls Invoices from our CRM Dynamics Online system into a .csv file.
Sometimes our salespeople create multiple invoices on the same Order in CRM, and I need a way to remove any duplicate invoices on the .csv.
I would like to only pull invoices with distinct order numbers. How would this be achieved? I've been working all morning with distincts to no avail.
My code:
private EntityCollection GetInvoices(Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy crmService)
    {
        string fx = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true'>
                <entity name='invoice'>
                    <attribute name='invoiceid' alias='InvoiceId' />
                    <attribute name='customerid' alias='ShipTO' />
                    <attribute name='shipto_postalcode' alias='ShipZip' />
                    <attribute name='shipto_line2' alias='ShipAddr2' />
                    <attribute name='shipto_line1' alias='ShipAddr1' />
                    <attribute name='shipto_stateorprovince' alias='ShipState' />
                    <attribute name='shipto_country' alias='ShipCountry' />
                    <attribute name='shipto_city' alias='ShipCity' />
                    <attribute name='neu_customerponumber' alias='PO' />
                    <attribute name='paymenttermscode' alias='Terms' />
                    <attribute name='createdon' alias='ShipDate'/>
                    <attribute name='ordernumber' alias='InvoiceNo' />
                            ";
        fx += GetInvoiceFilter();
        fx += @"
                    <link-entity name='salesorder' from='salesorderid' to='salesorderid' visible='false' link-type='outer' alias='order1'>
                        <attribute name='datefulfilled' alias='FirstOfShippingDate' />
                        <link-entity name='systemuser' from='systemuserid' to='ownerid' visible='false' link-type='outer' alias='systemuser1'>
                            <attribute name='fullname' alias='SalesRep' />
                        </link-entity>
                    </link-entity>
                    <link-entity name='invoicedetail' from='invoiceid' to='invoiceid' visible='false' link-type='outer' alias='invoicedetail1'>
                        <attribute name='neu_percentdiscount' alias='Discount' />
                        <attribute name='invoicedetailid' alias='InvoiceDetailId' />
                        <attribute name='baseamount' alias='Amount' />
                        <attribute name='extendedamount' alias='Sales' />
                        <link-entity name='product' from='productid' to='productid' visible='false' link-type='outer' alias='product1'>
                            <attribute name='neu_division' alias='Division' />
                            <attribute name='producttypecode' alias='Desc' />
                            <attribute name='productnumber' alias='CatalogNumber' />
                        </link-entity>
                    </link-entity>
                    <link-entity name='account' alias='account1' to='customerid' from='accountid'>
                         <attribute name='accountnumber' alias='CustID' />
                    </link-entity>
                </entity>
                </fetch>";

        return crmService.RetrieveMultiple(new FetchExpression(fx));

    }

    private string GetInvoiceFilter()
    {
        string fetchFilter = "";

        fetchFilter = @"<filter type='and'>";

        if (txtOrderName.Text.Length > 0)
        {
            fetchFilter += @"<condition attribute='ordernumber' operator='eq' value='";
            fetchFilter += txtOrderName.Text;
            fetchFilter += "' />";
        }
        else
        {
            fetchFilter += @"<condition attribute='statuscode' operator='eq' value='1' />";
            fetchFilter += @"<condition attribute='neu_exportedtopeachtree' operator='null' />";
            fetchFilter += @"<condition attribute='createdon' operator='on-or-after' value='";
            fetchFilter += dtpFrom.Text;
            fetchFilter += "' />";
            fetchFilter += " <condition attribute='createdon' operator='on-or-before' value='";
            fetchFilter += dtpTo.Text;
            fetchFilter += "' />";
        }

        fetchFilter += @"</filter>";

        return fetchFilter;
    }

A: The distinct clause on the fetch statement only filters out duplicate ids that come back in the result set.  To filter our your dupes based on order number, you'll have to do that programmatically after the results come back.


text:
Q: resource classPath file convert to byte array not working Hi guys i trying to convert a pdf file to byte array but it dosn't work for me when i trying to get the file from the classPath resource using the classLoader and after that transform it to byte array it doesn't work i don't have a null array but the getting array length it's not ok and when i write this byte array as a file i have an damaged file and i can't opend it.
A last thing when i trying to get the file using the path like (c://java//files//test.pdf) it's working and byte array length it's ok and when i write the array as a file i have exactly the some file in input. another thing the getting file length using classLoader and using path is exactly the some
My code is :
public static void main(String[] args) {

        try {

            // convert file to byte[]
            byte[] bFile = readBytesFromFile("C:\\TEMP\\test.pdf");
            byte[] bytes = readBytesFromFileResources();

            System.out.println(bFile.length);//60255
            System.out.println(bytes.length);//14463
}
 private static byte[] readBytesFromFile(String filePath) {

        FileInputStream fileInputStream = null;
        byte[] bytesArray = null;

        try {

            File file = new File(filePath);
            bytesArray = new byte[(int) file.length()];

            //read file into bytes[]
            fileInputStream = new FileInputStream(file);
            fileInputStream.read(bytesArray);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

        return bytesArray;

    }

    private static byte[] readBytesFromFileResources() {

        ClassLoader classLoader = ReadFile.class.getClassLoader();
        File file = new File(classLoader.getResource("test.pdf").getFile());
        FileInputStream fileInputStream = null;
        byte[] bytesArray = null;

        try {
            bytesArray = new byte[(int) file.length()];

            //read file into bytes[]
            fileInputStream = new FileInputStream(file);
            fileInputStream.read(bytesArray);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

        return bytesArray;

    }

A:
A last thing when i trying to get the file using the path like
  (c://java//files//test.pdf) it's working and byte array length it's ok
  and when i write the array as a file i have exactly the some file in
  input.

c://java//files//test.pdf is probably not in the classpath.
So, you cannot use the classloader to load the file as the classloader will not be able to find it.
Either you move the file in the classpath  (if it makes sense), either you load the file with the filesystem dependent way as you write in your question :
File file = new file("c://java//files//test.pdf)";


text:
Q: 10 fold cross-validation in one-against-all SVM (using LibSVM) I want to do a 10-fold cross-validation in my one-against-all support vector machine classification in MATLAB.
I tried to somehow mix these two related answers:

*

*Multi-class classification in libsvm

*Example of 10-fold SVM classification in MATLAB
But as I'm new to MATLAB and its syntax, I didn't manage to make it work till now.
On the other hand, I saw just the following few lines about cross validation in the LibSVM README files and I couldn't find any related example there:

option -v randomly splits the data into n parts and calculates cross
  validation accuracy/mean squared error on them.
See libsvm FAQ for the meaning of outputs.

Could anyone provide me an example of 10-fold cross-validation and one-against-all classification?

A: It may be confusing you that one of the two questions is not about LIBSVM. You should try to adjust this answer and ignore the other.
You should select the folds, and do the rest exactly as the linked question. Assume the data has been loaded into data and the labels into labels:
n = size(data,1);
ns = floor(n/10);
for fold=1:10,
    if fold==1,
        testindices= ((fold-1)*ns+1):fold*ns;
        trainindices = fold*ns+1:n;
    else
        if fold==10,
            testindices= ((fold-1)*ns+1):n;
            trainindices = 1:(fold-1)*ns;
        else
            testindices= ((fold-1)*ns+1):fold*ns;
            trainindices = [1:(fold-1)*ns,fold*ns+1:n];
         end
    end
    % use testindices only for testing and train indices only for testing
    trainLabel = label(trainindices);
    trainData = data(trainindices,:);
    testLabel = label(testindices);
    testData = data(testindices,:)
    %# train one-against-all models
    model = cell(numLabels,1);
    for k=1:numLabels
        model{k} = svmtrain(double(trainLabel==k), trainData, '-c 1 -g 0.2 -b 1');
    end

    %# get probability estimates of test instances using each model
    prob = zeros(size(testData,1),numLabels);
    for k=1:numLabels
        [~,~,p] = svmpredict(double(testLabel==k), testData, model{k}, '-b 1');
        prob(:,k) = p(:,model{k}.Label==1);    %# probability of class==k
    end

    %# predict the class with the highest probability
    [~,pred] = max(prob,[],2);
    acc = sum(pred == testLabel) ./ numel(testLabel)    %# accuracy
    C = confusionmat(testLabel, pred)                   %# confusion matrix
end

A: Mainly there are two reasons we do cross-validation:

*

*as a testing method which gives us a nearly unbiased estimate of the generalization power of our model (by avoiding overfitting)

*as a way of model selection (eg: find the best C and gamma parameters over the training data, see this post for an example)

For the first case which we are interested in, the process involves training k models for each fold, and then training one final model over the entire training set.
We report the average accuracy over the k-folds.
Now since we are using one-vs-all approach to handle the multi-class problem, each model consists of N support vector machines (one for each class).

The following are wrapper functions implementing the one-vs-all approach:
function mdl = libsvmtrain_ova(y, X, opts)
    if nargin < 3, opts = ''; end

    %# classes
    labels = unique(y);
    numLabels = numel(labels);

    %# train one-against-all models
    models = cell(numLabels,1);
    for k=1:numLabels
        models{k} = libsvmtrain(double(y==labels(k)), X, strcat(opts,' -b 1 -q'));
    end
    mdl = struct('models',{models}, 'labels',labels);
end

function [pred,acc,prob] = libsvmpredict_ova(y, X, mdl)
    %# classes
    labels = mdl.labels;
    numLabels = numel(labels);

    %# get probability estimates of test instances using each 1-vs-all model
    prob = zeros(size(X,1), numLabels);
    for k=1:numLabels
        [~,~,p] = libsvmpredict(double(y==labels(k)), X, mdl.models{k}, '-b 1 -q');
        prob(:,k) = p(:, mdl.models{k}.Label==1);
    end

    %# predict the class with the highest probability
    [~,pred] = max(prob, [], 2);
    %# compute classification accuracy
    acc = mean(pred == y);
end

And here are functions to support cross-validation:
function acc = libsvmcrossval_ova(y, X, opts, nfold, indices)
    if nargin < 3, opts = ''; end
    if nargin < 4, nfold = 10; end
    if nargin < 5, indices = crossvalidation(y, nfold); end

    %# N-fold cross-validation testing
    acc = zeros(nfold,1);
    for i=1:nfold
        testIdx = (indices == i); trainIdx = ~testIdx;
        mdl = libsvmtrain_ova(y(trainIdx), X(trainIdx,:), opts);
        [~,acc(i)] = libsvmpredict_ova(y(testIdx), X(testIdx,:), mdl);
    end
    acc = mean(acc);    %# average accuracy
end

function indices = crossvalidation(y, nfold)
    %# stratified n-fold cros-validation
    %#indices = crossvalind('Kfold', y, nfold);  %# Bioinformatics toolbox
    cv = cvpartition(y, 'kfold',nfold);          %# Statistics toolbox
    indices = zeros(size(y));
    for i=1:nfold
        indices(cv.test(i)) = i;
    end
end

Finally, here is simple demo to illustrate the usage:
%# laod dataset
S = load('fisheriris');
data = zscore(S.meas);
labels = grp2idx(S.species);

%# cross-validate using one-vs-all approach
opts = '-s 0 -t 2 -c 1 -g 0.25';    %# libsvm training options
nfold = 10;
acc = libsvmcrossval_ova(labels, data, opts, nfold);
fprintf('Cross Validation Accuracy = %.4f%%\n', 100*mean(acc));

%# compute final model over the entire dataset
mdl = libsvmtrain_ova(labels, data, opts);

Compare that against the one-vs-one approach which is used by default by libsvm:
acc = libsvmtrain(labels, data, sprintf('%s -v %d -q',opts,nfold));
model = libsvmtrain(labels, data, strcat(opts,' -q'));


text:
Q: Cubic function: Sign of the range (Precalculus) For the function $(x-1)(x-2)(x+1)\le0$ I found that $y=0$ when $x$ is either $-1, 1$ or $2$.
Now I have issues finding if $y$ is positive or negative when $x$ is between $1$ and $2$. By plotting above function I can see that $y$ is negative when $x$ is between $1$ and $2$, but when I replace $\frac12$ ($x$ value between $1$ and $2$) in the above function I got $\frac98$ which is "positive" but it is not $\le0$:
$$(x-1)(x-2)(x+1)\le0$$
$$(1/2-1)(1/2-2)(1/2+1)\le0$$
$$(-1/2)(-3/2)(3/2)\le0$$
$$(9/8)\le0$$
So, I don't know how to calculate sign of the range (if $y$ is positive or negative) of the cubic function in this case. For other ranges (less than $1$ and greater than $2$) I was able to correctly calculate sign (if $y$ is positive or negative).

A: $\frac12$ is not between $1$ and $2$. You should have tried something like $\frac32$ instead, which evaluates to $-\frac58$.

A: The function ''comes from below and goes to above'' if you consider its graph since the polynomial has odd degree and positive leading coefficient; i.e., the function is negative below $-1$, it is positive between $-1$ and $1$, it is negative between $1$ and $2$ and positive above $2$. My Eileen, 11th grade, can draw such a function.
So its positive between $-1$ and $1$. Your calculation for $x=1/2$ is correct.


text:
Q: List the nuget package from nexus server I want to get the nuget package list from some source
(https://nexus.sample.com) like that.When I try a below code
string void main(string args[])
{
  Process commandProcess = new Process();
  commandProcess.StartInfo.UseShellExecute = false;
  commandProcess.StartInfo.FileName = @"C:\Nuget\nuget.exe"; // this is the path of curl where it is installed;
  commandProcess.StartInfo.Arguments ="list -Verbose -AllVersions -Source http://nexus.sample.com/repository/nuget-hosted/";
  commandProcess.StartInfo.CreateNoWindow = true;
  commandProcess.StartInfo.RedirectStandardInput = true;
  commandProcess.StartInfo.RedirectStandardOutput = true;
  commandProcess.StartInfo.RedirectStandardError = true;
  commandProcess.Start();
  commandProcess.WaitForExit();
  string output = commandProcess.StandardOutput.ReadToEnd();
}

the command console was not run.If I set StartInfo.RedirectStandardOutput= false.the command console was run.but I can't read the output value.Plese give any suggestion.

A: Instead of running the executable, why don't you just use NuGet.Core to list all packages ?
IPackageRepository repo = PackageRepositoryFactory.Default.CreateRepository("http://nexus.sample.com/repository/nuget-hosted");

foreach (IPackage p in repo.GetPackages())
{
    Console.WriteLine(p.GetFullName());
}

For more infos :  Play with Packages, programmatically!


text:
Q: npm 'sass' package compile empty file in watch mode I use the npm sass library to compile my ".scss" file and it works really well without any problem but in watch mode, after some file save it starts to produce an empty file. I restart the app and it compiles successfully again.
my watch file is at this link:
sass builder file
I don't know if this is my watcher problem or sass problem or even windows file system problem.
can anyone check to help me to fix this problem?

A: I try many ways to fix this issue and I found the problem is the Windows file system.
in the windows file system if I save a file for a short moment depend on your system performance the file get empty and refill again so to fix this issue I add the setTimeout function in watch mode about 500ms so when user save scss file and we detect change first we wait 500ms then execute build function.
//before
 if (fileName && event == "change") {
   this.buildSassFile(fileConfig);
 }
//after
 if (fileName && event == "change") {
   setTimeout(()=>{
     this.buildSassFile(fileConfig);
   },300);

 }


text:
Q: Release source code for client I'm working for a client on their new website.
It's my last mission, so another developer is going to continue my work after my final delivry.
In order to accelerate the process of "switching developer", my client asks me to give an access of the source code to the next developer.. but as my mission is not finished yet (98% of the website is OK) I risk that the new developer steals the code and the client refuses to pay me.
Is there any tool allowing me to securely give the new developer an access to view my code, ask questions, etc without allowing him to steal it (at least easily) ?
Thank you.

A: No, this seems more like a legal/contract issue. If the other developer can see the source, he could always duplicate it.

A: In short, no: If they see they source code, they can duplicate it.
However, if your client simply wants the new developer to have an idea of how your code is structured, you could send them UML diagrams of the Class Hierarchy and the flow of the site.
I hope this helps.


text:
Q: How to create multi pods to run test case in bash scrips we have many test cases and want run one case(need execute multi command to run the test) in one pod. for example, we have 1000 cases, and we want to create 1000 pods in bash scripts with pod yaml template. is there any easy way to start/monitor/terminate the pods ?
current i just use the jenkins pipeline to get the pod and run the test in parallel. i just want to try use bash scripts to manage the flow but not sure what is the best way.


text:
Q: How to develop a ruby-on-rails application across multiple domains? Im rather new to Rails, but one of my clients plans to operate multiple very similar web platforms on different domains, which means most of the source/application code is identical (e.g. models/controllers). However, there could be some minor code changes or additions for the certain applications. If that circumstance is hard to achieve, at least the CSS files/images/views will be different though.
What's a good way to deal with this issue? Excluding the mentioned (different) files in the deployment and add them manually where needed? Though, this cannot really be the best solution?!
I'd obviously love to avoid copying and modifying the same project several times (per web application).

A: IMO, it has less to do with Rails and more with the way you keep your code versioned.
Firstly, I'd suggest you to use a distributed version control system (I recommend Git), then keep the common code in a branch (i.e. master), and create at least one branch per domain.
http://book.git-scm.com/

A: Create a Rails Engine for your core functionality. Then create separate rails applications that use your engine. Within each application, you should be able to override the bits that need customization or add additional functionality to the app.


text:
Q: Difference between creating foreign key and 1 to 1 identifying relationship in MySQL Workbench I am drawing up an ER model for a to-be application using MySQL workbench.
Being new to MySQL workbench, just wanted to understand how creating a foreign-key and 1-to-1 identifying relationship are different
Table: Employee
Column1: EmployeeID, Type INT [Primary Key]
Column2: Name, Type Varchar(45)

Table: EmployeeDetails
Column1: EmployeeID, Type INT [Primary Key]
Column2: Address, Varchar(100)

If I create a foreign key on EmployeeDetails table employeeid column that references employee table EmployeeID column, how is it different than creating a 1-to-1 identifying relationship?

A: Foreign keys and relationships are the same concept, just from different views. FKs are the entitity used in the database while relationships are their visualization in a model. In your model you only create relationships. You can edit their properties in the relationship editor (e.g. by double clicking on a relationship) to be 1:1, 1:n, identifying or not, mandatory etc. The different relationship tools are just convenience tools for the same thing.


text:
Q: Simulate output with 3 cases Physically is possible to simulate such situation on a board, using electronic components.
I got 2 inputs A and B , with 3 possible values for each one (-1,0,1). My final aim is to achieve this following truth table
     A |  B | result
    –1 | –1 | +1
    –1 | +1 |  0
     0 |  0 |  0
     0 | +1 | +1
    +1 | –1 |  0
    +1 |  0 | +1
    +1 | +1 | -1

A: In pseudo code:
if (A equals B)
    result = A * -1
else
    result = A + B

A: Yes it is absolutely possible and this what todays CPUs are using. The so called logic gates.
Of course depending on your project but won't probably need Intel processor to redo your work but much simpler components doing just that. See the above link for example components doing it.


text:
Q: Calling python functions with and without print() statement Earlier I was thinking about something in python for a while and I couldn't think of an answer. Hear me out.
def main():
    return 'hello people of stack overflow'
main()

VS
def main():
    return 'hello people of stack overflow'
print(main())

In the first simple program, nothing prints but runs, and the return code is 0. I wonder if python actually runs this program, and if it does, where is the output stored? Thanks


text:
Q: Delphi 7 : how to generate class hierarchy? I am seeking to understand someone else's code in Delphi 7 (I suspect that newer version have this built in, but I don't want to spring > $1k for the newest version).
Are their any (preferably FOSS) tools which will help me generate a class hierarchy diagram?

Actually, the class browser in GExperts is ok. Maybe not as good as the accepted answer, but just one of a great collection of tools

A: AFAIK ModelMaker 6.2 was included with Delphi 7, it's a UML tool. You can import your source code in it and generate class diagrams etc, I really don't remember anymore all of it's features, but I do remember that ModelMaker is awesome tool and it's sure worth a look.
Update: Model Maker (now MMX) is now free for all supported Delphi IDEs

A: You can take a look at our SynProject tool.
Synopse SynProject is an open source application for code source versioning and automated documentation of Delphi projects.
There is a pascal source parser, which will create all classes hierarchy documentation.
And it's much more than a parser: you can write the whole Specifications/Architecture/Design/Test/Release documents list in an integrated manner.
There are some tutorials, screenshots and resulting documentation sample in the above link.

A: Peganza's Pascal Analyzer (not FOSS)

A: You can use ESS-model from SourceForge.
If you Load and .PAS (also .DPR, .CLASS,...) with some classes this program generate a Class Diagram and some Documentation. It's free and you can access to code source.

Regards

A: Doc-o-matic's documentation generator creates class hierarchies. They have a free express version you can try.


text:
Q: How to get user's google api version on android? I'm facing some rare problem. I have a device running on Android API 14. Anytime I try to use MapActivity I get the same error - java.lang.NoClassDefFoundError: android.security.MessageDigest. On other 99% devices it works perfect.
After some digging, I've found root of the problem.

The error is the result of a device manufacturer or ROM creator using
  an older maps library with a new version of Android. (more at
  What is 'android.security.MessageDigest''?)

The functionality of MapActivity isn't required for application, so I want to check if user has such device.
How can I get user's google api version on android?

A: Use Google map v2.
You want to use Google map console to register SHA-1 for signing the key in Google api console.
The complete tutorial can be found here.


text:
Q: Run node server using gulp task I am new to gulp.
I need to run node server using gulp but without using any of its plugin.
Is it possible?
If not then what is the best plugin for it in gulp system.

A: You should try gulp-nodemon plugin. It's useful plugin for development with node.
// Gulpfile.js
var gulp = require('gulp')
  , nodemon = require('gulp-nodemon')
  , jshint = require('gulp-jshint')

gulp.task('lint', function () {
  gulp.src('./**/*.js')
    .pipe(jshint())
})

gulp.task('develop', function () {
  nodemon({ script: 'server.js'
          , ext: 'html js'
          , ignore: ['ignored.js']
          , tasks: ['lint'] })
    .on('restart', function () {
      console.log('restarted!')
    })
})

For more details you can visit here.
Also
If you don't want use any plugin, you can start node without it like below:
var gulp = require('gulp')
  , exec = require('child_process').exec

gulp.task('nodestart', function (cb) {
  exec('node bin/www.js', function (err, stdout, stderr) {
    console.log(stdout);
    console.log(stderr);
    cb(err);
  });
})

A: There are several plugins available with gulp.

*

*Nodemon (https://www.npmjs.com/package/gulp-nodemon)

*Express (https://www.npmjs.com/package/gulp-express)

*Develop Server (https://www.npmjs.com/package/gulp-develop-server)

if you wish to start the node server without any plugin you can try out the following.
var exec = require('child_process').exec;

gulp.task('start', function (callback) {
    exec('node server/app.js', function (err, stdout, stderr) {
        console.log(stdout);
        console.log(stderr);
        callback(err);
    });
});

A: if you are in development environment gulp-supervisor
// Gulpfile.js
var gulp = require( "gulp" ),
    supervisor = require( "gulp-supervisor" );

gulp.task( "supervisor-simple", function() {
    supervisor( "test/fixture/server.js" );
} );

gulp.task( "supervisor-all", function() {
    supervisor( "test/fixture/server.js", {
        args: [],
        watch: [ "test" ],
        ignore: [ "tasks" ],
        pollInterval: 500,
        extensions: [ "js" ],
        exec: "node",
        debug: true,
        debugBrk: false,
        harmony: true,
        noRestartOn: false,
        forceWatch: true,
        quiet: false
    } );
} );

if you are in production environment, i recommand gulp pm2 plugin, gulp-connect-pm2


text:
Q: remove/disable top-links-container form header How do i completely remove/disable top-links-container from the header?

A: You can write this code in your theme local.xml file
located app/design/fronend/YourPackage/YourTheme/layout/local.xml
<default>
  <reference name="header">
    <remove name="top.links">
  </reference>
</default>

A: Add below code in your local.xml :
    <default>
            <reference name="header">
                <remove name="top.links"/>
            </reference>
    </default>

if you want to remove the particular link:

*

*Customer links:  app\design\frontend\rwd\yourtheme\layout\customer.xml

comment below code :
<!--<action method="addLink" translate="label title" module="customer">
  <label>My Account</label>
  <url helper="customer/getAccountUrl"/>
  <title>My Account</title><prepare/><urlParams/>
  <position>10</position>
</action>-->

2. Wishlist Link: app\design\frontend\rwd\yourtheme\layout\wishlist.xml
Comment code :
<!--<reference name="top.links">
 <block type="wishlist/links" name="wishlist_link" />
 <action method="addLinkBlock"><blockName>wishlist_link</blockName></action>
</reference>-->

*Cart & Checkout Link :      app\design\frontend\rwd\yourtheme\layout\

Comment code :
<!--<reference name="top.links">
 <block type="checkout/links" name="checkout_cart_link">
  <action method="addCartLink"></action>
  <action method="addCheckoutLink"></action>
 </block>
</reference> –->