text:
Q: How to write setup.py to include a Git repository as a dependency I am trying to write setup.py for my package. My package needs to specify a dependency on another Git repository.
This is what I have so far:
from setuptools import setup, find_packages

setup(
    name='abc',
    packages=find_packages(),
    url='https://github.abc.com/abc/myabc',
    description='This is a description for abc',
    long_description=open('README.md').read(),
    install_requires=[
        "requests==2.7.0",
        "SomePrivateLib>=0.1.0",
        ],
    dependency_links = [
     "git+git://github.abc.com/abc/SomePrivateLib.git#egg=SomePrivateLib",
    ],
    include_package_data=True,
)

When I run:
pip install -e https://github.abc.com/abc/myabc.git#egg=analyse

I get

Could not find a version that satisfies the requirement
SomePrivateLib>=0.1.0 (from analyse) (from versions: ) No matching
distribution found for SomePrivateLib>=0.1.0 (from analyse)

What am I doing wrong?

A: A more general answer: To get the information from the requirements.txt file I do:
from setuptools import setup, find_packages
from os import path

loc = path.abspath(path.dirname(__file__))

with open(loc + '/requirements.txt') as f:
    requirements = f.read().splitlines()

required = []
dependency_links = []

# Do not add to required lines pointing to Git repositories
EGG_MARK = '#egg='
for line in requirements:
    if line.startswith('-e git:') or line.startswith('-e git+') or \
            line.startswith('git:') or line.startswith('git+'):
        line = line.lstrip('-e ')  # in case that is using "-e"
        if EGG_MARK in line:
            package_name = line[line.find(EGG_MARK) + len(EGG_MARK):]
            repository = line[:line.find(EGG_MARK)]
            required.append('%s @ %s' % (package_name, repository))
            dependency_links.append(line)
        else:
            print('Dependency to a git repository should have the format:')
            print('git+ssh://git@github.com/xxxxx/xxxxxx#egg=package_name')
    else:
        required.append(line)

setup(
    name='myproject',  # Required
    version='0.0.1',  # Required
    description='Description here....',  # Required
    packages=find_packages(),  # Required
    install_requires=required,
    dependency_links=dependency_links,
)

A:
This answer has been updated regularly as Python has evolved over the years. Scroll to the bottom for the most current answer, or read through to see how this has evolved.

Unfortunately the other answer does not work with private repositories, which is one of the most common use cases for this. I eventually did get it working with a setup.py file that looks like this (now deprecated) method:
from setuptools import setup, find_packages

setup(
    name = 'MyProject',
    version = '0.1.0',
    url = '',
    description = '',
    packages = find_packages(),
    install_requires = [
        # Github Private Repository - needs entry in `dependency_links`
        'ExampleRepo'
    ],

    dependency_links=[
        # Make sure to include the `#egg` portion so the `install_requires` recognizes the package
        'git+ssh://git@github.com/example_org/ExampleRepo.git#egg=ExampleRepo-0.1'
    ]
)

Newer versions of pip make this even easier by removing the need to use "dependency_links"-
from setuptools import setup, find_packages

setup(
    name = 'MyProject',
    version = '0.1.0',
    url = '',
    description = '',
    packages = find_packages(),
    install_requires = [
        # Github Private Repository
        'ExampleRepo @ git+ssh://git@github.com/example_org/ExampleRepo.git#egg=ExampleRepo-0.1'
    ]
)

However, with the very latest pip you'll run into issues with the EGG format handler. This is because while the egg is ignored pip is now doing direct URL matching and will consider two URLs, one with the egg fragment and the other without, to be completely different versions even if they point to the same package. As such it's best to leave any egg fragments off.
June 2021 - setup.py
So, the best way (current to June 2021) to add a dependency from Github to your setup.py that will work with public and private repositories:
from setuptools import setup, find_packages

setup(
    name = 'MyProject',
    version = '0.1.0',
    url = '',
    description = '',
    packages = find_packages(),
    install_requires = [
        # Github Private Repository
        'ExampleRepo @ git+ssh://git@github.com/example_org/ExampleRepo.git'
    ]
)

February 2022 - setup.cfg
Apparently setup.py is being deprecated (although my guess is it'll be around for awhile) and setup.cfg is the new thing.
[metadata]
name = MyProject
version = 0.1.1

[options]
packages = :find

install_requires =
  ExampleRepo @ git+ssh://git@github.com/example_org/ExampleRepo.git

June 16th 2022 - pyproject.toml
setup.cfg is already "pre" deprecated. as setuptools now has experimental support for pyproject.toml files.
This is the future, but since this is still experimental it should not be used in real projects for now. Even though setup.cfg is on its way out you should use it for a declarative format, otherwise setup.py is still the way to go. This answer will be updated when setuptools has stabilized their support of the new standard.
January 4th 2023 - pyproject.toml
It is now possible to define all of your dependencies in pyproject.toml. Other options such as setup.cfg still work.
[build-system]
requires = ["setuptools", "setuptools-scm"]
build-backend = "setuptools.build_meta"

[project]
dependencies = [
    'ExampleRepo @ git+ssh://git@github.com/example_org/ExampleRepo.git',
]

[project.optional-dependencies]
dev = ['ExtraExample @ git+ssh://git@github.com/example_org/ExtraExample.git']

A: Note: this answer is now outdated. Have a look at this answer from @Dick Fox for up-to-date instructions: https://stackoverflow.com/a/54794506/2272172

You can find the right way to do it here.
dependency_links=['http://github.com/user/repo/tarball/master#egg=package-1.0']

The key is not to give a link to a Git repository, but a link to a tarball. GitHub creates a tarball of the master branch for you if you append /tarball/master as shown above.

A: Actually if you like to make your packages installable recursively (YourCurrentPackage includes your SomePrivateLib), e.g. when you want to include YourCurrentPackage into another one (like OuterPackage → YourCurrentPackage → SomePrivateLib) you'll need both:
install_requires=[
    ...,
    "SomePrivateLib @ git+ssh://github.abc.com/abc/SomePrivateLib.git@0.1.0#egg=SomePrivateLib"
],
dependency_links = [
    "git+ssh://github.abc.com/abc/SomePrivateLib.git@0.1.0#egg=SomePrivateLib"
]

And make sure you have a tag created with your version number.
Also if your Git project is private and you like to install it inside the container, e.g., a Docker or GitLab runner, you will need authorized access to your repository. Please consider to use Git + HTTPS with access tokens (like on GitLab: https://docs.gitlab.com/ee/user/profile/personal_access_tokens.html):
import os
from setuptools import setup

TOKEN_VALUE = os.getenv('EXPORTED_VAR_WITH_TOKEN')

setup(
    ....

    install_requires=[
            ...,
            f"SomePrivateLib @ git+https://gitlab-ci-token:{TOKEN_VALUE}@gitlab.server.com/abc/SomePrivateLib.git@0.1.0#egg=SomePrivateLib"
    ],
    dependency_links = [
            f"git+https://gitlab-ci-token:{TOKEN_VALUE}@gitlab.server.com/abc/SomePrivateLib.git@0.1.0#egg=SomePrivateLib"
    ]
)

Updated:
You have to put #egg=SomePrivateLib at the end of dependency line if you like to have this dependency in requirements.txt file. Otherwise pip install -r requirements.txt won't work for you and you wil get something like:

ERROR: Could not detect requirement name for
'git+https://gitlab-ci-token:gitlabtokenvalue@gitlab.server.com/abc/SomePrivateLib.git@0.1.0',
please specify one with #egg=your_package_name

If you use reuirements.txt, this part is resposible for name of dependency's folder that would be created inside python_home_dir/src and for name of egg-link in site-packages/
You can use a environment variable in your requirements.txt to store your dependency's token value safe in your repo:
Example row in requrements.txt file for this case:
....

-e git+https://gitlab-ci-token:${EXPORTED_VAR_WITH_TOKEN}@gitlab.server.com/abc/SomePrivateLib.git@0.1.0#egg=SomePrivateLib
....

A: I was successful with these three options in GitLab. I am using version 11 of GitLab.
Option 1 - no token specified. The shell will prompt for username/password.
from setuptools import setup

TOKEN_VALUE = os.getenv('EXPORTED_VAR_WITH_TOKEN')

setup(
    install_requires=[
        "SomePrivateLib @ git+https://gitlab.server.com/abc/SomePrivateLib.git@0.1.0#egg=SomePrivateLib"
    ]
)

Option 2 - user access token specified. The token generated by going to GitLab → account top right → settings → access tokens. Create the token with read_repository rights.
Example:
import os
from setuptools import setup

TOKEN_VALUE = os.getenv('EXPORTED_VAR_WITH_TOKEN')

setup(
    install_requires=[
        f"SomePrivateLib @ git+https://gitlab-ci-token:{TOKEN_VALUE}@gitlab.server.com/abc/SomePrivateLib.git@0.1.0#egg=SomePrivateLib"
    ]
)

Option 3 - repository-level token specified. The token generated by going to the repository → settings → repository → deploy tokens. From here, create a token with read_repository rights.
Example:
import os
from setuptools import setup

TOKEN_USER = os.getenv('EXPORTED_TOKEN_USER')
TOKEN_VALUE = os.getenv('EXPORTED_VAR_WITH_TOKEN')

setup(
    install_requires=[
        f"SomePrivateLib @ git+https://{TOKEN_USER}:{TOKEN_VALUE}@gitlab.server.com/abc/SomePrivateLib.git@0.1.0#egg=SomePrivateLib"
    ]
)

In all three, I was able to do simply: "SomePrivateLib @ git+https://gitlab.server.com/abc/SomePrivateLib.git" without the #egg marking at the end.

A: After digging through the pip issue 3939 linked by @muon in the comments above and then the PEP-508 specification, I found success getting my private repo dependency to install via setup.py using this specification pattern in install_requires (no more dependency_links):
install_requires = [
  'some-pkg @ git+ssh://git@github.com/someorgname/pkg-repo-name@v1.1#egg=some-pkg',
]

The @v1.1 indicates the release tag created on github and could be replaced with a branch, commit, or different type of tag.

A: This solution works for me when I run python setup.py install:
setuptools.setup(
    ...,
    install_requires=[
        'numpy',
        'pandas',
        'my_private_pkg'
        ],
    dependency_links=["git+https://github.com/[username]/[my_private_pkg].git@main#egg=my_private_pkg"],
    ...
)


text:
Q: Copy jar file from one project to another using maven I have the following project structure.
Root
 |--> Project-A (It generates war) +  test.jar
 |--> Project-B (It only generates war)

I have a web application name 'Project-A' which when I do mvn clean package it generates Project-A.war and test.jar in target folder.
Similarly, I have a web application name 'Project-B' which when I do mvn clean package it generates only Project-B.war
WHAT I WANT is when I do mvn clean package for 'Project-B', test.jar should part of that war file or inside 'Project-B' libs?
Can anyone please suggest me?

A: You need to host your artifacts internally using a Repository Manager so they can be consumed by other projects, here are few popular ones.

*

*Artifactory

*Nexus Repository
Here is an article that have more deails How to setup a Private Maven Repository
Would recommend reading more about Repository Managemers, this link have more options.
Cheers !

redpajama_set_name: RedPajamaStackExchange


text:
Q: Creating a standard card game (iPhone SDK) I am trying to create a card game with a standard deck of cards. I need to be able to create a new card on screen every time someone draws a card from the deck and then be able to continuously move it throughout gameplay. I have image files for every card available in the game.
I have tried creating a card object which held a UIImageView for the card along with some other basic data but I had trouble referring back to that card to move it again after the first touch. Was this the right way to do this?

A: If I understand your question correctly, you're having trouble finding which "card" is associated with which "view" sometime later, when using some API that passes you the view object. I think the answer, if this is the case, is that you have your dependencies upside down. When using Model-View-Controller, which Cocoa is big on, you should create a UIImageView subclass that contains a reference to your Card object. I would make a protocol (CardDelegate?) and implement the protocol with your card object (getValue, getSuit, etc...) Your custom view would have a method e.g. getCardDelegate that returns the delegate from your custom view. The delegate holds all the state for your card. Later, when you get the view from some API, you can send messages to its delegate to change the state of your program, because the view refers to the model. You'll notice this is the same pattern that Interface Builder uses: you build a view, and then link it to some delegate that does all the work.


text:
Q: What are the GC implications of having a large array of small classes? If I have a multidimensional array with many hundreds of thousands of entries and all entries are class objects that are long-lived (ie are only created once and live for the entire duration of  the application), are there any GC implications I need to consider? Will this affect how much time it takes the GC to complete? Will this affect future allocations/deallocations?
For context, I am trying to make a decision between using a large array of classes or a large array of structs.

A: If those small classes are are long lived, they will soon be promoted to Gen2 objects and will not affect Gen0 and Gen1 collection. They will not affect allocation. They will affect Gen2 collection though, but if GC is doing Gen2 collection, then you have a different problem. You are running out of memory.
In addition to affecting GC, class vs struct will affect memory layout of you objects though. This will affect CPU cache performance which may have a larger impact on performance.

A: A large enough object is allocated in Large Object Heap (LOH) that does not get collected in the same way as regular heap allocations.  Objects in LOH do not get compacted normally, so it is much easier to wind up with fragmented memory, and, therefore, much likelier to get OutOfMemoryException even though your process is not using much of memory at all (my experience a while back was 700MB on a 32bit process could fairly easily run into such condition when dealing with a lot of large objects).
The reason I was asking about future allocations is that if this is the only large object that you expect in your program and it is not frequently reallocated along with others, then having one or a few is probably not a big deal and unlikely to affect you too much.  It's OK to have large objects such as massive arrays, or big strings.  If allocations requiring LOH would be frequent enough, then it may be a concern.
Struct vs objects.  Objects obviously make the width of an array the same size as the pointer - i.e. 32 or 64 bits.  Structs can be stored as the value itself in array, so if the struct is larger, then array of the same size element-wise would be larger byte-wise.  Hence smaller number of elements will cause array to be allocated into LOH.


text:
Q: How to query imported json using Mongoose I've uploaded a json file to MongoDB Atlas cluster (using mongoimport) and now I'm trying to display the data to localhost using express and mongoose.
I've gotten to a point where I can connect to the cluster but I'm struggling in fetching and displaying the data. Below is the code I have thus far. I'd like to query the database via Nodejs using mongoose as I do on the command line with Mongo shell. What am I missing here?
const express = require("express");
const mongoose = require("mongoose");

const app = express();

// DB config using Mongo Atlas
const uri = require("./config/keys").mongoURI;

// // Connect to Mongo
mongoose
  .connect(uri, { useNewUrlParser: true })
  .then(() => console.log("MongoDB Connected..."))
  .catch(err => console.log(err));

// @route GET
app.get("/", (req, res) => res.send(db.restaurants.find()));

const port = process.env.PORT || 5000;

app.listen(port, () => console.log(`Server started on port ${port}`));

A: First, initialize a model which Mongoose needs to query data. Since you've imported the data, you don't necessarily have to structure your schema.
// restaurants.js
const mongoose = require('mongoose');

const RestaurantsSchema = new mongoose.Schema({});

module.exports = mongoose.model('Restaurants', RestaurantsSchema)

Then, import the schema 'Restaurants' into your main driver file and specify your query by chaining filters like so:
// main.js
const express = require("express");
const mongoose = require("mongoose");
const Restaurants = require("./restaurants");

const app = express();

// DB config using Mongo Atlas
const uri = require("./config/keys").mongoURI;

// Connect to Mongo
mongoose
  .connect(uri, { useNewUrlParser: true })
  .then(() => console.log("MongoDB Connected..."))
  .catch(err => console.log(err));

// @route GET
app.get("/", (req, res) => {
  Restaurants.find()
    .where("filter1").gt(200)
    .where("filter2").equals("$$$")
    .where("filter3").nin(["Coffee"])
    .limit(100)
    .sort("sort1")
    .select("column1 column2 column3")
    .then(restaurants => res.json(restaurants))
    .catch(err => res.status(404).json({ success: false }));
});

const port = process.env.PORT || 5000;

app.listen(port, () => console.log(`Server started on port ${port}`));

You should fill in the applicable values for "filter", "sort", "column", "gt", "equals", "limit", and "nin".

A: I am not sure if this is the only record of that type of json in your data base. But If you want to send if follwing a get request you first need to get the document.
// @route GET
app.get("/", (req, res) => res.send(db.restaurants.find()));
// may be something like
app.get('/', (req, res) => {
    mongooseModel.find({query}, (err, result) => {
    res.send(result);
  });
})

Depending on what mongoose.model defenition you have and how you would like to find it you could use find (return an array) findById (return single document) or findOne and a query.

A: here an example how to create you model:
//restaurant.js
const mongoose = require('mongoose');

const RestaurantSchema = new mongoose.Schema({
      name: { type: String, required: true },
      address: { type: String, required: true },
      description:{ type: String, required: true }
      //just you add how you need your schema
});

module.exports = mongoose.model('Restaurant', RestaurantSchema);

and here your updated code
const express = require("express");
const mongoose = require("mongoose");
const Restaurant = require("./restaurant.js");

const app = express();

// DB config using Mongo Atlas
const uri = require("./config/keys").mongoURI;

// // Connect to Mongo
mongoose
.connect(uri, { useNewUrlParser: true })
.then(() => console.log("MongoDB Connected..."))
.catch(err => console.log(err));

// @route GET
app.get("/", (req, res) => {
   Restaurant.find({}, (err, docs) => {
     res.send(docs);
   });
);

const port = process.env.PORT || 5000;

app.listen(port, () => console.log(`Server started on port ${port}`));


text:
Q: Break up Large Row Heights with React Virtualized? I'm planning on rendering a list that contains nested tables.
If, for example, a row happens to contain a table containing 100s of items, would react-virtualized break up that row? Or would it render the entire row no matter its height, therefore defeating the purpose of virtualized infinite scroll?

A: Looks like the answer is a no:
https://github.com/bvaughn/react-virtualized/issues/980


text:
Q: if i put the code in my theme's function.php file can it work? $gr_preview_theme = $_GET['preview_theme'];
$gr_preview_css = $_GET['preview_css'];

if (! $gr_preview_css )
    $gr_preview_css = $gr_preview_theme;

if($gr_preview_theme && file_exists(get_theme_root() . "/$gr_preview_theme")) {
    add_filter('template','use_preview_theme');
}

if($gr_preview_css && file_exists(get_theme_root() . "/$gr_preview_css")) {
    add_filter('stylesheet','use_preview_css');
}

function use_preview_theme($themename) {
    global $gr_preview_theme;

    return $gr_preview_theme;
}

function use_preview_css($cssname) {
    global $gr_preview_css;

    return $gr_preview_css;
}

a pludgin's code is too small. i want to put the code into the theme's function.php file. could i do this?
add_filter('template','use_preview_theme');

what's the above line meaning? and what's use of it? thank you

A: Short Answer YES!! why because all a functions files does is act as a big huge plugin. Keep in mind though if you plan on using this with other themes or if in network mode you need the plugin file


text:
Q: Update the readme.txt of the data dump ... again In 2017 I asked to update the readme.txt of the data dump.
Today I revisited that read me due to Stack Exchange Data Dump — OwnerDisplayName and LastEditorDisplayName. I was surprised to find that the careful work done by Oded has been thoroughly destroyed.
Two requests:

*

*Can you restore the Read Me to at least the state Oded left it in.

*Can you add a link/reference in that Read Me to the canonical Meta post that describes the schema. In plain text that should probably be: https://meta.stackexchange.com/questions/2678. This was also proposed by user busterroni.

Note that the canonical covers both SEDE and the Data-dump and we're happy to keep that post up-to-date, which is much harder for the readme.txt as that is solely under your control and can only be updated by reporting bugs on it.

A: What happened
We don't know. The changes Oded talked about in 2017 predate any of us in DBRE. We're not confident those changes ever did make it into the data dump and, even if so, how to replicate them correctly now, or incorporate other changes that have happened in the meantime.
How we should fix it
Maintaining two independent copies of anything is a pain. My proposal is that the readme file we push to Archive.org simply tells the user to find schema documentation in the existing answer here on meta:

*

*Database schema documentation for the public data dump and SEDE
This way we can have a single canonical copy, and can all be involved in ownership / stewardship.


text:
Q: iOS Dynamic Form in UITableViewCells, Retrieve Values I have been searching and reading all over but couldn't find any conclusive method to achieve what I want to and hope to find help here...
I have a UITableView which allows the user to add multiple Flavours and Percentages to a Recipe. I have implemented the method to add or delete rows of Flavours with a custom Cell / Nib  and it works perfectly well.
The issue I'm facing now, is how to retrieve the values the user has provided per added row.
(Edit for Clarity: My problem is not the populating of data, but only the dynamic reading of all data so I can save it)
I do manage to get the values for the visible rows (I do understand how the Reuseidentifier and the Tableview works, per se that for memory management's sake, iOS only keeps track of the visible rows), but not the hidden ones.
I assume in theory that I have to create an Array of Cells outside of 'cellForRowAtIndexPath' which maintains all cells. But then I'm facing another conceptual problem that my custom Nib / cell doesn't show.... basically:

*

*How can I then use / register a nib without using the dequeingidentifier

*Or in General, how can I solve the overall problem to be able an read all user entered values per row

Here the code I'm using within my cellForRowAtIndexPath. As mentioned adding and remove cell works like a charm, that isn't the issue...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

RecipeFlavourTableViewCell *cell;
int section = (int)indexPath.section;

if(section==0)
    return [super tableView:tableView cellForRowAtIndexPath:indexPath];

if(!cell){
    [tableView registerNib:[UINib nibWithNibName:@"RecipeFlavourCell" bundle:nil] forCellReuseIdentifier:@"Cell"];
    cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
}

cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;

}
I have seen some Libraries doing it (e.g. XLForm) but do not understand (also when checking their sources) how they iterate through the values and overcome this dequeuing problem...
Any help is highly appreciated
EDIT 2: here the code I'm using to iterate through the cells in order to save the data, but as said I can only iterate through the visible cells:
- (IBAction)saveRecipe:(id)sender {

NSInteger dynamicRows = [self.tableView numberOfRowsInSection:1];

    for (int i=0; i<dynamicRows; i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:1];
        RecipeFlavourTableViewCell *cell = (RecipeFlavourTableViewCell *)[self.tableView cellForRowAtIndexPath:indexPath];
        NSLog(cell.flavour.text);
    }

}

A: After 2 days of searching I finally came up with a solid solution. In case someone bumps into the same problem of dynamic forms with a tableview, here the solution:
As we understand, what ever cell is created in cellForRowAtIndexPath, it only persists as long as it is displayed. As soon as you scroll and the cell disappears, it gets automatically thrown out of memory. This behaviour makes it impossible to iterate through all cells at a later stages.
The steps to follow in order to make it work are as follows:
Preparation

*

*Create an NSObject with all properties you want to persist in one form cell (-> cellObject)

*In the ViewDidLoad of your controller create a NSMutableArray which will contain the cellObjects (-cellsArray)

*Add as many cellObjects to the cellsArray as you initially want to appear in the Tableview

*In numberOfRowsInSection return the count of you cellsArray

*In the cellForRowAtIndexPath build your cells as usual BUT add a Textfield Delegate (self) to every Textfield in a cell

TextField Delegate
Implement:
 - (void)textFieldDidEndEditing:(UITextField *)textField

and update your cellsArray Objects every time a Textfield ends editing. Per se, get the cellObject for the row and edit the properties with the value of the TextField
Add Row
When ever you add a row, just add an empty cellObject to your cellsArray and use the beginUpdates / insertRowsAtIndexPaths / endUpdates on your tableView (NOT reloadData as the already typed in data would get lost). Also add the following at the very beginning of your addRow method, as you want to make sure that if the user adds a row while editing a textfield, the latter gets persisted as well:
 [self.view.window endEditing: YES];

Remove Row
Same as Add Row just reverse, remove the cellObject from your cellsArray and use deleteRowsAtIndexPaths on your tableView
Save Data
Now comes the trick: since you ought to always persist your data when a field ends editing mode, there is one case you need to cover: What if the user pushes "Save" when the focus is set on one TextField? Well at the very beginning of your Save Action insert the following:
 [self.view.window endEditing: YES];

This make sure the the textFieldEndEditing will be triggered one last time for the current textField and that its data will also be persisted.
Finally iterate through your cellsArray and do whatever you want with it (validate, save etc)...
That's it, hope this can help anyone else as I couldn't find any valuable explanation anywhere else...

A: Lets assume that you have an NSArray and that it contains data you want to show. Your code should look something like this:
// Add this property to the class and fill it in with data you want to show
@property NSArray flavourElements;

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    RecipeFlavourTableViewCell *cell;
    int section = (int)indexPath.section;

    if(section==0)
        return [super tableView:tableView cellForRowAtIndexPath:indexPath];

    if(!cell){
        [tableView registerNib:[UINib nibWithNibName:@"RecipeFlavourCell" bundle:nil] forCellReuseIdentifier:@"Cell"];
        cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
        // At this point your cell is ready for showing
        // And you can change values in it by getting element from array that contains data
        cell.flavorTextField = flavourElements[indexPath.row].flavour
        cell.precentageTextField = flavourElements[indexPath.row].precentage
    }

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;

}

I wrote a code for accessing elements without knowing what you actually have, so you will need to adjust it a little bit to fit your app.


text:
Q: Ruby how to iterate a collection and create a hash key if none exists, or add to the value if key does exist This is a pattern that I find myself using a lot and I am wondering if there is something in the built-in library that does this without adding all these control flow statements.  what I have is:
input = <<TEXT
/us/programming/sports:model.channel.tnt.name
/us/programming/sports:model.channel.spice.name
/us/programming/sports:model.classificationwebgenre.us-entertainment.programming_link_text
/international-sports/package:model.language.international-sports.name
/brazilian/programming/sports:model.package.hbo-extra.description
TEXT

def self.create_hash(text)
  output = {}
  text.each_line("\n") do |line|
    split_lines = line.split(":")
    if output.has_key?(split_lines.first)
      output[split_lines.first] << split_lines[1][0..-2]
    else
      output[split_lines.first] = [split_lines[1][0..-2]]
    end
  end
  output
end

end
also the output of this is:
{
      "/us/programming/sports" => ["model.channel.tnt.name", "model.channel.spice.name", "model.classificationwebgenre.us-entertainment.programming_link_text"],
      "/international-sports/package" => ["model.language.international-sports.name"],
      "/brazilian/programming/sports" => ["model.package.hbo-extra.description"]
    }

Am I just overcomplicating things with they way I am writing this?  Is there an idiomatic way to write this in ruby?  Thanks in advance.

A: Not sure if is faster, but it's cleaner
def self.create_hash(text)
  output = {}
  text.each_line("\n") do |line|
    split_lines = line.split(":")
    output[split_lines.first] ||= []
    output[split_lines.first] << split_lines[1][0..-2]
  end
  output
end

A: just define output with defaults:
output = Hash.new { |k, v| k[v] = [] }

That would turn your code into:
def self.create_hash(text)
  output = Hash.new { |k, v| k[v] = [] }
  text.each_line("\n") do |line|
    split_lines = line.split(":")
    output[split_lines.first] << split_lines[1][0..-2]
  end
  output
end


text:
Q: How to call a JS function inside a JSP? I'm trying to call a JS function embedded inside a JSP file from a servlet. I need to pass some arguments to the JS function. Will I be able to do that?

A: There is no reason why you should not be able to do that. However, note that the JS function will be executed in the client side. For example
<input type="text" name="user" onclick="submitName(this)"/>

can be part of a JSP and will be rendered as part HTML in the response. When the text field is clicked, the submitName() JS function will execute.
Note - This was to just illustrate that JS function call can be embedded in JSP , better way to bind events to HTML elements is to use frameworks like JQuery.

A: Yes. You have 2 options:
1) Call desired Java functionality using AJAX (mostly used when user do some action):
$.ajax('/url/to/your/servlet', {data: 1, another-data: 2}, function() {
     // success callback
});

2) Call desired JavaScript function when page is parsed or when it is loaded (prepare the call in JSP page). It is not direct call of JavaScript function from JSP, you just prepare the call and call is performed when page is parsed/loaded on the client side:
<script>
    // Alert is show when page is parsed
    alert(${data});
    $(document).ready(function() {
        // Alert is show when page is loaded (except of images and few other resources)
        alert(${data});
    });
</script>


text:
Q: google work icon displayed on react native app What's the purpose of google work icon on my react native app ,how to remove it ?
As i was working with react native ,suddenly google work icon is placed on the right bottom side of my icon ,also what is the purpose of that icon.
I couldn't find anything related to this on google


text:
Q: I'm having trouble with arraylists, i don't get it to return the right words The program runs well, but when I try to get it to return the "words", it returns the right amount of output, but all have the name of the last input.
Ex. if I store 3 different book names in my ArrayList, it returns 3 times the name of the last book.
Are there any obvious mistakes?
(the super-class and other classes should work fine)
import java.util.*;

public class libraryManager {

public static void main (String [] args) {

  String input =" ";

  ArrayList<Book> books = new ArrayList<Book>();
  ArrayList<CD> cds = new ArrayList<CD>();

  Book booka = new Book();
  CD cda = new CD();

    System.out.println("Welcome to library management system");
    Scanner reader = new Scanner(System.in);

    Scanner newBook = new Scanner(System.in);

    do{

        System.out.println("Main menu: ");
        System.out.println(" 1. Add book to the library ");
        System.out.println(" 2. Add CD to the library ");
        System.out.println(" 3. Print items ");
        System.out.println(" 4. Exit ");
        input = reader.nextLine();

         if (input.equals("1")){
             System.out.println("Input new book: ");
             input = reader.nextLine();
             booka.setName(input);
             books.add(booka); input ="1";
        }

        if (input.equals("2")){
            System.out.println("Input new CD: ");
            input = reader.nextLine();
            cda.setName(input);
            cds.add(cda);
        }

        if (input.equals("3")){
            System.out.println("Library contains:");
            for (int i= 0; i<books.size(); i++){
                System.out.println("Book: " + books.get(i).getName());
            }
            for (int i = 0; i<cds.size(); i++){
                System.out.println("CD: " +cds.get(i).getName());
            }

            break;
        }

  }while(!input.equals( "4"));
}
}

A: You are creating a single instance of Book and CD:
   Book booka = new Book();
   CD cda = new CD();

Then you add that same instance again and again to the lists, each time changing its properties. That's why you see that all the elements hold the same value (the value of the last element added).
You should create a new instance for each time to add an element to one of the lists.
For example:
     if (input.equals("1")){
         System.out.println("Input new book: ");
         input = reader.nextLine();
         Book booka = new Book(); // add this
         booka.setName(input);
         books.add(booka); input ="1";
    }

A: booka.setName(input);
books.add(booka); input ="1";

Here be the problem! You're adding the same instead of booka each time, so the last name you set to booka is the name that every reference to it in the ArrayList will return!


text:
Q: Math Menu Loop return The function will not return option, I ran the code multiple times and cannot spot the error. See if you guys can spot it out I've looked online everywhere.
def menu():
    print("1. Addition")
    print("2. Subtraction")
    print("3. Multiplication")
    print("4. Division")

def main(option):
    option = input("Enter your selection: ")

    while option != 1 or 2 or 3 or 4:
        count = 0 #controls how many menu() is printed
        print(menu(), count)
        count = +1
        option = input("Enter your selection: ")
        return option

main()

Console Output
TypeError: main() missing 1 required positional argument: 'option'

A: Try it like this:
menu()

choice = int(input("Enter input: ")) # get user input and cast it to int

main(choice) # requires a number to be passed to it

Or you can modify main to not take options:
def main(): # it no longer takes a parameter
    option = input("Enter your selection: ")

    while option != 1 or 2 or 3 or 4:
        count = 0 #controls how many menu() is printed
        print(menu(), count)
        count = +1
        option = input("Enter your selection: ")
        return option

main() # this will work now

A: you called a function main without calling passing in an argument.
Your function main is a function that takes in a variable option


text:
Q:  not working with iPad? I have a website where I use a dropdown with no parent menu point, see: http://wittmerperformance.com/site
Now, i just got told that the empty dropdown (SERVICES) doesn't work with the iPad. I unfortunately don't have an iPad to verify.
Could someone let me know how I can make this showing up on iPad properly too?

A: Wouldn't surprise me, I am having issues on my iPhone with iOS6 as well.  Typically, you need to still do a,  then set the href="#" for it to work on touch screen devices, since then it creates a zone that the user can click creating a pseudo hover/active state that then triggers the drop down.
So:
Services

Instead of your .


text:
Q: NSRegularExpression and repeating pattern I am writing an app that is receiving message blocks via TCP. A message block is composed of the following:

*

*a fixed header <<:--!!

*6 digits that give the length of the message

*the message itself

It sound logical to use NSRegularExpression to extract the messages from the data received, so I ended up with the following code in playground, implementing the processing of a string of data received:
import UIKit

struct Constants {
    static let messageHeaderPattern = "<<:--!!(\\d{6})(.+)"
}

let receivedData = "<<:--!!000010My message"

let regex = try! NSRegularExpression(pattern: Constants.messageHeaderPattern, options: [])  // Define the regular expression
let range = NSMakeRange(0, receivedData.characters.count)                          // Define the range (all the string)
let matches = regex.matchesInString(receivedData, options: [], range: range)       // Get the matches

print("Number of matches: \(matches.count)")

for match in matches {

    let locationOfMessageLength = match.rangeAtIndex(1).location
    let expectedLengthOfMessage = Int(receivedData.substringWithRange(Range(start: receivedData.startIndex.advancedBy(locationOfMessageLength),
        end: receivedData.startIndex.advancedBy(locationOfMessageLength + 6))))

    let locationOfMessage = match.rangeAtIndex(2).location
    let lengthOfMessage = match.rangeAtIndex(2).length
    let data = receivedData.substringWithRange(Range(start: receivedData.startIndex.advancedBy(locationOfMessage),
        end: receivedData.startIndex.advancedBy(locationOfMessage + lengthOfMessage)))

    // data contains "My message"

}

This code works well, but only if there is one message in the string. To make it work for multiple messages, I changed the regular expression:
static let messageHeaderPattern = "(?:<<:--!!(\\d{6})(.+))+"

and the received data:
let receivedData = "<<:--!!000010My message<<:--!!000014Second message"

But there is still only one match, and data contains My message<<:--!!000014Second message.
What is wrong with my regular expression?

A: The message could even contain <<:--!!\d{6} so I don't think you will be able to do this with regex alone, so the safe solution is.

*

*regex for ^<<:--!!(\d{6}) to extract the length N

*substring out N characters starting from the 13th

*repeat

If you want to live dangerously and are confident that <<:--!!\d{6} will never occur in the message then this regex will do the trick.
(?<=<<:--!!\d{6})(.*?)(?=<<:--!!\d{6}|$)

Just remember it will mess up if the delimiter occurs inside the string, you should use the method in my first example to be safe.

A: Try using the pattern static let messageHeaderPattern = "<<:--!!(\\d{6})(.+?)(?!<<:--!!)"

A: Try filtering the message itself more, so the (.*) not include the second message in it:
"(?:<<:--!!(\\d{6})([a-zA-Z ]+))"


text:
Q: How to handle array from collection_select rails I have a form that uses collection_select to be able to select multiple groups. But when I try to create a new record it fails in my notifications_controller.rb. The parameters are being passed correctly I think it might have to do with collection_select being passed as an array. I just can't for the life of me figure out how to handle it in the controller.
 undefined method `users' for #<Array:0x007fbb0e891b58>

What is being passed in the parameters:
 "group"=>{"group_id"=>["1", "2"]},

schema.rb
create_table "notifications", force: :cascade do |t|
 t.string "title"
 t.string "first_name"

 end

create_table "notifications_users", id: false, force: :cascade do |t|
 t.bigint "user_id", null: false
 t.bigint "notification_id", null: false
 end

create_table "users", force: :cascade do |t|
 t.string "first_name"
 t.string "last_name"
 t.string "user_type"
 t.string "username"

end

new.html.erb
   <%= f.label :To %>
       <%= collection_select(:group, :group_id, Group.all,:id,:name,
        {include_hidden: false}, {:multiple => true})%>

notifications_controller.rb
def create

@notification = Notification.new(notification_params)

if @notification.save
  @group = Group.find(params[:group][:group_id])

  #raise @group.inspect

  @users = @group.users <--this is where it fails
  @users.each do |user|
  @notification.users << user
end .....

A: Can you try:
def create

  @notification = Notification.new(notification_params)

  if @notification.save
    @group = Group.where(id: params[:group][:group_id])

    @group.each do |group|
      @users = group.users <--this is where it fails
      @users.each do |user|
      @notification.users << user
    end
  end
end

As you're selecting multiple groups and searching the group, you'll be getting an Array of the Groups. Instead when using the where as above, you'll get a ActiveRecordRelation
You've to loop through this result and use the users association with each record.
Note: The associations don't work with Active Record Relations or Arrays.
Hope this helps. Let me know if this works for you.


text:
Q: Merge Key of the same Dictionary by their name Let's say that I have a dictionary that contains the following:
Dessert = {'cake': 71,
 'Crumble': 53,
 'ice cream Chocolate': 23,
 'ice cream Vanilla': 15,
 'ice cream Strawberry': 9,
 'ice cream Mint chocolate': 8}

how can I group keys that start in the same way  ?
I would like to get something like this:
Dessert = {'cake': 71,
 'Crumble': 53,
 'ice cream': 55}

I'm not sure I'm using the right words when I do my research so a little help would be nice. Do I have to create a new dictionay and sum all the keys starting with 'ice cream'?

A: This code assumes that the keys of the different flavours of the desserts only differ at the end of the dish's name, which isn't guaranteed (for example it'll fail for ice cream Mint chocolate), but it's the best I could come up with.
simplified_dessert = dict()
core_dish = ''

for dish_name in dessert:
    if word:
        if dish_name.split()[:-1] == core_dish:
            simplified_dessert[core_dish] += dessert[dish_name]
    else:
        word = dish_name.split()[:-1]
        simplified_dessert[core_dish] = dessert[dish_name]

A: Maybe you can try this approach by using the defaultdict from collections module to parse the key as the criteria and recreate a new dictionary. This might help you:

from collections import defaultdict

ddc = defaultdict(int)

for key, val in Dessert.items():
    if key.startswith('ice'):
        key = key.split()[:2]             # extract "ice cream' as key
        ddc[' '.join(key)] += val
    else:
        ddc[key] += val

print(ddc)

Output:
defaultdict(<class 'int'>, {'cake': 71, 'Crumble': 53, 'ice cream': 55})


text:
Q: How get value from textbox in templatefield in gridview after buttonclick? i have follow gridview and i need get value from textbox in templatefield "VyskaStavky" after i click on button. Please can someone tell me how i can do that?
I tried something like this
           CommandArgument='<%# Eval("Id")+","+Eval("VyskaStavky")%>'
but i have problem, because VyskaStavky is not property of class Kurz (my naming of datasourceID is name of class + D from data and S from source)
    <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataSourceID="KurzDS" DataKeyNames="Id" OnRowCommand="GridView1_RowCommand">
        <Columns>
            <asp:BoundField DataField="Id" HeaderText="Id" SortExpression="Id" ReadOnly="True" Visible="False" />
            <asp:BoundField DataField="Zapas" HeaderText="Zapas" SortExpression="Zapas" ReadOnly="True" Visible="False" />
            <asp:BoundField DataField="AktKurz" HeaderText="AktKurz" SortExpression="AktKurz" />
            <asp:BoundField DataField="Tip" HeaderText="Tip" SortExpression="Tip" />
            <asp:BoundField DataField="Handicap" HeaderText="Handicap" SortExpression="Handicap" />
    <asp:TemplateField>
        <ItemTemplate>
            <asp:TextBox ID="VyskaStavky" runat="server" Text=""></asp:TextBox>
        </ItemTemplate>
        </asp:TemplateField>
            <asp:TemplateField>
            <ItemTemplate>
                <asp:Button ID="Button1" Text='Podat stavku' CommandArgument='<%# Eval("Id")%>'  CommandName="PodatStavku" runat="server" CausesValidation="false" />
            </ItemTemplate>
    </asp:TemplateField>
        </Columns>
    </asp:GridView>

Thanx a lot

A: I solved My problem. I changed templete button (from command to onclick)
            <ItemTemplate>
                <asp:Button ID="Button1" Text='Podat stavku' OnClick="Button1_Click" runat="server" CausesValidation="false" />
            </ItemTemplate>

and  in c# i got values
    protected void Button1_Click(object sender, EventArgs e)
    {
        Button btn = sender as Button;
        GridViewRow row = btn.NamingContainer as GridViewRow;
        string pk = GridView2.DataKeys[row.RowIndex].Values["Id"].ToString();
        TextBox ss = GridView2.Rows[row.RowIndex].Cells[3].FindControl("VyskaStavky") as TextBox;
        //ss.text have my requested value
    }


text:
Q: Android: организация прелодера Здравствуйте!
Возникла такая проблема, не получается написать эффективный прелодер данных.
После авторизации пользователя, на сервер последовательно посылаются 5 запросов, их ответы прасятся и пишутся в базу, данных с сервера приходит не много, но это всё занимает, как оказалось, огромное количество времени и приложение раз через раз падает с диалогом "Приложение повисло, подождать или закрыть?". Попытался поискать на гитхабе похожие REST проекты, но ничего не нашел. Подкиньте пожалуйста идею, как лучше сделать?
A: А зачем Вы используете сервис для этого? Мой вам совет: юзайте Async Http Client
Это красивая, удобная обертка вокруг Apache HTTP Client с человеческим лицом, которая содержит callbacks на все случаи жизни, в вашем случае onProgress и которые уже в UI-потоке, при том, что основные операции происходят в фоне(что-то вроде AsyncTask, выражаясь простым языком). Вы пишите запрос - в onProgress(уточните в документации) показываете крутяшку свою с сообщением - получаете ответ в методе onSuccess или если ошибка в onFailure.
A:
возврат в главный поток идет после выполнения запроса и только тогда посылается
следующий запрос, поэтому происходит так, что главный поток долго выполняется...

Фактически это все равно означает, что вы "держите" главный поток - поэтому все и падает. Надо делать не так:

*

*Из фонового сервиса/потока/асинктаска шлем запрос на сервер

*По получению запроса пишем результаты в локальную БД

*Над локальной БД рисуем ContentProvider

*Над ContentProvider рисуем CursorLoader и результаты читаем в основном потоке например через ListView
В этом случае отрисовка результатов будет происходить по мере получения ответа от сервера без задержки юайного потока.
Update здесь Google покрасивше расписал как это должно работать.


text:
Q: Define Layout, GUI by Code at Runtime Net Developer planning a new Product.
It will amongs other things generate dynamically its User Interface from a downloaded File.
I read that file and depending on it i create the necesseray buttons, labels, tables etc..
I wish to outsource that similar kind of product for a development for the IPhone..
So my question to Iphone experts is. Is this possible with the Iphone too?
With 'possible' I mean basically if it is technically possible and if it is 'allowed' on MacStore..
Any feedback is much appreciated...

A: Yes, it is possible and allowed. There are very little UI related operations that can't be done programatically on Cocoa Touch.

A: The user interface files on the iOS, the (the XIB files), are nothing more than a files containing archived objects. So when you create a static interface in Interface Builder, what Xcode actually does is to create objects for all the UI elements, setting the object properties according to your wishes, setting up the object graph (which objects has references to which other object) and finally archives the whole graph into a file. When you load a XIB file, the objects are simply unarchived and you get an object graph with all the UI objects in their desired states.
That means whatever can be done by loading an interface from a XIB file can also be done problematically. All you have to do is creating the objects yourself, setting all the properties as desired and chaining them to the desired object graph. And yes, creating UI problematically is absolutely allowed by the App Stores (for Mac and for iOS), since it does the same thing by hand as loading a XIB file does automated.


text:
Q: Symfony - image does not show up on page I am fairly a beginner at Symfony, doing rather well, but still having problem with images on page. These are facts:

*

*application is local, web page does not go live

*application is set in Apache so that start page is called using only a name:
<VirtualHost *:80>
    DocumentRoot "C:/xampp/htdocs/HealthCareSymfony/web/app_dev.php"
    ServerName HealthCareSymfony
 </VirtualHost>

*application start page is therefor just "http://healthcaresymfony/"

*images are copied in web/images folder (though I tried othe folders too, like Resources/public/images etc)

*standard image asset in twig:
img src="{{ asset('/images/Poppy-3.png') }}" alt="beach"

*tried the previous with number of other versions of path... none worked!

*when I try to get page with image like  (got the path from inspect page) "http://healthcaresymfony/web/images/Poppy-3.png" I get error "No route found for "GET /web/images/Poppy-3.png"

*tried number of ways to get page with this image, always same error.

Please, help me to find what am I doing wrong here!

A: I would say your DocumentRoot was incorrectly set
It should not point to the actual app_dev.php script
instead use
DocumentRoot C:/xampp/htdocs/HealthCareSymfony/web

Also your image does not seem to have < and > even when using twig the HTML you use should be correctly formed
<img src="{{ asset('/images/Poppy-3.png') }}" alt="beach">

Here is an example of one of my Symfony project Virtual Hosts
<VirtualHost *:80>
    ServerName sitename.test
    ServerAlias www.sitename.test
    DocumentRoot c:/websrc/sitename/web
    <Directory  "c:/websrc/sitename/web/">

        AllowOverride All
        Require local

        # this forces app_dev.php to be run by default
        <IfModule rewrite_module>
            RewriteEngine On
            RewriteCond %{REQUEST_FILENAME} !-f
            RewriteRule ^(.*)$ app_dev.php [QSA,L]
        </IfModule>
    </Directory>
</VirtualHost>

You would also have to add sitename.test into your HOSTS file to make this work
127.0.0.1 sitename.test
::1 sitename.test

Then restart the dnscache from a command windows started using "Start as Administrator"
>net stop dnscahce
>net start dnscache

or reboot the PC


text:
Q: Uninstall packages inside python I uninstalled tensorflow with:
pip uninstall tensorflow

it was successful and when I run it again, I receive this message:
Skipping tensorflow as it is not installed.

The issue is that when I import tensorflow inside python via:
python
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow
2022-05-27 09:35:22.981575: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'cudart64_100.dll'; dlerror: cudart64_100.dll not found
2022-05-27 09:35:22.981872: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
>>> tensorflow.__version__
'1.15.0'
>>>

Do there is tensorflow installed and I could not uninstall it. How can I uninstall it completely? I want to install tensorflow==1.14 instead of 1.15.
I can install tensorflow==1.14.0 via:
pip install tensorflow==1.14.0

but when I run python, it's using tensorflow==1.15 instead of 1.14.0

A: If you run "pip list", do you see TF listed still?
Are you running Python with your code in a VENV?  Curious if TensorFlow could be installed in main Python yet removed from VENV (though I saw your response to comment above).
Maybe go into Python's site-packages dir and check if TF package folder exists.  If on Windows, maybe Python is installed in your Users directory, this TF the same.  It can definitely get confusing.
Other folks mentioned to uninstall using "...-{cpu|gpu}".
I found this SO discussion about similar issue that may help.
Link
Please keep us updated on findings.


text:
Q: submit form based on location on page load I have a drop down menu that I am using as selector for the country to view our locations.
The drop down is currently working but I want it to load users current country before they have to select it from the drop down so that it automatically shows them the listing of locations in their country.
Currently I have the dropdown retrieving the users country however it is not submitting the form it is only showing the "selected" value.
Here is my code including the sql:
<?php

require_once( DIR_WS_CLASSES . 'geoplugin.class.php');
$geoplugin = new geoPlugin();
$geoplugin->locate();

echo $geoplugin->countryCode;

echo $geoplugin->countryName;

?>

<?php echo LOCATION_TITLE ;?>

<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post"  >

    <select name="selectboxvalue" onchange="this.form.submit();" id="selectboxvalue"   >

        <option>SELECT A COUNTRY</option>
        <option value="<?php $geoplugin->countryCode; ?>" <?php if ($geoplugin->countryCode == 'US' || $_POST["selectboxvalue"]=="US" ) echo "selected=\"selected\""; ?>>USA</option>
        <option value="canada" <?php if ( $geoplugin->countryCode == 'CA'|| $_POST["selectboxvalue"]=="canada" ) echo "selected=\"selected\""; ?>>Canada</option>
        <option value="international" <?php if ( $_POST["selectboxvalue"]=="international" ) echo "selected"; ?>> International</option>
    </select>

</form>

<?php

$location_query_raw =  "select l.storetitle,l.storeimage, l.country, l.state, l.city, l.postal, l.address, l.phone, l.storelink, l.latitude,l.longitude, l.sortorder, l.status from locations l";

switch ($_POST['selectboxvalue']) {
    case "US":
        $location_query_raw .= "  where l.country like \"%USA%\" ORDER BY l.state ";
        break;
    case "canada":
        $location_query_raw .= " where l.country like \"%CA%\" ORDER BY l.state";
        break;
    case "international":
        $location_query_raw .= " where l.country not like \"%USA%\" and l.country not like \"%CA%\" ORDER BY l.state";
        break;
    default:
        $location_query_raw .= " order by l.state";
        break;
}

$location_query= tep_db_query( $location_query_raw);

A: I found the problem... you aren't echoing the value.. :-)
<option value="<?php $geoplugin->countryCode; ?>"

Just add the echo and now the value will post! :
<option value="<?php echo $geoplugin->countryCode; ?>"


text:
Q: DJANGO not receiving data with POST I'm having an issue trying to send data with fetch to DJANGO.
I want to send some data to django through fetch but when I debug I receive nothing in the post value, do you know what could be happening?
This is my fetch call:
const defaults = {
    'method': 'POST',
    'credentials': 'include',
    'headers': new Headers({
        'X-CSRFToken': csrf_token,
        'Content-Type': 'application/json',
        'X-Requested-With': 'XMLHttpRequest'
    }),
    data:{'name':'A name'},
    dataType:'json'
}

const response = await fetch (url, defaults)

When I debug I get an empty querydict in the request.POST
What am I doing wrong?


text:
Q: ListView ScrollTo without delay on UWP I have created a simple ListView as I showed on my ListView is not scrolling with grouping question.
My problem is, that on UWP, I need to insert a await Task.Delay(1500) on Windows Phone, and about 200ms on Windows Desktop.
I am not filling the ListView with a lot of data, so I also want to know, what happen when the user runs it, as they can have a lot of data.
But why do I need it, cause to me it seems like a buggy code?
The Exception I am getting without Task.Delay is Error HRESULT E_FAIL has been returned from a call to a COM component.
The message is
System.Runtime.InteropServices.COMException: Error HRESULT E_FAIL has been returned from a call to a COM component.
   at Windows.UI.Xaml.UIElement.Measure(Size availableSize)
   at Xamarin.Forms.Platform.UWP.VisualElementRenderer`2.MeasureOverride(Size availableSize)
   at Windows.UI.Xaml.UIElement.Measure(Size availableSize)
   at Xamarin.Forms.Platform.UWP.VisualElementRenderer`2.MeasureOverride(Size availableSize)
   at Windows.UI.Xaml.UIElement.Measure(Size availableSize)
   at Xamarin.Forms.Plat

How can I fix this error/buggy code?
UPDATE
If I set HasUnevenRows = false it does not crash, but it just scrolls to the incorrect ViewCell. But I need to use HasUnevenRows = true.
The same problem is occuring if I set HasUnevenRows = false and a RowHeight.

A: My issue was similar to yours, where a Task.Delay() made the scrolling work on iOS. The reason was threading, where the scrolling was not in sync with other "tasks". After going from
Device.BeginInvokeOnMainThread(() =>
{
   listView.ScrollTo(defaultItem, ScrollToPosition.Center, true);
});

to
listView.ScrollTo(defaultItem, ScrollToPosition.Center, true);

I didn't need Task.Delay() anymore and the scrolling does work now. Though I never got your exception.


text:
Q: How to import data from a messed up CSV using VBA This is sort of a "which direction is best" sort of question.
I have a .CSV file that is in a less then ideal format.  I'll diagram the file below so you can see what I'm talking about.  This file is provided to me by a vendor who should know better... (Google, cough, hack, cough).
What is the best way to import only table2 from this data using VBA?  I'll list methods I've been trying after the diagram.
.CSV file looks like this if opened:
 Title Cell
 File Info Cell
 Time Date Cell

 Data1, Data 2
 Data1, Data 2
 Data1, Data 2
 Data1, Data 2
 Data1, Data 2
 Data1, Data 2
 Data1, Data 2
 Data1, Data 2
 Data1, Data 2
 Data1, Data 2
 Data1, Data 2
 Data1, Data 2
 Data1, Data 2
 Data1, Data 2
 ....(continues for around 800 rows)

 Second Table Title Cell
 Col1Title, Col2Title, ColTitle, Col4Title ....(continues for around 50 columns)
 Data 3,    Data4,     Data 5,   Data6 ....(continues for around 50 columns)
 Data 3,    Data4,     Data 5,   Data6 ....(continues for around 50 columns)
 Data 3,    Data4,     Data 5,   Data6 ....(continues for around 50 columns)
 Data 3,    Data4,     Data 5,   Data6 ....(continues for around 50 columns)
 Data 3,    Data4,     Data 5,   Data6 ....(continues for around 50 columns)
 Data 3,    Data4,     Data 5,   Data6 ....(continues for around 50 columns)
 Data 3,    Data4,     Data 5,   Data6 ....(continues for around 50 columns)
 Data 3,    Data4,     Data 5,   Data6 ....(continues for around 50 columns)
 ...(Continues for around 1500 rows)
 End of CSV

I've thus far attempted to the ADODB object but that relies on SQL query's (which to my limited SQL knowledge) assume that the data is formated correctly as a table - which it is not here.
I've also been trying reading the file line by line.
I could force either of these two solutions to work, but it's pretty messy both ways. I feel like there has to be clean way to do this?
Can anyone suggest a better approach or an efficient approach to the methods I've already tried?
Thanks in advance.
addendum
@ user3724 this is what i've been trying on the line by line approach:
Open strFile For Input As #1

  countLine = 0

  Do Until EOF(1)
     Line Input #1, LineFromFile
     (Increment countLine)
     (Break line into array)
     (strComp() each element with the value for title of Table 2)
     (When strComp() returns true return countLine as upperValue)
     (Exit Loop)
 Loop

 countLine = 0

 Do Until EOF(1)
     Line Input #1, LineFromFile
     (Increment countLine)
     If countline is >= uppervalue
         (Parse line and return it to target row of target worksheet)
     End If
 Loop

When I code this whole thing out it is a slow mess - lots of if statements and loops within loops.  @user3724, could you review this based on your experience?

A: I have no reputation to comment...But I may add answer.
If you wanna use vba then open file and read line by line (for example using line input) omit lines until you detect second empty string, then parse headers (next two lines) and store column headers in separate array (use redim preserve or predefined array size it depends on file format). The rest of "second" table just read line by line and parse each line to array (i recomend dynamic array with first dimension relying on count of headers) the second dim increase with each parsed line.
After all you will recieve two arrays one with field/column captions/names and the second with data. both arrays have same first dimensions.
The second stage upload data via ado using arrays.
I used the method for import data to db via ado from csv files with weird structure just like yours


text:
Q: PyQt ToolTip for QTreeView Please axplain how to enable and show a tooltip for each item in QTreeView. I found a sample of code class TreeModel(QAbstractItemModel) but due to my beginner's level I can't understand how to apply it to my needs.
Data for tooltip should be taken from value of key "note" in dictionary data_for_tree.
#!/usr/bin/env python -tt
# -*- coding: utf-8 -*-

from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *

import sys
reload(sys)
sys.setdefaultencoding('utf8')

data_for_tree = {"tomato":{"color":"red","ammount":"10", "note":"a note for tomato"},"banana":{"color":"yellow","ammount":"1", "note":"b note for banana"}, "some fruit":{"color":"unknown","ammount":"100", "note":"some text"}}

class TreeModel(QAbstractItemModel):

    def data(self, index, role=Qt.DisplayRole):
        #...
        if role == Qt.ToolTipRole:
            return 'ToolTip'

    def flags(self, index):
        if not index.isValid():
            return Qt.NoItemFlags # 0
        return Qt.ItemIsSelectable # or Qt.ItemIsEnabled

class ProxyModel(QSortFilterProxyModel):

    def __init__(self, parent=None):
        super(ProxyModel, self).__init__(parent)

    def lessThan(self, left, right):
        leftData = self.sourceModel().data(left)
        rightData = self.sourceModel().data(right)
        try:
            return float(leftData) < float(rightData)
        except ValueError:
            return leftData < rightData

class MainFrame(QWidget):
    def __init__(self):
        QWidget.__init__(self)

        self.MyTreeView = QTreeView()
        self.MyTreeViewModel = QStandardItemModel()
        self.MyTreeView.setModel(self.MyTreeViewModel)
        self.most_used_cat_header = ['Name', "ammount", "color"]
        self.MyTreeViewModel.setHorizontalHeaderLabels(self.most_used_cat_header)
        self.MyTreeView.setSortingEnabled(True)
        self.MyTreeView_Fill()

        MainWindow = QHBoxLayout(self)
        MainWindow.addWidget(self.MyTreeView)
        self.setLayout(MainWindow)

    def MyTreeView_Fill(self):
        for k in data_for_tree:
            name = QStandardItem(k)
            ammount = QStandardItem(data_for_tree[k]["ammount"])
            note = QStandardItem(data_for_tree[k]["color"])
            tooltip = data_for_tree[k]["note"]
            item = (name, ammount, note)
            self.MyTreeViewModel.appendRow(item)
        self.MyTreeView.sortByColumn(1, Qt.DescendingOrder)
        proxyModel = ProxyModel(self)
        proxyModel.setSourceModel(self.MyTreeViewModel)
        self.MyTreeView.setModel(proxyModel)

        c = 0
        while c < len(self.most_used_cat_header):
            self.MyTreeView.resizeColumnToContents(c)
            c=c+1

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = MainFrame()
    main.show()
    main.move(app.desktop().screen().rect().center() - main.rect().center())
sys.exit(app.exec_())

A: As you are using the QStandardItem and QStandardItemModel classes (which is what I would recommend!) you don't need to bother with the TreeModel class you have found. Creating your own model is rarely necessary, but for some reason tutorials often encourage you to do so. If you find something encouraging you to subclass QAbstractItemModel, I suggest you check on stack overflow first to see if there is a simpler way to do it! In this case, there is a very simple way to add your tooltips.
If you look at the C++ documentation (which I often find more useful than the PyQt documentation for finding out what methods are available), you will see that QStandardItem has a method called setToolTip().
So all you need to do is call this method on each of the items you add to the model. For example, inside the loop in the MyTreeView_Fill method:
name = QStandardItem(k)
ammount = QStandardItem(data_for_tree[k]["ammount"])
note = QStandardItem(data_for_tree[k]["color"])
tooltip = data_for_tree[k]["note"]
name.setToolTip(tooltip)
ammount.setToolTip(tooltip)
note.setToolTip(tooltip)

Here I've set the tooltip to be the same for every cell in the row (name, amount and note) but you could easily change this to have a different tooltip for one of the cells (hopefully it is obvious how to do that)


text:
Q: Change login to logout when the credentials is correct in asp.net Even if it wrong credentials it change the login to logout but it when it is null it still login. because of the if functions customer.User != null, how can I do if it is wrong credentials

      @{
                    AccountContactVM customer = (AccountContactVM)ViewBag.AccountData;
                }

                @if (customer.User != null)
                {

                        @customer.User.FirstName @customer.User.LastName

                                            @customer.User.FirstName @customer.User.LastName

                                            @customer.Company.AccountName

Customer Portal

Logout

                }
                else
                {

Register

Login

                }

Cart({{CartCount}})

Here is my controller code for the view
Controller code
[HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult SignIn(UserLogin user)
    {
        //Account Varialble
        Models.CustomerModel.Account account = new Models.CustomerModel.Account();

        //Contact Variable
        Models.CustomerModel.Contact contact = new Models.CustomerModel.Contact();

        AccountContactVM customer = new AccountContactVM();

        var a = user.Password.GetHashCode();
        ViewBag.CartItemCount = cartItemCount;
        if (ModelState.IsValid)
        {

            LoginAction login = new LoginAction();
            contact = login.ContactProfile(user);
            if (contact.ContactId != Guid.Empty)
            {
                if(contact.Authenticated == false)
                {
                    ViewBag.Message = "Your account is not confirmed.";

                    customer.Company = account;
                    customer.User = contact;
                    ViewBag.AccountData = customer;
                    return View(user);
                }else
                {
                    account = login.AccountProfile(contact.AccountId);
                    if (account.AccountId != Guid.Empty)
                    {
                        customer.Company = account;
                        customer.User = contact;
                        helper.SetObject("accountcustomer", customer);
                        ViewBag.AccountData = customer;
                        return RedirectToAction("Index","Home");
                    }

                    ViewBag.AccountData = customer;
                    ViewBag.Message = "Unable to find company profile";
                    return View(user);
                }

            }

            customer.Company = account;
            customer.User = contact;

            ViewBag.AccountData = customer;
            ViewBag.Message = "Invalid credentials";
            return View(user);

        }
        return View(user);
    }

A: Summarizing your requirements.

*

*Even if user login credentials are incorrect, you still want to display "Login" part of the view.

Personally, I am not quite sure about the business reason here...
Anyway, from your controller's code I am assuming that contact object returned by login.ContactProfile(user) is never null and when contact.ContactId is an empty GUID, then user has entered wrong credentials, and this results in "Invalid credentials" message.
As a simple solution following existing coding style would be to add additional condition to your if in the view. See below.
@if (customer.User != null || (customer.User != null && customer.User.ContactId == Guid.Empty)

I don't see code from all your classes, therefore this solution is based on the assumption above.
And ideally I would refactor code to have different partial views and dedicated view model, however this would be much bigger effort.


text:
Q: Evaluate $ \sum\limits_{j \in \mathbb{Z}_{\geq 0}} {n \choose r+kj}$ where $n,k$ are fixed
Is there a general way/technique to evaluate $ \sum\limits_{j \in \mathbb{Z}_{\geq 0}} {n \choose r+kj}$ in terms of $r$, where we consider $n$ and $k$ fixed natural numbers and $n > k$? (here, we consider ${a \choose b}=0$ if $b>a$)

In other words, I want the sum of the binomial coefficients ${n \choose i}$ where $i$ is less than or equal to $n$ and belongs to the arithmetic progression $r,r+k,r+2k,..., $ etc.
If $r=0$, we're looking for the sum of the binomial coefficients ${n \choose i}$ such that $k|i$, i.e., we want to evaluate the sum ${n \choose 0}+{n \choose k}+{n \choose 2k}+...$, which can be done using the roots of unity filter technique (link here) for the sum of the coefficients $a_i$ of a polynomial $f$ such that $k|i$ (in this case $f$ would be the polynomial $(1+x)^n$)
Any help? Thank you!


text:
Q: Determining the rotation matrix and subsequent translation which needs to be applied to a plane so that it aligns to an axis plane? Hi guys (and girls too),
 This might be the stupidest question to a math versed person but I'm having a lot of trouble and would appreciate it if someone could explain it please:
I would like to determine what angle of rotation I should apply to some plane in 3D whose normal form I have been given (in Matlab those are 4 (a,b,c,d) values representing  aX+bY+c*Z=d) so that after the applied rotation it aligns to an axis plane (i.e. XY plane which should have a normal form written as 1*X+1*Y+0*Z=1 <- unless I'm mistaking this)...
I'm sure it needs to be done using the normalized form thus I should divide the a,b,c values by d first, then try do something with cross product of the planes (as that is dependent on the cos of the angle between such vectors I think) but for the love of everything I am just baffled as to where and how to start with it - especially having seen some explanations using quaternions and similar matrix solutions that seem to be more powerful.
Can anyone help me please? TIA


text:
Q: Can 2 magnets crush something with their force? Say we have 2 magnets facing the same way with same charge, and we have a rock tied from the celling and to the ground so the rock dose not move away. Since the 2 magnets are repealing each other, if they move closer would the force of the magnets repealing break the rock?
Assume the rock is no bigger than a rice grain or an eraser in a pencil.

A: Only if the "rock" is something that's also magnetic. Most rocks aren't, and the magnetic force passes right through them as if they aren't there.
But if you replace that rock with something magnetic (and conductive helps), sure, with enough force you'll crush it.


text:
Q: How do specify the resolver (and GHC) Travis should use to test my Haskell package? I'm trying to test my Haskell package against several Stackage resolvers on Travis, but my --resolver environment variable is being ignored.
For example, if I specify
env:
- ARGS="--resolver lts-4.0"

in my .travis.yml,  I still still seem to be using a different resolver (the one in my stack.yaml?) and GHC, as shown by lines like
Installing library in
/home/travis/build/orome/crypto-enigma-hs/.stack-work/install/x86_64-linux/lts-9.1/8.0.2/lib/x86_64-linux-ghc-8.0.2/crypto-enigma-0.0.2.9-6Cs7XSzJkwSDxsEMnLKb0X

in the corresponding build log, which indicates a different resolver (9.1), and corresponding GHC (8.0.2) being used.
How should my build (stack.yaml, .travis.yml, etc.) be configured to ensure that the resolvers (and corresponding GHC) I specify are used to preform my Travis builds and tests?

A: With env you just define environment variables. You still have to use them. stack on its own does not respect the ARGS variable, so use it in your script, e.g.
install:
# Build dependencies
- stack $ARGS --no-terminal --install-ghc test --only-dependencies

script:
# Build the package, its tests, and its docs and run the tests
- stack $ARGS --no-terminal --install-ghc test --haddock --no-haddock-deps

You should probably use a better name, for example RESOLVER:
env:
- RESOLVER=lts-4.0
- RESOLVER=lts-6.0
- RESOLVER=lts-8.0

install:
# Build dependencies
- stack --resolver $RESOLVER --no-terminal --install-ghc test --only-dependencies

script:
# Build the package, its tests, and its docs and run the tests
- stack --resolver $RESOLVER --no-terminal --install-ghc test --haddock --no-haddock-deps

Also keep in mind that it's usually a better idea to use multiple stack.yml to hold the configuration for that specific LTS variant.
For more information, see stack's Travis documentation and Travis' environment variables documentation.


text:
Q: WUBI INstal problem - Windows 7 I have tried to use the WUBI install for 14.04. All appears to go well until towards the end the install starts to completely remove items. These items are things such as Firefox and rhythmbox etc. When the install has finished and the system reboots for finalisation the Ubuntu OS load states there is a serious error on the disk and it cannot mount the volume.
The Ubuntu directory that is left on the disk after the install looks pretty empty though does include directories such disks.
Any ideas are welcome.
PS. I have uninstalled Ubuntu using windows without problem.


text:
Q: Why is page scrolled to the top after calling window.scrollTo(...) wiith non zero Y I am observing strange behavior and I believe I can exclude some common reasons.
I need to implement scroll position restoration on going back in single page app (in Angular).
First, I need to say that for whole time, for debugging purpose, I have something like style="min-height: 8000px !important;" on body, to be sure that there is always enough space and viewport is not shorter then requested scroll.
history.scrollRestoration is set to "manual"
I am simply calling window.scrollTo(0, Y) when user navigates back.
Sometimes it works perfectly, sometimes it's scrolled to top (and scroll event emitted by browser says also scoll to 0) I dind't find clue why it's ok and why not/
Code looks like
window.addEventListener('scroll', function (e: any): void {
  console.log('window scrolled to ' + window.scrollY);
});

// called with resored Y value
function onNavigateBack(y) {
  console.log("Before " + window.scrollY)
  console.log("Calling scroll to y = " + y)
  window.scrollTo(0, y)
  console.log("After " + window.scrollY)
}

Assume that saved value is y=470, than output is
Before ... (there is actual value)
Calling scroll to y = 470
After 470
.... route is initialized there ...
window scrolled to 0

Observations

*

*no other window.scrollTo neither window.scroll is called (verified by mocking it)

*when scrollTo is not called then scroll to top in wrong case is not happening -> invalid scroll to top is consequence of requested scroll

*no other scoll event is triggered

*Chrome and Firefox are consistent, understand works sometimes

The questions is. Any idea what can cause such behavior? Or what can intercept scrolling?
My first concern was that page is simply too short between rendering, but it preserves even with min-height hack.
EDIT: One more observation
Seems that success scroll is linked to small Y (like never fails for y = 200) and failing on big Y (eg Y > 800px). But still, scrolling bellow page range should scroll to the current bottom. This makes no sense to me.

A: Wrapping scrollTo call into window.requesteAnimationFrame callback seems to fix the issue. Although I don't have idea why.


text:
Q: Is there a way to see the UI of an angular application in design time without running the application? I work on localisation engineering for an application that is developed in Angular. Since, the application is heavy and needs to enter lot of data in various pages to navigate to a particular screen, I am trying to do a quick check of the screens at design time to verify if the screens have been localized. Is there a way to check the look and feel of UI without running the application?

A: Angular is rendering the page based on the values set in ts code. You can set data manually in component.html and run the file in browser.


text:
Q: Escaped JSON response with [WebMethod] The JSON response from the following code is wrongly escaped as described below.
My webmethod is like this:
    [WebMethod (Description="doc here")]
    [ScriptMethod(ResponseFormat=ResponseFormat.Json)]
    public string responseMyObject() {
            if (!Setup()) return "";

            ...
            Proxy pu = new Proxy(...);
...

            string toReturn = JavaScriptConvert.SerializeObject(pu.getMyObject());
            Console.WriteLine(toReturn);
            return toReturn;
    }

from the console I get:
{"field1":vaule1,"field2":value2}

from JS:
$.ajax({
    type: "POST",
    url: "/myapi/myClass.asmx/responseMyObject",
    data: "{}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
                    var object = msg.d;
                    alert(object.field1);
    }
});

The problem is that in the HTTP response header I can see that the JSON response is wrongly (?) escaped in the following way:
{"d":"{\"field1\":value1,\"field2\":value2}"}

What's strange is that the console print is fine (but not yet encapsulated in {d: ...}
{"field1":value1,"field2":value2}

With similar code, if I call a [WebMethod] that returns basic types (no object) the JSON response is ok. Like:
{"d":8080}

A: [WebService]
[ScriptService]
public class MyWebService : WebService
{

  [WebMethod (Description="doc here")]
  [ScriptMethod( UseHttpGet=false, ResponseFormat=ResponseFormat.Json)]
  public MyObjectType responseMyObject()
  {
      Proxy pu = new Proxy(...);

      return pu.GetMyObject();
  }

}

You dont need a JSON serializer, tagging it with the ScriptService attribute gives it tie ability to serialize JSON out. You were pre serializing the JSON and then serializing it again :(

A: Why are you calling JavaScriptConvert.SerializeObject?
Can't you just change the return type of your method to be the type returned by pu.getMyObject() and the framework will do the rest?
In other words...
[WebMethod (Description="doc here")]
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public MyObjectType responseMyObject()
{
    Proxy pu = new Proxy(...);

    ...

    return pu.GetMyObject();
}

At the moment I think you're serializing your object into a JSON format and then, when you return from the method, the framework is serializing that string (which contains JSON formatted data) into a JSON format.


text:
Q: Tensorflow TypeError: Fetch argument None has invalid type  while finding gradient It's a text analysis task with CNN model,I want to visualize which word is triggering most to my particular classification,Here is my code
with tf.Session() as sess:

saver = tf.train.import_meta_graph('/home/rakesh/WORK/CNN_Lookout/runs/1519022246/checkpoints/model-200.meta') #load graph
saver.restore(sess,tf.train.latest_checkpoint('/home/rakesh/WORK/CNN_Lookout/runs/1519022246/checkpoints/./')) #load weigt

graph = tf.get_default_graph()
input_x = graph.get_tensor_by_name("input_x:0")
input_y = graph.get_tensor_by_name("input_y:0")
dropout_keep_prob=graph.get_tensor_by_name("dropout_keep_prob:0")
embedding_W= graph.get_tensor_by_name("embedding/W:0")

embedded_chars = tf.nn.embedding_lookup(embedding_W, input_x)
embedded_chars_expanded = tf.expand_dims(embedded_chars, -1)

conv_maxpool_5_W= graph.get_tensor_by_name("conv-maxpool-5/W:0")
conv_maxpool_5_b= graph.get_tensor_by_name("conv-maxpool-5/b:0")
conv_maxpool_5_conv= graph.get_operation_by_name("conv-maxpool-5/conv")
conv_maxpool_5_relu= graph.get_tensor_by_name("conv-maxpool-5/relu:0")
conv_maxpool_5_pool= graph.get_tensor_by_name("conv-maxpool-5/pool:0")

conv_maxpool_7_W= graph.get_tensor_by_name("conv-maxpool-7/W:0")
conv_maxpool_7_b= graph.get_tensor_by_name("conv-maxpool-7/b:0")
conv_maxpool_7_conv= graph.get_tensor_by_name("conv-maxpool-7/conv:0")
conv_maxpool_7_relu= graph.get_tensor_by_name("conv-maxpool-7/relu:0")
conv_maxpool_7_pool= graph.get_tensor_by_name("conv-maxpool-7/pool:0")

conv_maxpool_9_W= graph.get_tensor_by_name("conv-maxpool-9/W:0")
conv_maxpool_9_b= graph.get_tensor_by_name("conv-maxpool-9/b:0")
conv_maxpool_9_conv= graph.get_tensor_by_name("conv-maxpool-9/conv:0")
conv_maxpool_9_relu= graph.get_tensor_by_name("conv-maxpool-9/relu:0")
conv_maxpool_9_pool= graph.get_tensor_by_name("conv-maxpool-9/pool:0")

# Combine all the pooled features
num_filters_total = 128 * 3
pooled_outputs = [conv_maxpool_5_pool,conv_maxpool_7_pool,conv_maxpool_9_pool]
print(conv_maxpool_5_pool.shape)
h_pool = tf.concat(pooled_outputs,3)
h_pool_flat = tf.reshape(h_pool, [-1, num_filters_total])

final_w= graph.get_tensor_by_name("W:0")
final_b= graph.get_tensor_by_name("output/b:0")

# Unpooling
Ps = (tf.gradients(conv_maxpool_5_pool, conv_maxpool_5_relu))[0]
unpooled = tf.multiply(Ps, conv_maxpool_5_relu)
print(sess.run(unpooled,feed_dict))
print(sess.run(unpooled,feed_dict).shape)
#print(sess.run(conv_maxpool_5_relu,feed_dict))

# Deconv
batch_size = tf.shape(input_x)[0]
ds = [batch_size]
ds.append(embedded_chars_expanded.get_shape()[1])
ds.append(embedded_chars_expanded.get_shape()[2])
ds.append(embedded_chars_expanded.get_shape()[3])
deconv_shape = tf.stack(ds)
deconv = tf.nn.conv2d_transpose(
    unpooled,
    conv_maxpool_5_W,
    deconv_shape,
    strides=[1, 1, 1, 1],
    padding='VALID',
    name="Deconv"
    )
print(sess.run(deconv,feed_dict))
print(sess.run(deconv,feed_dict).shape)
print(sess.run(embedded_chars_expanded,feed_dict).shape)
#reshaped to original w2v embeding
embedded_chars_expanded_shape=sess.run(embedded_chars_expanded,feed_dict).shape
embedded_chars_back=tf.reshape(deconv,[embedded_chars_expanded_shape[0],embedded_chars_expanded_shape[1],embedded_chars_expanded_shape[2]])
print(sess.run(embedded_chars_back,feed_dict))
print(sess.run(embedded_chars_back,feed_dict).shape)
print(sess.run(embedded_chars,feed_dict))
print(sess.run(embedded_chars,feed_dict).shape)
#original input
print(sess.run(input_x, feed_dict))
print(sess.run(input_x, feed_dict).shape)
input_back = (tf.gradients(embedded_chars_back, input_x))[0]
#print(sess.run(input_back , feed_dict))
#input_back = tf.multiply(input_back, input_x)
#print(sess.run(input_back ,feed_dict).shape)

The last part where I want to get the original input by using gradient from embednding layer , the result is becoming None type, I am using Google word2vec model to get embedding in forward pass.
input_back = (tf.gradients(embedded_chars_back, input_x))[0]  #becoming none

print(sess.run(input_back , feed_dict))

I---->error of last line
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 155, in <module>
File "/home/rakesh/anaconda3/envs/tensorflow/lib/python3.5/site-
packages/tensorflow/python/client/session.py", line 889, in run
run_metadata_ptr)
File "/home/rakesh/anaconda3/envs/tensorflow/lib/python3.5/site-
packages/tensorflow/python/client/session.py", line 1105, in _run
self._graph, fetches, feed_dict_tensor, feed_handles=feed_handles)
File "/home/rakesh/anaconda3/envs/tensorflow/lib/python3.5/site-
packages/tensorflow/python/client/session.py", line 414, in __init__
self._fetch_mapper = _FetchMapper.for_fetch(fetches)
File "/home/rakesh/anaconda3/envs/tensorflow/lib/python3.5/site-
packages/tensorflow/python/client/session.py", line 231, in for_fetch
(fetch, type(fetch)))
TypeError: Fetch argument None has invalid type <class 'NoneType'>

I want to visualize the last cnn layer till the input so I wanted to find out how much is backpropagated till input, which word contribute most,

A: I don't see an explicit question, but I am assuming you are wondering why gradients return a None. tf.gradients (and various similar methods) return None when there is no sequences of differentiable operations connecting the x to the y (or if you explicitly called stop_gradients).
If it is not clear from the code (it is not to me), where the disconnect is, you can view the graph in tensorboard or you can try to bisect the sequence of operations between x and y to narrow down on the exact place where the gradient becomes None.


text:
Q: Inputing multiple doubles on a single line in c using scanf and loops without array My program is suppose to read multiple inputs and display the min, max, sum and the average.  It is supposed to look like this:
Input:
2.5 5 3.5 4.5 jfkjk

output:
min is 2.5
max is 5
sum is 15.5
average is 3.875

The program is supposed to quit when it reaches a non-number or a newline. The user can input as many numbers as they like. I cannot use arrays and must use loops.
This is what my program looks like:
void numbers()
      {
      double digit;
      double sum = 0;
      double avg = 0;
      double max;
      double min;
      unsigned count = 0;
      //int c;
      max = 0;
      printf("Input:");

      do {
          scanf("%lf", &digit);

          min = digit;
          if(max < digit)
              digit = max;
          if(min < digit)
              digit = min;
          sum += digit;
          count++;
          avg = sum/count;
      } while( scanf("%lf", &digit)==1 )

      printf(" min is %lf max is %lf sum is %lf avg is %lf count is %u", min, max, sum, avg, count);
      }

prints out:
Input:2.2 2.3 5 3.5 blah
 min is 3.500000 max is 0.000000 sum is 0.000000 avg is 0.000000 count is 4

A: There are 2 quite unpleasant errors hidden in your code:

*

*the way min and max are (not) being updated while iterating numbers
This:
if(max < digit)
     digit = max;
if(min < digit)            // <-- the comparison for min is incorrect as well
     digit = min;

should be:
if(max < digit)
    max = digit;
if(min > digit)
    min = digit;

since you want to update min / max, not the digit that has been read.

*logic of your loop
This:
do {
    scanf("%lf", &digit);
    ...
} while( scanf("%lf", &digit)==1 )

should be:
while( scanf("%lf", &digit)==1 ) {
    ...
}

A: If it is truly important to:
-- 1) User can input as many numbers as they like.
-- 2) Quit when it reaches a non-number or a newline.
-- 3) No arrays.
then reading in data is challenging.
We must deal with an input line that goes on and on.....
We must distinguish between new-line \n and other white-space char.
Following OP style, let's do the white-space parsing manually and then let scanf() read the number.
#include<stdio.h>
#include<ctype.h>

  ...
  double sum = 0.0;
  double avg = 0.0;
  double max = 0.0;
  double min = 0.0;
  unsigned count = 0;
  int done = 0;
  while (1) {
    double x;
    int ch;
    do {
      ch = getchar();
      if ((ch == '\n') || (ch == EOF)) {
        done = 1;
        break;
      }
    } while (isspace(ch));
    if (done || (1 != scanf("%lf", &x))) break;
    // Cope with first `x`.
    // Could instead be done with `max` initialized to -DBL_MAX, min = DBL_MIN
    if (count++ == 0) {
      min = max = x;
    } else {
      if (x < min) min = x;
      if (x > max) min = x;
    }
    sum += x;
    // OP had the following inside the loop - nicely avoids potential /0 outside loop
    avg = sum/count;
  }


text:
Q: Javascript Help about "document.getElementById" please Here's my code:

        <select id="pa_colour" name="attribute_pa_colour">
            <option value="">Choose an option…</option>
            <option value="black" class="active">Black</option>
            <option value="blue" class="active">Blue</option>
            <option value="red" class="active">Red</option>
            <option value="white" class="active">White</option>
        </select>

            <select>
                <option id="1">One</option>
                <option id="2">Two</option>
                <option id="3">three</option>
                <option id="4">Four</option>
            </select>

In this code what I want to do is when the user clicks an image, the select option value will change.
If the <select id="list"> select has an id it will work fine, but in my case, the select option has no id, but before the select there is a class "catProdAttributeItem".
How do I make it work with document.getElementById and select option?

A: Since the select element is within the catProdAttributeItem div, you can select it using the childNodes property
var selectList = document.getElementById("catProdAttributeItem").childNodes[0];

Rest of the code should work as it is.

A: Select element is the child of Div, so you need to access the child element. For that,use following :
var selectList = document.getElementById("catProdAttributeItem").children[0];

Here is the working demo : http://jsfiddle.net/spdX3/


text:
Q: xAxis values groups as slices + labels in Highcharts How could one achieve the xAxis series 'slices' & outer labels grouping/sub-series as seen in the example below?

chart source: http://data.worldjusticeproject.org/#/groups/BRA

A: Firstly, this is not something that comes off-the-shelf with Highcharts.  The example you provided appears to involve creating some of their own custom visuals. It all takes place in the following file:
http://data.worldjusticeproject.org/scripts/0d579abd.main.js
By beautifying this JavaScript, you can see that the outer labels are added declaratively. For example:
function() {
        "use strict";
        Roli.Labels = ["1.1", "1.2", "1.3", "1.4", "1.5", "1.6", "2.1", "2.2", "2.3", "2.4", "3.1", "3.2", "3.3", "3.4", "4.1", "4.2", "4.3", "4.4", "4.5", "4.6", "4.7", "4.8", "5.1", "5.2", "5.3", "6.1", "6.2", "6.3", "6.4", "6.5", "7.1", "7.2", "7.3", "7.4", "7.5", "7.6", "7.7", "8.1", "8.2", "8.3", "8.4", "8.5", "8.6", "8.7"], Roli.Descriptions = {
            "1.0": "Constraints on Government Powers",
            1.1: "Limits by legislature",
            1.2: "Limits by judiciary",
            1.3: "Independent auditing",
            1.4: "Sanctions for official misconduct",
            1.5: "Non-governmental checks",
            1.6: "Lawful transition of power",
            "2.0": "Absence of Corruption",
    ...
    ...
}

They then go on to define a function drawRadar which makes use of these labels.  This takes place in extending a view in Backbone: http://backbonejs.org/#View-extend


text:
Q: Entity Framework One to Many Relationship Model - How to select column from the child table My overall goal is to return awards with TeamIds that match a list of IDs passed in from a filter. I'm looking for

*

*Validation that my model is built correctly

*Help with writing the code to return the awards (needs to have a return type of IQueryable).

Here is a simplified version of my model. One Award can have many teams associated with it. Additionally one team can have many awards (but I don't really care about that relationship. I only need to go from Award to Team).
public class Award
    {
        [Key]
        [ForeignKey("Teams")]
        public int AwardId { get; set; }

        //navigation property
        public virtual ICollection<AwardTeamMap> Teams{ get; set; }

    }

    public class AwardRoleMap
    {

        [Key, Column(Order = 0)]
        public int AwardId { get; set; }

        [Key, Column(Order = 1)]
        public int TeamId { get; set; }

    }

In my dbcontext, I have this:
modelBuilder.Entity<Award>()
                .HasMany(m => m.GuruTeams)
                .WithOptional()
                .HasForeignKey(a => a.AwardId);

Now, I am trying to return the awards that have TeamIds that match ints provided by a filter that the user interacts with (filter.IntValues).
When I run this, I can this run time error: Only primitive types or enumeration types are supported in this context.
I feel there should be a better way to get TeamIds, but I am struggling.
var awards = from award in baseAwardQuery
                         from AwardTeams in db.Awards.Queryable.Where(a => filter.IntValues == a.Teams.Select(x => x.TeamId)
                          && a.AwardId == award.AwardId)
                          select award;

A: I don't understand your meaning a bit I guess this is what you mean.
Input is: Collection of team id
Output expected: All award of each team id above have got
First, you got these Entity Model
public class Team
{
    [Key]
    public int Id { get; set; }
    public virtual ICollection<TeamAward> AwardOfTeam { get; set; }

}

public class TeamAward
{
    public int TeamId { get; set; }
    public int AwardId { get; set; }

    public virtual Team Team { get; set; }
    public virtual Award Award { get; set; }
}

public class Award
{
    [Key]
    public int Id { get; set; }
    public virtual ICollection<TeamAward> TeamHasAward { get; set; }

}

And then, in your function you can query like this
// I don't know what is your filter.IntValues so I guess it is array of int
int[] teamIds = new[] { 1, 3, 4 };
// This is list of all award that Team 1, Team 3 and Team 4 got
List<Award> awards = context.Teams
                     .Where(team => teamIds.Contains(team.Id))
                     .SelectMany(team =>
                                 team.AwardOfTeam.Select(awardOfTeam =>
                                                         awardOfTeam.Award)).ToList();
// Do your stuff here
// foreach (Award award in awards)

Hope this help