text:
Q: How to show only evey nth categorical tickers in Bokeh There was the same question two years ago. It seemed that evey nth categorical tickers was not supported at that time.
https://stackoverflow.com/questions/34949298/python-bokeh-show-only-every-second-categorical-ticker
My bokeh version is 0.12.13. I wonder it is supported now.
Simply setting p.xaxis.ticker = ['A', 'B, 'C'] does not work(error is thrown)
In my dashbaord, the initial plot size is one quarter of browser view port and the x axis is crowded with many ticker and labels. So I want to show only 10 tickers and later show all of them when the plot is enlarged.

A: There's nothing built in to Bokeh to do this. You could accomplish something with a custom extension:
from bokeh.models CategoricalTicker

JS_CODE = """
import {CategoricalTicker} from "models/tickers/categorical_ticker"

export class MyTicker extends CategoricalTicker
  type: "MyTicker"

  get_ticks: (start, end, range, cross_loc) ->
    ticks = super(start, end, range, cross_loc)

    # drops every other tick -- update to suit your specific needs
    ticks.major = ticks.major.filter((element, index) -> index % 2 == 0)

    return ticks

"""

class MyTicker(CategoricalTicker):
    __implementation__ = JS_CODE

p.xaxis.ticker = MyTicker()

Note that the simple get_ticks defined above will not handle more complicated situations with nested categories, etc.


text:
Q: rails buttons click counter This is another I'm-totally-new-to-Ruby-please-have-mercy situation.
So i'm trying to figure out how to make a database of all my buttons to save the click count each time they're clicked. I started a new rails to try it out and generated a model Buttonand a controller buttons index
route.rbs
Rails.application.routes.draw do
  resources :buttons
  root 'buttons#index'
end

migration
class CreateButtons < ActiveRecord::Migration[5.0]
  def change
    create_table :buttons do |t|
      t.integer :clicks
      t.timestamps
    end
  end
end

buttons_controller
class ButtonsController < ApplicationController
  def index
    @button = Button.find(1)
  end

  def doit
    @button = Button.find(1)
    @newcount = @button.clicks + 1
    Button.find(1).update_attributes(:clicks => @newcount)
  end
end

Now.. i need to trigger the doit method.. is it possible to trigger a non CRUD operation ?
i tried this but it doesn't seem to work
index.html.erb

Hello, This is button and my click are :

<%= @button.clicks %>

<%= link_to 'click me', method: :doit %>

I know there's something I'm not getting here...
Ruby have been doing so much magic that I can't do a simple ruby method.. it have been really hard for me getting the part were methods are taking place without calling them by name..
Specially when I trigger a delete method and the destroy method is triggered by that.. I really need to get used to this too-much-magic coding

A: Several things to improve, I think. Please get back to me if something is not working (I did not run the code)
Make your index action list all the buttons
Controller:
def index
  @buttons = Button.all
end

View:

These are all my buttons

<% @buttons.each do |button| %>
  <%= link_to("Button #{button.id}", button_votes_path(button), method: :post) %>
<% end %>

It's common to have index show a list of resources.
Only create the routes you need, make increment a separate action
I'd chose to call it "vote". You could also call it "clicks" or "presses" or whatever.
resources :buttons, only: [:index] do
  resources :votes, only: [:create]
end

Add the votes controller
class VotesController < ApplicationController
  def create
    button = Button.find(params[:id])
    button.clicks += 1
    button.save
    redirect_to buttons_path
  end
end

No error handling here. So this is just to get you started.
For the next steps I suggest you follow a tutorial or start with simpler stuff.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why output is empty on Hadoop MapReduce? Debug? I want to aggregate the total_aomunt(float) for each date("yyyy-MM-dd HH:mm:ss.S").
The data is like here.
The output is empty like here.
The basic idea of the mapper is to skip the first line(header), and afterward get the date and total_amount of each line, then I change the date format to "yyyy-MM-dd". I guess the errors happen in try{} catch(){}.
By the way, I am wondering if there are some bad lines in the dataset, for instance, the value of total_amount is not floating but contains '$' like "$ 9.5" or the format of date is not like "yyyy-MM-dd HH:mm:ss.S", how to detect those lines and discard them? Do you have any ideas?
Here is the code:
public class RevenueSum extends Configured implements Tool {

    static int printUsage() {
        System.out.println("revenuesum [-m <maps>] [-r <reduces>] <input> <output>");
        ToolRunner.printGenericCommandUsage(System.out);
        return -1;
    }

    public static class RevenueSumMapper
                 extends Mapper<LongWritable, Text, Text, FloatWritable> {

          @Override
          public void map(LongWritable key, Text value, Context context
        ) throws IOException, InterruptedException {

            try {
                /*Some condition satisfying it is header*/
                if (key.get() == 0 && value.toString().contains("header") )
                    return;

                    else {
                    // For rest of data it goes here
                    String line = value.toString();
                    String[] items = line.split(",");

                    String old_date = items[3];
                    LocalDateTime datetime = LocalDateTime.parse(old_date, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S"));
                    String date = datetime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                    Float revenue = Float.parseFloat(items[10]);

                    context.write(new Text(date), new FloatWritable(revenue));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static class RevenueSumReducer
            extends Reducer<Text,FloatWritable,Text,FloatWritable> {
        private FloatWritable result = new FloatWritable();

        public void reduce(Text key, Iterable<FloatWritable> values,
                           Context context
        ) throws IOException, InterruptedException {
            int sum = 0;
            for (FloatWritable val : values) {
                sum += val.get();
            }
            result.set(sum);
            context.write(key, result);
        }
    }

    public int run(String[] args) throws Exception {

        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf, "revenue sum");
        job.setJarByClass(RevenueSum.class);
        job.setMapperClass(RevenueSumMapper.class);
        job.setCombinerClass(RevenueSumReducer.class);
        job.setReducerClass(RevenueSumReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(FloatWritable.class);

        List<String> other_args = new ArrayList<String>();
        for(int i=0; i < args.length; ++i) {
            try {
                if ("-r".equals(args[i])) {
                    job.setNumReduceTasks(Integer.parseInt(args[++i]));
                } else {
                    other_args.add(args[i]);
                }
            } catch (NumberFormatException except) {
                System.out.println("ERROR: Integer expected instead of " + args[i]);
                return printUsage();
            } catch (ArrayIndexOutOfBoundsException except) {
                System.out.println("ERROR: Required parameter missing from " +
                        args[i-1]);
                return printUsage();
            }
        }
        // Make sure there are exactly 2 parameters left.
        if (other_args.size() != 2) {
            System.out.println("ERROR: Wrong number of parameters: " +
                    other_args.size() + " instead of 2.");
            return printUsage();
        }
        FileInputFormat.setInputPaths(job, other_args.get(0));
        FileOutputFormat.setOutputPath(job, new Path(other_args.get(1)));
        return (job.waitForCompletion(true) ? 0 : 1);
    }

    public static void main(String[] args) throws Exception {
        int res = ToolRunner.run(new Configuration(), new RevenueSum(), args);
        System.exit(res);
    }


text:
Q: One uiview stop working when interacting with another On the same UIViewController, there's one UILabel being updated every 0.01s by a NSTimer. In the same Controller, there's an UIView containing a TableController from another .nib.
When I scroll the table, the UILabel stops from updating till the scroll finishes. Any ideas for that?
Thanks in advance.

A: You should register your timer with "NSRunLoopCommonModes" or "UITrackingRunLoopMode" mode.
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timer) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

- (void)timer
{
    label.text = @"different text";
}

And read NSRunLoop Class Reference, Threading Programming Guide and Concurrency Programming Guide

A: put the label updation code in a Thread.. it should solve your problem.


text:
Q: Sub-menu when using document.getElementById("nav01").innerHTML document.getElementById("nav01").innerHTML =
    "
" +
    "
Home
" +
    "
Calendar
" +
    "
Photos

test

"+
    "
Events
"+
"
";

/*Navagation CSS*/
ul#menu {
  padding: 0;
  margin-bottom: 11px;
}

ul#menu li {
  display: inline;
  margin-right: 3px;
}

ul#menu li a {
  background-color: #CCC;
  padding: 10px 20px;
  text-decoration: none;
  color: #696969;
  border-radius: 4px 4px 0 0;
}

ul#menu li a:hover {
color: white;
background-color: black;
}

ul#menu li a:active{
  background-color:blue;
}

This is the script code that I am using to create my menu. The problem i am having is i can not get the test menu to work like a sub menu. If it is not in there the Menu works like it should.
This is the full script code
I have added the CSS Code as this might help with the look i am trying to achieve

A: try this
document.getElementById("nav01").innerHTML =
"
" +
"
Home
" +
"
Calendar
" +
"
Photos
"

test

"+
"
Events
"+
"
"

the inner
 must be part of a
 of the outer

also refer to
http://www.w3.org/wiki/HTML_lists#Nesting_lists
how do you want this to appear?
when i got to
http://www.w3schools.com/html/tryit.asp?filename=tryhtml_intro
i see

is this not what you want?


text:
Q: Which of following inequality holds? $f(x,y) = _{\theta,\phi}^{{sup}}$ $ ||e^{i\theta}x - e^{i\phi}y||_{2}^2$
,where $x,y \in \mathbb{C^2}$ and $\theta,\phi \in \mathbb{R}$

*

*$f(x,y)  \leq ||x||^2 + ||y||^2 - 2Re (\langle x,y \rangle )$

*$f(x,y)  \leq ||x||^2 + ||y||^2 + 2Re ( \langle x,y\rangle )$

*$f(x,y)  \leq ||x||^2 + ||y||^2 - 2 \mid \langle x,y\rangle \mid$

*$f(x,y)  \geq ||x||^2 + ||y||^2 - 2Re ( \langle x,y\rangle )$

My claim :
Take n=2.
let $x= (x_1 ,x_2), y = (y_1,y_2)$
then $||e^{i\theta}x - e^{i\phi}y||_{2} =  \mid \mid (e^{i\theta}x_1-e^{i\phi} y_1,e^{i\theta}x_1-e^{i\phi} y_2) \mid \mid _{2}.$
Is that any two norms in $\mathbb{C^2}$ are also equivalent ?
Now we have to find the partial derivative w.r.t $\theta$ and $ \phi$ of both the co-ordinates and equate to zero and find the critical points to find the maximum.
Is that a correct way to proceed ?

A:
Inner products

In $\mathbb C:\;\,\qquad \langle x, y\rangle=\bar yx$
In $\mathbb C^2:\qquad\langle x, y\rangle=\bar y^\top x$

Norms

In $\mathbb C:\;\,\qquad ||x||_1^2=x\bar x$
In $\mathbb C^2:\qquad||x||_2^2=||x_1||_1^2+||x_2||_1^2$

Calculation

$$
||e^{\theta}x-e^{i\phi}y||_2^2=(e^{i\theta}x_1-e^{i\phi}y_1)\overline{(e^{i\theta}x_1-e^{i\phi}y_1)}+(e^{i\theta}x_2-e^{i\phi}y_2)\overline{(e^{i\theta}x_2-e^{i\phi}y_2)}=\\
(e^{i\theta}x_1-e^{i\phi}y_1){(e^{-i\theta}\bar x_1-e^{-i\phi}\bar y_1)}+(e^{i\theta}x_2-e^{i\phi}y_2)(e^{-i\theta}\bar x_2-e^{-i\phi}\bar y_2)=\\
||x||^2_2+||y||_2^2-e^{i(\theta-\phi)}\langle x,y\rangle-e^{-i(\theta-\phi)}\overline{\langle x,y\rangle}=\\
||x||^2_2+||y||_2^2-2\Re\left(e^{i(\theta-\phi)}\langle x,y\rangle\right)
$$

Conclusion

$$
f(x,y)=\sup_{\theta,\phi}||e^{i\theta}x-e^{i\phi}y||_2^2\ge\sup_{\phi}||e^{i\phi}x-e^{i\phi}y||_2^2=||x||^2_2+||y||_2^2-2\Re\left(\langle x,y\rangle\right)
$$


text:
Q: Create alarm template with CloudWatch Still discovering CloudWatch alarm. I have the metric M1, which have a Dimension "Namespace".
I have let say 10 different namespace.
I wish to create a different alarm per namespace, but the only way I find is to create 10 different alarm, one for each namespace.
Is is it possible to create alarm template with CloudWatch? I create one alarm, grouping by namespace. Meaning that the metrics of 3 different namespaces goes above the configured threshold, then I will have 3 alerts instead of just 1.


text:
Q: made a form with java and storing its values in database but it has some database query error? #this is when i didn't feed any values
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'values('','','','','',null,'','',''))' at line 1
#this is when i enter the values
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'values('**********785@gmail.com','','Aashin','sood','vpo bhawarn teh palampur di' at line 1
#and this is my code
public class RegisterServlet extends HttpServlet{
private static final String INSERT_QUERY = "INSERT INTO  USER (email, password, firstname, lastname, address, pincode, state,  number, feedback values(?,?,?,?,?,?,?,?,?))";

i dont know if the reason of error is this or something else

A: You omitted a closing bracket before values
update your code to
'''private static final String INSERT_QUERY = "INSERT INTO  USER (email, password, firstname, lastname, address, pincode, state,  number, feedback) values(?,?,?,?,?,?,?,?,?)";'''


text:
Q: How to avoid hidden files in file picker using tkinter filedialog.askopenfilename method? I want to allow the users to select CSV files from the file manager. But it shows all hidden folders too, which is very inappropriate. How can I avoid hidden folders?
def importCSV(self):
            self.file =  filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("CSV files","*.csv"),("all files","*.*")))

A: After a bit of searching around I managed to find the answer here. I did some slight changes to the linked example so it will run on Python 3. To test it out, simply press ctrl+o after executing.
from tkinter import *
from tkinter import filedialog

root = Tk()

try:
    # call a dummy dialog with an impossible option to initialize the file
    # dialog without really getting a dialog window; this will throw a
    # TclError, so we need a try...except :
    try:
        root.tk.call('tk_getOpenFile', '-foobarbaz')
    except TclError:
        pass
    # now set the magic variables accordingly
    root.tk.call('set', '::tk::dialog::file::showHiddenBtn', '1')
    root.tk.call('set', '::tk::dialog::file::showHiddenVar', '0')
except:
    pass

# a simple callback for testing:
def openfile(event):
    fname = filedialog.askopenfilename(initialdir='/', title='Select file', filetypes=(('CSV files', '*.csv'), ('all files', '*.*')))
    print(fname)
root.bind('<Control-o>', openfile)

root.mainloop()

The showHiddenVar is used to select if the hidden files will be displayed by default or not. If you don't want to allow the users to toggle between displaying and hiding the hidden files, then simply set showHiddenBtn to '0'.

A: filedialog.askopenfilename This line just opens a file picker of the Operating System. This is not Python's file picker.
You can disable the option to show hidden files in your operating system and they will disappear in the file picker too.
For windows, This option is available in File Explorer options in the Control Panel.
For Ubuntu, This option is available at  filemanager > top menu->View->Show hidden files


text:
Q: Inaccessible host: aws error on cdk deploy command hi I am trying to run command cdk deploy my-app and getting this error .  it was working fine but suddenly stopped  working.
this is exact error
Inaccessible host: cloudformation.us-west-2.api.aws' at port undefined'. This service may not be available in the `us-west-2' region.: getaddrinfo ENOTFOUND cloudformation.us-west-2.api.aws
my cdk version is cdk --version =  2.0.0

A: Same issues on me.
I solved the problem fixing my environment to:
  env: { account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION }

I think it is the bug in the latest CDK when using region code as string. I found same issues on examples using region code as string.


text:
Q: High Postgres-RDS CPU usage after migration We deployed an update of our software today (3 EC2 instances) and made a migration to our RDS (db.t2.medium, Postgres) which added one column to a table with ~15 rows. Before migrating, we had a CPU usage of around "2". After the migration the CPU usage increased to "60". After a db reboot, it dropped, but went up again.
As a sidenote: After migration we tried to connect using a GUI and it hanged while SSL-verification. We restartet the GUI and it worked again.
Any advice on this? Here is a screenshot with current metrics. You can clearly see the increase in usage.

We currently use PostgreSQL 9.6.2!

A: We fixed this ourselves:
The problem was, we didn't shut down our background service, which made several transactions while updating our software and the db. These transactions polluted the database. We found these transactions using this snippet:
SELECT pid, age(query_start, clock_timestamp()), usename, query,state
FROM pg_stat_activity
WHERE query != '<IDLE>' AND query NOT ILIKE '%pg_stat_activity%'
ORDER BY query_start desc;

After flushing our redis queue and restarting the background services, the CPU went down to 2% again.


text:
Q: python pandas groupby by multi columns problem on sum() and total add up I have a data of 90k rows and 14 columns.
want to add up the duplicated rows(13columns), except the column "quantity".
Sorry that i can not put the original data here for your easy check.
all below codes are pseudo codes, so ignore the obvious clerical error

*

*problem 1:
when i use
# gp_cols is the list of 13 columns name.
# except "quantity" column is uint32, other columns converted to category.

gp_cols = ['dddd-mm', 'province', 'city', 'maker', 'brand', 'model', \
           'model-year',  'color', 'liters', 'fueltype','type', 'appType', 'domesticimported']

gp = df_test.groupby(by=gp_cols, as_index=True)

# when i do gp.sum() or gp['quantity'].sum() or  gp.size(), the memory error will come up:
# even i just pull out the first 10k rows, same error happend.
MemoryError: Unable to allocate 455. PiB for an array with shape (512584853784231936,) and data type int8

why and how to avoid this?

*

*problem 2:
when i use cumsum() to solve the above problem, the final answer seems correct.
But when i compare the total value of 'quantity' and 'cumQty', they are not same.
df_test.sort_values(by=gp_cols,ignore_index=True, inplace=True)

t5 = df_test.join(gp.cumsum().rename(columns={'quantity':'cumQty'}))
t6 = t5.drop_duplicates(subset=gp_cols, keep='last')

print(t6['cumQty'].sum() )
print(t5['quantity'].sum())
print(df_test['quantity'].sum())
print(t5.shape,t6.shape)

# result after drop_duplicates are incorrect.
# t5 size is same to original data, t6 is the length of grouper. 633576 rows
#below 5001rows sample data result: drop_duplicates leads to data lost.
#37013
#39617
#39617
# (5001, 16) (2642, 16)

# run twice
#37199
#39617
#39617
#(5001, 15) (2642, 15)

# run third
#39860
#39617
#39617
#(5001, 15) (2642, 15)

# run forth
#58515
#39617
#39617
#(5001, 15) (2642, 15)

# then i tried join the 13 columns into one new reference column "key", the groupby result is correct.
t7 = df_test.iloc[:,0].astype('str')
for i in range(1, len(gp_cols)):
    t7 = t7 + "_" + df_test[gp_cols[i]].astype('str')

df_test['key'] = t7

gp7 = df_test.groupby(by="key", as_index=False)

print(gp7.sum()['quantity'].sum())
print(gp7.size())

# the quantity now is correct, same to original one's sum.
# below is the 5001 sample rows result. no data lost by reference column created.
# 39617
# 2642 rows x 2 columns

Why after drop duplicates, the total quantity is changed.
I guess when drop duplicates, some cumsum rows are dropped. or the problem is from join?
How can i get the correct answer, without create reference column and split the reference column?
Thanks!
Best Regards,
Kevin
for problem 1, as Joran's recommendation, i pull out a 4999 rows data for check both problem 1 and problem 2.
The link may expired after some time.
Even you only pull the first 1000rows, the codes will lead to problem 1, but no problem 2 found.
5001 rows sample data, has problem1 and problem2


text:
Q: IntPtr, SafeHandle and HandleRef - Explained Without pointing me to MSDN, could someone give a concise, clear explanation of the purpose of each of these and when to use them. (IntPtr, SafeHandle and HandleRef)

A: IntPtr is just a simple integer-based struct that can hold a pointer (ie., 32 bit size on 32-bit systems, 64-bit size on 64-bit systems).
SafeHandle is a class that is intended to hold Win32 object handles - it has a finalizer that makes sure that the handle is closed when the object is GC'ed.  SafeHandle is an abstract class because different Win32 handles have different ways they need to be closed.  Prior to the introduction of SafeHandle, IntPtr was used to hold Win32 handles, but ensuring that they were properly closed and prevented from being GC'ed was the responsibility of the programmer.
HandleRef is a way to make sure that an unmanaged handle is not GC'ed when you're in the middle of a P/Invoke call. Without something like HandleRef, if your managed code doesn't do anything with the handle after the P/Invoke call, if the GC were run during the P/Invoke call it would not realize that the handle was still in use and might GC it.  I imagine (but I'm not sure and haven't looked) that SafeHandle might use HandleRef as part of its management of the encapsulated handle.

A: HWnd a = new HWnd();
B.SendMessage(a.Handle, ...);

Assuming this is the only reference to "a" in the program, this is equivalent to:
HWnd a = new HWnd();
IntPtr h = a.Handle;
// a is no longer needed and thus can be GC'ed
B.SendMessage(h, ...);

The problem is that when "a" is disposed, it will close the handle. If this happens before or during the call to SendMessage, the handle will be invalid.
HandleRef prevents "a" from being garbage collected before the program is done with h.


text:
Q: How to escape a JSON variable posted with curl in bash script? I'm submitting a message to Mandrill in a bash script via their API and the content of the 'message' variable is causing the API call to come back with an error:
An error occured: {"status":"error","code":-1,"name":"ValidationError","message":"You must specify a key value"}

The content of the $message_body variable is:
Trigger: Network traffic high on 'server'
Trigger status: PROBLEM
Trigger severity: Average
Trigger URL:

Item values:

1. Network traffic inbound (server:net.if.in[eth0,bytes]): 3.54 MBytes
2. Network traffic outbound (server:net.if.out[eth0,bytes]): 77.26 KBytes
3. *UNKNOWN* (*UNKNOWN*:*UNKNOWN*): *UNKNOWN*

Original event ID: 84

I'm not sure what part of the string is throwing it off, but it seems that something is causing the JSON to be invalid when submitted to Mandrill's API.
If I change the above message to something simple such as "Testing 123" the message gets submitted successfully.
The code that does the POST is as follows:
#!/bin/bash
...
message_body = `cat message.txt`
msg='{ "async": false, "key": "'$key'", "message": { "from_email": "'$from_email'", "from_name": "'$from_name'", "headers": { "Reply-To": "'$reply_to'" }, "auto_html": false, "return_path_domain": null, "subject": "'$2'", "text": "'$message_body'", "to": [ { "email": "'$1'", "type": "to" } ] } }'
results=$(curl -A 'Mandrill-Curl/1.0' -d "$msg" 'https://mandrillapp.com/api/1.0/messages/send.json' -s 2>&1);
echo "$results"

What can I do to make sure the $message_body variable is prepared and ready to be submitted as valid JSON?

A: I suspect the problem is the lack of quoting around your variables
msg='{ "async": false, "key": "'$key'", "message": { "from_email": "'$from_email'", "from_name": "'$from_name'", "headers": { "Reply-To": "'$reply_to'" }, "auto_html": false, "return_path_domain": null, "subject": "'$2'", "text": "'$message_body'", "to": [ { "email": "'$1'", "type": "to" } ] } }'
# ..............................^^^^ no quotes around var ...........^^^^^^^^^^^...................^^^^^^^^^^...............................^^^^^^^^^...................................................................^^..............^^^^^^^^^^^^^.........................^^

Try this instead: any double quote in each variable is escaped.
escape_quotes() { echo "${1//\"/\\\"}"; }
msg=$(
    printf '{ "async": false, "key": "%s", "message": { "from_email": "%s", "from_name": "%s", "headers": { "Reply-To": "%s" }, "auto_html": false, "return_path_domain": null, "subject": "%s", "text": "%s", "to": [ { "email": "%s", "type": "to" } ] } }' \
        "$(escape_quotes "$key")"          \
        "$(escape_quotes "$from_email")"   \
        "$(escape_quotes "$from_name")"    \
        "$(escape_quotes "$reply_to")"     \
        "$(escape_quotes "$2")"            \
        "$(escape_quotes "$message_body")" \
        "$(escape_quotes "$1")"
)


text:
Q: Python as a web scripting language? I've recently been developing with Python, and I absolutely love it. It's a huge step up from PHP as a quick scripting language (imagine, no crazy function names!), and I would love to be able to use it as a web development language.
I've heard about Django, but I want something a bit more simple.
I run Lighttpd, and I've already gotten a Python script to work, but I can't pass arguments to it via the URL, like http://localhost/index.py?foo=bar. Is there a function/library that allows this?
I could be going at this all wrong, so please tell me if I am. But I absolutely hate PHP, now that I've seen Python. ;)

A: Assuming you're using a CGI interface, the cgi module.

A: You can check out the so-starving project to see a simple application written in a variety of different python web frameworks, and choose one that you agree with!

I can't pass arguments to it via the
  URL, like
  .../index.py?foo=bar. Is
  there a function/library that allows
  this?

Any of the available Python frameworks allow you to custom-map your URL's to specific python functions. The above URL would look more like .../blog/foo/bar and your app would know what to do with the extra bits.
On a personal note, I second the recommendation for Flask - It's a great microframework for beginners as well as useful to pros working on small projects.
I've also fallen in love with the framework Pyramid, which is a bit more complex but suited very well for larger applications.

A: I can recommend Django very highly. It's not that complicated. What I think you're looking for at the moment, however, is http://webpy.org/ .

A: You can use CGI, but it's somewhat counterintuitive and pretty painful to work with (compared to the alternatives). If you'd like to ease that pain, I'd suggest using a framework. There are quite a few frameworks out there, the most popular being Django, Pylons, and a few others. You can see a full list here and decide for yourself.
If you're looking for something full-stack, Django. If you want something small, Flask, web2py, and a number of others work.

A: If you want a dead simple but powerful framework, try Flask.
(Then learn some SQLAlchemy, and things will suddenly become even easier.)

A: You can use WSGI which is a standard interface between web servers and Python web applications or frameworks. This tutorial is really helpful for getting started with WSGI. It includes parsing GET and POST requests (as you mentioned in the question).

A: I'm a bit surprised that noone has named Turbogears ( http://turbogears.org/ ) yet. It is fairly new, but has a lot of promise and I find it quite simple and easy to use. I haven't tried many others as thorrowly though so I might be missing out :)
I am going  to check FLASK now though :P


text:
Q: How to achieve a result from MySQL with this table structure? I have a table that looks like this:
id  content_id  fields_id   value_int   value_string    value_decimal

351 3           1                       204
352 3           2                       Western Cape
353 3           3                       Cape Town

365 4           1                       205
366 4           2                       District of Columbia
367 4           3                       Washington

365 4           1                       204
366 4           2                       Eastern Cape
367 4           3                       Jeffreys Bay

This repeats for thousands of listings.
Now what I want to do, is write a query that I feed the ID (i.e 204, which is a country ID) - fields_id 1.
Then it must give me a result of a distinct list of all the states / provinces (the value string of fields_id 2) for country ID 204, for instance.
My MySQL skill are on the basic side, so could you please give an idea of how to achieve this in a query?

A: This SQL statement will do what you want:
SELECT w.id, w.value_string
FROM Table1 o
LEFT JOIN Table1 w ON w.id = (o.id + 1)
WHERE o.value_string = '204'

A: Try This.
Select distinct content_id from table_name where SUBSTRING('value_string',1,3)='204';

it gives you all ids associated with your desire info.


text:
Q: Replace character and the characters before and after text with pattern I need to replace a character with a pattern but the characters before the selected character also need to be replaced, using the search and replace function.
For instance: . has to be replace with 1/2, so hugo.ignatz becomes hug1/2gnatz.
How should I go about this?

A: If I understood you right, do you want this?
:%s#.[.].#1/2#g

this will replace x.y by 1/2


text:
Q: How to use std::vector for classes with handles I have definded the following class witch creates and frees an opaque object (e.g. an operating system handle)
class A
{
public:

    A(...)
    {
        allocateHandle(&h);
    }

    ~A()
    {
        freeHandle(h);
    }

    SomeHandle h;
}

When creating and resizing std::vector of A, the program crashes.
std::vector<A> vec;
vec.reserve(2);

vec.emplace_back(...);
vec.emplace_back(...);
vec.emplace_back(...); //crash

When std::vector reallocates memory, it calls the move constructor on all the objects, thus also moving the handle in A (which is basically an integer).
However, it also calls the destructor on the old object, which calls freeHandle(), thus it frees the memory behind the handle, that the new object still has, which becomes invalid and causes the crash.
How should I implement the move-constructor, so that the newly created object doesn't become invalid, when the old one is deleted?

A: You need to add some "no valid handle held" state to your objects. If your SomeHandle already has an "invalid handle" value (quite often, 0 is used for that), you can use that:
class A
{
public:

    A(...)
    {
        allocateHandle(&h);
    }

    A(A &&src) : h(src.h)
    {
        src.h = INVALID;
    }

    A& operator= (A &&rhs)
    {
      if (this == &rhs) return *this;
      if (h != INVALID) freeHandle(h);
      h = rhs.h;
      rhs.h = INVALID;
      return *this;
    }

    ~A()
    {
        if (h != INVALID)
          freeHandle(h);
    }

    SomeHandle h;
}

If there is no "invalid handle" value, you can change the type of h to std::optional<SomeHandle> and use std::nullopt as the invalid value.


text:
Q: Variables to work with loops in rails The Symfony framework has loop_index, first and last variables for working with loops.
{% for each link in links %}
    {% if loop_index == first %}
       .....
    {% else %}
       ....
    {%endif %}

{% end %}

Are there such variables or functions in rails?

A: Not exactly but you can use each_with_index:
{% links.each_with_index do |link, index| %}
    {% if index == 0 %}
       .....
    {% else %}
       ....
    {%endif %}

{% end %}


text:
Q: I want to run npm install and grunt in the background So I have code in node, I want to run npm install and grunt in the background. npm install should run before grunt runs. Both both should run in the asynchronously. How can I get this done using node?

A: Shelling out the commands from within node, it will look like this:
const exec = require('child_process').exec;
exec('npm install && grunt', (err, stdout, stderr) => {
  if (err) {
    console.error(err);
    return;
  }
  console.log(stdout);
});

If you want to run both as described, in the background from you shell just run
npm install && grunt &

To write the output to a file, you could do
const exec = require('child_process').exec;
exec('npm install && grunt', (err, stdout, stderr) => {
  fs.writeFile('outputOfNpmInstallPlusGrunt.txt', stdout, () => { ... })
}

Conversely, using spawn this would look something like:
const spawn = require('child_process').spawn;

function makeRunner(name, cb) {
  var ls = spawn(name, []);
  var output =  '';
  ls.stdout.on('data', (data) => { output += data; });

  ls.on('close', (code) => {
    fs.writeFile(name.split(' ').join('-'), output, cb);
  });
}

makeRunner('npm install', () => makeRunner('grunt'));


text:
Q: Online bash script that calls another script ignore functions and commands I wrote a bash script which downloads another script. To run the first script, I use
curl -s get.domain.com | bash

I use the following script to download:
#!/bin/bash

setup_dir=$(dirname "$(readlink -f $0)")
setupbuild=$vmsetup_dir/setupbuild
fileslocation=files.domain.com

wget -r -np -nH -A .sh ${fileslocation} -P ${setupbuild}
find ${setupbuild} -name "*.sh" -exec chmod +x {} +

exec ${vmsetupbuild}/menu.sh

At the end of the script, I want to run the downloaded script. This is where things go wrong and I don't understand it at all.
The menu of the called script seems to work. However, when a choice is made, the echo is ignored and the exit also doesn't do anything.
If I start the script from the prompt, everything works as expected.
I have tried to put an if in various places, but that also didn't help. It seems like certain things in the called script are being ignored.
menu.sh:
#!/bin/bash

main_menu() {
  clear
  echo "1) Option 1"
  echo "2) Option 2"
  echo "3) Other option"
  echo "4) Quit"
  read -p "Enter your choice: " main_menu_choice
  case $main_menu_choice in
  1)
    option1
    main_menu
    ;;
  2)
    option2
    main_menu
    ;;
  3)
    other_option
    main_menu
    ;;
  4)
    echo "Exit"
    exit 1
    ;;
  *)
    echo "Invalid option. Please try again."
    sleep 2
    main_menu
    ;;
  esac
}

option1() {
  echo "You chose option1."
  sleep 2
}

option2() {
  echo "You chose option2."
  sleep 2
}

other_option() {
  echo "You chose other option."
  sleep 2
}

main_menu

A: The script is reading standard input from the pipe, so you can't respond to prompts from the terminal.
When it executes menu.sh you can redirect input back to the terminal.
exec ${vmsetupbuild}/menu.sh < /dev/tty


text:
Q: fraction field of polynomial ring that is a finite extension of the base field Let $k$ be a field. Let $P$ be a prime ideal of $k[x_1, ..., x_n]$.
Let $K$ be a field of fractions of $k[x_1, ..., x_n]/P$. Suppose $K$ is a
finite extension of $k$. Does it then follow that $P$ is a maximal ideal?

A: We first prove a separate result.
Let $R$ be an integral domain which contains a field $k$.
If $R$ has finite dimension as a vector space over $k$, then $R$ is a field.
To see this, define, for each nonzero $v\in R$, a function $T_v:R\to R$ as $T_v(x)=vx$ for all $x\in R$.
It is clear that $T$ is a linear transformation.
Since $R$ is an integral domain, we must have that $T_v$ is injective.
Now by the fact that $R$ is finite dimensional over $k$ it follows that $T_v$ is in fact surjective and thus there exists $x_0\in R$ such that $T_v(x_0)=1=vx_0$.
Therefore $v$ is invertible, and consequently $R$ is a field.
Now.
If $P$ is a prime ideal in $S=k[x_1,\ldots,x_n]$, we know that $R=k[x_1,\ldots,x_n]/P$ is an integral domain. Now if we further assume that the field of fractions of $R$ is a finite extension of $k$, we get that $R$ itself is finite dimensional over $k$. By the above proved theorem, $R$ itself is a field. This gives us that $P$ is a maximal ideal.


text:
Q: quickblox web how to upload profile picture I'm trying to upload a profile picture (blob_id) from a javascript document and I can't find a way, I don´t know if I should use this snippets or even how to use it :(
I'll be so thankfull if you could help me
Thanks
QB.users.update({ id: user_creds.user_id, website: "http://quickblox.com"},   function(error, response){
    if(error) {
        console.log(error);
    } else {
        // Success
    }
});

A: sorry about this. We'll be beefing up the documentation soon.
Here's how to upload a profile picture
We'll have a file input:
<input type="file" id="picture" />

Then assuming you have jQuery in your environment, we'll reference it like this:
var profile_picture = $("#picture")[0].files;

Then you upload the file to Quickblox AWS like so:
QB.content.createAndUpload({file: profile_picture, public: true}, function(error, response) {
    if (error) {
        console.log("upload didn't work");
    } else {
        var blob_id = response.id;
    }
});

As you can see, the ID of the blob is the id field of the response.
You then add this blob ID as the blob_id field of a new user when you create him/her:
QB.users.create({login: "username_here", password: "password_here", blob_id: blob_id_here}, function(error, response){
    if(error) {
        console.log(error);
    } else {

    }
});

I made a page which demos the uploading functionality of the Javascript SDK - you can check it out here: http://www.quickblox.com/alex/websdk/upload.html


text:
Q: relative path in QtCreator I'm porting a console program with a config file containing lines of filename (relative to current directory) to Qt. When I run/debug the GUI in QtCreator, it seems cannot load the file from working directory.
Assuming my file system as follow:
C:/MyProjectSource
C:/MyProjectSource-Desktop-Debug // <-- created by QtCreator
C:/MyProjectSource-Desktop-Debug/debug/MyProgram.exe // <- my program
C:/MyProjectSource-Desktop-Debug/debug/params.txt    // <- program's config
C:/MyProjectSource-Desktop-Debug/debug/cfg/file1.txt // <- extra file
C:/MyProjectSource-Desktop-Debug/debug/cfg/file2.txt // <- extra file

params.txt looks like
# other setting
...
cfg/file1.txt      # at this line, program crash, saying cannot open file
cfg/file2.txt
...
# other setting

Code for reading file1.txt
std::ifstream ifs(filename); // <-- @runtime, filename = 'cfg/file1.txt'
if (!ifs)
{
    // failed inside QtCreator, but fine when start from explorer
    EMSG_OPENFILE(filename);
    exit(-1);
}

Baseline: no change to console program if possible. So, how to tell the QtCreator to understand the relative path? or should I enforce absolute path inside params.txt? Thanks.
Platform: QtCreator 2.6.1, Qt4.8, MinGW64, Win 7

A: the relative path is relative to current working directory not to the directory in which the executable is stored, so you need to change the current working directory to the executable directory, just add this line after the main function:
QDir::setCurrent(QCoreApplication::applicationDirPath());

if you need to set the current working directory from Qt Creator:
Project-> Run -> you will see Working Directory text box

then change this path to your executable location from browse button


text:
Q: Tabulator List Header Filter Issue Good Day
I am experiencing an issue when using the DataFiltered method on tabulator

table.on("dataFiltered", function(filters, rows){
    //filters - array of filters currently applied
    //rows - array of row components that pass the filters
});

When the table loads the method is activated. I am trying to trigger an event when the user filters the table using the header filter. Is there a way I can use a onchange method on the headers.

var Table = new Tabulator("#gridData", {
    height: 800,
    ajaxURL:"getData.php",
    layout: "fitData",
    selectable:1,
    columns:[

        {title:"Col", field:"Col1", sorter:"string",  headerFilter:"list", headerFilterParams:{valuesLookup:true, clearable:true, autocomplete:true}},
        {title:"Col2", field:"Col2", sorter:"string", headerFilter:"list", headerFilterParams:{valuesLookup:true, clearable:true, autocomplete:true}},
        {title:"Col3", field:"Col3", sorter:"string", headerFilter:"list", headerFilterParams:{valuesLookup:true, clearable:true, autocomplete:true}},
        {title:"Col4", field:"Col4", sorter:"string", headerFilter:"input"},
        {title:"Col5", field:"Col5", sorter:"string", headerFilter:"input"},

      ],
        ajaxResponse:function(url, params, response){
        return response.data; //pass the data array into Tabulator
      }
  });

  Table.on("dataFiltered", function(filters, rows){
    //filters - array of filters currently applied
    //rows - array of row components that pass the filters
    alert("table filtered");
});


text:
Q: Why can't orthogonal matrices be complex? I have been learning basic types of matrices, when I came across the following problem:
Prove that the eigenvalues of orthogonal matrices are of unit modulus.
And the solution mentioned that since Orthogonal matrices are unitary matrices, so the result held good as the same result had already been proven in case of Unitary Matrices.
I had the following questions in my mind next:

*

*Are all elements of an orthogonal matrix real? Why can't they be complex?

*Can a complex matrix be orthogonal?

Any productive discussion is looked forward to. And I think what might better help the discussion is an example of a "COMPLEX ORTHOGONAL MATRIX".

A: Here's a small orthogonal matrix with complex elements
$$\eqalign{
Q &= \frac 15\left[
\begin{array}{r}
-1-8\textit{i} & 2-4\textit{i} & -10+0\textit{i} \\
-10+0\textit{i} & -5+0\textit{i} & 0+10\textit{i} \\
-2+4\textit{i} & 4+2\textit{i} & 5+0\textit{i} \\
\end{array}
\right] \\\\
Q^HQ &= \frac 15\left[
\begin{array}{r}
37+0\textit{i} & 16+0\textit{i} & 0-40\textit{i} \\
16+0\textit{i} & 13+0\textit{i} & 0-20\textit{i} \\
0+40\textit{i} & 0+20\textit{i} & 45+0\textit{i} \\
\end{array}
\right], &\qquad Q^TQ=I \\\\
QQ^H &= \frac 15\left[
\begin{array}{r}
37+0\textit{i} & 0+40\textit{i} & -16+0\textit{i} \\
0-40\textit{i} & 45+0\textit{i} & 0+20\textit{i} \\
-16+0\textit{i} & 0-20\textit{i} & 13+0\textit{i} \\
\end{array}
\right], &\qquad QQ^T=I \\
}$$
which was generated with the following simple recipe
$$\eqalign{
A &= {\rm rand}(3,3) + i\cdot{\rm rand}(3,3) \quad&\big({\rm random\,matrix}\big) \\
K &= A-A^T \quad&\big({\rm skew\,matrix}\big) \\
Q &= (I+K)^{-1}(I-K) \quad&\big({\rm Cayley\,transform}\big) \\
}$$
So it's possible to create such matrices, but they're not really useful for anything.

A: Orthogonal matrices can be complex.
A square matrix $A$ is called orthogonal if $A^TA=I$. This definition is valid over any field, such as $\mathbb R,\mathbb C$ or $GF(2)$. E.g. here is a complex orthogonal matrix:
$$
A=\pmatrix{i&-\sqrt{2}\\ \sqrt{2}&i}
\Rightarrow A^TA=\pmatrix{i&\sqrt{2}\\ -\sqrt{2}&i}\pmatrix{i&-\sqrt{2}\\ \sqrt{2}&i}=I.
$$
However, most people only work with real or complex matrices, and real orthogonal matrices are more useful and appear far more frequently than their complex counterparts. When one speaks of an 'orthogonal matrix' without specifying the underlying field, one more often than not is talking about a real orthogonal matrix.


text:
Q: Renomear pasta da solução do Visual Studio Eu fiz todos os procedimento para alterar o nome do namespace do meu projeto, esta tudo certinho já compilando e tudo mais, só quando vou no explorador de arquivo as pasta estão com o nome antigo e não consigo modificar, alguém saber como proceder?
Imagens da soluçao nomeada corretamente:

Imagens das pasta no explorador de arquivos:

A: É simples,
Abra o projeto normalmente no Visual Studio, procure no gerenciador de soluções um botão com o nome "Soluções e Pastas", fica ao lado de uma casinha chamada "inicio", ao clicar, vai exibir as pastas do projeto, basta clicar com o botão direito e em seguida renomear. Pronto, depois disso, já estará renomeado.

A: Aperte as teclas Ctrl + Shift + F,e , na aba Replace in files na opção find What digite o old value, e em Replace With o new value e pressione o botão Replace All.


text:
Q: Can you say "I savaged myself" or "She savaged herself" for something or someone? Can you say "I savaged myself" or "He/She savaged himself/herself" for something or someone? For instance, someone was trying to prepare themselves for a contest or a competition, fiercely changing their appearance, behavior etc. and now they are not too happy about it. So is it O'K if this person would use a word "Savage" as a verb for a more dramatic effect (in an interview for example) and say that they savaged themselves for a chance to be on the show?
Thank you!

A: This is how Merriam-Webster defines the verb savage:

: to attack or treat brutally

If I mutilate myself with a knife, then it would make sense to say I savaged myself. In fact, I'd argue it would be a natural phrase in that context. It's at least one that I've heard applied in such a context before. The reflexive use is also fine in that context.
But simply changing your appearance doesn't have the same sense of permanent harm or attack that savaged would imply. Hearing the verb applied to makeup or clothing would be out of place.

Even if they are trying to use a verb in a dramatically figurative fashion, I think savaged would be taking it a little too far. You likely wouldn't say I brutalized myself or I abused myself in this context either.
It's possible you could use attack, if you qualified it: I attacked myself with new clothing and makeup. If said in the right way, it would convey a mix of imagery and humour.
Otherwise, something more simple like I transfigured myself would be dramatic enough, without also having an implication of harm.

In response to a comment:

changing the appearance in this context implies plastic surgery

In that specific context, the use of savaged might be appropriate—although normally only if the results were undesirable and harmful.
Also, unless you performed the surgery on yourself, the specific phrasing would be I was savaged or I got myself savaged.


text:
Q: Find a file which contains a string and delete it in Ubuntu My CMS is full of SPAM scripts and they are almost in every folder. I figured out, that I can find those scripts by using this find/grep command:
sudo find . -type f \( -name '*.php' -or -name '*.node' \) -exec grep -i "eval(base64_decode" {} +

Well some of the files just contain the spam-script and they are between 300 - 302 Bytes.
But some other files, which are been used by the CMS, are also infected. They should not be deleted completely, just everything from the first character untill the first php closing ("?>").
First I used the "delete" command and wrote this:
sudo find . -type f \( -name '*.php' -or -name '*.node' \) -exec grep -i "eval(base64_decode" {} + -delete

But that was a big mistake because I deleted all my important files. Before I delete more files, I just wanted to ask how to do it?
Something like: Get every file the code above finds and check if it is between 300 - 302 bytes, if yes -> delete it. If no -> Delete the first PHP section. But important!!! Not deleting the rest! The file is like:
<?php ?> ... <?php ?> ... <?php ?>"

only the first PHP block is infected.
Please can you help me? There are hundreds of files and I don't wanna do this by my own.
Thanks a lot in advanced!

A: You can try the following command which will call a perl find/replace command for every file matching the "eval(base64_decode" pattern:
sudo find . -type f \( -name '*.php' -or -name '*.node' \) -exec grep -li "eval(base64_decode" {} \; 2>/dev/null | xargs perl -i -p0e 's/<\?php.*?\?>//s'

The perl part will just remove the first <?php ?> block in the files returned by the find command.


text:
Q: Better Guard (Spork/RSpec) I'm using bundle exec guard as my main test runner, and I'm liking it even though I'm a total n00b about it.
Something that has troubled me is the way that I have to manually 'r' to restart it for any real code change. I'm OK with the slow reload time (though it'd be nice if it did something like what rails c's reload! does), but the thing I can't stand is having to switch to the window manually and hit r.  Especially when I forget to do this, and think it's all good. So it is inconsistency on top of inefficiency.
Here is my Guardfile:
guard 'spork', wait: 45 do
  watch 'config/application.rb'
  watch 'config/environment.rb'
  watch %r{^config/environments/.+\.rb$}
  watch %r{^config/initializers/.+\.rb$}
  watch 'Gemfile'
  watch 'Gemfile.lock'
  watch 'spec/spec_helper.rb' do 'spec' end
end

guard 'rspec', version: 2 do
  watch %r{^spec/.+_spec\.rb$}
  watch %r{^lib/(.+)\.rb$} do |m| "spec/lib/#{m[1]}_spec.rb" end

  watch %r{^spec/.+_spec\.rb$}
  watch %r{^app/(.+)\.rb$} do |m| "spec/#{m[1]}_spec.rb" end
  watch %r{^app/(.*)(\.erb|\.haml)$} do |m| "spec/#{m[1]}#{m[2]}_spec.rb" end
  watch %r{^lib/(.+)\.rb$} do |m| "spec/lib/#{m[1]}_spec.rb" end
  watch %r{^app/controllers/(.+)_(controller)\.rb$} do |m| ["spec/routing/#{m[1]}_routing_spec.rb", "spec/#{m[2]}s/#{m[1]}_#{m[2]}_spec.rb", "spec/acceptance/#{m[1]}_spec.rb"] end
  watch %r{^spec/support/(.+)\.rb$} do 'spec' end
  watch 'spec/spec_helper.rb' do "spec" end
  watch 'config/routes.rb' do 'spec/routing' end
  watch 'app/controllers/application_controller.rb' do 'spec/controllers' end
  # Capybara request specs
  watch %r{^app/views/(.+)/.*\.(erb|haml)$} do |m| "spec/views/**/#{m[1]}_spec.rb" end
  watch %r{^app/.*\.sass$} do 'spec/requests/*' end
end

I thought about doing something like:
watch %r{^app/models/*.rb} do system `killall bundle` end
…

But that's obviously an enormous kludge. Still it'd be better than seeing fakely-passing tests scroll by.
Thanks for any advice on making this setup better.

A: Here is my "Day 1" edit (that is, the one above was me fumbling around trying
to get it going with as little learning as possible, but this one is a bit
more informed). This one is working much better for me.
notification :on
guard 'spork', wait: 45, rspec_env: { 'RAILS_ENV' => 'test' } do
  [
    %r{^config/(environments|initializers)/.+\.rb$},
    %r{^config/(application|environment|routes)\.rb$},
    %r{Gemfile(.lock)?},
    %r{^lib/},
    %r{app/(models|controllers)},
    'spec/spec_helper.rb'
  ].each do |e| watch e end
end
guard 'rspec', version: 2 do
  watch %r{^spec/.+_spec\.rb$}
  watch %r{^app/(.+)\.rb$} do |m| "spec/#{m[1]}_spec.rb" end
  watch %r{^lib/(.+)\.rb$} do |m| "spec/lib/#{m[1]}_spec.rb" end
  watch %r{^app/(.*)(\.erb|\.haml)$} do |m| "spec/#{m[1]}#{m[2]}_spec.rb" end
  watch %r{^app/views/(.+)/.*\.(erb|haml)$} do |m| "spec/views/**/#{m[1]}_spec.rb" end
  watch %r{^app/.*\.sass$} do 'spec/requests/*' end
end

It's working OK. More improvements to come, I bet.
—☈


text:
Q: Python: Turn off automatic output in console/shell between asking user for input when I run the code below, I'm constantly hammered by a load of object creation confirmations printing between user inputs... I would love if there was some way I could silence the console while the user focuses on inputting answers. I've found some sketchy solutions, but they seem too convoluted for how simple the issue is. Code snippet and sample output below. Thanks!
Code:
#Engages in battles until user quits
def battle(self):

    battles_threshold = min([a.battles_fought for a in self.artists])
    contenders = [a for a in self.artists if
        a.battles_fought == battles_threshold]
    noncontenders = list(set(self.artists)-set(contenders))
    print(noncontenders)
    contenders.append(random.choice(contenders))
    contender1=contenders.pop(random.choice(range(len(contenders))))
    contender2=contenders.pop(random.choice(range(len(contenders))))
    elo1 = contender1.elo
    elo2 = contender2.elo
    outcome = ''
    while (outcome != 'y' and outcome != 'n' and
        outcome != 'm' and outcome != 'q'):
        outcome = \
        raw_input('Do you like "' + contender1.name +
            '" more than "' + contender2.name + '"?\n')
    if outcome == 'q':
        return None
    elif outcome == 'y':
        contender1.elo_calc(1,contender2.name,elo2)
        contender2.elo_calc(0,contender1.name,elo1)
    elif outcome == 'n':
        contender1.elo_calc(0,contender2.name,elo2)
        contender2.elo_calc(1,contender1.name,elo1)
    else:
        contender1.elo_calc(0.5,contender2.name,elo2)
        contender2.elo_calc(0.5,contender1.name,elo1)
    pickle.dump(music_battler, open(self.path_name +
        'music_battler.p','wb'))
    self.battle()

Output:
Do you like "basshunter" more than "lil wayne"?
y
[<__main__.Artist instance at 0x10dc91ab8>, <__main__.Artist instance at      0x10dc7b050>, <__main__.Artist instance at 0x10dcdb878>, <__main__.Artist instance at 0x10dc82098>, <__main__.Artist instance at 0x10dc830e0>, <__main__.Artist instance at 0x10dc7b908>, <__main__.Artist instance at 0x10da15d88>, <__main__.Artist instance at 0x10dcd1128>, <__main__.Artist instance at 0x10dc7b950>, <__main__.Artist instance at 0x10da0c170>, <__main__.Artist instance at 0x10dccf998>, <__main__.Artist instance at 0x10dc911b8>, <__main__.Artist instance at 0x10dcd89e0>, <__main__.Artist instance at 0x10da1f050>, <__main__.Artist instance at 0x10da0d200>, <__main__.Artist instance at 0x10dc8b1b8>, <__main__.Artist instance at 0x10dab4c68>, <__main__.Artist instance at 0x10dcd1a70>, <__main__.Artist instance at 0x10dcd8290>, <__main__.Artist instance at 0x10dc8b878>, <__main__.Artist instance at 0x10dc9f320>, <__main__.Artist instance at 0x10dcd1dd0>, <__main__.Artist instance at 0x10dc91b00>, <__main__.Artist instance at 0x10dc7b488>, <__main__.Artist instance at 0x10da0d320>, <__main__.Artist instance at 0x10da22b48>, <__main__.Artist instance at 0x10dc85098>, <__main__.Artist instance at 0x10da0bb48>, <__main__.Artist instance at 0x10dcd1c20>, <__main__.Artist instance at 0x10dc7bcb0>, <__main__.Artist instance at 0x10dc85a70>, <__main__.Artist instance at 0x10da1dc68>, <__main__.Artist instance at 0x10dc85e18>, <__main__.Artist instance at 0x10daee488>, <__main__.Artist instance at 0x10dc9fcb0>, <__main__.Artist instance at 0x10dcd14d0>, <__main__.Artist instance at 0x10dc91cf8>, <__main__.Artist instance at 0x10da39d88>, <__main__.Artist instance at 0x10dccfdd0>, <__main__.Artist instance at 0x10dc915f0>, <__main__.Artist instance at 0x10dc91908>, <__main__.Artist instance at 0x10dcddea8>, <__main__.Artist instance at 0x10da2aa70>, <__main__.Artist instance at 0x10dc916c8>, <__main__.Artist instance at 0x10dc85ef0>, <__main__.Artist instance at 0x10dccf710>, <__main__.Artist instance at 0x10dc85758>, <__main__.Artist instance at 0x10da11f80>, <__main__.Artist instance at 0x10dc7bfc8>, <__main__.Artist instance at 0x10dc9f7e8>]

Do you like "alesso" more than "taking back sunday"?

A: print(noncontenders) is the line that is giving you the printout [<__main__.Artist instance at 0x10dc91ab8>, <__main__.Artist instance at... removing it should eliminate that.


text:
Q: Validator inside Server control I have a server control that inherits from TableRow and INamingContainer.
I override the CreateChildControls and add three cells, in the first one I put a label, in the second one I put a textbox (lets call it A) with autopostback true and causevalidation true, a required validator and a range validator, in the third one another label.
Additionally, I have another textbox (B) with autopostback true and cause validation true, but in the webform, not in the server control.
When I write a valid value in the textbox A, the postback occurs but the rangevalidator is displayed. If after that, I change the value of the textbox B, the rangevalidator of the textbox A is not displayed and everything works as I expect.
What is wrong?


text:
Q: I can't update my MySQLi Database with PHP (no Errors) I can't Update my Database with PHP. I don't get any errors but it doesn't change anything!
Here is my file:
<?php
include_once 'dbh.inc.php';
?>

<?php
    $id = $_GET['verId'];
    $name = $_GET['verName'];
    echo $id;
    echo $name;
    $sql  = "UPDATE allusers SET ver = '1' WHERE idUsers = '$id';";
?>

The variables are defined and work.
Here's the dbh.inc.php file:
<?php

$servername = "localhost";
$dBUsername = "root";
$dBPassword = "";
$dBName = "loginsystem";

$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBName);

if (!$conn) {

    die("Connection failed: ".msqli_connect_error());

}
?>

Other files that use dbh.inc.php work fine.
Thanks for your help.

A: You need to execute your SQL, but the way you are using MySQLi is very wrong. Let me show you how to get started with a simple query.
First in your dbh.inc.php (you should name it properly too) you should have the following code:
<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new \mysqli("localhost", "root", "", "loginsystem");
$conn->set_charset('utf8mb4');

Do not use root for connection. Create a valid MySQL user with a proper password.
Then in your main PHP file, you can use it as follows:
<?php

include_once 'dbh.inc.php';

$id = $_GET['verId'];
$name = $_GET['verName'];
echo $id;
echo $name;

// prepare -> bind data -> execute
$stmt = $conn->prepare("UPDATE allusers SET ver='1' WHERE idUsers=?");
$stmt->bind_param('s', $id);
$stmt->execute();

I used here what is called a prepared statement. You can learn more about MySQLi here: https://phpdelusions.net/mysqli_examples/update


text:
Q: Why are Selenium searches delay compared to The Human Hand ( Manual search ) I'm using the facebook webdriver with PHP Unit.
Whenever I enter 'PHP Unit' manually in a search field. It finds it instantly(within a second).
The code below is what I use to send 'PHP Unit' into the searchbox and the code works just fine.
Just whenever selenium enters the text into the searchbox, it takes about 8-13 seconds before it finds a result/starts searching.
Question: Any clue why this happens and is it normal or can I bypass this issue somehow?
$this->webDriver->findElement(WebDriverBy::xpath('//*[@id="datatable_modules_wrapper"]/div[3]/div[2]/div[3]/div/table/tfoot/tr/td[1]/div/input'))->click();
sleep(1);
$this->webDriver->getKeyboard()->sendKeys('PHP Unit');

EDIT: The searchbox has live filtering so when I start typing it searches instantly.
When I enter the text with selenium, it pastes it all in at the same time basically, could this be an side-effect of it?

A: Your edit is pointing to your issue.  Here is the logic and execution.
Manual:
 1. Type some text
 2. javascript is executed on text change which filters results.  The time to enter the key and see results should be minimal but the performance decreases because it is already filtered for each letter. Thus subsequent letters entered take less time to visually see than before.
Automated:
 1. All letters are suddenly existing in the search.  The filter will have to process all letters at the same time resulting in a longer javascript filter time than if there was one at a time. (shouldn't be that much longer though)
The overall time should be shorter for the automated test even though the "appearance" of the filter should be shorter.  So if you time your manual entry to completed rendering and then time your automated entry to completed rendering the automation time should be faster overall.
If this is not the case in your situation which points to an application problem in the processing of that control.  The javascript filter execution is not being fired the same way.  You might try a manual copy and paste and compare this as the events might actually be different javascript events to execute the filter.  If the manual copy and paste doesn't match the same behavior then I suggest trying to send individual key strokes and not use the built in sendkeys functionality.  The sendkeys will be closer to a copy & paste than an actual typing of the keyboard.
I know how to do this in other languages, but I don't think php has built out as much support for this as other languages.  pear.php.net seems to have a little support of this type of functionality that would send hardware keystrokes and not just modify the DOM with text on the control.


text:
Q: Error when I try playground for Swift in Xcode 6 beta I encountered the following error when I create and open a playground for Swift, any solution for it?
Error running playground.
Failed to prepare for communication with playground.

A: I'm experiencing the same problem, but restarting xCode6-beta seems to solve it.

A: For me the restarting XCode 6 did not solve the problem. So I restarted the Mac. It worked afterwards.
This tutorial was helpful: http://www.raywenderlich.com/74438/swift-tutorial-a-quick-start

A: On Xcode 6.1.1
Creating playground using the path Xcode->Start and selecting "Get Started With a Playground" is giving "Error running playground. Unable to find suitable target device"
Creating playground using the path Xcode->File->New and then choosing playground => No errors


text:
Q: Showing that the Class of Cyclic Groups Aren't Axiomatizable The class of finite cyclic groups are not axiomatizable, for if we supposed they were by some set of sentences $\Sigma$, then there would exist a model for $\Sigma$ of at least order $n$ for all $n \in \mathbb{N}$ (i.e., the model $Z_{n+1}$ for each $n$).  Then we would have that there would also exist an infinite model as well by the compactness theorem (and hence we would have a contradiction).
But evidently the theory all cyclic groups (including the infinite ones) are also not axiomatizable.  Why is this so?

A: Suppose there is a set $\Sigma$ of first-order sentences such that $\mathrm{Mod}(\Sigma)$ is the class of all cyclic groups $(A,+)$.  For $m,n\in\mathbb Z\setminus\{0\}$, let $\varphi_{m,n}(x,y)$ be the formula $(x\ne0)\land(y\ne0)\land(mx\ne ny)$. Then $\Sigma\cup\{\varphi_{m,n}(x,y):m,n\in\mathbb Z\setminus\{0\}\}\ $ is not satisfiable, although every finite subset is satisfiable. This contradicts the compactness theorem.

A: André's answer provides an answer to your question, but the result can be strengthened: the cyclic groups are not axiomatisable even among countable groups.
This is, in part, because the theory of $({\bf Z},+)$ is not $\omega$-categorical. For instance ${\bf Z}\oplus {\bf Q}$ is elementarily equivalent to it, and is evidently not cyclic. In fact, the theory has $2^{\aleph_0}$ nonisomorphic countable models. To see this, notice that there are that many complete types over $\emptyset$.
On the other hand, using the classification theorem for finitely generated abelian groups, one can show that cyclic groups are elementary relative to the (clearly non-elementary) class of finitely generated groups.

A: Basically the same idea will work: By Upward Lowenheim-Skolem, there would be models of arbitrarily high (in particular, uncountable) cardinality. But an uncountable group cannot be cyclic.


text:
Q: Blocks HTML Cache & Sub Category Display So I've moved my store up to 1.9.2.1 Everything is looking good except for the Blocks HTML Cache.
I'll try to explain this as best I can.
I have the common setup of using a static block calling a script to display sub-categories within a parent category.  Something similar to this tutorial
It's always worked without any hitches...Until I upgraded. The issue I'm seeing is that any category pages using this static block script to display sub-categories are failing, resulting in all of these categories displaying the same cached sub-categories page. It's like it's not re-caching and just serving up the same content to all of these pages. It means customers can't navigate through to the correct layers of the site because any Category using the sub-category script will see the same cached layout with incorrect sub categories.
I've run a Mage cleanup script to reset any strange permission issues but with no avail. As a temporary fix so my customers can actually browse the site, I've disabled the Blocks HTML Cache which fixes the issue straight away. So clearly the issue is with the Cache not serving up the content correctly or in fact, realising that a re-cache is required. How do I go about fixing this? Is there a more efficient way of serving sub-categories within parent categories that do no list individual products?
Here is the code I am using to display sub categories in a nice grid
(Pastbin):

<?php
if($_collectionSize):
    $i=0;
    $layer = Mage::getSingleton('catalog/layer');
    ?>

    <?php
    foreach ($_categories as $_category):

        $layer->setCurrentCategory($_category);
        $_category = Mage::getModel('catalog/category')->load($_category->getId());

        $products = Mage::getModel('catalog/product')->getCollection()
                                                ->addCategoryFilter($_category)
                                                ->addAttributeToSort('price', 'asc')
                                                ->setPageSize(1)
                                                ->load();

        $prod = $products->getFirstItem();
        $lowestProductPrice = $taxHelper->getPrice($prod, $prod->getPrice(), true, null, null, null, null, false);
        $formattedPrice = Mage::helper('core')->currency($lowestProductPrice, true, false);

            //$originalCategory->getThumbnail();
             $_img = ($_category->getThumbnail()) ? "/media/catalog/category/".$_category->getThumbnail() : "/media/placeholders/small.jpg";
             $_img = Mage::getBaseUrl() . $_img;
        ?>
                    <li class="item <?php if(($i-1)%$_columnCount==0): ?> first<?php elseif($i%$_columnCount==0): ?> last<?php endif; ?>">
                        <a href="<?php echo $_category->getUrl(); ?>" title="<?php echo $_category->getName(); ?>" class="product-image">
                            <?php if($_img):?>
                                <img src="<?php echo $_img; ?>" alt="<?php echo $_category->getName();?>" />
                            <?php else:?>
                                <?php echo $_category->getName();?>
                            <?php endif;?>

<a href="<?php echo $helper->getCategoryUrl($_category); ?>" title="<?php echo $this->stripTags($_category->getName(), null, true) ?>"><?php echo $_category->getName(); ?>

    <?php endforeach; ?>

<?php else: ?>

<?php echo $this->__('No categories found.'); ?>

<?php endif ?>

A: You may well be experiencing the static block cache bug introduced with 1.9.2, although reported as fixed in 1.9.2.1 I have still experienced caching problems with static blocks. More information available here
Magento 1.9.2.0 static block display issues
A good fix/workaround for this bug is this module
https://github.com/progammer-rkt/Rkt_SbCache


text:
Q: Count and Compare rows Query Mysql PHP I am a beginner in PHP, I want your help, if all rows of the query are correct: prints a message, if some or all do not meet the condition, print another message.
I need help with Qry and PHP sintaxis, i think i need use te COUNT, but i dont now exactly how do it.
Thanks.
My Table Name:  oder_product
+-----+-----+-----+-----+-----+------+
| id | item_id | shipping | delivery |
======================================
| 1  |    1    |   YES    |    NO    |
======================================

======================================
| 2  |    2    |   YES    |   YES    |
======================================
| 3  |    2    |   YES    |   YES    |
======================================
| 4  |    2    |   YES    |   YES    |
======================================
| 5  |    2    |   YES    |   YES    |
======================================

======================================
| 6  |    3    |   YES    |    NO    |
======================================
| 7  |    3    |   YES    |   YES    |
======================================

SELECT * FROM oder_product WHERE shipping='YES' AND delivery='YES' AND item_id='2';

PHP
If $result=all rows match;
Echo' All Products match';

else
Echo' some products don't match';

A: $sql=SELECT * FROM oder_product WHERE shipping='YES' AND delivery='YES' AND item_id='2';
$result=mysqli_query($con,$sql);

use mysqli_num_rows() to find number
$rowcount=mysqli_num_rows($result);
if($rowcount>0){
echo 'All Products match';
}
else{
echo 'some products don't match';
 }


text:
Q: How can I pass the value of a var to print in my TextView I want to print the values of var list2: [String] = [] in my UITextView
I'm writing this code, but it gives error
@IBOutlet weak var notesShow: UITextView!

override func viewDidLoad() {
    super.viewDidLoad()

    notesShow.text = list2
}

A: list2 is an array.  You cannot assign an array of string to a string.  Join the elements with a line break into a single string
notesShow.text = list2.joined(separator: "\n")


text:
Q: creating video from images array in ios creating but not playing smoothly i'm cutting video frame by frame and than give effect in frame (using aviary SDK) and than create video of that images.
well my code creates video with the expected duration but when i play this video it will play stickly (not smoothly).
Here is my code.
- (IBAction)generateVideo:(id)sender
{
    NSLog(@"Enter in generateVideo Action");

    NSString *videoPath = [[Util mySaveFileToPath] stringByAppendingString:@"/video2.mp4"];

    UIImage * img = (UIImage *)[arrFramesOfVideo objectAtIndex:0];

    [self exportImages:arrFramesOfVideo asVideoToPath:videoPath withFrameSize:img.size framesPerSecond:framePerSec numberOfSecondsPerFrame:(1/framePerSec)];
}

well fps i'm getting at the time when i'm fetching frames from video using AVAssetTrack so i think there is no prob with that.
- (void)exportImages:(NSMutableArray *)imageArray asVideoToPath:(NSString *)videoOutputPath withFrameSize:(CGSize)imageSize framesPerSecond:(float)fps numberOfSecondsPerFrame:(float)numberOfSecondsPerFrame
{
    NSError *error = nil;
    NSLog(@"Start building video from defined frames.");
    NSLog(@"Video Path = %@",videoOutputPath);
    AVAssetWriter *videoWriter = [[AVAssetWriter alloc] initWithURL:[NSURL fileURLWithPath:videoOutputPath] fileType:AVFileTypeQuickTimeMovie error:&error];

    NSParameterAssert(videoWriter);

    NSDictionary *videoSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                               AVVideoCodecH264, AVVideoCodecKey,
                               [NSNumber numberWithInt:imageSize.width], AVVideoWidthKey,
                               [NSNumber numberWithInt:imageSize.height], AVVideoHeightKey,
                               nil];

    AVAssetWriterInput* videoWriterInput = [AVAssetWriterInput
                                        assetWriterInputWithMediaType:AVMediaTypeVideo
                                        outputSettings:videoSettings];

    NSLog(@"videoWriterInput == %@",videoWriterInput);
    AVAssetWriterInputPixelBufferAdaptor *adaptor = [AVAssetWriterInputPixelBufferAdaptor
    assetWriterInputPixelBufferAdaptorWithAssetWriterInput:videoWriterInput
        sourcePixelBufferAttributes:nil];

    NSParameterAssert(videoWriterInput);
    NSParameterAssert([videoWriter canAddInput:videoWriterInput]);
    videoWriterInput.expectsMediaDataInRealTime = YES;
    [videoWriter addInput:videoWriterInput];

    //Start a session:
    [videoWriter startWriting];
    [videoWriter startSessionAtSourceTime:kCMTimeZero];

    CVPixelBufferRef buffer = NULL;

    //convert uiimage to CGImage.
     int  frameCount = 0;
    //double numberOfSecondsPerFrame = 6;
    double frameDuration = fps * numberOfSecondsPerFrame;

    //for(VideoFrame * frm in imageArray)
    NSLog(@"**************************************************");
    //for(UIImage * img in imageArray)
    for (int i = 0; i < arrFramesOfVideo.count; i++)
    {
        //NSLog(@"in loop");
        UIImage * img = (UIImage *)[arrFramesOfVideo objectAtIndex:i];
        buffer = [self pixelBufferFromCGImage:[img CGImage]];
        //dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.001 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

        if (adaptor.assetWriterInput.readyForMoreMediaData)
        {
            NSLog(@"frameCount == %d",frameCount);
            CMTime frameTime = CMTimeMake(i*numberOfSecondsPerFrame * 10000,10000);
            //CMTime frameTime = CMTimeMakeWithSeconds(frameCount*numberOfSecondsPerFrame, fps);
            CMTimeShow(frameTime);
            //CMTime frameTime = CMTimeMake(frameCount*frameDuration,fps);
            [adaptor appendPixelBuffer:buffer withPresentationTime:frameTime];
            frameCount ++;
            CVPixelBufferRelease(buffer);
        }
        else
        {
            i--;
            NSLog(@"adaptor not ready.");
            [NSThread sleepForTimeInterval:0.0001];
        }

    //});
    }
    NSLog(@"**************************************************");

    //Finish the session:
    [videoWriterInput markAsFinished];
    //[videoWriter finishWriting];

    [videoWriter finishWritingWithCompletionHandler:^{

        if (videoWriter.status == AVAssetWriterStatusFailed)
        {
            NSLog(@"Movie Save Failed.");
        }
        else
        {
            NSLog(@"Movie Saved.");
        }

    }];

    NSLog(@"Write Ended");
    NSLog(@"Video Path = %@",videoOutputPath);
}

And other code is default for getting buffer i don't think it is required in this question B'coz it is common (without any changes).
If any body done this please help me i spent one day for this but still not found any solution.
Thank you!


text:
Q: Ignore property from serialization in a collection of a type with Json.Net Is there an "easy way" to ignore a property from Model serialization on a collection of a type in Asp.Net Core?
For example
public sealed class MainViewModel
{
  public Guid Id { get; set; }

  [JsonIgnore("PropertyInSubViewModel")]
  public ICollection<SubViewModel> Products { get; set; }
}

The idea was to remove some property in SubViewModel from model serialization, so when I get it in my action, it would have its default value set, not the one set through the request.

A: Not with JsonIgnore. That can only be applied on the actual property that you want to ignore, and is constant at that point. However, JSON.NET does have support for conditional serialization. The easiest and most straight-forward is adding a ShouldSerialize* method to your class. You'd obviously need to determine some condition you could lean on for the determination, but that could be a straight-forward as literally setting some boolean on your sub view model instances. Basically, you just add something like:
public class SubViewModel
{
    ...

    public bool ShouldSerializePropertyInSubViewModel()
    {
         // return true or false to either allow or disallow serializing the property on this instance
    }
}


text:
Q: Как найти и отредактировать нужный бизнес-процесс в Битрикс? Осваиваю Битрикс.
Структура процесса:
- приходит электронная завка на подразделение;
- сотрудник его принимает заявку и формирует задачу на какого-то исполнителя.
Нужно сделать так, чтобы при формировании задачи на конкретного исполнителя (назовем его id=1234), конечная дата выполнения задачи (а также и заявки) увеличивалась бы на 1 день.
Извините, если путаюсь в терминах.


text:
Q: All framework error when launch framework/Info.plist: No such file or directory I have a project on react native,
I'm Stack all day with this error I try a lot of things but nothing works, build successfully but the application is not launched on device or simulator here is the error I got

Could not install at this time.
Failed to load Info.plist from bundle at path /Users/BT/Library/Developer/CoreSimulator/Devices/32A76497-8C7B-4639-B3F9-80379AF5CB9A/data/Library/Caches/com.apple.mobile.installd.staging/temp.SEVqpI/extracted/XXXXXX.app/Frameworks/RCTVibration.framework; Extra info about Info.plist: Couldn't stat /Users/BT/Library/Developer/CoreSimulator/Devices/32A76497-8C7B-4639-B3F9-80379AF5CB9A/data/Library/Caches/com.apple.mobile.installd.staging/temp.SEVqpI/extracted/XXXXX.app/Frameworks/RCTVibration.framework/Info.plist: No such file or directory

Even I reset to the old version of the project witch worked perfectly I'm getting the error
When I add a info.plist to RCTVibration other library has the same problem as 20 library
I tried to clean project, close xcode, delete derived data, restart Mac i tried Embded Framework copy only when installing ... but still stuck i can't delete use_frameworks! because i have dynamic and no dynamic framework
On device i'm getting a different error :
Details
Unable to install "XXXXX"
Domain: com.apple.dt.MobileDeviceErrorDomain
Code: -402653103
Could not inspect the application package.
Domain: com.apple.dt.MobileDeviceErrorDomain
Code: -402653103
User Info: {
DVTRadarComponentKey = 282703;
MobileDeviceErrorCode = "(0xE8000051)";
"com.apple.dtdevicekit.stacktrace" = (
0   DTDeviceKitBase                     0x0000000129dbe93f DTDKCreateNSErrorFromAMDErrorCode + 220
1   DTDeviceKitBase                     0x0000000129dfd124 __90-[DTDKMobileDeviceToken installApplicationBundleAtPath:withOptions:andError:withCallback:]_block_invoke + 155
2   DVTFoundation                       0x000000010d9a1b43 DVTInvokeWithStrongOwnership + 71
3   DTDeviceKitBase                     0x0000000129dfce65 -[DTDKMobileDeviceToken installApplicationBundleAtPath:withOptions:andError:withCallback:] + 1440
4   IDEiOSSupportCore                   0x0000000129c6dd28 __118-[DVTiOSDevice(DVTiPhoneApplicationInstallation) processAppInstallSet:appUninstallSet:installOptions:completionBlock:]_block_invoke.292 + 3513
5   DVTFoundation                       0x000000010dad02aa DVT_CALLING_CLIENT_BLOCK + 7
6   DVTFoundation                       0x000000010dad1ecc __DVTDispatchAsync_block_invoke + 1191
7   libdispatch.dylib                   0x00007fff6d0416c4 _dispatch_call_block_and_release + 12
8   libdispatch.dylib                   0x00007fff6d042658 _dispatch_client_callout + 8
9   libdispatch.dylib                   0x00007fff6d047c44 _dispatch_lane_serial_drain + 597
10  libdispatch.dylib                   0x00007fff6d0485d6 _dispatch_lane_invoke + 363
11  libdispatch.dylib                   0x00007fff6d051c09 _dispatch_workloop_worker_thread + 596
12  libsystem_pthread.dylib             0x00007fff6d29ca3d _pthread_wqthread + 290
13  libsystem_pthread.dylib             0x00007fff6d29bb77 start_wqthread + 15
);
}
System Information
macOS Version 10.15.7 (Build 19H2)
Xcode 12.0.1 (17220)
any help will be appreciated

A: I tried even uninstall xcode and install again another version, also pull project git on a new location, create new simulator, restart device nothing worked
What worked for is adding for every framework, click on choose info.plist file like image show it and pods-Project-info.plist and it will be filled with correct information
It's not the best solution because it takes me a lot of time to associate all plist file, but it's the only solution that worked for me

A: Try running your project with npx react-native run-ios.
After hours of struggling and trying everything I found (cleaning derived data, erasing content and settings of simulators, reinstalling Xcode...)
This is the only thing that made it work, I was even able to build with Xcode after running the build with npx.

A:
I was getting a similar error even after the builds passed and the simulator popped up. But the app was prevented from opening as it seems there was some .plist file missing in the frameworks.
I rechecked and set the Embed mode to "Do not Embed" for each of the frameworks added in the .xcworkspace target > General.
I also might had Clean the build folder (Cmd + Shift + K), closed the xcode, deleted DerivedData, pod deintegrate && pod update before shooting the Run in xcode again.
Other Info: Xcode-13.2.1, React Native project, M1Pro mac, Xcode running in Rosetta, Excluded Architecture - arch64 (in target & project Build Settings)

A: Clean drive data in XCODE preferences, clean and then rebuild the project. Hope it works!

A: One probable solution is following the steps:

*

*Run pod install command in your terminal

*Before installing App again delete content of your Derived Data
folder
Build and run to install the app.
Moreover if the above 2 steps doesn't work the try removing use_frameworks! from your Podfile and follow steps 1 & 2.

A: I also tried all the methods mentioned above, but they didn't work, and when I debugged all the Cocoapod and XcodeProj in Ruby, it was confirmed that the problem occurred due to the special setting. It may be a unique case, but it is very simple to check, so I recommend you to try it...
if ENV['INFOPLIST_FILE'] has a file for any Info.plist,
CocoaPods doesn't make Info.plist for Pod targets.
reference: https://github.com/CocoaPods/Xcodeproj/blob/29cd0821d47f864abbd1ca80f23ff2aded0adfed/lib/xcodeproj/project/object/build_configuration.rb#L115
I put this phrase in for the test and I was able to confirm that the file existed.
puts "#{ENV['INFOPLIST_FILE']}"
Finally, I could solved adding this line on top of Podfile.
ENV['INFOPLIST_FILE'] = nil
By the way, I don't know how I ended up assigning a specific Info.plist file to ENV...


text:
Q: tampermonkey getting button by style instead of class or ID How would I go about checking if this is is active:
When its not active its just
The "style" is the part that makes it "active" and visible on screen.   Is there a way that I can get the Jump button by that style inside the div?

A: You can check to see if the element has a style attribute by putting [style] in a selector:
if (document.querySelector('#jump[style]')) {
  console.log('style attribute exists on jump element');
} else {
  console.log('style attribute doesn\'t exist');
}


text:
Q: Require a certain amount of reputation to answer questions that already have an accepted answer?
Possible Duplicate:
New Users Adding Answers to Answered Questions

Maybe around 5? Low enough to not prevent better solutions, but high enough to stop "thank you" answers and some spam answers.
P.S. I'm suggesting an addition to protection, not a replacement.

A: I'd say no because I've seen on numerous occasions where a first-time answer is a new user who comes in and has a very good answer to share on an existing question that may have an accepted answer, but one that is still relatively poor.  The worst thing we can do is not allow someone to answer a question when they have a good answer to contribute, and this has the potential to do that.
Rather than open ourselves up to the possibility of denying quality answers, I'd say we should stick with relying on the community/moderators to clean up the not-so-quality answers.


text:
Q: Any statistics available regarding relative popularity of OpenId providers? I'm using OpenId, and am providing buttons for all the usual suspects, but I'd like to be a little more scientific about it.
Are there any public stats regarding numbers of users for each provider?

A: Why are you "providing buttons for all the usual suspects" ?!
One of the main reasons for OpenID is to avoid the NASCAR problem (which requires buttons for all the usual suspects).
One OpenID button should be enough.


text:
Q: What is the alternate to npts function of basemap in cartopy? I want to emulate the function of ntps which is in basemap.Geod class.
Its function is described as follows:
Given a single initial point and terminus point (specified by
        python floats lon1,lat1 and lon2,lat2), returns a list of
        longitude/latitude pairs describing npts equally spaced
        intermediate points along the geodesic between the initial and
        terminus points.

I want to do the same thing in cartopy, aparantly one way is to calculate the distance needed between each pair of successive coordinate and use that distance to compute coordinates from start to end point. Is there any other way to do so?

A: Based on cartopy's source, https://github.com/SciTools/cartopy/tree/master/lib/cartopy/geodesic
, it is clearly that no equivalent of ntps() function is available from cartopy.
However, it is not difficult to compute locations of points along a geodesic if you know the bearing from one of the end point. Here are steps that you can follow:

*

*Use Geodesic.inverse() with input of (long, lat) of point1 and2, and get (forward_bearing, backward_bearing, geodesic_dist) as the result.

*Suppose you want to get (long, lat) of a point (say 1/4 of the whole distance) along that geodesic (in 1), use Geodesic.direct() with long1, lat1, the obtained forward_bearing and geodesic_dist/4.

A better alternative is to use pyproj and forget all the above.


text:
Q: How to add separate text and separate image on the one heigth [CSS/HTML]? I wanna to set up image and paragraph on one height as I said in title. And I wanna this image to be like the same width and height with the paragraph. The main problem, if I tried to use my container(I don't really know if it's a container), the image goes inside the paragraph. I got a really terrible headache and didn't solve it yet. Need some help.
This is my code + image of page that I wanna to create:

body {
  background-image: url('');
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-size: 100%;
}

.h1_main {
  text-align: center;
  text-shadow: #06FE35 1px 1px 20px;
  font-size: 50px;
}

.pretty_1 {
  margin-top: 50px;
  text-shadow: grey 1px 1px 15px;
  font-size: 40px;
}

.container {
  border: 7px solid #01FE30;
  margin-right: 75%;
  padding: 20px 30px 20px 30px;
  font-size: 30px;
  text-shadow: #F40752 1px 1px 50px;
  text-align: center;
}

.right_image {
  float: left;
}

.ecorp {
  text-shadow: red 1px 1px 6px;
  text-align: center;
}

.transparent {
  zoom: 1;
  filter: alpha(opacity=50);
  opacity: 0.5;
  position: fixed;
  text-align: left;
  bottom: 0px;
  width: 100%;
}

.fsoc {
  font-size: 20px;
  text-shadow: red 2px 0px 0px;
}

.links {
    font-color: black;
    text-shadow: grey 1px 1px 10px;
    text-decoration: none;
    color: black;
    font-size: 26px;
    text-align: center;
}

.center {
  text-align: center;
}
 <!DOCTYPE html>

    <meta charset="utf-8">
    <title>MR.Twister</title>
    <link rel='stylesheet' type='text/css' href='podstava.css'>

Who is

      Main
        About
        Galley

Wiki Says:

 - - - - - - - - - - - - - - - - - - - - - - - - - - - -

      Hi there Hi there

      - - - - - - - - - - - - - - - - - - - - - - - - - - - -

      You are the best thing to ever happen to me. You are the true definition of a true value. True friendship stands the test of time and you have shown me what it is to have real friends. I value your friendship and I will remain every grateful for your love. Thanks for being my friend. Cheers to our loving friendship.ECorp.

      all rights reserved (c)

here is a picture

A: There are many ways to accomplish this but using the latest CSS3+ properties such as Flex and Grid, you can create the layout you want.
All that is needed for the flex solution is to specify the container to width: 100%; to make the container take full width of the page, allowing you to layout freely, set its display: flex; to use the flex property and set the flex-direction: row; to make the items inside the container be aligned horizontally.
Then separate the right content in a div and the left content in a different div with both being inside the container.
Refer to this fiddle, I've fixed some code issues that you have. Also, don't use the font tag as it's not supported in HTML5, use the style attribute instead.
https://jsfiddle.net/9oej1z6p/


text:
Q: Error al activar funcion popup en jquery Tengo el siguiente código que funciona correctamente y me permite desplegar todos los anuncios publicados en mi web por un usuario y que al hacer click sobre cada uno de ellos se desplegue un popup mas información sobre el mismo. Mi problema es que desarrollé una nueva sección en la que hay un botón debajo de cada anuncio que permite editar el mismo. Lo que pretendo es que al hacer click en cada uno de estos botones, se ejecute una función jquery que cumpla el mismo objetivo que la expresada más arriba. Sin embargo, tengo un error y es que al cliquear este botón, se desplegan todos los popups a la vez y no cada uno en particular como sucedía con la función anterior. Dejo el código que tengo actualmente.
Código PHP
    <?php
    $CantShow=10;
        $compag = (int)(!isset($_GET['publishpShow'])) ? 1 : $_GET['publishpShow'];
        $TotalReg = mysqli_query($conexion, "SELECT * FROM anuncios");
        $totalr = mysqli_num_rows($TotalReg);
        $TotalRegistro = ceil($totalr/$CantShow);
        $IncNum = (($compag +1)<=$TotalRegistro)?($compag +1):0;
        $consult = mysqli_query($conexion, "SELECT * FROM anuncios WHERE id = '$id' ORDER BY id_pub DESC LIMIT ".(($compag-1)*$CantShow)." , ".$CantShow);
        //$consultA = mysqli_query($conexion, $consult);
    ?>

        <?php
        while($lista = mysqli_fetch_array($consult)){
                $userid = mysqli_real_escape_string($conexion, $lista['id']);
                $usuariob = mysqli_query($conexion, "SELECT * FROM usuarios WHERE id = '$userid'");
                $use = mysqli_fetch_array($usuariob);
        ?>

                            <?php $date = $lista['fecha']; ?>

Publicado el <?php echo date('d/m/Y', strtotime($date))?> a las <?php echo date('G:i', strtotime($date))?>

En <?php echo $lista['provincia']?>

<?php echo $lista['localidad']?>

<?php echo $lista['cantidad']?>

<?php echo $lista['moneda']?>

Fee <?php echo $lista['comision']?>%

<?php echo $lista['operacion']?>

Acepta:

<?php echo $lista['p2p']?>

<?php echo $lista['f2f']?>

                            <?php
                            if($use['id'] == $_SESSION['id']){
                            ?>

Así veran tu anuncio los demás usuarios. <a href="myannouncements.php?id=<?php echo $use['id'];?>">Editar

                            <?php
                            }
                            ?>

                                    <img class="profpicDpub" src="img/profilepics/<?php echo $use['avatar']?>" alt="Avatar">

@<?php echo $use['usuario']?>

                                        <a href="userprofile.php?id=<?php echo $use['id'];?>" class="publishDProfile">Ver perfil

                                    <?php
                                        if($use['criptotop'] != 0) {?>

                                    <?php } ?>

Publicado el <?php echo date('d/m/Y', strtotime($date))?> a las <?php echo date('G:i', strtotime($date))?>

En <?php echo $lista['provincia']?>
<?php echo $lista['localidad']?>

<?php echo $lista['operacion']?>

<?php echo $lista['cantidad']?>

<?php echo $lista['moneda']?>

Fee <?php echo $lista['comision']?>%

                                Métodos aceptados:

<?php echo $lista['p2p']?>

<?php echo $lista['f2f']?>

                                <a href="chat.php?id=<?php echo $use['id']?>">Contactar

Modificar

                    <input type="submit" id="delete" name="delete" class="deleteButton" value="Eliminar" onclick="confirm();">

        <?php } ?>

Código JQuery que funciona correctamente: el anuncio popup se desplega al cliquear sobre "publishContainer"
    $(function() {
    $('.publishContainer').on('click', function(e) {
        $(this).find('.publishOverlay').addClass('active');
        $(this).find('.publishannounce').addClass('active');
        $(this).find('.publish').addClass('active');
        $(this).find('.publishCriptoTop').addClass('active');
        $(this).addClass('active');
    });
    $('.btn-cerrar-popup').on('click', function(e) {
        e.stopPropagation();
        $(this).closest('.publishOverlay').removeClass('active');
        $(this).closest('.publishannounce').removeClass('active');
        $('.publish').removeClass('active');
        $('.publishCriptoTop').removeClass('active');
        $('.publishContainer').removeClass('active');
    });
});

Código jquery que no logro hacer funcionar: el anuncio popup debería desplegarse al hacer click en "publishPModify"
$(function() {
    $('.publishPModify').on('click', function(e) {
        var publishContainer = $('.publishContainer');
        // Obtener ventana del anuncio y mostrar
        $(publishContainer).find('.publishOverlay').addClass('active');
        $(publishContainer).find('.publishannounce').addClass('active');
        $(publishContainer).find('.publish').addClass('active');
        $(publishContainer).find('.publishCriptoTop').addClass('active');
        $(publishContainer).addClass('active');
    });
    $('.btn-cerrar-popup').on('click', function(e) {
        var publishContainer = $('.publishContainer');
        e.stopPropagation();
        $(this).closest('.publishOverlay').removeClass('active');
        $(this).closest('.publishannounce').removeClass('active');
        $('.publish').removeClass('active');
        $('.publishCriptoTop').removeClass('active');
        $(publishContainer).removeClass('active');
    });
});

Aclaraciones: 1. El código PHP aquí es uno solo para no ocupar tanto espacio en la pregunta. Sin embargo, en mi web es el mismo pero en dos secciones diferentes. El código que funciona no incluye el div "publishPModify" que sería el botón de 'editar', sino que ese está incluido en la sección en la cual estoy trabajando actualmente y con la cual no logro hacer que funcione el código jquery. 2. Los códigos jquery estan alojados en dos archivos .JS diferentes, llamando respectivamente a cada uno de ellos en las diferentes secciones de mi web.
Necesito entender cómo puedo hacer que funcione el código que actualmente no está funcionando correctamente. Desde ya muchas gracias.

A: El problema es que con $('.publishContainer'); jQuery buscará en todo el documento y va a devolver el primer elemento que coincida con el selector. Debes buscar el contenedor padre desde el elemento que dispara el evento, con el método .closest().
$(function() {
    $('.publishPModify').on('click', function(e) {
        // $(this) es el elemento que disparó el evento
        let publishContainer = $(this).closest('.publishContainer');
        // Obtener ventana del anuncio y mostrar
        $(publishContainer).find('.publishOverlay').addClass('active');
        $(publishContainer).find('.publishannounce').addClass('active');
        $(publishContainer).find('.publish').addClass('active');
        $(publishContainer).find('.publishCriptoTop').addClass('active');
        $(publishContainer).addClass('active');
    });
    $('.btn-cerrar-popup').on('click', function(e) {
        let publishContainer = $(this).closest('.publishContainer');
        e.stopPropagation();
        $(this).closest('.publishOverlay').removeClass('active');
        $(this).closest('.publishannounce').removeClass('active');
        $('.publish').removeClass('active');
        $('.publishCriptoTop').removeClass('active');
        $(publishContainer).removeClass('active');
    });
});

Algunas recomendaciones:

*

*Declara tus variables con let para que solo estén disponibles en cada bloque

*Podrías tener una sola ventana (o popup) para controlar todos los anuncios y, al abrirla, tomar los datos necesarios desde .publishContainer para mostrarlos en esa ventana. Es un poco más trabajo en Javascript, pero resultará mucho más eficiente al reducir el código HTML creado y enviado desde PHP al navegador.


text:
Q: character encoding of the server logs in s3 As the question suggest, I lneed to know the encoding of the data in the server logs.
I am getting the server logs using S3ObjectInputStream. as following:
amazonS3Client as3c;
S3ObjectInputStream is = as3c.getObject(bucketName, key).getObjectContent();
//read it for processing using buffered input stream.
BufferedReader br = new BufferedReader(new InputStreamReader(is,..unknown..));
//need character encoding(charset eg: UTF-8, UTF-16 etc.) of the data in the object
//to pass it to InputStreamReader.

In the docs, I only see getContentEncoding() function but I do not think that it fits my purpose.
Useful references:
ObjectMetadata
AmazonS3Interface

A: Did you check the other constructor of InputStreamReader? There is a constructor that receives only the InputStream as a parameter.
http://docs.oracle.com/javase/7/docs/api/java/io/InputStreamReader.html
As far as I know, the files in S3 are saved using the encoding the writer has chosen. Anyway I would suggest you to try the UTF-8 encoding and check whether it throws a UnsupportedEncodingException.