text:
Q: java concurrency with scheduledexecutor and infinite loop I need to create two threads , one invoking a scheduler executor service and the other which runs in an infinite loop to fetch and process files.
I use the following code:
ScheduledExecutorService executor = new ScheduledThreadPoolExecutor(1);
executor.scheduleAtFixedRate(new Runnable() {
        public void run()
        {
            obj.checkFileExist();
            obj.enqueue();

         }
    }, 0, 1, TimeUnit.MINUTES);

And in an infinite loop I process files one by one:
public class processModel extends Thread{

    public static void getQueueSize(int size)
    {
        System.out.println("getting queue size");

    }
    public void dequeue()
    {

        // dequeue the queue
        System.out.println("dequeue");

    }

    public void processFile()
    {
        // process the file
        System.out.println("process file");
    }

    public static void main(String[] args) {
        final boolean flag = true;
        final int size = 9;
        final processModel obj = new processModel();
        Thread t1 = new Thread(){
            public void run()
            {
                while(flag)
                {
                obj.dequeue();
                obj.processFile();
                getQueueSize(size);

                }

            }

        };

        t1.start();

    }

}

How can I achieve both concurrently?

*

*Thread 1 - check if file exists in a folder. if yes enqueue it else sleep for a min.. - scheduler can perform this

*Thread 2 - if queue is non empty , process one by one. else sleep for a minute

How can I run these 2 threads concurrently. It would help me a lot if you show up some code.

A: Using two threads doesn't make any sense.  The only time both thread will run at once is when the enqueuer is picking up files faster than the dequeuer can process them.  You solution would be simpler and more robust if you has a single repeating task which will ensure you never have one thread critically always ahead of the other ( and the code is much simpler)
ScheduledExecutorService executor = new SingleScheduledThreadPool();
executor.scheduleAtFixedRate(new Runnable() {
    public void run() {
        for(File file: obj.getCHangedFiles())
            obj.processFile(file);

     }
}, 0, 1, TimeUnit.MINUTES);

A: You have at least three threads running (in addition to the main thread): At least one from the ExecutorService, processModel and t1. But in principle, you only need one.
I think the job being scheduled with scheduleAtFixedRate(...) could just as well do the processing itself. After all, it won't take more than a minute to process the file, will it? This way, you greatly reduce the complexity of your program.
But if you insist on doing the checking and processing in different threads, I suggest you use one of the BlockingQueue implementations from the JDK. The scheduled taks would put the file or whatever object in the queue and a second thread like t1 in your code can then take and process the object.

A: I agree with the other 2 answers. If you still what to use threads, the you should study the wait-notify mechanism. Because its much more efficient than running a thread every minute.
*In case its the first time you use threads and concurrency - You will not get it in 5 minutes! It will take some time till get it, so be patient.
Edit: As stated in the comment - its better to use existing libraries if possible.


text:
Q: Return a list of selected values in a tkinter Listbox I am trying to create a tkinter listbox and print the user-selected options as a list.
So far I have:
from tkinter import *
from tkinter import ttk

main = Tk()
main.title('Test GUI')
main.geometry('700x500')

nb = ttk.Notebook(main)
nb.grid(row=1, column=0, columnspan=50, rowspan=49, sticky='NESW')

page1 = ttk.Frame(nb)
nb.add(page1, text='Search Terms')

p1_IncludeLanguage = Listbox(page1)
p1_IncludeLanguage.configure(selectmode=MULTIPLE, width=9, height=5)
p1_IncludeLanguage.grid(row=0, column=0)

for lang in ["English", "German", "French", "Italian", "Portuguese"]:
    p1_IncludeLanguage.insert(END, lang)

main.mainloop()

I want to print out the selected options in the listbox, and I tried starting off by getting their line numbers with p1_IncludeLanguage.curselection(), but this results in an error of TclError: invalid command name ".!notebook.!frame.!listbox"
Is there any other way to accomplish this? Why is .curselection() not working?

A: How does this work for you? I've added a button which will get the list of selected items.
from tkinter import *
from tkinter import ttk

def get_selection():
    items = [languages[int(item)] for item in  p1_IncludeLanguage.curselection()]
    print(items)

main = Tk()
main.title('Test GUI')
main.geometry('700x500')

nb = ttk.Notebook(main)
nb.grid(row=1, column=0, columnspan=50, rowspan=49, sticky='NESW')

page1 = ttk.Frame(nb)
nb.add(page1, text='Search Terms')

p1_IncludeLanguage = Listbox(page1)
p1_IncludeLanguage.configure(selectmode=MULTIPLE, width=9, height=5)
p1_IncludeLanguage.grid(row=0, column=0)

btnGet = Button(page1,text="Get Selection",command=get_selection)
btnGet.grid()

languages = ["English", "German", "French", "Italian", "Portuguese"]

for lang in languages:
    p1_IncludeLanguage.insert(END, lang)

main.mainloop()

redpajama_set_name: RedPajamaStackExchange


text:
Q: export tables from google bigquery to google storage I'm new on bigQuery. I need to export tables from BigQuery to google storage.
For the moment, I can list all tables by dataset.
Does some boody can help me with how can I export then tables?
My python code is below :
#!/usr/bin/env python

from googleapiclient import discovery
from oauth2client.client import GoogleCredentials
from bigquery_client import client

credentials = GoogleCredentials.get_application_default()
service = discovery.build('bigquery', 'v2', credentials=credentials)

# * Project ID of the datasets to be listed
projectId = 'xxxxxxxxx'

datasets = service.datasets()
request = datasets.list(projectId=projectId)

response = request.execute()

for dataset in response['datasets']:
  datasetId = dataset['datasetReference']['datasetId']
  tables = service.tables()
request = tables.list(projectId=projectId, datasetId=datasetId)
response = request.execute()
if 'tables' in response :
    for table in response['tables']:
        print ('Dataset name treated is :' + '%s' % dataset['datasetReference']['datasetId'])
        print ('%s' % dataset['datasetReference']['datasetId'])
        print ('Is table number:' + '%s' % table['tableReference']['tableId'])

Thanks

A: There is a full Python example on the docs page
including here for future reference:
def export_data_to_gcs(dataset_name, table_name, destination):
    bigquery_client = bigquery.Client()
    dataset = bigquery_client.dataset(dataset_name)
    table = dataset.table(table_name)

    job = bigquery_client.extract_table(
        table, destination)

    job.result()

    print('Exported {}:{} to {}'.format(
        dataset_name, table_name, destination))


text:
Q: Spark SQL: Parsing two correlated columns I have 2 columns in below format:
+-----------------------------------------+-----------------------------------+
|Values                                   |Flags                              |
+-----------------------------------------+-----------------------------------+
|0x006c,0x0072,0x0074,0x0099,0x009a,0x009f|0x00,0x00,0x00,0x00,0x00,0x01      |
|0x009a,0x00a3,0x009f,0x0099,0x00a5,0x00a7|0x00,0x00,0x01,0x00,0x00,0x00      |

Now I need to parse the Flags column, find out which position has flag set to 1 and return that corresponding value. In this case 0x009f for both the rows.
How to do it efficiently using SQL commands? One option could be to convert the 2 columns into 2 tables and then join them by the column number? Anything better? I am not familiar with SQL much. Thanks.


text:
Q: Find all roots for the equation I am trying to solve $2^x = 4x$. Have taken logs on both sides, represented as an exponent and haven't got it close to the form from which I could find a solution.

A: Note you can write $4=2^2$ so that you have $2^x=2^2x$, dividing by $2^2$ you have $2^{x-2}=x$. But this is really as far as this goes since these type of equations require special functions to solve. WolframAlpha gives
$$
x= - \dfrac{W_n\left(-\dfrac{\log 2}{4}\right)}{\log 2}
$$
Note that you can try a few 'nice' solutions and see that $x=4$ works.


text:
Q: StatefulWidgets in ReorderableListView don't keep their state when reordering the list Here I have a trimmed down page which creates a ReorderableListView, which has its body set to two RecipeStepWidgets with UniqueKeys set (I've also tried this with ValueKey and ObjectKey)
import 'package:flutter/material.dart';
import 'consts.dart';
import 'recipeStep.dart';
import 'recipeStepWidget.dart';

class NewRecipePage extends StatefulWidget {
  @override
  _NewRecipePageState createState() => _NewRecipePageState();
}

class _NewRecipePageState extends State<NewRecipePage> {
  final TextEditingController _nameController = TextEditingController();
  @override
  Widget build(BuildContext context) {
    List<RecipeStep> recipeSteps = [];

    List<RecipeStepWidget> stepWidgets = [
      RecipeStepWidget(key: UniqueKey()),
      RecipeStepWidget(key: UniqueKey())
    ];

    void _onReorder(int oldIndex, int newIndex) {
      setState(
        () {
          if (newIndex > oldIndex) {
            newIndex -= 1;
          }

          final RecipeStepWidget item = stepWidgets.removeAt(oldIndex);
          stepWidgets.insert(newIndex, item);
        },
      );
    }

    return Scaffold(
      appBar: AppBar(title: Text("New Recipe")),
      body: Column(
        children: <Widget>[
          Expanded(
            child: ReorderableListView(
              header: Text("Steps"),
              onReorder: _onReorder,
              children: stepWidgets,
            ),
          ),
        ],
      ),
    );
  }
}

The RecipeStepWidget class is (ignoring includes):
class RecipeStepWidget extends StatefulWidget {

  RecipeStepWidget({@required Key key}) : super(key: key);

  _RecipeStepWidgetState createState() => _RecipeStepWidgetState();

}

class _RecipeStepWidgetState extends State<RecipeStepWidget> {
  TextEditingController _controller = TextEditingController();
  TextEditingController _durationLowController = TextEditingController();
  TextEditingController _durationHighController = TextEditingController();
  bool concurrent = false;

  RecipeStep toRecipeStep() {
    return RecipeStep(
      text: _controller.text,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        TextField(
          controller: _controller,
          decoration: InputDecoration(hintText: "Step text"),
        ),
        Row(
          children: <Widget>[
            Text("Duration min: "),
            Container(
              width: 40.0,
              //height: 100.0,
              child: TextField(
                controller: _durationLowController,
                keyboardType: TextInputType.number,
                decoration: InputDecoration(hintText: "0"),
                onChanged: (String val) {
                  if (_durationHighController.text.isEmpty ||
                      int.parse(val) >
                          int.parse(_durationHighController.text)) {
                    _durationHighController.text = val;
                  }
                },
              ),
            ),
            Text(" max: "),
            Container(
              width: 40.0,
              //height: 100.0,
              child: TextField(
                controller: _durationHighController,
                keyboardType: TextInputType.number,
                decoration: InputDecoration(hintText: "0"),
              ),
            ),
          ],
        ),
        Row(
          children: <Widget>[
            Text("Start concurrently with previous step"),
            Checkbox(
                value: concurrent,
                onChanged: (bool val) => {
                      setState(() {
                        concurrent = val;
                      })
                    }),
          ],
        ),
      ],
    );
  }
}

When I edit the textfields or checkboxes in the RecipeStateWidgets and then reorder them within the list by clicking+dragging them, the widgets get reset to their default state.
Does anyone have any ideas why this is happening? I thought that all I had to do in order to get the ReorderableListView to work as intended was to set a key on each of its children. Is that not correct?
Thanks!

A: I think you can use AutomaticKeepAliveClientMixin like so:
class _RecipeStepWidgetState extends State<RecipeStepWidget> with AutomaticKeepAliveClientMixin  {

  @override
  bool get wantKeepAlive => true;

A: Giving the list item a ValueKey seems to fix the problem for me. Hopefully helps in your situation as well.
e.g.
  List<YourModel> _items = [];

  Widget _itemsListWidget() {
    return ReorderableListView(
      onReorder: (oldIndex, newIndex) {
        //
      },
      children: [
        for (int index = 0; index < _items.length; index += 1)
          Text(
            _items[index],
            key: ValueKey(_items[index].id), // <--- This is what you need to add
          ),
      ],
    );
  }


text:
Q: Text in a div that has a opacity of 0.5 I have a div container with text inside it.
The problem is I have the container set to have a opacity of 0.5 and I want the text to be at opacity of 1, but it can't exceed 0.5 because of the div.
I each made it so "p" was set to opacity of 1.0 in the stylesheet, but that still doesn't work.
Any ideas?

A: Use rgba() instead on the container div to set the opacity, as the opacity property is inherited by all children elements, even text nodes, meaning a descendant of any kind can't have a higher opacity than its parent

A: Without seeing your specific situation it's hard to say, but an element can only be as opaque as its parent.
One solution is to have another div that's a child of the div that acts like the one you have now.  Make the the second div position: relative and the transparent one position: absolute; width: 100%; height: 100%;, and it will be transparent in the background.  Other children of the main div can have their full opacity.  They need position: relative so the first div does not cover them.
http://jsfiddle.net/ExplosionPIlls/ngW9m/1/

A: this seems to be working in all browsers i have:
http://css-tricks.com/non-transparent-elements-inside-transparent-elements/


text:
Q: Django Elastic Beanstalk App - Cannot Set Secure Listener Port to 443: LoadBalancerHTTPSPort I'm a pretty new developer and deployed my first Django app via Elastic Beanstalk. I want to serve https requests and have configured my SSL certificate and have my load balancer set up correctly. When I go into EB > Configuration > Secure listener port and set it to 443 I'm getting the error upon saving:
LoadBalancerHTTPSPort: You have specified both the @deprecated(:default.aws:elb:loadbalancer:LoadBalancerHTTPSPort)
    option as well as one in the new aws:elb:listener:443 namespace.
The :default.aws:elb:loadbalancer:LoadBalancerHTTPSPort option will be ignored.

Not sure what I'm missing because I'm still not able to serve https requests

A: I had the same problem with a NodeJS Elastic Beanstalk app. However, I was able to get around it by updating the Listener/Certificate settings via the AWS EC2 console (https://console.aws.amazon.com/ec2/), via the Load Balancers section (under LOAD BALANCING).
I was updating the certificate for a staging version of a cloned environment. This was the only way I could assign a different certificate to the staging environment.
See more at http://docs.aws.amazon.com/elasticloadbalancing/latest/classic/elb-create-https-ssl-load-balancer.html


text:
Q: What does this mean? What does:

let bygones be bygones

and

live and let live

mean?
I read it in the book <<Have Space Suit - Will Travel>>.

A: "Let bygones be bygones" is an idiom that's used when two parties have been in conflict with each other, but decide to let go of the conflict.
"Live and let live" is an idiom that means to live with an attitude of acceptance for other peoples' differences.


text:
Q: Uploading Python Pandas dataframe to MySQL - InternalError: 1366, "Incorrect String Value" I am trying to write a Pandas dataframe into MySQL database, and have used the following code:
engine = sqlalchemy.create_engine("mysql+pymysql://root:password@localhost/skills?charset=utf8mb4")
connection = engine.connect
dataframe.head().to_sql('indeed_resumes', engine, flavor='mysql', if_exists='replace',index=True)

However, I get the following error:
InternalError: (1366, "Incorrect string value: '\\xE1\\xBB\\x99i\\x0AO...' for column 'work' at row 5")

The datatype of the MySQL table is as follows:
 mysql> desc indeed_resumes;
    +-----------+------------+------+-----+---------+-------+
    | Field     | Type       | Null | Key | Default | Extra |
    +-----------+------------+------+-----+---------+-------+
    | index     | bigint(20) | YES  | MUL | NULL    |       |
    | certs     | text       | YES  |     | NULL    |       |
    | contact   | text       | YES  |     | NULL    |       |
    | education | text       | YES  |     | NULL    |       |
    | headline  | text       | YES  |     | NULL    |       |
    | info      | text       | YES  |     | NULL    |       |
    | skills    | text       | YES  |     | NULL    |       |
    | summary   | text       | YES  |     | NULL    |       |
    | updated   | text       | YES  |     | NULL    |       |
    | work      | text       | YES  |     | NULL    |       |
    +-----------+------------+------+-----+---------+-------+
    10 rows in set (0.00 sec)

My data consists of very long strings (sometimes around 3000 characters), so this could be causing the error. Any suggestions?

A: I seem to have resolved this issue. It looks like I also needed to change the database encoding using the following commands.
ALTER DATABASE skills CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
ALTER TABLE indeed_resumes CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

From https://mathiasbynens.be/notes/mysql-utf8mb4:
"Turns out MySQL's utf8 charset only partially implements proper UTF-8 encoding. It can only store UTF-8-encoded symbols that consist of one to three bytes; encoded symbols that take up four bytes aren't supported.
Luckily, MySQL 5.5.3 (released in early 2010) introduced a new encoding called utf8mb4 which maps to proper UTF-8 and thus fully supports Unicode, including astral symbols."


text:
Q: Loading a Ruby file in Windows 7. How do I do this? Loadpath issue? I can't seem to load files. I am using Ruby 2.0.0 x64 and the built in command prompt with Ruby.
I have 2 problems.
1) If I use Powershell or the cmd.exe, I can't access Ruby if I type in irb. Any idea how to connect the two.
2) So instead I use the downloaded command prompt with Ruby. I have a file created called banking.rb. I am trying to load the file so I can test my code. Here is the location of my file:
C:\Users\Jwan\Desktop\Ruby Programs.
When I type in load 'banking.rb', I get this error:
LoadError:  cannot load such file -- banking.rb
    from <irb>:6:in 'load'
    from <irb>:6
    from C:/Ruby200-x64/bin/irb:12:in '<main>'

So my guess is that the ruby loadpath is incorrect? The folder where this file is located is on my desktop. How do I change my loadpath (full disclosure:, please try to dumb down the instructions. I didn't even know what loadpath was prior to this post)

A: Check the Ruby docs for Kernel.load:

Loads and executes the Ruby program in the file filename. If the
  filename does not resolve to an absolute path, the file is searched
  for in the library directories listed in $:.

So you can either type the absolute path
load 'C:\Users\Jwan\Desktop\Ruby Programs\banking.rb'

or modify $:
$: << 'C:\Users\Jwan\Desktop\Ruby Programs'
load 'banking.rb'

$: can also be referenced with $LOAD_PATH. It is the array of directories that Ruby searches for files to load. If you want to permanently add directories to your load path, you can set the RUBYLIB environment variable to a colon-separated list of them (look up how to do this on Windows, it's nestled deep in some menu).


text:
Q: HTML listing product properties I would like to list product properties like the following way:
Property 1:     Item
Property 2:     Item
Property 3:     Item
Property 4432:  Item
Notice that "Item" starts kind of indented.
I know this can be accomplished with using tables and divs. However they seem to be a little bit of a overkill to me. Can someone tell me how this is commonly implemented?
Thanks in advance!

A: A definition list would be appropriate here:

Property

The related item

Property2

The second related item

To make that list display exactly as you show in your question use the following CSS:
dl dt {
    float: left;
    margin: 0 10px 0 0;
}

dl dd + dt, dl dd + dd {
    clear: left
}

dl dd + dd {
    float: none
}

See the jsfiddle here: http://jsfiddle.net/Jolora/N5Zkd/
Alternatively a simple unordered list would produce cleaner code albeit a little less semantic:

Property The related item

Property 2 The related item

The span tags allow you to add CSS to apply the indentation. If no extra than one space indentation is needed then remove the span tags.


text:
Q: Sidebar with 100% height and scrolling content area I'm using Bootstrap Twitter and designed a fluid layout with fixed navbar and footer. But I still need a fixed left sidebar with 100% height and a content area that scrolls if necessary.
I'd like to use the browser's default vertical scrollbar, I mean, I don't want to use overflow-y in my content div. I saw this on some HTML5 websites and I'd like to do the same.
Can you help me?
Here is the code I'm using: http://jsfiddle.net/julianonunes/AhK3c/2/embedded/result/

                Texto

Dashboard

Link

Sidebar

Link

Link

Link

Link

Sidebar

Link

Link

Link

Link

Link

Link

Sidebar

Link

Link

Link

Home  /

Link

Copyright Site 2013.

Thanks.

A: Your footer is not fixed ... but rather pushed to the bottom of page when the content is shorter ("sticky").
To make it actually fixed you need to make it have something like:
  position:fixed;
  width:100%;
  bottom:0;

and the sidebar you can make to something like this, that it always spans between the fixed header and footer (with the top and bottom, you can here make it span the way you want):
  .sidebar-nav {
      position:fixed;
      top:52px;
      bottom:52px;
      width:12%;
  }

here is an update to your jsfiddle

Note: With position set to fixed, the element gets positioned in a similar way to absolute (so you can set its boundaries/span by defining top, bottom, left and right), but instead of being positioned relative to any one of its parent html elements, a fixed element gets positioned relative to the browser window/viewport. Here is quite a good post on the position property, if you want to read some more.

A: Like this - jsFiddle 1
.navbar-fixed-top, #footer, .sidebar-nav{
    position:fixed;
}

.sidebar-nav{
    top:50px;
    bottom:40px;
    overflow-y:scroll;
}

Or like this - jsFiddle 2
.navbar-fixed-top, #footer{
    position:fixed;
}

.sidebar-nav{
    position:relative;
    margin-bottom:60px;
}

#footer {
    height: 60px;
    width:100%;
    bottom:0px;
}

These will likely need a little fine tuning, you seem to be using a lot of external resources that are effecting your layout. You may want to consider simplifying a bit.


text:
Q: Mandrill — How to format complex data for handlebars templates I am trying to send a templated email via Mandrill but am having issues with the templates picking up the data I am sending.
The docs say that I need to convert my data to arrays of [{ name: 'propertyName', content: 'the content' }]
The example they give is as follows
Data
"global_merge_vars": [
  {
    "name": "user_name",
    "content": "Mandrill_User1"
  }
]

Template

Thanks for registering! Your username is {{user_name}}.

Result

Thanks for registering! Your username is Mandrill_User1.

In my case the data is more complex.
I have something like
{
  "firstname": "Tyler",
  "lastname": "Durden",
  "fullname": "Tyler Durden",
  "email": "tyler.durden@testy.tes",
  "company": {
    "name": "Company 1",
    "role": {
      "slug": "supplier",
      "name": "Supplier"
    }
  }
}

which I convert to name:content pairs as follows, to send as the global_merge_vars
[
   { name: 'firstname', content: 'Tyler' },
  { name: 'lastname', content: 'Durden' },
  { name: 'fullname', content: 'Tyler Durden' },
  { name: 'email', content: 'tyler.durden@testy.tes' },
  {
    name: 'company',
    content: [
      { name: 'name', content: 'Company 1' },
      {
        name: 'role',
        content: [
          { name: 'slug', content: 'supplier' },
          { name: 'name', content: 'Supplier' }
        ]
      }
    ]
  }
]

And my template is
Subject
Dear {{user.firstname}} {{company.name}} has been approved.

Body

Dear {{user.firstname}},

Your company {{company.name}} has been approved.

But the result is
Subject
Dear has been approved.
Body

Dear ,

Your company  has been approved.

I have set up Mandrill to use handlebars as its template language.
What am I missing?

A: After some trial and error I have worked this out.  It turns out only the top level object needs to be turned into a name, content pair. The lower order object structure can stay as a normal JSON object.
So
{
  "name": "user"
  "content": {
    "firstname": "Tyler",
    "lastname": "Durden",
    "fullname": "Tyler Durden",
    "email": "tyler.durden@testy.tes",
    "company": {
      "name": "Company 1",
      "role": {
        "slug": "supplier",
        "name": "Supplier"
      }
    }
  }
}

with template subject: Hello {{user.firstname}}
and body

Dear {{user.firstname}},

Your company {{user.company.name}} has been approved.

Works fine.
The docs were a bit misleading in this regard.


text:
Q: Using LINQ expression to get previous element from a collection I need to write a LINQ expression based on the following scenario:
public class Meeting
{
   public int Id { get; set; }
   public DateTime Date { get; set; }
   public bool Selected { get; set; }
}

List<Meeting> Meetings

Using LINQ expression, how to retrieve the metting occurring just before the first one which is selected ?
For example in the liste below I need to retrieve the meeting Id 2.

*

*Id:1 Date:11/1 Selected: false

*Id:2 Date:12/1 Selected: false

*Id:3 Date:13/1 Selected: true

*Id:4 Date:14/1 Selected: true

A: You could use TakeWhile and LastOrDefault:
var meeting = Meetings.TakeWhile(m => !m.Selected)
                      .LastOrDefault();

if (meeting != null)
{
    // Use the meeting
}
else
{
    // The first meeting was selected, or there are no meetings
}

TakeWhile basically stops when it hits the first item that doesn't match the predicate - it's like a Where that stops early, in other words.
You need to be careful with ordering though - you're pretty much assuming there's a bunch of unselected meetings, followed by selected ones.

A: You could use TakeWhile and LastOrDefault.
Meetings.TakeWhile(m => !m.Selected).LastOrDefault()


text:
Q: Populate TableLayout with android:layout_weight programmatically I am trying to populate a tablelayout with cells and rows stretches to fill the whole screen. Like this:
http://imageshack.us/photo/my-images/69/device20120201005942.png/
This layout designed in Graphical Layout window in Eclipse gives what I want (android:layout_weight solves vertical stretching):
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_gravity="center"
    android:stretchColumns="*" >

    <TableRow
        android:id="@+id/tableRow1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center" android:layout_weight="1">

        <ImageView
            android:id="@+id/imageView1"
            android:layout_gravity="center"
            android:src="@drawable/add" />
        <ImageView
            android:id="@+id/imageView2"
            android:layout_gravity="center"
            android:src="@drawable/bound" />
        <ImageView
            android:id="@+id/imageView3"
            android:layout_gravity="center"
            android:src="@drawable/cod" />
    </TableRow>

    <TableRow
        android:id="@+id/tableRow2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="1" >

    <ImageView
        android:id="@+id/imageView4"
        android:layout_gravity="center"
        android:src="@drawable/delete" />
    <ImageView
        android:id="@+id/imageView5"
        android:layout_gravity="center"
        android:src="@drawable/delete2" />
    <ImageView
        android:id="@+id/imageView6"
        android:layout_gravity="center"
        android:src="@drawable/floppy" />
    </TableRow>
</TableLayout>

I am trying to create the same look within code but failed so far. Here is the oncreate of my Activity:
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.tablelo);

    TableLayout tl = (TableLayout) findViewById(R.id.table);
    Log.d(TAG, "Width :" + tl.getWidth());
    for (int row = 0; row < 3; row++) {
        TableRow tr = new TableRow(this);
        tr.setId(100 + row);

        for (int cell = 0; cell < 3; cell++) {
            ImageView image = new ImageView(this);
            image.setImageResource(imageIDs[row * 3 + cell]);
            tr.addView(image);
        }

        tr.setGravity(Gravity.CENTER);
        LayoutParams params = new TableRow.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 1);

        tr.setLayoutParams(params);

        tl.addView(tr, params);
    }
    tl.setStretchAllColumns(true);
}

I am missing the code to set ImageView gravity, but this attemp causes crash:
image.setLayoutParams(new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER));

This code results 3 rows created, each stretch horizontally but not vertically:
http://imageshack.us/photo/my-images/835/gridc.png/
I can not find what I am missing here. I also tried to prepare a tablerow  in designer and inflate and add to table during runtime but result did not change.
So, somehow, I want to get programmatically the same layout that I could created with editor .
Help, please!

A: I've spent an hour and a half trying to figure out what was going on. And then I found it :) Here's a complete listing of my TableActivity, please note the usage of different LayoutParams for table rows and images:
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.widget.*;
import android.widget.TableLayout;
import android.widget.TableRow;

public class TableActivity extends Activity {

    private static final String TAG="TableActivity";

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.table_activity);

        TableLayout tl = (TableLayout) findViewById(R.id.table);
        Log.d(TAG, "Width :" + tl.getWidth());

        for (int row = 0; row < 3; row++) {
            TableRow tr = new TableRow(this);
            tr.setId(100 + row);

            //Note that you must use TableLayout.LayoutParams,
            //since the parent of this TableRow is a TableLayout
            TableLayout.LayoutParams params = new TableLayout.LayoutParams(
                    TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT, 1f);

            for (int cell = 0; cell < 3; cell++) {
                ImageView image = new ImageView(this);
                image.setImageResource(android.R.drawable.btn_plus);
                //Note that here you must use TableRow.LayoutParams
                //since TableRow is the parent of this ImageView
                TableRow.LayoutParams imageParams = new TableRow.LayoutParams();

                //And this is how you set the gravity:
                imageParams.gravity = Gravity.CENTER;
                image.setLayoutParams(imageParams);
                tr.addView(image);
            }
            tr.setLayoutParams(params);
            tl.addView(tr, params);
        }
        tl.setStretchAllColumns(true);
    }
}

table_activity.xml is just an empty table layout:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
         android:id="@+id/table"
          android:layout_width="match_parent"
          android:layout_height="match_parent">
</TableLayout>

So to put it short, the simplest solution would be to use layouts defined in xml files :) But if you have to use JAVA, you must be careful with what king of LayoutParams you are using, you should always use the one of a view's parent.


text:
Q: Completely close speech recognizer I need to use Speech Recognition for file browsing, using command "show numbers". I want Speech Recognizer to start when I open folder browser dialog, and when the browser dialog window closes, I want Speech Recognizer to close. How can I completely close speech recognizer using C# in code-behind ?
EDIT:
I have found "ugly" solution for my problem: to kill sapisvr.exe

A: Why do you want to completely close WSR?  It takes a fair amount of time to start up and shut down.  It's possible to make WSR stop listening by CoCreateing the shared recognizer instance (CLSID_SpSharedRecognizer), and then setting the recognizer state to SPRST_INACTIVE.  That's much faster.

A: Your other option is to use an inproc SpeechRecognitionEngine.
Create the engine and load an appropriate grammar (even if it's just the dictation grammar), and then call Recognize() as long as the file browser dialog is open.
Something like this (spitballing, not copied from VS):
// This goes in your application initialization code
var engine = new SpeechRecognitionEngine();
// Set event handlers here...
// Load grammar here...

// This goes in your code where you open the dialog and want
// speech recognition
while (isFileDialogOpen) {
    engine.Recognize(); // It's probably not called 'engine' in your code ;)
}

If you only want to do one and only one recognition, you can leave out the while loop and call Recognize bare, but I wouldn't recommend it unless the room is perfectly silent and you don't mutter to yourself.

A: This is what I used:
Process[] processes = Process.GetProcessesByName("sapisvr");
foreach (var process in processes)
    {
        process.Kill();
    }


text:
Q: List View on binding context change empties the button text I have been facing this weird behaviour for a while now and I am unable to understand what exactly is causing the problem.
I am using FreshMvvm and I have a ListView with two buttons inside of it.
Now the problem is one of the buttons gets its text from Binding, Secondly to assign the button with a click command I had to follow this.
Now after adding this, the click event works perfectly but the text binding is not working I suspected this happened because of binding context change which I am sure is the whole reason but I am not able to find a way to fix this my listview code is as follows:
<ListView Grid.Row="1"
          ItemsSource="{Binding CategoryAndActivities}"
          x:Name="WishListName"
          HorizontalOptions="FillAndExpand"
          VerticalOptions="FillAndExpand" >
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                    <Frame>
                        <Grid VerticalOptions="FillAndExpand"
                              HorizontalOptions="FillAndExpand">
                            <Grid.RowDefinitions>
                                <RowDefinition Height="Auto" />
                                <RowDefinition Height="*" />
                                <RowDefinition Height="Auto" />
                            </Grid.RowDefinitions>
                            <!--Image and Title-->
                            <AbsoluteLayout Grid.Row="0"
                                            HeightRequest="70"
                                            IsClippedToBounds = "true">
                                <ffimageloading:CachedImage Source="{Binding ActivityImage}"
                                                            Aspect="AspectFill"
                                                            AbsoluteLayout.LayoutFlags="All"
                                                            AbsoluteLayout.LayoutBounds="0.0, 0.0, 0.3, 0.85"
                                                            Margin="5, 0, 5, 5"
                                                            ErrorPlaceholder="nopreviewlandscape"
                                                            LoadingPlaceholder="loadingicon"/>
                                <Label x:Name="ActivityNameLabel"
                                       Text="{Binding ActivityName}"
                                       FontAttributes="Bold"
                                       VerticalTextAlignment="Start"
                                       TextColor="{StaticResource price_text_color}"
                                       FontSize="Small"
                                       AbsoluteLayout.LayoutFlags="All"
                                       AbsoluteLayout.LayoutBounds="1.0, 0.0, 0.7, 0.85"
                                       Margin="5, 5, 5, 5">
                                </Label>
                            </AbsoluteLayout>
                            <!--Descp-->
                            <StackLayout Grid.Row = "1"
                                         IsClippedToBounds="true">
                                <Label Text="{Binding AcitivityDescription}"
                                       FontSize="Small"
                                       LineBreakMode="WordWrap"
                                       Margin="5, 0, 5, 5"/>
                            </StackLayout>
                            <Grid BackgroundColor="White"
                                  Grid.Row = "2"
                                  VerticalOptions="FillAndExpand"
                                  HorizontalOptions="FillAndExpand">
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="50*"/>
                                    <ColumnDefinition Width="50*"/>
                                </Grid.ColumnDefinitions>

                                <Button BackgroundColor="{StaticResource ColorBrandingYellow}"
                                        HorizontalOptions="FillAndExpand"
                                        Command="{Binding AddToWishListCommand}"
                                        Grid.Column="0"
                                        BindingContext="{Binding Source={x:Reference ListName}, Path=BindingContext}"
                                        CommandParameter="{Binding Source={x:Reference ActivityNameLabel},Path=BindingContext}"
                                        TextColor="Black"
                                        Text="{resourceLocal:Translate addToWishlist}"
                                        FontSize = "Small" />
                                <Button BackgroundColor="{StaticResource ColorBrandingYellow}"
                                        HorizontalOptions="FillAndExpand"
                                        Grid.Column="1"
                                        TextColor="Black"
                                        Text="{Binding ActivityAmount}"
                                        FontSize = "Small"
                                        Command="{Binding GoFeatureActivityDetail}"
                                        BindingContext="{Binding Source={x:Reference ListName}, Path=BindingContext}"
                                        CommandParameter="{Binding Source={x:Reference ActivityNameLabel},Path=BindingContext}"/>
                            </Grid>
                        </Grid>
                    </Frame>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

The problem is in the button with binding as text what happems is the text just show empty even though the data actually exist.
The Click event code is as follows:
public ICommand GoFeatureActivityDetail { get; set; }

public BrowseFeaturesPageModel()
{
    AddToWishListCommand = new Command(WishListCommand);
    GoFeatureActivityDetail = new Command(FeatureActivityDetailCommand);
}

private async void FeatureActivityDetailCommand(object obj)
{}

A: Right thinking, bad implementation.
What's going on here is that you've changed the Button's BindingContext and now it's not anymore able to "see" the ActivityAmount property of the item 'cause it's 'looking' to the BrowseFeaturesPageModel object.
You can keep the things simpler, changing the BindingContext only where you'll use, not the whole View (the button in this case):
<Button BackgroundColor="{StaticResource ColorBrandingYellow}"
        HorizontalOptions="FillAndExpand"
        Grid.Column="1"
        TextColor="Black"
        Text="{Binding ActivityAmount}"
        FontSize = "Small"
        Command="{Binding BindingContext.GoFeatureActivityDetail, Source={x:Reference ListName}}"
        CommandParameter="{Binding .}"/>


text:
Q: Python two variables are the same but python doesnt think that they are I am making a program which has a login; it checks the input against the user's input. However, it won't accept that they have entered the correct password, even when it is correct:
for i in range(5):
    existingUsername = input("What is your user name?")
    if existingUsername in open('logins.txt').read():
        with open("logins.txt", "r") as myFile:
            for num, line in enumerate(myFile, 1):
                if existingUsername in line:
                    passwordLine = num + 1
                    passwordAttempt = input(str("What is your password?"))
                    passwordText = linecache.getline("logins.txt", passwordLine)
                    if passwordAttempt == passwordText:
                        print("That is correct")
                        quizSelection()
                        break
                    else:
                        print("That doesn't seem to match. Please try again")

The text file it references only has Har16 and Google in it, on separate lines with Har16 at the top

A: When you run passwordText = linecache.getline("logins.txt", passwordLine), if your file has multiple lines, it may return the string with \n at the end.


text:
Q: How is this algorithm working?! Can someone explain it to me please..have an interview tomorrow def sum_in(numbers, sum_):
    """whether any two numbers from `numbers` form `sum_`."""
    return any((sum_-n) in numbers for n in numbers)

It basically takes a list, and checks if any two numbers from it form a sum equalling sum_. I can't seem to get how that sum_-n verifies that TWO numbers equal the sum. Wouldn't it just be checking with one n each loop?!

A: It's checking sum_-n is in numbers.  If it is, then that number + n = sum_.

A: For each iteration, a bool is generated whether (sum_ -  n) is in the set of numbers. If one of these bools is True, the function returns True. It returns False otherwise, clearly.
This is not a great algorithm, to put it mildly.
Consider:
sum_in((3,), 6)

This will return True. Why? Because 6 - 3 is in numbers.
So yes, it is only checking one value in each iteration.
Good luck with the interview!


text:
Q: Marketing Cloud sFTP to vendor issue We are trying to use Marketing Cloud to drop a file onto a vendors sFTP site. We have username and password etc and can make the connection from home, Starbucks or any network except where we work.
Our employer heavily restricts access to network ports, as you'd expect, but our thought was that if we are going to the vendor from SFMC how is the security on our internal network causing the blackout?

A: The SFTP connection from SFMC is happening directly to the "receiving end". Hence your local network policies don't have any impact on this.
To be on the safe side, please ask the vendor to whitelist the FTP IP addresses, which you can find here. This is probably not an issue in your case, since you can connect to the vendor's FTP from any other location.


text:
Q: Is possible create map html area in percentage? I need to create something like this:
http://www.mrporter.com/journal/journal_issue71/2#2
where every product in my big image is associated with a tooltip which appears on mouse hover.
But I need this to work with fullscreen images.
The first solution I thought (as the example above) is the map html solution where each  fill up exactly the boundaries of my products.
The problem is that I can't indicate precise values for my  because my image size depends on window screen.
The best solution would be the possibility to set percentage values for my area.
Is this possible? Any other suggestions ?

A: There is a jQuery plugin for this jQuery RWD Image Maps.
You might want to integrate my pending pull request (manually) to support "width=100%": https://github.com/stowball/jQuery-rwdImageMaps/pull/10

A: you can check this this plugin is life saving.
Useful when you want to map a percentage scaled image etc.
It can be used with or without jQuery.
https://github.com/davidjbradshaw/imagemap-resizer
and you can see it working at.
http://davidjbradshaw.com/imagemap-resizer/example/

A: Because this can't be done with simple HTML/CSS manipulation, the only alternative is JavaScript to, effectively, recalculate the coordinates based on the resizing of the image. To this end I've put together a function (though there's two functions involved) that achieves this end:
function findSizes(el, src) {
    if (!el || !src) {
        return false;
    }
    else {
        var wGCS = window.getComputedStyle,
            pI = parseInt,
            dimensions = {};
        dimensions.actualWidth = pI(wGCS(el, null).width.replace('px', ''), 10);
        var newImg = document.createElement('img');
        newImg.src = src;
        newImg.style.position = 'absolute';
        newImg.style.left = '-10000px';
        document.body.appendChild(newImg);
        dimensions.originalWidth = newImg.width;
        document.body.removeChild(newImg);
        return dimensions;
    }
}

function remap(imgElem) {
    if (!imgElem) {
        return false;
    }
    else {
        var mapName = imgElem
            .getAttribute('usemap')
            .substring(1),
            map = document.getElementsByName(mapName)[0],
            areas = map.getElementsByTagName('area'),
            imgSrc = imgElem.src,
            sizes = findSizes(imgElem, imgSrc),
            currentWidth = sizes.actualWidth,
            originalWidth = sizes.originalWidth,
            multiplier = currentWidth / originalWidth,
            newCoords;

        for (var i = 0, len = areas.length; i < len; i++) {
            newCoords = areas[i]
                .getAttribute('coords')
                .replace(/(\d+)/g,function(a){
                    return Math.round(a * multiplier);
                });
            areas[i].setAttribute('coords',newCoords);
        }
    }
}

var imgElement = document.getElementsByTagName('img')[0];

remap(imgElement);

JS Fiddle demo.
Please note, though, that this requires a browser that implements window.getComputedStyle() (most current browsers, but only in IE from version 9, and above). Also, there are no sanity checks other than ensuring the required arguments are passed into the functions. These should, though, be a start if you want to experiment.
References:

*

*document.body.

*document.createElement().

*document.getElementsByName().

*document.getElementsByTagName().

*element.getAttribute().

*element.setAttribute().

*element.style.

*Math.round().

*node.appendChild().

*node.removeChild().

*parseInt().

*string.replace().

*string.substring().

*window.getComputedStyle.

A: Alternative solution using links:
CSS:
.image{
  position: relative;
}
.image a{
  display: block;
  position: absolute;
}

HTML:

Percentage dimensions can be detected in graphic editors

A: Percentages in image maps are not an option. You might want to get some scripting involved (JS) that recalculates the exact position on images resize. Of course, in that script you can work with percentages if you want.

A: Consider using the Raphaël JavaScript Library with some CSS. See http://raphaeljs.com/ and Drawing over an image using Raphael.js.

A: I know this is an old question but maybe someone needs this at some point as I did. I modified @David Thomas' answer a bit to be have this little piece of JS be able to handle future recalculations:
function findSizes(el, src) {
    if (!el || !src) {
        return false;
    }
    else {
        var wGCS = window.getComputedStyle,
        pI = parseInt,
        dimensions = {};
        dimensions.actualWidth = pI(wGCS(el, null).width.replace('px', ''), 10);
        var newImg = document.createElement('img');
        newImg.src = src;
        newImg.style.position = 'absolute';
        newImg.style.left = '-10000px';
        document.body.appendChild(newImg);
        dimensions.originalWidth = newImg.width;
        document.body.removeChild(newImg);
        return dimensions;
    }
}

function remap(imgElem) {
    if (!imgElem) {
        return false;
    }
    else {
        var mapName = imgElem
        .getAttribute('usemap')
        .substring(1),
        map = document.getElementsByName(mapName)[0],
        areas = map.getElementsByTagName('area'),
        imgSrc = imgElem.src,
        sizes = findSizes(imgElem, imgSrc),
        currentWidth = sizes.actualWidth,
        originalWidth = sizes.originalWidth,
        multiplier = currentWidth / originalWidth,
        newCoords;

        for (var i = 0, len = areas.length; i < len; i++) {
            // Save original coordinates for future use
            var originalCoords = areas[i].getAttribute('data-original-coords');
            if (originalCoords == undefined) {
                originalCoords = areas[i].getAttribute('coords');
                areas[i].setAttribute('data-original-coords', originalCoords);
            }

            newCoords = originalCoords.replace(/(\d+)/g,function(a){
                return Math.round(a * multiplier);
            });
            areas[i].setAttribute('coords',newCoords);
        }
    }
}

function remapImage() {
    var imgElement = document.getElementsByTagName('img')[0];
    remap(imgElement);
}

// Add a window resize event listener
var addEvent = function(object, type, callback) {
    if (object == null || typeof(object) == 'undefined') return;
    if (object.addEventListener) {
        object.addEventListener(type, callback, false);
    } else if (object.attachEvent) {
        object.attachEvent("on" + type, callback);
    } else {
        object["on"+type] = callback;
    }
};

addEvent(window, "resize", remapImage);


text:
Q: How sensitive is DeviceOrientation when browsing the web on Mobile in a handheld context I'd like to determine the chances or prospects of reading a mobile device's orientation using the DeviceOrientation Javascript API (not orientationchange) when loading a web page.
Unless I am mistaken, the W3C specs indicate the DeviceOrientation properties can only be read during an event trigger. i.e. The initial states are not exposed if the device is not moving at all.
If so, is DeviceOrientation sensitive enough to read a value in most common cases where the device is held by hand(s), while the user wait for a page load, assuming very subtle hand/motion tilts.

A: After testing on actual devices, I am noticing that the device orientation is quite sensitive. For my initial use case anyway. It's sensitive enough that it almost always fire, reporting alpha, beta and gamma value that are not all 0 when using any mobile browser (phone or tablet) that support the DeviceOrientation API, not matter how you use it (even if it sits on a table).
The drawback is that the ondeviceorientation event only fires after window.load on Webkit/Blink. Or about 25ms to 100ms after the window load event, varying upon browsers and devices. While Firefox fires the event early at the interactive state of the document before DOMContentLoaded.
So it seems impossible to start rendering a web page in the context of the initial device's rotation for lack of early detection capabilities. That's a significant flaw of the current DeviceOrientation API.


text:
Q: Redirect to OAuth url google+ I have created two files that I run using xampp on localhost.
The first file is my .php file that acts as a server as describe in the google+ api docs for server side authentication:
<?php
    set_include_path("Google" . PATH_SEPARATOR . get_include_path());
    require_once 'Google/Client.php';
    require_once 'Google/Auth/OAuth2.php';
    require_once 'Google/Service/Plus.php';
    require_once 'Google/Http/Request.php';

    $client = new Google_Client();
    $client->setClientId("...");
    $client->setClientSecret("...");
    $client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
    $client->setAccessType("offline");
    $client->setApplicationName('app');
    $client->setDeveloperKey('...');
    $client->setScopes("https://www.googleapis.com/auth/plus.login");
    $client->setApprovalPrompt('auto');

    session_start();
    if (isset($_GET['logout'])) {
        unset($_SESSION['access_token']);
        die;
    }

    if (isset($_GET['code'])) {
        $client->authenticate($_GET['code']);
        $_SESSION['access_token'] = $client->getAccessToken();
        $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
        header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
    }

    if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
        $client->setAccessToken($_SESSION['access_token']);
    }

    if (!$client->getAccessToken()) {
        $authUrl = $client->createAuthUrl();
        header("Location: ".$authUrl);
        die;
    }

    echo 'Successful';
?>

In the above, it is supposed to "redirect" the client to $authUrl if no accessToken exists. However, it does NOT redirect them at all. If I echo a link with the url & click it, then it works just fine.
My HTML page looks like:

        <title>Test Page</title>

        <button id='signInBtn' class="g-signin"
            data-scope="https://www.googleapis.com/auth/plus.login"
            data-clientid="...."
            data-callback="onSignInCallback"
            data-theme="dark"
            data-redirecturi="postmessage"
            data-accesstype="offline"
            data-approvalprompt="auto"
            data-cookiepolicy="single_host_origin"
            data-requestvisibleactions="http://schemas.google.com/AddActivity"
            data-width="wide">
        </button>

Did I do something wrong? Why does it not redirect them to the url so they can "accept"?


text:
Q: android adb frequently disconnects from eclipse? My android adb automatically disconnects from eclipse,every time i need to reset adb from ddms manager setting it is very hectic during project development.

A: You can try this restart the adb server. or, kill the adb server and restart the eclipse.
c:>adb kill-server
Restarting the eclipse will start the adb server.


text:
Q: InitBinder is not called/Invoked I have radio  button on JSP Page.
<form:form  modelAttribute="obj" action="save">
    <form:radiobuttons path="person" items="${List}"/>

<form:button>Save</form:button>
</form:form>

List : List of person Objects
Obj :
Class obj{
     Person person;
     getter/setters
}

In that JSP, i have to append person when particular radio button selected.
On Controller side
    @RequestMapping(value = "/save", method = RequestMethod.POST)
        public String postProcess(@ModelAttribute("obj") Obj obj,BindingResult error) {

            //processing
            return "anotherJsp";
        }

     @InitBinder
     public void initBinder(WebDataBinder binder, Locale locale, HttpServletRequest request) {
    binder.registerCustomEditor(Obj.class,"person", new PropertyEditorSupport() {
        @Override
        public void setAsText(String text) {
            //processing for conversion of person object String to Person Object
            setValue(text);
        }
    });
}

Here i am using initbinder,because i am getting person object string from jsp...So i am getting binding exception that can not convert from String to Person.
InitBinder is called before when binding data to modelAttribute.Hence in initbinder i will conver string to Person object.
Here The main problem is That My InitBinder in Not called/Invoked.
please give me solution.
Thank you.

A: Please check whether it is getting called by putting breakpoints or debug statements.
Your model attribute is named "obj". But in propertyeditor you've used "person" as property path.
Please try using "obj" as propertyPath or remove that parameter and use this signature.
registerCustomEditor(Class requiredType, PropertyEditor propertyEditor)
Hope it helps.

A: Wild stab in the dark, is it importing the correct @InitBinder from org.springframework.web.bind.annotation?


text:
Q: rake aborted! ActiveRecord::RecordInvalid: Validation failed: Email can't be blank, Password can't be blank I am getting an error while doing
heroku run rake db:seed

rake aborted!
  ActiveRecord::RecordInvalid: Validation failed: Email can't be blank, Password can't be blank

I am using a rails composer app with Devise gem.
Any suggestions?!


text:
Q: Node.js how to get path between host and a filename? I am struggling with this one.. I want to get the path between hostname and filename:
http://host.com/this/is/what/i/want/file.jpg
Method should return "this/is/what/i/want".
I was looking at the URL module but can't find the right property.
url.parse(host).pathname

returns the whole path but with the filename :(.
Thanks in advance,

A: This requires the path and url built-in node modules.
var path = require("path"),
    url = require("url"),
    myUrl = "http://host.com/this/is/what/i/want/file.jpg",
    dir = path.dirname(url.parse(myUrl).pathname);

console.log(dir); // -> /this/is/what/i/want

A: You can do substring with the full pathname info you have
var pathname = url.parse(host).pathname;
pathname = pathnam.substring(0,pathname.lastIndexOf("/"));


text:
Q: Application didn't launch when I create a Button in java I've a strange problem. I explain after this :
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    // final Button buttonAlpha = (Button) findViewById(R.id.Alphabet);

}

Look you see, I put in comments the buttonAlpha and the launching of application works perfectly but when I remove the comments, my app didn't launching and I've no idea why. If somebody have/had the same problem, can I help me please ?

A: You need to put
final Button buttonAlpha = (Button) findViewById(R.id.Alphabet);

inside a method or else it will try to run it before running onCreate(), hence before setContentView()
  public class MainActivity extends Activity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final Button buttonAlpha = (Button) findViewById(R.id.Alphabet);
  }


text:
Q: createNotFoundException is not working in symfony I'm using symfony 3.2. I don't know what happened here when I link the page in to this one
hello_dev.com/app_dev.php/portal/68/facilities/120

I get this kind of 500 http error

but when I link this to this one
hello_dev.com/app_dev.php/portal/68/facilities/119

I get this error page which is correct

If you notice it, I change only the id of the facility 120 to 119. All want is the same error 404 page. Do I miss something about the setup in symfony? And here is the code of my backend. It just simple action code.
/**
     * @Route("/{transactionId}/facilities/{transactionFacilityId}", name="portal_get_facility")
     * @param Request $request
     * @throws \RangeException
     * @throws QueryException
     * @return Response
     */
    public function getFacilityAction(Request $request) {
            throw $this->createNotFoundException('Invalid facility');
     }


text:
Q: How are WordPress draft previews generated? I'm trying to troubleshoot page previews in WordPress. I can't entirely figure out how they work. But I do know:

*

*The preview ID and preview nonce uniquely identify the preview and indicate where to pull the preview data from.

*The preview data is not pulled from the database since it doesn't use the stored data but data inputted into page edit fields.

*The preview data is not stored in $_GET because the GET parameters don't include all the data.
So is the preview data pulled from $_SESSION or some other part of the database? How does WordPress get from the form fields in the editor to the actual preview page?

A: Yes, this one is a duplicate of this post.
I will provide little different examination mechanism.
You use wp cli export before and after you preview the minimal asdf post.
wp export

You don't save anything, you just preview.

Make sure you have super big autosave interval.
  define( 'AUTOSAVE_INTERVAL', 1000000 );
  The default interval is 60 seconds.

After that, you use the diff command tool to check the two xml files.
wp export will return XML files.
diff *.xml

I will get the idea this is a post (state draft) without the title with the content of asdf.
> <item>
>   <title/>
>   <link>http://test100.com/?p=1705</link>
>   <pubDate>Mon, 30 Nov -0001 00:00:00 +0000</pubDate>
>   <dc:creator>admin</dc:creator>
>   <guid isPermaLink="false">http://test100.com/?p=1705</guid>
>   <description/>
>   <content:encoded><![CDATA[asdf]]></content:encoded>
>   <excerpt:encoded><![CDATA[]]></excerpt:encoded>
>   <wp:post_id>1705</wp:post_id>
>   <wp:post_date>2016-12-23 01:03:44</wp:post_date>
>   <wp:post_date_gmt>0000-00-00 00:00:00</wp:post_date_gmt>
>   <wp:comment_status>open</wp:comment_status>
>   <wp:ping_status>open</wp:ping_status>
>   <wp:post_name/>
>   <wp:status>draft</wp:status>
>   <wp:post_parent>0</wp:post_parent>
>   <wp:menu_order>0</wp:menu_order>
>   <wp:post_type>post</wp:post_type>
>   <wp:post_password/>
>   <wp:is_sticky>0</wp:is_sticky>
>   <category domain="category" nicename="uncategorized"><![CDATA[Uncategorized]]></category>
>   <wp:postmeta>
>     <wp:meta_key>_edit_last</wp:meta_key>
>     <wp:meta_value><![CDATA[1]]></wp:meta_value>
>   </wp:postmeta>
> </item>

So just for the preview WordPress created the draft post. In our case ?p=1705, means the post ID will be 1705.
Hope you like this explanation.
In WordPress, there are no PHP sessions.


text:
Q: PL/SQL Execute immediate how to use bind variables after "using" Parameters coming my function starts with "p_" so i'm trying to get colum names from table and changed them to (p_city,p_number,p_country) for to use it in after "using clause"
simple ex:
execute immediate insert into ADDRESS values(:city,:number,:country) using p_city,p_number,p_country;

 for i in 1 .. v_max loop
    select t.column_name
      into v_column_name
      from user_tab_columns t
     where table_name = 'ADDRESS'
       and t.column_id = i;

    if i = v_max then
      v_values := v_values || ':' || v_column_name || ')';
      v_params := v_params || 'p_' || v_column_name;
    else
      v_values := v_values || ':' || v_column_name || ',';

      v_params := v_params || 'p_' || v_column_name || ',';
      end if;
    end if;

  end loop;

  dbms_output.put_line(v_values);
  --VALUES (:city,:number,:country)      //v_values output
  dbms_output.put_line('v_params ' || v_params);
  --p_CITY,p_NUMBER,p_COUNTRY    //v_params output
  sql_stmt := 'INSERT INTO ' || v_table_name || v_values;
  dbms_output.put_line(sql_stmt);
  --INSERT INTO ADDRESS VALUES (:city,:number,:country)  //sql_stmt output

  //error comes from here : Not all variables bound.
. execute immediate sql_stmt  using v_params;
  //sql_stmt working good but , after "using" i can't bind variable like this.

A: 'execute immediate' needs to know how many bind variables are going to be used.  If you know an upper limit, then you can mimic this kind of operation.  Let says you have 7 "true" bind variables to use, but you know that you'll have at most 10.
You build the following SQL
insert into TARGET_TABLE ( col1, col2, ...., col7)
select :1, :2, :3, :4, :5, :6, :7
from dual
where :8 is null
or :9 is null
or :10 is null

which can then be run as:
execute immediate my_sql
using :myval1, :myval2, :myval3, :myval4, :myval5, :myval6, :myval7, null, null, null;

That way, the number of binds is fixed at your upper limit (10), and you just augment the true values with as many nulls as you need.


text:
Q: replace content of multiple Files with PowerShell I'm trying to replace a certain Line in multiple logonscripts (>2000 Scripts).
The script works in the current form, but it writes every file to the disk, even when no changes are made, but I don't want this behaviour. It only should write to the disk, if changes are made.
This is what I already have:
$varFiles = Get-ChildItem $varPath*.$VarEnding
foreach ($file in $varFiles)
{
    (Get-Content $file) |
    Foreach-Object { $_ -replace [regex]::Escape("$varFind"), "$varReplace" } |
    Set-Content $file
}

And this is what I already tried, but it seems, that it is not possible to use if in piped commands:
$varFiles = Get-ChildItem $varPath*.$VarEnding
foreach ($file in $varFiles)
{
    $control = $file
    (Get-Content $file) |
    Foreach-Object { $_ -replace [regex]::Escape("$varFind"), "$varReplace" } |
    If($control -ne $file){Set-Content $file}
}

The variables $varPath, $varEnding, $varFind and $varReplace are defined by a few Read-Host commands at the start of the script.
I hope you guys can help me :)

A: For simplicity and speed - although at the expense of memory use - I'd simply cache and operate on whole input files (requires PowerShell v3+, due to use of -Raw[1]); since logon scripts are generally small, this should be acceptable:
$varFindEscaped = [regex]::Escape($varFind)
$varReplaceEscaped = $varReplace -replace '\$', '$$$$'

foreach ($file in Get-ChildItem $varPath*$varEnding) {
  $contentBefore = Get-Content -Raw $file
  $contentAfter = $contentBefore -replace $varFindEscaped, $varReplaceEscaped
  if ($contentBefore -ne $contentAfter) {
    Set-Content $file $contentAfter
  }
}

*

*To improve performance I've moved escaping of the -regex operands outside the loop.

*

*Note that I'm also escaping $ instances in the replacement value to prevent their interpretation as references to what was matched, such as $& to refer to the entire match.

*Note that Set-Content by default uses the system's default code page rather than UTF-8 encoding.

[1]
In PS v2, you may omit -Raw, which turns $contentBefore into an array of strings (lines) on whose elements -replace then operates individually (as in the OP's approach). While probably slightly slower, it does have the advantage of performing the substitution on individual lines only rather than potentially across multiple lines.


text:
Q: PCB Design on width I would like to construct a 25A on board. How much mil or mm should I use for wire width? I have search for it size shown that 300mil/7.62mm for 10A.

A: There are several factors that need to be considered as it can depend on the number of layers you have on the PCBA that you can allot to the traces as well as the copper weight,ambient temperature and the temperature rise that you can tolerate and/or dissipate. I would suggest taking a look at a PCB calculator. It is derived from IPC2221 which discusses this. I use one of the following:
https://www.desmith.net/NMdS/Electronics/TraceWidth.html
https://www.4pcb.com/trace-width-calculator.html
If you are using KiCAD there is a tool-set built-in that uses the same calculator or something similar.
Now a simplified answer to your question-> Based on 25amb and 10 deg temp rise.

*

*At 25Amps on 1oz copper single layer - 1000mils or 1in wide trace

*At 25Amps on 2oz single layer - ~500mil wide

*At 25Amps on 4oz single layer - ~250mil wide

Internal layers require more spacing as you will see from the tool.
Hope that helps :)

A: I use a rule of thumb of 4A per square mm of copper cross-section.  For high current you may want to specify a relatively high copper thickness.  You can also use multiple layers, but it's wise to fill any vias with conductive material (solder or copper).


text:
Q: Why aren't my inputs formatting correctly in bootstrap I have a form, which is created dynamically, which is the reason for the jquery (It's easier).  I am trying to figure out why the input fields are not formatting correctly.
I have just changed the way it is formatted, from being in a table, to a more bootstrappy way of things, and this way, only the input fields I put icons on are working properly.  The jQuery works fine when I have the same fields in the table.
What am I doing wrong?
There is also a jsfiddle.
Here is a representative portion of the form:

    *
      First name:

      <input type="text" name="first_name" required maxlength="50" required id="id_first_name">

    *
      Last name:

      <input type="text" name="last_name" required maxlength="50" required id="id_last_name">

    *
      Phone:

      <input id="id_phone" name="phone" type="tel" required />

Since my fields are created dynamically, and their attributes are more work to get at, I have used jQuery to add the form-control class to the inputs, and some other minor things.
Here is that code:
$("input[type='email']").parent('div:first').prepend('

');
$("input[type='tel']").parent('div:first').prepend('

');
$('input').addClass('form-control').each(function () {
    var $this = $(this);
    var $label = $('label[for="' + $this.attr('id') + '"]');
    $this.attr('placeholder', $label.text().slice(0, -1));
});
$('select').addClass('form-control');

A: This is happening because you have your regular inputs inside of an input-group element but are not adding an icon inside with the input which it expects.
For any input that wont have an icon, change your html from:

  <input type="text" name="first_name" required maxlength="50" required id="id_first_name">

To simply:
  <input type="text" name="first_name" required maxlength="50" required id="id_first_name">

and the formatting will work as expected.
working jsfiddle


text:
Q: System32 folder in windows 7 I'm using this code in XP 32-bit OS to get the %windir%\windows\system32 folder path.
sysFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.System)

What I want to know is that will this same code return the %windir%\windows\syswow64 folder when used in Windows 7 (64/32-bit)?

A: It will return c:\windows\system32, even in a 32-bit program that runs on the 64-bit version of Windows.  Do not fix this, it doesn't need fixing.  Because when you use that path, Windows will automatically remap it to c:\windows\syswow64.  The file system redirector takes care of it.

A: I tried on my Windows7 box with .NET 4.0
This code:
Console.WriteLine(Environment.GetFolderPath(Environment.SpecialFolder.System));
Console.WriteLine(Environment.GetFolderPath(Environment.SpecialFolder.SystemX86));

Prints the following from both 32- and 64-bit process:
C:\Windows\system32
C:\Windows\SysWOW64

A: Nope.  On my Windows 7 64-bit box, targeting x64:
C:\Windows\system32


text:
Q: Jasmine spy setup for Promise wraps Observable I am writing Angular a unit test case for a promise that wraps the observable call using Jasmine. I am not able to mock this promise in order to test it.
Component
ngOnInit(){
 this.getOrder().then(
        () => {
            this.getShippingAddress();
        });
}

private getOrder() {
    var promise = new Promise((resolve, reject) => {
        this.orderService.getOrder(this.orderOfferId)
            .subscribe(
            res => {
               // This part is not executed from Test
                var result: IOrderViewData = this.utilities.resolveJsonReferences(res);
                this.viewData = result;
                if (this.viewData.orderDate < this.today) {
                    this.message = "Order cannot be in the past";
                }
                resolve();
            },
            err => {
                reject();
            });
    });
    return promise;
}

private getShippingAddress() {
  return  this.communicationService.getShippingAddress(this.orderOfferId);
}

Test
    it('Should validate the order date given the date is in past', (done) => {
        orderMockViewData.orderDate = new Date(2017,10,22);

        let orderSpy = spyOn(orderService, "getOrder").and.returnValue(Observable.of(orderMockViewData));
        let addressSpy = spyOn(communicationService, "getShippingAddress").and.returnValue(Observable.of(shippingMockViewData));
        fixture.detectChanges();

        fixture.whenStable().then(() => {
            expect(orderSpy).toHaveBeenCalledWith("order/d371abcb-a935-4f85-bcca-baa0bf32e1ac"); // SUCCESS
            expect(addressSpy).toHaveBeenCalledWith("address/d371abcb-a935-4f85-bcca-baa0bf32e1ac"); // FAILED
            expect(componentInstance.message).toEqual("Order cannot be in the past"); // FAILED
            done();
        });

    });

Problem
I could see orderSpy is getting called as it was setup using Observable. of. But the call to the communicationService does not happen as it was resolved in a promise.
Does anyone help me on how to mock such things as I need to test promise and observable combination?


text:
Q: How to get text content between asp:LinkButton tag I have no problem to get text content if it is declear inside the <asp:LinkButton runat="server" Text="Test Content">.
However, when I place the text content between a pair of open and close <asp:LinkButton> tags. Using the following code cannot get the text content.
ASP.NET WebForm

    <asp:LinkButton ID="linkButtonLogout" runat="server" OnClick="menuItem_Click">  Logout</asp:LinkButton>

C# Code
protected void menuItem_Click(object sender, EventArgs e)
{
        LinkButton clickedMenuItem = (LinkButton)sender;
        string menuItemStr = clickedMenuItem.Text;
        Debug.WriteLine(">>> menuItem_Click item: " + clickedMenuItem.Text);
}

Is there a way to get text content between asp tags?

A: If you will check the page source in both cases i.e. if you specify the text property explicitly or write the text between tags, you can see that both are same so in either of the two cased you can use the Textproperty like this:-
protected void menuItem_Click(object sender, EventArgs e)
{
     Response.Write(">>> menuItem_Click item: " + linkButtonLogout.Text);
}


text:
Q: choice field symfony "Notice: Array to string conversion " Trying to validate a choice field (multiple checkboxes) Im having this problem:
"Notice: Array to string conversion "

My validation file looks like this one:
Cgboard\AppBundle\Forms\UploadImageEntity:
  properties:
    image:
          ...
    cgnetworks:
      - Choice:
          choices: [flickr, tumblr]  //<--- this is giving me problems!!!

My form entity class (Im not going to save this to db for now):
class UploadImageEntity {
    public $image;
    public $cgnetworks;
}

And my form class:
class UploadImageForm extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('image', 'file')
            ->add('cgnetworks', 'choice', [
                    'choices'  => $this->getCgNetworks(),
                    'multiple' => TRUE,
                    'expanded' => TRUE
                ]
            );
    }

    public function getCgNetworks()
    {
        return [
        'tumblr' => 'Tumblr',
        'flickr' => 'Flickr'
        ];
    }

}

Any idea?

A: perhaps you need to specify multiple in your validation
cgnetworks:
  - Choice:
      choices: [flickr, tumblr]  //<--- this is giving me problems!!!
      multiple: true

A: Check your Entity field getter. If you have something else instead of
public function getValue(){
      return $this->value;
}

You can reach this error.
Form builder uses get and set entity methods, that's why you need to return an allowable value.


text:
Q: How to output variables into jmeter results file XML? We are reading data for our test cases from a CSV data set config. We would like to output these variables into the results XML.
For example, if the CSV data set has:
test case name 1,first1, last1, assertion1
test case name 2,first2, last2, assertion2
...

for variables testCase, firstName, lastName, assertion,
then the results XML file should have:
<testCase>
...
</testCase>
...
<assertion>
...
</assertion>

Is there a way to do this?


text:
Q: SAP BAPI get all Functional Locations I have been a longtime lurker of stackoverflow and have now decided to join.  I am trying to pull a list of every Functional Location out of SAP using BAPI.  When I run this code it returns with an empty table.  I dont have very much experiance with BAPI and I am trying to teach myself.  Can someone please help with what im missing to make this work.
Thanks,
See code bellow:
Dim sapFunc As New SAPFunctionsOCX.SAPFunctions
    Dim objServer = sapFunc.Connection
    objServer.Client = "101"
    objServer.User = "MyUserName"
    objServer.Ticket = "MyKey"
    objServer.system = "PEC"
    objServer.MessageServer = "MyMessagerServer"
    objServer.GroupName = "PUBLIC"
    If objServer.logon(0, True) <> True Then
        MsgBox("Key Rejected")
        Exit Sub
    End If

    Dim objRfcFunc As SAPFunctionsOCX.Function
    objRfcFunc = sapFunc.Add("BAPI_FUNCLOC_GETLIST")
    'System.Console.Write(objRfcFunc.Description)

    If objRfcFunc.Call = False Then
        MsgBox("Error occured - " & objRfcFunc.Exception)
        Exit Sub
    End If

    Dim tab = objRfcFunc.Tables("FUNCLOC_LIST")
    System.Console.WriteLine("Input start:")
    For I = 1 To tab.RowCount
        For j = 1 To tab.ColumnCount
            System.Console.Write(tab.ColumnName(j) + ":")
            System.Console.WriteLine(tab.Cell(I, j))
        Next
    Next
    System.Console.WriteLine("Input end.")

A: I don't intend for this to be an answer, but if it helps then that's good.  If it doesn't, I'll delete it.
With objRfcFunc.tables("funcloc_ra")
    If .RowCount < 1 Then .Rows.Add
    .cell(1, 1) = "I"
    .cell(1, 2) = "EQ"
    .cell(1, 3) = "Your Func Loc"
End With

Do this after setting objRfcFunc and before calling it.  The call will use these parameters.
I means to Include, EQ means you want to find items equal to the value in low.


text:
Q: how to find out why the process is sleeping/blocked in linux friends:
some time we found our program run abnormally, that is, it is not crashed, but did not running as we expected, it is SLEEPING!
then, i want to find out why it is SLEEPING, such as, some socket reading blocked? some signal waiting blocked? or other things occurred to block this process.
HOW to DO? i find the ps or the /proc/pid/stats only can indicate its states and its signal mask. BUT i want to know more detail, which socket,signal or other things blocked it?
anyone can give some help information?
it is in linux/android, the process is common process, native or java process.
thx a lot in advance

A: If your process is blocked on a system call, you can use strace to find out what it is. Note that the strace binary may not be installed on your android system, but there is a version of it in recent versions of busybox. Also you may need root access, so you'll want to jailbreak your android device.
Here's a contrived example.
$ mkfifo /tmp/foo
$ cat /tmp/foo &       # blocks
$ ps                   # note pid of the blocked "cat" process; in my case it's 29739
$ sudo strace -p 29739 # attach to the process

The output of strace in this case is:
Process 29739 attached - interrupt to quit
open("/tmp/foo", O_RDONLY^C <unfinished ...>

strace will then hang along with your process; hit ctrl-c to break.
Here's another example:
$ nc -l  8888 &
[2] 31087
$ sudo strace -p 31087
Process 31087 attached - interrupt to quit
accept(3,

In this case you might want to know what it's trying to accept; you can use the /proc filesystem for this:
$ ls -l /proc/31087/fd/3
lrwx------ 1 abliss abliss 64 Jun 25 12:22 /proc/31087/fd/3 -> socket:[2265625]

If your process is blocked in a java thread, you'll probably have better luck using the android tools to attach a debugger like jdb.


text:
Q: What is the best approach in Snowflake for delete operations on a really large table? We're thinking of moving our ODS from S3 into Snowflake but have some concerns on performance.  Deleting 39 million rows from a 1.5 Billion (this would be on the smaller side) row table took 15 minutes on an x-small warehouse, 8 on a small, and 5 on a medium.  We could throw money at larger instances, but really don't want to do that until all other measures were explored.
We were also thinking about implementing a manual partition system, to chunk up the table, but there would be a dev cost to create the supporting functionality.
Does Snowflake have a partitioning system that I'm not aware about that's equivalent to SQL Server?  I know that's a reach, but swapping partitions was great.
Thanks for any feedback!

A: Snowflake doesn't have partitions like SQL Server as such, but the storage method of data in Snowflake is micro-partitions, which are similar...sort of.  You can use Snowflake's automatic re-clustering service to align those micro-partitions on one or multiple fields, which would then make deleting on those keys a much faster operation.  Leveraging the fields that you are deleting off of to cluster your tables should help quite a bit.

A: The approach of doing explicit clustering on a table requires thoughtful planning  to consider various access patterns and workloads (ingestions, queries etc) touching that same table and cost considerations, so I am not sure if doing explicit clustering for the delete case is good enough reason to change the table layout.
What if instead of deleting from large able, use CTAS to create another table on the surviving rows and the drop original table?


text:
Q: How insert 700 records into mysql database with one query in php I have been trying with this for days i have 700+ records in a mysql database that i use a select query to get and then do some stuff to it. But when i want to reinsert the data it takes a long time to insert. How can i speed this up any help appreciated
       $zip_db_name = $wpdb->prefix . 'wa_zip_codes';

        $taxTable = $wpdb->prefix . "woocommerce_tax_rates";

        $taxTableLocation = $wpdb->prefix . "woocommerce_tax_rate_locations";

        $getzip = $wpdb->get_results("SELECT zip FROM $zip_db_name ORDER BY zip DESC");

        foreach ($getzip as $retrieved_data){
            $zipcode = $retrieved_data->zip;

            $url = 'http://dor.wa.gov/AddressRates.aspx?output=xml&addr=&city=&zip='. $zipcode .'';
            $xml = simplexml_load_file($url) or die("feed not loading");

            foreach ($xml as $value){
                //data to be stored
                $country = 'US';

                $state = 'WA';

                $city = '*';

                $rate = $xml['rate'];

                $wpdb->query("START TRANSACTION");

                    // Inserts values into woocommerce_tax_rates
                    $wpdb->query("INSERT INTO $taxTable (tax_rate_country, tax_rate_state, tax_rate, tax_rate_name) VALUES ('$country', '$state', '$rate', '$city')");

                    $thelastId = $wpdb->get_results("SELECT tax_rate_id FROM $taxTable ORDER BY tax_rate_id DESC LIMIT 1;");

                    //Gets the ID of the last inserted value in wpdb

                    $lastid = $wpdb->insert_id;

                    //Inserts zip code value into wp_woocommerce_tax_rate_locations

                    $wpdb->query("INSERT INTO $taxTableLocation (tax_rate_id, location_code, location_type) VALUES ('$lastid', '$zipcode', 'postcode')");

                $wpdb->query("COMMIT");
            }
        }


text:
Q: handling matrix in R I have data like this
    SB1 SB2 SB3 DB1 DB2 DB3 DB4 DB5 FB1 FB2 FB3 FB4
SB1 ... -45 32  -4  10  -13 -9  12  -45 -4  -43 -2
SB2 45  ... 30  70  55  60  16  20  22  48  0   8
SB3 -32 -30 ... -26 -40 -10 -14 31  -10 -82 -97 -4
DB1 4   -70 26  ... -5  2   7   32  -4  0   -45 0
DB2 -10 -55 40  5   ... 2   3   26  -43 0   -43 0
DB3 13  -60 10  -2  -2  ... -3  29  20  -4  -6  0
DB4 9   -16 14  -7  -3  3   ... 20  19  -30 -8  0
DB5 -12 -20 -31 -32 -26 -29 -20 ... 0   -20 -23 -20
FB1 45  -22 10  4   43  -20 -19 0   ... -20 -20 -20
FB2 4   -48 82  0   0   4   30  20  20  ... 0   0
FB3 43  0   97  45  43  6   8   23  20  0   ... 0
FB4 2   -8  4   0   0   0   0   20  20  0   0   ...

What I want is to remove the negative number from this matrix and it can be done with this command:
 apply(inter,2, function (x){ifelse(x<0,0,x)})

However, this code remove both the negative and the "..." which I need for further calculation. How can i remove the negative but still preserve the "..."? I have tried this code
apply(inter1,2, function (x){ifelse(x>0|x %in% "...",x,0)})

but it doesn't work and R gave me this warning
Error in apply(inter1, 2, function(x) { :
dim(X) must have a positive length

Please give me some advice and if you could, please let me know which package is the best in handing data in matrix form.
Thank you.

A: Your data is currently stored as text because of the "..." values. You'll probably find it easier to store these special values as NA and to store your data in a numeric matrix:
# Load data, currently stored as a data frame with text in it
dat <- read.table(text="    SB1 SB2 SB3 DB1 DB2 DB3 DB4 DB5 FB1 FB2 FB3 FB4
SB1 ... -45 32  -4  10  -13 -9  12  -45 -4  -43 -2
SB2 45  ... 30  70  55  60  16  20  22  48  0   8
SB3 -32 -30 ... -26 -40 -10 -14 31  -10 -82 -97 -4
DB1 4   -70 26  ... -5  2   7   32  -4  0   -45 0
DB2 -10 -55 40  5   ... 2   3   26  -43 0   -43 0
DB3 13  -60 10  -2  -2  ... -3  29  20  -4  -6  0
DB4 9   -16 14  -7  -3  3   ... 20  19  -30 -8  0
DB5 -12 -20 -31 -32 -26 -29 -20 ... 0   -20 -23 -20
FB1 45  -22 10  4   43  -20 -19 0   ... -20 -20 -20
FB2 4   -48 82  0   0   4   30  20  20  ... 0   0
FB3 43  0   97  45  43  6   8   23  20  0   ... 0
FB4 2   -8  4   0   0   0   0   20  20  0   0   ...", header=TRUE, stringsAsFactors=FALSE)

# Convert to a numeric matrix, with `NA` instead of ...
mat <- data.matrix(dat)

Now, you should find it relatively simple to replace all the negative values with 0:
mat[mat < 0] <- 0
mat
#     SB1 SB2 SB3 DB1 DB2 DB3 DB4 DB5 FB1 FB2 FB3 FB4
# SB1  NA   0  32   0  10   0   0  12   0   0   0   0
# SB2  45  NA  30  70  55  60  16  20  22  48   0   8
# SB3   0   0  NA   0   0   0   0  31   0   0   0   0
# DB1   4   0  26  NA   0   2   7  32   0   0   0   0
# DB2   0   0  40   5  NA   2   3  26   0   0   0   0
# DB3  13   0  10   0   0  NA   0  29  20   0   0   0
# DB4   9   0  14   0   0   3  NA  20  19   0   0   0
# DB5   0   0   0   0   0   0   0  NA   0   0   0   0
# FB1  45   0  10   4  43   0   0   0  NA   0   0   0
# FB2   4   0  82   0   0   4  30  20  20  NA   0   0
# FB3  43   0  97  45  43   6   8  23  20   0  NA   0
# FB4   2   0   4   0   0   0   0  20  20   0   0  NA

Instead of using x == "..." to check for your special values, you can use is.na(x).

A: It would be better to convert ... to NA.  If your data is matrix, I assume the columns are character class.  If you don't want ... to get converted to NA and wants the matrix to remain character class
indx1 <- grep("\\d+", inter)  #inter is the matrix
inter[indx1][as.numeric(inter[indx1]) <0] <- 0
inter

A: A couple of things:

*

*Is this an object of class data.frame? Because then every column will only be of only one atomic type, meaning every element of your matrix is of type character due to the "...".

*If you actually want to do calculations, why the dots? You can not use them in a meaningful way in a mathematical function. Your function works only because the ">" operator compares the alphabetical value if the letters. The dots get removed because their alphabetical value is higher than zero in R.

*Lastly, the apply() function with argument MARGIN=2 uses the complete column as input for the applied function, while what you want to do is to apply a function to every single element. A lot of R functions are vectorized, but the function that you would need has to be written with this in mind.
If you actually want the dots to stay as is, you will have to do a check for them first. Here's a way to do this:
checkerFun <- function(x){
    if(x=="...") return("...") else {
        x <- as.integer(x)
        x <- ifelse(x>0,0,x)
        return(x)
    }
}

data.frame(lapply(X=inter, FUN=function(x){sapply(X=x,checkerFun)}))

Explanation: checkerFun() first compares the element to the dots, if the element is anything else it coerces it into an integer and applies your replacement. checkerFun is a function which expects a single element as input, not a vector like it would get as input in an *apply type function.
In the last row, i nest an sapply in an lapply: the lapply runs the function on every element of inter, which is a list of atomic vectors. Therefore, the FUN argument of lapply() needs to be another sapply() function, which runs checkerFun on every element of each of the given vectors.


text:
Q: Need to figure out how to delete from Android Database alright, So when i call
ourDatabase.delete(DATABASE_TABLE, KEY_ROWID + "=" + lrow, null);

which is a delete function for my database, it works and deletes the long i send to it as lrow, the problem i have is then when it deletes the one i pick it leaves all the numbers in the database the same. example i have a list of words 1-10 in a database it shows "1,2,3,4,5,6,7,8,9,10". I delete number 4 and then in the list showing the word it shows "1,2,3,5,6,7,8,9,10" - No 4. Is there anyway this can be fixed and have it count the new amount i have and reset the database. so it would show "1,2,3,4,5,6,7,8,9"
How i get the data is through an array that has each length of the words in my database.
Hope you understand, if not post a comment!

A: Not exactly sure what the problem is... maybe the numbers you are referring to are some ID for example for your entries in your database?
You could update all the entries with numbers higher than the one you deleted to decrease by one... the update function will not really work with the ContentValues, but you could try this:
ourDatabase.execSQL("UPDATE "+DATABASE_TABLE+" SET "+KEY_ROWID+"="+KEY_ROWID+"-1 WHERE +"KEY_ROWID+">"+lrow);

But it's really ugly... I think you should look more at why you need this and is it really necessary...


text:
Q: Rotation around 2 axes include unwanted Rotations I want to spin an object around x and rotate y axis to a direction.
    Quaternion qr = Quaternion.Euler(transform.eulerAngles.x, 0,0);
    transform.rotation = Quaternion.Lerp(transform.rotation,qr,Time.deltaTime*5);

    transform.rotation = Quaternion.Euler(xRotation(xRotationSpeed),
                         transform.eulerAngles.y, 0);

x and y Rotations combined make weird rotations and sometimes even rotate z even though I have it set to 0.

A: Here is an example that yawing an object while rolling.
Notice that the rotation is applied from right to left.
const float ROLL_SPEED = 120f;
const float YAW_SCALE = 60;

float _lastYawBase;

void Update()
{
    var yawBase = Input.GetAxis("Horizontal");
    var tsf = transform;

    tsf.localRotation =
        // 4. apply new yaw
        Quaternion.Euler(0, yawBase * YAW_SCALE, 0) *
        // 3. roll
        Quaternion.Euler(ROLL_SPEED * Time.deltaTime, 0f, 0f) *
        // 2. revert last yaw
        Quaternion.Euler(0, -_lastYawBase * YAW_SCALE, 0) *
        // 1. current rotation
        tsf.localRotation;

    _lastYawBase = yawBase;
}


text:
Q: HTTP 504 Gateway Time-out when serving static file with Django (Nginx + Gunicorn) I've been having problem hosting my Django project on Amazon EC2.
Using Gunicorn and Nginx to host the site, I get the following error when trying to load my page in the browser (excerpt from the Javascript console):
Failed to load resource: the server responded with a status of 504 (Gateway Time-out): https://example.com/favicon.ico

I believe Nginx has some problems finding my static files, but I'm not sure why. Here's my Nginx config:
server {
    listen 443 default;
    client_max_body_size 100M;
    server_name www.example.com;

    keepalive_timeout 5;

    ssl on;
    ssl_certificate /etc/letsencrypt/live/www.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/www.example.com/privkey.pem;

    # the domain name it will serve for
    charset     utf-8;

    # path for static files
    root /opt/app/staticfiles;

    location /static {
        root /opt/app/staticfiles;
    }

    location / {
        # checks for static file, if not found proxy to app
        try_files $uri @proxy_to_app;
    }

    location @proxy_to_app {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;

        proxy_pass   http://app_server;
    }

}

/var/log/nginx/access.log and cat /var/log/nginx/error.log don't show anything.
For HTTP code 504 it is usually a problem that a long request is hanging and eventually times out, but I'm not sure how it applies to my project, since I'm only trying to load the site.
Not sure how to debug this issue, so any help is appreciated!

A: This may help you :
What I did is I have edited /etc/nginx/site-enabled/default file as follows:
server {
        #nginx server configuration
        listen 80 default_server;
#       listen [::] default_server ipv6only=on;
        listen [::]:80 default_server ipv6only=on;

        root /usr/share/nginx/html;
        index index.html index.htm;

        # Make site accessible from http://localhost/
#       server_name localhost;
        # provide whole path of static files you got after running `python manage.py collectstatics`
        location /static{
                 alias /home/ubuntu/folder1/folder2/webpage/static;
        }

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                proxy_pass http://0.0.0.0:8134;#Provide your django server's link
                # Uncomment to enable naxsi on this location
                # include /etc/nginx/naxsi.rules
        }
}

Note:- Make sure you have done python manage.py collectstatics. Don't do any changes in nginx.conf file


text:
Q: Text width in one sided documents? Example:
\documentclass[paper=a4, fontsize=10pt, parskip=half, DIV=9]{scrartcl}

How do I calculate text width?
In particular: I understand that DIV=9 specifies that the page is divided into nine stripes, but how many are used for the border, in case the document is single sided?
In the documentation I only found explanation for two sided documents.
I measured text width with a ruler, and it's about: 14cm

A: I think the most accurate measurement you can obtain is via the basic TeX primitive \the followed by the specific lenght implicity declared inside \documentclass; this command is used to get the value of a counter, eg. \the\mylenght. (that's why the geometry package has to do with appropriatley modifying those parameters!).
Here is the MiniMWE:
\documentclass[paper=a4, fontsize=10pt, parskip=half, DIV=9]{scrartcl}
%
\usepackage{calc}
%
\begin{document}
%
\the\textheight\\ % this is the HEIGHT of the space occupied by whole text
\the\textwidth    % this is the WIDTH  of the space occupied by whole text
%
\end{document}

Which yields:

574.0pt
398.33862pt

Using the appropriate conversion you can have exactly (with the appropriate significant figures, let me be a little more scientific):

20.17cm
14.000001cm

You can see that this is within the accuracy of your measurement.

A: The DIV=n method consists in considering the available paper area (binding correction removed) formed by n2 equal smaller rectangles, by dividing both width and height by n. The upper horizontal stripe and the two lower ones make the upper and lower margin. Similarly the inner vertical stripe and the two outer ones make the inner and outer margins. However, when the oneside option is active, one fourth of the outer margin is transferred to the inner margin (so both are one and a half stripe wide). The upper and lower margins still follow the rule.
So, with DIV=9 on A4 paper, we get a text width of 6 times 21/9 centimeters, that is 14 centimeters, as you found out.
The parameter \oddsidemargin turns out to be 27.31467pt that, added to 1 inch, give exactly 3.5 centimeters. The computations are a bit involved because they must take into account the one inch shift in both vertical and horizontal directions that DVI drivers (and pdfTeX too, for compatibility) always do when printing or previewing a document.
When the twoside option is active, instead, \oddsidemargin is –5.88022pt; adding 1 inch gives 2.33333 cm; the outer margin the double (4.66667 cm), making again for 14 cm textwidth.


text:
Q: Search text in files with accent characters I would like to search for text with accents in files. I know that I can use grep for searching regular text:
grep -rnw './' -e 'KORONA'

...but it doesn't work for words with accent characters, like KORONAVÍRUS, obmedzená.
Any recommendation?

A: If the encoding of all the files is the same, you just need to write the searched sentence in that encoding. That brings up two possible conditions:

*

*The encoding on the command line (or where the command is executed) (probably set by one of the locale variables LC_*) is the same as the encoding of all the files, then, just grep as usual:
grep -rn 'KORONAVÍRUS, obmedzená.'

Use the -w option only if you want to match the whole line.

*

*If the encoding of all files is different, change the search string to that encoding.
$ echo 'KORONAVÍRUS, obmedzená.' >orig
$ grep -ran "$(cat orig | iconv -t CP1252)"

Here, the -a option allows grep to search inside files with diferent encodings that may be detected as binary.
If the files could contain different encodings then there is no solution possible. There is no way to auto-detect a file encoding.
It is not possible to search inside a list of files if the files doesn't have an uniform encoding.
Related:
How to use grep/ack with files in arbitrary encoding?