text:
Q: How to Fix vulnerability at Manifest.xml file in Android for an exposed component I need to expose a module of my app to more than one app. Since, I did not specify any permission or expose attribute of the activity.
<activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/Theme.Transparent">
</activity>

With this, I can able to launch the application and i can able to do activity from other application too by calling intent.
But, When I integrate with SonarQube, its showing vulnerability and stating below issue.

Implement permissions on this exported component.

To fix this issue, I have tried following method.

*

*If I implement the permission to refer, vulnerability removed but I cannot able to run the application (I meant cannot place able to any actions from other app).

In my app, I have defined the permission
<permission android:name="com.myApp.NORMAL_PERMISSION"
    android:description="@string/perm_desc_NORMAL_PERMISSION"
    android:label="@string/perm_label_NORMAL_PERMISSION"
    android:protectionLevel="normal" />

and I refer this permission to my activity as below.
 <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:permission="com.myApp.NORMAL_PERMISSION"
        android:theme="@style/Theme.Transparent">

But, I cannot able to do any action from other app by calling intent. But, vulnerability has been fixed.

*If I add the below field to activity still its listed under vulnerability android:exported= "true"

*if its android:exported= "false", vulnerability removed but app completely is not working
Let me know any other method to fix this vulnerability.

A: In my main activity which hash intent-filter action android.intent.action.MAIN and category android.intent.category.LAUNCHER.
Its intended to be launched from other applications without any special permissions.
So, its require no permission.
<activity
    . . .
    android:exported="true"
    android:permission="" >

That being said defining the permission as empty string resolves the issues and explicitly shows your intent that there are no permissions needed to launch this activity.


text:
Q: Find indexes of multiple minimum in an array in javascript I want to find the indexes of the minimum of an array.
E.g.
var array = [1,2,3,4,1,7,8,9,1];

var min = Math.min.apply( Math, array )
var key = array.indexOf(min);

The problem is that Math.min.apply return only the first index
min = 1 and key = 0
What I want to do is to return
min = 1 and key = [0,4,8];

Is it possible to do it with Math.min.apply?

A: var array = [1,2,3,4,1,7,8,9,1];

function findMinimumIndexes(array) {
    var min = Math.min.apply(Math, array);
    var indexes = [];

    array.forEach(function(item, idx, arr) {
        if (item === min) {
            indexes.push(idx);
        }
    });

    return indexes;
}

console.log(findMinimumIndexes(array));

The function declares the variable indexes and assigns to it an empty array which then it fills up using a forEach call with elements' indexes whose value matches min.
Notice that this only works for primitive values since it uses === to check for equivalence.
To make it work on arrays or objects that are 'deeply equal' to the one you are looking for, you would need a more rigorous implementation.

A: var array = [1,2,3,4,1,7,8,9,1];
var min = Math.min.apply( Math, array )

var arrayWithIndex = array.map(function(element, index) {
    return element + "-" + index;
});

var minValues = arrayWithIndex.filter(function(element) {
    return Number(element.split('-')[0]) === min;
});

var keys = minValues.map(function(element) {
    return Number(element.split('-')[1]);
});

My algorithm is mapping the original array to include a new array that contains both the number and index. I'm then filtering that array for elements, where the number is equal to min, and then mapping again to find the index.
You can also chain these methods
return array.map(function(element, index) {
    return element + "-" + index;
})
.filter(function(element) {
    return Number(element.split('-')[0]) === min;
}).
.filter(function(element) {
    return Number(element.split('-')[1]);
});

A: An Array.prototype.reduce should do the work.

var array = [1, 2, 3, 4, 1, 7, 8, 9, 1];

function getMinKeys(array) {
    var min = Math.min.apply(Math, array);
    return array.reduce(function (r, a, i) {
        a === min && r.push(i);
        return r;
    }, []);
}

document.write('<pre>' + JSON.stringify(getMinKeys(array), 0, 4) + '</pre>');

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I obtain a GDrive access token without using a library? There seems to be very little information about getting started with Google's Drive REST API, besides the Quickstarts section (https://developers.google.com/drive/api/v3/about-sdk). I am trying to use their API in AutoIt, but I can't seem to find out how to generate an access token without using one of the available quickstart libraries. I am aware of the REST API docs (https://developers.google.com/drive/api/v3/reference/), but still, can't find anything about generating the access token. I have already generated a Client ID and a Client Secret though. Any help is appreciated.

A: Google's OAuth endpoints can be used with any library (or you could roll your own, but there are plenty of quality libraries). There is plenty of documentation of OAuth2 at Google, and there is the OAuth2 Playground where you can experiment with OAuth and the Google APIs.
If you have a library, Google's OAuth endpoints are available in the OpenIdConnect discovery doc at https://accounts.google.com/.well-known/openid-configuration


text:
Q: HttpPost method of PartialView in ASP.NET MVC 4 I have a view that contain two partial views. One of them for creating, and the other is list of created(companies). My problem is that, when I try create HttpPost method does not work and calls only Index method again. Please help me to fix this problem.
This is my Index view
@model InvoiceModel.HelperClasses.CompanyViewModel

@{
    ViewBag.Title = "Companies";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@Html.Partial("CreateCompany", Model.Create)

@Html.Partial("CompanyTable", Model.Companies)

A: Use @Html.BeginForm() to define your Model that you are creating so when you post it is all mapped up properly.
@using (Html.BeginForm("(Action)", "(Controller)", FormMethod.Post, null))
{
    (Your model here)

    <input type="submit" value="Save" />
}

@Html.Partial("CompanyTable", Model.Companies)


text:
Q: Content elements as inline elements in a content element My idea is to build a content element with some inline elements. No big problem if the inline elements derive from an other table ... But i want to use other content elements - like news, where you can add content elements to the detail page as inline elements.
The problem is the colPos value - if it is the value of the current column the inline elements are shown twice: once as standalone element and once as inline (it works in news only because news eintries are normally on sysfolders). If i force other values for the colPos entry (like 999 oder -10) i get in the backend always INVALID VALUE ("-10")
Any idea? Is there a possibility?
It would be a nice solution for e.g. a accordion or tabs.
Thanks!

My solution:
There were too many arguements against content elements inline a content element. So i solved it with a content element with inline elements from an other table - the same way as mask would solve the problem. It works for me without the problems which mentioned in the answers. Many thanks!

A: IRRE tt_content to tt_content is notoriously error prone; there are concerns not only with the colPos column but also with recursion. I very strongly advise against it. It breaks translation ability, has problems with workspaces and it potentially treats file references of the children incorrectly.
That said: you can add virtual colPos values by modifying the TCA of tt_content.colPos to add selection values that match your chosen colPos value.

A: The extension Gridelements does this. Why dont you use it?


text:
Q: Is the use of Neo4j's internal ID still not recommended? I am planning to use Neo4j for my current project (a REST API). I've read it is discouraged to use the ID of Neo4j, as the ID can be reused upon a restart for optimisations. However, these threads date a few years back up to 2012. On the official GitHub page of Neo4j, it seems they promised to resolve this issue for Neo4j 2.x (back in 2013). It is now 2016 and Neo4j is on 3.0.
So my question is: has anything changed? Is it still unsafe to expose the ID in the API? Or are we still stuck on UUIDs to guarantee uniqueness?

A: Neo4j internal IDs should not be used to reference nodes or relationships in an external system. These IDs are essentially offsets that point to some place in the filestore to reference a node or relationship.
As you point out, as data is deleted this empty space in the filestore can be reclaimed, meaning that internal IDs can be reclaimed.
If you are referring to a node / relationship in an external system, a common approach is to generate a UUID and store that as a property on the node (using an index so the node can be looked up efficiently).
In Neo4j 3.x there is a user defined function in the APOC library for generating UUIDs from Cypher. For example:
CREATE (p:Person)
SET p.name = "Will",
    p.uuid = apoc.create.uuid()

A: Also have a look at https://github.com/graphaware/neo4j-uuid which will generate the UUIDs for you and make sure nobody can change or delete them, without the need to change your queries.


text:
Q: quintsect an angle with a compass and a straight edge I require to construct a reasonably accurate $9^{\circ}$. And quickly. I learn that the quickest way is to make a straight line of $180^{\circ}$, bisect it (to make $90^{\circ}$), bisect that angle (to create a $45^{\circ}$ angle), and 5-sect* it.
Using a straight edge and a compass, how would I do this accurately? I need the error margin to be below 0.01%.
Additionally, I need proof.
It is on paper, and my pencil is as sharp as possible.

*For extra brownie points, tell me the technical word for 5-secting an angle.

Edit: @kennytm got the brownie points !!

A: You do not quintisect any angles (which is impossible with unmarked straightedge and compasses and an open problem if you have a marked straightedge). Instead, use a more ingenious linear combination.
Study Ptolemy's construction of the regular pentagon given here. (This link is also the source of the illustration given below.)

Once you have constructed the pentagon (or just the needed parts to do the steps below), you then have various ways to render the $9°$ angle. Two are given below:

*

*Angle $PCQ$ measures $36°$ and is bisected by diameter $CD$. Either bisect one of the resulting half-angles or subtract the full angle $PCQ$ from $45°$.

*Draw chord $BC$. This makes a $45°$ angle with diameter $CD$, and the side from $C$ to the unlabeled vertex on the right makes a $54°$ angle with that diameter. The $9°$ angle is the difference between these two angles.


text:
Q: ES 2015 VS 2015 for node.js running task runner explorer I have a ASP.NET 5 project in VS 2015. I'm setting up my gulp tasks and I am using the gulp-chmod module. This allows me to remove read only properties set by TFS in my copy processes. I've used v1.3 of this module sucessfully before in VS 2015 however the new version v2.0 has been upgraded to use ES 2015 features specifically:
note use of const, let
 'use strict';
 const through = require('through2');
 const deepAssign = require('deep-assign');
 const Mode = require('stat-mode');

 const defaultMode = 0o777 & (~process.umask());

 function normalize(mode) {
      let called = false;const through = require('through2');
      const deepAssign = require('deep-assign');
      ...

I get the error:
cmd.exe /c gulp --tasks-simple
<MY_PATH>\node_modules\gulp-chmod\index.js:2
const through = require('through2');
^^^^^
SyntaxError: Use of const in strict mode.
    at Module._compile (module.js:439:25)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (<MYPATH>\gulpfile.js:9:13)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
In the output from Task Runner explorer.
I have the latest version of Node.js installed and off the command line it all works well.
My node path is set to point to ./node_modules/.bin
I checked in the package manager console using node -v and it appears I am using the latest node version.
So how do I control the Node version in use through task manager. I would like it to use ES2015 to compile my modules?
Thanks in advance

A: It sounds like you're running on an older version of Node.js.
I found this github ticket that suggests adding the following to your gulp script to show what version of node you're running under.
https://github.com/sindresorhus/gulp-imagemin/issues/178
console.log('Node version: ' + process.version);

You can go to Tools > Options > Projects and Solutions > External Web Tools to find out where the version of node that VS is using resides.
This question has a fairly elegant solution of moving your "$(PATH)" entry to the top: Gulp task failing when run from VS 2015 Task Runner explorer, but not from command prompt


text:
Q: React controlled input I made a simple react controlled input that store the value in a state and i dont understand why when i press a key for the first time the console log shows "".
Here is my code

class Form extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      value: "",
    };
  }

  handleForm = (e) => {
    console.log("test");

    e.preventDefault();
  };

  handleUsername = (e) => {
    this.setState({ value: e.target.value });

    console.log(this.state);
  };

  render() {
    return (
      <>
        <div>
          <form onSubmit={this.handleForm}>
            <input
              onChange={this.handleUsername}
              type="text"
              placeholder="username"
              value={this.state.value}
            />
            <input type="submit" />
          </form>
        </div>
      </>
    );
  }
}

export default Form;


text:
Q: When using doctrine in phpStorm console it runs in --no-interaction by default I'm having troubles with the console when using PhpStorm in combination with Symfony 2. It runs in --no-interaction mode, and only gives my errors. But when I use the same command in the terminal, it works fine. Somebody knows how I should fix this problem?
In PhpStorm console:

➜ /Applications/MAMP/bin/php/php5.5.3/bin/php /Users/job/PhpstormProjects/prop/app/console doctrine:generate:entity
[InvalidArgumentException]
    The entity name must contain a : ("" given, expecting something like AcmeBlogBundle:Blog/Post)
doctrine:generate:entity [--entity="..."] [--fields="..."] [--format="..."] [--with-repository]
Process finished with exit code 1 at 14:09:35. Execution time: 2.387 ms.

In MacOS terminal it works fine:

➜  ~  /Applications/MAMP/bin/php/php5.5.3/bin/php /Users/job/PhpstormProjects/prop/app/console doctrine:generate:entity
<  Welcome to the Doctrine2 entity generator
< This command helps you generate Doctrine2 entities.
< First, you need to give the entity name you want to generate.
  < You must use the shortcut notation like AcmeBlogBundle:Post.
< The Entity shortcut name:

A: You are using PhpStorm v6, which means Command Line Tools. It indeed has problems with interactive mode, since it only emulates terminal (AFAIK). Check and watch this ticket for details:

*

*http://youtrack.jetbrains.com/issue/WI-16892
If you want to execute such commends from within PhpStorm, I may only suggest to try v7 which has proper Terminal support (local and remote (SSH)). More details in this blog post:

*

*http://blog.jetbrains.com/phpstorm/2013/09/built-in-local-terminal-in-phpstorm-7/

*also: http://blog.jetbrains.com/phpstorm/?s=terminal


text:
Q: Copy Controls from a list to another without the same pointer reference Today I would like to create a copy/paste function for a software I develop.
I have a Panel that contains Controls and I want to copy/paste.
I have a selection tool that permit the user to select different Controls and add this Controls to a List. I have called it "SelectionActuelle".
Then, when the user clicks on "Copy". I would like to add every controls that SelectionActuelle contains into a new List called "PressePapier".
But when I do, it copies the same pointer reference, and I dont want.
I throught that add a Control to another List should copy it and create a new instance but it doesn't.
I tried this example HERE but it doesn't work.
What I have now is only 6 lines (it doesn't work !!) to try to make a copy of the List :
private void bt_copier_Click(object sender, EventArgs e)
    {
        PressePapier.Clear();

        foreach(Control ctr in SelectionActuelle)
        {
            PressePapier.Add(ctr);
        }
        bt_coller.Enabled = true;
    }

How can I simply copy Control to make my Copy/Paste tool ? So is it possible (I think yes but we never know) ?
Have a good day,
Julien

A: Thanks to you, I found out that my structure was not great and I changed it to a simpler structure and more reutilisable.
I will apply this :

You should foreach the selected controls and check it's type, just generate a new instance of that control with it's properties.

But Dr. Coconut, my problem was that .NET does not appreciate some expressions in the code even if I have adapted it... I don't know why. Question of framework version ?


text:
Q: Woocommerce Dynamic Checkout Form fields I am currently working on a wordpress website. I customized my woo commerce checkout page to include an additional form field with this code in my function.php child theme. It works well.
add_action('woocommerce_after_order_notes', 'my_custom_checkout_fields');

function my_custom_checkout_fields($checkout){

echo '

' .__('New Field').'
';

woocommerce_form_field('my_field_name', array(
    'type' =>'text',
    'class'=>array('my-field-class form-row-wide'),
    'label'=>__('Fill this field'),
    'placeholder'=>__('Enter Something'),
    ), $checkout->get_value('my_field_name'));

echo '
';

}

I want to have this form field repeat itself in accordance to the quantity of a product ordered. Lets say I ordered a product 3 times, I want the form field to appear 3 times at the checkout. Help Anyone?

A: Updated - This can be easily with 2 loops inside your hooked function:

*

*The first iterate through each cart item

*The second one for each unit related to the quantity

So for example if you have a 2 cart items: first has a quantity of 3 and second a quantity of 2, you will get 5 custom checkout text fields.
add_action('woocommerce_after_order_notes', 'my_custom_checkout_fields', 20, 1 );
function my_custom_checkout_fields( $checkout ){
     $index = 0;

    echo '

' .__('New Field').'
';

    // First Loop go through cart items
    foreach( WC()->cart->get_cart() as $cart_item ) {
        // 2nd Loop go through each unit related to item quantity
        for( $i = 1; $i <= $cart_item['quantity']; $i++ ) {
            $index++;

            woocommerce_form_field('my_field_name_'.$index, array(
                'type' =>'text',
                'class'=>array('my-field-class form-row-wide'),
                'label'=>__('Fill this field') . ' ' . $index,
                'placeholder'=>__('Enter Something'),
            ), $checkout->get_value('my_field_name_'.$index));

        }
    }

    echo '
';

}

Code goes in function.php file of your active child theme (or active theme). Tested and works


text:
Q: Set Theory Relations Given set $A={1, 2, 3}$ consider the following relation on $A$
$R=\{(1, 1), (2, 1), (3, 3), (3, 2)\}$
Which one of the following statements are true

*

*$R$ is antisymmetric and transitive

*$R$ is antisymmetric but not transitive

*$R$ is not transitive and not antisymmetric

*$R$ is reflexive and antisymmetric

I have 4 as the answer, because:

*

*$R$ is reflexive: $(1, 1), (3, 3)$

*$R$ is antisymmetric: $(2, 1), (3, 2)$ are in $R$ but not $(1, 2), (2, 3)$

But there may also be a case for transitivity because of $(2, 1), (3, 2)$
I'm at a bit of a loss really

A: The relation is not reflexive because $(2,2)\notin R$.  Remember that the definition of reflexivity is that $(a,a)\in R$ for all $a\in A$.
Also, the relation is not transitive, because $(3,2)\in R$ and $(2,1)\in R$, but $(3,1)\notin R$.
Finally, a relation is antisymmetric if the conditions $(a,b)\in R$ and $(b,a)\in R$ imply $a=b$.  Is this true in the $R$ you've given?


text:
Q: How to save image in memory and how to zip all the images in swift? In our project when we captured an image we stored the image in local app path and it's in an encrypted format. And add some information. Finally, we have zip all the image and send it server, this is our current flow.
What we are trying to do is we convert an image into data and encoded a base64 format. But how to zip all the images(we need to capture more than 5 images).
Zip all the base64 format string and send it to the server . How to do that?
Do u have any idea about to save the image in memory and zip all those images and send to the server instead of the store an image in app folder?

A: 1- convert each image into data and encoded a base64 format and zip it :
let strBase64 = imageData.base64EncodedString(options: .lineLength64Characters)
print(strBase64)

zip string using chilkat : https://www.example-code.com/swift/compress_decompress_string.asp
func chilkatTest() {
//  This example requires the Chilkat API to have been previously unlocked.
//  See Compression UnlockComponent for sample code.

var success: Bool
let sb = CkoStringBuilder()

var i: Int
for i = 1; i <= 20; i++ {
    sb.Append("This is the original uncompressed string.\r\n")
}

let compress = CkoCompression()
compress.Algorithm = "deflate"
//  Indicate that the utf-8 byte representation of the string should be compressed.
compress.Charset = "utf-8"

var compressedBytes: NSData
compressedBytes = compress.CompressString(sb.GetAsString())

//  If the compressed data is desired in string format, then get the base64 representation of the bytes.
compress.EncodingMode = "base64"
var compressedBase64: String? = compress.CompressStringENC(sb.GetAsString())
print("Compressed Bytes as Base64: \(compressedBase64!)")

//  Now decompress...
var decompressedString: String? = compress.DecompressString(compressedBytes)
print("The original string after decompressing from binary compressed data:")
print("\(decompressedString!)")

//  To decompress from Base64...
compress.EncodingMode = "base64"
decompressedString = compress.DecompressStringENC(compressedBase64)
print("The original string after decompressing from Base64:")
print("\(decompressedString!)")

}

2- save it in json format :
   [
     {"1": "strBase64FromStep1"},
     {"2": "strBase64FromStep1"},
      .
      .
      .
   ]

3- save the json String to text file :
let file = "file.txt" //this is the file. we will write to and read from it

let text = "some text" //just a text

if let dir = FileManager.default.urls(for: .documentDirectory, in:
    .userDomainMask).first {

    let fileURL = dir.appendingPathComponent(file)

    //writing
    do {
        try text.write(to: fileURL, atomically: false, encoding: .utf8)
    }
    catch {/* error handling here */}

    //reading
    do {
        let text2 = try String(contentsOf: fileURL, encoding: .utf8)
    }
    catch {/* error handling here */}
}

4- save your file url to UserDefaults :
fileURL From step 3

NSUserDefaults.standardUserDefaults().setObject(fileURL, forKey: "path")
NSUserDefaults.standardUserDefaults().synchronize()

5 - use this file any time you want to send to server .


text:
Q: how to declare an array in $_SESSION? I want to declare an array in $_SESSION to store items in a cart, so that each time a user presses the add to cart button that item is added to the array.
i tried
array_push($_SESSION['cart_items'],$_SESSION[product_id]);

but it gives me this error
Warning: array_push() expects parameter 1 to be array, string given in

A: $_SESSION['cart_items'] should be an array.
before you use array_push(), make it an array:
if(!is_array($_SESSION['cart_items'])){ $_SESSION['cart_items'] = array(); }

Then use:
array_push($_SESSION['cart_items'], $_SESSION['product_id']);


text:
Q: UIPageViewController page control not showing when used as a child controller My controller hierarchy is as follows:
Tab View Controller (Parent) -> Main View Controller (Child)
Main View Controller (Parent) -> Page View Controller (Child)
Page View Controller (Parent) -> Secondary View Controller (Child)
When I navigate to the page view controller without setting it as a child view controller (but still within the tab view controller), the page control is visible at the bottom of the screen when I hide the tab bar.
When I use a container view in the Main View Controller to show the page view controller, the page control disappears (even with the tab bar hidden).
Why does this happen? Can I fix it/work around it?

A: Use the "view debugger" and see if the "Page Control" is there:

If it is, you can use this view debugger to figure out why it's not visible (it may be white-on-white; it may be obscured by something else in front of it; it may be off-screen).
If it is not there, then add breakpoints in your presentationCountForPageViewController: (aka presentationCount(for:)) and your presentationIndexForPageViewController: (aka presentationIndex(for:)) and make sure they're getting called like you think they should. Also make sure controller's transition style is UIPageViewControllerTransitionStyleScroll as outlined in the documentation.


text:
Q: Unable to understand dimension mismatch error in Julia I'm a beginner with Julia and ML. I'm attempting to re-use code from the Flux Model Zoo, specifically this, to classify images from this dataset. Below is my version of the code - I modified the data load and the params in the build_model to account for the difference in image size and the number of character types to be classified. The original had 28x28 and 10 digits, the arabic character set had 32x32 images and 28 characters.
function getimages(filename)
    filepath = pwd() * "/images/" * filename

    mtrx = Matrix(DataFrame(CSV.File(filepath)))
    r, _ = size(mtrx)

    v = Vector{Matrix{Int64}}()

    for i = 1:r
        push!(v, reshape(m[i, :], 32, 32))
    end

    v
end

function getlabels(filename)
    filepath = pwd() * "/images/" * filename
    vec(Matrix(DataFrame(CSV.File(filepath))))
end

function load_data(args)
    train_data_file = "csvTrainImages.csv"
    test_data_file = "csvTestImages.csv"
    train_label_file = "csvTrainLabel.csv"
    test_label_file = "csvTestLabel.csv"

    train_data = getimages(train_data_file)
    test_data = getimages(test_data_file)
    train_labels = getlabels(train_label_file)
    test_labels = getlabels(test_label_file)

    xtrain = Flux.flatten(train_data)
    xtest = Flux.flatten(test_data)

    ytrain, ytest = onehotbatch(train_labels, 1:28), onehotbatch(test_labels, 1:28)

    train_loader = DataLoader((xtrain, ytrain), batchsize=args.batchsize, shuffle=true)
    test_loader = DataLoader((xtest, ytest), batchsize=args.batchsize)

    return train_loader, test_loader
end

function build_model(; imgsize=(32,32,1), nclasses=28)
    return Chain(
            Dense(prod(imgsize), 32, relu),
            Dense(32, nclasses))
end

function loss_and_accuracy(data_loader, model, device)
    acc = 0
    ls = 0.0f0
    num = 0
    for (x, y) in data_loader
        x, y = device(x), device(y)
        ŷ = model(x)
        ls += logitcrossentropy(model(x), y, agg=sum)
        acc += sum(onecold(cpu(model(x))) .== onecold(cpu(y)))
        num +=  size(x, 2)
    end
    return ls / num, acc / num
end

@kwdef mutable struct Args
    η::Float64 = 3e-4       # learning rate
    batchsize::Int = 256    # batch size
    epochs::Int = 10        # number of epochs
    use_cuda::Bool = true   # use gpu (if cuda available)
end

function train(; kws...)
    args = Args(; kws...) # collect options in a struct for convenience

    if CUDA.functional() && args.use_cuda
        @info "Training on CUDA GPU"
        CUDA.allowscalar(false)
        device = gpu
    else
        @info "Training on CPU"
        device = cpu
    end

    # Create test and train dataloaders
    train_loader, test_loader = load_data(args)

    # Construct model
    model = build_model() |> device
    ps = Flux.params(model) # model's trainable parameters

    ## Optimizer
    opt = ADAM(args.η)

    ## Training
    for epoch in 1:args.epochs
        for (x, y) in train_loader
            x, y = device(x), device(y) # transfer data to device
            gs = gradient(() -> logitcrossentropy(model(x), y), ps) # compute gradient
            Flux.Optimise.update!(opt, ps, gs) # update parameters
        end

        # Report on train and test
        train_loss, train_acc = loss_and_accuracy(train_loader, model, device)
        test_loss, test_acc = loss_and_accuracy(test_loader, model, device)
        println("Epoch=$epoch")
        println("  train_loss = $train_loss, train_accuracy = $train_acc")
        println("  test_loss = $test_loss, test_accuracy = $test_acc")
    end
end

I get the following error when I train the model. Specifically, during the gradient computation. Could you help me understand which two matrices the error refers to and point me towards a solution? My guess is that it has to do with the build_model params, but I'm not quite sure what needs to change and how.
DimensionMismatch("matrix A has dimensions (32,1024), matrix B has dimensions (1,256)")
macro expansion@interface2.jl:0[inlined]
_pullback(::Zygote.Context, ::typeof(throw), ::DimensionMismatch)@interface2.jl:9
_pullback@matmul.jl:814[inlined]
_pullback(::Zygote.Context, ::typeof(LinearAlgebra._generic_matmatmul!), ::Matrix{Matrix{Float32}}, ::Char, ::Char, ::Matrix{Float32}, ::Matrix{Matrix{Int64}}, ::LinearAlgebra.MulAddMul{true, true, Bool, Bool})@interface2.jl:0
_pullback@matmul.jl:802[inlined]
_pullback(::Zygote.Context, ::typeof(LinearAlgebra.generic_matmatmul!), ::Matrix{Matrix{Float32}}, ::Char, ::Char, ::Matrix{Float32}, ::Matrix{Matrix{Int64}}, ::LinearAlgebra.MulAddMul{true, true, Bool, Bool})@interface2.jl:0
_pullback@matmul.jl:302[inlined]
_pullback@matmul.jl:275[inlined]
_pullback(::Zygote.Context, ::typeof(LinearAlgebra.mul!), ::Matrix{Matrix{Float32}}, ::Matrix{Float32}, ::Matrix{Matrix{Int64}})@interface2.jl:0
_pullback@matmul.jl:153[inlined]
_pullback(::Zygote.Context, ::typeof(*), ::Matrix{Float32}, ::Matrix{Matrix{Int64}})@interface2.jl:0
_pullback@basic.jl:147[inlined] ....

A: Solved by fixing the get images method as below.
function getimages(filename)
    filepath = pwd() * "/images/" * filename

    mtrx = Matrix(DataFrame(CSV.File(filepath)))

    return mtrx'
end


text:
Q: SQL Server registry error I installed SQL Server configuration manager and management studio version 2005, on windows 7 Ultimate.
I added a game server to the database and everything worked fine till where I started configuring the game's database and I was prompted to restart/stop/start the server, this is where I was baffled by the errors. I know there are several ways you can do this restart, but I cannot seem to get any to work for issues unknown to me.
I have tried running cmd prompt using the commands:
 net stop mssql server

also tried manually doing it from management studio, where the option to restart in the pull down menu appears to be unavailable.
It's helpful if I could get rid of this problem before I can move on to extensive table editing as this itself is being a major pain.

A: From the start menu, run: services.msc
Scroll down to Sql Server (SQLEXPRESS)

*

*Replace "SQLEXPRESS" with your instance name

Right click --> Restart


text:
Q: Computer specific ID? I'm trying to generate a specific computer id using Java. I've thought about things like Hard Drive Serials, or Windows Serial Keys, CPU ID's, or MAC Addresses, but other computers could have the same ones.. For instance, If someone pirates a copy of Windows 7 they could have the same serial as someone.. I was wondering if someone could give me a way to generate a computer specific ID that is never changed and is retrievable using Java?
I did some research and found some useful functions. And, I was thinking something like this. But if they change their hardware, It will change the computer ID. Anyone know of something I can use?
public String getComputerID(){
    InetAddress ip = InetAddress.getLocalHost();
    NetworkInterface network = NetworkInterface.getByInetAddress(ip);
    byte[] mac = network.getHardwareAddress();
    String sn = getSerialNumber("C");
    String cpuId = getMotherboardSN();
    return MD5(mac + sn + cpuId);
}

public String MD5(String md5) {
try {
        java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
        byte[] array = md.digest(md5.getBytes());
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < array.length; ++i) {
        sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
    }
        return sb.toString();
    } catch (java.security.NoSuchAlgorithmException e) {
    }
    return null;
}

public String getSerialNumber(String drive) {
String result = "";
    try {
    File file = File.createTempFile("realhowto",".vbs");
    file.deleteOnExit();
    FileWriter fw = new java.io.FileWriter(file);

  StringBufferring vbs = "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n"
                +"Set colDrives = objFSO.Drives\n"
                +"Set objDrive = colDrives.item(\"" + drive + "\")\n"
                +"Wscript.Echo objDrive.SerialNumber";  // see note
    fw.write(vbs);
    FileWriter.close();
      Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
      BufferedReader input =
        new BufferedReader
        (new InputStreamReader(p.getInputStream()));
    String line;
    while ((line = input.readLine()) != null) {
        result += line;
    }
    input.close();
    }
    catch(Exception e){
        e.printStackTrace();
    }
    return result.trim();
}

public String getMotherboardSN() {
String result = "";
try {
File file = File.createTempFile("realhowto",".vbs");
file.deleteOnExit();
FileWriter fw = new java.io.FileWriter(file);

String vbs =
"Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
+ "Set colItems = objWMIService.ExecQuery _ \n"
+ " (\"Select * from Win32_BaseBoard\") \n"
+ "For Each objItem in colItems \n"
+ " Wscript.Echo objItem.SerialNumber \n"
+ " exit for ' do the first cpu only! \n"
+ "Next \n";

fw.write(vbs);
fw.close();
Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
BufferedReader input =
new BufferedReader
(new InputStreamReader(p.getInputStream()));
String line;
while ((line = input.readLine()) != null) {
result += line;
}
input.close();
}
catch(Exception e){
e.printStackTrace();
}
return result.trim();
}

A: I actually do believe you should use something from hardware profile.
A computer can be considered as a set of pieces of hardware, including the network interface.
A typical pattern can be to have combination of a MAC address and a generated ID by a management system that manages computers over the network.
The MAC address to identify uniquely the machine during a registration process to the management system.
As a result of the registration, the management system can return a generated UniqueId,
to be stored on the computer that registered to it, and will later on be used.
After a successful registration, you can replace the network interface card, as the computer does not depend on the MAC address to be identified.
You can also consider using the linux dmidecode utility  (for linux machines,  as you provided a win-based solution,  so for our linux readers,  I would like to suggest a linux alternaties) (if the machine you want to uniquely identify has linux and dmidecoe installed).
Using dmidecoe you can get more hardware profile, and perform some hash function on it, and generate a unique ID that will identify uniquely (with high probability, to be precise) your machine.
Read more about dmidecode here.
Of course, in case you go to "get information on hardware from the operating system" approach (which is dmidecode or what you suggested at the part after getting the MAC address,
You need for a cross platform code to check what is the OS the java program runs on, you do that using this:
System.getProperty("os.name");

A: After looking over everyone's input, and quite a few google searches I've come to this conclusion
In technicality, Seeing as if you removed a component and replaced it, it would be an entirely new computer, to generate a true computer specific ID you would have to get a specific variable from each component in the system, (i.e. the serial number), combine them all, and that would be a "Computer Specific ID". However, Since a computer is so susceptible to change, the closest one would get is to take the LEAST LIKELY TO CHANGE component, and us a specific variable from it for the computer ID. This will generally be the motherboard or another component that is not likely to change. So, The closest one might get would be the serial number (or some other child component) of the motherboard.. In my personal opinion.
Why is the motherboard the least likely to change?
It seems that the motherboard is the last part people consider changing, especially on newer computers. They won't normally change it unless it is absolutely required. Another viable option would be the NIC. It's honestly up to you what piece of hardware you use, But the best one to use would be the one that you think would be the least likely to change.

A: For Disk/Volumes it could be:
    /**
     * Execute system console command 'vol' and retrieve volume serial number
     *
     * @param driveLetter - drive letter in convetion 'X:'
     * @return - Volume Serial Number, typically: 'XXXX-XXXX'
     * @throws IOException
     * @throws InterruptedException
     */
    static final String getVolumeSerial(String driveLetter) throws IOException, InterruptedException {
        Process process = Runtime.getRuntime().exec("cmd /C vol " + driveLetter);
        InputStream inputStream = process.getInputStream();
        InputStream errorStream = process.getErrorStream();
        if (process.waitFor() != 0) {
            Scanner sce = new Scanner(errorStream);
            throw new RuntimeException(sce.findWithinHorizon(".*", 0));
        }
        Scanner scn = new Scanner(inputStream);
        // looking for: ': XXXX-XXXX' using regex
        String res = scn.findWithinHorizon(": \\w+-\\w+", 0);
        return res.substring(2).toUpperCase().trim();
    }


text:
Q: Angular interpret {{}} inside a link function of a custom directive Is there a way to interpret the content of a div having my directive as an attribute :
example :

{{1+1}}

and my link function looks like this :
  link = (scope, element, attrs) =>
  interpretedString = element.text()

in this example interpretedString  is equal to {{1+1}} instead of 2
any help? the scope.$eval evaluates attributes, but what if I want to evaluate the text of a directive?
thanks

A: In order to interpret the string, you need to interpolate it thanks to the angular's $interpolate service.
Example:
link = (scope, element, attrs) =>
  interpretedString = $interpolate(element.text())(scope)

A: Just to back up a bit, the contents of an element could be anything -- an array of element trees, text nodes, comments, and (unless you declare your directive "terminal") it all gets evaluated recursively and could have directives inside directive. I think you'd be much better off passing an interpolated string as an attribute. I mean you could do it this way, but whoever's using your widget wouldn't really expect that.
Something like:

Or even (if that attribute is "primary"):

From there, instead of $interpolate(element.text())(scope) you'd have $interpolate(attrs.myDirective)(scope)
Of course, the nature of Angular is everything is dynamic and can update all the time. What if the expression didn't just have constants, as a real expression likely wouldn't. If it were:
{{1+foo}}

Then the question is do you care about it changing? If not, $interpolate is fine. It captures the initial value. If you do care about it updating, you should use $observe.
attrs.$observe('myDirective', function(val) {
    // if say "foo" is 5, val would be 6 here
});

Then later if you're like scope.foo = 8 the callback runs and passes 9.

A: Alternative is to do
<my-directive ng-bind="1+1" />

var two = $scope.$eval('ngBind');

:-p
.directive('myDirective', function () {
    return {
        restrict: 'E',
        scope: {
            ngBind : '='
        },
        link: function (scope, element, attrs) {
            console.log('expecting string "1+1": '+attrs.ngBind);
            console.log('expecting evaluated string "2": '+scope.$eval('ngBind'));
        }
    };
});

side note:

 is almost the same as
{{val}}
. Except that u save 4 brackets and never see them flashing into view when things might go slower whatsoever reason.


text:
Q: flask jinja2 template renders question marks instead of utf-8 characters I'm working on a flask project. The database has been set to UTF8_bin, but after selecting data from database at the time of rendering the html page, it returns question marks insted of persian alphabet letters in {{ }}. I also have put <meta charset="UTF-8"> in the html file.
In html page:
{% for each in menue %}
    <li>{{ each.txt }}</li>
{% endfor %}

And the output is:

?????????

What is the problem? Only selected utf8 data from database cannot be rendered in {{ }}. Other persian letters in the html page have been rendered well.


text:
Q: A subgroup that contains the powers of 2 of all elements contains the commutator The question is as follow:

$G$ is a group. $N$ is the smallest subgroup of G the contains {$ g^2 | g \in G$}. Prove that $N \triangleleft G$ and $G/N$ is abelian.

So my plan is to use the theorem that states that:

$G'\leq N \iff N\triangleleft G , G/N  $ is abelian

so I have problems to show now that $G'\leq N$ any help is appreciated!.


text:
Q: Why can't an unsigned char properly display a hex value I am trying to create an array of 1 byte values, using unsigned chars to hold the values.
my code looks like this:
unsigned char state[4][4] = {   {0xd4, 0xe0, 0xb8, 0x1e},
                                {0xbf, 0xb4, 0x41, 0x27},
                                {0x5d, 0x52, 0x11, 0x98},
                                {0x30, 0xae, 0xf1, 0xe5}};

Where each value is 2 hex digits which makes a byte. However, when I attempt to print the array out using
    cout << "\nInitial State \n------------------------------------------------------\n";
    for(int x = 0; x < 4; x++)
    {
        for(int y = 0; y < 4; y++)
            cout << hex << setw(2) << setfill('0') << state[x][y] << " ";
        cout << "\n";
    }

I don't get the hex value, but rather weird symbols
Initial State
---------------------
0Ô 0à 0¸ 0
0¿ 0´ 0A 0'
0] 0R 0 0˜
00 0® 0ñ 0å

I understand the 0s come from set(w) and setfill('0') but I don't understand why it isn't showing the proper values. However, if I make the state an unsigned long, I then get the proper values.
So I'm confused. If a char holds exactly one byte, why can't the char display the byte as a hex value?

A: cout is specialized to output the char type as a character, not a number. That goes for unsigned chars too. You get around it by casting to an unsigned int.
cout << hex << setw(2) << setfill('0') << static_cast<unsigned int>(state[x][y]) << " ";


text:
Q: FactoryGirl - using traits not giving expecting result When I define my User factory this way
  FactoryGirl.define do
    factory :user do
      roles {[FactoryGirl.create(:role, :system, :admin)]}
      email "visitor.administration@example.com"
      name  "Visitor Administration"
      password "visitor123"
    end
  end

with the following  Role factory :
    FactoryGirl.define do
      factory :role do
        company "internal"
        group "administration"
        function "visitor"
        activities '{}'
      end
      trait :system do
        group "system"
      end
      trait :admin do
        function "admin"
        activities '{"sheet" => ["create", "update", "delete", "show", "index"] }'
      end
    end

executing
FactoryGirl.create(:user)

gives me the expected result ...
BUT if I try to define a trait in the User factory
  FactoryGirl.define do
    factory :user do
      roles {[FactoryGirl.create(:role)]}
      email "visitor.administration@example.com"
      name  "Visitor Administration"
      password "visitor123"

      trait :system_admin do
        roles {[FactoryGirl.create(:role, :system, :admin)]}
        email "admin.system@example.com"
        name  "Admin System"
        password "admin123"
      end
      factory :system_admin_user,  traits: [:system_admin ]
    end
  end

and I execute now :
user = FactoryGirl.create(:system_admin_user)

Then I get an error :
    (0.3ms)  BEGIN
      SQL (5.4ms)  INSERT INTO "roles" ("group", "function", "activities", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id"  [["group", "system"], ["function", "admin"], ["activities", nil], ["created_at", "2015-09-19 09:08:19.572605"], ["updated_at", "2015-09-19 09:08:19.572605"]]
    PG::NotNullViolation: ERROR:  null value in column "activities" violates not-null constraint
    DETAIL:  Failing row contains (14, internal, system, admin, null, 2015-09-19 09:08:19.572605, 2015-09-19 09:08:19.572605).

Is the activities JSON field incorrectly defined ?

A: Yes, the activities attribute is not written correctly :
activities '{"sheet" => ["create", "update", "delete", "show", "index"] }'

SHOULD BE :
activities {{ sheet: ["create", "update", "delete", "show", "index"] }}


text:
Q: Missing services for Aero Glass on Windows 10? As suggested in this thread http://answers.microsoft.com/en-us/windows/forum/windows_vista-desktop/windows-color-and-appearance-no-aero/ada52f54-8a09-4c5a-95ba-05dc9375fd9a
I tried to locate Desktop Window Manager Session Manager and also start it manual by net start uxsms. Same problem With Themes service. Seems that none of these services are pre installed on my Windows 10 version. Any chance to install them ?

A: The DWM is always running since Windows 8 and can't be really stopped without breaking the new Store Apps/Startmenu.
Also since Windows 8, Microsoft removed the Aero Glass effect. You have to re- enable it with a 3rd party DLL.


text:
Q: How to select everything but a certain html element using beautifulsoup4? Example:
import bs4

html = '''

Android Apps Security provides guiding principles for how to
best design and develop Android apps with security in mind. The book explores
techniques that developers can use to build additional layers of security into
their apps beyond the security controls provided by Android itself.

∨ Full Description ∨

'''
soup = bs4.BeautifulSoup(html)

How do I get the following(a beautifulsoup object) from soup?

Android Apps Security provides guiding principles for how to
best design and develop Android apps with security in mind. The book explores
techniques that developers can use to build additional layers of security into
their apps beyond the security controls provided by Android itself.

A: Simply search for it:
soup.find('p', class_='scroll-down')

I used the class to limit the find, but since there are no other p elements that's a little redundant here.
If, instead, you need to remove the tag, use the above method to first find it, then call .extract() on it to remove it from the document:
>>> soup.find('p', class_='scroll-down').extract()

 Full Description

>>> print soup

Android Apps Security provides guiding principles for how to
best design and develop Android apps with security in mind. The book explores
techniques that developers can use to build additional layers of security into
their apps beyond the security controls provided by Android itself.

Two things: the removed tag is returned from the .extract() method, you could save it for later use. The tag is removed from the document altogether, you'd have to re-add it manually later if you still need it to be in the document anyway.
Alternatively, you could use the .decompose() method, which deletes the tag from the document altogether, without returning a reference. The tag is then gone forever.


text:
Q: Build docker images with local npm packages I want to be able to build images for testing purpose without publishing the changes I made in any of my packages to npm
Here is the structure of the folders:
/backend
  /server
    DockerFile
    package.json
  /http
    package.json
  /api
    package.json
  /dashboard
    DockerFile
    package.json

So each folder is a npm package (and a git repository). Here are the links between these npm packages:

*

*/server requires /http

*/http requires /api

*/dashboard requires /api
When I develop locally I use npm link, but when I want to build the docker images of /server and /dashboard, the npm links are no longer used and the packages are pulled from the published versions hosted on npm during the npm install in the container.
How can I build images based on the changes I made locally ?
I tried to link packages using a relative path in package.json :
"my-http": "file:./../http" instead of "my-http": "0.1.0"
It works locally but it's out of context when I try to build this in docker


text:
Q: Ajax take data from php fault In a php file (ajax_chart.php) I have this

$search=$_POST['present'];
if(!empty($search)){

        include '../main_includes/connect_db.php';
        $present_day = date("d");
        $present_month = date("m");
        $present_year = date("y");
        for ($i=0;$i<=23;$i++){
        $total_visitors_present=[];
        $query="SELECT * FROM visitors WHERE visitor_day=$present_day AND visitor_hour=$i AND visitor_minute<=59   ";
        $select_query= mysqli_query($connect, $query);
        $num_visitors[$i]= intval(mysqli_num_rows($select_query));
        array_push($total_visitors_present, $num_visitors);

        }
        echo json_encode($total_visitors_present[0]);

}

and in another php file (charts.php) in script tag I have the following Ajax code

$.ajax({
                url: 'includes/ajax_chart.php',
                data:{present:'present'},
                type: 'POST',
                success: function (data) {
                     if(!data.error){
                        console.log(data);
                     }
                    }
            });

The console output is weird.
while that i expected to output is the following array
[0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
What am I doing wrong?
How i retrieve the array with ajax?


text: Q: Можно ли с помощью React JS/React Native писать приложения одновременно для iOS/Android и для веба Есть ли техническая возможность создавать с помощью реакта приложение одновременно и для веба и для мобильных платформ? Для мобилок и веба нужен совершенно разный код или пойдет один и тот же с какой-то адаптацией?


text:
Q: Wanted: SQL query to count records meeting certain criteria & return info about highest count I've got a puzzle for you... I have database table that stores scores for a game.  It records the name of the player, the name of their computer opponent, and the final scores for each:

 player_name | bot_name | player_score | bot_score
---------------------------------------------------
  Alan         bot1          2            1
  Bill         bot1          3            0
  Casey        bot2          5            0
  Alan         bot2          0            3
  Bill         bot3          1            2
  Casey        bot3          4            0
  Alan         bot4          0            3

For each bot, the player with the largest margin of victory is the one with the highest (player_score - bot_score) value.  I want to write a SQL query that finds the player who has the most largest margins of victory.
Example: In the table above, Bill has the largest margin of victory over bot1, Casey has the largest margins of victory over bot2 and bot3, and no player has a largest margin of victory over bot4 since no player won against that bot.  So, Bill has one largest margin of victory, and Casey has two.  In this scenario, the query should return "Casey" and "2" since that's the player with the most largest margins of victory.
Is it possible to write a single SQL query to retrieve this information?

A: This is rather complicated.  For each bot, you can the player (or players) with the largest margin by doing:
select bot_name, max(player_score - bot_score) as max_diff
from t
where player_score > bot_score
group by bot_name;

To get the players with the maximum score is a bit trickier:
select t.*
from t
where (t.player_score - t.bot_score) =
       (select max(player_score - bot_score) as max_diff
        from t t2
        where t2.player_score > t2.bot_score and
              t2.bot_name = t.bot_name
       );

But, that is still not what you want.  You want the players with the largest such wins.  Here is how you get the list in order:
select t.player_name, count(*) as num_wins
from t
where (t.player_score - t.bot_score) =
       (select max(player_score - bot_score) as max_diff
        from t t2
        where t2.player_score > t2.bot_score and
              t2.bot_name = t.bot_name
       )
group by t.player_name
order by num_wins desc;


text:
Q: Trigger ripple effect on form submit by enter key I have a simple form with submit button. When i click the button, there is a nice ripple effect. I want the same ripple effect to appear when a user submits the form using the enter key. I couldn't find how to do it.
using angular 6 with the latest material version

A: try to add keydown.enter event listener to your form, which will trigger button's ripple:
<form (keydown.enter)="btn.ripple.launch({centered:true})">
  <input>
  <button #btn mat-button>Click me!</button>
</form>

please note, I added btn template reference to mat button.
If you want to trigger the ripple from your ts file:
import {Component, ViewChild} from '@angular/core';
import {MatButton} from '@angular/material';
  .
  .
  .
@ViewChild('btn') btn: MatButton;
  .
  .
  .
ripple() {
  this.btn.ripple.launch({
    centered: true
  });
}

and your HTML should look like:
<form (keydown.enter)="ripple()">
  <input>
  <button #btn mat-button>Click me!</button>
</form>

USING ngSubmit instead of keydown.enter will also work:
<form (ngSubmit)="ripple()">
  <input>
  <button #btn mat-button>Click me!</button>
</form>

STACKBLITZ


text:
Q: Hide/Show elements in a ListView item after a click I have a Fragment which contains a ListView. The ListView items contain TextView and Button elements. When I press a button in the listview I would like to update the row in which I clicked the button to hide the button and display a TextView (the text inside the TextView also needs to be updated once every second).
Is this possible and how?
MyFragment
public class MyFragment extends Fragment implements ClickedListener {
    private static final String TAG = MyFragment.class.getSimpleName();

    private MyListAdapter myListAdapter;

    public MyFragment() {
        // Required empty public constructor
        Log.e(TAG, "MyFragmment");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Log.e(TAG, "onCreateView");
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_mine, container, false);

        ListView myListView = view.findViewById(R.id.listView);

        myListAdapter = new MyListAdapter(getActivity(), MyFragment.this);
        myListView.setAdapter(myListAdapter);

        getList();

        return view;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && isResumed()) {
            getList();
        }
    }

    private void getList() { //This part works no need to discuss this.
        List<Items> items = myItemsContent.getItems();
                    myListAdapter.setItems(items);
    }

    @Override
    public void buttonClicked(Item item) {
        doSomeStuff();
        myListAdapter.displayTextView();
    }
}

MyListAdapter
public class MyListAdapter extends ArrayAdapter<Item> {
    private static final String TAG = MyListAdapter.class.getSimpleName();

    private Button myButton;
    private TextView status;

    private final Context context;

    public interface ClickedListener {
        void buttonClicked(Item item);
    }

    private final ClickedListener clickedListener;

    public MyListAdapter(@NonNull Context context, ClickedListener clickedListener) {
        super(context, R.layout.list_item);

        this.context = context;
        this.clickedListener = clickedListener;
    }

    public void setItems(List<Items> items) {
        super.addAll(items);
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        View row = convertView;

        if (row == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = inflater.inflate(R.layout.list_item, parent, false);
        }

        TextView itemName = row.findViewById(R.id.list_item_name);
        myButton = row.findViewById(R.id.myButton);
        status = row.findViewById(R.id.status);

        Item item = getItem(position);
        if (item != null) {
            itemName.setText(item.getName());

            myButton.setOnClickListener(v -> clickedListener.buttonClicked(item));
        }

        return row;
    }

    public void displayTextView() {
        myButton.setVisibility(View.INVISIBLE);
        status.setVisibility(View.VISIBLE);
    }
}

A: you can get button click event in fragment and then set boolean variable to model and according to that show/hide text view in adapter.

A: I will do it more reliable way. I think you know the working of the Listview and adapter.
So You have list of Items that you are passing to your adapter. I will change my Item class in following way. Please add these two fields in the Item class which I think is the model
public boolean isButtonVisible = true;
public boolean isTextViewVisible = false;

Go a head create there header and setter.Or change any default value
now in your getView method of Adapter do this in the end //Or just copy replace
    @NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    View row = convertView;

    if (row == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        row = inflater.inflate(R.layout.list_item, parent, false);
    }

    TextView itemName = row.findViewById(R.id.list_item_name);
    myButton = row.findViewById(R.id.myButton);
    status = row.findViewById(R.id.status);

    Item item = getItem(position);
    if (item != null) {
        itemName.setText(item.getName());

        myButton.setOnClickListener(v -> clickedListener.buttonClicked(item));

       if(item.isButtonVisible){
        myButton.setVisiblity(View.VISIBLE);
       }else{
       myButton.setVisibilty(View.GONE)
       }

       if(item.isTextViewVisible){
        myTextView.setVisiblity(View.VISIBLE);
       }else{
       myTextView.setVisibilty(View.GONE)
       }

    }

    return row;
    }

Finally do this in your fragment inside following method
 @Override
   public void buttonClicked(Item item) {
    doSomeStuff();
    item.setButtonVisibility (Whatever you want to do true or false)
    ite.setTextViewVisible  (Whatever you want to do true or false)
    myListAdapter.notifyDataSetChanged();
    }

Important: You need to call myListAdapter.notifyDataSetChanged() in
  the end. you do not need to call myListAdapter.displayTextView(); as
  this will not work


text:
Q: Staging, Testing, and Version Control Server Spec Recommendations I am going to be working with a few outside developers for some ASP.NET projects and wanted to setup a co-located server for version control, testing, and staging client sites until they are ready to deploy.
I already have the ISP and have a 10 megabit connection burstable to 100, so I don't think bandwidth is going to be an issue.
My question is, what specs should the server itself have? I was thinking of getting a Dell server with the following specs:

*

*Dual Core Intel Pentium E2180, 2.0GHz, 1MB Cache, 800MHz FSB

*4GB, DDR2, 800MHz, 4x1GB,Dual Ranked DIMM

*RAID 1 160GB 7.2K RPM SATA 3Gbps hard drives

*Windows Server 2008

Will this suffice?

A: If the project isn't too big that looks fine.  My experience with version control systems on large projects is that memory tends to be the biggest bottleneck.  I'd make sure you can upgrade to 8GB RAM if the project is going to be large.


text:
Q: Modeling counting problems - Proof verification I'm trying to model the following problem in a meaningful way, and also I need help with part (b).

For part (a), I'm thinking that one way to see the problem is to group the players into $n$ pairs, represented by the sets $A_i$, for $i =1,2,...,n$. Now if the color is not an issue, then we simply need to enumerate the set $$\{\{A_1,A_2,...,A_n\}: \dot{\bigcup} A_i = [2n], |A_i|=2\}$$
which is
$$\frac{{2n\choose 2}{2n-2\choose 2}...{2\choose 2}}{n!}$$
But for each pair, there are 2 ways to give the 2 players the color black or white. So we want to multiply each term in the numerator by 2, which gives the final answer:
$$\frac{[{2n\choose 2}\times 2]\times[{2n-2\choose 2}\times 2]...[{2\choose 2}\times 2]}{n!} = \frac{{2n\choose 2}{2n-2\choose 2}...{2\choose 2}}{n!} \times 2^n$$
For part (b), I use the same $A_i$'s, but each one of them is also paired up with a $t_j$, for $j=1,2,...n$, denoting the table that the pair sit in. The set that need to be enumerated would be:
$$\{\{(A_1,t_1),(A_2,t_2)...,(A_n,t_n)\}: \dot{\bigcup} A_i = [2n], |A_i|=2, \dot{\bigcup} t_j = [n], |t_j|=1\}$$
Here I get stuck since I don't know how to reason about the number of time a particular set $\{(A_1,t_1),(A_2,t_2)...,(A_n,t_n)\}$ is counted, i.e. what the denominator of the fraction would be.
So my questions are:
(1) Is the analysis above correct?
(2) If yes, how do I incorporate the information about the colors into the set representation in part (a)?
(3) What is the denominator in part (b)?
=======================================================
Edit:
For part (c), following the same strategy, I think the set that needs to be enumerated would be:
$$\{\{(A_1,t_1,a_1),(A_2,t_2,a_1)...,(A_n,t_n,a_n)\}: \dot{\bigcup} A_i = [2n], |A_i|=2, t_j = \{0,1\}^1, a_i \in A_i\}$$
where $t_j$ is a binary variable denoting whether the pairs sit at the special table or not, and $a_i$ is the variable for color.
The count would be:
$$\frac{{2n\choose 2}{2n-2\choose 2}...{2\choose 2}}{n!} \times 4^n$$
Please (4) verify this solution.

A: *

*Yes.

*For each pair $A_i$, you just need to specify the white player. For example, you could use
$$
\{((A_1,a_1),(A_2,a_2),\dots,(A_n,a_n)):\bigsqcup A_i=[2n],|A_i|=2,a_i\in A_i\}
$$

*For (b), each seating arrangement can be represented in $n!$ ways by the notation $((A_1,t_1),(A_2,t_2),\dots,(A_n,t_n))$, corresponding to the $n!$ permutations of the list of the $n$ tuples $(A_i,t_i)$.  Therefore, the denominator is $n!$.The set-builder description you are using obscures the simplicity of the answer. There are $\binom{2n}2$ choices for who sits at the first table, $\binom{2n-2}2$ for who sits at the second table, and so on. Thus, the count is $\binom{2n}2\binom{2n-2}2\cdots\binom{2}2$.

A: This problem looks like it was specially designed to be scholastically approached by species and e.g.f.'s.
1) We have a n-sets of 2-sets. The species is $E_n(E_2(X))$ and the e.g.f. is:
$\frac{1}{n!} \left(\frac {x^2}{2!}\right)^n = \frac{(2n)!}{n!(2^n)} \frac {x^{2n}}{(2n)!} $
the number required is the coefficient $ \frac{(2n)!}{n!(2^n)} $
2) We have a n-string of 2-sets. The species is $L_n(E_2(X))$ and the e.g.f. is:
$\left(\frac {x^2}{2!}\right)^n = \frac{(2n)!}{2^n} \frac {x^{2n}}{(2n)!} $
The number required is the coefficient $ \frac{(2n)!}{2^n} $
3) We have a pair and a (n-1)-set of pairs.
The species is $L_2(X).E_{n-1}(L_2(X))$ and the e.g.f. is:
$ x^2 \frac{\left(x^2\right)^{n-1}}{(n-1)!}= \frac{(2n)!}{(n-1)!} \frac {x^{2n}}{(2n)!} $
The number required is the coefficient $ \frac{(2n)!}{(n-1)!} $


text:
Q: I can't get records from a stored procedure I can't get records from a stored procedure. If I run from SQL Server, I get records. If I call it from .NET, I get records... but if I call it from PHP, I don't get records.
I am using PHP 5.3.3 on CentOS 6. I am using mssql. All others SP are ok.
I tried
$provider = 1010;
$array = array();
$stmt2 = mssql_init("[dbo].[PORA_sp_GET_LetterGenerationRecords]");
mssql_bind($stmt2, "@ProviderID", $provider, SQLINT4);
$letters = mssql_execute($stmt2);
while($row = mssql_fetch_assoc($letters)){
    $array[] = $row;
}
mssql_free_statement($stmt2);
echo '
'; print_r($array); echo '
';

and I have
Array
(
)

I tried too
$array = array();
$letters = mssql_query('EXEC [dbo].[PORA_sp_GET_LetterGenerationRecords] @ProviderID = 1010');
while($row = mssql_fetch_assoc($letters)){
    $array[] = $row;
}
echo '
'; print_r($array); echo '
';

and I got
Array
(
)

I included
echo 'MSSQL error: '. mssql_get_last_message();

and the answer:
MSSQL error:

I am very curious. Right now I am running the SP step by step from PHP. It's a shameful.
I tried:
    $provider = 1010;
    $array = array();
//    $letters = mssql_query('EXEC [dbo].[PORA_sp_GET_LetterGenerationRecords] @ProviderID = 1010');
    $stmt2 = mssql_init("[dbo].[PORA_sp_GET_LetterGenerationRecords]");
    mssql_bind($stmt2, "@ProviderID", $provider, SQLINT4);
    $letters = mssql_execute($stmt2);
    if($letters){
        echo mssql_num_rows($letters);
        while($row = mssql_fetch_assoc($letters)){
            $array[] = $row;
        }
        mssql_free_statement($stmt2);
        echo '
'; print_r($array); echo '
';
    }
    else{
        echo 'MSSQL error: '. mssql_get_last_message();

        echo error_get_last();
    }

and same answer.

A: Your code looks fine but for some reason the sql statement is being terminated.
So you need to debug this,I would suggest first try to get it to work with the parameter hard coded:
try {
    $array = array();
    $result = mssql_query('EXEC [dbo].[PORA_sp_GET_LetterGenerationRecords] @ProviderID = 1010');
    while ($row = mssql_fetch_assoc($result))
    {
        $array[] = $row;
    }
    var_dump($array);
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
    error_log($e->getMessage());// or log it to a txt file
    echo 'MSSQL error: '. mssql_get_last_message();
    echo 'Last error: '.error_get_last();

}

You should also run SQL profiler and filter on the exception to have a better idea.

A: <?php
   $query = "EXEC [dbo].[PORA_sp_GET_LetterGenerationRecords] @ProviderID = 1010";
   $result = mssql_query($query);
   if (!$result) {
       die('Invalid query: ' . mssql_error());
   }

   while ($row = @mssql_fetch_assoc($result)) {
        echo $row['col1']
   }
?>


text:
Q: Merging Excel sheets in a workbook to make panel data table with time and firms as indices I want to create a panel data table for panel data regression in R. I have a workbook with each sheet containing variables for a single firm (total 5 sheets so 5 firms). The variables are same for each firm. The frequency is daily. I want a single panel data table with Firms and time as indices so that I can take yearly averages of variables for each firm and do panel data regression. I have been running the following code:
sheets<- c("BOB", "RIL",  "GAIL", "ITC", "MM")for (x in 1:5)  {df <- bind_rows(df, read.xlsx(path, sheet=sheets[x] ), .id= "Firm")}

but the above code only takes the first sheet, create Firms column with values always 1, and date column as unknown numbers. I have also tried the following code:
df <- bind_rows(read.xlsx(path, sheets[x]), .id= "Firm")

But it returns the same result. It seems that the code is able to access only the first sheet in the workbook. Please suggest a way to solve this. Following is the link to the workbook: workbook

A: This uses the readxl package. The xlsx package didn't like something in your file and threw an error.
library("readxl")
sheets<- c("BOB", "RIL",  "GAIL", "ITC", "MM")
df <- NULL
for (sheet in sheets){
  tmp <- read_excel(path, sheet=paste0(sheet, " IS Equity"))
  tmp$firm <- rep(sheet, nrow(tmp))
  df <- rbind(df, tmp)
}


text:
Q: Multi-variable non-convex optimization problem where the problem is convex if one variable is fixed I have a non-convex optimization problem in the form
$$
\begin{align}
& \min{f(x,y)} \\
& \text{s.t. } h(x,y) \le 0
\end{align}
$$
I cannot derive a closed form solution. However, if I assume $y$ is constant, then the problem becomes convex and I can derive a closed form solution for $x$ as a function of $y$, i.e,
$$
\begin{align}
x^*(y) = \; & \arg \min_{x}{f(x,y)} \\
& \text{s.t. } h(x,y) \le 0
\end{align}
$$
Now, let's assume I can find the global optimal solution of the original problem somehow (numerially) and is denoted by $x_\text{opt}$ and $y_\text{opt}$. Are the following statement and the correspodning proof correct?
$$
x_\text{opt} = x^*(y_\text{opt})
$$
Proof:
By definition we have
$$
f(x_\text{opt},y_\text{opt}) \le f(x,y) \quad \forall x,y \quad \text{s.t.} \quad h(x,y) \le 0
$$
and therefore,
$$
f(x_\text{opt},y_\text{opt}) \le f(x^*(y_\text{opt}),y_\text{opt}).
$$
Also, we have
$$
f(x^*(y),y) \le f(x,y) \quad \forall x,y \quad \text{s.t.} \quad h(x,y) \le 0
$$
Therefore, we can write
$$
f(x^*(y_\text{opt}),y_\text{opt}) \le f(x_\text{opt},y_\text{opt}).
$$
Consequently,
$$
f(x^*(y_\text{opt}),y_\text{opt}) = f(x_\text{opt},y_\text{opt})
$$
and
$$
x^*(y_\text{opt}) = x_\text{opt}.
$$


text:
Q: Find consecutive integers in a list I am trying to find consecutive values from an unsorted list. Experimental code below:
num = [8, 9, 4, 1, 2, 3]

#(num[0+1])  next value

for i in range(len(num)-1):  # not using -1 will cause index error
    if num[i]+1==num[i+1]:
        print('Con',num[i])

Problem: I am unable to get the last value with this current code. My output excludes the last value. Here is what I get (no 9 or no 3):
Con 8
Con 1
Con 2

I have seen a few complex solutions which were a little difficult for me to understand. Is it possible to tweak the for loop part a little and get the entire sequence? Thanks a lot.

A: You can use the function groupby:
from itertools import groupby

num = [8, 9, 4, 1, 2, 3]

# Enumerate and get differences between counter—integer pairs
# Group by differences (consecutive integers have equal differences)
gb = groupby(enumerate(num), key=lambda x: x[0] - x[1])

# Repack elements from each group into list
all_groups = ([i[1] for i in g] for _, g in gb)

# Filter out one element lists
list(filter(lambda x: len(x) > 1, all_groups))
# [[8, 9], [1, 2, 3]]

A: This is because you only check the next number. When you want the second number (like 9 or 3), you have to include a check for the previous number too. This will make the if a bit longer, but it'll work.
num=[8,9,4,1,2,3]

for i in range(len(num)):
    if (
        (  # check for the next number
            i + 1 != len (num) and  # don't check the end of the list
            num[i]+1==num[i+1]
        ) or (  # check for the previous number
            i != 0 and  # don't check before the list
            num [i-1] == num [i] - 1
        )
    ): print('Con',num[i])

Also, I had to remove the -1 in your range, because I already do a manual check, and as pointed out, this prvented 3 from being shown.

A: Your code only tests in one direction (being followed by a consecutive number).
For the full sequence you have to test in both direction.
num=[8,9,4,1,2,3]

assert(len(num) > 1)
for i, n in enumerate(num):
    if i != 0:
        if n == num[i-1] + 1:
            print("Con", n)
            continue
    if i != len(num) - 1:
        if n == num[i+1] - 1:
            print("Con", n)

A: One way would be to print both numbers when you found them to be consecutive, but also check that the one at index i-1 was not in the consecutive list as well so that the number at index i is not printed twice:
num = [8, 9, 4, 1, 2, 3]

for i in range(len(num)-1):  # not using -1 will cause index error
    if num[i] + 1 == num[i + 1]:
        if i == 0 or (i - 1 >= 0 and num[i - 1] != num[i] - 1):
            print('Con', num[i])
        print('Con', num[i + 1])

Could try with a more complex list as well:
num = [8, 9, 4, 1, 2, 3, 4, 4, 8, 9, 1, 2, 3, 0, 1, 5, 6, 1]

for i in range(len(num)-1):  # not using -1 will cause index error
    if num[i] + 1 == num[i + 1]:
        if i == 0 or (i - 1 >= 0 and num[i - 1] != num[i] - 1):
            print('Con', num[i])
        print('Con', num[i + 1])

A: num = [8, 9, 4, 1, 2, 3]

def con(rng, pos=0):
    if pos < len(rng):
        if (pos > 0 and rng[pos]-1 == rng[pos-1]) or (pos < len(rng) -1 and rng[pos]+1 == rng[pos+1]):
            print("con", rng[pos])
        con(rng, pos+1)

con(num)

edit:
this is solution is based on concurrent function, and needs only the list as argument. As long as they are within lower-/upperbound of list, the function will check if (previous number)-1 or (next number)+1 are equal (this number)
output will be:
con 8
con 9
con 1
con 2
con 3


text:
Q: Integrability of almost product structure An almost produsct structure on a smooth manifold $M$ is a pair $(D,D')$ of complementary distributions. One says that the structure is integrable if there is a local map $(U,\phi^i,\psi^\alpha)$ for every point on $M$ with property: $$D=span \left\{\frac{\partial}{\partial \phi^i} \right\}$$
$$D'=span \left\{\frac{\partial}{\partial \psi^i} \right\}.$$ Generally the integrability of an almost product structure is more than an integrability of both distributions in any sence you like (involutivity or existance of a foliated atlas), yet I have faced the fallowing statement in $\textit{Foliations and Geometric Structures - A. Bejancu, H. R. Farran}$:

if $D$ is a distribution of codimension one, then both $D$ and $D'$ are integrable and we may consider foliated charts whose coordinates $(x^1, ..., x^{m−1}, t)$. [...] In this case we can choose a natural frame field
  $\left\{
\frac{∂}{
∂x^i}
, \frac{∂}{
∂t} \right\}$
  on M such that
  $\frac{∂}{
∂x^i}
∈ Γ(D)$ and $\frac{∂}{
∂t}
∈ Γ(D').$

I have been thinking for a while yet can't see why can we assume also that the last canonical vector field spans the last distribution?

A: First, pick a coordinate chart $$y = (y^1, ... , y^m) \,\, \in \, \,\mathbb{D}^{(m-1)} \times (-\delta, \delta)  \,\, \subset \,\, \mathbb{R}^m$$ with $\mathbb{D}^{(m-1)} = \{\hat{y} = (y^1, ..., y^{m-1}) \, : \,  -1 < y^j < 1\}$ and $y^m \in (-\delta,\delta)$, where the codimesnion one foliation $F_D$ of the distribution $D$  looks like  $$F_D = \{ \,\mathbb{D}^{(m-1)} \times\, \{y_0^m\} \,\, : \,\, y^m_0 \in (-\delta,\delta)\, \}$$ i.e. $D = \text{span}\left\{\frac{\partial}{\partial y^1}, ... , \frac{\partial}{\partial y^{m-1}}\right\}$. In such a chart, the other foliation $D'$, which is in fact a line field, is panned by a vector field $$Y(y) = \sum_{j = 1}^{m}  \, Y^j(y) \, \frac{\partial}{\partial y^j} = \left( \, \sum_{j = 1}^{m-1}  \, Y^j(y) \, \frac{\partial}{\partial y^j} \, \right) \, + \, Y^m(y) \, \frac{\partial}{\partial y^m}$$ transverse to $D$, meaning that $Y^m(y) = Y^m(y^1,..., y^m)$ is never zero. Therefore, one can rescale the vector field $Y(y)$ by dividing it by $Y^m(y)$ and get the vector field
$$X(y) = \frac{1}{Y^m(y)} \, Y(y) = \left( \, \sum_{j = 1}^{m-1} \, \,\frac{ Y^j(y)}{Y^m(y)} \,\, \frac{\partial}{\partial y^j} \, \right) \, + \,  \frac{\partial}{\partial y^m}$$
which after setting $X^j(y) = \frac{ Y^j(y)}{Y^m(y)} $ for all $j=1, ...,m-1$ looks like
$$X(y) = \left( \, \sum_{j = 1}^{m-1} \, \,X^j(y) \,\, \frac{\partial}{\partial y^j} \, \right) \, + \,  \frac{\partial}{\partial y^m}$$ or if we split the variables into $y = (\hat{y}, y^m)$, where $\hat{y} = (y^1, ..., y^{m-1})$
$$X(\hat{y}, y^m) = \left( \, \sum_{j = 1}^{m-1} \, \,X^j(\hat{y}, y^m) \,\, \frac{\partial}{\partial y^j} \, \right) \, + \,  \frac{\partial}{\partial y^m}$$ The new vector field $X(y) = X(\hat{y}, y^m)$ still spans the line field $D'$. A phase curve of $X(\hat{y}, y^m)$, starting form a point $(\hat{y}, y^m)$, looks like $$t \, \mapsto \,\big(\,\hat{y}(t \, | \,y^m, \, \hat{y}), \, y^m + t\,\big)$$ where $\hat{y}(y^m  \, | \,y^m, \, \hat{y} ) = \hat{y}$. Whit this special construction in mind, define the diffeomorphism $$\Phi \, : \, \mathbb{D}^{(m-1)} \times (-\delta, \delta) \, \to \, \mathbb{D}^{(m-1)} \times (-\delta, \delta) $$ by
$$\Phi \, : \, (x,t) \, \mapsto \, \big(\hat{y}(t  \, | \,0, \, x ) , \,  t\,\big)$$ where $x = (x^1,... , x^{m-1}) \in \mathbb{D}^{(m-1)}$. You may have to shrink the domain of the map $\Phi$, I am being a bit sloppy and I am abusing notation. Then
$$\Phi_*\left(\frac{\partial}{\partial t}\right) = \frac{d}{dt} \Phi(x, t) = \frac{d}{dt} \hat{y}(t  \, | \,0, \, x )  + \frac{dt}{dt} \, \frac{\partial}{\partial y^m} = X(\hat{y}, y^m) = X(y).$$ Notice that if we take an $m-1$ dimensional slice $\mathbb{D}^{(m-1)} \times \{t\}$ the diffeomorphism $\Phi$ maps it to $\Phi\big(\mathbb{D}^{(m-1)} \times \{t\}\big) = \mathbb{D}^{(m-1)} \times \{t\}$, which is a leaf of the foliation $F_D$, because $\Phi(x,t) = (\hat{y},t)$. Therefore, in the new coordinate chart $\Phi$ with local coordinates $(x^1,..., x^{m-1}, t)$, the distribution $D$ of the foliation $F_D$ is still spanned by $D = \text{span}\left\{\frac{\partial}{\partial x^1}, ... , \frac{\partial}{\partial x^{m-1}}\right\}$ while the transverse one-dimesnional distribution $D'$ is now spanned by $D' = \text{span}\left\{\frac{\partial}{\partial t}\right\}$.


text:
Q: SQL INSERT ISSUE WITH CTE I have the following query that I am working on. The goal is to insert the [AppID] and randomly selected [ufid] that meet the criteria in the where clause without inserting duplicates. I have researched the TABLESAMPLE and Random() but was unable to figure this out.
For example: #mult_nuf table has 4 records with the  AppID = 123456 and Major = 'GEBOX'. The #temp_rUF will have a record in the table with the ufid = 'UF7' and sh_plan = 'GEBOX'.I need to insert the [App_ID] and the [ufid] of another [sh_plan] into a temp table WHERE the [Major] and [sh_plan] are NOT be the same. So far a record for every [ufid] is being inserted with the same [Appid]. I have 45 [ufid} in the table so the temp table has 45 records for the same [AppID]. Should only be 4 records for the [AppID] with 4 random [ufid]..
mult_nuf table
AppID              Major
004540036          GEBOX
004540036          GEBOX
004540036          GEBOX
004540036          GEBOX

The #temp_ruf table
ufID                  sh_Plan
U1                    GECCE
U2                    REDSG
U5                    GFRTY
U7                    GEBOX
U8                    JKIUTY

Sample Output should look like
App_ID              ufID
004540036              U1
004540036              U2
004540036              U5
004540036              U8

Query I am working with
WITH Match_NomineesWithReviewers AS
(
    SELECT DISTINCT
        [AppID],
        RTRIM(Major) AS Major
    FROM
        #mult_nuf
)
SELECT
    m.[AppID],
    r.ufid
INTO
    #TempNTable
FROM
    Match_NWithR m
CROSS APPLY
    (SELECT ir.ufid
     FROM #temp_rUF ir
     WHERE m.Major <> ir.sh_plan) r

A: You can try something like this. It should work if the appid's are all the same.
INSERT INTO ATempTable
SELECT TOP (SELECT COUNT(1) FROM mult_nuf) Appid,
  ufID
FROM
    (SELECT DISTINCT *
    FROM mult_nuf
    CROSS JOIN temp_ruf
    WHERE major <> sh_plan) BaseQuery
ORDER BY NEWID()

A: Assuming you want to do this on a set of AppID's, I'd use ROW_NUMBER and ORDER BY newid() for random, then limit to the first 4 results, something like this:
WITH Match_NomineesWithReviewers AS
(
    SELECT
        [AppID],
        RTRIM(Major) AS Major
    FROM
        #mult_nuf
    GROUP BY
        [AppID],
        RTRIM(Major)
)
, rownum_matches AS (
SELECT
    m.[AppID],
    r.ufid,
    ROW_NUMBER() OVER (PARTITION BY m.[AppID] ORDER BY newid()) AS rownum
FROM
    Match_NomineesWithReviewers m
JOIN
    #temp_rUF t ON t.sh_Plan != m.Major
 )
 SELECT [AppID], ufid FROM rownum_matches WHERE rownum <= 4

If you need it to match the original number of records, maybe something like this:
WITH Match_NomineesWithReviewers AS
(
    SELECT
        [AppID],
        RTRIM(Major) AS Major,
        COUNT(1) AS rowcnt
    FROM
        #mult_nuf
    GROUP BY
        [AppID],
        RTRIM(Major)
)
, rownum_matches AS (
SELECT
    m.[AppID],
    r.ufid,
    m.rowcnt,
    ROW_NUMBER() OVER (PARTITION BY m.[AppID] ORDER BY newid()) AS rownum
FROM
    Match_NomineesWithReviewers m
JOIN
    #temp_rUF t ON t.sh_Plan != m.Major
 )
SELECT [AppID], ufid FROM rownum_matches rm WHERE rownum <= rowcnt


text:
Q: In Harry Potter and the Half Blood Prince, how does Hermione recognise Veritaserum? In Harry Potter and the Half-Blood Prince, during their first lesson with Slughorn, the students were asked to identify various potions, one of which is Veritaserum:

"It's Veritaserum, a colourless, odourless potion that forces the drinker to tell the truth,' said Hermione."
Harry Potter and the Half-Blood Prince, Chapter 9

Now the question is, if the potion is colorless and odorless, how is it possible to identify the potion just by looking into a cauldron full of it? For all we know, it could be simply water (colorless and odorless).

A: It might have other properties that make it identifiable.
Being colourless and odourless means it's virtually undetectable if added to someone's food or drink. However, the potion itself (as presented in a cauldron or vial) might be recognisable by other properties, such as:

*

*reflection (the way it breaks the light)

*viscosity (how "liquid" it looks/behaves compared to water)

*freezing/boiling point (the way it reacts to the temperature)

Now these are probably rather subtle but Veritaserum is not exactly an obscure potion and Hermione would know to look for these signs, especially as (as Bellatrix has pointed out) Slughorn is unlikely to show them a cauldron full of water.

A: Lacking color and odor is distinctive, and she had information to deduce it.
First of all, being colorless and odorless does help identify the potion - it eliminates all potions that have either a color or scent. In addition, she knew from what Slughorn said that it would be a N.E.W.T. level potion.

"Now then,' said Slughorn, returning to the front of the class and inflating his already bulging chest, so that the buttons on his waistcoat threatened to burst off, 'I've prepared a few potions for you to have a look at, just out of interest, you know. These are the kind of thing you ought to be able to make after completing your N.E.W.T.s. You ought to have heard of 'em, even if you haven't made 'em yet. Anyone tell me what this one is?" - Harry Potter and the Half-Blood Prince, Chapter 9 (The Half-Blood Prince)

She'd also presume it wouldn't be water, which would be a reasonable assumption. Water is indeed colorless and odorless, but in the context of the Potions class, it's highly unlikely that Slughorn would have filled a cauldron with water to show his students. His goal was to show them the types of potions they should be able to brew once they become more skilled.
It's entirely possible that Veritaserum is the only N.E.W.T. level potion that's odorless and colorless, and if it is, it would have been simple for Hermione to figure it out.
It seems unlikely that she saw another characteristic that no one mentioned.
In all the mentions of Veritaserum, the only distinctive characteristics it's said to have is it having no scent or color, and looking like water. Although Harry isn't the most observant and isn't particularly good at Potions, he had mentally described the other potions as well, and seen things like the way Polyjuice Potion bubbled slowly and was mud like, and the way Felix Felicis bubbled merrily about in its cauldron. However, when looking at the Veritaserum, all he thinks about it is that it looks like a cauldron of boiling water.

"He indicated the cauldron nearest the Slytherin table. Harry raised himself slightly in his seat and saw what looked like plain water boiling away inside it.
Hermione's well-practised hand hit the air before anybody else's; Slughorn pointed at her.
'It's Veritaserum, a colourless, odourless potion that forces the drinker to tell the truth,' said Hermione." - Harry Potter and the Half-Blood Prince, Chapter 9 (The Half-Blood Prince)

Now, Hermione is certainly more attentive than Harry, and more likely to notice a subtle characteristic distinct to Veritaserum other than its similarities to water. Frankly, though, it seems highly unlikely that Hermione would have noticed something subtle that most people wouldn't have noticed and not mentioned it to Slughorn. She tells Slughorn how she recognized the distinctive spirals of smoke she noticed on the cauldron of Amortentia, as well as what she knew about how it's supposed to smell. It seems odd that she'd pick up on something similar with the Veritaserum and not take the opportunity to show her knowledge to the new professor, who was also more easily impressed than Snape, instead of saying how she noticed a distinctive trait not many people would.


text:
Q: Calculating distances between unique Python array regions? I have a raster with a set of unique ID patches/regions which I've converted into a two-dimensional Python numpy array. I would like to calculate pairwise Euclidean distances between all regions to obtain the minimum distance separating the nearest edges of each raster patch. As the array was originally a raster, a solution needs to account for diagonal distances across cells (I can always convert any distances measured in cells back to metres by multiplying by the raster resolution).
I've experimented with the cdist function from scipy.spatial.distance as suggested in this answer to a related question, but so far I've been unable to solve my problem using the available documentation. As an end result I would ideally have a 3 by X array in the form of "from ID, to ID, distance", including distances between all possible combinations of regions.
Here's a sample dataset resembling my input data:
import numpy as np
import matplotlib.pyplot as plt

# Sample study area array
example_array = np.array([[0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0],
                          [0, 0, 2, 0, 2, 2, 0, 6, 0, 3, 3, 3],
                          [0, 0, 0, 0, 2, 2, 0, 0, 0, 3, 3, 3],
                          [0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 3, 0],
                          [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3],
                          [1, 1, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3],
                          [1, 1, 1, 0, 0, 0, 3, 3, 3, 0, 0, 3],
                          [1, 1, 1, 0, 0, 0, 3, 3, 3, 0, 0, 0],
                          [1, 1, 1, 0, 0, 0, 3, 3, 3, 0, 0, 0],
                          [1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                          [1, 0, 1, 0, 0, 0, 0, 5, 5, 0, 0, 0],
                          [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4]])

# Plot array
plt.imshow(example_array, cmap="spectral", interpolation='nearest')

A: Distances between labeled regions of an image can be calculated with the following code,
import itertools
from scipy.spatial.distance import cdist

# making sure that IDs are integer
example_array = np.asarray(example_array, dtype=np.int)
# we assume that IDs start from 1, so we have n-1 unique IDs between 1 and n
n = example_array.max()

indexes = []
for k in range(1, n):
    tmp = np.nonzero(example_array == k)
    tmp = np.asarray(tmp).T
    indexes.append(tmp)

# calculating the distance matrix
distance_matrix = np.zeros((n-1, n-1), dtype=np.float)
for i, j in itertools.combinations(range(n-1), 2):
    # use squared Euclidean distance (more efficient), and take the square root only of the single element we are interested in.
    d2 = cdist(indexes[i], indexes[j], metric='sqeuclidean')
    distance_matrix[i, j] = distance_matrix[j, i] = d2.min()**0.5

# mapping the distance matrix to labeled IDs (could be improved/extended)
labels_i, labels_j = np.meshgrid( range(1, n), range(1, n))
results = np.dstack((labels_i, labels_j, distance_matrix)).reshape((-1, 3))

print(distance_matrix)
print(results)

This assumes integer IDs, and would need to be extended if that is not the case. For instance, with the test data above, the calculated distance matrix is,
# From  1             2         3            4              5         # To
[[  0.           4.12310563   4.           9.05538514   5.        ]   # 1
 [  4.12310563   0.           3.16227766  10.81665383   8.24621125]   # 2
 [  4.           3.16227766   0.           4.24264069   2.        ]   # 3
 [  9.05538514  10.81665383   4.24264069   0.           3.16227766]   # 4
 [  5.           8.24621125   2.           3.16227766   0.        ]]  # 5

while the full output can be found here. Note that this takes the Eucledian distance from the center of each pixel. For instance, the distance between zones 1 and 3 is 2.0, while they are separated by 1 pixel.
This is a brute-force approach, where we calculate all the pairwise distances between pixels of different regions. This should be sufficient for most applications. Still, if you need better performance, have a look at scipy.spatial.cKDTree which would be more efficient in computing the minimum distance between two regions, when compared to cdist.


text:
Q: Find a basis of E as a vector space over $ \mathbb{Q} $
Find a basis for the factor ring
  $$\frac{\mathbb{Q}}{<16x^4-30x^3+15x^2+6>} $$ as a vector space over
  $\mathbb{Q} $.

I honestly don't even know how to start this :( I though I would use the Grobner Bases for Ideals stuff in my textbook, but I don't understand where it says "as a vector space over $\mathbb{Q}$" so I'm stuck.
Any help (even just hints) would be greatly appreciated!

A: Did you mean to write
$$\frac{\mathbb{Q}[x]}{<16x^4-30x^3+15x^2+6>}$$
??
The "as a vector space over $\mathbb Q$" thing means that there is a natural action of $\mathbb Q$ on this ring and that makes the ring a vector space over the field $\mathbb Q$.  Every vector space has a basis so you should be able to list elements of the ring which span and are linearly independent (both with respect to $\mathbb Q$).
For the basis, what about the sequence $1, x, x^2, \ldots$?  What's the first $x^n$ that can be written (in your ring) in terms of lower powers of $x$?  Once you've figured out what $n$ is ask yourself if $1, x, x^2, \ldots, x^{n - 1}$ is a basis.


text:
Q: Cannot import pyscipopt into python (ubuntu) I am trying to use scip's python interface. I have already downloaded the python interface and installed it according to the instructions given in
Python interface for the SCIP Optimization Suite. However, when I try to import pyscipopt to python, there is an ImportError:No module named 'pyscipopt.scip'.
I'm using scipsuite-3.2.1 under ubuntu.

A: Please make sure to be in a different directory than from where you installed the interface. Python gets confused when trying to import something when there is a directory of the same name in the current directory. Please go into the subdirectory scip/interfaces/python/tests and try running the provided test files.


text:
Q: Date conversion in react js I want to display dates (range of dates). The format of dates coming from DB seperated by hyphen is

Sep 21, 2017 - Sep 29, 2017

I want to convert it to the format

09/21/2017 - 09/25/2017

How can I convert this?

A: You can use this function that converts to your format:
Your CodeSand

const convert = dateRange =>
    dateRange.split(" - ")
        .map(date => new Intl.DateTimeFormat('en-US').format(new Date(date)))
        .join(" - ")

console.log(convert("Sep 21, 2017 - Sep 29, 2017"));

The code below works and uses only pure JavaScript ES6.

A: You can use Intl.DateTimeFormat object.

const dbDate = new Date("Sep 21, 2017")

console.log(new Intl.DateTimeFormat('en-US').format(dbDate))

From the MDN Docs -

The Intl.DateTimeFormat object is a constructor for objects that
  enable language-sensitive date and time formatting.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
Edit - If you are getting both dates in an single string you can split() it out and then apply the above method and concatenate (based on your requirement).

A: ReactJS have it's own date library which is moment date library. It can Parse, validate, manipulate, and display dates and times in JavaScript.
So use npm to install react-moment along with its peer dependency, moment by running this command :

npm install moment

Then Import and use in your Typescript file
import * as moment from 'moment';
const date = moment("Sep 21, 2017").format('MM/DD/YYYY');
console.log(date); // 09/21/2017

A: Moment.js mentioned in your comments has helped me a lot with the situation, specifically for what you want to do is found here
And moment.js package for reactjs can be installed from here
this will definitely help with your formating issue

A: const date = "Sep 21, 2017 - Sep 29, 2017"

const dateConvertor = date => {

    const splited = date.split(" ")

    const dateItems = []
    splited.forEach((item,index) => {
            if(item.indexOf(",") === -1) {
                dateItems.push(item)
            } else {
                dateItems.push(item.slice(0,item.indexOf(",")))
            }
     })

     let convertedDate = "";

     dateItems.forEach((item,index) => {
        if(index === 1 || index === 5) {
            convertedDate += "/"+item+"/"
        } else if (index === 3) {
            convertedDate += " "+ item + " "
        } else {
            convertedDate += item
        }
    })

    return convertedDate
}

dateConvertor(date)

A: First separate the string so that you can use it:
const [from, to] = '09/21/2017 - 09/25/2017'.split(' - ');

This will give you 2 strings, not formatted as you want so you will need to do some further transformation (assuming momentjs is available):
const [from, to] = '09/21/2017 - 09/25/2017'.split(' - ').map(item =>
moment(item).format('DD-MM-YYYY'));

If a slight format difference is OK, you might not need moment and use it like this
const [from, to] = '09/21/2017 - 09/25/2017'.split(' - ').map(item =>
new Intl.DateTimeFormat('en-US').format(new Date(item), {month: "2-digit", day: "2-digit"}));

NOTE: I am using 2-digit param here, which is supposed to provide the date / month as mentioned (09 instead of 9) but there seems to be an issue with that at least in some browsers.
Some explanation if not obvious:
The split part, creates an array. The map part, will transform the 2 strings to formatted date objects. The first part (left of the =) is destructuring the array and giving you the variables to use.


text:
Q: How to concatenate method request parameters in body mapping template AWS API Gateway I am trying to retrieve a list of entries from AWS DynamoDB with a primary hash and sort key composite.
The idea is to retrieve a list which matches a given query string value which is a part of the sort key, for example, the sort keys can be  a_b_c, a_d_e, a_f_g and i need to get the all entries with b in it.
I am asking for three query strings from the client and concatenating them in the body mapping template in the integration request section of AWS API gateway.
I am searching the web to accomplish the same but haven't been successful in finding a solution.
It would save a lot of time if somebody could help me with this.
Below is my approach.
{
    "TableName": "$util.escapeJavaScript("$context.stage\_TableName").replaceAll("\\","")",
    "FilterExpression": "identityId = :v1 and aWithbWithc = :v2 + _ + :v3 + _ + :v4",
    "ExpressionAttributeValues": {
        ":v1": {
            "S": "$context.identity.cognitoIdentityId"
        },
        ":v2" : {
            "S" : "$input.params('a')"
        },
        ":v3" : {
            "S" : "$input.params('b')"
        },
        ":v4" : {
            "S" : "$input.params('c')"
        }
    }
}

A: I have found the solution and putting it out here.
{
    "TableName": "$util.escapeJavaScript("$context.stage\_TableName").replaceAll("\\","")",
    "FilterExpression": "identityId = :v1 and aWithbWithc = :v2",
    "ExpressionAttributeValues": {
        ":v1": {
            "S": "$context.identity.cognitoIdentityId"
        },
        ":v2" : {
            "S" : "$util.escapeJavaScript($input.params('a'))__$util.escapeJavaScript($input.params('b'))__$util.escapeJavaScript($input.params('c'))"
        }
    }
}

A: you can have something like
{
#set($tableNameSuffix = "_TableName")
"TableName": "$stageVariables.environment$tableNameSuffix",
"ConsistentRead": true,
"KeyConditionExpression": "XXX = :val",
"ExpressionAttributeValues": {
        ":val": {
        "S": "$method.request.path.xxx"
        }
    }
}