text:
Q: django haystack whoosh search I am trying to create multiple query using haystack-whoosh
I am getting error below   in command prompt:
   C:\Users\varun\Desktop\Project\mysite>python manage.py rebuild_index
C:\Python34\lib\importlib\_bootstrap.py:321: RemovedInDjango110Warning: django.core.context_processors is deprecated in favor of django.template.context_processors.
  return f(*args, **kwds)

WARNING: This will irreparably remove EVERYTHING from your search index in connection 'default'.
Your choices after this are to restore from backups or rebuild via the `rebuild_index` command.
Are you sure you wish to continue? [y/N] y
Removing all documents from your index because you said so.
Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Python34\lib\site-packages\django\core\management\__init__.py", line 353, in execute_from_command_line
    utility.execute()
  File "C:\Python34\lib\site-packages\django\core\management\__init__.py", line 345, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Python34\lib\site-packages\django\core\management\base.py", line 348, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Python34\lib\site-packages\django\core\management\base.py", line 399, in execute
    output = self.handle(*args, **options)
  File "C:\Python34\lib\site-packages\haystack\management\commands\rebuild_index.py", line 32, in handle
    call_command('clear_index', **options)
  File "C:\Python34\lib\site-packages\django\core\management\__init__.py", line 119, in call_command
    return command.execute(*args, **defaults)
  File "C:\Python34\lib\site-packages\django\core\management\base.py", line 399, in execute
    output = self.handle(*args, **options)
  File "C:\Python34\lib\site-packages\haystack\management\commands\clear_index.py", line 53, in handle
    backend.clear(commit=self.commit)
  File "C:\Python34\lib\site-packages\haystack\backends\whoosh_backend.py", line 232, in clear
    self.setup()
  File "C:\Python34\lib\site-packages\haystack\backends\whoosh_backend.py", line 119, in setup
    self.content_field_name, self.schema = self.build_schema(connections[self.connection_alias].get_unified_index().all_searchfields())
  File "C:\Python34\lib\site-packages\haystack\utils\loading.py", line 342, in all_searchfields
    self.build()
  File "C:\Python34\lib\site-packages\haystack\utils\loading.py", line 237, in build
    self.collect_fields(index)
  File "C:\Python34\lib\site-packages\haystack\utils\loading.py", line 245, in collect_fields
    raise SearchFieldError("All 'SearchIndex' classes must use the same '%s' fieldname for the 'document=True' field. Offending index is '%s'." % (self.document_field, index))
haystack.exceptions.SearchFieldError: All 'SearchIndex' classes must use the same 'text' fieldname for the 'document=True' field. Offending index is '<personal.search_indexes.PostIndex object at 0x00000000056DFCA8>'.

settings.py
HAYSTACK_CONNECTIONS = {
     'autocomplete': {
        'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
        'PATH': 'C:\\Users\\varun\\Desktop\\Project\\mysite\\personal\\templates\\search\\indexes,
        'STORAGE': 'file',
        'POST_LIMIT': 128 * 1024 * 1024,
        'INCLUDE_SPELLING': True,
        'BATCH_SIZE': 100,
        'EXCLUDED_INDEXES': ['thirdpartyapp.search_indexes.BarIndex'],
    },
}

HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'

while my search_indexes.py reads
import datetime
from haystack import indexes
from Post.models import Post

class PostIndex(indexes.SearchIndex,indexes.Indexable):
    from1 = models.CharField(document=True,use_template=True)
    type_of_truck = models.CharField(max_length=20)
    date = models.DateField()
    slug = models.SlugField(unique=True)
    weight = models.DecimalField( max_digits=5, decimal_places=2)
    Material_Name = models.CharField(max_length=20)
    To = models.CharField(max_length=20)
    Number_Of_Truck = models.CharField(max_length=20)
    Time = models.TimeField()
    Volume = models.CharField(max_length=20)
    Material_Type = models.CharField(max_length=20)

    content_auto = indexes.EdgeNgramField(model_attr='from1')

    def get_model(self):
        return Post
    def index_queryset(self,using=None):
            """used when entire index for model is updated."""
        return self.get.model().objects.all()

models.py
class Post(models.Model):

    id = models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')
    user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
    from1 = models.CharField(max_length=20)
    type_of_truck = models.CharField(max_length=20)
    date = models.DateField()
    slug = models.SlugField(unique=True)
    weight = models.DecimalField( max_digits=5, decimal_places=2)
    Material_Name = models.CharField(max_length=20)
    To = models.CharField(max_length=20)
    Number_Of_Truck = models.CharField(max_length=20)
    Time = models.TimeField()
    Volume = models.CharField(max_length=20)
    Material_Type = models.CharField(max_length=20)
    #updated = models.DateTimeField(auto_now=True, auto_now_add=False)
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)

Post_text
{{object.from1}}
{{object.To}}
{{object.Material_Type}}

while i just added "from haystack.query import SearchQuerySet" in my views.py
as earlier my search query was working but i could search only single query at a time,while i want to create query having multiple filters
please help why i am getting error


text:
Q: Upgrading to New MacBook Pro Currently I have the MacBook Pro Mid'12 and which comes with a 500 GB HDD I want to upgrade to the 2015 model MacBook Pro. I have cleared my MacBook out so I have now used around 130GB which SSD will I need 256GB or 512GB?

A: It is your decision and you need to evaluate the circumstances, but keep in mind that you cannot expand the storage. If you see yourself needing a large amount of storage for something like photos or videos, I would recommend the 512. Mine is a 256 and I'm fine with it though.

A: I would get the larger SSD. You'll never be sorry that you have "too much" storage.
Whether you get the 512 GB or the 256 GB, there is currently at least one option for expanding the 2015 MacBook Pro storage: memory that goes into the SD Card slot. Transcend makes a variety of card (different capacities, and different shapes to sit flush with the various MacBook Pros and MacBook Airs). You can use their site to see what would work in the MacBook Pro you are thinking of buying.
Adding an SD card gives you a second volume on the MacBook Pro. It does not "merge" with the built-in storage but you can probably find a way to use it that works for you. Some people use the SD card memory for music, some for photos.
(Technically you can combine two physical storage units into a single "logical" unit (that is, one icon on the desktop). It is not what I would recommend here.)
I am not affiliated with Transcend but I have used their products and they work fine.
http://www.transcend-info.com/support/Compatibility

A: Physically either of the 256GB or 512GB options will satisfy your requirements as you only have 130GB of data on your old device.
Apple tends to charge more for upgrades than 3rd party options, however there is some value in having an OEM solution to storage. You could start with 256GB and use a 3rd party upgrade down the line to obtain more storage if you feel technically inclined enough to do the hard drive swap. It's certainly very simple to do and there are many walkthroughs available on the internet. For instance, here are the instructions for performing this upgrade on a 2014 Retina MacBook Pro. The steps for a more recent generation Retina Macbook Pro would be similar.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Node.js Setting Header complains can't set header after being sent, but it is before In Node.js(Connect.js, actually)Trying to set the header but I get "Error: Can't set headers after they are sent.". But I am setting it before the header is sent with server.use(function(req, res, next) {}) so I don't clearly see what is wrong.
server.use(livereload({ port: lrport }));
server.use(bodyParser.urlencoded({
    extended: true
}));
server.use(function(req, res, next) {
    res.writeHead(200, [
        ['Set-Cookie', 'mycookie1=value1']
        ]);
    console.log(req);
    next();
});

server.use(prism.middleware);

A: I was able to use setHeader() instead. Not sure what would be the difference between res.writeHead() and res.setHeader() as far as setting headers is concerned.


text:
Q: Barcode 39 font in PDF File Writer C# Class Library I am using PDF File Writer C# Class Library. I want to print a barcode. How can I add the Barcode 39 font to this library?

A: Per the example project in the source, you can reference fonts on the local system with the following:
PdfFont ArialNormal = new PdfFont(Document, "Arial", FontStyle.Regular, true);
Contents.DrawText(ArialNormal, NoteSize, NoteX, NoteY0, "text goes here");

If you install this Barcode font you should be able to reference it in the same way. Note: you may want to close Visual Studio, install the font, then reopen (or reboot) to ensure you're referencing the updated font list.

A: Please note the PDF File Writer C# Class Library (Version 1.5) supports barcode. The supported codes are Code-39, Code-128, UPC-A and EAN-13. This support is without using fonts.


text:
Q: Jwplayer can't play video in Chrome This is my first time using Jwplayer. I am trying to play a video using Jwplayer. The code I have written works in Firefox, IE, Opera but not in Chrome.
It is saying "error loading media : file cannot be played". My code is given below. I am also using CodeIgniter and Bootstrap.

Loading the player...

$(document).ready(function(){
    jwplayer("ad-video").setup({
        file: "http://vatiali.com/assets/videos/choc.mp4",
        image: "http://vatiali.com/assets/images/black.jpg"
    });
});

A: I don't think that is the correct fix. I think that is a workaround which is masking the true problem.
The default setting for primary playback mode is HTML5. When operating with the default setting JWPlayer should automatically fallback to playing the video with flash if the browser does not support HTML playback for the video file and the Flash plugin is installed.
I suspect that your JWPlayer implementation only works with Flash.
Please test your implementation on a browser that does not have Flash installed but supports HTML5 playback of the video type you are using. I suspect it will not work.

To further troubleshoot this please revert the primary setting to the default, open the JavaScript console, refresh the page and tell us what error you see.
Here's a guess as to what the problem might be. Is the jwplayer.html5.js file located in the same directory as the jwplayer.js file? If not you can use the 'html5player' option t specify the location of the file.

A: I had to set the option for primary to 'flash' for my jwplayer setup. The code looks like
video_player_jw.setup({
        file: $('#source_url').val(),
        height: 360,
        width: 640,
        primary: 'flash'
    });

I am only doing this in chrome as it works fine with primary as html5 in all other browsers.


text:
Q: ruby splat operator compilation error in eclipse but runs fine on command line I have the following ruby script ruby_test.rb in eclipse (DLTK/RUBY), which throws a compilation error and I am not able to run in eclipse. This makes sense since *arr should be the last parameter. But when I run it on command line (ruby ruby_test.rb) its runs fine. any idea why?
My installed ruby version is 2.1.6p336
#!/usr/bin/ruby

arr = [1,2,3]

def test(a1,a2,a3,a4,a5)
   puts "The first number  is #{a1}"
   puts "The second number is #{a2}"
end

test(0, *arr, 4)

A: Perhaps you have an old version of Ruby on eclipse, on which a splat argument had to be the last argument.


text:
Q: Performing arithmetic on floating point values of different sizes My code does not run as I would expect if one float variable has 5 digits, others have 4, and an arithmetical operation is performed on them. For example:
def capacity(self):

    mmax = self.mmax.get()
    current = self.current.get()
    mmin = self.mmin.get()

    flag = False

    if flag is False:
        if mmax.isdigit() and mmin.isdigit() and current.isdigit():
            capacity = float(100 * ((float(current) - float(mmin)) / (float(mmax) - float(mmin))))
            if mmin <= current <= mmax and 0 <= capacity <= 100:
                flag = True
            else:
                self.result = str("Please ensure the values entered correspond to the correct value.")
        else:
            self.result = str("Please enter only positive integers.")

    if flag is True:
        self.result = "Capacity: %2.2f" % capacity + '%'

If mmax = 10000, current = 5000, and mmin = 1000, self.result = str("Please ensure...").
If mmax = 9999, current = 5000, and mmin = 1000, self.result = str("Capacity: 44.45%).
What's going on here/ how can I overcome this problem?

A: I'm guessing that mmin and current and mmax are strings. In which case, this expression:
if mmin <= current <= mmax and 0 <= capacity <= 100:

... Is doing a lexicographical comparison on the values. This is different from a numerical comparison: for example, "5000" < "10000" evaluates to False because "5" is larger than "1".
Convert your values to numbers before doing comparisons on them.
if mmax.isdigit() and mmin.isdigit() and current.isdigit():
    mmax = float(mmax)
    current = float(current)
    mmin = float(mmin)

    capacity = float(100 * ... #etc

Or
if float(mmin) <= float(current) <= float(mmax) and 0 <= capacity <= 100:


text:
Q: ElasticBeanstalk change a file I want to add analytics code to an HTML file in a ElasticBeanstalk app. I just want to change one HTML file.
I don't want to update my app completely. Is there an easy way to do that?

A: You can follow the instruction in below documentation where it is mentioned step by step on how you can update your application. They have shown this update by just updating one file which is index.php.
Update an Application with AWS Elastic Beanstalk
To summarise, below are high-level steps :

*

*if you have .zip file of your existing code then unzip it.

*Make the changes in that one file.

*Zip it again.

*Upload it in the Application Version with a different name and click on deploy.

*Your updated code will be deployed.

To update the file without the downtime, please use EB provided Deployment Strategies which avoid any downtime.
Deploying Applications to AWS Elastic Beanstalk Environments
Below are the three strategies which you can utilize :

*

*Rolling with additional batch

*Immutable

*Blue/green


text:
Q: C# WPF - How to send an e-mail (to myself)? for debugging purposes, I have globally handled all exceptions. Whenever an exception occurs, I silently handle it, and want to send myself an e-mail with the error details, so I can address this issue.
I have two emails, email1@gmail.com, and email2@gmail.com...
I have attempted using this code to send myself an e-mail, but it is not working.
        string to = "email1@gmail.com";
        string from = "email2@gmail.com";
        string subject = "an error ocurred";
        string body = e.ToString();
        MailMessage message = new MailMessage(from, to, subject, body);
        SmtpClient client = new SmtpClient("smtp.google.com");
        client.Timeout = 100;
        client.Credentials = CredentialCache.DefaultNetworkCredentials;
        client.Send(message);

I have tried countless other pieces of code but I have no idea how to do it. Does anyone have a solid solution for this? Thanks a bunch.

A: This has to work. See more info here: Sending email in .NET through Gmail
using System.Net;
using System.Net.Mail;

//...

var fromAddress = new MailAddress("alextodorov01@abv.bg", "From Name");
var toAddress = new MailAddress("kozichka01@abv.bg", "To Name");
const string fromPassword = "fromPassword";
const string subject = "an error ocurred";
const string body = e.ToString();

var smtp = new SmtpClient
{
    Host = "smtp.gmail.com",
    Port = 587,
    EnableSsl = true,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    UseDefaultCredentials = false,
    Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
    Subject = subject,
    Body = body
})
{
    smtp.Send(message);
}

//...


text:
Q: Coding ordered sets As for having Coq programming experience,
I'd like to know if there are any other ways to code, instead of my coding, preorder relations for using them in checking a function is non-decreasing. I replaced the datatypes and functions of my program to simple ones in the code below.
mydata is a set with a preorder relation (i.e. with a reflexive and transitive relation)  and is  the range of the function mappingFunction which maps nat numbers to mydata. I couldn't define preorder relation on mydata when coding theorem  mappingFunction_isIncreasing, so as a solution I mapped mydata to nat numbers through dataparts_toNat to enable me to define the preorder relation among them. I wonder if there is any other ways to do this program, for example without having dataparts_toNat. Thank you.
 (*defining the datatype*)
Inductive mydata : Set :=
  | part1 : mydata
  | part2 : mydata
  |part3 :mydata.

(* mapping to nats to have
        preorder relation(part1<part2<part3 and part1=part1 and part2=part2 and part3=part3)*)
Definition dataparts_toNat (n:mydata):nat :=
   match n with
          |part1 => 0
          |part2 => 1
          |part3 => 2
    end.

(* a sample function from nat to mydata which is always increasing or not changing*)
Definition mappingFunction
  (a1:nat): mydata :=
        match a1 with
           |0=> part1
           |S(0) => part2
           |_ => part3
         end.
Theorem mappingFunction_isIncreasing: forall(a1 a2: nat)(data1 data2: mydata),
   a1<=a2 -> (mappingFunction a1= data1 )/\(mappingFunction a2=
data2) -> ((dataparts_toNat data1) <= dataparts_toNat(data2)).
Proof.

A: (* The definition of mydata again, for completeness *)
Inductive mydata : Set :=
| part1 : mydata
| part2 : mydata
| part3 : mydata.

You can define a comparison as a boolean function mydata -> mydata -> bool:
Definition le_mydata_dec (d1 d2 : mydata) : bool :=
  match d1, d2 with
  | part1, _ => true
  | part2, (part2 | part3) => true
  | part3, part3 => true
  | _, _ => false
  end.

And from that, derive a comparison relation mydata -> mydata -> Prop (this is only one way, sometimes it's more convenient to define le_mydata as an Inductive proposition).
Definition le_mydata (d1 d2 : mydata) : Prop :=
  le_mydata_dec d1 d2 = true.

The mapping function is the same (renamed f for brevity):
(* a sample function from nat to mydata which is always increasing or not changing*)
Definition f
  (a1:nat): mydata :=
        match a1 with
           |0=> part1
           |S(0) => part2
           |_ => part3
         end.

Now this is monotonicity:
Theorem f_isMonotonic: forall(a1 a2: nat),
   a1<=a2 -> le_mydata (f a1) (f a2).
Proof.
Abort.

You can use notations to replace le_mydata with a prettier <=. Here we are careful to not hide the preexisting notation <= for comparison of nat, by assigning this new notation to a new scope mydata_scope, delimited with the key mydata.
Infix "<=" := le_mydata : mydata_scope.
Delimit Scope mydata_scope with mydata.
(* now we can write  (x <= y)%mydata  instead of  le_mydata x y *)

The monotonicity theorem again, using that notation:
Theorem f_isMonotonic: forall(a1 a2: nat),
   a1<=a2 -> (f a1 <= f a2)%mydata.
Proof.
Abort.


text:
Q: phantom access website and got page with title "Welcome To Zscaler Directory Authentication" Here is my code,
var page = require('webpage').create();
page.open('http://github.com', function() {
  page.render('example.png');

});

Here is what I got
------------
Welcome To Zscaler Directory Authentication
------------
Authenticating user to the Web Security Service

Anyone know how to solve this?


text:
Q: An error occurred while uploading the image in Sitecore Media Library I want to manually upload an image into specific folder in the Sitecore Media Library.
While uploading the image I am getting an error saying An error occurred while uploading a file. The reason may be the that the file does not exist or the path is wrong.
Please see the screenshot below:

I have tried to change some configuration settings in the Sitecore.Speak.Applications.config file but still having the same issue.
Please advise what can be causing this error.

A: I saw a similar error in the past and in my case it was caused by a duplicate item name in the Media Library folder.
Image names in each media folder should be unique. If you try to upload a file with the name that already exists in the selected folder, Sitecore will return the message saying "the file does not exist or the path is wrong".
If this is the problem, you will see the error Sitecore.Exceptions.DuplicateItemNameException in Sitecore log file:
35220 12:30:19 ERROR Could not save posted file: test.png
Exception: Sitecore.Exceptions.DuplicateItemNameException
Message: The item name "test" is already defined on this level.
Source: Sitecore.Kernel
   at Sitecore.Data.Items.ItemUtil.AssertDuplicateItemName(Item destinationItem, Item sourceItem, String name)
   at Sitecore.Data.Items.ItemUtil.AssertItemName(Item destinationItem, Item sourceItem, String name)
   at Sitecore.Data.Items.Item.Add(String name, TemplateID templateID)
   at Sitecore.Resources.Media.MediaCreator.CreateItem(String itemPath, String filePath, MediaCreatorOptions options)
   at Sitecore.Resources.Media.MediaCreator.AttachStreamToMediaItem(Stream stream, String itemPath, String fileName, MediaCreatorOptions options)
   at Sitecore.Resources.Media.MediaCreator.CreateFromStream(Stream stream, String filePath, MediaCreatorOptions options)
   at Sitecore.Resources.Media.MediaUploader.UploadToDatabase(List`1 list)
   at Sitecore.Resources.Media.MediaUploader.Upload()
   at Sitecore.Pipelines.Upload.Save.Process(UploadArgs args)

UPDATE:
I double checked when this error message is used, and it can be caused by any exception thrown during media item creation. Some exceptions are thrown during item name validation: for example, if file name is too long (setting MaxItemNameLength), name ends with ., name starts or ends with spaces or tabs, name contains invalid characters (setting InvalidItemNameChars) or name does not match pattern from the setting ItemNameValidation.
So you can try uploading another file or renaming your file to a simple file name containing only letters and see if it helps.


text:
Q: Confused About Change of Integration Limits in Convolution Proof My textbook has proved the convolution theorem as follows:

Theorem
If $f(t)$ and $g(t)$ are two functions of exponential order (so that their Laplace transforms exist), and writing $\mathcal{L} \{ f \} = F(s)$ and $\mathcal{L} \{ g \} = G(s)$ as the two Laplace transforms, then $\mathcal{L}^{-1} \{ FG \} = f * g$, where $*$ is the convolution operator.
Proof
Suppose that $f(t)$ and $g(t)$ are two functions of exponential order.
Then
$$ \mathcal{L} \{ f(t) * g(t) \} = \int_0^\infty e^{-st} \int_0^t f(\tau) g(t - \tau) \ d\tau \ dt ,$$
by the definition of Laplace transform and convolution.
Rewriting of this double integral to facilitate changing the order of integration gives
$$\mathcal{L} \{ f(t) * g(t) \} = \int_0^\infty \int_0^t e^{-st} f(\tau)g(t - \tau) \ d \tau \ dt$$
And then integrating with respect to $t$ first gives
$$\mathcal{L} \{ f(t) * g(t) \} = \int_0^\infty \int_{\tau}^\infty e^{-st} f(\tau) g(t - \tau) \ dt \ d\tau = \int_0^\infty f(\tau) \left\{ \int_{\tau}^\infty e^{-st} g(t - \tau) \ dt \right\} \ d\tau$$
[...]

I'm wondering how/why the limits of integration on the second integral changes from $0$ and $t$ to $\tau$ and $\infty$?
I would greatly appreciate it if someone could please take the time to clarify this.

A: Sketching a graph for the region of integration is a big help.
Note that the region of integration for   $$ \int_0^\infty \int_0^t e^{-st} f(\tau)g(t - \tau) \ d \tau \ dt$$
is a triangular region below that line $\tau=t $ where t goes from $0$ to $\infty$ and $\tau $ goes from $0$ to $t$
When you change the order of integration on the same region, starting  with $\tau$, the region is on the right side of the line $t=\tau$ so you have $\tau$ going from $0$ to $\infty$ and $t$ goes from $\tau$ to $\infty$
Thus you have $$  \int_0^\infty \int_{\tau}^\infty e^{-st} f(\tau) g(t - \tau) \ dt \ d\tau  $$


text:
Q: How to use QAndroidJniObject to call a Intent from Java
*

*I want to use the rtl_tcp Driver for my App in Android to read Raw data from a usb Tv tuner.

*I found this source code https://github.com/martinmarinov/rtl_tcp_andro- and the guy has an App as driver at google play and anyone can call this App and can read raw data via tcp port.

*This is the App https://play.google.com/store/apps/details?id=marto.rtl_tcp_andro&hl=en
Now, i would like to call this drivers from my App, but i use QT. I found the classes QAndroidJNIObject to call java code.
I found also at github.com/demantz/RFAnalyzer/blob/master/app/src/main/java/com/mantz_it/rfanalyzer/MainActivity.java an example in java.
try {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setData(Uri.parse("iqsrc://-a 127.0.0.1 -p 1234 -n 1"));
    startActivityForResult(intent, RTL2832U_RESULT_CODE);
}
catch (ActivityNotFoundException e)
{
    Log.e(LOGTAG, "createSource: RTL2832U is not installed");
    ...
}

But i cannot find a way to write the right code in C++/Qt to make the equal call like the example in Java. I am not sure if this java code is correct or missing something.
Can someone help me ?
Also i want to ask if i can have a tcp connection with anet.h libs from Qt code?

A: You need to use QJniAndroidObject class to create JNI objects and manipulate them. It's not always obvious but it works in the end. Your 9-line of Java will most likely end up to be a 50-line C++ code. I recommend that you transcode each line one by one and always check objects are valid (QJniAndroidObject::isValid()).
Here is an example creating an Intent and starting an activity:
startActivity on Qt, nothing displays
Try to write some code and post another SO question if it fails (syntax to create and manipulate QJniAndroidObject is not always obvious for C++ developers not familiar with Java).


text:
Q: XSL producing HTML can not insert HTML fragments from XML What I want to achieve:
1 XSL file produces an HTML output based on XSLT.
Parts of the output HTML is stored in XML. So you need to read that part from an XML and insert it (merge) with the other content that XSL directly produces.
Example Code XSL:

This is a title

And this is the content coming from XML:

    <xsl:copy-of select="/*/xhtml:myelement" />

And the XML looks like this:
<?xml version="1.0" encoding="UTF-8"?>
  <z:article xmlns:ns0="http://www.w3.org/1999/xhtml">
  <ns0:myelement><p>here is some text with a special character &#776; and &#187; but actually any valid html can be stored like this in XML.</p><br/>
    <h2>an H2 title in the XML</h2>
    <p>and again some text</p>
  </ns0:myelement>
</z:article>

What I get as output is the HTML itself (as text), so it is still escaped and therefore not interpreted as HTML:
This is a title
And this is the content coming from XML:

here is some text with a special character ̈ and » but actually any valid html can be stored like this in XML.

an H2 title in the XML

and again some text

So my question is: HOW can I write the XSL code so that the text in the XML is copied as actual HTML and not as TEXT ?

A: Instead of:
<xsl:copy-of select="ns0:myelement" />

try:
<xsl:value-of select="ns0:myelement" disable-output-escaping="yes"/>


text:
Q: R - How to merge several rows into one by summing the values while keeping the columns intact I've been struggling on R for the last two days with a simple basic operation that would take 1 min to perform in Excel. Let me explain: I have a dataframe with 65 columns (variables, the species found) and 75 rows (obs, the quadrats). The first 25 rows are quadrats of site A, then the next 25 from site B then the last 25 from site C. Each column is a species and if the species X is present in Site A1, we have a 1 and if it's not there is a zero. I would like to study the diversity index of each site and not of each quadrat which is what specnumber() and diversity() will give me.
Here is an exemple of the dataframe with 5 quadrats from site A and 3 species:

Site
Quadrat
Sp X.
Sp Y.
Sp Z.

A
Quadrat A1
1
1
0

A
Quadrat A2
0
1
0

A
Quadrat A3
1
1
0

A
Quadrat A4
0
0
1

A
Quadrat A5
1
1
1

And here is what I would like to get:

Site
Sp X.
Sp Y.
Sp Z.

Site A
3
4
2

I have tried sumRows and sum of course, as well as rbind and dozens of other things found online but nothing seems to work, I am really new to R:
new <- rbind(df, L = sum(df[1:25,]) )
new <- rowSums(df[1:25,]
Thank you so much

A: Some example data.
df <- structure(list(Sites = c("Quadrat A1", "Quadrat A2", "Quadrat A3",
"Quadrat A4", "Quadrat A5"), `Sp X.` = c(0L, 1L, 1L, 0L, 1L),
    `Sp Y.` = c(0L, 1L, 1L, 0L, 1L), `Sp Z.` = c(0L, 0L, 0L,
    1L, 1L)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-5L))

Tidyverse solution. It should work with any number of sites.
library("dplyr")
library("stringr")

df |>
  mutate(Sites=str_glue("Site {x}", x=str_extract(Sites, "(?<=\\s)[[:alpha:]]+"))) |>
  group_by(Sites) |>
  summarize(across(where(is.numeric), sum), .groups="drop")

Result.
# A tibble: 1 × 4
  Sites  `Sp X.` `Sp Y.` `Sp Z.`
  <glue>   <int>   <int>   <int>
1 Site A       3       3       2

A: You might reformat your data by adding a column for Site. You can write code to pull out the "A" and "B" from Quadrant, but that is making it harder than it needs to be.
df <- data.frame("Site" = c("A", "A", "A", "B", "B", "C"), "SpecA" = c(1,0,1,1,1,0), "SpecB" = c(0,1,0,1,1,1))

Then do something like this:
siteA <- sum(df$SpecA[df$Site == "A"])

A: If You know how many rows each squares occupy, you can use colSums for these rows and make a data frame out of it.
For exapmle data:
       Sites Sp_x Sp_y Sp_z
1 Quadrat A1    1    1    0
2 Quadrat A2    0    1    0
3 Quadrat A3    1    1    0
4 Quadrat B1    0    0    1
5 Quadrat B2    1    1    1
6 Quadrat B3    1    1    0
7 Quadrat C1    1    1    0
8 Quadrat C2    0    0    1
9 Quadrat C3    0    0    0

Quadrat_A <- colSums(data[1:3,-1])
Quadrat_B <- colSums(data[4:6,-1])
Quadrat_C <- colSums(data[7:9,-1])

data_merged <- t(data.frame(Quadrat_A,Quadrat_B,Quadrat_C, stringsAsFactors=FALSE))

Output:
          Sp_x Sp_y Sp_z
Quadrat_A    2    3    0
Quadrat_B    2    2    2
Quadrat_C    1    1    1


text:
Q: There is natural surjective map from $U(\mathbb{Z}_n)$ to $U(\mathbb{Z}_m)$.
Let $m,n$ be positive integers where $m$ divides $n$. Then there is a natural map $$ \phi : U(\mathbb{Z}_n) \to U(\mathbb{Z}_m)$$ $$ [a]_n \mapsto [a]_m$$
for any integer $a$ with $\gcd(a,n) = 1$. Show that this map is surjective.

I do find the statements intuitive, I considered proving it along the lines of showing that $U(\mathbb{Z}_m)$ is either equal to or contained in $U(\mathbb{Z}_n)$.  Because $m=nq$ for some integer $q$, all numbers relative prime to $m$ is relatively prime to $n$. If my intuition is correct this map would necessarily be surjective?


text:
Q: How do I chain the cancellationToken for request from the browser to SQL Server via MVC and Web Api I have scenario where User is able to abort the jQuery Ajax call, subsequently I want to Cancel MVC Request then Web API request and lastly the SQL procedure execution.
How do I chain the cancellation of request from the browser to MVC Application. The MVC application will now trigger a Web API request which will query the database. we want to cancel any subsequent queries through the whole leg of the process if the requested response is not received.
I googled and found cancellation token of task can help me but I am unable to figure out how to make it work.
looking for example/suggestions on how to implement this.
so far I have tried using Task.Factory.StartNew but its not waiting for results.

  var tcs = new TaskCompletionSource<JsonResult>();

            //comment this whole this is just used for testing
             Task.Factory.StartNew(() =>
            {
                //Simulate work (usually from 3rd party code)
                for (int i = 0; i < 100000; i++)
                   Console.WriteLine("value" + i);

                //execution never comes here till above for loop or
                //may be long execution /computation get completed
                if (token.IsCancellationRequested)
                    token.ThrowIfCancellationRequested();

                //Console.WriteLine("Task finished!");
            }, token);
            tcs.SetResult(Json(ringSearch, JsonRequestBehavior.AllowGet));
            return tcs.Task;

A: TLDR;
Simply pass the token to all layers that may need it, and in each layer check whether IsCancellationIsRequested is true.
Long... requires some thought across sessions and requests...
On the request side, you need to have some sort of key. This key could be a GUID or some other unique, munged ID associated with the request. This is quite literally the key to everything that a particular user may do soon. This key (string) must map back to a CancellationTokenSource. It can be stored in HttpContext.Session or some other ephemeral store associated back to your user.
This means a few things.
Start the (possibly cancellable) Web API request (Db access or whatever) as an awaitable task, and, using this keyed task (This should run in the backgound), immediately return a DELETE HTTP or POST response with the cancelled task's info (it wasn't clear from your question whether the operation was a delete or a modify... I'm wording this as a delete, but the principle should be the same).
With this key, you've got it in the session state, and you can pass it on through any other layers of your solution. For example, you can

*

*delete or cancel the entity from the database

*remove it from the database

*trigger any other business rules.

This cancellation token can be propagated to any or all layers of your software solution (see: https://devblogs.microsoft.com/premier-developer/recommended-patterns-for-cancellationtoken/).
Cancellation is done, on demand, by the user or a system call; in your case that could be a simple button click. At that point, any calls on any threads that check for cancellation will cancel their operations (if you so code, and you should). Why/how? You literally pass this token through every layer as part of a constructor call or other method, and in every layer check to see if the operation is cancelled (cooperative) or skip the checks and handle OperationCancelledOperation.


text:
Q: Dispose vs Terminate vs Shutdown in ZContext I am confused to see following 3 similar methods available in Zeromq C# API.

*

*Dispose

*Terminate

*Shutdown

The above 3 methods looks similar by name. However I am not sure about their proper meaning.
Basically, in the provided examples such as Weather update server, the dispose functionality is done automatically by C# because of keyword using. However, in my code, I want to dispose the ZContext object manually.  See below the code snippet:
public partial class DataPublisherForm : Form
{
    private ZContext zmqContext;
    private ZSocket sensorDataPublisher;

    public DataPublisherForm()
    {
        mySensor = new Sensor();
        mySensor.DataArrived += OnDataArrived;
        zmqContext = new ZContext();
        sensorDataPublisher = new ZSocket(zmqContext, ZSocketType.PUB);
        sensorDataPublisher.SetOption(ZSocketOption.CONFLATE, 1);
        sensorDataPublisher.Bind("tcp://*:10000");
    }

    private void OnDataArrived(object sender, DataArrivedEventArgs e)
    {
        byte[] sensorData = e.getSenorData();
        sensorDataPublisher.Send(new ZFrame(sensorData));
    }

    private void DataPublisherForm_FormClosing(object sender, FormClosingEventArgs e)
    {
        zmqContext.Shutdown();
        if (sensorDataPublisher != null)
        {
            sensorDataPublisher.Close();
            sensorDataPublisher.Dispose();
        }
    }
}

Following are my observations:

*

*Dispose: When I use Dispose method, the application hangs (doesn't respond)

*Shutdown: When I use Shutdown method, the application closes smoothly.

Below are my queries:

*

*What is the proper way to dispose ZContext and ZSocket objects?

*What is the difference among Dispose, Terminate and Shutdown methods?

A: Short version:
Well, there are certain magics under the hood of the ZeroMQ zmqContext() instance, which may well turn things into havoc.
.Terminate() method is a mandatory API-call
.Shutdown() method wraps an optional-only API-call, with a must to call the mandatory API-call
.Dispose() method does GC.SuppressFinalize(this); first and calls .Terminate()

Best practices:
Be nice to resources. Better manage them explicitly and with a due care.
Be cautions on closing the things, that worked. Can hang the whole circus by not doing things right.
public partial class DataPublisherForm : Form
{
    private ZContext zmqContext;                 // a Context() class-instance
    private ZSocket sensorDataPublisher;         // a Socket()  class-instance
 // -------------------------------------------- // this.VERSION details
    private int     majorVerNUM,
                    minorVerNUM,
                    patchVerNUM;

    private string libzmqVerSTR;
 // -------------------------------------------- //
    public DataPublisherForm()                   // CONSTRUCTOR:
    {
        zmqContext = new ZContext();
        zmq.zmq_version( this.majorVerNUM,       // Ref. a trailer note:
                         this.minorVerNUM,
                         this.patchVerNUM
                         );
        this.libzmqVerSTR = string.Format( "libzmq DLL is version {0}",
                                            zmq.LibraryVersion()
                                            );

        mySensor = new Sensor();
        mySensor.DataArrived += OnDataArrived;

        sensorDataPublisher = new ZSocket(zmqContext, ZSocketType.PUB);
        sensorDataPublisher.SetOption(ZSocketOption.CONFLATE, 1);
        sensorDataPublisher.Bind("tcp://*:10000");
    }

    private void OnDataArrived(object sender, DataArrivedEventArgs e)
    {
        byte[] sensorData = e.getSenorData();
        sensorDataPublisher.Send(new ZFrame(sensorData));
    }

    private void DataPublisherForm_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (sensorDataPublisher != null)
        {   sensorDataPublisher.SetOption( ZSocketOption.LINGER, 0 );
            sensorDataPublisher.Close();
            sensorDataPublisher.Dispose();
        }
     // -------------------------<NEVER BEFORE SAFE DISMANTLING ALL SOCKETS>---
        zmqContext.Shutdown();                   // optional  API-call
        zmqContext.Terminate();                  // mandatory API-call
    }
 // -------------------------------------------- // VERSION CONTROL METHODS
    public  string  getDllVersionSTRING()        // a DLL version
    {   return this.libzmqVerSTR;
    }

    public  int getVersionMAJOR()                // a version() responder
    {
        return this.majorVerNUM;
    }

    public  int getVersionMINOR()                // a version() responder
    {
        return this.minorVerNUM;
    }

    public  int getVersionPATCH()                // a version() responder
    {
        return this.patchVerNUM;
    }

}

A few version-control methods were just sketched in principle, not finalised in detail, the less tested. The rationale for using a similar concept is in the fact that one cannot ensure ( enforce ) a realistic, distributed ecosystem, where only homogeneous API-versions are granted.
Thus in many operational cases, the API-versions need not match and ZeroMQ has ( besides its own version evolution ) different behaviour requirements ( performance-wise, memory-wise, {local|non-local}-processing-wise ) and having methods to locally detect which API-version or DLL-version is actually used / linked against, is worth having them ( debugging report being the Case#1, not to mention other, API-specific decisions taken on-the-fly ).
An ability to ask a class-method to answer these actual version details could literally save one's hair in troubles during a bug-hunt or after a new version release there comes a review of all related engineering changes and tracking new decision points introduced by all the new features / changed modus operandi.


text:
Q: php query string header Hello I have a problem with header('Location: http://www.example2.com/'); while there is a query string.
Ok I will make the question easy to understand:
now I have a domain name http://example1.com/?url=url I want when someone want to access example1.com it redirects him to example2.com but if he types example1.com/?url=url nothing will happen so how can I do that please and thanks in advance

A: What do you use for redirecting? From your post's first line I assume, that you're redirecting the user via the PHP header function. So, check in PHP whether there is a query string or not:
<?php
if (empty($_SERVER["QUERY_STRING"]))
{
    header("Location:  http://www.example2.com/");
}
?>

A: I assume you have index.php in root directory of domain example1.com. And you can use this;
<?php

if (empty($_GET["url"])) {
    header("Location:  http://www.example2.com/");
}


text:
Q: Ionic 1 - npm install error - unknown revision in working tree I get the following error for installing npm packages.
D:\Mobile Project>npm install
npm WARN deprecated gulp-minify-css@0.3.13: Please use gulp-clean-css
npm WARN deprecated cordova-plugin-console@1.1.0: This plugin has been
deprecated since it is now included in the latest versions of cordova-ios
npm ERR! git rev-list -n1 master: fatal: ambiguous argument 'master':
unknown revision or path not in the working tree.
npm ERR! git rev-list -n1 master: Use '--' to separate paths from revisions,
like this:
npm ERR! git rev-list -n1 master: 'git <command> [<revision>...] --
[<file>...]'
npm ERR! git rev-list -n1 master:
npm ERR! Windows_NT 6.3.9600
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe"
"C:\\Users\\naveenkumar\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-
 cli.js" "install"
npm ERR! node v6.10.3
npm ERR! npm  v4.1.1
npm ERR! code 128

npm ERR! Command failed: git -c core.longpaths=true rev-list -n1 master
npm ERR! fatal: ambiguous argument 'master': unknown revision or path not in
the working tree.
npm ERR! Use '--' to separate paths from revisions, like this:
npm ERR! 'git <command> [<revision>...] -- [<file>...]'
npm ERR!
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>

npm ERR! Please include the following file with any support request:
npm ERR!     D:\Mobile Project\npm-debug.log

Packages.json dependencies:
"dependencies": {
    "cordova-plugin-compat": "^1.2.0",
    "cordova-plugin-console": "^1.1.0",
    "cordova-plugin-device": "^1.1.7",
    "cordova-plugin-file": "^4.3.3",
    "cordova-plugin-ionic-webview": "^1.1.16",
    "cordova-plugin-ios-disableshaketoedit": "^1.0.0",
    "cordova-plugin-network-information": "^1.3.4",
    "cordova-plugin-splashscreen": "^4.1.0",
    "cordova-plugin-statusbar": "^2.3.0",
    "cordova-plugin-vibration": "^2.1.6",
    "cordova-plugin-whitelist": "^1.3.3",
    "cordova-plugin-wkwebview-engine": "^1.1.4",
    "cordova-plugin-x-toast": "git+https://github.com/EddyVerbruggen/Toast-PhoneGap-Plugin.git",
    "cordova-sqlite-storage": "https://github.com/litehelpers/Cordova-sqlite-storage.git",
    "cordova-uglify": "^0.2.9",
    "gulp": "^3.5.6",
    "gulp-concat": "^2.2.0",
    "gulp-minify-css": "^0.3.0",
    "gulp-rename": "^1.2.0",
    "gulp-sass": "^2.0.4",
    "ionic-plugin-keyboard": "^2.2.1",
    "onesignal-cordova-plugin": "^2.2.2",
    "phonegap-plugin-barcodescanner": "git+https://github.com/phonegap/phonegap-plugin-barcodescanner.git"
},

A: Changing the version for the following dependencies as suggested by VS code intellisense solved it. Hope it might help others. :)
"dependencies": {
  ....
  "cordova-plugin-x-toast":"^2.6.0",
  "cordova-sqlite-storage":"^2.1.2",
  "phonegap-plugin-barcodescanner":"^7.0.0",
  ....
}

Thanks to those who tried to solve my issue.


text:
Q: Reflection.Emit: property with function call in getter/setter I am trying to use Reflection.Emit to create a dynamic type which inherits from a given type, and adds a new property whose getter/setter call methods of the base type.
Suppose my base type looks as follows:
class Test
{
    private int _val1;

    public int GetVal(int fld)
    {
        if (fld == 1) return _val1;
        return 0;
    }

    public void SetVal(int fld, int val)
    {
        if (fld == 1) _val1 = val;
    }
}

I want to create a subtype which has a new property, defined as follows:
public int NewProp { get { return GetVal(1); } set { SetVal(1, value); } }

Seems simple enough.
I came up with the following (which is the working answer):
PropertyBuilder pbNewProp = tb.DefineProperty("NewProp", PropertyAttributes.HasDefault, typeof(int), null);
MethodAttributes getSetAttr = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig;

// Define the "get" accessor method
MethodBuilder mbNewPropGetAccessor = tb.DefineMethod(
    "get_NewProp",
    getSetAttr,
    typeof(int),
    Type.EmptyTypes);

ILGenerator NewPropGetIL = mbNewPropGetAccessor.GetILGenerator();
NewPropGetIL.Emit(OpCodes.Ldarg_0);
NewPropGetIL.Emit(OpCodes.Ldc_I4_1);
NewPropGetIL.Emit(OpCodes.Call, typeof(Test).GetMethod("GetVal"));
NewPropGetIL.Emit(OpCodes.Ret);

// Define the "set" accessor method
MethodBuilder mbNewPropSetAccessor = tb.DefineMethod(
    "set_NewProp",
    getSetAttr,
    null,
    new Type[] { typeof(int) });

ILGenerator NewPropSetIL = mbNewPropSetAccessor.GetILGenerator();
NewPropSetIL.Emit(OpCodes.Ldarg_0);
NewPropSetIL.Emit(OpCodes.Ldc_I4_1);
NewPropSetIL.Emit(OpCodes.Ldarg_1);
NewPropSetIL.Emit(OpCodes.Call, typeof(Test).GetMethod("SetVal"));
NewPropSetIL.Emit(OpCodes.Ret);

// Map the accessor methods
pbNewProp.SetGetMethod(mbNewPropGetAccessor);
pbNewProp.SetSetMethod(mbNewPropSetAccessor);

I did compare this to the compiler generated IL (using ildasm) based on a hardcoded sample and can't spot a difference.
Here is what I did to test whether above code would work:
var inst = Activator.CreateInstance(myType);

var p = inst.GetType().GetProperty("NewProp");
p.GetValue(inst, null);
p.SetValue(inst, 1, null);

For reference, here is what ildasm says about "set_NewProp":
.method public hidebysig specialname instance void
    set_NewProp(int32 'value') cil managed
{
    // Code size       9 (0x9)
        .maxstack  8
        IL_0000:  ldarg.0
        IL_0001:  ldc.i4.1
        IL_0002:  ldarg.1
        IL_0003:  call       instance void ConsoleApplication2.Test::SetVal(int32, int32)
        IL_0008:  ret
    } // end of method TestSub::set_NewProp

And here "get_NewProp":
.method public hidebysig specialname instance int32
    get_NewProp() cil managed
    {
        // Code size       8 (0x8)
        .maxstack  8
        IL_0000:  ldarg.0
        IL_0001:  ldc.i4.1
        IL_0002:  call       instance int32 ConsoleApplication2.Test::GetVal(int32)
        IL_0007:  ret
    } // end of method TestSub::get_NewProp

In the original version of the question, the call to GetValue threw a TargetInvocationException, whose InnerException was an InvalidProgramException that says "Common Language Runtime detected an invalid program."  It was due to a typo (since corrected); d'oh!

A: You'll kick yourself:
NewPropSetIL.Emit(OpCodes.Ldarg_1);
NewPropGetIL.Emit(OpCodes.Callvirt, typeof(Test).GetMethod("SetVal"));
NewPropSetIL.Emit(OpCodes.Ret);

Look closely. Closer. Closer. Still not there?

 Line 2 talks to NewPropGetIL

If that still doesn't work, make sure that you declared the base-type in the TypeBuilder, and that the class Test is public, and not internal as shown in the question. It works fine for me now.
How I investigated it
I started by adding the following preamble:
AssemblyName aName = new AssemblyName("SomeAssembly");
AssemblyBuilder ab =
    AppDomain.CurrentDomain.DefineDynamicAssembly(
        aName,
        AssemblyBuilderAccess.RunAndSave);

// For a single-module assembly, the module name is usually
// the assembly name plus an extension.
ModuleBuilder mb =
    ab.DefineDynamicModule(aName.Name, aName.Name + ".dll");

TypeBuilder tb = mb.DefineType(
    "SomeType",
     TypeAttributes.Public, typeof(Test));

and the following foot:
RunTest(typeof(ManualTest));
RunTest(tb.CreateType());

where:
private static void RunTest(Type type)
{
    Console.WriteLine(type.Name);
    Console.WriteLine();
    dynamic obj = Activator.CreateInstance(type);

    int i = obj.NewProp;
    Console.WriteLine(i);
    obj.NewProp = 123;
    i = obj.NewProp;
    Console.WriteLine(i);

    Console.WriteLine();
}

I also added some logging to the base methods:
public class Test
{
    private int _val1;

    public int GetVal(int fld)
    {
        Console.WriteLine("GetVal:" + fld);
        if (fld == 1) return _val1;
        return 0;
    }

    public void SetVal(int fld, int val)
    {
        Console.WriteLine("SetVal:" + fld);
        if (fld == 1) _val1 = val;
    }
}

and a manual test for comparison (the expected result):
class ManualTest : Test
{
    public int NewProp { get { return GetVal(1); } set { SetVal(1, value); } }
}

With this in place, it was clear that there is a problem in the set:
ManualTest

GetVal:1
0
SetVal:1
GetVal:1
123

SomeType

GetVal:1
0
GetVal:1
0


text:
Q: SQL query in Doctrine2 I really need help here, does anyone know how to transform this SQL query into a Doctrine2 query using the createQueryBuilder?

SELECT a.resposta,
(
    SELECT count(r.id)
    FROM car_resultado r2
    LEFT JOIN car_resultado_inquerito ri2 ON r2.id_resultado_inquerito = ri2.id
    WHERE ri2.id_inquerito = 20 AND r2.id_resposta = a.id
    GROUP BY r2.id_pergunta, r2.id_resposta
) as total
FROM car_resposta a
LEFT JOIN car_resultado r ON ( r.id_resposta = a.id )
GROUP BY a.id, r.id_resposta

I have no idea how to do it, mainly because that nested SELECT

A: Normally you have to create your Entities and Repositories to get the data from your database. But in Doctrine2 is a uncool way. You can execute native SQL.
Doctrine2 Native SQL
If its possible you shouldn't do it and work with the classes but if you have a complicated existing queries you can do it.


text:
Q: How do we access popup in android appium I'm unable to find in app popups in uiautomator, is there a way to find out xpath for pop-ups in android?
I have tried using uiautomaotor for different versions of android os (4.4 to 7)

A: popup are not part of your layout and hence you cant see it in your view hierarchy. so can't use Xpath.


text:
Q: How to make Magento2 development environment fast? I was trying to make changes on frontend but the site load very slow Whenever I disabled the cache. Please help, How could i make it faster like in 2-3 sec?
I even trying to setup docker environment with Magento2. But still very slow whenever i clear cache. I refer to this article setup https://www.magemodule.com/all-things-magento/magento-2-tutorials/docker-magento-2-development/
My laptop Spec are
1) window 10 Home
2) i7 , 8Gb Ram
3) SSD


text:
Q: jsp не отображаются картинки dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        ">
 <!-- sets you your Spring context to allow for dispatching requests to Controllers. -->
<mvc:annotation-driven />
<context:component-scan base-package="by.onlinelibrary" />
<mvc:resources mapping="/resources/**" location="/resources/" />

<!--Internalization -->
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/resources/msg/messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>

<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang" />
</bean>
</mvc:interceptors>

<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="en" />
</bean>
 <context:component-scan base-package="by.onlinelibrary.controllers"/>
 <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

index.jsp
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>

        <img src="/resources/images/en.jpg"/>
      <%--<jsp:forward page="/val/reg"/>--%>
    </body>
</html>

не отображает картинку. Прошу помочь и объяснить что к чему.


text:
Q: Can't retrieve new value from GridView template field I am having trouble retrieving the new value that is entered in a textbox template field in my GridView.
Here is my markup:
<asp:TemplateField HeaderText="username" SortExpression="username">
    <ItemTemplate>
        <asp:Label ID="Label2" runat="server" Text='<%# Bind("username") %>'></asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
        <asp:TextBox ID="txtUserName" runat="server" Text='<%# Bind("username") %>'></asp:TextBox>
    </EditItemTemplate>
</asp:TemplateField>

And here is how I'm trying to retrieve the new value, inside the RowCommand event handler of my GridView:
 string userName = ((TextBox)grdUserList.Rows[rowIndex].FindControl("txtUserName")).Text;

I get the old value instead of the newly typed value when I execute this code.
Does anyone know what I am missing? Thanks in advance.

A: I just found out the solution for my problem. I searched and found out that the GridView is being refreshed before the retrieving process begins because I was rebinding the GridView on the Page_Load method. I fixed the problem by not rebinding the gridview when it is a post back (or at least not before I have made the changes) using the IsPostback method. Thanks for everyone's reply :)

A: You are retrieving new value in wrong GridView event. You have to add OnRowUpdating="grdUserList_RowUpdating" event in your GridView control and then retrieve new TextBox value.
OnRowUpdating event in code-behind:
protected void grdUserList_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    string userName = ((TextBox)grdUserList.Rows[e.RowIndex].FindControl("txtUserName")).Text;

    // Write your update query and logic over here.
}

You can take a reference from here for additional knowledge.
Please let me know if you have any questions.

A: use this code in gridview

  <Columns>

    <asp:TemplateField HeaderText="SrNo">
    <EditItemTemplate>

    <asp:TextBox ID="txtsrno" runat="server" Text='<%#Eval("SrNo") %>'>
    </asp:TextBox>
    </EditItemTemplate>

    <ItemTemplate>
  <asp:Label ID="lblsrno" runat="server" Text='<%#Eval("SrNo") %>'>
    </asp:Label>

    </ItemTemplate>
    </asp:TemplateField>
  </Columns>


text:
Q: NSTextView freezing my app when adding a lot of data asyncronously I'm building a simple talker/listener app that receives OSC data through UDP.  I'm using OSCKit pod which itself uses CocoaAsyncSocket library for the internal UDP communication.

When I'm listening to a particular port to receive data from another OSC capable software, I log the received commands to a NSTextView.  The problem is that sometimes, I receive thousands of messages in a very short period of time (EDIT: I just added a counter to see how many messages I'm receiving.  I got over 14000 in just a few seconds and that is only a single moving object in my software).  There is no way to predict when this is gonna happen so I cannot lock the textStorage object of the NSTextView to keep it from sending all its notifications to update the UI.  The data is processed through a delegate callback function.

So how would you go around that limitation?
   ///Handle incoming OSC messages
   func handle(_ message: OSCMessage!) {

      print("OSC Message: \(message)")

      let targetPath = message.address
      let args = message.arguments

      let msgAsString = "Path: \"\(targetPath)\"\nArguments: \n\(args)\n\n"
      print(msgAsString)
      oscLogView.string?.append(msgAsString)
      oscLogView.scrollToEndOfDocument(self)
   }

As you can see here (this is the callback function) I'm updating the TextView directly from the callback (both adding data and scrolling to the end), every time a message is received.  This is where Instruments tell me the slow down happens and the append is the slowest one.  I didn't go further than that in the analysis, but it certainly is due to the fact that it tries to do a visual update, which takes a lot more time than parsing 32bits of data, and when it's finished it receives another update right away from the server's buffer.
Could I send that call to the background thread?  I don't feel like filling up the background thread with visual updates is such a great idea.  Maybe growing my own string buffer and flushing it to the TextView every now and then with a timer?
I want to give this a console feel, but a console that freezes is not a console.
Here is a link to the project on github.  the pods are all there and configured with cocoapods, so just open the workspace.  You guys might not have anything to generate that much OSC traffic, but if you really feel like digging in, you can get IanniX, which is an open-source sequencer/trajectory automator that can generate OSC and a lot of it.  I've just downloaded it and I'll build a quick project that should send enough data to freeze the app and I'll add it to the repo if anybody want to give it a shot.

A: I append the incoming data to a buffer variable and I use a timer that flushes that buffer to the textview every 0.2 seconds.  The update cycle of the textview is way too slow to handle the amount of incoming data so unloding the network callback to a timer let the server process the data instead of being stopped every 32bits.
If anybody come up with a more elegant method, I'm open minded.


text:
Q: How can I ovveride tabs css styles in component.css by using customClass? I use ngx-bootstrap/tabsfor tabs.
Here is my HTML-Template:
<tabset [justified]="true">
  <tab heading="About" customClass="about-tab">
    <app-about></app-about>
  </tab>
  <tab heading="Projects" customClass="projects-tab">
    <app-projects></app-projects>
  </tab>
</tabset>

With my custom css classes I would override default tab styling. In my component.css I defined css rules, like this:
.about-tab {
  background-color: #c7c7c7;
  // more rules
}

.projects-tab {
  background-color: #e5e5e5;
  // more rules
}

But this doesn't work for me. Then I move my css rules in main styles.css of my angular app and it works, but this solution is not good for me, because I have one more component which also contain tabs.
Why it doesn't work from components.css? How can I bring to work my custom css styles from my component.css?

A: /deep/, >>>, and ::ng-deep selectors will be deprecated in Angular at some point so I wouldn't rely on those. The only way I am aware is to set component viewEncapsulation to none, but be sure to wrap the styles to your component specifically so they won't leak since styles are added to global css scope.
import { Component, ViewEncapsulation } from '@angular/core';

@Component({
    selector: 'app-component',
    templateUrl: './app-component.component.html',
    styleUrls: ['./app-component.component.scss'],
    encapsulation: ViewEncapsulation.None,
})

A: use :host /deep/  in your component.css
:host /deep/ .about-tab {
  background-color: #c7c7c7;
  // more rules
}

:host /deep/ .projects-tab {
  background-color: #e5e5e5;
  // more rules
}


text:
Q: Account created inside another account Somehow in my friend's computer, someone managed to create an account inside another account. Ever since that happened, she hasn't been able to save documents or any kind of files for that matter inside her computer because it always tells her "File or directory damaged or illegible"
To give you an idea, there are two ways to access the very same folder:
C:\Users\Gilda\Desktop\fotos

and
C:\Users\Gilda\Desktop\Victoria Valdivia\Desktop\fotos

However, when you click the address bar on either, they both say: C:\Users\Gilda\Desktop\fotos
I really don't know what to do, and I can't find the answer anywhere else. I don't know if you can imagine what the problem is, but any help is appreciated.

A: Navigate to Accounts (in settings) select Family and other users.You should see Victoria Valdivia's account there.Just select her account and Remove.


text:
Q: Apache reverse proxy to google.com (just for testing) I am trying to create a reverse proxy (just as a test) which maps https://www.google.com to https://myserver.net/google
This is what I did in my conf:
SSLProxyEngine On
ProxyPass "/google" "https://www.google.com"
ProxyPassReverse "/google" "https://www.google.com"

Doing this lets me visit myserver.net/google but images don't load and similarly if I type in a search query, it maps the url to myserver.net/search which obviously doesn't work
How do I fix this?

A: Problem solved - it needs to be done for every sub-url as well
So
SSLProxyEngine On
ProxyPass "/google" "https://www.google.com"
ProxyPass "/search" "https://www.google.com/search"
ProxyPass "/images" "https://www.google.com/images"


text:
Q: how to format json dumps I got json dumps like this:
"aaa": {
    "bbb": {
        "ccc": {
            "ddd": "string1",
            "eee": "string2"
        }
    },
    "kkk": "string3"
}

And I'd like to format it this way: enclose every key-value pair (separated by :) with {} and then replace : with ,.
I know that I can use re.sub() to replace string patterns, but regular expression does not work with overlapping patterns, so I can match, for example, "ddd": "string1" but not "ccc": {...} at the same time.
For the above json string, I'd like to get:
{"aaa", {
    {"bbb", {
        {"ccc", {
            {"ddd", "string1"},
            {"eee", "string2"}
        }}
    }},
    {"kkk", "string3"}
}}

A: Here's a hack which converts everything to lists and then changes square brackets to curly ones. If your strings might contain square brackets that'll be a problem.
import json

inp = """
{
    "aaa": {
        "bbb": {
            "ccc": {
                "ddd": "string1",
                "eee": "string2"
            }
        },
        "kkk": "string3"
    }
}
"""

inp = json.loads(inp)

def items(d):
    if isinstance(d, dict):
        return [(k, items(v)) for k, v in d.items()]
    return d

inp = items(inp)

print(json.dumps(inp, indent=2).replace("[", "{").replace("]", "}"))

Output:
{
  {
    "aaa",
    {
      {
        "bbb",
        {
          {
            "ccc",
            {
              {
                "ddd",
                "string1"
              },
              {
                "eee",
                "string2"
              }
            }
          }
        }
      },
      {
        "kkk",
        "string3"
      }
    }
  }
}

A: Note that you are treating dictionary keys as ordered when they aren't, so I made it more explicit with lists.
If it were me, I wouldn't dump to JSON in the first place, I'd serialize the native python data structure straight to C++ initializer list syntax:
myobj = {
  "aaa": [
    { "bbb": {
        "ccc": [
            {"ddd": "string1"},
            {"eee": "string2"}
        ]
    }},
    { "kkk": "string3" }
  ]
}

def pyToCpp(value, key=None):
  if key:
    return '{{ "{}", {} }}'.format(key, pyToCpp(value))
  if type(value) == dict:
    for k, v in value.items():
      return pyToCpp(v, k)
  elif type(value) == list:
    l = [pyToCpp(v) for v in value]
    return '{{ {} }}'.format(", ".join(l))
  else:
    return '"{}"'.format(value)

y = pyToCpp(myobj)
print(y)

Output:
{ "aaa", { { "bbb", { "ccc", { { "ddd", "string1" }, { "eee", "string2" } } } }, { "kkk", "string3" } } }

Run it here: https://repl.it/repls/OddFrontUsers


text:
Q: getting an error since 1.8.2 update I'm getting an error when trying to index with search API since I upgraded to 1.8.2 dev server... Here's Traceback with relevant data:
search.Index( 'something' ).put( self.document() )

File "C:\Dev\GAE\google\appengine\api\search\search.py", line 2485, in put
  response)

File "C:\Dev\GAE\google\appengine\api\apiproxy_stub_map.py", line 94, in MakeSyncCall
  return stubmap.MakeSyncCall(service, call, request, response)

File "C:\Dev\GAE\google\appengine\api\apiproxy_stub_map.py", line 328, in MakeSyncCall
  rpc.CheckSuccess()

File "C:\Dev\GAE\google\appengine\api\apiproxy_rpc.py", line 156, in _WaitImpl
  self.request, self.response)

File "C:\Dev\GAE\google\appengine\ext\remote_api\remote_api_stub.py", line 200, in MakeSyncCall
  self._MakeRealSyncCall(service, call, request, response)

File "C:\Dev\GAE\google\appengine\ext\remote_api\remote_api_stub.py", line 234, in _MakeRealSyncCall
  raise pickle.loads(response_pb.exception())

AttributeError: 'dict' object has no attribute 'AddFieldType'

Anyone knows why is this happening? Worked on 1.8.1...

A: remove your search index and reindex your entities.
that solved it for me.


text:
Q: Schedule task when USB device (Keyboard) is unplugged and plugged in So I would like to schedule a task to run a specific command when a certain hardware (usb) device is unplugged, then another command when it is plugged in.
The commands:
#Unplug
nircmd monitor off
#Plug in
nircmd monitor on

I want this to use as little resources as possible (to keep scripting to a minimum, e.g. I'd like to avoid setting up a constantly running background script, task scheduler by itself should be able to do this job), I'd also like to avoid installing 3rd party software if it can be avoided.
Just about all the information I was able to gather is that there is a logfile C:\Windows\inf\setupapi.dev.log which logs all "Device install messages" (Plugged in) but it does not seem to track unplugs.
According to this file the device ID in question is USB\VID_1B1C&PID_1B11 (can confirm that on linux the device ID is also 1B1C:1B11, that's how I knew which device I was looking for in the first place, god bless lsusb right?)
This gives me that in task scheduler I should probably be able to set up a "plug-in" task based around the setup api, but since I'm actually not familiar with the task scheduler I don't know how (and more specifically, don't know what "Event ID" I would use)
Where will I find device disconnect events? And how do I make task viewer execute my desired commands for each event?


text:
Q: Convert 2D coordinates from NAD83 to WGS84 using Postgis I have a set of NAD83 coordinates that I need to convert to WGS84 coordinates. I am using postgis on an RDS. Specs for the box I am using from postgis_full_version():
POSTGIS="2.1.3 r12547" GEOS="3.4.2-CAPI-1.8.2 r3921" PROJ="Rel. 4.8.0, 6 March 2012" GDAL="GDAL 1.10.1, released 2013/08/26" LIBXML="2.9.1" LIBJSON="UNKNOWN" TOPOLOGY RASTER

I have tried a number of queries using built in functions. My latest iteration:
select st_asText(st_transform(st_setsrid(st_makepoint(-77.0282705292858, 38.9170880930097), 4269), 4326));

Result:
                 st_astext
-------------------------------------------
 POINT(-77.0282705292858 38.9170880930097)
(1 row)

The exact same coordinates. I have tried this with other addresses in DC (this one is for Ben's Chili Bowl) and other addresses in other states, but have always received back the exact same coordinates that were initially entered.
I would have assumed that the coordinates should be the same, but when using the online tool provided by WV (http://tagis.dep.wv.gov/convert/index.html) that uses ArcGIS on the backend, the coordinate conversion returns different results.
My assumption is that I'm missing something obvious with the query which is causing results to repeat themselves or am misunderstanding how this conversion is supposed to work.

A: With @mkennedy's suggestion, I looked into the conversion information available within Postgis' spatial_ref_sys. The code is available in their subversion repo at http://svn.osgeo.org/postgis/trunk/spatial_ref_sys.sql
The conversion statement was:
TOWGS84[0,0,0,0,0,0,0]

So the result of the conversion calculation was the same NAD83 values that had be entered.


text:
Q: jquery prevent the onclick event of a tags with specified class name this is the code I have:
    $('a').on('click', function(e) {
    e.preventDefault();
    });

but this stops every link from working, I need it to be specific to the link that have a class of the name : "prevent"
for example :
in this case I want #link1 to work normally and #link will trigger e.preventDefault();
any ideas please? thank you

A: You can select the anchors based on their class names:
$('a.prevent').on('click', function(e) {
     e.preventDefault();
});

A:  $('a.prevent').on('click', function(e) {
e.preventDefault();
});

You should read: http://api.jquery.com/category/selectors/


text:
Q: SQL Parameters and Question Marks I am making the switch from classic ASP to ASP.NET. And I am having some trouble doing some basic stuff that I used to do easily with the old method. Below is a handy ASP function that I used to execute scalar queries with a few lines.
FUNCTION ExecuteScalarParams(SQLQuery, Parameter_Array)
Set cmd1 = Server.CreateObject("ADODB.Command")
cmd1.ActiveConnection = con
cmd1.CommandText = SQLQuery
cmd1.CommandType = 1

FOR ParamCount = 0 TO UBOUND(Parameter_Array)
    cmd1.Parameters(ParamCount) = Parameter_Array(ParamCount)
NEXT 'ParamCount

Set rstScalar = cmd1.Execute()

IF NOT rstScalar.EOF THEN
    arrScalar = rstScalar.GetRows()
    IF UBOUND(arrScalar,2) = 0 THEN
        ExecuteScalarParams = arrScalar(0,0)
    ELSE
        ExecuteScalarParams = NULL
    END IF
ELSE
    ExecuteScalarParams = NULL
END IF

rstScalar.Close
Set rstScalar = Nothing
Set cmd1 = Nothing
END FUNCTION

I used to pass a SQL query with question marks as place holders for the parameters like this:
SELECT TOP 1 UserName FROM Members WHERE (Created>?) AND (AdminLevel=?);

I would then set up a parameters array and pass it on to the function:
MyArray = ARRAY("1-JAN-2012",1)

The parameters in the array would replace the question marks in the query string in the order they appear.
I am trying to mimic this function in C# but I am stuck in the part where I have to pass the parameters. So far I got to the point where I have to used named place holders such as @Created and @AdminLevel instead of the question marks and then I have to set up parameter objects like this:
SqlParameter param = new SqlParameter();
param.ParameterName = "@AdminLevel";
param.Value = 1;

Is there a way to pass the parameters without having to set the parameter names and simply use question marks and the order in which they appear to specify which parameter goes where?

A: edit: as pointed out by Dana the MSDN Docs for Parameters shows you need to use named parameters for SqlClient but can use positional parameters for OleDb/ODBC.
You can make adding parameters a lot easier by using the code below; it's the skeleton I use but I'm sure there's a better way of doing it.
You still need to used named parameters, but you can simulate your question marks to an extent by naming them @a, @b, @c.. - positional parameters are fine until you get more than a handful of parameters and you have to constantly count the number of question marks to figure out which parameter value is being applied where, often resulting in mistakes.
using (var con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
    con.Open();
    {
        using (var command = con.CreateCommand())
        {
            command.Connection = conn;
            command.CommandText = "SELECT * FROM [dbo].[Table] WHERE [c1] = @a AND [c2] = @b";
            command.Parameters.AddWithValue("@a", aVal);
            command.Parameters.AddWithValue("@b", bVal);
            command.CommandType = CommandType.Text;

            using (var reader = command.ExecuteReader())
            {
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        ///
                    }
                }
                else
                {
                    ///
                }
            }
        }
    }
}


text:
Q: Strategy for package searching I am using 11.10 the amd64 version (I assume, but I don't know how to figure that out). Now when I add a section to /etc/apt/source.list.d/foo.list:
deb http://<myserver>/download/public stable main

and put my package in
http://<myserver>/download/public/dists/stable/main/binary-amd64/

I get an error:
Err http://<myserver> stable/main i386 Packages
   404  Not Found

Now the question is: do I have to provide a Packages(.gz) in the binary-i386 subdirectory even if it is empty? This is not a i386 package and I don't request one on the command line. Does Ubuntu require both architectures to be available?

A: You need the Packages.gz file to make it a proper repository. If it is empty, just wait adding it to sources.list until you have finished setting it up.
See http://mediakey.dk/~cc/howto-create-your-own-debian-or-ubuntu-package-repository/ for detailed instructions, including generating Packages.gz
To verify your architecture, run uname -m in a terminal. If it is a 64-bit machine, it should report x86_64.


text:
Q: how to sort an array which is mostly sorted i have an array like this:
1,2,3,5,6,4
it is 99% sorted and has 40K elements.
i can put them in an array, list, linked list, ...
but i don`t know the fastest way to sort them!

A: "They laughed when I sat down at the keyboard and coded a bubblesort..."
But seriously: Bubblesort is close but not quite. Bubblesort repeatedly moves in one direction, so if there's a low-key value near the top end of the array it and the comparison site "bubbles" upward all the time, it takes many iterations of the main loop for the data item to bubble down against the current. That's pretty much worst case behavior, which for Bubblesort is disastrous.
But there's a refinement to BubbleSort, sometimes called ElevatorCocktail Sort, where the bubble moves in alternating directions: One pass up, one pass down, repeat. This permits single elements to move a long distance in a single pass (or actually, 2 passes), and the number of passes is proportional to the number of elements that need moving. For a small number of unsorted elements, this can approach efficiency.

I believe that for the general case, the second link in marek's answer will be faster. The advantage of Bubble/ElevatorCocktail sort is that it's so simple, it's virtually foolproof, and not a lot of work.

A: If it's already ordered to such a high degree, and the not-quite-sorted elements are not far from their correct positions, then this may be one of the few cases that bubblesort is useful.

A: The following site has a comparison between common sorting algorithms - it seems that insertion sort wins when the collection is nearly sorted.

A: Google gives a lot of results for this, e.g. this one with an overview of various methods how to accomplish that: http://home.tiac.net/~cri/2004/ksort.html

A: Put them in an array. You don't want to mess with a 40k linked-list.
There is a very narrow case for CocktailSort (bubblesort in 2 directions). But that depends on what exactly that 1% unsorted means. If there are a few elements displaced, but close to their target positions it might work.
But InsertionSort or ShellSort are almost always going to win. Even in the cases where CocktailSort would theoretically be better, the difference will be small. So they are the (much) safer bet.

A: As with most questions of this sort, the answer is "That depends...".  Do you care if the sort is stable, i.e. if elements whose keys are equal retain their original relative ordering after being sorted?  Do you just care about raw speed?  Is simplicity of implementation important?  Does memory consumption matter?
Personally, I will always choose a stable sort algorithm, as I'm willing to sacrifice some raw speed for what I consider to be "reasonable" behavior, and non-stable sorting is too often "unreasonable".  So I tend to go with the merge-sort algorithm, which is fast and reasonably simple, but it does use extra memory.  Another advantage of merge-sort is that if the data is already sorted its complexity is O(n), so for nearly-sorted data it should be close to O(n).
YMMV.

A: Is performance critical (as verified by a profiler)? Otherwise, just use your framework/langauge's default sort (probably quicksort). It will perform decently.


text:
Q: Regular values and maps of degree 0 There is an elementary phenomenon in differential topology, that I've never quite understood: It is well known that the mapping degree (Brouwer degree) $\operatorname{deg}(f) = \operatorname{deg}(f;y)$, $y \in N$, of a smooth map $f \colon M^n \to N^n$ ($M$ closed, $N$ connected) does not depend on the regular value $y$ used to compute it. So if $f$ is not surjective, one may simply pick a point $y \in N \backslash f(M)$ to conclude that $\operatorname{deg}(f) = \operatorname{deg}(f;y) = \sum_{x \in f^{-1}(y)} \operatorname{sign}(f_*)_x = 0$. But how do I know that for another value $z \in N$ with $f^{-1}(z) \neq \varnothing$ the sum $\sum_{x \in f^{-1}(z)} \operatorname{sign}(f_*)_x$ will actually add up to 0? Choosing $y \in N \backslash f(M)$ to conclude that $\operatorname{deg}(f) = 0$ has always appeared like a kind of "proof by definition" to me (using the quite unnatural definition that every $y \in N \backslash f(M)$ is a regular value, although $f^{-1}(y) = \varnothing$) and I have never understood, why it is allowed to make this kind of argument.
Can anybody help me understand this?

A: This argument  can't be found in Guillemin & Pollack, as per the comments above, but the idea "if you have two oriented sets of points $X$ and $Y$, and you want to show that a signed count of the numbers is equal - find an oriented cobordism between them", can. This works because a signed count of the number of boundary points of a compact 1-manifold is zero, so if you have a compact 1-manifold $N$ with $\partial N = X \sqcup \bar Y$ ($\bar Y$ being $Y$ with the opposite orientation), then $\#X = \#Y$, where here we're taking a signed count.
So you have a smooth map $g: M \to Y$, where $M$ and $Y$ are closed, and you want to show that if $x, y$ are regular values of $g$, then $\# g^{-1}(x) = \# g^{-1}(y)$. Let $f: I \to Y$ be an embedded path with $f(0) = x$, $f(1) = y$. Now invoke the corollary to the transversality theory on page 73 of Guillemin and Pollack to homotope $f$ - without changing what it does at the endpoints! - to a map transverse to $g$. Because you can perturb $f$ by an arbitrary small amount, you can choose it to remain an embedding. Then (by a mild modification of the same argument as usual), because $f(I)$ is transverse to $g$, $g^{-1}(f(I))$ is an oriented submanifold of $M$ with boundary, whose boundary is $f^{-1}(x) \sqcup \overline{f^{-1}(y)}.$
I think what we do here - trying whatever we can to find a cobordism between the two sets of points - is fairly intuitive. In particular, if a map is of degree zero, this shows that for any $x,y$ with $f^{-1}(x) = \varnothing$, there is a manifold whose boundary is $f^{-1}(y)$, hence the signed count of points is zero.


text:
Q: One Styled HTML Page with Dynamic Content I have a question that I may just be overthinking. So I have three links on a page. All three links will open the same HTML page. The only problem is I want to display different images depending on which link is clicked.
I don't want to create three different variation of the same page, so is there a way to do this dynamically (maybe Javascript?)
Any help would be appreciated.
Thanks!

A: The easiest way I could imagine this working is using a hash in the URL of the  elements in the origin page:
Link to show image one
Link to show image two
Link to show image three

And in the receiving page, the CSS:
/* selects the relevant images: */
.imgClass {
    /* hides them: */
    display: none;
}

/* selects the image whose id appears in the URL: */
.imgClass:target {
    /* shows that image: */
    display: inline-block;
}

Reference:

*

*:target pseudo-class.

A: Use a query parameter.
Link 1 might point to /page?link=1, link 2 might go to /page?link=2, and so on. You'd probably want to generalize out to "which kind of image should display," but you get the gist. Don't forget to include some default value in case no parameter is presented.
And for the record, you'd typically handle the query and choose the image server-side, although yes, you could also do it in JavaScript.

A: Since I assume that you are not using any server side script what you can do is pass query string parameters from one page to another.
Suppose the name of the second page is images.html you can call the link as images.html?img=1 or images.html?img=2 etc, on the page you need to use javascript to read the query string values.Based on the img value you can load different images.  Check this stackoverflow for details
How can I get query string values in JavaScript?


text:
Q: Facebook Open Graph Action Optional Parameters I have an open graph action that takes a required reference parameter and an optional reference parameter. My question regards how to define captions for when the optional parameter is not there.
So, if for example, my action is about earning badges that can be linked to a specific event or not as in:
[User:Raul] has just [Verb:earned] the [Badge:Gold] badge for the [Event:400 meter dash]

But could also be:
[User:Raul] has just [Verb:earned] the [Badge:Overall 1st Place] badge

Is there any way to accomplish setting the caption to this? How are we supposed to handle optional parameters then?
My experience is that if I set any of the caption lines to include the optional parameter and it is not there then Facebook will use a generic caption for the event.


text:
Q: React, getting Error: Invalid hook call. Hooks can only be called inside of the body of a function component Can anyone help me with React Hooks basics, I am relatively new and couldn't find proper help online
import React from 'react'
import { auth, provider } from "../../../firebaseSetup";
import { useNavigate } from "react-router-dom"

const GoogleAuth = async() => {
  const navigate = useNavigate()

    auth.signInWithPopup(provider).then(() => {
      navigate('/home');
    }).catch((error) => {
      console.log(error.message)
    })
}
export  default GoogleAuth

I get error on const navigate = useNavigate() saying:
Error: Invalid hook call. Hooks can only be called inside of the body of a function component

A: What they want for useNavigate (and all hooks) is to be called only at the top level of a React component or a custom hook.

Don't call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function, before any early returns.

See Rules of Hooks for more.

A solution to your problem could be calling const navigate = useNavigate() in the component where you will use GoogleAuth, and pass navigate as parameter.
As an example like so:
import React from 'react'
import { auth, provider } from "../../../firebaseSetup";
import { useNavigate } from "react-router-dom"

const GoogleAuth = async(navigate) => {
    auth.signInWithPopup(provider).then(() => {
      navigate('/home');
    }).catch((error) => {
      console.log(error.message)
    })
}
export  default GoogleAuth

import GoogleAuth from "GoogleAuth";
const App = ()=>{
       /*
          here at the top level, not inside an if block,
          not inside a function defined here in the component...
       */
       const navigate = useNavigate();
       useEffect(()=>{
         GoogleAuth(navigate)
       },[])
       return

    }
export default App;


text:
Q: Experimental signature of topological superconductor I was wondering if someone can provides some clear experimental signatures of a topological superconductors ?
I was thinking about that, because for topological insulator, one of the hallmarks is the insulating behaviour of the bulk versus the metallic behaviour at the edge. So, a good experimental signature is simply the presence of edge conducting channel(s). But for superconductors, even the non-topological (say $s$-wave for simplicity) ones already have only edge propagating modes, as elaborated by London long times ago. So, what would be the smoking gun experiment about topological superconductors ? Are we obliged to probe the gap symmetry (what I would not really like because it is more or less a symmetry check, not a topological one), or is there something more fancy ?
Any good reference is obviously warm welcome.

A: There are different categories of topological superconductors. I'm guessing that you are referring to the time-reversal invariant (class DIII) ones, in 2D or 3D. Yes, it is possible to distinguish the surface/edge states of 3D/2D topological superconductors from the bulk. I'm not talking about designing some intricate experimental technique to separate out the contribution from the bulk and the surface; as it turns out, they don't need any separating!  The bulk and surface states are distinct in a very fundamental way. That statement is true not just in topological superconductors but also in topological insulators. First allow me to make a few comments on topological insulators case.
Yes, an ideal topological insulator is insulating in the bulk and conducting on the surface/edge. Despite the existence of an extensive list of (3D) band topological insulators discovered to date, none of them are insulating in the bulk! The Kondo topological insulator SmB$_6$ is the only one with the properties of an ideal topological insulator; but the Kondo gap opens up only at cryogenic temperatures ($\approx$ 4 K). So this example is not "natural" in the sense that it doesn't exist in a topological phase under ambient conditions.
The reason we can distinguish between the surface (in the 3D case) and bulk states of a topological insulator, even when the bulk is conducting, is because the surface forms the so-called "helical metal." The conducting electronic states in this helical metal do not hybridize (or mix) with the conducting states in the bulk; picture this with the analogy of two immiscible liquids in a container. The following paper discusses in detail how topological surface states refuse to hybridize with the bulk

Bohm-Jung Yang, Mohammad Saeed Bahramy, and Naoto Nagaosa.
  "Topological protection of bound states against the hybridization."
  Nature communications 4 (2013): 1524. (arXiv version)

These helical states, which form a 2D electronic system on the boundary of a 3D system, have half the degrees of freedom (DOF) of an equivalent purely 2D system; the other half (DOF) are on the other surface (look up the holographic principle). As a result, no time-reversal symmetry preserving perturbation can gap them out. In other words, they are topologically protected (due to symmetry). Another important thing to stress is that just because an insulator is topologically trivial doesn't mean it cannot have surface states. The only difference is that these states can be destroyed.
Now, in the case of topological superconductors, the surface states are even more exotic. The surfaces of 3D time-reversal invariant topological superconductors host Majorana modes. You would observe a topologically protected Dirac cone, just like a 3D topological insulator, on the surface of a topological superconductor. The only difference is that this Dirac cone represents the dispersion of Majorana modes instead of Dirac fermions and has half the degrees of freedom due to particle-hole symmetry. There is a tonne of literature out there which proposes schemes of experimentally detecting these Majorana modes. For the case of 3D time-reversal invariant topological superconductors, however, I am familiar with only two: Scanning Tunneling Microscopy (STM) and Angle-Resolved Photoemission Spectroscopy (ARPES). In a point contact spectroscopy measurement on a topological superconductor you are supposed to see a so-called Zero-Bias Conductance Peak (ZBCP) inside the bulk gap as shown in Fig. 2 of:

Satoshi Sasaki, M. Kriener, Kouji Segawa, Keiji Yada, Yukio Tanaka,
  Masatoshi Sato, and Yoichi Ando. "Topological Superconductivity in
  Cu$_x$Bi$_2$Se$_3$." Physical Review Letters 107, no. 21 (2011):
  217001. (arXiv version)

One small disclaimer: there is still a lot of debate whether the authors of the above paper have really seen the Majorana mode or not. For example check this article which refutes the claims of the above paper:

Niv Levy, Tong Zhang, Jeonghoon Ha, Fred Sharifi, A. Alec Talin, Young
  Kuk, and Joseph A. Stroscio. "Experimental Evidence for $s$-Wave
  Pairing Symmetry in Superconducting Cu$_x$Bi$_2$Se$_3$ Single Crystals
  Using a Scanning Tunneling Microscope." Physical Review Letters 110,
  no. 11 (2013): 117001.
  (arXiv version)

Alternatively, instead of the momentum-integrated density of states in STM, you can directly "see" the Dirac cone of Majorana modes using ARPES since you are measuring the bandstructure directly. As matter of fact, the existence of first and second generation of 3D topological insulators was identified using precisely this technique. To my knowledge, no one has so far observed Majorana modes on the surface of a topological superconductor using ARPES. The main reasons are technical: cooling capabilities, energy resolution, lack of stoichiometrically stable (unlike Cu$_x$Bi$_2$Se$_3$) material candidates which can be cleaved to give atomically flat surfaces, etc.
Aside from time-reversal invariant topological superconductors, a broad list of schemes to engineer topological superconductors and detect their Majorana modes can be seen in the following (excellent) review articles:

Jason Alicea. "New directions in the pursuit of Majorana fermions in
  solid state systems." Reports on Progress in Physics 75, no. 7
  (2012): 076501. (arXiv version)
C. W. J. Beenakker, "Search for Majorana Fermions in
  Superconductors." Annual Review of Condensed Matter Physics
4, no. 1 (2013): 113-136. (arXiv version)

Details (continued from the comments section below)
As far as the ZBCP goes, I feel that it is still more reliable using STM (compared to transport) for 3D superconductors (class DIII). For the system investigated by Kouwenhoven and others in the 1D Rashba nanowires (class D) the situation is way more ambiguous. Transport is way more finicky; it's (obviously) not as direct as STM or ARPES. The discrepancies in the above mentioned STM studies arise (in Yoichi Ando's and my opinion) because Cu$_x$Bi$_2$Se$_3$ is very hard to work with. Since Cu$_x$Bi$_2$Se$_3$ is not stoichiometrically stable, the dopant copper atoms diffuse and form "pockets" of superconducting and normal (or topological and non-topological) regions (depending on local density of Cu). Ando thinks that the two studies measured different such regions! That being said, I don't know if Cu$_x$Bi$_2$Se$_3$ is topological if the above problem didn't exist. I'm just pointing out the source of the confusion.
Few comments on ARPES: this is the real deal! You can indeed have a smoking gun detection using ARPES; after all you see the Majorana mode dispersion directly. The reason people haven't seen this yet, as I mentioned, is mainly technical. First of all, the state-of-the-art ARPES systems can go to into the $\approx$ 10 K range. Most topological superconductor candidates have $T_c$'s way below that (e.g. half-Heusler compounds and heavy-fermion superconductors). Some (laser-based) systems can go down to 1.5 K. It might seem that Cu$_x$Bi$_2$Se$_3$ (with $T_c = 3.8$ K) might be perfect. But it's not enough to go just below $T_c$. You have to go way below in temperature to see the (superconducting) gap features clearly (i.e. when the gap is big enough); the gap size roughly follows a power law like $\approx 1/T^2$ below $T_c$. Also the gaps of many candidate materials are very small (compared to topological insulator band gaps). Conventionally synchrotron-based ARPES is the state-of-the-art tool for doing ARPES experiments. However, recently laser-based ARPES is becoming more commonplace in labs. Apart from the compactness and significantly less resource consumption (both monetary and operating manpower) laser-based ARPES is becoming popular because it's "clean." Check out this image to see what I mean by that:

The synchrotron-based ARPES systems have more "juice" (high photon energies in the tens of eV) as opposed to laser-based ones (6-7 eV), but they have very poor resolution. Good resolution is what we really need if we want to see the features of the Majorana modes inside the tiny superconducting gap.
Few comments on potential topological superconductor candidates: in addition to being very good topological insulator candidates, some of the half-Heusler compounds become superconducting at very low temperatures (1-2 K). For example LaPtBi, YPtBi, and LuPtBi have $T_c$'s of 0.9 K, 0.77 K, 1 K respectively. Unfortunately the samples of these materials that have been grown so far are "rock-like" (as opposed to crystalline) and it's very hard to cleave them get an atomically flat surface to do ARPES on. After all the Majorana modes live on the surface!
Long story short, ARPES can give us smoking gun signatures Majorana modes. I'm sure there are other clever (indirect) ways of getting smoking gun signatures as well.


text:
Q: How to use autossh with google compute (`gcloud compute ssh`) I would like to use autossh instead of the ssh command run by google cloud while doing
gcloud compute ssh --zone myzone --project myproject mymachine
What is the command line to replace it?

A: A replacement for the command line
Here is the two commands that allow you to use autossh:
gcloud compute config-ssh
autossh -M9042 mymachine.myzone.myproject

In my opinion, this is the easiest way to do it. The first line export the ssh key and configuration of your machines, and the second just use this alias.

More on ssh configuration
This also allow you to use the shortcut mymachine.myzone.myproject for scp, ssh, and all ssh related tools. Indeed, the list of your machines are exported in your ~/.ssh/config.
This is a list of aliases you can also configure by hand.
For more information on gcloud's config-ssh, you can refer to the official documentation.
Notice that some shell environment will provide you with ssh command autocompletion, which is really helpful when it comme to remembering the name of your machines. Here is a reference for zsh.


text:
Q: Derived category of a hypersurface Let $X$ be a smooth projective variety over $\mathbb{C}$, and $H \subset X$ be a smooth hypersurface.
Many properties of an ambient variety $X$ could somehow inherit to the hypersurface $H$, I was wondering if there is any know result dealing with the relation between the derived categories of (bounded) complexes of quasi-coherent sheaves (or coherent sheaves) on $X$ and $H$?

A: In terms of semiorthogonal decompositions, there is an answer to this question, as it has been mentioned above.
More precisely, if one has a so called Lefschetz decomposition of the bounded derived category of coherent sheaves on a smooth projective variety (such a decomposition depends also on the choice of a projective embedding) then one has an induced semiorthogonal decomposition of the derived category of a hyperplane section, with pieces coming from the ambient variety and then an additional component. One can think of this as some sort of a Lefschetz hyperplane theorem result. More details here: Kuznetsov`s Main HPD Paper
Then, if you have a degree d hypersurface H in P^n, this hypersurface can be seen as a linear section of P^n with respect to the degree d Veronese embedding.
In this direction, the paper mentioned above (by Ballard, Deliu, Favero, Isik and Katzarkov) gives an answer to what the extra information is, either in terms of LG-models (matrix factorization categories) or in terms of the derived category of sheaves of modules over a sheaf of A_infty algebras (there is a nice, simple formula describing the sheaf of A_infty algebras).

A: Maybe it's worth spelling out the easy case of projective space (and Veronese embedding).
Take the standard exceptional collection $<O,O(1),...,O(n)>.$
The derived category of a hypersurface X of degree d has then a semi-orthogonal decomposition $<A_X, O, O(1), ..., O(n-d)>$. We might think of $A_X$ as being the "interesting" part of the derived category of X.
We can also intersect further and $D(X_1 \cap X_2) = <A_{X_1 \cap X_2}, O,\ldots, O(n-2d)>$.
Take the universal hypersurface of degree d, call it $H$.
This sits inside $P^n \times P^N$, where $N$ is the ambient dimension of the degree d Veronese embedding.
The category $H$ (being itself a hypersurface) has a decomposition where we call the interesting part just $A$.
For each point $p \in P^N$ we have a hypersurface $H_p$ and thus an interesting category $A_{H_p}$.
The "homological dual" variety is a $Y$, mapping to the dual $P^N$, such that $D(Y)$ is the total $A$. In some sense, $Y$ is parameterezing all the categories $A_{H_p}$.
The point of HPD is then the compatibility between passing to base loci and base changing Y.
If $L < P^N$ is some linear system, then the derived category of the corresponding base locus has a decomposition and the interesting part is the interesting part of $D(Y \times_{P^N} L$.
(this is perhaps too sloppy to be useful but I tried)
The Viennese school of Katzarkov, Ballard, Favero etc. has shown that in this context (of degree d Veronese embedding) there is a (sort of tautological) dual. Unfortunately this dual is a highly non-commutative variety, in fact it's the dual $P^N$ with a sheaf of $A_\infty$-algebras over it.