How set XAttribute Value null

Question: <code> XElement xml = new XElement("MyMenu",
                     from c in db.Security_Module_Menus
                     //where (c.ParentID == 0)
                     orderby c.Menu_ID
                     select new XElement("Item",
                               new XAttribute("Text", c.Menu_Name), new XAttribute("NavigateUrl", c.Target_URL)

                               )
                     );
</code>
From my above syntax c.Menu_Name,c.Target_URL  values are  nullable.Show me the error
Value cannot be null.
Parameter name: value I know SetElementValue() used to solve this error.But how can i use to my above syntax.Help me to Use it.Show me syntax
Answer: Presumably you want to avoid creating the attributes if c.Menu_Name and c.Target_URL are null? If so, you can do it as follows:
<code>new XElement("MyMenu",
  from c in db.Security_Module_Menus
  orderby c.Menu_ID
  select new XElement("Item",
    c.Menu_Name == null ? null : new XAttribute("Text", c.Menu_Name),
    c.Target_URL == null ? null : new XAttribute("NavigateUrl", c.Target_URL))
  )
</code>
Comment: Thanks for help .I have Menu_ID and Parent_ID columns.want to create ...........on basis of parent id.http://stackoverflow.com/questions/3412530/how-to-create-dynamic-aspxmenu-from-database .Here you can see my talbe.Plz help me to solve this proble.Thanks again for help.

How set XAttribute Value null


iOS: Saving to Data Structure

Question: I would like to create an NSObject class that I can use the instance of and save to its variables and later pass its data elsewhere (NSManagedObject).  Do I need to do anything  else besides creating a new Object-C Class that inherits from NSObject.  Create Variables in .h and synthesize in .m.
i.e.:
my .h file:
#import <Foundation/Foundation.h>
@interface MyDataClass : NSObject

@property (nonatomic, retain) NSNumber *variable1
@property (nonatomic, retain) NSString *variable2
@property (nonatomic, retain) NSDate *variable3

@end

.m file:
#import "MyDataClass.h"

@implementation MyDataClass

@synthesize variable1, variable2, variable3

@end

I would like to be able do the following in some SomeViewController:
@property (nonatomic, strong) MyDataClass *newDataClass

@systhesize newDataClass;

newDataClass.variable1 = @"123457890";
newDataClass.variable2 = @"This is the new Variable";
newDataClass.variable3 = [NSDate date];

Is there anything else I need to do to initialize each variable when an instance of this class is created?  Am I missing anything?
Comment: I am not sure what exactly you want to do. Do you want to create a custom NSManagedObjectClass which you would use to store your data?
Answer: That's all that you need for a custom object which you want to use to store data.
Of course when you go to use it (in SomeViewController), you need to actually create an instance of your class before you start setting the variables:
self.newDataClass = [[MyDataClass alloc] init];

I would also use self.newDataClass instead of just newDataClass unless you have a reason not to.
Comment: What's the advantage over self.newDataClass vs using the synthesized property newDataClass directly?
Comment: Actually I would go a step further and get in the habit of using auto-sythesized underscore variables along with the "new" helper which does the same thing as alloc ]init] as well. _newDataClass = [MyDataClass new];
Comment: Thank you!  Last question, once I'm done with this instance and want to delete/clear it, should I just do newDataclass = NULL; ?
Comment: Yes, since this is a `strong` declared property, you should just set it to `nil` when you are done using it and it will release the object.  Using `self.` invokes the setter/getter (as appropriate) and makes it easy in the future if you need to change the default behavior.  For instance, if you need to update another variable whenever this one is changed, you can add it one place (in a custom setter) and this will happen automatically instead of having to find every place that you updated it and adding it there.
Comment: For some more specific details about using `self.`, see this question:  http://stackoverflow.com/q/4142177/937822 (especially the most upvoted answer, rather than the accepted answer).

iOS: Saving to Data Structure


Simulation from cdf

Question: Give a method for simulating from

$$F(x) =\left\{\matrix{ \frac{(1-e^{-2x}+2x)}{3},& 0 < x < 1\cr
\frac{3-e^{-2x}}{3}, & 1 < x < ∞}\right.$$

(Work out the pdf, and try to write it as a mixture, with one of the components being an $Exp(λ)$ pdf )
Can someone help me here? What should I do after I differentiate the respective $F(x)$ and get $f(x)$.
Comment: Is this homework? What did you try?
Comment: A sample question for my finals. I combined the two pdfs obtained  from F'(x) and didn't know how to continue after that.
Comment: How come we do not see what you did to follow the indication to "Work out the pdf, and try to write it as a mixture, with one of the components being an Exp(λ) pdf"?
Answer: First differentiate $F$ to get the density function $f(x)$, then observe that the density can be writtes as
$$
     f(x) = \frac23 e^{-2x} + \frac23I(0<x<1).
$$
That is a mixture between an exponential distribution (with mean $1/2$) and a uniform distribution on the unit interval, and can be simulated as such.

Simulation from cdf


Extending internet signal to all outlets

Question: My house is wired with two Cat5e cables: one terminated downstairs, one upstairs. Currently, only the downstairs outlet is receiving signal, with the modem being hooked up to it. I'd like to move the modem before the two cables, so I can have ethernet upstairs too without having to run a new cable. Seems pretty straight forward, but don't want to operate on assumptions and break something.
My internet point of entry is the outdoor device pictured below. The cable coming out of the board is going to a junction box right below where it's spliced directly into the downstairs Cat cable. The upstairs cable is also in this junction box, unterminated.
Am I correct to assume that I can can simply run a cable from the pictured device straight into the modem, then have the two house wires connected to the modem, or am I missing something?
Thanks in advance
Comment: Wow, if that's supposed to be Ethernet it's very poorly done. (Bonus points for using the same cable for telephone as well – now it can never go above 100Mbps.) What kind of modem are you taking about – does it connect to the phone line for DSL or does it just directly get Ethernet in? Do you have photos of the rest?
Comment: While adding pictures, add pictures of your downstairs device. It's quite possible that this thing is already doing "modem and router" duty, (which you could check on by plugging in a couple of computers to the "LAN ports 1-6" and see if they both work at the same time when connected that way) in which case all you need is to bring up to 6 wires out to this device and plug them in. Whoever wired this was a ***Bozo***, but there's no shortage of clowns in the industry, unfortunately. If it reaches, terminating your upstairs cable and plugging it in to another LAN port should work.
Comment: That connector wiring doesn't look like the right pins for 100Base-T. That box is converting from fiber so I'd expect Ethernet on the LAN ports but I sure doesn't look right, not to mention the wire colors being wrong for CAT-5 (or better) cable.
Comment: I will upload a photo of the junction box connection tomorrow, the cable pictured here is a patch cable gone wild.
Comment: What is the actual device you have that the downstair Cat-5 cable terminating into?  Is it really a Modem (per your statement)  that is used at the terminal end of the downstairs cable.  It seem strange that a modem is connecting to a LAN connection.   Please provide a picture and model of the device at the end of the downstairs cable.
Comment: I think you guys may be correct - I _assumed_ the Netgear device I have inside is a modem without thinking twice about it, since my previous provider had the exact same device working as a modem/router combo, but hooked up to coax instead. I don't know much about telcom, I assumed the outdoor device pictured could be used by my provider to somehow differentiate between landline & internet signal, with the indoor Netgear device I believed to be a modem doing further signal processing.
Comment: But if that's not a thing and a modem would have no business receiving signal via ethernet, what I have is definitely a router and that makes a lot of sense. I'm not home atm to check the exact model, but a quick google search shows identical-looking devices being sold as modems(AC1600 and others) and routers(R6250 and others). This should be easy to test (hopefully), I will plug my laptop in as @Ecnerwal suggested.
Comment: Despite my answer (which I may well delete), I don't think you could possibly have a functioning ethernet connection from the other end of that cable - there are only 4 wires connected. RJ11 (POTS) only takes 4 wires (actually only 2, 2 provide power), but Ethernet requires all 8 be connected and in the proper order.
Comment: @FreeMan My knowledge of telcom/networking is minimal, but from what I understand pins 4,5,7,8 are not always used. It currently works, but I intend to replace this connection - is there a reason other than convenience for which the technician might have wired it this way?
Comment: Not a clue why it was done this way. Beyond my pay grade!
Comment: @FreeMan 10-BaseT and 100-BaseT only use 1,2,3, & 6 (the "green" and "orange" pairs - in this case the blue pair seems to be used for POTS (center pins on an RJ-11), and so long as the pairing/pinning is correct, the color of the pairs does not matter) - Gigabit (1000-BaseT) requires all 8. If service is 100Mbit or less, that's adequate, but still looks like a clown did it...
Comment: thanks for the info @Ecnerwal. I'm more of a software guy, I only do hardware when I have to. i.e. at home. :/
Comment: Missed the POTS comment earlier - fun fact - RJ-11 is a two-line connector. Each POTS line is just two wires, power and signal share the same line. The inner pair and outer pair are separate lines, but 99% of phones only use the inner pair (single line) - which was the basis for an early data scheme (Farallon PhoneNet) using the outer pair as it was commonly present but unused. Line 1 (inner) is red/green or white/blue, outer pair is yellow/black or white/orange in standard (USA) scheme.
Comment: The RJ-12 is the same size (RJ-11 or 12 will fit RJ12 or 11 jacks) but has 6 connectors and can carry 3 phone lines. Obviously the outmost pair won't do any good on a jack with only 4 contacts (or the outer two pairs for the very common "I'm a single line phone, I'm only paying for two contacts" jack which leaves the outer pair of a 4 conductor RJ11 idle. But two conductor phone patch cords were also pretty common...)
Answer: What you are showing in the photo is the internet provider's "modem".  In this case it appears to be a FTTH termination with 6 "Ethernet" outputs.
There also appears to be a single, poorly done, connection to one of these Ethernet ports that is going somewhere, presumably to the working downstairs location.
The photo doesn't appear to show any additional Ethernet wires that might be used to distribute Ethernet signals to other parts of the home.
While you might be able to do it yourself, what is needed is a new Ethernet wire from another of the "LAN" ports to the new location you want to have a connection to.  The simplest way would be to purchase a ready-made Ethernet cable of the suitable length and "fish" it through the walls in order to route it to the new location.
If that's beyond your capabilities, it might be wise to have a professional installer do this for you.  While they are at it, the existing wire should be checked and possibly replaced.
Comment: Most "ready made" ethernet cables are *patch cables* and the insulation type is not appropriate for in-wall use. It's also a huge pain to fish a cable with a connector on it.
Comment: @Ecnerwal I agree but it takes some degree of skill and proper tools to terminate your own cables.  The OP appears to have neither of these.
Comment: Thanks for this, I addressed my misconception in a post comment above. The upstairs cable is already near the provider modem (in a junction right box below, as mentioned), so I can just extend & terminate it, then plug it in see what happens.


Best way to access sorted array from hash after sort_by in Ruby?

Question: Note: I'm using ruby 1.9.3 and I can't bring any external dependencies. I have to do this with the core lib.
@run_histogram is a Hash of names to an Array of values (two values at this time, :failure, and :run)
foo = @run_histogram.sort_by { |scenario_name, failure_and_run_count|
  (failure_and_run_count[:failure].to_f / failure_and_run_count[:run].to_f) * -100.0
}

foo.each{|x| puts x[0]; puts x[1][:run]; puts x[1][:failure] }

The sorting is working properly, but now my issues is that I want to be able to print out the scenario_name (the index to the hash) and then print out the run and failure count.
Unfortunately at the moment I'm forced to use the indexes of the array after using sort_by, which is bad. They're "magic numbers". I would much rather continue to use the :run and :failure symbols to access the data.
Anyone have a better solution?
Answer: Why don't you just name the arguments like you did in the first place?
foo = @run_histogram.sort_by { |scenario_name, failure_and_run_count|
  (failure_and_run_count[:failure].to_f / failure_and_run_count[:run].to_f) * -100.0
}

foo.each do |scenario_name, failure_and_run_count|
  puts scenario_name
  puts failure_and_run_count[:run]
  puts failure_and_run_count[:failure]
end

You can also chain these together if you don't need to store the intermediate form:
@run_histogram.sort_by do |scenario_name, failure_and_run_count|
   # ...
end.each do |scenario_name, failure_and_run_count|
   # ...
end

Note that it's more typical to use { ... } for single-line blocks, and do ... end for multi-line. Forcing a series of things into one line impairs readability and is generally a bad thing.
Comment: Ruby will automatically expand that single argument for you if it's a Hash key/value pair, or an array. It's similar to how you can do `x, y = method_call` where `x` and `y` are assigned directly. A more formal way of declaring this might be `|(x,y)|` but that's not usually necessary. You've done it inadvertently in your `sort_by` routine, you know!
Comment: It's an automatic conversion between list and Array. An explicit version is called [splat](http://theplana.wordpress.com/2007/03/03/ruby-idioms-the-splat-operator/).
Comment: The {...} with many puts was just quick and dirty :) My print statement is more complicated.
Comment: Your solution works, but I don't really understand why :( I look at the http://ruby-doc.org/core-1.9.3/Array.html#method-i-each and it is a block that only takes one argument. How are you using a block that takes two arguments?
Comment: I had no idea :C Thanks! Does this bit of ruby functionality have a name? Is it documented somewhere?


How to refresh table data ajax form submit?

Question: I'm submitting an ajax request using Bootstrap Modal. When I submit, I want to refresh the modal body. It means that what I have saved from my form I'm showing my modal body I want show that row in table. when I use this, that table got hidden without refreshing. What's wrong?
$('#uploadform').submit(function(e) {

    e.preventDefault();

    var formData = new FormData();
    formData.append('file', $('input[type=file]')[0].files[0]);
    formData.append('task_id','{{$task->id}}');
    formData.append('title',$('#title').val());

    $.ajax({
        type:'POST',
        url:'{{url('/uploadTask')}}',
        data:formData,
        success:function(data){

            $("#images-table").html(data);

            $("#some_form")[0].reset();

        },
        error:function (data) {
            alert('error');
        },
        async:false,
        processData: false,
        contentType: false,
    });
});

Comment: Provide a [mcve]. Also never ever use `async:false` ... it is a terrible practice. Look at the deprecation notice it creates in your console
Comment: i took of  async:false, but still its hide that div when i submit a form
Comment: There isn't enough information to provide an accurate answer.  You need to verify the ajax response payload is actually being returned in the format you'd expect, then you need to bind the data to your table.  If you're not using something like angular, that means iterating over all the elements in the response and adding tr and td elements to build your table.
Answer: return that row data form controller and create html and append to to existing table. there is no concept of refreshing bootstrap table. only append new data.
$('#tableid').append('
name
');

this will append that row to at the last of your table.


Ubuntu 22.10 Modeset Error

Question: I am running Ubuntu 22.10 (i7 9700KF + RTX 2080) with Nvidia driver version 525.xx, on X11. Recently I have been noticing micro-freezes (around 1-2 seconds) on unlocking, and sometimes while tab-switching in Firefox. These are the only occurrences, and other GPU intensive tasks (like gaming etc.) does not cause any freezes or slowdown. The only thing I could find of any relevance in the logs that correlate with the freezes is this error:
[drm:nv_drm_master_set [nvidia_drm]] *ERROR* [nvidia-drm] [GPU ID 0x00000100] Failed to grab modeset ownership

Any ideas on how to resolve this? There seems to be launchpad bug report, but without much info in the comments section.
Answer: I get micro-freezes+ running 525.xx on X11 and GNOME 42.9 on 22.04. I just recovered from a macro-freeze that required a hard power cycle. I was running Blender when the last system hangup started. dmesg last entries show plenty of your ~same message

nvidia_drm ... ERROR ... "Failed to grab modeset ownership"

Answers I've seen so far advise updating grub to include this directive:
GRUB_CMDLINE_LINUX_DEFAULT="nvidia-drm.modeset=1"
The reasoning / detail are in the threads below. I'm going to reboot, fire up Blender and will report back here.
Three active threads I researched:

https://forums.opensuse.org/t/solution-to-nvidia-drm-failed-to-grab-modeset-ownership/148509
https://forums.developer.nvidia.com/t/ubuntu-21-10-failed-to-grab-modeset-ownership-with-495-44/193867/7
https://answers.launchpad.net/ubuntu/+question/706349

Ubuntu 22.10 Modeset Error


Date format from rrule in Calendar

Question: I read out a recurring Calendar event. In this event there is a rrule (CalendarContract.Events.RRULE) which describes the recurring event. In it can be an "until" date which looks like the code snippset below. An example rrule could be:
FREQ=WEEKLY;UNTIL=20121115T180000Z;BYDAY=MO,TU,WE,TH,FR
My question is about the date format. I don't know what "T" and "Z" means. Is it something with timezone?
String untilDate = "20121115T180000Z"

SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
date = format.parse(untilDate);

EDIT:
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd'T'HHmmssZ");

Answer: The T and Z are literal letters, meaning there must be an actual T and Z in those respective positions.
In the date string, the T indicates that time follows (as opposed to date) and the Z indicates Zulu, or UTC (GMT) time.
Comment: Thanks a lot, then the EDIT in my Question would be correct? I used following docs: [link](http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html)
Comment: No, in your edit, the Z looks for a time zone in the format of -0800 while your input string has an actual Z.  If your input will always have a Z, then just match it as you did before the edit and set the time zone of `format` to UTC.

Date format from rrule in Calendar


Stop/continue a C program

Question: In my C program, I want to get the PID of the process, send a SIGSTOP to that and wait until a SIGCONT arrives from another terminal. So, the procedure looks like
int pid_t = getpid();
printf("PID %d has been stopped\n", pid_t);
STOP(pid_t);
while (not_received_CONT(pid_t))
   ;
// continue the program

How can I complete that?
Comment: Note that names ending `_t` are often type names, and `pid_t` specifically is the type for a PID.  While it works to use it as a variable name, it is not a good idea to use it as such.
Answer: What you're writing doesn't make sense. When you stop the process, there is no more instructions being processed in the program and as such there is no while loop to wait for receiving the continuation.
If you check man 7 signal you can see that only one signal currently (in Linux) causes continuation of a process: SIGCONT, hence its not technically necessary to process a while loop check if you didn't get a continuation -- UNLESS you've got a situation where a number of signals are pending and you're trying to determine that.
You can rewrite your code implicitly to be:
int pid = getpid();
printf("PID %d has been stopped\n", pid);
kill(pid, SIGSTOP);
/* Process implicitly continues here, no while needed */

There are multiple vectors in Linux to manage signal handling which may not necessarily be portable.
There is the traditional signal/sigaction method of catching signals and invoking function calls on receipt of the signal. This can come with some unexpected caveats if you aren't careful.
Another way you can manage signals is the use of sigwait, you block the signal with sigprocmask and can consume signals in a safe fashion using sigwait to consume the signal at some controlled point in your process.
Finally you can do similar to sigwait with a signalfd. The main difference between it and sigwait being you can poll the FD to determine its readiness (a signal is received) then read the FD to consume the signals. This makes it a very nice way to manage signals in event driven programs.

Stop/continue a C program


SQL - Generate column from sum of columns from different table

Question: I have two tables: The first one contains numeral values, it looks like this:

The id column is the primary key; it has the attribute AUTO_INCREMENT. All columns have the datatype INT.
Now my question: Can I create a table like the following:
create table testsumtable
(
    id int primary key auto_increment,
    sumColumn int generated always as (sum(SELECT intone, inttwo, intthree FROM valuestable WHERE id=new.id))
);

Comment: I'm sorry for the typing mistake: It is intthree with two and not three 'e'.
Comment: Are you just looking to create a generated column that contains the sum of the three other columns?
Answer: Are you just looking to create a generated column that contains the sum of the three other columns?
If so, you should add it directly to the original table:
alter table mytable
add column sumColumn as (intone + inttwo + intthree)

If you don't want (or can't) alter the original table, I would suggest creating a view instead:
create view myview as
select id, intone, inttwo, intthree, intone + inttwo + intthree sumColumn from mytable

Comment: Thank you for your answer! I'll just create a sumColumn as you suggested and make the sumColumn from the sumTable as a foreign key pointing to the sumColumn from the first table.


How do I uninstall the Mention beta for Ubuntu?

Question: I recently installed the Mention beta for Ubuntu, a tool to track mentions in social media. The install is a bin file that you have to install from the command line. There's no uninstaller and apt-get remove mention does not find the package. How do I remove it?
Answer: This is a simple install in the /opt/mention directory. All you have to do is empty the directory and remove it:
sudo rm -rf /opt/mention

You can paste this code in a terminal window by using Ctrl+Shift+V.


how to Tryparse Numbers from Text file like ascii art?

Question: how can i get the numbers that are coded in a ascii art with sticks?
the numberss are in a txt file und it contains this:

I must convert this txt file in
     3 2 1 4 5
     1 4 5
I read the text file so:
<code>            using (StreamReader sr = new StreamReader("SourceFile.txt"))
        {
            String line;

            // Read and display lines from the file until the end of
            // the file is reached.
            while ((line = sr.ReadLine()) != null)
            {
                sb.AppendLine(line);
            }
        }

        string allines = sb.ToString();
</code>
Now, like the answer of @Zotta i have to  save in two different strings (the first 4 lines and the seconds, than
then will be easier
Comment: @displayName Who voted for this edit? OP does not ask for libraries.
Comment: @HimBromBeere the OP approved the edit... [see history](http://stackoverflow.com/review/suggested-edits/9306333)
Comment: @HimBromBeere: I know. But OPs original question is too bad and not salvageable. Looking at what OP finally wants done, this is question to be asked instead of what was originally asked by OP.
Answer: Your numbers are 4 lines tall each => Split input into blocks of 4 Lines each
Your numbers are separated by columns of whitespace => Search for colums containing only whitespaces and split.
After you separated all the numbers, use a lookup table.
Comment: Any idea hot to split into blocks of 4 lines?
Comment: @AlmirM. You probably shouldn't store all the lines from the file in a single `string`. Instead use an array or some other collection. Then just iterate over that collection in multiples of 4.
Comment: @sab669 some code example?
Comment: `string[] lines = File.ReadAllLines(pathToFile);`. Divide `lines.Length` by 4 to know how many rows of numbers you have. Loop that many times in a `for` loop or whatever.
Answer: I don't know why this question is down-voted so much but I think it's interesting question. I'll answer giving a general approach other than hardcoding the possible results by finding the characters and that would work with different "ASCII font".
If you're looking for a library, maybe you can look at captcha decoding on google. There is a comprehensive article here if you want to do it yourself for ASCII specifically:
http://www.boyter.org/decoding-captchas/
Also, since most libraries probably only support images, maybe you'll need to convert your ascii art text file into a bitmap by rendering it yourself.
Comment: I would guess it's downvoted because the OP didn't present any attempt to solve the problem themselves - so there was no specific programming issue to solve.


Show factorization $ x^{2n}-1=(x^2-1) \prod_{k=1}^{n-1}(x^2-2x \cos \frac{\pi k}{n} + 1) $

Question: I'm interested in how to show that
$$
x^{2n}-1=(x^2-1) \prod_{k=1}^{n-1}(x^2-2x \cos \frac{\pi k}{n} + 1)
$$
I've seen this equality too often, but have no idea how to derive it. I've tried the following:
$$
x^{2n}-1=(x^n-1)(x^n+1)
$$
We all know that $x^n-1=(x-\xi^0)(x-\xi^1) \dots (x-\xi^{n-1})$,  where $\xi=\exp(i \cdot \frac{2 \pi}{n})$.
Here $x-\xi^0$ gives us the desired $x-1$(for $x^2-1$ in RHS).
But the problem is, we can not do the same with $x^n+1$, because as I understand, there is no such general factorization of $x^n+1$. Firstly, it depends whether $n$ is even or not. Secondly, if for the sake for simplicity $n$ is odd, then we can decompose the polynomial such a way:
$$x^n+1=(x+1)(1-x+x^2-x^3 \dots -x^{n-2}+x^{n-1})$$
I don't see here anything to continue with. Any suggestions?
Comment: Consider directly $ x^{2n } - 1 = \prod ( x - \zeta_{2n} ^ k)$. Figure out what $ ( x - \zeta_{2n} ) ( x - \zeta_{2n} ^ { 2n -k } ) $ is equal to . The leftover terms correspond to $ k = 0, n$, which give us $ (x-1)(x+1) = (x^2 - 1)$.
Comment: @CalvinLin:  Did you mean $(x-\zeta_{2n}^\color{red}k)(x-\zeta_{2n}^{2n-k})$?
Comment: @J.W.Tanner Yes indeed.
Answer: Note
\begin{align}
x^{2n}-1
&=\prod_{k=0}^{2n-1} (x-e^{i\frac{\pi k}n})
=\prod_{k=0}^{n-1} (x-e^{i\frac{\pi k}n})\cdot
\underset{k=2n-j}{ \prod_{k=n}^{2n-1} (x-e^{i\frac{\pi k}n})}\\
&=(x-1)\prod_{k=1}^{n-1} (x-e^{i\frac{\pi k}n})
\cdot \prod_{j=1}^{n-1} (x-e^{-i\frac{\pi j}n}) (x-e^{-i \pi})\\
 &=(x-1)(x+1)\prod_{k=1}^{n-1} (x-e^{i\frac{\pi k}n})
(x-e^{-i\frac{\pi k}n})\\
 &=(x^2-1)\prod_{k=1}^{n-1} (x^2 - 2x\cos\frac{\pi k}n+1)
\\
\end{align}
Comment: High @Quanto. That's a good one.
Answer: Thanks to @CalvinLin for this post. The idea was to apply direct substitution
$$
x^{2n}-1=\prod_{k=0}^{2n-1} (x-\xi^k)
$$
where $\xi$ is a base root of the equation $x^{2n}-1=0$, e.g. $\xi=\exp({i \cdot \frac{\pi}{n}})$.
It gives us the following:
$$
\prod_{k=0}^{2n-1} (x-\xi^k)=(x-\xi^0)(x-\xi^n) \prod_{k=1}^{n-1} (x-\xi^k)(x-\xi^{2n-k})
$$
$(x-\xi^0)(x-\xi^n)=(x-1)(x+1)=(x^2-1)$ since $\xi^n=\exp(i \cdot \pi)=-1$
Now let's take a deeper look at multiplier inside the product notation.
$$
(x-\xi^k)(x-\xi^{2n-k})=x^2-(\xi^k+\xi^{2n-k})x+\xi^k \cdot \xi^{2n-k}
$$
Obviously, $\xi^k \cdot \xi^{2n-k}=\xi^{2n}=1$. Consider the coefficient at $x$:
$$
\xi^k+\xi^{2n-k} \\
=\cos(k\cdot \frac{\pi}{n})+i\sin(k\cdot\frac{\pi}{n})+\cos((2n-k)\cdot \frac{\pi}{n})+i\sin((2n-k)\cdot \frac{\pi}{n})\\
=\cos(k\cdot \frac{\pi}{n})+i\sin(k\cdot\frac{\pi}{n})+\cos(2\pi - k\cdot \frac{\pi}{n})+i\sin(2\pi - k\cdot \frac{\pi}{n}) \\
=2\cos(k\cdot \frac{\pi}{n})
$$
The last equality comes from the periodicity and evenness/oddness of $\cos$/$\sin$.
So, for now we have:
$$
=(x^2-1)\prod_{k=1}^{n-1}(x^2-2x\cos(k \cdot \frac{\pi}{n})+1)
$$
And we are done!
Comment: Note that the "it gives us the following" is not correct. You currently do not have $ ( x - \zeta^n)$, and have $ ( x - \zeta^0) = (x - \zeta^{2n}$ repeated. That is why I referred to these terms as "leftover". Apart from that, this looks good.
Comment: @CalvinLin corrected, thanks again!
Answer: Hint
You can use the same idea in the factorization of $x^n-1$.
Think of
$$x^n=-1=e^{i(2k+1)\pi}$$


Migrate to iOS VoIP push notifications

Question: We have a VoIP app where we are currently using standard push notifications. We would like to update to using PushKit and VoIP push notifications. I'm a bit unsure how to migrate from our current standard APNS setup to the new. Questions:
1) Will our current APNS production certificate be able to send push messages to new VoIP clients?
2) Will our new VoIP push certificate be able to send push messages to existing, standard APNS apps (tokens)?
Comment: From https://developer.apple.com/library/prerelease/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/APNSOverview.html#//apple_ref/doc/uid/TP40008194-CH8-SW10 it seems that Token-Based Provider-to-APNs Trust can be used for both standard APNS + VoIP push
Comment: Use your APNS certificate for simple push notifications and Create new Voip Certificates for Voip push
Answer: Please do refer pushkit demo https://github.com/hasyapanchasara/PushKit_SilentPushNotification
Objective c demo is also there https://github.com/hasyapanchasara/PushKit_SilentPushNotification/tree/master/Objective%20C%20Demo/PushKitDemoObjectiveC
Below is swift code to register for push kit and receive pushkit payload.
<code>import UIKit
import PushKit

class AppDelegate: UIResponder, UIApplicationDelegate,PKPushRegistryDelegate{

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    let types: UIRemoteNotificationType = [.Alert, .Badge, .Sound]
    application.registerForRemoteNotificationTypes(types)

    self. PushKitRegistration()

    return true
}

//MARK: - PushKitRegistration

func PushKitRegistration()
{

    let mainQueue = dispatch_get_main_queue()
    // Create a push registry object
    if #available(iOS 8.0, *) {

        let voipRegistry: PKPushRegistry = PKPushRegistry(queue: mainQueue)

        // Set the registry's delegate to self

        voipRegistry.delegate = self

        // Set the push type to VoIP

        voipRegistry.desiredPushTypes = [PKPushTypeVoIP]

    } else {
        // Fallback on earlier versions
    }

}

@available(iOS 8.0, *)
func pushRegistry(registry: PKPushRegistry!, didUpdatePushCredentials credentials: PKPushCredentials!, forType type: String!) {
    // Register VoIP push token (a property of PKPushCredentials) with server

    let hexString : String = UnsafeBufferPointer<UInt8>(start: UnsafePointer(credentials.token.bytes),
        count: credentials.token.length).map { String(format: "%02x", $0) }.joinWithSeparator("")

    print(hexString)

}

@available(iOS 8.0, *)
func pushRegistry(registry: PKPushRegistry!, didReceiveIncomingPushWithPayload payload: PKPushPayload!, forType type: String!) {
    // Process the received push
    // From here you have to schedule your local notification

}

}
</code>
When your app is based on VOIP, then once you receive pushkit payload then you can schedule local notification. As per interactive local notification you can receive, disconnect etc feature can process ( Same like Whatsapp, Skype etc ).
1) Will our current APNS production certificate be able to send push messages to new VoIP clients?

No, you have to create pem file and configure at back end as well.

2) Will our new VoIP push certificate be able to send push messages to existing, standard APNS apps (tokens)?

No, Pushkit tokens will be different from APNS tokens.
List item

Refer more for Debug, Certificate, Local notification
https://github.com/hasyapanchasara/PushKit_SilentPushNotification

Migrate to iOS VoIP push notifications


Accessing CSS custom variable with Javascript

Question: I have as the following style in a css file
#galleryImages{
    position:absolute;
    top:24px;
    left:41px;
    width:900px;
    moving:false;
}

When I try to access it through Javascript, it returns undefined
The external css is correct, it returns other style variables properly as well as the getElementById
alert("External: " + document.styleSheets[0].cssRules[2].style.moving +
    "\nInternal: " + document.getElementById("galleryImages").style.moving);

It gives an alert with:
External: Undefined
Internal: Undefined

Is there a way to access a custom CSS variable through javascript?
Thank you in advance
Comment: As far as I know, non-standard CSS definitions are completely ignored by the browser, as such it won't appear in any attempt to reference it. I might be wrong, but I'm fairly certain I'm not.
Comment: Is there any reason you are using a custom css variable? If your site is HTML5, then I'd go with a data attribute, which were designed to solve this situation. http://html5doctor.com/html5-custom-data-attributes/, even if it's not html5 I'd still argue a data attribute is a better solution.
Comment: see this [question](http://stackoverflow.com/questions/2926326/can-i-access-the-value-of-invalid-custom-css-properties-from-javascript) and this mozilla [bug](https://bugzilla.mozilla.org/show_bug.cgi?id=116694).
Comment: What does that `moving` CSS property do?
Answer: Most (all?) browsers won't load unknown CSS into the DOM, and JavaScript cannot directly access CSS styles directly, only the ones that are loaded into the DOM.
The only way I can think of would be to implement your own CSS parsing JavaScript, but for the mostpart, that would probably be excessive for what you want to do, and a pure JavaScript solution or a class value would better.
e.g. In HTML

Using that example, you could use your JavaScript to get the classname of the element, and if it has the "moveable" class, you know it can move.
EDIT:
In @Anurag's posted link to the Mozilla bug, it is mentioned that unknown CSS properties are to be ignored as part of the CSS 2.1 specification.


Adding if statement to an existing while loop

Question: I have to do add an if statement to my while loop.
When I write ./scriptname 1, it executes my while loop.
When I instead write ./scriptname hello, it still executes my while loop.
What I want it to do is echo "no" if I add letters after ./scriptname but execute the while loop if I add numbers after ./scriptname.
Does anyone know what I have done wrong in the script attached?
Comment: Please don't post images of text - copy and paste the script into your question using the [edit] button and format it as code using the markdown tools provided
Comment: it should be ```x=$1``` and its  better to test other way around, for non-digit ```[[ ! $x =~ [^0-9] ]]```
Answer: Its a good practice to keep your if-then-statement as short as possible, this way you dont need the else statement.
#!/bin/bash

x=$1
y=$2

if [[ $x =~ (^$|[^0-9]) ]]; then
    echo "no"
    exit 0
fi
while (( $x <= 3 )); do
    echo "$x $y"
    ((x++))
    sleep 5
done

Or with a for-loop:
for ((z=3; $x<=$z; x++)); do
    echo "$x $y"
    sleep 5
done


Preview android xml layout outside of eclipse/ADT

Question: Is there any way to render an xml layout from an android project outside of eclipse/ADT?
To be extremely clear, I'm not asking to view some random xml file marked up like an android layout xml file. A layout could reference custom views and anything that would provide a preview needs to be able to load such a resource. So really, anything out there?
Comment: follow with Barcardi bat answer.
Comment: I followed, but the answer deals with an answer to the question as being a side effect of what i might consider an accepted answer. I'm looking for just a renderer.
Answer: You view this in DroidDraw Tool. Download the tool here. Hope this may help you.


Searching through a tree and adding up the distances of towns you pass by

Question: These 2 functions together should return the total distance you must travel to go directly to a node. At the moment, it doesn't work with more long and complex things. Simple things however work just fine.
<code>    int Stree::distance(string origin_city, string destination_city)
{
    int total_distance = 0;
    Node *new_root = m_root;
    new_root = find_node(m_root, origin_city);
    total_distance = get_distance(new_root, total_distance, destination_city);
    return total_distance;
}

int Stree::get_distance(Node* cur, int distance, string destination)
{
    Node *tmp = cur;
    if(cur == NULL)
        return 0;
    if(cur->m_city == destination || tmp->m_city == destination)
    {
        //cout << distance + cur->m_parent_distance << endl;
        return distance += cur->m_parent_distance;
    }
    if(tmp->m_left != NULL)
    {
        //cout << "checking left" << endl;
        tmp = cur->m_left;
        return get_distance(cur->m_left, distance, destination) ;
    }
    else
    {
        //cout << "checking right" << endl;
        return get_distance(cur->m_right, distance, destination);
    }
}
</code>
Comment: Can you provide some input data for cases that work and for cases that do not, to help us understand what you mean by "long and complex" as opposed to "simple"?
Comment: the input is in another function, that places them all into the tree, this one then looks them up.
Comment: this is what i meant to say at the top of the code::

I am currently working on a function that has 1 helper function, the main function takes in 2 strings and searches for the first one (which becomes a reference as if it was m_root) and a second one to be searched in the tree. once they are searched, my helper function is supposed to search for the 2nd city and count the distance it had to travel as if a truck was going towards that city.
Comment: People on SO will need more information than you've provided if they are to have a chance of helping you. What do you mean by "long and complex" as opposed to "simple" in this context?
Comment: it just means that if you input just 1 or 3 cities, it works fine, but once it has to start checking for more complex trees, it doesnt work.
Comment: In getdistance function, you are always going left when left != NULL. So right tree will not be traversed.
Answer: Just a guess: I think the only way your code could loop should be when the tree contains loops - i.e. isn't a tree at all.
Try this debugging helper:
<code>#include <vector>
#include <algorithm>
#include <stdexcept>
using namespace std;
...
static vector<Node*> visited;

int Stree::get_distance(Node* cur, int distance, string destination)
{
    if (find(visited.begin(), visited.end(), cur) != visited.end())
        throw runtime_error("looping " + cur->m_city);

    Node *tmp = cur;
    if(cur == NULL)
        return 0;

    int ret;
    visited.push_back(cur);
    if(cur->m_city == destination || tmp->m_city == destination)
    {
        //cout << distance + cur->m_parent_distance << endl;
        ret = distance += cur->m_parent_distance;
    }
    if(tmp->m_left != NULL)
    {
        //cout << "checking left" << endl;
        tmp = cur->m_left;
        ret = get_distance(cur->m_left, distance, destination) ;
    }
    else
    {
        //cout << "checking right" << endl;
        ret = get_distance(cur->m_right, distance, destination);
    }

    visited.pop_back();
    return ret;
}
</code>


How can I temporarily fix a leaky faucet?

Question: I have a house from the late '20's and my hot water leaks in my tub.  I've had it fixed a few times by plumbers and the last one said that to permanently fix it, I'm going to need to replace the whole shebang.
While I'm saving up for that, is there a less permanent option to address the issue?  A rubber stopper?
Comment: If you were to try to cork the faucet, then it needs to be able to withstand the full pressure of your water supply since the leak will eventually equalize the pressure before it stops leaking. And this assumes you don't have a shower head and that other fittings after the valve are designed for full water pressure. In short, there's no easy "rubber stopper" solution that I know of.
Comment: can you get to the pipe feeding the faucet and turn off a valve there? (or have a valve installed there to shut it off when you're not using it)
Comment: I pondered that.  Not sure how much that would cost.  Probably worth the walk to the basement for bathtime to save on hot water costs.
Comment: A picture would help. If you have an old-style faucet that uses a washer (ie, the faucet hasn't been replaced in the last 90 years), then the you might have to grind the seat as *veljkoz* mentioned. The fact that plumbers have "fixed" the problem with relatively low cost indicates that you do have washers, but I'm surprised that they didn't clean up the seat as a matter of course. So it's possible that there's something more to the problem.
Comment: One plumber did mention cleaning the seat, but didn't make it sound like he thought it would help.
Answer: Other than turning the water off at a location before the faucet, there is no real temporary fix - you either fix it, or you don't.
The problem with really old faucets is finding replacement parts.  I had one from the '70s with a similar issue and I couldn't even get replacement parts. I opted to just replace it.
That being said, replacing it should not be a huge job.  I was able to replace an old 3 handle faucet with a single handle faucet in a couple hours (my first real plmbing project). They make special remodel wall plates specifically for this that allow you to cut a large enough hole in the wall to replace the faucet, and then cover it up with the plate:

If you are able to access the wall behind the shower then it is even easier since you can easily cut and repair a large drywall hole.
If you are handy you can definitely do it yourself, or call in a plumber to do it for you.  I imagine a plumber would make quick work of this.
Comment: Thanks.  Wall access is very hard to get - plaster not drywall through the side and builtin drawers behind.
Comment: With the remodel plate, you can cut the hole in the shower side and cover it up afterwards.
Answer: (sorry about not knowing all the names of stuff, the english is not my native tongue)
Depending on the type of the faucet, there's an option for a really cheap and more permanent fix. We had a leaky faucet and each time the 'rubber-part-that-goes-inside-the-faucet-handle' (sorry, don't know the real translation :)) gets replaced, it works for a little while, but after a month or so you just can't turn the faucet hard enough to stop it from leaking.
I'm not sure if that's the problem you're having, but here's what was the problem in our case... the place where the faucet knob/handle goes in, if you unscrew that just like you're preparing to replace the rubber (provided you closed off the water in bathroom), you will see where the rubber on the inside of the handle touches the metal circle. The turning of the knob is what moves the rubber to and from the metal circle, giving the way of water to pass through. The problem here is that if the water is dripping for some time, the metal gets "eaten away" by the water, ie there's a canal going through it's surface, so no matter how hard you turn the knob the water passes through the canal. When you replace it the rubber is more flexible and it can fill in the gap, but after a while it hardens and that's when you need to replace it again.
The only solution here is to take off some of the metal. There's no way you can do it without a proper tool though - there's a special "screw" with metal teeth that you tie instead of the knob, and by turning it like a knob the metal teeth eat away at the metal evenly. That way the metal gets even, and now when you place your original knob it will hold the water in.
Hope it helps.
Comment: +1 - it's the faucet seat, and there is a tool to do it but I couldn't find a link on the Home Depot site
Comment: This is precisely the issue I have.  Should I fear that with the age of my hardware that I would grind through too much metal and leave myself with an immediate need for replacement?
Comment: Age here is an issue only if this was already done before for several times. But usually, "in good old days" they've built these things to last and to be able to be fixed like this, so my guess is that you'll be OK. When you take off some of the metal the problem is not the reach of the knob, but the metal itself - take a look and see how much is left until the base of it. Usually you don't need more than 1-2 full turns for the teeth to make it even. You'll have to make that assessment for yourself, or maybe call some plumber...


unable to deploy portia project using scrapyd-deploy due to 'No module found ..'

Question: I am evaluating portia and run in to an issue deploying to scrapyd.
When I try to deploy my portia project using
scrapyd-deploy local -p new_project

from my portia project directory I get the following error message
Packing version 1433441798
Deploying to project "new_project" in http://192.168.59.103:6800/addversion.json
Server response (200):
{"status": "error", "message": "ImportError: Error loading object
'slybot.spidermanager.ZipfileSlybotSpiderManager': No module named slybot.spidermanager"}

I have one docker container running portia and another running scrapyd.
My project runs via portiacrawl successfully.
I also tried creating a simple scrapy project using the startproject and genspider commands which deployed successfully on scrapyd
I'm not sure where to find the egg file that is generated.
Scrapyd log
2015-06-04 18:28:51+0000 [HTTPChannel,21,172.17.42.1] Unhandled Error
        Traceback (most recent call last):
          File "/usr/lib/python2.7/dist-packages/twisted/web/http.py", line 1618, in allContentReceived
            req.requestReceived(command, path, version)
          File "/usr/lib/python2.7/dist-packages/twisted/web/http.py", line 773, in requestReceived
            self.process()
          File "/usr/lib/python2.7/dist-packages/twisted/web/server.py", line 132, in process
            self.render(resrc)
          File "/usr/lib/python2.7/dist-packages/twisted/web/server.py", line 167, in render
            body = resrc.render(self)
        --- <exception caught here> ---
          File "/usr/lib/pymodules/python2.7/scrapyd/webservice.py", line 18, in render
            return JsonResource.render(self, txrequest)
          File "/usr/lib/pymodules/python2.7/scrapy/utils/txweb.py", line 10, in render
            r = resource.Resource.render(self, txrequest)
          File "/usr/lib/python2.7/dist-packages/twisted/web/resource.py", line 216, in render
            return m(request)
          File "/usr/lib/pymodules/python2.7/scrapyd/webservice.py", line 66, in render_POST
            spiders = get_spider_list(project)
          File "/usr/lib/pymodules/python2.7/scrapyd/utils.py", line 65, in get_spider_list
            raise RuntimeError(msg.splitlines()[-1])
        exceptions.RuntimeError: ImportError: Error loading object 'slybot.spidermanager.ZipfileSlybotSpiderManager': No module named slybot.spidermanager

2015-06-04 18:28:51+0000 [HTTPChannel,21,172.17.42.1] 172.17.42.1 - - [04/Jun/2015:18:28:51 +0000] "POST /addversion.json HTTP/1.1" 200 156 "-" "Python-urllib/2.7"

Any ideas what I am missing ?
Answer: I was able to basically resolve this by using the latest from github instead of 1.0.1 version and a scrapy version of 0.25.1
More info here:
https://github.com/scrapinghub/portia/issues/209


Ignoring `CUDA_VISIBLE_DEVICES` environment variable

Question: Since CUDA 3.1 it is possible to limit the list of GPUs visible to applicaion by setting CUDA_VISIBLE_DEVICES environment variable.
This affects both Runtime API and Driver API (to be sure I've checked it myself). It seems that device filtering is enforced somewher on driver level, and there is no way to ignore it.
However, I've encountered one closed source application which seems to somehow ignore this variable and always use device 0, even if we set CUDA_VISIBLE_DEVICES to empty string, which means that appliction should not see any CUDA-capable device.
The application in question uses same CUDA libraries as dummy application for counting available devices:
$ ldd a.out  # dummy
    linux-vdso.so.1 =>  (0x00007fff7ec60000)
    libcuda.so.1 => /usr/lib64/libcuda.so.1 (0x00007f606783a000)
    libcudart.so.4 => /usr/local/cuda41/cuda/lib64/libcudart.so.4 (0x00007f60675e3000)
    libstdc++.so.6 => /usr/lib64/libstdc++.so.6 (0x00007f60672dd000)
    libm.so.6 => /lib64/libm.so.6 (0x00007f606704e000)
    libgcc_s.so.1 => /lib64/libgcc_s.so.1 (0x00007f6066e37000)
    libc.so.6 => /lib64/libc.so.6 (0x00007f6066aa7000)
    libpthread.so.0 => /lib64/libpthread.so.0 (0x00007f606688b000)
    libz.so.1 => /lib64/libz.so.1 (0x00007f6066674000)
    libdl.so.2 => /lib64/libdl.so.2 (0x00007f6066470000)
    librt.so.1 => /lib64/librt.so.1 (0x00007f6066268000)
    /lib64/ld-linux-x86-64.so.2 (0x00007f6068232000)

$ ldd ../../bin/one.closed.source.application # application in question
    linux-vdso.so.1 =>  (0x00007fffcf99c000)
    libcufft.so.4 => /usr/local/cuda41/cuda/lib64/libcufft.so.4 (0x00007f06ce53a000)
    libcuda.so.1 => /usr/lib64/libcuda.so.1 (0x00007f06cdb44000)
    libcudart.so.4 => /usr/local/cuda41/cuda/lib64/libcudart.so.4 (0x00007f06cd8ed000)
    libz.so.1 => /lib64/libz.so.1 (0x00007f06cd6cb000)
    libdl.so.2 => /lib64/libdl.so.2 (0x00007f06cd4c7000)
    librt.so.1 => /lib64/librt.so.1 (0x00007f06cd2bf000)
    libstdc++.so.6 => /usr/lib64/libstdc++.so.6 (0x00007f06ccfb8000)
    libm.so.6 => /lib64/libm.so.6 (0x00007f06ccd34000)
    libgcc_s.so.1 => /lib64/libgcc_s.so.1 (0x00007f06ccb1e000)
    libc.so.6 => /lib64/libc.so.6 (0x00007f06cc78d000)
    libpthread.so.0 => /lib64/libpthread.so.0 (0x00007f06cc571000)
    /lib64/ld-linux-x86-64.so.2 (0x00007f06d0110000)

I'm curious how is it possible to do this trick.
Answer: Rubber duck debugging really works.
Turns out it is enough to use unsetenv before calling cuInit or cudaSetDevice, and the  initial value of environmetal variable will be ignored.
#include <stdio.h>
#include <stdlib.h>
#include <cuda.h>

int main(int argc, char **argv, char **env) {
  int x;
  unsetenv("CUDA_VISIBLE_DEVICES");
  cuInit(0);
  // Now we see all the devices on machine
  cuDeviceGetCount(&x);
  printf("%d\n",x);
  return 0;
}


Scanning big binary with Erlang

Question: I like to scan larger(>500M) binary files for structs/patterns. I am new to the language an hope that someone can give me start. Actually the files are a database containing Segments. A Segment starts with a fixed sized header followed by a fixed sized optional part followed by the payload/data part of variable lenght. For a first test i just like to log the number of segments in the file. I googled already for some tutorial but found nothing which helped. I need a hint or a tutorial which is not too far from my use case to get started.
Greets
Stefan
Comment: It would also help with an example of the binary you are trying to parse and what the end result should look like.
Answer: you need to learn about Bit Syntax and Binary Comprehensions. More useful links to follow: http://www.erlang.org/documentation/doc-5.6/doc/programming_examples/bit_syntax.html, and http://goto0.cubelogic.org/a/90.You will also need to learn how to process files, reading from files (line-by-line, chunk-by-chunk, at given positions in a file, e.t.c.), writing to files in several ways. The file processing functions are explained here You can also choose to look at the source code of large file processing libraries within the erlang packages e.g. Disk Log, Dets and mnesia. These libraries heavily read and write into files and their source code is open for you to see. I hope that helps
Answer: Here is a synthesized sample problem: I have a binary file (test.txt) that I want to parse. I want to find all the binary patterns of <<$a, $b, $c>> in the file.
The content of "test.txt":
I arbitrarily decide to choose the string "abc" as my target string for my test. I want to find all the abc's in my testing file.

A sample program (lab.erl):
-module(lab).
-compile(export_all).

find(BinPattern, InputFile) ->
    BinPatternLength = length(binary_to_list(BinPattern)),
    {ok, S} = file:open(InputFile, [read, binary, raw]),
    loop(S, BinPattern, 0, BinPatternLength, 0),
    file:close(S),
    io:format("Done!~n", []).

loop(S, BinPattern, StartPos, Length, Acc) ->
    case file:pread(S, StartPos, Length) of
    {ok, Bin} ->
        case Bin of
        BinPattern ->
            io:format("Found one at position: ~p.~n", [StartPos]),
            loop(S, BinPattern, StartPos + 1, Length, Acc + 1);
        _ ->
            loop(S, BinPattern, StartPos + 1, Length, Acc)
        end;
    eof ->
        io:format("I've proudly found ~p matches:)~n", [Acc])
    end.

Run it:
1> c(lab).
{ok,lab}
2> lab:find(<<"abc">>, "./test.txt").
Found one at position: 43.
Found one at position: 103.
I've proudly found 2 matches:)
Done!
ok

Note that the code above is not very efficient (the scanning process shifts one byte at a time) and it is sequential (not utilizing all the "cores" on your computer). It is meant only to get you started.
Answer: When your data fits into memory, best thing what you can to do is read data in whole using file:read_file/1. If you can't use file in raw mode. Then you can parse data using bit_syntax. If you write it in right manner you can achieve parsing speed in tens of MB/s when parsing module is compile using HiPE. Exact techniques of parsing depends on exact segment data format and how robust/accurate result you are looking for. For parallel parsing you can inspire by Tim Bray's Wide Finder project.

Scanning big binary with Erlang


BeautifulSoup: AttributeError: 'NoneType' object has no attribute 'contents'

Question: EDIT: I added the full set of code since my attempt at simplifying it didn't work. I was able to comment out the problematic line and it works, so I assumed I was ok until then
I'm working on a web scraper and I'm stuck on this AttributeError on this line historical_seasons = soup_loop.find('select', {'name': 'comp_id'}).contents and can't figure out what is wrong
# https://statbunker.com/robots.txt

import requests
from bs4 import BeautifulSoup

# navigate to https://rugby.statbunker.com/
url = 'https://rugby.statbunker.com/'
response = requests.get(url)
html = response.content
soup = BeautifulSoup(html, 'html.parser')

# create lists of all leagues
league_links = []
leagues = soup.find_all('a', {'class': 'pointer'})

for link in leagues:
    if link.has_attr('href'):
        league_links.append(link['href'])
print(league_links)

# create list of all seasons for that league
season_links = []
for link in league_links:
    response_loop = requests.get(link)
    html_loop = response_loop.content
    soup_loop = BeautifulSoup(html_loop, 'html.parser')

    league_results = soup_loop.find_all('img', alt='Latest Results')

    for results in league_results:
        parent = results.parent
        if parent.has_attr('href'):
            season_links.append(parent['href'])

    # historical seasons
    historical_seasons = soup_loop.find('select', {'name': 'comp_id'}).contents

    for season in historical_seasons[3:-1]:
        season_id = season['value']
        base_url = 'https://rugby.statbunker.com/competitions/LastMatches?comp_id='
        new_url = base_url + season_id
        season_links.append(new_url)
print(len(season_links))

What's particularly confusing for me is that when I isolate it somewhat it seems to work
import requests
from bs4 import BeautifulSoup

# navigate to https://rugby.statbunker.com/

url = 'https://rugby.statbunker.com/competitions/LastMatches?comp_id=637'
response = requests.get(url)
html_loop = response.content
soup_loop = BeautifulSoup(html_loop, 'html.parser')

test_list = []
historical_seasons = soup_loop.find('select', {'name': 'comp_id'}).contents

for season in historical_seasons[3:-1]:
    season_id = season['value']
    base_url = 'https://rugby.statbunker.com/competitions/LastMatches?comp_id='
    new_url = base_url + season_id
    test_list.append(new_url)
print(test_list)

Comment: Your first entry in `league_links` is missing an opening `'` character, is that the problem? That should just give you a SyntaxError, though...
Comment: If I fix that error, the program builds fine for me with Python 3.9, and prints `63` at the end.
Comment: I am not able to reproduce the problem. First snippet, after fixing the typo, works fine for me. it prints 63
Comment: @MattDMo thanks for taking a look, I just updated it to be my full code, thought I could just isolate the area with the error
Comment: @buran thanks for taking a look, I just updated it to be my full code, thought I could just isolate the area with the error
Comment: If you print `link` in each iteration you will see that the 4th link is `https://rugby.statbunker.com/competitions/LeagueTable?comp_id=` and as a result you get the error.
Answer: The full code finally recreated the error for me. Looking through the output of print(league_links), the fourth one is 'https://rugby.statbunker.com/competitions/LeagueTable?comp_id=', with no comp_id. This loads a page with no table, therefore there's nothing to be found with soup_loop.find('select', {'name': 'comp_id'}), so it returns None. None doesn't have an attribute content, hence your error.
I'm not sure why the comp_id= link is being returned, so you'll have to debug that part yourself.


Price Tables: what's the best position for "Best value" option on even grids?

Question: Is there a documented 'best position' for highlighting the 'best value' or 'recommended' option in a table with four columns? In tables with 3 or 5 columns, the best placement is typically the center. But what about when there are 4 columns? Should the 'best value' be in the second or third column?
Please provide any supporting documents for this placement, as we have a tight deadline and no time for pre-testing (although we plan to test afterward).
Note: I know the Serial Position Effect might play a role here, making the 3rd column the right place, but this is only a hunch, so I'd like to know if there's some kind of research o this since I couldn't find anything. Papers, articles or live examples are OK
Comment: If your second column is your best value, what would make your user consider the third column? Is it something like an "enterprise" level amount that they'll buy regardless of value?
Comment: hi @Izquierdo I mean where to place that "best value". Either way, and for reference, second and third columns are very different, so we can't make a direct comparison,  but we still want one of the choices to be selected over the other as much as possible.
Comment: Is the best value associated with the highest price in each column? Or are you considering adding "Best Value" to a mid-range price, based on other aspects?
Comment: it's a mid range
Comment: I am curious to know whether you reached a conclusion as to what the best position is for the best value option.
Answer: I looked at a couple of pages where a range of different price table designs are displayed, and I think that you have to challenge some of the assumptions that are made relating to whether there is a definitive 'best' position for the design, or whether it is about making the design highlight a specific option you want to draw the user's attention to.
For example, this page lists 50 different pricing table examples, or the one here with 11 pricing table designs, I noticed that:

There are indeed examples where the 2nd or 3rd option is highlighted, but there are also examples where they are not
For pages with odd numbers of options, the middle options isn't always the one highlighted
Some designs deliberately don't highlight a particular option, either to make the user go through them all, or to make it difficult to make comparisons

There is no question that in some of the designs, the serial position effect is at play, but I think it is easier to tailor the visual design to the information that you want to display rather than designing for a particular effect that the user is likely to be drawn to.
For example, I think if the options in a pricing table follow a linear progression that scales to some underlying business pricing model, then the user is looking for any cues that will suggest the level where the best value for money presents itself, regardless of where this falls in a row of even or odd numbered options. By default they might start looking from a specific position or remember certain options better, and this is where you can use visual design to highlight the option you want them to look at.
On the other hand, if the options in a pricing table is discreetly bundled into packages that are not easily compared, then this is where you could position things in places that they are likely to look at first and remember better.


stl::sort() is changing the attributes of the objects it is sorting

Question: I've been coding a solution for the Graph Coloring Problem using Brown's algorithm. The algorithm is working just fine but, to add a little efficiency I'm trying to sort the nodes by their degree. To do so I'm using stl::sort(). Nonetheless, after sort has ordered the elements, the adyacency list of each element has been modified. I've got 4 files:
nodo.h:
class Nodo{
private:
    int id;
    int color;
    vector<Nodo*> adyacentes;
public:
    int grado;
    vector<Nodo*> getAdyacentes();
    int getId();
    int getColor();
}

nodo.cpp -> Includes the basic implementation of the getters.
grafo.h:
class Grafo{
private:
    Nodo *nodos;
    int tam;
public:
    void colorearBrown();
    void imprimir();
}

grafo.cpp:
void Grafo::imprimir(){
    cout << setw(6) << "Numero" << setw(5) << " Color"  << " Nodos adyacentes" << endl;
    for(int i = 0; i < tam; ++ i){
        cout << setw(6) << nodos[i].getId() << setw(5) << nodos[i].getColor() << "  ";
        vector<Nodo*> ady = nodos[i].getAdyacentes();
        for(vector<Nodo*>::iterator it = ady.begin(); it != ady.end(); ++ it){
            if (it != ady.begin()){
                cout << ",";
            }
            cout << (*it)->getId();
        }
        cout << endl;
    }
}

bool operator<(const Nodo& a, const Nodo& b){
    return (a.grado >= b.grado);
}

void Grafo::colorearBrown(){
    imprimir();
    sort(&nodos[0], &nodos[tam]);
    cout << endl << endl;
    imprimir();
}

And that's it. Assuming I've a correctly loaded graph in a 'Grafo' object, I run the method colorearBrown() and get the following output (part):
.
.
.
    16  -1  1,22,36,43,47,48
    17  -1  10,13,20,22,44,47
    18  -1  27,32,48
    19  -1  4,32,36
    20  -1  6,8,10,12,17,33,36,38,43,45,48
    21  -1  4,6,45
    22  -1  6,16,17,26,30,31
    23  -1  3,8,10,14,24,26,32,36
.
.
.

Numero Color Nodos adyacentes
    20  -1  4,42,22,32,10,3,34,50,18,19,25
     7  -1  20,32,6,13,3,50,2,18,31,19
    36  -1  7,14,16,44,12,38,30,1,50,37
    14  -1  22,30,49,24,2,11,40,5
.
.
.

See how the list of adyacent nodes changes on node 20(here), but this is repeated for all nodes.
The program perfectly compiles and, if not sorted, the nodes stay the same way throughout the hole execution.
Any ideas on why the sorting algorithm is messing with my structure would be helpful.
Comment: instead of using html tags, you can simply add 4 spaces in front of your code to have nicer formatting.
Comment: You can also highlight the code lines and use the `{}` button to format the code.
Comment: `vector getAdyacentes` ? Choose one language and stick with it; this isn't exactly readable.
Answer: std::sort copies (or moves, in C++11) the objects. However you have pointers in your objects, which point at the place where the object is. After the sort, there's another object at that place.
Think of it as people sitting on chairs. You give each person a list of chairs where the "adjacent" people sit. And then you ask the people to change places. People changing places does not change what is written on the paper.
The people are the node objects, the places are the positions in he array, and the pieces of paper with the lists are your vectors of pointers to adjacent nodes.
A simple solution to that problem would be using a std::list and sorting with its sort member function. That member function doesn't move objects around, but just relinks the internal nodes, therefore your pointers will continue to point to the correct object. One disadvantage of that solution (which may or may not matter in your case) is that the list doesn't offer random access.


Laravel dynamic config variable get

Question: This is my config/filesystems.php file.
'default' => env('FILESYSTEM_DRIVER', 's3'),

'disks' => [
       's3' => [
            'driver' => 's3',
            'key' => env('AWS_ACCESS_KEY_ID'),
            'secret' => env('AWS_SECRET_ACCESS_KEY'),
        ],
       'b2' => [
            'driver' => 's3',
            'key' => env('B2_KEY_ID'),
            'secret' => env('B2_APP_KEY'),
        ],
]

How can I get default filesystem's key value?
I think this is possible.
config("filesystems.disks." . config("filesystems.default") . ".key");
I believe there is any better way.
Can anyone help me?
Comment: That's how I would do it. I don't know of a better or built-in way.
Comment: You can create a common helper function and set values according to your requirement.
Answer: If you want to change config value you should call config helper function and pass the value you want to set as the second argument. You can check it in Laravel documentation

Laravel dynamic config variable get


Is there any alternative for gnome-appearance-properties?

Question: gnome-appearance-properties is no more available in Gnome3 and newer.
I want to change Background and Text colors of Windows, Input Boxes, Selected Items, etc. and customize Theme.
Is there any application available to do that?
Comment: Please see [this question](http://askubuntu.com/q/63126/61218). If you think, that question is sufficient you can flag it to close or delete the question (on certain situation). If you wanted something other than that question, please be specific about your question i.e What part of the themes you want to customize. thanks
Answer: You could try gtk-chtheme for basic selection of themes. I've also installed metacity-themes, shiki-colors and customised window buttons through gconf-editor under .../apps/metacity/.


Does Soul Harvest "Siphon" steal life?

Question: Is the Life the Witch Doctor gains from the "Siphon" rune of Soul Harvest taken from the enemy? Does the enemy's life decrease? Or does the Witch Doctor just gain the Life, without the monster losing it?
Answer: No, it does not do damage.  Note the text simply says:

Gain 2171 Life for every enemy harvested.

No where does it actually do damage.  Just to be sure, I took my level 60 WD to a normal game and performed it and confirmed that no monsters died/took damage.

Does Soul Harvest "Siphon" steal life?


Problem with Ladylux kitchen faucet sprayer

Question: I have a 14-year old Grohe Ladylux kitchen faucet.  Recently, the spray knob stopped working properly.  Normally when you press and release the knob, the faucet goes to spray mode until you press the release knob.  Now it only stays in spray mode if you continuously hold the spray knob down.  Any ideas on how to fix this?
Answer: For mine, it seems to be limescale or other mineral buildup.  While throughput is no longer an issue after I soak it in vinegar/water, the mechanism that switches back to plain flow isn't working and I'm very frustrated.
Comment: Hello, and welcome to Home Improvement. This is interesting, but doesn't answer the original question. Please [take our tour](//diy.stackexchange.com/tour) so you'll know how best to contribute here.
Comment: Welcome to Home Improvement! If you have a NEW question, please ask it by clicking the [Ask Question](//diy.stackexchange.com/questions/ask) button. If you have sufficient reputation, [you may upvote](//diy.stackexchange.com/privileges/vote-up) the question. Alternatively, "star" it as a favorite and you will be notified of any new answers.


Typescript: How to narrow down function return type based on function parameter value

Question: I'm fairly new to typescript and can't figure out a way to properly narrow down the return type of a function based on an argument of that same function.
Consider the following code:
import exampleApiResource from './resources/example';
import exampleApiResource2 from './resources/example2';
import { ApiResources } from './typings';

const apiResources: ApiResources = {
  exampleResource: exampleApiResource,
  exampleResource2: exampleApiResource2,
};

export function useApiClient(resource: keyof ApiResources) {
  return apiResources[resource];
}

export default apiResources;

/** typings **/
export type ApiResources = {
  exampleResource: ExampleType;
  exampleResource2: ExampleType2;
};

export type ExampleType = {
  getExample: () => Promise<TestResource>;
};

export type ExampleType2 = {
  getExample2: () => Promise<TestResource>;
};

I want to expose the apiResources object through the useApiClient function. The exampleApiResource and exampleApiResource2 hold different properties, as you can see in the typings.
Typescript infers the useApiClient function to return the following types: ExampleType | ExampleType2
How would one narrow this down to a specific type, is this even possible?
--
Use case:
Expose an axios based API client through a function. The function accepts a parameter which will resolve to an object which contains functions to perform API related actions (E.G: getPosts(), updatePost() etc).
Answer: You should make useApiClient() a generic function whose type parameter K corresponds to the particular member(s) of keyof ApiResources passed in as resource:
export function useApiClient<K extends keyof ApiResources>(resource: K) {
  return apiResources[resource];
}

Now the return type of the function is ApiResources[K], an indexed access type corresponding to the type of the property value of type ApiResources at a key of type K.

You can verify that this will behave as desired when you call useApiClient() and return either ExampleType or ExampleType2 depending on the input:
const ex = useApiClient("exampleResource"); // const ex: ExampleType
const ex2 = useApiClient("exampleResource2"); // const ex2: ExampleType2

You'll only get the union ExampleType | ExampleType2 in cases where the input type is also a union:
const exUnion = useApiClient(
  Math.random() < 0.5 ? "exampleResource" : "exampleResource2"
);
// const exUnion: ExampleType | ExampleType2

Playground link to code


Enabling correct view updates in a custom SwiftUI container view

Question: The traditional way of creating a custom SwiftUI container is to simply declare a var content: () -> Content property inside a custom : View struct. We can then call the content function inside the container view's body to place the contained content.
This generally works, but there are situations where this fails. In the following simple scenario, view updates stop working reliably.
We also notice that if we replace our custom container with a native container such as HStack, the updates work correctly, implying that native containers come with something extra that allows the updates to trigger. It is unclear what is missing:
struct Container<Content: View>: View {
    @ViewBuilder var content: () -> Content

    var body: some View {
        self.content()
    }
}

struct Screen: View {
    // [1]
    // @State
    @AppStorage("isOn")
    private var isOn = false

    var body: some View {
        Form {
            Toggle("Outside", isOn: self.$isOn)

            Container {
                Toggle("Container", isOn: self.$isOn)
            }
            // [2]
            HStack {
                Toggle("HStack", isOn: self.$isOn)
            }
        }
        // [3]
        // .toggleStyle(MyToggleStyle())
    }
}

public struct MyToggleStyle: ToggleStyle {
    public func makeBody(configuration: Configuration) -> some View {
        Button {
            configuration.isOn.toggle()
        } label: {
            configuration.label

            Text(configuration.isMixed ? "Mixed" : configuration.isOn ? "On" : "Off")
        }
    }
}

#Preview {
    Screen()
}

We make a few observations (see annotations in the code):

If we use @State to track the state of isOn, all view updates trigger correctly. However, with @AppStorage, they do not.
The native HStack container does not suffer from any view update issues while the custom Container view does.
When we specify a custom ToggleStyle, the view updates further degrade, causing the content view to stop updating even when interacted with directly.

Can anyone advise how to implement a correct custom SwiftUI container view which behaves akin to the native ones regarding view updates?
Comment: I highly suspect this is a bug with `AppStorage`. If you wrap the `Toggle("Container", isOn: self.$isOn)` into its own view, passing the `Binding`. It works too.
Comment: @Sweeper I suspect that is because in such a case, the view updates are being handled by your new view, rather than by the parent.
Answer: When passing in T: View, it is recommended to evaluate the closure before storing it. When you do this, it stays in sync in all the examples that you listed:
struct Container<Content: View>: View {
    var content: Content

    init(@ViewBuilder content: () -> Content) {
        self.content = content()
    }

    var body: some View {
        self.content
    }
}

Note: this was mentioned in the SwiftUI WWDC Labs by SwiftUI engineers, but unfortunately, Apple doesn't publish that content after WWDC and it remains at best in the walled garden of the Slack and at worst, lost to time. I'm looking for a link that backs up my claim.
Comment: Huh. So the fact that using `@State` works is a mere coincidence? This also means that one would have to hand-write a lot of initialisers, not being able to use the automatically generated memberwise initialiser. :(
Comment: Thanks! You are on to something. Presumably, when the contained view is resolved during init of the container, it is done so under the supervision of the contained (parent) view, which is the one that owns `@AppStorage`, while left as a closure, the view resolution happens inside the container's body.
We can also use `struct Container: View { @ViewBuilder let content: Content`, so an `init` is unnecessary.
If you can track down that information, would be fantastic.


DB2DataReader object has data but HasRows property is false

Question: I have a program that uses a DB2 stored procedure called from a C# batch job. Once the .ExecuteReader() call has been made, Visual Studio 2010 shows that the FieldCount for the data reader object is '0' and the HasRows property is 'False.'
However.. upon further inspection I come to find that hidden deep within the object (this was discovered by sifting through the 'Locals' readout while debugging), the stored procedure is in fact sending data back and the information I need is burried deep within the DB2DataReader object.
Since both the HasRows and FieldCount properties are 'False' and '0', respectively, I cannot get to the data using any of it's built-in methods (i.e. .GetString(x), .GetValue(x).ToString(), etc). I cannot loop through the results because a while(reader.Read()) command will always be false (due to the HasRows property).
Has anyone experienced problems like this using any sort of DataReader, or have any suggestions in general?
Answer: As it turned out, the DB2 DataReader was not the best object to use. Instead we simply called an ExecuteNonQuery() command on the DB2Connection object (in C#) as were able to pull the data out using this method.


Get the number of different elements of a column when grouping by another column

Question: I am working with this pandas dataframe:
      Id     nb   sampleId
0      A     1       sA
1      B     2       sB
2      C     3       sD
3      D     4       sF
4      D     5       sF
5      A     6       sF
6      E     7       sF
7      F     8       sO
8      G     9       SP
9      H    10       SS
10     I    11       sK
11     C    12       sL

I am trying to get another dataframe grouping by Id as first column, and getting the number of different sampleId as second column. So my desired output would be this:
     Id  sampleId
0     A         2
1     B         1
2     C         2
3     D         1
4     E         1
5     F         1
6     G         1
7     H         1
8     I         1

I have tryed this:
df2=df.groupby(['Id'])['sampleId'].count().reset_index()

which is just counting the number of times each Id is repeated, not what I am looking for (as you can see, it seems that element D is repeated in two different sampleIds, when actually it is occurring twice in the same sampleId):
  srcId  sampleId
0     A         2
1     B         1
2     C         2
3     D         2
4     E         1
5     F         1
6     G         1
7     H         1
8     I         1

How can I achieve that?
Answer: Use -
df.groupby(['Id'])['sampleId'].nunique().reset_index()

Output
Id  sampleId
0   A   2
1   B   1
2   C   2
3   D   1
4   E   1
5   F   1
6   G   1
7   H   1
8   I   1


How can I auto check elements in nested ng-repeat?

Question: I have a div which contains ng-repeat elements. These ng-repeat elements are inter-related to each other. Elements of ng-repeat are having checkboxes. What I want is when the element of top ng-repeat is check it should auto check the elements in other ng-repeat. Below picture is showing the actual representation of elements and next pic is showing what actually I am trying to achieve.

I did try this but it is not working at all

            <input class="checkbox-actor" type="checkbox" name="actor-checkbox"  id="actor-checkbox\{{$index}}">\{{actor}}

                    <input class="checkbox-activity" type="checkbox" name="impact-checkbox" id="activity-checkbox\{{$index}}actor\{{actors.indexOf(actor)}}" activity-check-box>\{{impact}}

                                 <input class="checkbox" type="checkbox" name="impact-checkbox" id="" >\{{feature}}

Directive code:
    angular.module('mainModule').directive('activityCheckBox', function($interval) {
    return {
        restrict: 'EA',
        /*replace: false,*/
        scope: {
            ngModel:'='
        }
        /*require: 'createConnections','updateConnections', 'featureConnection'*/,
        /*transclude: true,*/

        link: function(scope, element, attrs) {

            element.find('input[type="checkbox"]').prop('checked',true);
        }
    };
});

angular.module('mainModule').directive('actorCheckBox', function($interval) {

    return {
        restrict: 'EA',
        /*transclude: true,*/

        link: function (scope, element, attrs, ctrl) {

            console.log(element);

            scope.$watch('ngModel', function(newValue){

                element.find('input[type="checkbox"]').prop('activityCheckBox',true).trigger('change');

            });
        }
    }
});

Answer: This cannot be implemented using the normal way we follow to check and uncheck elements. I used emit and brodcast inside the directive by capturing the dom. Here is the code I wrote and it works like a charm:
    angular.module('mainModule').directive('allCheckboxesBroadcast', function($interval) {
    return {
        restrict: 'A',
        controller: function($scope) {

            $scope.checkAll = function (model,id) {
                if (model == true){
                    $scope.$broadcast('allCheckboxes',id,  true);
                }else{
                    $scope.$broadcast('allCheckboxes',id,  false);
                }

            }

        }
    };
});

    angular.module('mainModule').directive('allCheckboxesListeners', function($interval) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {

            attrs.$observe('actorId', function(value) {

                scope.$on('allCheckboxes', function(event, id,shouldCheckAllCheckboxes) {

                    actorId = 'actor' + id;
                    if (value == actorId){

                        element.find('input').prop('checked', shouldCheckAllCheckboxes);
                        $scope.$broadcast('featureCheckboxesListeners', actorId, true);
                    }

                });

            });

        }
    };
});


How to get cell information of call received in android?

Question: I want get cell information (name of cell and address of cell) of incoming call in android?
Is this possible?
Comment: possible duplicate of [Android Handle phone call](http://stackoverflow.com/questions/4324659/android-handle-phone-call)
Answer: It is possible, if the information are stored in your device phonebook.  You can use PhoneStateListener to detected Phone call State.
Here more information
Comment: Explain and give an example to be more. please


How to change a picture to fail comparison algorithms?

Question: Is there a way to change a picture so it would fail to match against existing copy of the same picture on the big social networks such as Facebook, Twitter, Instagram, Tinder and others? Desired result should be as close as possible to the original.
Answer: It's dependent on the algorithm used for comparison, but if you have access to that algorithm, you can add small amounts of noise to pixels randomly until it misclassifies the image.
If you had deeper knowledge of the algorithm used, and it was differentiable, you could use gradient descent (ascent) to modify the image to increase the error of what was detected. This is the reverse of what you do when training image comparisons/classifiers which modify the weights to minimize the error.
But in short, if you dont have much knowledge of how the algorithm used works, I personally would try adding noise to pixels randomly, such that the image was still easily recognizable, but a decent amount of noise was added in.
Comment: Probably, there is a fft, wavelet or laplacian. Many of them are extremely noise resistant.
Comment: @joojaa The laplacian is the opposite of noise resistant, it blows up noise disproportionately. That's why you usually apply Gaussian convolution before that. But facebook certainly uses something more robust, so it should deal with noise quite easily. Honestly, without knowing the algo, or extensive trial and error, it is very hard to know how to modify the image.
Comment: Is there something that those techniques are weak against? I wonder if tone mapping or white balance type things would thwart them?
Comment: Well usually a mirror image or gafting two pictures into one
Comment: Ah neat, so maybe mirror image and add some noise to cover your bases?


(Proof-verification) Geometric interpretation of homology

Question: I want to verify the following claim:

Any singular $n-$boundary "encloses" a homotopy of singular $n-$simplices (for $n \ge 1$).

Specifically, let $p \in \Delta_n$ be given, i.e. $p=(p_0,p_1,\dots,p_n) \in \mathbb{R}^{n+1}$, $\sum_{k=0}^n p_k =1$.
Let $\phi: \Delta_{n+1} \to X$ be continuous (this is called a singular $(n+1)-$simplex).
As I argue below, I think the following assertion "proves" the above heuristic claim -- I am pretty sure that the correctness of the assertion follows immediately from the definitions, but I would like someone to double-check this, since I have not seen it written anywhere else before:

Assertion: Between the two singular $n-$simplices, $$(\partial_i\phi)(r_0, \dots, r_n) = \phi(r_0, \dots, r_{i-1},0,r_i, r_{i+1}, \dots, r_n), \\ (\partial_j\phi)(s_0, \dots, s_n)=\phi(s_0,\dots,s_{j-1},0,s_j,s_{j+1},\dots, s_n),$$ called the $i$th and $j$th faces of the singular $(n+1)-$simplex $\phi$, respectively, the following is a homotopy, i.e. a continuous function $H: \Delta_n \times[0,1] \to X$ such that for all $p \in \Delta_n$, $H(p,0)=(\partial_i \phi)(p)$ and $H(p,1)=(\partial_j \phi)(p)$: $$ H(p,\!t)\!=\!\begin{cases}  \phi(p_0,\!\dots\!, p_{i-1}, tp_i, (1\!-\!t)p_i + tp_{i+1},\!\dots\!, (1\!-\!t)p_{j-2}+tp_{j-1}, (1\!-\!t)p_{j-1}, p_j,\!\dots\!, p_n) & i < j \\ \phi(p_0,\!\dots\!, p_{j-1}, tp_j, (1\!-\!t)p_j + tp_{j+1},\!\dots\!, (1\!-\!t)p_{i-2}+tp_{i-1}, (1\!-\!t)p_{i-1}, p_i,\!\dots\!, p_n) & j<i \end{cases}$$ Additionally, it is also the case that $H(\Delta_n \times [0,1]) \subseteq \phi(\Delta_{n+1})$.
Comment: What is the phrase "a homotopy of n-simplices" supposed to mean?
Comment: @Semiclassical singular $n-$simplices are continuous maps $\sigma: \Delta_n \to X$, so given two singular $n-$simplices $\sigma_1, \sigma_2$, a homotopy between them is a continuous function $H: \Delta_n \times [0,1] \to X$ such that, for $p \in \Delta_n$, $H(p,0)=\sigma_1(p)$ and $H(p,1)=\sigma_2(p)$.
Answer: Unnecessarily Verbose Background Information
Note: singular $n-$simplices are continuous maps $\sigma: \Delta_n \to X$, so given two singular $n-$simplices $\sigma_1, \sigma_2$, a homotopy between them is a continuous function $H: \Delta_n \times [0,1] \to X$ such that, for $p \in \Delta_n$, $H(p,0)=\sigma_1(p)$ and $H(p,1)=\sigma_2(p)$.
What I mean by the image of a singular $m-$chain $0\not=\mathfrak{s}\in C_m(X)$: for any singular $m-$chain $\mathfrak{s}\not=0$ we have a decomposition as follows: $$ \mathfrak{s} = a_1\mathfrak{s}_1 + \dots + a_{\ell}\mathfrak{s}_{\ell} $$ where all of the $a_i \not=0$ and all of the $\mathfrak{s}_i$ are singular $m-$simplices, continuous maps $\mathfrak{s}_i: \Delta_m \to X$. Then we define the image of $\mathfrak{s}$ to be $$\bigcup_{j=1}^{\ell} \mathfrak{s}_j(\Delta_m) \subseteq X$$ i.e. the image of the "sum" of generators is just their union, and non-zero multiplicity does not affect the set of points we determine to be their image. For the singular $m-$chain $0$ (the additive identity of the free abelian group $C_m(X)$), we declare its image to be the empty set $\emptyset$.
When I say that a singular $n-$boundary $\partial(c)$ encloses a homotopy $\tilde{\phi}$ singular $n-$simplices, I mean that the image of the homotopy $\tilde{\phi}(\Delta_n \times [0,1]) \subseteq X$ in X is a subset of the image of the singular $(n+1)-$chain $c$ as defined above.
Attempt: Define the $(n+1)$th boundary map $\partial: C_{n+1}(X) \to C_n(X)$ by $$\partial:= \sum_{i=0}^{n+1} (-1)^i \partial_i \quad \text{(with the $i$th face $\partial_i$ to be defined later).}$$ (This is the definition used in Vick's Homology Theory -- note that $C_{n+1}(X)$ is the group of singular $(n+1)-$chains, i.e. the free abelian group whose generators are singular $(n+1)-$simplices). Given any $n-$boundary, by definition it equals $\partial(c)$ for some $a_1 c_1 + \dots + a_kc_k \in C_{n+1}(X)$, where all of the $c_i$ are singular $(n+1)-$simplices. Since $\partial$ is a group homomorphism, we have that $$\partial(c)=\partial(a_1c_1 + \dots + a_k c_k)=a_1\partial(c_1) + \dots + a_k\partial(c_k), $$ so without loss of generality we consider only the case of $n-$boundaries of the form $\partial(\phi)$ for $\sigma$ a singular $(n+1)-$simplex, $\phi: \Delta_{n+1} \to X$ continuous.
Now we define the faces of $\phi$ for $0 \le i \le n$ by $$(\partial_i\phi)(s_0, \dots, s_n)=\phi(s_0, s_1, \dots, s_{i-1},0,s_i, \dots, s_n),$$ note that these are all singular $n-$simplices. Now for $i\not=j$ such that $(-1)^i=(-1)^j$ (which exists since $n+1 \ge 2$ by assumption and $0 \le i,j \le n+1$) we can define a homotopy between the singular $n-$simplices $(\partial_i \phi)$ and $(\partial_j \phi)$ as follows: $$ t\in[0,1], \quad \tilde{\phi}_{i \to j} =  \begin{cases} \phi(s_0, s_1, \dots, s_{i-1}, ts_j, s_i, s_{i+1}, \dots, s_{j-1}, (1-t)s_i, s_j, s_{j+1}, \dots, s_n) & i<j \\ \phi(s_0, s_1, \dots, s_{j-1}, (1-t) s_i, s_j, s_{j+1}, \dots, s_{i-1}, ts_j, s_i, s_{i+1}, \dots, s_n) & j <i \end{cases} $$ Letting $(-1)^i = \varepsilon = (-1)^j$, we have that $\varepsilon \tilde{\phi}_{i \to j}(0) = \varepsilon \phi_i$ with $\phi_i(\Delta_n) \subseteq \bigcup_{i=0}^{n+1} (\partial_i \phi)(\Delta_n)$ and $\varepsilon \tilde{\phi}_{i \to j}(1) = \varepsilon \phi_j$ with $\phi_j(\Delta_n) \subseteq \bigcup_{i=0}^{n+1} (\partial_i \phi)(\Delta_n)$, thus the singular $n-$boundary "encloses" a homotopy between the singular $n-$simplices $\varepsilon \phi_i$ and $\varepsilon \phi_j$. This completes the proof. $\square$
Now since I am not proving that coordinate restrictions of $\phi$ are again continuous functions into $X$, I am not sure if this proof is obviously incorrect or obviously correct -- either way I'm sure it is a dumb question. In any case, if anyone who is an expert in this area wouldn't mind giving this a quick glance-over and me a sanity check, I would be much obliged for their help.
Context/Motivation for Question: So far I have been trying to use the following heuristic interpretation of (singular) homology to motivate the definitions and computations:

Geometric holes are modeled topologically by the non-existence of continuous deformations.
The absence of geometric holes is modeled topologically by the existence of continuous deformations.

Specifically, for each dimension $n$ (and to motivate the definition of boundaries and why we factor them out from homology groups):

"$n-$dimensional holes" are modeled topologically by the non-existence of an enclosed homotopy between singular $n-$simplices.
The absence of "$n-$dimensional holes" (i.e. (generators of) $n-$boundaries) are modeled topologically by the existence of an enclosed homotopy of singular $n-$simplices.

If you have any comments about the sensibility/dangerousness of these statements, please let me know, although it is not the main thrust of my question.


What is the name of this multiplayer game where a shield can be 'Regraded' into 'Divine'?

Question:
I cannot provide any description, since I have nothing to go on other than the screenshot. I tried a google reverse search, but it came up empty.
Screenshot is taken from here: https://i.stack.imgur.com/IvSbt.jpg
Does anyone know which game this is? I know it is not Guild Wars 2 as suggested in the comments of that gallery post.
Answer: Based on one of the comments on the Imgur page, and then looking at said game, I think it is Archeage. Here is a screenshot I found on Google Images, where the style and UI matches:
https://i.ytimg.com/vi/rlb6A-AEtfw/maxresdefault.jpg


How to change bar button image color?

Question: I want to set image in bar button item like below.

I added this image to Assets.xcassets and when i tried to set image, it changes color automatically.

how can I set image as it is in bar button item?
Answer: Well, you have to edit your image first. Make it transparent (PNG) if it's not, and objects must be be white within the image, in your case it's black now. Then in your code change the tint color like this:
let myImage = UIImage(named: "myImage")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
myImage.tintColor = UIColor.blackColor()

Comment: What  for objective c?
Comment: `Value of type 'UIImage' has no member 'tintColor'`
Comment: Read this https://stackoverflow.com/questions/11066008/why-is-my-uibutton-tintcolor-not-working @pableiros
Answer: I think you need to change the rendering mode of image to always original.
It is taking template image of your image.
let img:UIImage = UIImage(named: "Bitcoin")!
img.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)

try changing the rendering mode of the image before setting it to bar button.
for more info on Image Rendering Mode refer this
for Objective C....
UIImage *img = [UIImage imageNamed:@"Bitcoin"];
UIImage *original = [img imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)];

:)
Answer: Try to change the Tint colour.
Comment: i already tried. but this is change color of image. i want to set image default color.
Answer: UIImage* image3 = [UIImage imageNamed:@"search_button.png"];
CGRect frameimg = CGRectMake(15,5, 25,25);

UIButton *someButton = [[UIButton alloc] initWithFrame:frameimg];
[someButton setImage:image3 forState:UIControlStateNormal];
[someButton addTarget:self action:@selector(Search_btn:)
     forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *searchButton =[[UIBarButtonItem alloc] initWithCustomView:someButton];
self.navigationItem.leftBarButtonItem =mailbutton;

How to change bar button image color?


How to select video from gallery and set the selected video icon to ImageView

Question: This technique is successfully performed for using pictures from Gallery
But i want to implement the same thing for Audio as well as video .
The code is
<code>public void video(View v)
{
    Intent i = new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
    RESULT_LOAD_VIDEO = 1;
    startActivityForResult(i, RESULT_LOAD_VIDEO);
}
public void audio(View v)
{
    Intent i = new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
    RESULT_LOAD_AUDIO = 1;
    startActivityForResult(i, RESULT_LOAD_AUDIO);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

      if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK &&null != data)
      {
          Uri selectedImage = data.getData(); String[]
      filePathColumn = { MediaStore.Images.Media.DATA };

      Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
      cursor.moveToFirst();

      int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
      String picturePath = cursor.getString(columnIndex); cursor.close();

      // String picturePath contains the path of selected Image

      NewPoll.flag++;
      Path.patha= picturePath;
      Intent ints=new  Intent(getApplicationContext(),NewPoll.class);
      ints.putExtra("address",picturePath);
      ints.putExtra("option",comingData);
      startActivity(ints);
      }

      if (requestCode == RESULT_LOAD_VIDEO && resultCode == RESULT_OK &&null != data)
      {
          Uri selectedVideo= data.getData(); String[]
      filePathColumn = { MediaStore.Video.Media.DATA };

      Cursor cursor = getContentResolver().query(selectedVideo,filePathColumn, null, null, null);
      cursor.moveToFirst();

      int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
      String videoPath = cursor.getString(columnIndex); cursor.close();

      // String picturePath contains the path of selected Image

      NewPoll.flag++;
      Path.patha= videoPath;
      Intent ints=new  Intent(getApplicationContext(),NewPoll.class);
      ints.putExtra("address",videoPath);
      ints.putExtra("option",comingData);
      startActivity(ints);
      }

      if (requestCode == RESULT_LOAD_AUDIO && resultCode == RESULT_OK &&null != data)
      {
          Uri selectedAudio= data.getData(); String[]
      filePathColumn = { MediaStore.Audio.Media.DATA };

      Cursor cursor = getContentResolver().query(selectedAudio,filePathColumn, null, null, null);
      cursor.moveToFirst();

      int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
      String audioPath = cursor.getString(columnIndex); cursor.close();

      // String picturePath contains the path of selected Image

      NewPoll.flag++;
      Path.patha= audioPath;
      Intent ints=new  Intent(getApplicationContext(),NewPoll.class);
      ints.putExtra("address",audioPath);
      ints.putExtra("option",comingData);
      startActivity(ints);
      }

}
</code>
I got success for photo-gallery but dont know how to use video and audio gallery
Code from ur side is appriciated !
Thanks
Answer: <code>//from this u get all audio
    private void getallaudio()
    {

        String[] STAR = { "*" };

        Cursor audioCursor = ((Activity) cntx).managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, STAR, null, null, null);
        if (audioCursor != null)
        {
            if (audioCursor.moveToFirst())
            {
                do
                {

                    String path = audioCursor.getString(audioCursor.getColumnIndex(MediaStore.Audio.Media.DATA));
                    controller.audioWrapper.add(new MediaWrapper(new File(path).getName(), path, "Audio",false,color_string));
//                    Log.i("Audio Path",path);
                }while (audioCursor.moveToNext());

            }
//            audioCursor.close();
        }
    }

    //from this u get all video
    private void getallvideo()
    {
         String[] STAR = { "*" };

        controller.videoWrapper.clear();
        Cursor videoCursor = ((Activity) cntx).managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, STAR, null, null, null);
        if (videoCursor != null)
        {
            if (videoCursor.moveToFirst())
            {
                do
                {

                    String path = videoCursor.getString(videoCursor.getColumnIndex(MediaStore.Images.Media.DATA));
                    controller.videoWrapper.add(new MediaWrapper(new File(path).getName(), path, "Video",false,color_string));
//                    Log.i("Video Path",path);
                }while (videoCursor.moveToNext());

            }
//            videoCursor.close();
        }
    }
</code>
Comment: what is  controller ??
Comment: just ignore it actually it is my class name where i save this data u can save anywhere your data
Comment: ok ! I tried ur code it have no error,, i tried debugging ,,, ur code is executing but not giving the output,, it s not even opening the gallery .....
Comment: dude its only give u all image detaik like name path etc etc etc then u just make one adapter take grid view and set it with help of my data :) its custom dude