text:
Q: Migrate from Google App Engine Model to Pure Django System How can I rewrite this AppEngine specific code for pure Django Model system
(without google api)
class A(db.Model):
    name = db.StringProperty(multiline=True)
    description = db.TextProperty()
    isAdvanced = db.BooleanProperty()
    foos = db.ListProperty(db.Key)
    bar = db.IntegerProperty()

    def get_foos(self):
        return db.get(self.foos)

A: AFAIK, you'll have to do it manually. Thankfully though, Django can do most of the work for you.
First, make sure you have the appropriate database settings in settings.py. You can find a detailed walkthrough of database configuration here.
Once finished, run python manage.py inspectdb > models.py. It'll dump manage.py's output, which constructs the python code for the models, into models.py, which you can then add to the relevant Django application. You'll have to double check it, but it should take far less effort.
In addition, from personal experience, if it encounters any problems, it'll let you know. For example, both PostgreSQL's money and MySQL's currency fields are not recognized by Django's models, so it will emit models.TextField(), followed by # This is a guess..
EDIT: Just found this article when Googling for it:
Migrating from Google App Engine to Django
EDIT 2: I just realized I probably didn't answer your question. This is (roughly) what it would look like, though I'd still recommend you run python manage.py inspectdb > models.py.
from django.db import models

class A(models.Model):
    name = models.TextField()
    description = models.TextField()
    isAdvanced = models.BooleanField()
    foos = # Dunno, a quick Google search doesn't turn up the equivalent
    bar = models.IntegerField()

To get a the multiline attribute for name, you may want to take a look at this question from Google groups or Google it yourself.

A: Edwin's answer is a good start.
I've been using django-nonrel, instead of the basic django.
django-nonrel comes with a module called djangotoolbox, that offers a ListField wrapper for a google ListProperty.  Normal django doesn't have an equivalent.

A: As far as I know, you have to rewrite all the db associated code with hand. I am in a similar situation. :-)


text:
Q: How to create separate file ( .vb or .cs ) for each table in db using subsonic 3.0 i am using subsonic v.3 to generate my DAL layer in my ASP.NET application with VB.NET(.NET framework 3.5).
i have used the subsonic v.2 and i which it was creating a separate .cs file for each table and event each class file has on method called LoadByParam() or LoadByKey() in case if one want to load the object by passing some field value.
but in subsonic 3 when i add core file and add T4 template in my project it's generating three vb file named activrecord.vb , context.vb and struct.vb
I want to know how can i load all the table in separate file as in subsonic
how to load a database object by passing some field as a filed
i.e in subsonic 2.0 when i want to load user table with some give id i was loading it this way
new myProject.user(column-name, filed-value);
how can i achieve the same with subsonic 3.0  ??

A: If you ask me, I would add a c# class library to your project and use for your DAL, since the c# have a broader userbase and are thus more tested. VB and C# work perfectly together in a Solution
This said, the latest c# templates already create seperate files: https://github.com/subsonic/SubSonic-3.0-Templates/tree/master/ActiveRecord
I suppose nobody migrated the code to vb.net atm.
Regarding your second question (how to load an object by columnname), subsonic 3 makes heavy use of lambda expressions, so you only need to use the overload that takes an Expression(of Func(of User, Boolean))
In other words:
dim user1 as new User(Function(x) x.UserName = "Test")

or
dim user2 as User = User.SingleOrDefault(Function(x) x.UserName = "Test")

or even
dim user3 as User = (From u in User.All()
                     Where u.UserName = "Test"
                     Select u).SingleOrDefault()

the last two return a User object or Nothing.
The first always returns an object, even if the user does not exist, so you have to check
user1.IsNew() if needed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: JQuery works when pasted into console but not on page load Why does this not work on page load, but when I paste the jquery into the console on my page it works.
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Alex Cory</title>
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css">

A: Judging by how your webpage seems to be set up, I suspect you're injecting your content into the page from:

since there's no actual content in the code itself.
When this is the case, it's because when the page loads and $(document).ready() fires, $('.page-scroll a') returns null because it's not rendered into the DOM yet, to put it simply.
To solve this issue, you need to attach your event handler to an element that is going to be rendered into the page when it loads. The body tag is good for this example, and we want to listen for .page-scroll a to be clicked using jQuery's on method:
// We attach a click event listener to the body element
// and we try to track when .page-scroll a is clicked
$('body').on('click', '.page-scroll a' function(event) {
  console.log('CLICKED BUTTON! ^_^');
  event.preventDefault();
});

This works because since the event handler is attached to the body, each time something is clicked on the web page, it checks to see if .page-scroll a is clicked, rather than before you were trying to attach an event handler to an element that didn't exist yet.

A: Your anchor must be created after DOM is ready. So you should bind click to parent element, for example:
$('body').on('click', '.page-scroll a', function(e) {....});

That way, no matter when the anchor was created, whenever one clicks body and target is .page-scroll a the function will be executed.

A: From JQuery Documentation

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .bind() occurs. For more flexible event binding, see the discussion of event delegation in .on() or .delegate().

So you use JQuery.on() method
why does your code console is precisely because there is already the elemente

A: The problem is because you want to call a function while the DOM is not yet ready.
insert into the body tag
//link to the script file here

this will load your function and that particular function will run when the page is loaded.


text:
Q: How to use Google Maps API in Visual C# Forms Application? I have decided to design a desktop forms application in Visual C# 2012 which will download google map images within user specified coordinate and zoom level. Actually, the target is to create offline map as jpeg. Later I'll have to join the downloaded images also! Can anyone please help me on this issue?
Note: I will not display any web page. I just want to download the direct image from google maps as per specification on zoom level and coordinate.
Regards.

A: Have you checked GMap.NET? "Great Maps for Windows Forms and Presentation"

*

*http://www.codeproject.com/Articles/32643/GMap-NET-Great-Maps-for-Windows-Forms-and-Presenta

*http://greatmaps.codeplex.com


text:
Q: After the update of eclipse plugin, cannot deploy due to application limit of 150MB, again and again Its incredible that this issue keep apearing and google dont solve it.
You update the sdks (gwt/gae) and the eclipse plugin, and BANG!! You cannot deploy anymore.
java.io.IOException: Applications are limited to 157286400 bytes of resource files, you have 212487584.

But now I will help google to find a real final solution for this problem.
First of all, here is some people who had the same problem before:
I personally have this problem in 2011:
groups.google.com/forum/#!searchin/google-appengine/application$20size$20limit/google-appengine/Xe2nX1MYKEE/B24as7k8ubwJ

And others:
groups.google.com/forum/#!msg/nimbits/FY02Yq6lyMk/DWa5N-gzo7sJ
code.google.com/p/googleappengine/issues/detail?id=7676
comments.gmane.org/gmane.org.google.gwt/60935

The problem is not the application size. Its is some bug on eclipse plugin.
I know that cause this time I recovered the backup of my eclipse before the sdks and plugin updates. And I could deploy normally (same project with no alteration). Than I updated just the gwt sdk and yes, I could deploy. Than I updated the appengine sdk and yes, I could deploy. But if I go to eclipse plugin than I CANNOT.
Here is a possible cause of the problem. I founded the snipet of code of the eclipse plugin that produces the message on this link:
http://code.google.com/p/googleappengine/source/browse/trunk/java/src/main/com/google/appengine/tools/admin/AppVersionUpload.java?spec=svn450&r=450
if (resourceTotal > resourceLimits.maxTotalFileSize()) {
   throw new LocalIOException("Applications are limited to "
  + resourceLimits.maxTotalFileSize() + " bytes of resource files, "
  + "you have " + resourceTotal + ".");
}

On same page you can see that the variable resourceTotal is the sum of size of files in a directory represented a variable called basepath, which is initiated by this method:
private File getBasepath() {
    File path = app.getStagingDir();
    if (path == null) {
        path = new File(app.getPath());
    }
}

I think the problem is here. It uses the staging directory (that temporary directory created before the update), but if for some reason it returns null, it uses the app path that of course is much bigger and is not what is uploaded to gae. I think it should gives a error instead of this treatment that can end a limit quota.
Hope this can help someone in the future. I just lost 2 days of work cause of this bug. I have both versions of eclipse here with the problem and without it, if someone needs aditional info, and hope google correct this, cause I will need to upgrade the plugin some day.
[],
Rodrigo.

A: I had this problem once. And the cause was very different: I was logged in under a different Google account. Once I switched to the right account, the deployment went smoothly as usual.

A: Just had this problem.  For me it was something different again.
Frustratingly the cause of error bears absolutely no relation to the error message:

So, it is nothing to do with app size at all, but that I'd simply made a typo on my application name during the deploy:

easy to fix at least once I'd worked that out!


text:
Q: TFS State Changed Date not Working We're using the Scrum 1.0 template for TFS. We're trying to do a work item query and I've noticed the State Changed Date for all of our items is empty. If I do a search for Changed Date, that works fine, but doesn't produce the desired results...
Why would this be the case?

A: *

*Export the WIT (Task, Bug or Impediment) using the Process Editor or witadmin to a file.

*Add the following block within the  element:
<FIELD refname="Microsoft.VSTS.Common.StateChangeDate" name="State Change Date" type="DateTime">
   <WHENCHANGED field="System.State">
     <SERVERDEFAULT from="clock" />
   </WHENCHANGED>
   <WHENNOTCHANGED field="System.State">
    <READONLY />
   </WHENNOTCHANGED>
 <HELPTEXT>Date and time that the value of the State field changed. </HELPTEXT>
</FIELD>

*Save the file, and import it back to TFS using the Process Editor or witadmin..

*Click the Refresh button on Team Explorer.

*From this point forward changing the state of a work item will be queryable.


text:
Q: C# Class Add ID from one class to another i have one class named with Animal, with Name, Type, Gender, and i have another class named with AnimalList, i need to know how can i add Animals to my AnimalList, this is my class animal(im in console application):
Filename Animal.cs
class Animal
{
  public string Name {get; set;}
  public string Type {get; set;}
  public string Gender {get; set;}

  public Person(string name, string type, string gender)
  {
       Name = name;
       Type = type;
       Gender = gender;
  }
}

And my class AnimalList:
FilenameAnimalList.cs
class AnimalList: List<Animal>
{
     what should i do to add Animals to this list
}

shouldn't be better  like this?
public new void Add(Animal value)
{
}

A: Why do you have the constructor for Person in your Animal class?
Do like this:
var animals = new AnimalList();
var animal = new Animal();
animals.Add(animal);

You have to make your Animal class public:
public class Animal
{
}

A: Instantiate your AnimalList class somewhere(for example in main method) and then add the instances of an Animal class.
for example:
var animals = new AnimalList();

animals.Add(new Animal() {
   Name = "",
   Type = "",
   Gender = ""});

A: First of all make your class Public
And do this:
 AnimalList animalList = new AnimalList();
            Animal animal = new Animal();
            animal.Name = "x";
            animal.Type = "Y";
            animal.Gender = "M/F";
            animalList.add(animal);


text:
Q: Read and write avro files by inferring schema using Python SDK in Google Cloud Dataflow - Apache Beam Problem: I am trying to create a cloud dataflow pipeline that reads Avro files from Google Cloud Storage using Python SDK, does some processing and writes back an Avro file on Google Cloud Storage. After looking into some examples provided on Apache Beam website I tried running the following code. I used ReadFromAvro and WriteToAvro functions. The thing I am trying to achieve is just read an Avro file and write the same Avro file using Dataflow but It gives me the following warning and does not output an avro file.
Warning/Error:
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/apache_beam/io/gcp/gcsio.py:121: DeprecationWarning: object() takes no parameters
  super(GcsIO, cls).__new__(cls, storage_client))
INFO:root:Starting the size estimation of the input
INFO:oauth2client.transport:Attempting refresh to obtain initial access_token
INFO:oauth2client.client:Refreshing access_token
INFO:root:Finished the size estimation of the input at 1 files. Estimation took 0.31790304184 seconds
Traceback (most recent call last):
  File "/Users/USER/PycharmProjects/GCP-gcs_to_bq/gcs-bq.py", line 52, in <module>
    run()
  File "/Users/USER/PycharmProjects/GCP-gcs_to_bq/gcs-bq.py", line 47, in run
    records | WriteToAvro(known_args.output)
TypeError: __init__() takes at least 3 arguments (2 given)

Code:
from __future__ import absolute_import

import argparse
import logging

import apache_beam as beam
from apache_beam.io import ReadFromAvro
from apache_beam.io import WriteToAvro
from apache_beam.options.pipeline_options import PipelineOptions
from apache_beam.options.pipeline_options import SetupOptions

def run(argv=None):
    parser = argparse.ArgumentParser()
    parser.add_argument('--input',
                        dest='input',
                        default='gs://BUCKET/000000_0.avro',
                        help='Input file to process.')
    parser.add_argument('--output',
                        dest='output',
                        default='gs://BUCKET/',
                        #required=True,
                        help='Output file to write results to.')
    known_args, pipeline_args = parser.parse_known_args(argv)
    pipeline_args.extend([
        # CHANGE 2/5: (OPTIONAL) Change this to DataflowRunner to
        # run your pipeline on the Google Cloud Dataflow Service.
        '--runner=DataflowRunner',
        # CHANGE 3/5: Your project ID is required in order to run your pipeline on
        # the Google Cloud Dataflow Service.
        '--project=PROJECT_NAME',
        # CHANGE 4/5: Your Google Cloud Storage path is required for staging local
        # files.
        '--staging_location=gs://BUCKET/staging',
        # CHANGE 5/5: Your Google Cloud Storage path is required for temporary
        # files.
        '--temp_location=gs://BUCKET/temp',
        '--job_name=parse-avro',
    ])
    pipeline_options = PipelineOptions(pipeline_args)
    p = beam.Pipeline(options=pipeline_options)

    # Read the avro file[pattern] into a PCollection.
    records = p | ReadFromAvro(known_args.input)
    records | WriteToAvro(known_args.output)

if __name__ == '__main__':
    logging.getLogger().setLevel(logging.INFO)
    run()

Edit:
I tried adding schema to WriteToAvro function but it now gives me the following error:
Error:
/usr/local/bin/python /Users/USER/PycharmProjects/GCP-gcs_to_bq/gcs-bq.py
No handlers could be found for logger "oauth2client.contrib.multistore_file"

/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/apache_beam/coders/typecoders.py:135: UserWarning: Using fallback coder for typehint: <type 'NoneType'>.
  warnings.warn('Using fallback coder for typehint: %r.' % typehint)

Schema:
{"fields": [{"default": null, "type": ["null", {"logicalType": "timestamp-millis", "type": "long"}], "name": "_col0"}, {"default": null, "type": ["null", {"logicalType": "char", "type": "string", "maxLength": 1}], "name": "_col1"}, {"default": null, "type": ["null", {"logicalType": "char", "type": "string", "maxLength": 1}], "name": "_col2"}, {"default": null, "type": ["null", {"logicalType": "char", "type": "string", "maxLength": 1}], "name": "_col3"}, {"default": null, "type": ["null", "long"], "name": "_col4"}, {"default": null, "type": ["null", {"logicalType": "char", "type": "string", "maxLength": 1}], "name": "_col5"}, {"default": null, "type": ["null", {"logicalType": "varchar", "type": "string", "maxLength": 10}], "name": "_col6"}, {"default": null, "type": ["null", "double"], "name": "_col7"}, {"default": null, "type": ["null", "long"], "name": "_col8"}, {"default": null, "type": ["null", {"logicalType": "varchar", "type": "string", "maxLength": 6}], "name": "_col9"}, {"default": null, "type": ["null", {"logicalType": "varchar", "type": "string", "maxLength": 6}], "name": "_col10"}], "type": "record", "name": "baseRecord"}

Code:
pipeline_options = PipelineOptions(pipeline_args)
p = beam.Pipeline(options=pipeline_options)

schema = avro.schema.parse(open("avro.avsc", "rb").read())

# Read the avro file[pattern] into a PCollection.
records = p | ReadFromAvro(known_args.input)
records | WriteToAvro(known_args.output, schema=schema)

A: The problem was that the data pipeline was actually not getting executed. I managed to fix it. The solution is you need to run the beam pipeline in either one of the following 2 options:
Option 1:
p = beam.Pipeline(options=pipeline_options)

schema = avro.schema.parse(open("avro.avsc", "rb").read())

records = p | 'Read from Avro' >> ReadFromAvro(known_args.input)

# Write the file
records | 'Write to Avro' >> WriteToAvro(known_args.output, schema=schema, file_name_suffix='.avro')

# Run the pipeline
result = p.run()
result.wait_until_finish()

Option 2:
Use python with keyword to execute the pipeline:
schema = avro.schema.parse(open("avro.avsc", "rb").read())

with beam.Pipeline(options=pipeline_options) as p:
    records = p | ReadFromAvro(known_args.input)
    records | WriteToAvro(known_args.output, schema=schema, file_name_suffix='.avro')

A: The error says that your code didn't pass all the required arguments to the constructor of WriteToAvro() transform - and indeed it requires at least 2 arguments (filename prefix and schema), but this code passes only 1 (filename prefix).
WriteToAvro currently requires the schema: it is not an optional parameter and there is no workaround to avoid specifying it. The reason for that is that Avro files in general require knowing a schema in advance before creating the file, so WriteToAvro requires knowing the schema too.
Moreover we can not unambiguously infer the schema from the collection returned by ReadFromAvro: imagine that a user passes as --input a filepattern that matches Avro files with several different schemas - which of those schemas would WriteToAvro then have to use?


text:
Q: Algorthm to make a tree from list of paths The task is to make a tree from list of sorted paths. Each node is a filesystem object(file or folder).
Currently I'm using this one (pseudo code):
foreach(string path in pathList)
{
    INode currentNode = rootNode;
    StringCollection pathTokens = path.split(pathSplitter);
    foreach(pathToken in pathTokens)
    {
        if (currentNode.Children.contains(pathToken ))
        {
            currentNode = currentNode.Children.find(pathToken);
        }
        else
        {
            currentNode  = currentNode.Children.Add(pathToken);
        }
    }
 }

pathSplitter is a \ for win and / for *nix.
Is there a more efficient way to solve that task?

A: They key quality of your input data is that the list of paths is sorted. Hence you can work with common prefixes between the current and previous nodes quite efficiently. What you can do is maitain the last trace through the tree data structure from its root the leaf folder node. Then for the current  path you just traverse the previous trace (i.e. process the current path relative to the last path) instead of finding the right position in the tree again and again.
When comparing the last and current path, three cases may happen:
1) Same paths
\path\to\folder\file1.txt
\path\to\folder\file2.txt

The trace remains, node for file2.txt is added.
2) New path is a subpath
\path\to\folder\file1.txt
\path\to\folder\subfolder\file2.txt

Nodes for subfolder and file2.txt are added.
3) New path is different
\path\to\folder\file1.txt
\path\to\another_folder\subfolder\file2.txt

First you need to back-track the trace to represent \path\to\. Then, nodes for another_path, subfolder and file2.txt are added. (Note that the another_folder\subfolder\ portion may be missing completely — I hope it's clear.)
Depending on the overall characteristics and volume of data such algoritm may perform faster. You could play with some formal Big-O estimations, but I think it would be faster to just test it.

A: The algorithm seems optimal to me; if I am not mistaken, the sorting of paths implies that the nodes will be generated in a depth-first sequence with respect to the tree on which they originate. This means that no unneccessary backtracing in the graph is performed. Furthermore, the algorithm is linear in the number of paths in the input and every path is processin in time linear in its length, so the overall running time is linear in the size of the input. Complexity-wise, this means that the algorithm is optimal since it is impossible to read all paths with lower runtime complexity.


text:
Q: Laravel vite won't process custom css I am trying to inject my custom css in built css file but it does not process resources/css/app.css file
vite.config.js
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';

export default defineConfig({
    plugins: [
        laravel({
            input: [
                'resources/css/app.css',
                'resources/sass/app.scss',
                'resources/js/app.js',
            ],
            refresh: true,
        }),
    ],
    resolve: {
        alias: {
            '$': 'jQuery'
        },
    },
});

resources/css/app.css
h2.swal2-title {
    font-size: 1.2em !important;
}

This css does not add to generate css file by npm run build
Any idea?


text:
Q: Will the following sentence still be grammatical if I remove the "of them"?
I explored every inch of the beach: its rocks, its reefs, its shoreline,
  all (of them) coated with green moss.

Can I omit that "of them"? Why or why not?

A: Both examples are grammatically correct but omitting of them changes the meaning: all would then apply to just the shoreline (i.e. all the shoreline coated with green).
Consider if the order of words were changed, to make it more obvious:
I explored every inch of the beach: its rocks, its shoreline, all coated with green, its reefs.


text:
Q: flask container not responding while standalone application works python
from flask import Flask
import socket
app = Flask(__name__)

@app.route("/")
def hello_world():
    return 'Hello World!'

if __name__ == "__main__":
    app.run(host='0.0.0.0')

when I run this using python app.py, I am able to access it on web browser with http://192.168.56.1:5000/
Now create a container with docker
# Format: FROM    repository[:version]
FROM ubuntu:latest
RUN apt-get update -y
RUN apt-get install -y python-pip python-dev build-essential
COPY . /app
WORKDIR /app
RUN pip install -r requirements.txt
ENTRYPOINT ["python"]
CMD ["app.py", "--host", "0.0.0.0"]

build and run it.
    docker build -t helloworld:latest .
    docker run -d -p 5000:5000 helloworld
docker ps -a shows image is up from 7 mins. but when I hit url on web browser, it doesn't respond.
What can be wrong here? any suggestions?


text:
Q: expected Hash (got Array) for param 'samples' I have been following Railscasts episodes of Nested forms and complex forms. During the time of creating multiple model in a single form I was able to edit, update, delete and create records for sample models that were nested in the Batch model.
I have been breaking my head from a long time and tried searching around as well but could not get any right solution for solving this problem.
my development log file gives me the following error.
ERROR MESSAGE:
Status: 500 Internal Server Error
  expected Hash (got Array) for param `samples'

in my controller I have the update action like this
def update
     @batch = Batch.find(params[:id])

     respond_to do |format|
       if @batch.update_attributes(params[:batch])
         flash[:notice] = 'Successfully updated Batch.'
         format.html { redirect_to(@batch) }
         format.xml  { head :ok }
       else
         format.html { render :action => "edit" }
         format.xml  { render :xml => @batch.errors, :status => :unprocessable_entity }
       end
     end
   end

my view is something like this:
<%= form_for @batch do |f| %>
......
<%= f.fields_for :samples do |s_form| %>
.... s_form things
<% end %>
<% end %>

my model contains the same stuff :
has_many :samples, :dependent => :destroy

  accepts_nested_attributes_for :samples, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true

All suggestions are appreciated.

A: I had the same problem, and just fixed it.
Check the headers of your request.  I mine I saw:
weight[2][name]:Tests
weight[2][value]:75
weight[1][name]:Quizzes
weight[1][value]:25
weight[][name]:Foo
weight[][value]:

It was the last two which caused the issue.  In my case I had to give this weight an ID to get rid of the error.

A: for others who met the same problem:
this error is caused when you have two fields in your form like:
video: 'some string'
video['url']:  'some url'

then rails will crash with the error: expected Hash (got String) for param
the solution is quite simple: change 'video' to something else. e.g.:
video_origin_url: 'some string'
video['url']: 'some url'

A: I also got this error Invalid request parameters: expected Hash (got Array) for param 'cell'.
In my case, I misformed the field name like
f.text_field :name, name: 'cell[name][]'

this was causing the error. Now I did the following and the error is gone:-
f.text_field :name, name: 'cell[][name]'

in this solution I was actually trying to get data in array format.

A: I had this problem, when the user typed the params himself in the request like:
https://example.com/page?samples[]=1&samples[test]=2
Debugging the code, I got down to a Rack::QueryParser.parse_nested_query method in the rack gem:
# parse_nested_query expands a query string into structural types. Supported
# types are Arrays, Hashes and basic value types. It is possible to supply
# query strings with parameters of conflicting types, in this case a
# ParameterTypeError is raised. Users are encouraged to return a 400 in this
# case.
def parse_nested_query(qs, d = nil)
  params = make_params

  unless qs.nil? || qs.empty?
    (qs || '').split(d ? (COMMON_SEP[d] || /[#{d}] */n) : DEFAULT_SEP).each do |p|
      k, v = p.split('=', 2).map! { |s| unescape(s) }

      normalize_params(params, k, v, param_depth_limit)
    end
  end

  return params.to_h
rescue ArgumentError => e
  raise InvalidParameterError, e.message, e.backtrace
end

From the docstring:

It is possible to supply query strings with parameters of conflicting types, in this case a ParameterTypeError is raised. Users are encouraged to return a 400 in this case.

I found few solutions here Rails ActionController::BadRequest causes 500 Server Error on production server


text:
Q: "'Undefined is not an object (evaluating 'row[0].val')" error in react native This is the PayScrn.js code. When Im pressing the 'Add' button I receive "Undefined is not an object (evaluating 'row[0].val')" error present in expo. I cant understand how it happen.
import React, { useState } from 'react';
import { View,Button} from 'react-native';

const PayScrn = props => {
    const [row, addRow] = useState([]);
    const addItem = () => {
        addRow([...row,{ val: '20', type: 'Credit card' }]);
        alert(row[0].val)
    };
    return (
        <View>
             <Button onPress={addItem} title='Add' />
        </View>
    );
};

A: addRow is asynchronous. To view the updated result use useEffect()
useEffect(() => { console.log(row)}, row)

Every time row is updated, useEffect will be called
useEffect


text:
Q: xdebug not talking to Eclipse debugger I'm trying to get Eclipse to talk to xdebug. From the xdebug log, it seems that xdebug is working correctly (i.e.: it's sending it's <init> and <response> messages), but Eclipse is not sending anything to xdebug (i.e.: no feature_set, feature_get, etc. commands like Netbeans).

Here's my setup:

*

*Mac OS/X 10.7.5

*Eclipse 4.2.1 "Juno"

*

*PHP Development Tools (PDT) SDK Feature 3.1.1.201209101312

*(Netbeans 7.1.2)

*MAMP 2.1.1 running:

*

*apache 2.2.22

*PHP 5.4.4

*

*the PHP executable being run is /Applications/MAMP/bin/php/php5.4.4/bin/php

*the PHP config file being used is /Applications/MAMP/bin/php/php5.4.4/conf/php.ini

*xdebug 2.2.0

The relevant lines from my php.ini are:
[xdebug]
zend_extension = "/Applications/MAMP/bin/php/php5.4.4/lib/php/extensions/no-debug-non-zts-20100525/xdebug.so"
xdebug.default_enable = on
xdebug.remote_enable = on
xdebug.remote_host = localhost
xdebug.remote_port = 9000
xdebug.remote_autostart = on
xdebug.remote_handler = "dbgp"
xdebug.remote_autostart = on
xdebug.remote_mode = "req"
xdebug.remote_connect_back = on
xdebug.remote_log = /tmp/xdebuglog.log

I can get Netbeans to connect to xdebug on port 9000 with session ID netbeans-xdebug with no problem. Note that when I start debugging, it opens a new window in my web browser with ?XDEBUG_SESSION_START=netbeans-xdebug appended to the URL of the PHP file I'm running.
Here is a snippet from the xdebug log when Netbeans tries to connect:
Log opened at 2013-01-18 18:42:52
I: Checking remote connect back address.
I: Remote address found, connecting to ::1:9000.
I: Connected to client. :-)
-> <init xmlns="urn:debugger_protocol_v1" xmlns:xdebug="http://xdebug.org/dbgp/xdebug" fileuri="file:///Applications/MAMP/htdocs/projectname/index.php" language="PHP" protocol_version="1.0" appid="647" idekey="netbeans-xdebug"><engine version="2.2.0"><![CDATA[Xdebug]]></engine><author><![CDATA[Derick Rethans]]></author><url><![CDATA[http://xdebug.org]]></url><copyright><![CDATA[Copyright (c) 2002-2012 by Derick Rethans]]></copyright></init>

<- feature_set -i 0 -n show_hidden -v 1
-> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="http://xdebug.org/dbgp/xdebug" command="feature_set" transaction_id="0" feature="show_hidden" success="1"></response>

<- feature_set -i 1 -n max_depth -v 3
-> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="http://xdebug.org/dbgp/xdebug" command="feature_set" transaction_id="1" feature="max_depth" success="1"></response>

<- feature_set -i 2 -n max_children -v 30
-> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="http://xdebug.org/dbgp/xdebug" command="feature_set" transaction_id="2" feature="max_children" success="1"></response>

<- feature_get -i 3 -n max_data
-> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="http://xdebug.org/dbgp/xdebug" command="feature_get" transaction_id="3" feature_name="max_data" supported="1"><![CDATA[1024]]></response>

<- stdout -i 4 -c 1
-> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="http://xdebug.org/dbgp/xdebug" command="stdout" transaction_id="4" success="1"></response>

<- step_into -i 5
-> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="http://xdebug.org/dbgp/xdebug" command="step_into" transaction_id="5" status="break" reason="ok"><xdebug:message filename="file:///Applications/MAMP/htdocs/projectname/index.php" lineno="17"></xdebug:message></response>

<- stack_get -i 6
-> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="http://xdebug.org/dbgp/xdebug" command="stack_get" transaction_id="6"><stack where="{main}" level="0" type="file" filename="file:///Applications/MAMP/htdocs/projectname/index.php" lineno="17"></stack></response>

…

-> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="http://xdebug.org/dbgp/xdebug" command="feature_get" transaction_id="14" status="stopping" reason="ok"></response>

Log closed at 2013-01-18 18:47:21

In Eclipse…
I created a new PHP Project in the workspace, using the default PHP settings, and created separate folders for source files and public resources. I changed nothing in the PHP Include Path step, but in the PHP Build Path, I clicked Link Source and linked /Applications/MAMP/htdocs/projectname with a projectname folder in my project.
I then set Eclipse preferences as follows:

*

*In General -> Web Browser, I've set it to use an external web browser (Firefox).

*In PHP -> Debug -> Installed Debuggers, I've checked that XDebug is in the list, is using port 9000, JIT remote sessions are off, and I used these instructions to ensure it uses the idekey mparker17.

*In PHP -> Debug, I:

*

*Set the PHP Debugger to "XDebug"

*Set the PHP Server to the correct base URL (http://projectname.local) local web root (/Applications/MAMP/htdocs/projectname) and path mapping between the server and my workspace.

*Set the PHP Executable to the correct executable path (/Applications/MAMP/bin/php/php5.4.4/bin/php), PHP ini file (/Applications/MAMP/bin/php/php5.4.4/conf/php.ini), the SAPI type to "CLI" and the PHP debugger to "XDebug".

*Checked the Enable CLI Debug checkbox.

*Checked the Break at first line checkbox.

In my debug configurations, I added a PHP Web Application and set it's preferences as follows:

*

*In the Server tab I set the PHP server created above, set the file correctly, and set the URL correctly.

Here is a snippet from the xdebug log when Eclipse tries to connect:
Log opened at 2013-01-18 17:33:48
I: Checking remote connect back address.
I: Remote address found, connecting to ::1:9000.
I: Connected to client. :-)
-> <init xmlns="urn:debugger_protocol_v1" xmlns:xdebug="http://xdebug.org/dbgp/xdebug" fileuri="file:///Applications/MAMP/htdocs/projectname/index.php" language="PHP" protocol_version="1.0" appid="703" idekey="mparker17"><engine version="2.2.0"><![CDATA[Xdebug]]></engine><author><![CDATA[Derick Rethans]]></author><url><![CDATA[http://xdebug.org]]></url><copyright><![CDATA[Copyright (c) 2002-2012 by Derick Rethans]]></copyright></init>

-> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="http://xdebug.org/dbgp/xdebug" status="stopping" reason="ok"></response>

Log closed at 2013-01-18 17:33:49

This seems to indicate to me that Eclipse isn't talking to xdebug, but I'm stumped as to why that would be happening.

A:
JIT remote sessions are off

Turn it on.


text:
Q: Is one C# thread one CPU thread? I am wondering if one C# thread uses up one CPU thread as example:
If you have a CPU with eight threads, for example: 4790k and you start two new C# threads, do you lose two threads? Like 8 - 2 = 6?

A: Threads are not cores. In the case you gave, your computer has 8 cores (4 physical and 4 logical) that can handle threads.
Computers handle hundreds of threads at once and switch in-between them extremely fast. If you create a Thread class in your C# application, it will create a new thread that will execute on any of the cores on your CPU. The more cores that you have, the faster your computer runs because it can handle more threads at once (there are other factors at play in the speed of the computer than just how many cores you have).

A: The virtual machine (CLR) is free to do whatever it wants if I recall correctly. There are implementations called green threads for example, that don't necessarily map managed threads to native threads. However, of course, in .NET on a desktop x86, the implementation we know try hard to really map to system threads.
Now this is one layer, but it still says nothing about the CPU. The OS scheduler will let a hardware thread (virtualized because of hyper threading) execute a native thread when it decides it's OK.
There is such a thing known as overcommit which speaks of when too many native threads wants to run (are present in the OS's scheduler ready queue), but the CPU have only that many threads to use, so some remains waiting, until their weight which is an internal measure of the OS scheduler decides that it's their turn.
You can check this document for more information: CFS Scheduler
Then as for the CLR, maybe this question: How does a managed thread work and exist on a native platform?
Indeed in the discussion the useful MSDN page
Managed and unmanaged threading in Windows
explains that:

An operating-system ThreadId has no fixed relationship to a managed
thread, because an unmanaged host can control the relationship between
managed and unmanaged threads. Specifically, a sophisticated host can
use the Fiber API to schedule many managed threads against the same
operating system thread, or to move a managed thread among different
operating system threads.

For very interesting reasons. One of course is the freedom of virtual machine implementation. But another one is the freedom of passing between the native/managed barrier with lots of flexibility as explained on this page. Notably the fact that native threads can enter to managed application domains backwards, and see the virtual machine allocating a managed thread object automatically. This management is maintained using thread id hashes. Crazy stuff :)
Actually, we can see on page CLR Inside Out that the CLR has configurable thread API mapping. So quite flexible, and that proves indeed that you cannot say for sure that one C# thread == one native thread.

A: As JRLambert already touched on, you can have many threads running on the same core.
When you spawn new threads in your .NET application, you are not actually multi-"tasking" at all. What's happening is time-slicing. Your CPU will constantly switch between the different threads letting them seem like they're working in parallel. However, a core can only work on a single thread at any given time.
When implementing the Task Parallel Library (TPL) for instance, and your machine has multiple cores, you'll see that the cores get more equally distributed work loads, than when simply spawning new threads. Microsoft really did some fantastic work with TPL to simplify a multi-thread asynchronous environment without having to do heavy work with the Thread Pool and Synchronization primitives as we may have had to in the past.
Have a look at this YouTube video. He describes time-slicing vs. multi-tasking quite well.
If you're not familiar with TPL yet, Sacha Barber has a fantastic series on Code Project.

A: Just want to share an experience as an enthusiastic programmer. I hope it may help someone.
I was developing a code, defining a certain amount of tasks which were planned to start in a fraction of a second interval. however, I noticed that all tasks were run in a group of 8! I was wondering whether the number of CPU thread imposed a limitation here? Actually, I expected all tasks, say 40, should've started exactly in a queue, one by one, according to time interval I set in the code. My old laptop had a CPU corei5, with 4 cores and 8 threats. the same number of 8 made me so confused so that I wanted to hit my head on a wall :)
Task<object>[] tasks = new Task<object>[maxLoop];
        String[] timeStamps = new String[maxLoop];

        for (int i = 0; i < maxLoop; i++)
        {
            tasks[i] = SubmitRequest();
            timeStamps[i] = DateTime.Now.TimeOfDay.ToString();
            await Task.Delay(timeInterval);
        }
        await Task.WhenAll(tasks);

After reading the Microsoft documents, I reached to this page:ThreadPool.SetMinThreads(Int32, Int32) Method
According to the page, "By default, the minimum number of threads is set to the number of processors on a system. You can use the SetMinThreads method to increase the minimum number of threads."
then I added this to the code:
ThreadPool.SetMinThreads(maxLoop, maxLoop);

and the problem was resolved.
Just notice unnecessarily increasing the minimum threads may decrease performance. If too many tasks start at the same time, it may impact the overall speed of the task. So normally, it was advised to leave it to the thread pool to decide with its own algorithm for allocating threads.


text:
Q: Adding NSAllowsArbitraryLoads to plist Still Not Working I have a PHP file on another machine that creates JSON, and wanted to grab it from iOS application.
I tried to use the IP address to connect from the iOS application with NSURL
NSURL *url = [NSURL URLWithString:@"http://192.168.xx.xxx/JSON/JSONtoIOS.php"];
NSData *data = [NSData dataWithContentsOfURL:url options:NSDataReadingUncached error:&error];

Then, I added below code in info.plist file:
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

However, I am still getting a same error message:

Transport security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.

The URL opens fine on a web browser, but having a problem with NSData returning nil.
Can anyone help me on this issue?
EDIT: Using NSURLSession in (void)viewDidLoad
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:@"http://192.168.xx.xxx/JSON/JSONtoIOS.php"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSLog(@"%@", json);
}];
[dataTask resume];

A: First, it should be Info.plist.  The filesystem is case-sensitive on iOS.  Just to pick nits—I doubt this is your problem.  :-)
Second, make sure you added this in the right place in the Info.plist.  It must be at the top level.
Third, if this app contains any app extensions, frameworks, or anything else that might contain an Info.plist file, make sure you're editing the right Info.plist file.
Fourth, make sure you rebuilt your app afterwards, and that you're really running the rebuilt copy.
Fifth, if that doesn't help, enable CFNetwork diagnostic logging, as described in QA1887.

A: Try this,
NSData *postData = [someStringToPost dataUsingEncoding:NSUTF8StringEncoding];

NSURL *url = [NSURL URLWithString:someURLString];

I think thats where the problem is.
Hope this helps.

A: The problem is this line:
NSData *data = [NSData dataWithContentsOfURL:url options:NSDataReadingUncached error:&error];

That's not how you do networking! It's a misuse of dataWithContentsOfURL (it's for opening local file URLs), plus it's synchronous so even if you were networking, you'd be doing a bad thing.
Use NSURLSession to retrieve the data through a data task. Now your NSAppTransportSecurity settings will be obeyed (plus you'll have much better info about what's going on as the networking proceeds).


text:
Q: Issues in getting $PWD in shell script I am calling a system call from my linux application.
/* Some file.c */
file.c is embedded in an executable called file.elf. this file.elf is present in directory
/home/ubuntu/file.elf
when i execute the file.elf the echo $BB_PATH prints the executable directory path. i am expecting the directory path to be the path where the script has been placed. i.e
/home/ubuntu/Desktop/BIN/BB/Chk_File.sh
How can this be acheived ?
if(!(system("ls /home/ubuntu/Desktop/BIN/BB")))
    {
    /* Test Path : remove after testing */
    dw_flag = system("/home/ubuntu/Desktop/BIN/BB/Chk_File.sh");//Call to execute Script
    dw_flag = WEXITSTATUS(dw_flag);
    }

this in turns call the file CHK_File.sh
ret_val=0

BB_PATH=$(pwd)

echo $BB_PATH

if [ ! -f ACTION_TAG.txt ]
then
  echo " ACTION_TAG NOT PRESENT "
else

ret_val=1
fi

echo $ret_val
exit $ret_val

A: You can use dirname to get the directory of the shell script.
echo `dirname $0`

A: Adding this below lines in script helped me
if [ -L $0 ] ; then
    DIR=$(dirname $(readlink -f $0)) ;
else
    DIR=$(dirname $0) ;
fi ;

echo $DIR

Now we dont need to worry from which directory the script is called !! Great !!


text:
Q: Excel VBA populates one set of cells from Textstream but ignores the next 22 sets. Tried everything I can think of Trying to populate some cells from a TSV file. I can find no reason why this doesn't work. "Break on all errors" is set - it throws no errors. The array is perfectly populated from the textstream. The guard clauses work as intended. The column offset variable incrementing and resulting address are correct. The cells are not locked and sheet protection is not enabled anyway. And it works fine for the very first set of numbers/text/date. But for the remaining 22 sets it does nothing. I've tried the .Range("A1") and .MergedArea devices after the .Offset(...). Office365 Pro. I'm stumped.
Sub chartTextData(ByVal pathToData As String, dateEarliest As Date, Optional ByVal strFile As String)

    On Error GoTo LoopExit
                            Debug.Print Now() & " chartTextData BEGIN"
    Application.EnableEvents = False
    Application.Calculation = xlCalculationManual

    Dim fso As FileSystemObject
    Set fso = New FileSystemObject
    Dim TxtStream As textStream
    Dim linebuffer
    Dim myArray
    Dim cellAnchor As Range
    Dim i As Long
    Debug.Assert i = 0

    Set cellAnchor = ActiveSheet.Range("D39")   '38 on some

         Set TxtStream = fso.OpenTextFile(pathToData & strFile, ForReading, False, TristateUseDefault)
Do While Not TxtStream.AtEndOfStream

    linebuffer = TxtStream.ReadLine
    '  0     1     2        3            4        5   6 7
    '33.19,$F$38,good,No Need to Act,11/20/2014,2100,DB,2
    myArray = Split(linebuffer, vbTab, , vbTextCompare)
    'header row, skip it
    If myArray(1) Like "*DATE*" Then GoTo JumpHereToBypassOlderThanDateEarliest
    If myArray(1) < dateEarliest Then GoTo JumpHereToBypassOlderThanDateEarliest

    'Set cellAnchor = ActiveSheet.Range(myArray(1))  'eg, "$D$39"
    cellAnchor.Offset(0, i).Value2 = CDbl(myArray(0))  'test value
    cellAnchor.Offset(3, i).Value2 = CDate(myArray(1))  'Date
    cellAnchor.Offset(2, i).Value2 = myArray(2)  'time
    cellAnchor.Offset(4, i).Value2 = myArray(3)  'Tech
                                'Debug.Print myArray(0)
    i = i + 2                   'merged cells, 2 per
                                'Debug.Print i & " <--i"
    If i >= 46 Then GoTo LoopExit

JumpHereToBypassOlderThanDateEarliest:
Loop

LoopExit:
    TxtStream.Close
    Set TxtStream = Nothing
    Set fso = Nothing
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.Calculate
            Debug.Print Now() & " chartTextData END"
End Sub

A: This works, and I don't know why. Not using i for column-offset, Activating top cell of each vertical range to be populated, and re-Setting cellAnchor to it.
Sub chartTextData(ByVal pathToData As String, dateEarliest As Date, Optional ByVal strFile As String)

    On Error GoTo LoopExit
                            Debug.Print Now() & " chartTextData BEGIN"
    Application.EnableEvents = False
    Application.Calculation = xlCalculationManual

    Dim fso As FileSystemObject
    Set fso = New FileSystemObject
    Dim TxtStream As textStream
    Dim linebuffer
    Dim myArray
    Dim cellAnchor As Range
    Dim i As Long

    Set cellAnchor = ActiveSheet.Range("D39")   '38 on some
        cellAnchor.Activate

         Set TxtStream = fso.OpenTextFile(pathToData & strFile, ForReading, False, TristateUseDefault)
Do While Not TxtStream.AtEndOfStream

    linebuffer = TxtStream.ReadLine
    '  0     1     2        3            4        5   6 7
    '33.19,$F$38,good,No Need to Act,11/20/2014,2100,DB,2
    myArray = Split(linebuffer, vbTab, , vbTextCompare)
    'header row, skip it
    If myArray(1) Like "*DATE*" Then GoTo JumpHereToBypassOlderThanDateEarliest
    If myArray(1) < dateEarliest Then GoTo JumpHereToBypassOlderThanDateEarliest

    cellAnchor.Offset(0, 0).Value2 = CDbl(myArray(0))  'test value
    cellAnchor.Offset(3, 0).Value2 = CDate(myArray(1))  'Date
    cellAnchor.Offset(2, 0).Value2 = myArray(2)  'time
    cellAnchor.Offset(4, 0).Value2 = myArray(3)  'Tech
                                'Debug.Print myArray(0)
    i = i + 2                   'merged cells, 2 per

        cellAnchor.Offset(0, 2).Activate
    Set cellAnchor = ActiveCell

    If i >= 46 Then GoTo LoopExit

JumpHereToBypassOlderThanDateEarliest:
Loop

LoopExit:
    TxtStream.Close
    Set TxtStream = Nothing
    Set fso = Nothing
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.Calculate
            Debug.Print Now() & " chartTextData END"
End Sub
```**


text:
Q: Clear multi divs with jquery Quick question. If i am trying to clear multiple divs with the same class all at once is there a jQuery short cut to doing this? I tried $('.clearit').empty(); and that does not seem to work at all (none on the divs with that class are being cleared). Could I be doing this wrong or does this just not work? Let me know, I tried $('.clearit').html('');. Also I have this along with other code that runs after it in jquery and everything else runs as it should. I debugged the code and it seems to run the function and move on with no errors but the div content is not cleared. Here is a sample of the divs:

Loading the player ...

Loading the player ...

Loading the player ...

and here is the code for one of the handlers. Please note everything in there works except for the $('.clearit').html('');.
$('.thumbNav li a').click(function(){
    $('.clearit').html('');

var str = $(this).html();
var pattern = /[0-9]+/g;
var matches = str.match(pattern);
var myInteger = parseInt(matches);
//variable for player
var container = "container"+myInteger;
var what = 'skill'+myInteger;
var location = "https://aliahealthcare.com/videofetcher.php?id=skill"+myInteger;
player(container,what,location);

$('#'+what).attr('selected', 'selected');

    });

To anyone still helping me, THANKS SO MUCH! also i have modified the site so you no longer need a login to get in so you can see it in action for yourself. Please use the code above as reference in finding the javascript. (It is all located in vid.php) Thanks
https://aliahealthcare.com/vid.php
Also i just discovered something interesting. The li's above are part of a ul with in id of slider. When i do $('#slider').html(''); or $('#slider').empty(); It works but it clears all the div thus the players that load inside those divs dont load. All i need to do is just clear the players so you cant have multipul players running at the same time.

A: Please see working demo here: http://jsfiddle.net/TxR8K/
updated from your given code: http://jsfiddle.net/TxR8K/1/
by the way your unordered list tag i.e. ul is missing in the sample :)
Update further after discussion with OP - we also found out - the player is actually not part of the html in the div, hence he/she knows what needs to be done and clears his./her way for further fix :)
This should do the trick
   $('.clearit').html('');

A: Your problem is most likely that you're running that command before the DOM has loaded. Open a console window in StackOverflow and run $("div").empty();. Everything disappears!

A: You're code should work properly.
Please check that

*

*you place you code within $(document).ready(function() {...}), in short $(function() {..})

*you're loading you jQuery library properly

*don't have any typos mistake
If everything is OK, then your code should work.
If not then try with @Tats_innit answer.
According to you edit
Still I think  your code should work.
but if not then you can try this:
$('div[id^=container].clearit').empty();

DEMO


text:
Q: Color selected by user as "drawing color" With the web app that i have here, the user needs to hand select the color's. And i have a limit of the colors that are usable. i want to have a color-picker that the user can use to select the drawing color. but i dont get it to work.
My webapp so far...

var started = false;
var canvas, context;
var stampId = '';
var lastColor = 'black';
var lastStampId = '';
var enableDraw = false;

function init() {
    canvas = $('#imageView').get(0);
    context = canvas.getContext('2d');

    // Auto-adjust canvas size to fit window.
    canvas.width = window.innerWidth - 75;
    canvas.height = window.innerHeight - 75;

    //$('#container').get(0).addEventListener('mousemove', onMouseMove, false);
    canvas.addEventListener('mousemove', onMouseMove, false);
    canvas.addEventListener('click', onClick, false);
    canvas.addEventListener('mousedown', function (e) {
        enableDraw = true;
    }, false);
    canvas.addEventListener('mouseup', function (e) {
        enableDraw = false;
        started = false;
    }, false);

    // Add events for toolbar buttons.
    $('#red').get(0).addEventListener('click', function (e) {
        onColorClick(e.target.id);
    }, false);
    $('#pink').get(0).addEventListener('click', function (e) {
        onColorClick(e.target.id);
    }, false);
    $('#fuchsia').get(0).addEventListener('click', function (e) {
        onColorClick(e.target.id);
    }, false);
    $('#orange').get(0).addEventListener('click', function (e) {
        onColorClick(e.target.id);
    }, false);
    $('#yellow').get(0).addEventListener('click', function (e) {
        onColorClick(e.target.id);
    }, false);
    $('#lime').get(0).addEventListener('click', function (e) {
        onColorClick(e.target.id);
    }, false);
    $('#green').get(0).addEventListener('click', function (e) {
        onColorClick(e.target.id);
    }, false);
    $('#blue').get(0).addEventListener('click', function (e) {
        onColorClick(e.target.id);
    }, false);
    $('#purple').get(0).addEventListener('click', function (e) {
        onColorClick(e.target.id);
    }, false);
    $('#black').get(0).addEventListener('click', function (e) {
        onColorClick(e.target.id);
    }, false);
    $('#white').get(0).addEventListener('click', function (e) {
        onColorClick(e.target.id);
    }, false);
    $('#cat').get(0).addEventListener('click', function (e) {
        onStamp(e.target.id);
    }, false);
    $('#dragonfly').get(0).addEventListener('click', function (e) {
        onStamp(e.target.id);
    }, false);
    $('#ladybug').get(0).addEventListener('click', function (e) {
        onStamp(e.target.id);
    }, false);
    $('#heart').get(0).addEventListener('click', function (e) {
        onStamp(e.target.id);
    }, false);
    $('#dog').get(0).addEventListener('click', function (e) {
        onStamp(e.target.id);
    }, false);
    $('#fill').get(0).addEventListener('click', function (e) {
        onFill();
    }, false);
    $('#save').get(0).addEventListener('click', function (e) {
        onSave();
    }, false);
}

function onMouseMove(ev) {
    var x, y;

    // Get the mouse position.
    if (ev.layerX >= 0) {
        // Firefox
        x = ev.layerX - 0;
        y = ev.layerY - 0;
    }
    else if (ev.offsetX >= 0) {
        // Opera
        x = ev.offsetX - 0;
        y = ev.offsetY - 0;
    }

    if (enableDraw && stampId.length === 0) {
        if (!started) {
            started = true;
            context.beginPath();
            context.moveTo(x, y);
        }
        else {
            context.lineTo(x, y);
            context.stroke();
        }
    }

    $('#stats').text('x ' + x + ', ' + 'y ' + y);
    $('#size').text('width ' + canvas.width + ', ' + 'height' + canvas.height);
}

function onClick(e) {
    if (stampId.length > 0) {
        context.drawImage($(stampId).get(0), e.pageX - 90, e.pageY - 60, 80, 80);
    }
}

function onColorClick(color) {
    // Start a new path to begin drawing in a new color.
    context.closePath();
    context.beginPath();

    // Select the new color.
    context.strokeStyle = color;

    // Highlight selected color.
    var borderColor = 'white';
    if (color === 'white' || color === 'yellow') {
        borderColor = 'black';
    }

    $('#' + lastColor).css("border", "0px dashed white");
    $('#' + color).css("border", "1px dashed " + borderColor);

    // Store color so we can un-highlight it next time around.
    lastColor = color;

    // Turn off any stamp selection, since we're painting again.
    $(stampId).css("border", "0px dashed white");
    stampId = '';
}

function onFill() {
    // Start a new path to begin drawing in a new color.
    context.closePath();
    context.beginPath();

    context.fillStyle = context.strokeStyle;
    context.fillRect(0, 0, canvas.width, canvas.height);
}

function onStamp(id) {
    // Update the stamp image.
    stampId = '#' + id;

    if (lastStampId === stampId) {
        // User clicked the selected stamp again, so deselect it.
        stampId = '';
    }

    $(lastStampId).css("border", "0px dashed white");
    $(stampId).css("border", "1px dashed black");

    $('#' + lastColor).css("border", "0px dashed white");

    // Store stamp so we can un-highlight it next time around.
    lastStampId = stampId;
}

function onSave() {
    var image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream.png");
    window.location.href=image;
}
/**
 *  Created somewhere on the Bahama's.
 *    __̴ı̴̴̡̡̡ ̡͌l̡̡̡ ̡͌l̡*̡̡ ̴̡ı̴̴̡ ̡̡͡|̲̲̲͡͡͡ ̲▫̲͡ ̲̲̲͡͡π̲̲͡͡ ̲̲͡▫̲̲͡͡ ̲|̡̡̡ ̡ ̴̡ı̴̡̡ ̡͌l̡̡̡̡.___
 *  By Samir.
 */
#container {
    position: relative;
}

#imageView {
    border: 1px solid #000;
}

html, body {
    width: 100%;
    height: 100%;
    margin: 0px;
}

div#canvasDiv {
    cursor: crosshair;
}

div {
    cursor: pointer;
}
<!DOCTYPE html>

    <title>Paint</title>
    <link rel="stylesheet" href="style/style.css">

Save

        <canvas id="imageView">

Unfortunately, your browser is currently unsupported by our web
                application. We are sorry for the inconvenience. Please use one of the
                supported browsers listed below, or draw the image you want using an
                offline tool.

Supported browsers: Opera, Firefox, Safari, and Konqueror.

        </canvas>

0 0

0 0

Can someone insert a working colorpicker in my code?
like this :


text:
Q: Write a function that returns a list for the number of vowels per line Define a function lineStats() that takes one parameter:
1. paragraph, a string of words and white spaces
The function returns a list containing the number of vowels in each line.
for example,
t="Apple\npear and kiwi"
print(lineStats(t))
[2,5]

This is what I have. I've gotten the output to be 7 but not to be able to make it 2,5. I tried to make a counter for each line but that didn't work, any suggestions?
def lineStats(paragraph):
    vowels = "AEIOUaeiou"
    for line in paragraph:
        for word in line:
            for letter in word:
                if letter in vowels:
                    counter +=1
                else:
                    continue

    return counter

t = "Apple\npear and kiwi"
print(lineStats(t))

A: Try this
Create this function
def temp(x):
    return sum(v for k, v in Counter(x).items() if k.lower() in 'aeiuo')

Now
from collections import Counter

print [temp(x) for x in lines.split('\n')]

A: Changing as little of your code as necessary, other answers offer improvements.
def lineStats(paragraph):
    counter = []
    vowels = "AEIOUaeiou"
    lines = paragraph.split('\n')
    for line in lines:
        count = 0
        for word in line:
            for letter in word:
                if letter in vowels:
                    count +=1
                else:
                    continue
        counter.append(count)
    return counter

t = "Apple\npear and kiwi"
print(lineStats(t))        # [2, 5]

The problem states it wants the result to be a list of counts, so changing counter to be a list that we can append to, then use that list to store the vowel count for each line. That may be the only major change to your code that you need to get the required output.
However, there is the concern of newlines ('\n') in the "paragraph", so we str.split() the paragraph into individual lines before entering the for-loop. This will break the count for each line, instead of the total count that you were getting.

A: Here's an adaption of your current code
def lineStats(paragraph):
    vowels = "AEIOUaeiou"
    counter = []
    current_line_count = 0
    newline = "\n"

    for letter in paragraph:
        if letter in vowels:
            current_line_count += 1
        elif letter == newline:
            counter.append(current_line_count)
            current_line_count = 0
    counter.append(current_line_count)
    return counter

A: t="Apple\npear and kiwi"

def lineStats(p):
    #find vowels in each line and sum the occurences using map
    return map(sum, [[1 for e in f if e in "AEIOUaeiou"] for f in p.split('\n')])

lineStats(t)
Out[601]: [2, 5]


text:
Q: Which is a valid bucket url for mybucket I prepare to aws certification and found an answer:
Which is a valid bucket url for mybucket?
Answers
A. http://s3-sa-east-1.amazonaws.com/mybucket
B. http://s3.amazonaws.com/mybucket
C. All of the above

Right answer is C, but I am not agree with it. I don't see variant of backet url without region: https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingBucket.html#access-bucket-intro. But on the other side - bucket name is unique globally, so, what is the sense to write bucket-region if you provide bucket name?
So, which answer is correct?

A: Bucket url without region is Legacy Global Endpoint still used N. Virginia region.
S3 is a regional service, though bucket names are global. Since its regional service, using url endpoint with the address directs all your queries to the endpoint in the same region as your data.

A: A. http://s3-sa-east-1.amazonaws.com/mybucket

A. is correct. Some older Amazon S3 Regions support endpoints that contains a dash between S3 and the Region instead of a dot.
B. http://s3.amazonaws.com/mybucket

B. is using the legacy global endpoint and therefore is implicitly us-east-1 (N. Virginia) Region.
From the doc:

For the US East (N. Virginia) Region, the legacy global endpoint can be used for path-style requests.
For all other Regions, the path-style syntax requires that you use the
  Region-specific endpoint when attempting to access a bucket. If you
  try to access a bucket with the legacy global endpoint or another
  endpoint that is different than the one for the Region where the
  bucket resides, you will receive an HTTP response code 307 Temporary
  Redirect error and a message indicating the correct URI for your
  resource. For example, if you use https://s3.amazonaws.com/bucket-name
  for a bucket that was created in the US West (Oregon) Region, you will
  receive an HTTP 307 Temporary Redirect error.

So the right answer is
C. All of the above


text:
Q: print object.object with mustache Is there a way to do something like this:
var html,
    templ = '
{{config.title}}
',
    data = {config: {title: 'some text'}};
html = Mustache.to_html(templ, data);
alert(html);

With the Mustache library?
Or maybe with some other library.

A: Use moustache contexts:
var html,
    templ = '
{{#config}}{{title}}{{/config}}
',
    data = {config: {title: 'some text'}};
html = Mustache.to_html(templ, data);
alert(html);

-> '
some text
'

A: https://github.com/janl/mustache.js
Usage
A quick example how to use mustache.js:
var view = {
  title: "Joe",
  calc: function() {
    return 2 + 4;
  }
}

var template = "{{title}} spends {{calc}}";

var html = Mustache.to_html(template, view);

template is a simple string with mustache tags and view is a JavaScript object containing the data and any code to render the template.

A: Insted of mustache use underscore.js:
_.templateSettings = { interpolate : /\{\{(.+?)\}\}/g };
var templateStructure = 'Hello {{ name }}!';
var template = _.template(templateStructure);
alert(template(yourObject));

Be careful: the data You put in Your template is unescaped.
There is one more think:

If Your templateStructure contains 'null' You will get an error.
To make it work do this:
var templateStructure = 'Hello {{ name }}! Did You know that "null" will provide an error?';
    templateStructure.replace(/null/g, 'NULL_REPLACEMENT');
var template = _.template(templateStructure);
var out = template(yourObject);
    out = template.replace(/NULL_REPLACEMENT/g, 'null');
alert(out);


text:
Q: Any way to get the currently executing function object in javascript? Is there any way to refer to the function object that you're currently executing in?  If it's not a method of any object or not called with .call() or .apply(), the this pointer is likely just window, not the function object.
I often use a design pattern like this for global variables that I want scoped to a particular function as this keeps them out of the top level namespace:
function generateRandom() {
    if (!generateRandom.prevNums) {
        generateRandom.prevNums = {};    // generateRandom.prevNums is a global variable
    }
    var random;
    do {
        random = Math.floor((Math.random() * (99999999 - 10000000 + 1)) + 10000000);
    } while (generateRandom.prevNums[random])
    generateRandom.prevNums[random] = true;
    return(random.toString());
}

But, I'd rather not have to spell out the function name every time I want to use a variable scoped to that object.  If the name of the function ever changes, there are then a lot of places to change the name.
Is there any way to get the currently executing function object?

A: Well, you could use arguments.callee()...
https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope/arguments/callee
From MDN:

Description
callee is a property of the arguments object. It can be used to refer
  to the currently executing function inside the function body of that
  function. This is for example useful when you don't know the name of
  this function, which is for example the case with anonymous functions.
Note: You should avoid using arguments.callee() and just give every
  function (expression) a name.

BUT...
What you really want are Javascript Prototypes.
function RandomSomethingGenerator()
{
   this.prevNums = {};
}

RandomSomethingGenerator.prototype.generate = function() {
    var random;
    do {
        random = Math.floor((Math.random() * (99999999 - 10000000 + 1)) + 10000000);
    } while (this.prevNums[random])
    this.prevNums[random] = true;
    return(random.toString());
};

Why do I say this?
1.) You're dirtying the global space with all those functions.
2.) Even if you like Jani's suggestion, and you want a "static" function like you have now, my suggestion would be the same, but with a twist: Create your global function, and wrap an instance of an object (built from a prototype) inside the closure and make the call to it (so, basically, make yourself a singleton).
As in this (adapted from Jani's answer):
var randomSomething = (function() {
    var randomSomethingGenerator = new RandomSomethingGenerator();

    return function() {
        randomSomethingGenerator.generate();
    };
})();

A: I don't think there's any way to do exactly what you ask, but you could use a closure for your function-local static variables instead.
You can easily achieve this using an IIFE:
var generateRandom = (function() {
    //any function's static variables go here
    var prevNums = {};

    return function() {
        //function code goes here
        var random;
        do {
            random = Math....
        }

        prevNums[random] = true;

        return random.toString();
    };
})();

A: You want arguments.callee. From MDN - callee:

callee is a property of the arguments object. It can be used to refer to the currently executing function inside the function body of that function. This is for example useful when you don't know the name of this function, which is for example the case with anonymous functions.

For example:
> foo = function() { console.log(arguments.callee); };
> bar = function() { foo() };
> bar();
function () { console.log(arguments.callee) }

However, I think this is being deprecated. The above link says, "The 5th edition of ECMAScript forbids use of arguments.callee() in strict mode."


text:
Q: Baby rudin theorem 8.18 $\Gamma(x) = \int_0^\infty t^{x-1}e^{-t}dt.$
Here is the Hölder's inequality:
(1/p) + (1/q) = 1.
|$\int_a^bfg$ $d\alpha$| $\leq$ {$\int_a^b$ $|f|^p$ $d\alpha$}$^{1/p}$ {$\int_a^b$ $|g|^q$ $d\alpha$}$^{1/q}$.
The 8.18 theorem says that log $\Gamma$ is convex on (0,$\infty$).
Here is the proof of this:
If 1 < p < $\infty$ and (1/p) + (1/q) = 1, apply  Hölder's inequality to $\Gamma(x)$ and obtain $\Gamma(\frac{x}{p} + \frac{y}{q})$ $\leq$ $\Gamma(x)^{1/p}\Gamma(y)^{1/q}.$
This is equivalent to this : "log $\Gamma$ is convex on (0,$\infty$)."
This means that $\int_0^\infty t^{\frac{x}{p} + \frac{y}{q} - 1}e^{-t}dt$ $\leq$ ${\int_0^\infty t^{x-1}e^{-t}dt}^{1/p}{\int_0^\infty t^{y-1}e^{-t}}dt^{1/q}$.
I couldn't relate this inequality to the Hölder's inequality. I don't understand how did we obtain this.
I also don't understand the idea of the convexity of log $\Gamma$. As I know the definition of convexity of function I couldn't relate this inequality: $\Gamma(\frac{x}{p} + \frac{y}{q})$ $\leq$ $\Gamma(x)^{1/p}\Gamma(y)^{1/q}$ to the idea of $log\Gamma(x)$ convexity on (0,$\infty$).
Any help would be appreciated.


text:
Q: Numerical solution's evolution's dependance on timestep and the absolute time passed. After solving a heat equation (1 space dimension and the time dimension) with a scheme, if I get different results at the same absolute points of time for different durations of the timestep, does it mean that I have made a mistake?
With my solution I've noticed that my solution settles after a certain amount of iterations (or so it seems), and hence by making the timestep however small I want, it seems like I can make my solution settle after however small amount of time. Am I necesserily making a mistake?


text:
Q: Strange behavior using variable in Exists I came across a behavior that doesn't make sense to me when I tried to use Exists in Reduce.
If I run commands:
l = {a0, a1, x};
Reduce[Exists[l , a1 != 0 && a0 + a1 x == 0 && a1 < 0], Reals]

I get output:
a1 < 0 && a0 == -a1 x

But if I run command:
Reduce[Exists[{a0, a1, x} , a1 != 0 && a0 + a1 x == 0 && a1 < 0], Reals]

I get output:
True

I think the problem is in exists part:
Exists[l, a1 != 0 && a0 + a1 x == 0 && a1 < 0]

Gives output
a1 != 0 && a0 + a1 x == 0 && a1 < 0

And
Exists[{a0, a1, x} , a1 != 0 && a0 + a1 x == 0 && a1 < 0]

Gives output (which I think is correct):
\!\(\*SubscriptBox[\(\[Exists]\), \({a0, a1, x}\)]\((a1 != 0 && a0 + a1\ x == 0 && a1 < 0)\)\)

Can somebody explain what is going on there and how could I use variable in Exists if this not the correct way?

A: As belisarius pointed out the strange behavior disappears when using Evaluate.
Reduce[Exists[Evaluate[l] , a1 != 0 && a0 + a1 x == 0 && a1 < 0], Reals]

Gives output:
True


text:
Q: Python Mechanize: Web Forms with Javascript I am trying to upload information through a form using Python.  I would share the form but it is password protected (I have permission to access it though).  I have been using mechanize but have encountered a problem.
The page that I am uploading to actually consists of a number of forms, which are accessed by tabs at the top of the page.  These tabs are set up using Javascript.  When I access the URL of the page, I can see the form for the first tab using mechanize, but I do not know how to change tabs.
This is a snippet I got with Firebug:
<form id="frmEntityEdit" enctype="multipart/form-data" onsubmit="javascript:return
 WebForm_OnSubmit();" action="entityEditProducts.aspx?
EntityFilterID=239&EntityName=Category&iden=6751" method="post" name="frmEntityEdit">

Also, when I change tabs, value for "TabStrip1_SelectedNode" cycles through "p0", "p1", "p2", etc.
<input id="TabStrip1_Data" type="hidden" name="TabStrip1_Data">
<input id="TabStrip1_Properties" type="hidden" name="TabStrip1_Properties">
<input id="TabStrip1_SelectedNode" type="hidden" value="p0" name="TabStrip1_SelectedNode">
<input id="TabStrip1_ScrollData" type="hidden" value="0" name="TabStrip1_ScrollData">

I would like to be able to switch tabs, so that I can fill out all the forms.
Thanks in advance for the help.  Let me know if you need more information.

A: mechanize doesn't evaluate javascript. The easiest way that I've seen to do it is by using Selenium, which will open a browser on your computer and communicate with python.
I answered a similar question here.


text:
Q: How can I get a Dialog style activity window to fill the screen? I am using an activity with the dialog theme set, and I want it to be full screen. I tried all sorts of things, even going through the WindowManager to expand the window to full width and height manually, but nothing works.
Apparently, a dialog window (or an activity with the dialog theme) will only expand according to its contents, but even that doesn't always work. For instance, I show a progress bar circle which has width and height set to FILL_PARENT (so does its layout container), but still, the dialog wraps around the much smaller progress bar instead of filling the screen.
There must be a way of displaying something small inside a dialog window but have it expand to full screen size without its content resizing as well?

A: For Dialog
This may helpful for someone.
I want a dialog to take full width of screen. searched a lot but nothing found useful. Finally this worked for me:
mDialog.setContentView(R.layout.my_custom_dialog);
mDialog.getWindow().setBackgroundDrawable(null);

after adding this, my dialog appears in full width of screen.

A: You may add this values to your style android:windowMinWidthMajor and android:windowMinWidthMinor
<style name="Theme_Dialog" parent="android:Theme.Holo.Dialog">
    ...
    <item name="android:windowMinWidthMajor">97%</item>
    <item name="android:windowMinWidthMinor">97%</item>
</style>

A: This answer is a workaround for those who use "Theme.AppCompat.Dialog" or any other "Theme.AppCompat.Dialog" descendants like "Theme.AppCompat.Light.Dialog", "Theme.AppCompat.DayNight.Dialog", etc.
I myself has to use AppCompat dialog because i use AppCompatActivity as extends for all my activities. There will be a problem that make the dialog has padding on every sides(top, right, bottom and left) if we use the accepted answer.
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.your_layout);

    getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
}

On your Activity's style, add these code
<style name="DialogActivityTheme" parent="Theme.AppCompat.Dialog">
    <item name="windowNoTitle">true</item>
    <item name="android:windowBackground">@null</item>
</style>

As you may notice, the problem that generate padding to our dialog is "android:windowBackground", so here i make the window background to null.

A: I just want to fill only 80% of the screen for that I did like this below
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        int screenWidth = (int) (metrics.widthPixels * 0.80);

        setContentView(R.layout.mylayout);

        getWindow().setLayout(screenWidth, LayoutParams.WRAP_CONTENT); //set below the setContentview

it works only when I put the getwindow().setLayout... line below the setContentView(..)
thanks @Matthias

A: I found the solution:
In your activity which has the Theme.Dialog style set, do this:
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.your_layout);

    getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
}

It's important that you call Window.setLayout() after you call setContentView(), otherwise it won't work.

A: Set a minimum width at the top most layout.
android:minWidth="300dp"

For example:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"
  xmlns:android="http://schemas.android.com/apk/res/android" android:minWidth="300dp">

<!-- Put remaining contents here -->

</LinearLayout>

A: Matthias' answer is mostly right but it's still not filling the entire screen as it has a small padding on each side (pointed out by @Holmes). In addition to his code, we could fix this by extending Theme.Dialog style and add some attributes like this.
<style name="MyDialog" parent="@android:style/Theme.Dialog">
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowNoTitle">true</item>
</style>

Then we simply declare Activity with theme set to MyDialog:
<activity
    android:name=".FooActivity"
    android:theme="@style/MyDialog" />

A: This would be helpful for someone like me. Create custom dialog style:
<style name="MyDialog" parent="Theme.AppCompat.Light.Dialog">
    <item name="windowNoTitle">true</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowIsFloating">false</item>
</style>

In AndroidManifest.xml file set theme for wanted activity:
<activity
        android:name=".CustomDialog"
        ...
        android:theme="@style/MyDialog"/>

That is all, no need to call methods programaticaly.

A: Wrap your dialog_custom_layout.xml into RelativeLayout instead of any other layout.That worked for me.

A: In your manifest file where our activity is defined
<activity
        android:name=".YourPopUpActivity"
        android:theme="@android:style/Theme.Holo.Dialog" >
    </activity>

without action bar
<activity android:name=".YourPopUpActivity"
            android:theme="@android:style/Theme.Holo.Dialog.NoActionBar"/>


text:
Q: The more you're sinless vs the more sinless you are
The more you're sinless
The more I wanna bite
I'm lost inside of the night
So leave me here where I roam
All on my own

On My Own - Hyde
Shouldn't it be "the more sinless you are"? The phrase used seems to be ungrammatial. Am I correct? Also, "lost inside of the night", is that grammatical too?

A: This is a song, which is an example of poetry. The rules of grammar are often relaxed to the point of being almost nonexistent in poetry, especially sung poetry. This is not a new concept and has been explained many times on this site.
"The more you're sinless" doesn't truly make a lot of sense because "being sinless" is a binary thing—either you have sinned or you haven't. Someone who has never sinned would be called "sinless" and someone who as sinned even once wouldn't be. But things aren't so strict in songs and there isn't really a grammatical issue here.
Similarly, "lost inside of the night" is perhaps not as logically sound as it could be, but is perfectly fine from a grammar standpoint.


text:
Q: According Facebook Platform Policy, Could I save UID in my secure database? According to Facebook Platform policy, Could I save UID in my secure database?
The reason for that is , I want to remember user when they use Facebook account login to my website. For example, they like post and I want to remember them access to some restricted area.
Any help would be appreciated.

A: Yes , but you must remove it if the user deauths your app, and you can't share it outside your app. If you need to share it, use the third party id instead.
The auth docs (https://developers.facebook.com/docs/authentication/) have details on how to handle deauths.


text:
Q: how to display the recent call logs I am new in android programming.I want the data of recent call logs not the whole history I write this code .It displays all the records upto to the newest call record .
Please help me. Please tell me what to use or how I can get the most recent call data this is my code
public class MainActivity extends Activity {
    TextView call;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         call =(TextView) findViewById(R.id.tvcall);
        callDetails();
    }
    private void callDetails()
    {
        StringBuffer sb = new StringBuffer();
        Cursor managedCursor =managedQuery(CallLog.Calls.CONTENT_URI, null, null, null, null);
        int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
        int name = managedCursor.getColumnIndex(CallLog.Calls.CACHED_NAME);
        int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
        int date =managedCursor.getColumnIndex(CallLog.Calls.DATE);
        int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
        sb.append("call details:");
        while(managedCursor.moveToNext())
        {
            String phNumber=managedCursor.getString(number);
            String callerName=managedCursor.getString(name);
            String callType=managedCursor.getString(type);
            String callDate=managedCursor.getString(date);
            Date callDayTime= new Date(Long.valueOf(callDate));
            String callDuaration= managedCursor.getString(duration);
            String dir=null;
            int dirCode=Integer.parseInt(callType);
            switch(dirCode)
            {
            case CallLog.Calls.OUTGOING_TYPE:
                dir="OUTGOING";
                break;
            case CallLog.Calls.INCOMING_TYPE:
                dir="INCOMING";
                break;
            case CallLog.Calls.MISSED_TYPE:
                dir="MISSED";
                break;

            }
        sb.append("\n Phone Number:--"+phNumber+"\n caller Name:--"+callerName+"\n call Type:--"+dir+"\n Call Date:--"+callDayTime+"\n call duration in sec:--"+callDuaration);
        sb.append("\n----------------------------");
        }
        managedCursor.close();
        call.setText(sb);

    }

A: Just order by.
Cursor managedCursor =managedQuery(CallLog.Calls.CONTENT_URI, null, null, null, null);

try change it.
Cursor managedCursor = managedQuery(CallLog.Calls.Content_URI, null, null, null, CallLog.Calls.DATE + " DESC");


text:
Q: How to make Python requests.get cut off or fail faster? Why does the Python requests.get() function take too long to be cut off (or fail) if the target request URL is a remote URL (i.e. not localhost) and it can't be reached?
If the target request URL is just localhost and it can't be reached, it cuts off or fails very fast so the issue only occurs if the target request URL is a remote URL.
How could I make it quicker?

A: Yes. A timeout would do the trick, but you'll need to make sure the remote server will execute the request (if it's supposed to). Meaning: don't make the request timeout 1s if the request would take 5s to execute.
Requests Docs for Timeouts
requests.get('https://github.com/', timeout=0.001)

Alternatively, you could (on localhost) point to the server you're after. And have some kind of variable that points to the "correct" server based on if the Python server is local or remote?


text:
Q: Sequel transactions wrap exceptions instead of reraising them When using transactions in Sequel you are supposed to be able to raise an exception and have it bubble out of the transaction block.
From the Sequel documentation:

If any other exception is raised, the transaction is rolled back, and the exception is raised outside the block:

DB.transaction do # BEGIN
  raise ArgumentError
end # ROLLBACK
# ArgumentError raised

However, it seems I'm not able to catch the ArgumentError since Sequel wraps it in a Sequel::DatabaseError:
begin
  DB.transaction do
    raise ArgumentError.new('Hey')
  end
rescue => e
  puts e.inspect
  puts e.kind_of?(ArgumentError)
end

Result:
> #<Sequel::DatabaseError: ArgumentError: Hey>
> false

How can I solve this?

A: You could try using wrapped_exception as documented here and re-raise the exception.
begin
  DB.transaction do
    raise ArgumentError.new('Hey')
  end
rescue Sequel::DatabaseError => e
  raise e.wrapped_exception
end


text:
Q: Clear Connections/Outlets in ViewController Class? I am working in XCode and I copied a view controller over to a different project, but all the connections/outlets are still connected to the old project. If I mouse over the connection dot, it highlights the outlet object in the other project. How do I remove all the connections for the class?
It seems like if the ViewController's name is the same, if I add the a IBOutlet of the same type and name it will automatically connect to the old project.
Thanks!

A: If you paste the classes in while the source project is open, it will link for some reason. Once you quit xCode and reopen just the new project, it will clear the connections to the old project!


text:
Q: Fluent-Nhibernate References and PropertyRef Doing a Select With Lazy Load I am using PropertyRef for one of my References properties. With LazyLoad() it still does a Select and loads the User entity, even though I never "hit" the SalesPerson property.
Order Mapping
Id(x => x.Id).GeneratedBy.Native();
References(x => x.SalesPerson)
                        .LazyLoad()
                        .PropertyRef(x => x.Username)
                        .Column("rsm");
Map(x => x.Title);

Order Class
public class Order : BaseEntity
{
    ...
    public virtual User SalesPerson { get; set; }
    public virtual string Title { get; set; }
    ...
}

User Mapping
Id(x => x.Id).GeneratedBy.Native();
Map(x => x.Username).Column("login");

User Class
public class User : BaseEntity
{
     public virtual string Username { get; set; }
     ...
}

Generated Order Mapping
<many-to-one class="Project.User" lazy="proxy" name="SalesPerson" property-ref="Username">
      <column name="rsm" />
</many-to-one>

Executing Code
var order = session.Get<Order>(1);
Console.WriteLine(order.Title);

Is there anyway to prevent the Select to load the User entity when I'm not using the User entity?

A: Has to do with property-ref see
NHibernate creates proxy via session.Load(), but not via Linq or Criteria API
And not that you asked, but also consider that many-to-one with proxy does not allow you to do type-checking if you subclass User, see
http://ayende.com/Blog/archive/2010/01/28/nhibernate-new-feature-no-proxy-associations.aspx

A: I don't think this is a bug in NHibernate. It depends on your mapping.
First, remember that the reference map will join the key (primary key and foreign key) between 2 mapping tables. To prevent SELECT + 1, just ignore the key joint.
References(x => x.SalesPerson)
                    .LazyLoad()
                    .PropertyRef(x => x.Username)
                    WithForeignKeyName("none") //disable key join.


text:
Q: Install TRibbon Delphi Berlin update 2 How to install tribbon manually in delphi Berlin update 2?
PS: TRibbon Donwload link?
Thx.

A: You can use TurboPack's Ribbon Framework. This library will allow you to implement the type TUIRibbon. There are instructions on how to add a TUIRibbon are on the GitHub page. There is a wiki with more detailed instructions.
To install it: (instructions from GitHub)

*

*Download the library

*Open the project "Package\UIRibbonPackage.dproj"

*Right click "UIRibbonPackage" and click "install"

*"Tools > Options > Environment Options > Delphi Options > Library > Library Path > [...]" Browse to the "Lib" folder of this framework, press "OK", "Add", "OK", "OK"

Hope that helps.


text:
Q: Getting git to never push a single commit? I don't think this is possible, but thought someone might have a nifty idea of how to accomplish this:
I have a project that I checked out that was in existence long before I took it over.  I have about a dozen changes in various files that I never want checked in (they're all config changes).
Is there any way to commit this set of changes and then never actually push that one commit?  I know it sounds odd :)
clarification:
I want these changes to stay in my working directory, I need them for the app to function locally.  I want to be able to keep commit other changes around them, even changes in the same file, but never push the config changes to anywhere else...
It's somewhat like before every push I would want to:

*

*cherry pick and stash this one commit

*rebase the one commit out

*push

*re-apply this stash to my codebase

A: Use git update-index --assume-unchanged on these files to make git think that the files are not modified.
After comments, an alternative is to have a separate branch that you push from. The commits in this branch are cherry picked etc from the work branch. So when you want to push, switch to the "push" branch, cherry-pick commits from "work" and push.

A: This is a similar pattern to maintaining a local patch set to an upstream project you don't control.  The easiest way to handle this is to have an intermediate branch that all changes get merged through, like this:
___________________________ master
\__________________________ config-changes
     \_____________________ daily-work

master contains everything that is to be shared.  The only things committed in config-changes are changes you want to be able to revert easily when they are shared.  daily-work is the branch you do all your work in.  To set it up, do:
# (no local config changes should be in master at this point)
git checkout -b config-changes master
# Make your config-related changes that you don't want to share
git commit -am "Made local config changes"
git checkout -b daily-work
# Work and commit like normal

When you're ready to share your changes, do:
git rebase --onto master config-changes daily-work
git checkout master
git merge daily-work

That will revert all the changes made in config-changes, but otherwise make it look like you branched directly from master.  Note that after you do this rebase, if you want to continue to work in daily-work, you need to rebase it back onto config-changes, but it's really better to create a new branch for each change.
When you need to pull down new changes from master, do:
git checkout master
git pull
git checkout config-changes
git merge master

The merge reapplies your local config changes onto the latest master.  You're then free to create a new daily-work branch, or merge config-changes into the old one, as appropriate.  Basically, you never merge directly from master into daily-work.  You always go through config-changes first.
It seems like a lot of work at first, but once you do it once or twice you'll see it's a lot easier than maintaining the changes manually.

A: Yeah, just create a separate branch and store these changes there:
git checkout -b your-new-branch
git commit -a

After you are done committing, just go back to your original branch and forget about these changes.


text:
Q: Pass Query String parameter to JsonResult action in MVC controller I have trying to pass a query string parameter to my JsonResult action in the controller. I keep getting the following error:
Value cannot be null.
Parameter name: String
I need the task_id from this url:
TaskIn?task_id=33
In my view I have tried (fails with same error):
 @model TaskingSystem.Models.AcceptTasksViewModel

 @{string task_id = @Request.QueryString["task_id"];}
 @Html.HiddenFor(m => m.task_id)

In controller:
  public JsonResult TasksExist(string email, string task_id)
    {

        int tasks_id = int.Parse("task_id");
        return Json(db.Tasks_Validate.Any(e => e.Email == email && e.task_id == tasks_id), JsonRequestBehavior.AllowGet);

    }

My model:
 public class AcceptTasksViewModel{

    [Required]
    [DataType(DataType.EmailAddress)]
    [Display(Name = "Email:")]
    //Using Remote validation attribute
    [Remote("TasksExist", "Task_Results",  ErrorMessage = "Email does not exists in database. Please try a different email address.")]
    public string email { get; set; }

    public int task_id { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }
}

I have also tried just passing straight into the action using this but it still fails.
  int tasks_id = int.Parse(Request.Params["task_id"]);

A: To pass the task_id along with the email to your TasksExist(string email, string task_id) method, you have to mention task_id in AdditionalFields property of Remote attribute as follows:
[Remote("TasksExist", "Task_Results",AdditionalFields = "task_id"  ErrorMessage = "Email does not exists in database. Please try a different email address.")]
public string email { get; set; }


text:
Q: What characters need to be escaped in a Sql Server LIKE query The LIKE operator in a SQL server query can be very useful to match custom patterns. However sometimes the need raises to escape some characters or substrings from the pattern, such as ampersands '%', underscores '_', square brackets '[' and ']',  etc.
Indeed I'm using parametrized queries but it does not solve LIKE case because for example searching for _ would mean "any character".
What is the set of characters that must be considered while escaping such patterns? Can a C# function be provided to perform a safe escape?

A: %, _, [, ], and ^ need to be escaped, and you will need to choose a suitable escape character, i.e. one that you aren't using elsewhere in your LIKE pattern.
Full description here LIKE (Transact-SQL)
I'm sure you could write a function in C# to do that.

A: See the existing stackoverflow answer here...
How to use wildcards in SQL query with parameters
DO use SQLParameter
DONT use stringbuilder or add strings together
Unless you understand SQL Injection Attacks
https://en.wikipedia.org/wiki/SQL_injection


text:
Q: Linear Algebra and augmented matrix If the coefficient matrix A in a homogeneous system of 22 equations in 16 unknowns is known to have rank 5,
how many parameters are there in the general solution

A: *

*So we have 5 linearly independent equations, since the system has rank 5, hence we can determine only 5 unknowns. The fact that there are 22 equations is more or less irrelevant, since 17 of them must just be linear combinations of 5 that are linearly independent.

Incidentally, is this homework?

A: I don't know whether you have seen the following concepts, but here goes:
The number of parameters is the dimension of the nullspace of the matrix.
The dimension of the nullspace of any matrix, plus the rank of the matrix, gives you the number of columns of the matrix.
And you have been given both the rank and the number of columns (since there is one column for each unknown), so you should be set!

A: The answer is 11.
Irrelevant Aside:
(Why the hell must the body be at least 30 characters long?)


text:
Q: How to add hourly rows on a daily sequence dataframe? if i have a daily data in the following format:
A:
    DD-MM-YYYY
    01-01-2000
    02-01-2000
    03-01-2000
    04-01-2000
    ...
    31-12-2010
    31-12-2010
    31-12-2010
    31-12-2010

How to add hourly values to all the days and obtain a new A like:
A:
    DD-MM-YYYY hour
    01-01-2000 00:00
    01-01-2000 01:00
    01-01-2000 02:00
    01-01-2000 03:00
    ...
    01-01-2000 21:00
    01-01-2000 22:00
    01-01-2000 23:00

    ...
    ...
    31-12-2010 21:00
    31-12-2010 22:00
    31-12-2010 23:00

A: This will stick 00:00 to 23:00 on to each of your days:
expand.grid(day = A$`DD-MM-YYYY`, hour = sprintf("%02d:00", 0:23))

However, in the real world you might prefer to use seq.POSIXt, which will account for leap years, daylight savings, etc.


text:
Q: How to make structure fields programmable in matlab? I have a excell file that I need to read into matlab. I already read excel file as cell form in matlab.
I want to convert cell data type to structure in matlab. My excel file is like this
       Va   Ia   Vb   Ib   Vc   ... ...
01:00  100  10   200  20   300  ... ...
02:00  110  11   210  21   310  ... ...
03:00  120  12   220  22   320  ... ...
04:00  130  13   230  23   330  ... ...
...    ...  ...  ...  ...  ...  ... ...

and then I know taht structure data type consist field and material. I wanna that first column use to field name. for instance, I want this
structure A
field 1: Va
material : [100;110;120;130 ... ...]
field 2: Ia
material : [10 ;11 ;12 ;13  ... ...]

and I will use that to access variables in structure
A.Va(3)= ~~~~~ ;somethig.....


text:
Q: Android Debugging techniques My question is there is a way to debug a specific line of code to check how much memory it takes or a technique of figuring out how much it uses?.
Note* I am using eclipse.

A: See http://www.droidnova.com/debugging-in-android-using-eclipse,541.html
and
http://macgyverdev.blogspot.de/2011/07/profiling-android-application-tutorial.html
that's all you need to know ;)
Debugging and Profiling are the keywords.


text:
Q: spring boot spring data jpa multiple datasource to execute same service I have a requirement where I need to fetch data from one MySQL DB table, and this data needs to be fetched from multiple MySQL DBs. So the code needs to be same just datasource needs to be different.
I want my application to be generic so that in case there is new DB is required we just have to put the entries into application.properties and no more code changes are required. We can do something with for loop etc.
I am able to do multiple connections by creating different beans like:
@Bean(name = "mysqlDb")
    @ConfigurationProperties(prefix = "spring.ds_mysql")
    public DataSource mysqlDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "mysqlJdbcTemplate")
    public JdbcTemplate jdbcTemplate(@Qualifier("mysqlDb") DataSource dsMySQL) {
        return new JdbcTemplate(dsMySQL);
    }

But I will have to put code with every bean, which I want to ignore as the datasource beans creation should be dynamic and I just need to put the db properties in application.properties.
Please let me know if there is any way to do so.