text:
Q: How to trigger an iframe event Jquery I have an IFRAME and I want to trigger an event (which is inside the iframe) from the parent of an IFRAME:
Just a rough example of what I am trying to do :

A: Your jquery is correct only problem is that that you are doing this when document is ready but at that time iframe is not getting fully loaded therefore div doesn't exist at that time and not triggers click.
Change your main page script to
$(document).ready(function() {
    //want to trigger it from outside the iframe
    $("#i").load(function(){
        $("#i").contents().find("div").trigger("click");
    });
});

A: try this
ger javascript event from within an iFrame
but look at answer from Gilly
document.myFrameName.myFunction();

regards


text:
Q: QODBC - Email Sent Date I'm using QODC, Just trying to find if anyone knows where the data is stored for the history of the Estimate "Sent Date" or if there is a way to get this from Quickbooks desktop into SQL.  I have been through the tables and cannot see this as record anywhere.  Any help would be greatly appreciated.

A: Alex, I would suggest using QuickBooks Application and exporting the Estimate records to Excel to see if this information is available in the exported excel file. Export the "Estimate" table using QODBC. You can then use join/lookup on both the Excel file.
QODBC is able to access data from QuickBooks using the QuickBooks SDK, which is an embedded feature of the QuickBooks Desktop Application.
QODBC can only use those fields and commands which are allowed by the QuickBooks SDK.
QuickBooks SDK does not provide us the "Sent Date" field in the table Estimate or EstimateLine. Thus, it is not available in QODBC.
QODBC will, of course, support it when this feature is available through SDK. I would request you to get in touch with Intuit with your request.
QuickBooks Support: https://help.quickbooks.intuit.com/en_US/contact
Intuit Developer Support: https://help.developer.intuit.com/s/topic/0TOG0000000kF9KOAU/quickbooks-desktop
QuickBooks SDK: https://static.developer.intuit.com/qbSDK-current/common/newosr/index.html
QODBC Support: http://support.qodbc.com

redpajama_set_name: RedPajamaStackExchange


text:
Q: odoo 11 changes to report renderer from odoo 9 We've just upgraded from odoo 9 to odoo 11.  odoo 11 has had the Report printing functionality removed, meaning the old code I used of:
report = xmlrpclib.ServerProxy('{}/xmlrpc/2/report'.format('https://odoo.example.com'))
result = report.render_report(self.odooconnection1.db, self.odooconnection1.uid, self.odooconnection1.password, 'account.report_invoice', [invoice_id])

is now deprecated.
How do i go about programmatically downloading reports in odoo 11

A: So this isn't the best way at all, and is a bit of a hack but i solved it by:
Using the python requests and lxml packages to make a request, manually login to the odoo site and then with that session, download the various PDF's i required.
import requests
from lxml import html

def __download_report(self, invoice_ids, date_to_use):
        session_requests = requests.session()
        login_url = "https://odoo.example.com/web/login"
        result = session_requests.get(login_url)

        tree = html.fromstring(result.text)
        authenticity_token = list(set(tree.xpath("//input[@name='csrf_token']/@value")))[0]
        payload = {
            "login": "username",
            "password": "password",
            "csrf_token": authenticity_token
        }
        result = session_requests.post(
            login_url,
            data = payload,
            headers = dict(referer=login_url)
        )
        for invoice_id in invoice_ids:
            filename = self.__get_file_name(invoice_id)

            url = "https://odoo.example.com/report/pdf/account.report_invoice/"+str(invoice_id)
            pdf = session_requests.get(
                url,
                stream=True
            )
            sys.stdout.write("\r[%s]" % filename )
            sys.stdout.flush()
            self.__save_report(pdf, filename, date_to_use)

def __save_report(self, report_data, filename, date_to_use):
        with open(filename, 'wb') as f:
            f.write(report_data.content)


text:
Q: Camel Case property names in json files are not getting mapped to Java Object I have a json object with property names like: itemsRequired, sortable_list. And in my ObjectMapper, I have
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);

With this sortable_list gets mapped to appropriate property in POJO but itemsRequired is ignored. While if I remove the PropertyNamingStrategy, then itemsRequired works and sortable_list don't. What should be done if I want both to work together?
I am using fasterxml lib. I have also tried codehaus's jackson with same result.

Update: The POJO is as follows,
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(Include.NON_NULL)
public class CreateList extends Header {
    private String question;
    private String placeholder;
    private String help;
    private int itemsRequired;
    private List<String> list;

    // Getter and Setter methods
}

And the JSON is,
"create": {
    "heading": "Activities Available to You",
    "question": "List at least four activities at school and in your community that you may want to try out.\n",
    "placeholder": "List an activity",
    "help": "You can only have 10 list items",
    "list": [],
    "items_required": 4
  }

Everything works fine, if I have the JSON as above. But things do not work when I change the JSON to,
"create": {
    "heading": "Activities Available to You",
    "question": "List at least four activities at school and in your community that you may want to try out.\n",
    "placeholder": "List an activity",
    "help": "You can only have 10 list items",
    "list": [],
    "itemsRequired": 4
  }

itemsRequired is ignored in latter case.
I would like it to work in both cases, whether it is named as items_required or itemsRequired.

A: As suggested, you should probably use explicit annotation for entries that you do not want to be modified.
I don't know why code above wouldn't work: it seems like it should. You are also correct in using Jackson 2.x version (com.fasterxml package); there is no benefit trying to use older 1.x versions.
You may want to file a bug report: this could be a bug. But to know this, bit of sample code is needed; perhaps there is another explanation to the problem.

A: You can use @JsonProperty. If you donot like idea of adding annotation to target class you can use always use Mixins, if you want to have few if them as snake case and other camelCase.Since mixins allows you to add property names to class without actually editing
target class, mostly in case of third party classes.
But I would preffer custom naming strategy
since it allow you to have strategy which can parse both and will be registered with ObjectMapper, will help you to avoid maintaining mixins,JsonProperty etc.


text:
Q: SVG  with text and div fill width with transition I'm working on an SVG here I want a rectangle to add text inside div and color fill with transition I had tried like this
<g>
  <rect width="25%" height="100%" fill="blue"></rect>
  <rect width="100%" height="100%" fill="none"></rect>
  <text x="0" y="50"  font-size="35" fill="green">text here</text>
</g>

Still not coming and for the animation i tried like this
<animate attributeName="width" from="0" to="200" dur="5s" />

Can anyone suggest to me how to achieve this output. Any help will be appreciate

svg {
  width: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="slider1" type="range" min="0" max="100" step="25" value="25" oninput="document.querySelector(`#SVG${this.id} rect`).setAttribute('width',this.value+'%')" />

<svg id="SVGslider1" viewBox="0 0 30 6">
  <rect width="25%" height="100%" fill="blue" />
  <rect width="100%" height="100%" fill="none" stroke="black"/>
</svg>

A: Try adjusting x, y and font-size on the text and adding a transition property for the rect:

svg {
  width: 200px;
}

rect {
  transition: width 0.5s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="slider1" type="range" min="0" max="100" step="25" value="25" oninput="document.querySelector(`#SVG${this.id} rect`).setAttribute('width',this.value+'%')" />

<svg id="SVGslider1" viewBox="0 0 30 6">
  <rect width="25%" height="100%" fill="blue" />
  <rect width="100%" height="100%" fill="none" stroke="black"/>
  <text x="5" y="5"  font-size="6" fill="green">text here</text>
</svg>

EDIT: to make the <rect> element fill vertically, swap width for height and y:

svg {
  width: 200px;
}

rect {
  transition: y 0.5s, height 0.5s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="slider1" type="range" min="0" max="100" step="25" value="25" oninput="document.querySelector(`#SVG${this.id} rect`).setAttribute('height',this.value+'%');document.querySelector(`#SVG${this.id} rect`).setAttribute('y',100-this.value+'%')" />

<svg id="SVGslider1" viewBox="0 0 30 6">
  <rect y="75%" width="100%" height="25%" fill="blue" />
  <rect width="100%" height="100%" fill="none" stroke="black"/>
  <text x="5" y="5"  font-size="6" fill="green">text here</text>
</svg>


text:
Q: Array Sorting - Swift How Can Sort A-Z I have an array of pdf files (see attached screenshot) that I need to sort alphabetically. Here is the code that generates the array, can anybody suggest changes to have the array sorted?
import UIKit

var pdfsArray = [String]()

class PDFListViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let fm = FileManager.default

        let path = Bundle.main.resourcePath!

        let items = try! fm.contentsOfDirectory(atPath: path)

        for item in items {
            if item.hasSuffix(".pdf") {

                pdfsArray.append(item.uppercased())

            }
            let sortedFiles = pdfsArray.sorted()
             pdfsArray = sortedFiles
        }

A: Simple enough, you can just call swift's sort (or sorted) function and provide the sort-function to sort by numeric values:
var array = ["Part 45", "Part 1", "Part 10", "Part 20", "Part 100", "Part 2"]
array.sort { st1, st2 in
    st1.compare(st2, options: .numeric) == .orderedAscending
}


text:
Q: String Manipulation with the difference of two numbers in SQL I have a field called StartYear, the value of my field is 2000.
I have another field called EndYear, the value of my field is 2005.
I want to create a field called YearsInTheProgram that has the values 2005,2004, 2003,2002,2001,2000.
Each of my rows have different values, so in essence I would like this field to have the difference of my fields separated my commas.
Any help would be appreciated

A: CREATE FUNCTION [dbo].[GetAllYears] (
    @START BIGINT = 2000,
    @END BIGINT = 2005
) RETURNS NVARCHAR(MAX) AS BEGIN

    DECLARE @RET NVARCHAR(MAX);

    SET @RET = CONVERT(NVARCHAR(4), @START)

    WHILE @START < @END BEGIN
        SET @START += 1;
        SET @RET = @RET + ',' + CONVERT(VARCHAR(4), @START);
    END

    RETURN ISNULL(@RET, '');
END
GO

using;
select
    startYear,
    endYear,
    dbo.GetAllYears(startYear, endYear) as AllYears
from
    xxxxTable

you can update your table;
update xxxxTable (AllYears)
select dbo.GetAllYears(startYear, endYear) from xxxxTable


text:
Q: Pandas rowwise data to table form I have information from a csv file that is presented rowwise:
Color     Shape    Value
red       triangle    10
red       circle      11
blue      triangle    12
blue      circle      13

I need to convert this to a new dataFrame in a matrix form, where the columns are colors and the indexes are shapes
           red  blue
triangle    10    12
circle      11    13

I managed to do this by iterating in a loop
new_df = pd.DataFrame(columns=list_of_colors, index=list_of_shapes)

for color_i in list_of_colors:
  # this gives me the values of each color sorted* by Shape
  df[df['Color'] == color_i].sort_values('Shape')['Value']

  # so I can append this to the new dataframe
  ...

*

*I really don't need the shapes to be sorted, but I need to guarantee that in each iteration the retrieved shapes list are in the same order, otherwise the resulting table will be wrong

This works, this I think I'm overdoing it.
Is there a direct way of taking rowwise info and converting it to a table form?
Thanks

A: You can use pivot_table():
For the data:
import pandas as pd
df = pd.DataFrame({'Color': ['red', 'red', 'blue', 'blue'],
                   'Shape': ['triangle', 'circle', 'triangle', 'circle'],
                   'Value': [10, 11, 12, 13]})

df.pivot_table(index = 'Color', columns = 'Shape', values = 'Value')

The result is:
Shape   circle  triangle
Color
blue     13       12
red      11       10


text:
Q: ASP.NET MVC3 edit action not updating records in database I have an edit action configured that is not updating records but not throwing any exceptions. The update appears to have worked but the changes are not reflected in the database.
I am using EF and MVC3, i have an interface that defines save customer
 public interface ICustomerRepository
 {
    //allows a sequence of customers to be displayed
    IQueryable<Customer> Customers { get; }
    //saves edits to customer records
    void SaveCustomer(Customer customer);
 }

Then my implementation of this
public void SaveCustomer(Customer customer)
    {
        if (customer.CustomerId == 0)
        {
            context.Customers.Add(customer);
        }
        context.SaveChanges();
    }

Then in the controller my get and post actions
public ViewResult Edit(int customerId)
    {
        Customer customer = repository.Customers.FirstOrDefault(c => c.CustomerId ==   customerId);
        return View(customer);
    }

 [HttpPost]
    public ActionResult Edit(Customer customer)
    {
        if (ModelState.IsValid)
        {
            repository.SaveCustomer(customer);
            TempData["message"] = string.Format("{0} has been saved",    customer.CustomerName);
            return RedirectToAction("Index");
        }
        else
        {
            //there is something wrong with the data values
            return View(customer);
        }
    }

Then in my view i have
 @model CustomerOrders.Domain.Entities.Customer

@{
ViewBag.Title = "Admin: Edit" + @Model.CustomerName;
Layout = "~/Views/Shared/_AdminLayout.cshtml";
 }

Edit @Model.CustomerName

using (Html.BeginForm("Edit", "Admin"))
{

@Html.EditorFor(model => model.CustomerId)

@Html.LabelFor(model => model.CustomerName)

@Html.EditorFor(model => model.CustomerName)

@Html.ValidationMessageFor(model => model.CustomerName)

@Html.LabelFor(model => model.PrimaryContactName)

@Html.EditorFor(model => model.PrimaryContactName)

@Html.LabelFor(model => model.PrimaryContactNo)

@Html.EditorFor(model => model.PrimaryContactNo)

<input type="submit" value="Save" />
@Html.ActionLink("Cancel and return to list", "Index")

}

I also have a create method wired up to the same edit action and view which works fine. Not sure where i am going wrong, im new to MVC3 and not sure if my edit implementation is correct?

A: The simple answer is because your working in a stateless environment, unless your using self tracking entities, you need to Attach the object to EF's graph.
I've had problems with edit in the past though. So i ended up going to the DB to fetch the object first, then merging in the changes i need, then doing Save.
You need to seperate your Create/Edit actions out. Simply checking if the ID > 0 to deem an edit is not enough, be more explicit.
So to sum up:

*

*Have one action method for new objects. Use context.AddObject in this scenario.

*Have another action method for modifying objects. Go get the object from the repository, merge in your changes (left to right, or auto mapper, or TryUpdateModel), and do context.SaveChanges.

Overall, it's a pain. Many developers (myself included) have gone through what you have.


text:
Q: Go time.Parse() getting "month out of range" error I'm new to Go and I was parsing a nginx time format string. You can check my code here:

package main

import (
 "time"
 "log"
 "fmt"
)

func main(){
 //nginx time format
 nginx_time :="03/Apr/2017:08:29:05 +0800"
 t,err:=time.Parse("02/Jan/2016:15:04:05 MST",nginx_time)

 if err != nil {
  log.Fatal(err)
 }

 fmt.Println(t.Format("2006-01-02 15:04:05"))
}

I received the following error:

GOROOT=/usr/local/go
GOPATH=/usr/local/share/go:/Users/sinopex/goroot:/Users/sinopex/goroot
/usr/local/go/bin/go build -o "/private/var/folders/5b/yf1f_9lj06bfvqvcq2h9myph0000gn/T/Build 1.go and rungo" /Users/sinopex/goroot/src/github.com/sinopex/golang/example/test/1.go
"/private/var/folders/5b/yf1f_9lj06bfvqvcq2h9myph0000gn/T/Build 1.go and rungo"
2017/04/03 12:17:12 parsing time "03/Apr/2017:08:29:05 +0800": month out of range
http://stackoverflow.com/questions/ask#
Process finished with exit code 1

Any ideas on what I am doing incorrectly?
Thank you.

A: Your parsing format does not match the reference format and the input format in 2 places:

*

*The year in the reference format should be 2006

*The timezone offset is to be specified by numbers, not by timezone name: -0700
So:
t, err := time.Parse("02/Jan/2006:15:04:05 -0700", nginx_time)

play.golang: https://play.golang.org/p/enJY0VBt3a


text:
Q: What's the difference between `hostip` and `windows ip` when set WSL2 proxy by Clash `Allow LAN`? I have searched and scanned many blogs or websites for "how to set proxy for WSL2". Such as here or here.
My confusion is, that I find the following 2 ways can both set proxy for WSL2 successfully when using wegt www.google.com to test.
Assume I have windowsip=192.168.3.3 and hostip=172.24.80.1 as

*

*use hostip
hostip=172.24.80.1
proxyPort=7890
export https_proxy="http://${hostip}:${proxyPort}";
export http_proxy="http://${hostip}:${proxyPort}";
export all_proxy="http://${hostip}:${proxyPort}";

Then the test result of using hostip=172.24.80.1 is:

*

*or use windows ip:

windowsip=192.168.3.3
proxyPort=7890
export https_proxy="http://${windowsip}:${proxyPort}";
export http_proxy="http://${windowsip}:${proxyPort}";
export all_proxy="http://${windowsip}:${proxyPort}";

The test result of using windowsip=192.168.3.3 is:
Since I do lack corresponding knowledge of computer networks, I'm very confused about them. Why the ip 192.168.3.3 and 172.24.80.1 are both effective for WSL2 when CFW's Allow LAN enabled?
So, what is the difference between the above 2 methods?
And are there any potential differences that may influence my succedent usage?
Thanks in advance.

A: Literally none. In both cases, the variable has no meaning on its own – it's a temporary definition that is only used as a $variable substitution in the subsequent export lines. (Only "exported" variables become visible to child processes as environment variables; the rest remain internal to the shell.) In both cases, the end result is export https_proxy="http://172.24.80.1:7890".


text:
Q: How to return a CompletableFuture from the thenApply of another CompletableFuture in Java? I am new to the concept of CompletableFuture in Java, so I don't know a whole lot about it and its functions other than thenApply
I have a requirement where I have to test some condition in the thenApply block of a CompletableFuture A. If the condition is satisfied, return null, else return another CompletableFuture B so that in the next thenApply, the result will be that of B.
Basically I am trying to do something like the following:
CompletableFuture<String> A = ......
CompletableFuture<Boolean> B = ......

A.thenApply((res) -> {
  if (res.equals("hey")) {
   return null;
  } else {
   return B;
  }
})
.thenApply((bResult) -> { // At this point, I want it to act as if I was calling B.thenApply

   //some function;
})

Is this possible? Can I return a CompletableFuture from another CompletableFuture so that the next thenApply on the chain will actually be a thenApply of the returned CompletableFuture?
Also, if I want to cancel the next thenApplys on some condition. How do I do that?


text:
Q: Ansible vars_prompt for roles I have a set of Ansible playbooks and the main yml file is like this
- hosts: all
  roles:
    - common
    - install_nginx

I want to add the confirm message when I trigger the playbook. I tried this and did not work
- hosts: all
  vars_prompt:
    - name: CONFIRM
      prompt: Just to confirm you will install stuff
  tasks:
    - fail: no deployment this time
      when: CONFIRM != 'yes'
  roles:
    - common
    - install_nginx

How can I use vars_prompt in this case without modify every role?

A: If you look at the output from running your playbook with the vars_prompt you'll see that the fail task runs after the other roles. This is also mentioned in the Ansible docs for playbooks and roles:

If the play still has a 'tasks' section, those tasks are executed
  after roles are applied.

As the above docs also mention if you want to force a task to run before any roles then you can use pre_tasks.
So to have your confirmation style prompt you could simply do this:
- hosts: all
  vars_prompt:
    - name: CONFIRM
      prompt: Just to confirm you will install stuff
  pre_tasks:
    - fail: no deployment this time
      when: CONFIRM != 'yes'
  roles:
    - common
    - install_nginx

A: I am not very sure, but the way this works is :
- hosts: all

  vars_prompt:
    - name: "confirm"
      prompt: Just to confirm you will install stuff
      private: no
      default: "no"
  tasks:
    - name: Install Nginx
      apt: name=nginx
      sudo: true
      when:  confirm == "yes"

Now if we need to call each role based on a condition , i suppose we shoud be using tags.

A: How to use Ansible vars_prompt for roles
i got the solution to use vars_prompts in ansible role section
i have directly included vars_prompt in my main.yml playbook as like before
- hosts: "{{HOSTS}}"
  gather_facts: yes
  become: yes
  roles:
    - syslog
    - splunk
    - nmon
    - trendmicro
    - user-creation
    - extened-history
  vars_prompt:
    - name: "user_password"
      prompt: "Enter User Password"
      private: yes
      confirm: yes
==========================================================

Below is the ansible command to execute the playbook
# ansible-playbook ort-linux.yml -e "HOSTS=TESTSERVER"
Enter User Password:
confirm Enter User Password:

========================================================

Below is my roles playbook for user id creation
---
  - name: "Task-1 create Linux Team user"
    user:
     name: "{{item}}"
     comment: LINUX_UNIX_TEAM
     group: LINUX_UNIX_TEAM
     shell: /bin/bash
     generate_ssh_key: yes
     ssh_key_bits: 2048
     ssh_key_file: .ssh/id_rsa
     createhome: yes
     password: "{{user_password|password_hash('sha512')}}"

    loop:
     - sam
     - jack
     - kumar
     - ravi
    tags: linuxuser


text:
Q: Why there is no UserSet class defined in Python? Why python does not provide UserSetclass to extend and define user defined Set. It does provide UserDict,UserList, UserString but no UserSet.
I'm referring to Python Documentation

A: PEP 3108 provides some insight into why no UserSet or similar implementations were added in similar fashion to UserDict and the like.

Guido pronounced that "silly old stuff" is to be deleted from the
  stdlib for Py3K. This is open-ended on purpose. Each module to be
  removed needs to have a justification as to why it should no longer be
  distributed with Python.

UserDict, UserList, and UserString are all listed in the "Obsolete" section of PEP 3108 with the following reason noted and an indication that they were moved to the collections module.

Not as useful since types can be a superclass

Given that they were considered "obsolete", it is unsurprising that similar classes were not implemented for other types such as sets.
Since types can be superclasses and abstract base classes provide a reasonable alternative for creating subclasses of various set, sequence, mapping, and other types with significant changes that would be difficult to implement by extending the built-in types themselves, it seems unnecessary to include these "starter" classes for each and every type beyond what is already provided in collections.abc.
Following is a very basic implementation of UserSet with a data attribute that stores the contents of the class in a real set (similar to the approach taken with UserDict and the like). While it might be useful to you to have such an implementation included in the standard library, it is not terribly difficult to implement yourself (and if everything that was potentially "useful" to someone was included in the standard library, Python would become awfully bloated).
from collections.abc import Hashable, MutableSet

class UserSet(Hashable, MutableSet):
    __hash__ = MutableSet._hash

    def __init__(self, iterable=()):
        self.data = set(iterable)

    def __contains__(self, value):
        return value in self.data

    def __iter__(self):
        return iter(self.data)

    def __len__(self):
        return len(self.data)

    def __repr__(self):
        return repr(self.data)

    def add(self, item):
        self.data.add(item)

    def discard(self, item):
        self.data.discard(item)

s = UserSet([1,1,2,3])
print(s)
# {1, 2, 3}

A: I'm not sure whether it is widely known or not but I managed to create and successfully use a subclass of the built-in set without the need to manually manipulate with the underlying data using the self.data attribute or similar. Working with the data is mediated using the self attribute itself. I'm yet to find the drawbacks of such solution.
class IntegerSet(set):
    def sum(self) -> int:
        return sum(self)

iset = IntegerSet((1, 1, 2, 3))
iset.add(4)
print(iset.sum())  # 10


text:
Q: Efficient Way to Create Subcollection From List With Firestore I'm looking for an efficient way to add a List of Documents to a sub collection of elements in Firestore using Flutter. Currently I can do the following:
documents.forEach((doc) => Firestore.instance
          .collection('mainCollection')
          .document('mainDoc')
          .collection('mySubCollection')
          .add(doc));

What I'm wondering is is this the most efficient way to add a list of elements, as this list may be quite large, or is there an operation for this that I can't seem to find. Thanks for any help!

A: You have two options:

*

*Add each document individually.

*Use a batch write, which is limited to 500 documents (see WriteBatch for Flutter).

Any more than 500 documents, and you will not be able to add them all in one operation, as there are no other bulk add operations.  A batch write might be slightly faster than individual inserts. I suggest benchmarking to find out which one is best for your case.

A: The Firestore API doesn't have any addAll that I know of, but you could use a generator function to add each document asynchronously, and know when it's done, because the Stream returned by the generator will be done.


text:
Q: kentico is not able to trim a string, error outOfBoundException I am trying to switch from iframe tag to  tag by taking the src of youtube iframe and use it as a src for  tag, I have already put the video sources as a large string in the page form and split it to smaller parts by this char '|' so each  tag will know which src index he'll have to reference. my problem is that I want to take the image of youtube video by using this format:
https://img.youtube.com/vi/<insert-youtube-video-id-here>/hqdefault.jpg

from the split string, so to get this image i am trying to resplit the source string , to get the video Id (and therefore get the video image) below is my code:
 protected void Page_Load(object sender, EventArgs e)
{

    string [] values = ImageFieldValues.Split('|');
    if (values.Length != 0) {
    foreach (string source in values)
    {

        litCon.Text = "";
        AddToDivImages.Controls.Add(litCon);

    }
    }
}

this is a custom control used within a transformation in kentico project, video sources are loading fine, the only problem is with source.substring(26), it is returning an error saying that index is out of boundaries, it is only working for index (0), any number larger than zero will return the same error, I also tried to trim, split, Remove... its like it is taking the whole string as one block, here is a screenshot for the event log in kentico
Event Logs

A: Without seeing the initial value of ImageFieldValues, it's hard to say why it isn't working.  Could it be that you have an empty string (created by an additional pipe at the end of the string)?  Try using the overload for Split that removes empty entries:
ImageFieldValues.Split(new[] { "|"}, StringSplitOptions.RemoveEmptyEntries);

From the above, I'm assuming that ImageFieldValues looks something like this:
https://www.youtube.com/watch?v=dQw4w9WgXcQ|https://www.youtube.com/watch?v=wZZ7oFKsKzY

Rather than using substrings, you might want to try using a regular expression.  I had a little look and you should be able to achieve what you're with the following:
protected void Page_Load(object sender, EventArgs e)
{
    string pattern = "watch\\?v=(?[A-Za-z0-9_]*)";

    string [] values = ImageFieldValues.Split('|');
    if (values.Length != 0) {
    foreach (var source in values)
    {
        Match match = Regex.Match(source, pattern);

        litCon.Text = "";
        AddToDivImages.Controls.Add(litCon);
    }
}

This removes the reliance on the index you're using for source.Substring, which will protect you if the URL structure varies.  You can find a breakdown of the pattern here if you're not familiar with regular expressions: https://regex101.com/r/3Y0ZNY/1


text:
Q: Why the onclick element will trigger twice for label element

      window.onload = function(){
         var wow = document.getElementById("wow");
      wow.onclick = function(){
          alert("hi");
      }
      }
    <input type="checkbox" name="checkbox" value="value">Text

This is my code, when I clicked on "Text" it will alert hi twice but when I clicked on the box, the onclick element will only trigger once, why?

A: When you click on the label, it triggers the click handler, and you get an alert.
But clicking on a label also automatically sends a click event to the associated input element, so this is treated as a click on the checkbox. Then event bubbling causes that click event to be triggered on the containing element, which is the label, so your handler is run again.
If you change your HTML to this, you won't get the double alert:
<input id="wowcb" type="checkbox" name="checkbox" value="value">
Text

The label is now associated with the checkbox using the for attribute instead of wrapping around it.
DEMO

A: If your intention is to respond only to clicks on the label and not on the checkbox, you can look at the event.target property. It references the element that called the listener so that if the click wasn't on that element, don't to the action:
window.onload = function(){
  var el = document.getElementById('wow');
  el.addEventListener('click', function(event) {

    if (this === event.target) {
      /* click was on label */
      alert('click was on label');

    } else {
      /* click was on checkbox */
      event.stopPropagation();
      return false;
    }

  }, false);
}

If, on the other hand, you want to only respond to clicks on the checkbox (where a click on the label also produces a click on the checkbox), then do the reverse. Do nothing for clicks on the label and let ones from the checkbox through:
window.onload = function(){
  var el = document.getElementById('foolabel');
  el.addEventListener('click', function(event) {

    if (this === event.target) {
      /* click was on label */
      event.stopPropagation();
      return false;

    } else {

      /*
      ** click is from checkbox, initiated by click on label
      ** or checkbox
      */

      alert('click from checkbox');
    }

  }, false);
}

This version seems to have the most natural behaviour. However, changing the markup so that the label no longer wraps the checkbox will mean the listener is not called.

A: Event bubble.
The checkbox is the child node of the label. You click the checkbox. Event bubble to the label. Then alert pop up twice.
To prevent alert pop up twice when you click the checkbox. You can change you onclick function into this:
wow.onclick = function(e){
    alert('hi');
    stopBubble(e);
}

function stopBubble(e)
{
    if (e && e.stopPropagation)
        e.stopPropagation()
    else
        window.event.cancelBubble=true
}

Hope this can work for you.

A: The Label tag will be associated with the input tag inside it. So when you click the label, it will also trigger a click event for the input, then bubble to the label itself.
See this:
document.getElementById("winput").addEventListener('click', function(event){
     alert('input click');

     //stop bubble
     event.stopPropagation();

 }, false);

http://jsfiddle.net/96vPP/

A: Rammed headfirst into this gotcha again and decided to prove what it did to myself, hopefully helping me remember. To help future people to whom the above might not be clear enough, here the example I made.
https://jsfiddle.net/ashes/0bcauenm/
$(".someBigContainer").on("click", "input[type=checkbox]", ()=> {
    $output.val("Clicked: checkbox\n" + $output.val());
});

edit: added the link with a snipped of the code.

A: This is probably the simplest answer. Just add a span around your text and stop event propagation.

window.onload = function(){
    var wow = document.getElementById("wow");
    wow.onclick = function(){
        alert("hi");
    }
}

    <input type="checkbox" name="checkbox" value="value">
    Text

Or without inline-javaScript

window.onload = function(){
    var wow = document.getElementById("wow");
    wow.onclick = function(){
        alert("hi");
    }

    var span = document.getElementsByTagName("span")[0];
    span.onclick = function(event){
        event.stopPropagation();
    }
}

    <input type="checkbox" name="checkbox" value="value">
    Text

A: For those using React and Material UI - I've encountered this issue on one of my forms.  event.preventDefault() is stopping the event from bubbling as described by the accepted answer.
  <Button
    onClick={(event) => {
      event.preventDefault()
      this.handleCardClick(planName)
    }}
  >
    <FormControl component="fieldset">
      <RadioGroup
        row
        value={selectedPlan}
      >
        <FormControlLabel
          control={<Radio color="secondary" />}
          label={label}
        />
      </RadioGroup>
    </FormControl>
  </Button>

A: Use change to listen for events instead of click


text:
Q: delete XML node using javascript in firefox Im trying to delete a node in XML file using Javascript. The used browser is Firefox. Im reaching the node which I want to delete successfuly, then Im trying
delNode.ParentNode.RemoveChild(delNode)
but when i went back to the xml file on my harddisk, the node was still there. I need to delete the whole node (not only children). If someone could guide me to what to do, I'll be so greatful ;)
Thanks

A: That should remove delNode. Are you getting an error? What is the result of delNode.parentNode.removeChild(delNode) ? I do the same thing all the time and it works for me.
I'm sorry I missed the part about writing it back to the file. Use nsiFile to do that and a chrome:// url. In order to take advantage of these things you'll probably have to create a directory with a directory called 'chrome' which will have your script, a chrome.manifest file.

A: Thanks for the help. I couldn't find a way to change the content of the file in javascript so I used PHP. I was trying simply to delete the first node in my xml activity1.xml. Here is the code:
$xdoc = new DomDocument;
$xdoc->Load('images\activity\activity1.xml');
$xdoc->documentElement->removeChild($xdoc->documentElement->childNodes->item(1));
$xdoc->save('images\activity\activity1.xml');

It simply delete the first node whatever children it has ;)


text:
Q: gpg symmetric encryption using pipes I'm trying to generate keys to lock my drive (using DM-Crypt with LUKS) by pulling data from /dev/random and then encrypting that using GPG.
In the guide I'm using, it suggests using the following command:
dd if=/dev/random count=1 | gpg --symmetric -a >./[drive]_key.gpg

If you do it without a pipe, and feed it a file, it will pop up an (n?)curses prompt for you to type in a password.  However when I pipe in the data, it repeats the following message four times and sits there frozen:
pinentry-curses: no LC_CTYPE known assuming UTF-8

It also says can't connect to '/root/.gnupg/S.gpg-agent': File or directory doesn't exist, however I am assuming that this doesn't have anything to do with it, since it shows up even when the input is from a file.
So I guess my question boils down to this: is there a way to force gpg to accept the passphrase from the command line, or in some other way get this to work, or will I have to write the data from /dev/random to a temporary file, and then encrypt that file? (Which as far as I know should be alright due to the fact that I'm doing this on the LiveCD and haven't yet created the swap, so there should be no way for it to be written to disk.)

A: Well...in the end, I decided to just write out to a file, and then encrypt that file, assuming that since there was no swap, and the filesystem was in ram, that it would die with the next shutdown.
However, for the reference of anyone who finds this question (and to cement the idea in my head), I will write down a procedure I found that would work long after I found out when creating the initramfs.
What you need to do is go back to a version of gpg before they started using the external pinentry program for password entry.  As far as I know, that happened with version 2.  Assuming that you have a currently working Linux install, you will want to get a statically compiled version of gpg<2.0.
This is extremely easy to do with Gentoo, only requiring the following command:
USE="static" emerge -a1 "<gnupg-2"

Just make sure to use ldd to confirm that they are in fact static before you copy them to your thumb drive so that you can use them during the install.
On other distributions, I suggest you look @ your package manager, and if that doesn't work, then I would try downloading the sources, and compiling from them.

A: Make sure you own the tty:
# ls -l $(tty)
crw--w----. 1 foo tty 136, 0 Mar  1 16:53 /dev/pts/0
# chown root $(tty)

Set GPG_TTY:
# export GPG_TTY=$(tty)

gpg/pinentry should work after these steps.


text:
Q: Google sheet formula to find missing number based on matching criteria With the data in the attached google sheet, Col F (IN/OUT) will have either IN or OUT and Col J (Bag Numbers) will have numbers seperated by Comma.
Based on the sample data, for Vendor 4-Sunil, Bag numbers 2,3,4,5 where sent OUT on 8/9/21. On 17/9/21, 2,3,4,5 where received IN. So there is nothing Pending with Vendor 4-Sunil.
On the other hand with Vendor 5-Rajan, Bag numbers 13,14,15,16 where sent OUT on 14/9/21. On 25/9/21 Bag Numbers 13,15 where received IN. So the pending bags yet to be received IN from Vendor 5-Rajan is 14,16.
Is there a way to build a formula in Google sheet to indicate the number of pending Bags based on IN or OUT criteria for a given Vendor?
Thank you.
Sample Google sheet
https://docs.google.com/spreadsheets/d/10XP3k4HLteGHgOEdd0YIZR-_0p2IiHog5R7luIM5NeM/edit?usp=sharing

A: To display Bag numbers out, try:
=arrayformula(query({
query({A:J},"select Col5 where Col5 !='' and Col6 contains 'OUT' order by Col5",1),
regexreplace(regexreplace(regexreplace(query({A:J},"select Col10 where Col5 !='' and Col6 contains 'OUT' order by Col5",1),iferror(vlookup(query({A:J},"select Col5 where Col5 !='' and Col6 contains 'OUT' order by Col5",1),{query({A:I,iferror(regexreplace(J:J,",","|"),J:J)},"select Col5, Col10 where Col5 !='' and Col6 contains 'IN' order by Col5",1)},2,0)),""),",+",","),"^,+|,+$",)
},"where Col2 != '' label Col2 'Remaining out' ",1))

If you want a more complex solution running from a single cell that handles multiple OUT and IN for the same Vendor, then try:
=arrayformula({"Vendor","Items still out";regexreplace(query({
query(regexreplace(split(flatten(regexreplace(trim(query(transpose(query(if(E2:E<>"",substitute({E2:E&char(9998)&F2:F&char(9998),J2:J,J2:J}," ",char(9999)),),"select Col1,Max(Col2) where Col1 !='' group by Col1 pivot Col3",)),"",9^9))," ",",")),char(9998)),"^,+|,+$",),"select Col1 where Col2 contains 'OUT' order by Col1",0),
iferror(regexreplace(regexreplace(query(regexreplace(split(flatten(regexreplace(trim(query(transpose(query(if(E2:E<>"",substitute({E2:E&char(9998)&F2:F&char(9998),J2:J,J2:J}," ",char(9999)),),"select Col1,Max(Col2) where Col1 !='' group by Col1 pivot Col3",)),"",9^9))," ",",")),char(9998)),"^,+|,+$",),"select Col3 where Col2 contains 'OUT' order by Col1",0),iferror(vlookup(
query(regexreplace(split(flatten(regexreplace(trim(query(transpose(query(if(E2:E<>"",substitute({E2:E&char(9998)&F2:F&char(9998),J2:J,J2:J}," ",char(9999)),),"select Col1,Max(Col2) where Col1 !='' group by Col1 pivot Col3",)),"",9^9))," ",",")),char(9998)),"^,+|,+$",),"select Col1 where Col2 contains 'OUT' order by Col1",0),
{regexreplace(query(regexreplace(split(flatten(regexreplace(trim(query(transpose(query(if(E2:E<>"",substitute({E2:E&char(9998)&F2:F&char(9998),J2:J,J2:J}," ",char(9999)),),"select Col1,Max(Col2) where Col1 !='' group by Col1 pivot Col3",)),"",9^9))," ",",")),char(9998)),"^,+|,+$",),"where Col2 contains 'IN' order by Col1",0),",","|")}
,3,0),),),"^,+|,+$",),)
},"where Col2 !='' ",0),char(9999)," ")})


text: Q: What are the methods of dynamic hashing? I'm new to this topic and I have a question. Google does not help, finds only linear hashing and dynamic resizing. What other methods exist? Or I something not so understand?


text:
Q: Octave Error: Subscript indices must be integers or boolean I was trying to solve a system of non-linear equations and check the stability of its equilibrium points. Initially, I declared two equations
adot = -a + 2*a^3 + b
bdot = -a -b

By equating both the equations with 0, I get the equilibrium points. Now, I am trying to get the Jacobian of the [adot;bdot] matrix using the jacobian([adot;bdot],[a,b]) method of symbolic package in Octave, which should just return a matrix whose items are the partial derivatives of "adot" and "bdot" w.r.t. "a" and "b", but it gives the following error
error: subscript indices must be integers or boolean

Can anyone tell me where I'm going wrong with this?
Edit: I'm adding the complete code down below:
pkg load symbolic

syms x y

xdot = -x + 2*x^3 + y;
ydot = -x - y;

[xeq,yeq] = solve(xdot==0,ydot==0);

xeq = double(xeq);
yeq = double(yeq);

jacobian_matrix = jacobian([xdot;ydot]);

At this point I'm getting the above mentioned error. The values in the [xeq,yeq] matrix are the equilibrium points of the system, which are to be used later on.


text:
Q: Better way to test .htaccess file I don't have much experience with htaccess rules, some of them are working but when I add a new rule or remove one, how do I test them?? I cannot test it on the actual server. Even in my localhost, I won't be able to test some like https rules, www and other stuff.
I can test the rest of url patterns but when I add the www and https rules along with the tested ones on the live server, it gives an error and then I continue testing them on the live server.
Is there a way to test them without using the actual server and not create another server for testing those rules. Something like a htaccess rule checker or something!?

A: There are a few web based testers available to use, unfortunately, these don't always understand all the syntax to accurately check how it works on a real site.
One web based one I like to use is this online tester from Made with Love;  http://htaccess.madewithlove.be/
It doesn't understand a few items such as %{REQUEST_FILENAME} but for general testing I think it should do the job for you. You copy your code into the box, and you can also submit a url to see what it will rewrite to. If you just want to check syntax errors there are a few web tools available as well.
Using web based tools are great for an overall check, but you can't really be sure how it affects a real site until you upload it either to a dev version of the real thing.
Just recently I've edited a htaccess file, which showed no syntax errors and worked as expected on the tester, which did not work at all on the real site. Site settings may have an impact and all other things which will not show on a web tool.

A: I tested a couple of .htaccess rules on local server and 1 of them didn't work. The system gave a 500 Internal Server Error message so I was very confused: This is the one that didn't work:
# Prevent search engines from indexing some files
<FilesMatch "^(about-cosma.html|footer.html|menu.html|acerca-de-cosma.html|es-footer.html|es-menu.html)">
Header set X-Robots-Tag "noindex, nofollow"
</FilesMatch>

I was about asking in Stackoverflow why it didn't work but then I decided to test it live and it worked perfectly.


text:
Q: Spring integartion LoggingHandler logs all messages to Error I created a spring boot application that sends Messages through a PublishSubscribeChannel. This Channel is "autowired" as SubscribableChannel interface.
I am only subscribing one MessageHandler to this channel, a KafkaProducerMessageHandler.
My problem is that one additional MessageHandler is subscribed and this is an LoggingHandler. It is instantiated with ERROR level. So i see every message logged es error.
I want to know why and where this LoggingHandler is wired (instantiated) and why it is subscribed to the channel - i want to disable it.
(
I debugged around a bit but (was not really helpful):
The LoggingHandler is instantiated and subscribed after the KafkaHandler.
I see this chain EventdrivenConsumer.doStart()<-- ``ConsumerEndpointFactoryBean.initializeEndpoint()<-- ... until reflective calls
)
EDIT
As suggested in comments here is some code (i can't share the whole project). My problem is that the code can't explain the behavior. The LoggingHandler is beeing subscribed to my PublishSubscribeChannel for some unknown reason and it is instantiated with error as level for some unknown reason.
The class that subscribes the KafkaHandler:
@Component
public class EventRelay  {

    @Autowired
    private EventRelay( SubscribableChannel eventBus, @Qualifier( KafkaProducerConfig.KAFKA_PRODUCER ) MessageHandler kafka ) {

        eventBus.subscribe( kafka );

    }
}

The class that send events is implementing an proprietary interface with many callback methods:
public class PropEvents implements PropClass.IEvents {

    private SubscribableChannel eventBus;
    private final ObjectMapper om;
    private final String userId;

    public PropEvents( SubscribableChannel eventBus, ObjectMapper om, String userId ) {

        this.eventBus = eventBus;
        this.om = om;
        this.userId = userId;
    }

    @Override
    public void onLogin(  ) {
                 eventBus.send( new OnLoginMessage(... ) ) );
    }
    //many other onXYZ methods
}

Here is the Factory that produces instances of PropEvents:
@Configuration
public class EventHandlerFactory {

    private final ObjectMapper om;
    private final SubscribableChannel eventBus;

    @Autowired
    public EventHandlerFactory( ObjectMapper om, SubscribableChannel eventBus){
        this.om = checkNotNull( om );
        this.eventBus = checkNotNull( eventBus );
    }

    @Bean
    @Scope( SCOPE_PROTOTYPE)
    public IEvents getEvantHandler(String userId){
        if(Strings.isNullOrEmpty(userId)){
            throw new IllegalArgumentException( "user id must be set." );
        }
        return new PropEvents(eventBus, om, userId);
    }

}

I appreciate any help with debugging or use tooling (e.g. Eclipse Spring tools does not show any hint to a LoggingHandler Bean) to find where and why a LoggingHandler is instantiated and subscribed to my autowired Channel.
My current workaround is to disable logging for LoggingHandler.
My question at a glance
Why spring instantiates an LoggingHandler with error level and subscribes it to my SubscribableChannel(provided by PublishSubscribeChannel)? How to disable this?

A: When you @Autowired SubscribableChannel, there should be one in the application context. That might be confusing a bit and mislead, but Spring Integration provides a PublishSubscribeChannel for the global errorChannel: https://docs.spring.io/spring-integration/docs/5.0.2.RELEASE/reference/html/messaging-channels-section.html#channel-special-channels
This one has a LoggingHandler to log error as a default subscriber.
I don't think that it is OK to make your logic based on the errorChannel.
You should consider to declare your own MessageChannel bean and inject it by the particular @Qualifier.


text:
Q: What happened with the manifest file of android? I have update android studio version 3.2.
After that, some gradle files are also converted with this type of encoding:

Thanks for your help.

A: Add systemProp.file.encoding=UTF-8 to gradle.properties to fix all encoding problems.


text:
Q: Read from System.in from another Thread I'm currently developing a console application, which observes multiple directories with the Java 7 WatchService API.
While in the main method the observation loop takes place, I want a separate thread to read from the System.in stream to check whether the observation must stop.
My Runnable implementation looks like this:
public class InputHandler implements Runnable {
    @Override
    public void run() {
        boolean keepRunning = true;
        int readBytes = -1;
        byte[] readChunk = new byte[8];

        System.out.println("Starting directory observation ...");
        System.out.println("Type 'stop' to end directory observation.\n");

        while (keepRunning) {
            try {
                readBytes = System.in.read(readChunk);

                if (readBytes > 4) {
                    keepRunning &= !(new String(readChunk).contains("stop"));
                }
            } catch (Exception e) {
                System.err.println("Failed to read input!");
                keepRunning = false;
            }
        }

        System.out.println("\nDirectory observation stops now ...");
    }
}

My main method does this:
// Prepare the WatchService stuff ...
Thread ihThread = new Thread(new InputHandler());

do {
    WatchKey watchKey = directoryWatch.take();

    for (WatchEvent<?> event : watchKey.pollEvents()) {
        if (StandardWatchEventKinds.ENTRY_CREATE.equals(event.kind())) {
            // do something
        }
    }

    keepRunning &= !Thread.State.TERMINATED.equals(ihThread.getState())
            && watchKey.reset();
} while (keepRunning);

When I run the code, no message is printed and I can't write anything in the command line. How can I access the 'main' System.in and System.out from the new thread?


text:
Q: How do i create a direct message in django channels I have watched a couple of tutorials on Django channels but i can't figure out how to create a direct message in my website.
Every tutorial's always creating a room and then adding multiple users.
I want to build a message system whereby users can message other users i.e only 2 participant.
Like a p2p message


text:
Q: c# convert a string of 1's and 0's to a sequence of bits I am currently involved in image compression using Huffman model. At this point I have achieved compression and decompression but there is the following problem:
I use a text file to store the ones and zeros. However this is not really a compression as I need to store the ones and zeros as bits and not ascii characters. So the question is how do I convert a string of 1 and 0 into a sequence of bits? Attention: every 1 and 0 is a simple bit. Example: "10" into 10 as bits.
P.S. The language Iam using is C#


text:
Q: crontab won't run os.system python command Using ubuntu's 16.04 crontab and @reboot to run python3 script.  The script runs properly on reboot as I see the logged output.  However, my script's os.system command is not running.  It runs fine if ran outside of crontab.  My scripts are all executable.
crontab -l output:
SHELL=/bin/bash
@reboot nohup /usr/bin/python3 -u /home/path/scheduler.py >> /path/log.out &

scheduler.py code:
#...(check if web server is running...if not restart)
os.system('nohup /usr/bin/python3 -u /path/webserver/main.py &')
print('this function ran')

When I logged the output of the os.system command , there was no output.
As a side note, I am running python schedule commands to check the general health of a webserver.  crontab doesn't seem to be the right tool for this so I just use crontab to start my python scheduler on reboot.
I am using flask as the webserver, and would use gunicorn and systemctrl if I could get it to work... but it didn't so this is my workaround.

A: The point is that, the command called by os.system is not in default path.
For example, tcpdump is not in /usr/bin/.
So, you can solve the problem by adding the full path of the command.

A: I was facing the same issue when we try to run python script directly in crontab it just by passes the os.system() commands.
Make launcher.sh:
#!bin/bash
cd /home/pi/
sudo python example.py

Then, make your script executable:
chmod 755 launcher.sh

And at last, add your script to crontab:
crontab -e

and add this line at the end:
@reboot sh /home/pi/launcher.sh
(I set the program to run at each reboot)


text:
Q: How to redirect to prefixed path in Expressjs Router I am deploying an app in a specific path say under /path.
// login form
router.get('/login', function (req, res) {
})
router.post('/login', function(req, res) {
  if (success) {
     res.redirect('/') // <<--- does not direct to /path
  }
})
// install router under path
app.use('/path', router)

So I can navigate to http://.../path/login
and after logged in, I want to redirect the user to the / under /path.
I don't want to hardcode /path and only use relative path since router has already been mounted under path.
Is it possible? How to do that?

A: If you want to redirect a user to the mount path (in this case, /path) without hardcoding it, you can use req.baseUrl:
res.redirect(req.baseUrl + '/');

The + '/' is optional for nested routers, but it's necessary for the application-level router because it has an empty req.baseUrl. Alternatively (if you don't want to add a trailing slash), you can use this (if you also want it to work in the application-level router):
res.redirect(req.baseUrl || '/');


text:
Q: Minecraft: question about loot tables I want to make datapack that changes amount of items dropped from mined blocks and killed mobs by player, in range from 1 to 1024 for example, how can it be done?
I know how to change dropped items to a specific amount and not range for one block, how can I make it for range and make it for all blocks and mobs?
Basically this is something like in this video:

A: This is done via the min and max properties. Here is an example of a loot table that drops 1-1024 diamonds:
{
    "pools": [
        {
            "rolls": 1,
            "entries": [
                {
                    "type": "item",
                    "name": "minecraft:diamond",
                    "functions": [
                        {
                            "function": "minecraft:set_count",
                            "count": {
                                "min": 1,
                                "max": 1024
                            }
                        }
                    ]
                }
            ]
        }
    ]
}

Since there is no way to apply a single loot table to all blocks and mobs, you need to create a loot table like this for every block and mob.


text:
Q: Heavy ContentProvider query and ListView Sorry for a probably noob question, but couldn't find the answer despite studying numerous tutorials and other questions here on SO.
What I want to do is fairly simple: display an Android ListView with a lot of database-stored strings. And by "a lot" I mean up to 100MB, but the ListView should start displaying things without delay.
The context is: this is the note management app, and by default it should display all user's notes unfiltered. I'm studying how the app will behave if there are a lot of notes.
Now I use the recommended approach with the Loader framework: kicking off a ContentProvider query in onCreateLoader, and assigning the resulting Cursor to the ListView's adapter in onLoadFinished.
Still this is painfully slow (initial load up to 10s). I've studied the sources of Cursor and know that it keeps a "window" of data, so that not all 100MB of text should be loaded at once. However it seems that this is the case.
I thought this to be a fairly common task, and am surprised not to find any good information on it. This is the critical part of the app, and I want to get it right from the start - it will be difficult to refactor this later.
So could anyone please help with this? Is lazy loading the answer? Why doesn't Cursor do it itself? How to do it properly - do I have to cache an array of IDs first and load chunks upon scrolling?
Thanks!

A: SimpleCursorAdapter + CursorLoader should work just fine, seems that your db query is that slow, most likely you want to sort the data on unindexed field


text:
Q: Apple Mail not showing attachments correctly from PHP I am trying to send HTML emails with attachments from Opencart. There is a built in function $mail->addAttachment. Everything is fine, except that on the place of the attachment is a white box in Apple Mail. In iOs Mail app the attachment is not showing at all. On GMail it's ok:

The attachment is available in Apple Mail too, because if I double click on the white area, the attachment is opening.
Here is the source of the message, opened in GMail (I removed X headers):
X-Mailer: PHP/5.4.39-0+deb7u2
Content-Type: multipart/related; boundary="----=_NextPart_fefb9509ef8523a96a17066ecf8472c8"

------=_NextPart_fefb9509ef8523a96a17066ecf8472c8
Content-Type: multipart/alternative; boundary="----=_NextPart_fefb9509ef8523a96a17066ecf8472c8_alt"

------=_NextPart_fefb9509ef8523a96a17066ecf8472c8_alt
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 8bit

Some text (text/plain)

------=_NextPart_fefb9509ef8523a96a17066ecf8472c8_alt
Content-Type: text/html; charset="utf-8"
Content-Transfer-Encoding: 8bit

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/1999/REC-html401-19991224/strict.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
                <title>Test title</title>

Some html text(text/html)

------=_NextPart_fefb9509ef8523a96a17066ecf8472c8_alt--
------=_NextPart_fefb9509ef8523a96a17066ecf8472c8
Content-Type: application/pdf; name="form.pdf"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="form.pdf"
Content-ID  <%2Fhome%2Fhtml%2Fdownload%2form.pdf>
X-Attachment-Id: %2Fhome%2Fhtml%2Fdownload%2form.pdf

JVBERi0xLjMKJcTl8uXrp/Og0MTGCjQgMCBvYmoKPDwgL0xlbmd0aCA1IDAgUiAvRmlsdGVyIC9G
bGF0ZURlY29kZSA+PgpzdHJlYW0KeAGdW0tzHLcRvs+vQGInGbqk0bwfuTl2qqKkbMkRk1Q58mFJ
jkJylzvS7pIu8Q/o5oMuLlfpmB+Un5SvHwDmtdylSyXNAgM0uhuN7q8bo3fmO/POxPhTNIWp89Rs
WvMvszbPvtom5nxrEv6zPccIenvjxq34V2xWPHsVXJo3TCtLoiYr49ykdZQVpsjqqKqqxlR1GWWW
+jtQpUUTk5WmKjNzfmP+dGr+fAoStHKAlel9bLCyH1ympspqHRxHcRwn5vTcJDkP1cfpjXl2ekp8
...
------=_NextPart_fefb9509ef8523a96a17066ecf8472c8--

Relevant part from /system/library/mail.php:
foreach ($this->attachments as $attachment) {
            if (file_exists($attachment)) {
                $handle = fopen($attachment, 'r');

                $content = fread($handle, filesize($attachment));

                fclose($handle);

                $message .= '--' . $boundary . $this->newline;
                $message .= 'Content-Type: application/pdf; name="' . basename($attachment) . '"' . $this->newline;
                $message .= 'Content-Transfer-Encoding: base64' . $this->newline;
                $message .= 'Content-Disposition: attachment; filename="' . basename($attachment) . '"' . $this->newline;
                $message .= 'Content-ID: <' . basename(urlencode($attachment)) . '>' . $this->newline;
                $message .= 'X-Attachment-Id: ' . basename(urlencode($attachment)) . $this->newline . $this->newline;
                $message .= chunk_split(base64_encode($content));
            }
        }

EDIT:
I just realized that Content-ID and X-Attachment-Id was the problem:
basename(urlencode($attachment)

should be:
urlencode(basename($attachment))

It works fine in Apple Mail now, but the attachment still missing on iOS (iPhone/iPad). Any idea?

A: Headers must be like this:
MIME-Version: 1.0
Content-Type: multipart/alternative; boundary=boundary42

In most cases found missing mime version tag. You have error in boundaries let me first give rules body of a multipart entity has the syntax (only the important parts):

 multipart-body := [preamble CRLF]
                   dash-boundary transport-padding CRLF
                   body-part *encapsulation
                   close-delimiter transport-padding
                   [CRLF epilogue]
 dash-boundary := "--" boundary
 encapsulation := delimiter transport-padding
                  CRLF body-part
 delimiter := CRLF dash-boundary
 close-delimiter := delimiter "--"

The preceeding -- is mandatory for every boundary used in the message and the trailing -- is mandatory for the closing boundary (close-delimiter). So a multipart body with three body-parts with boundary as boundary can look like this:
--boundary42
Content-Type: text/plain; charset=us-ascii

...plain text version of message goes here....

--boundary42
Content-Type: text/richtext

.... richtext version of same message goes here ...

--boundary42
Content-Type: text/x-whatever

.... fanciest formatted version of same  message  goes  here...

--boundary42--

Read the document RFC


text:
Q: How to test an animation that has same start and endpoint? I have a component that "shakes" when animated prop is set to true. This is how it looks
const Shake = ({ animate, children, ...props }) => {
  const { x } = useSpring({
    from: { x: 0 },
    x: animate ? 1 : 0,
    config: { mass: 12, tension: 500, friction: 80 },
  });
  return (
    <animated.div
      style={{
        transformOrigin: 'center center',
        transform: animate && x
          .interpolate({
            range: [0, 0.5, 1],
            output: [0, 2, 0],
          })
          .interpolate((x) => `rotate(${x}deg)`),
      }}
      {...props}
    >
      {children}
    </animated.div>
  );
};

Animations I tested before were more or less just transitions from one state to another, like opacity from 0 to 1. It was easy to test with react-testing-library, I just called the .toHaveStyle assertion from jest-dom.
However on this component my animation uses a combination of range and output. At first it will start by rotation of 0deg, then it goes to 0.5deg and finally back to 0deg. So just using
.toHaveStyle(`transform: rotate(0deg)`)

could be a false positive because the animation might not even be triggered.
This animation is spring based, powered by react-spring, and not time based so I cannot say exactly when the middle of the animation is triggered.
Does anybody have an idea to solve this?


text:
Q: SQL(Joining tables Query) Course_info table:

-----------------------------------------------
 COURSE_ID    COURSE_NAME          COURSE_DURATION
----------   -------------------- ---------------
     6      SQL                                3
     7      PF                                12
     8      JAVA                              13
     9      C                                  2
     0      UNIX                               4

FACULTY_INFO table:

-------------------------------------------------------------
FACULTY_ID   FACULTY_NAME         LOCATION             EXPERIENCE
---------- -------------------- -------------------- ----------
     1   ABC                  DELHI                        10
     2   DEF                  NOIDA                         4
     3   GHI                  GGN                           2
     4   JKL                  HYD                           1
     5   MNO                  GOA                          25

Paper_info table:

FACULTY_ID  COURSE_ID DIFFICULTY_LEVEL     NO_OF_PAPER SUBMITTED
---------- ---------- -------------------- -----------
         1          8 DIFFICULT                      1
         2          9 STANDARD                       5
         3          8 DIFFICULT                      2
         4          7 STANDARD                       5
         5          7 STANDARD                       8

Now the query is to retrieve the course_id for which no papers were submitted.
This query:
select c.course_id
from course_info c, paper_info p
where c.course_id <> p.course_id;

gives:

COURSE_ID
-------------
6
8
7
9
0 (But 6,7 are not present in course_id of paper_info)

Second query:
select c.course_id
from course_info c, paper_info p
where c.course_id not in (select course_id from paper_info);

Output:

0
6  (Working fine)

Whats the difference between the two queries?

A: The difference between the two is that the second query will exclude the course_id in paper_info. The first query will make a comparison between the two table and the include those that meets your condition.
For example:
Course_info with course_id 8 is equal (has a relation) to paper_info with course_id equal 8. Because of that, that relation will not be included in your results due to your where clause.
However course_id 8 in course_info is not equal to course_id 9 in paper_info. Because of that, that relation will be included. Which is why you see 9 in that first query.
What you should have done was a left join on c.course_id = p.course_id where p.course_id is null

A: <> in sql means "Not Equal To".
Basically in compares two expressions, returns TRUE if left operand "Not Equal To" right operand. Otherwise FALSE. Remember: In any valid expression. Both expressions must have implicitly convertible data types.
In above example, each COURSE_ID in Course_Info table will be compared with every COURSE_ID in Paper_Info table. Because right hand expression is not a single integer value. It is set of all COURSE_ID's of Paper_Info table, compared one at each time. So I think output will be as below
6
6
6
6
6
7
7
7
8
8
8
9
9
9
9
0
0
0
0
0
Correct me, If I am wrong. Thanks!


text:
Q: Mercurial extension or hook to prevent backout of merge changesets As noted in the documentation, the hg backout command can cause problems when used with merge changesets. We have had a couple of cases recently of newer developers backing out merge changesets and causing code that we wanted to keep to be reverted when everything gets merged back together.
To avoid this, I'm trying to think of a good way to prevent this from happening at all. Is there a good general way I could write a hook or just disable the backout command entirely?
(Part of our standard developer setup is to install a custom set of extensions, so I already have a good way to install these types of rules locally for our entire development team -- I just haven't thought of a good way to implement the ruleset.)

A: What about this:
$ hg --version
Mercurial Distributed SCM (version 2.6.3)
...
$ hg log --graph --template='{rev} {desc}'
@  5 c5
|
o    4 merge
|\
| o  3 c4
| |
o |  2 c3
|/
o  1 c2
|
o  0 c1

$ hg backout 4
abort: cannot backout a merge changeset

So it looks like Mercurial does what you want by default. Maybe you need a more recent Mercurial version.
If you are stuck to an old Mercurial version, here is a hacky hook (for *nix/Bash) which aborts backouts of merges:
[hooks]
pre-backout=REV=`echo $HG_PATS | sed -e "s/[^0-9]//g"`; test `hg log -r "parents($REV)" --template='{node}\n' | wc -l` -eq 1 || { echo 'do not do that'; exit 1; }

It extract the revision number from $HG_PATS and then uses hg log and wc to count the number of parents of the revision in question. If there is more than one parent, it is a merge.
Still, I highly recommend to use a recent Mercurial: check the release notes for exciting features you are missing.

A: Here's a simple Python-based hook that prevents backout of merges. Credit goes to @Oben for pointing me in the right direction.
def prebackout_prevent_backout_merge( ui, repo, **kwargs ):
    '''Don't allow backouts to of merge changesets.'''

    # Figure out if a --parent version was given or not.
    backout_to_parent = kwargs['opts'].get( 'parent', None )

    # If no parent version was given, proceed.
    if backout_to_parent is '':
        return False

    # Otherwise abort the operation.
    from mercurial import util
    raise util.Abort( 'Backout of a merge changeset is not allowed.' )

You can configure this hook in .hgrc or Mercurial.ini with:
[hooks]
pre-backout.ttd_prevent_backout_merge = python:PATH_TO_HOOK_SCRIPT:prebackout_prevent_backout_merge


text:
Q: Possibly upgraded Windows 7 to Windows 10, but Win7 product key still works? I wish to install Windows 7 on my mac. I had a copy of Win7 years ago, and I believe I allowed the automatic upgrade to Win10 to happen, on my current PC. Tonight I entered my old Win7 product key here:
https://www.microsoft.com/en-gb/software-download/windows7
...and it validates, and allows me to download a Win7 disc image file.
Questions are... 1) Shouldn't that product key have expired for Win7? 2) Is there any scenario where my Win7 product key might be available to use (unassigned)?
Thanks for any advice in advance. I'm just trying to get a totally legal Win7 installation, wouldn't mind paying.


text:
Q: Is there any compiler and library where strcmp() returns values other than -1 0 and 1? Though the common sense and literature is clear about the behaviour of strcmp():

int strcmp( const char *lhs, const char *rhs );

Negative value if lhs appears before rhs in lexicographical order.
Zero if lhs and rhs compare equal.
Positive value if lhs appears after rhs in lexicographical order.

I can't seem to make it return any values other than -1, 0 and 1.
Sure it is true that the behaviour is consistent with the definition but I was expecting values bigger or smaller than 1 or -1 since the definition asserts that results will be <0, 0 or >0, not -1, 0 or 1.
I tested this in several compilers and libraries with the same results. I would like to see an example where that's not the case.
sample code
#include <stdio.h>
#include <string.h>

int main()
{
   printf("%d ", strcmp("a", "a"));
   printf("%d ", strcmp("abc", "aaioioa"));
   printf("%d ", strcmp("eer", "tsdf"));
   printf("%d ", strcmp("cdac", "cdac"));
   printf("%d ", strcmp("zsdvfgh", "ertgthhgj"));
   printf("%d ", strcmp("abcdfg", "rthyuk"));
   printf("%d ", strcmp("ze34", "ze34"));
   printf("%d ", strcmp("er45\n", "io\nioa"));
   printf("%d", strcmp("jhgjgh", "cdgffd"));
}

Result: 0 1 -1 0 1 -1 0 -1 1

A: The specification says that the numbers have to be negative, zero or positive, but it doesn't lock down the exact value necessary. The library itself may behave in more specific ways.
The spec means that code like this is technically invalid:
if (strcmp(a, b) == 1)

This may "work on my machine" but not someone else's who uses a different library.
Where what you should be writing is:
if (strcmp(a, b) > 0)

That's all it really means: expect values other than just 1/-1 and code accordingly.

A: The C standard clearly says (C11 §7.24.4.2 The strcmp function):

The strcmp function returns an integer greater than, equal to, or less than zero, accordingly as the string pointed to by s1 is greater than, equal to, or less than the string pointed to by s2.

It doesn't say how much greater than or less than zero the result must be; a function that always returns -1, 0 or +1 meets the standard; so does a function that sometimes returns values with a magnitude larger than 1, such as -27, 0, +35.  If your code is to conform to the C standard, it must not assume either set of results; it may only assume that the sign of the result is correct.
Here is an implementation of strcmp() — named str_cmp() here so that the result can be compared with strcmp() — which does not return -1 or +1:
#include <string.h>
#include <stdio.h>

static int str_cmp(const char *s1, const char *s2)
{
    while (*s1 == *s2 && *s1 != '\0')
        s1++, s2++;
    int c1 = (int)(unsigned char)*s1;
    int c2 = (int)(unsigned char)*s2;
    return (c1 - c2);
}

int main(void)
{
   printf("%d ", strcmp("a", "a"));
   printf("%d ", strcmp("abc", "aAioioa"));
   printf("%d\n", strcmp("eer", "tsdf"));

   printf("%d ", str_cmp("a", "a"));
   printf("%d ", str_cmp("abc", "aAioioa"));
   printf("%d\n", str_cmp("eer", "tsdf"));
   return 0;
}

When run on a Mac (macOS Mojave 10.14.6; GCC 9.2.0; Xcode 11.13.1), I get the output:
0 1 -1
0 33 -15

I did change your data slightly — "aaioioa" became "aAioioa".  The overall result is no different (but the value 33 is bigger than you'd get with the original string) — the return value is less than, equal to, or greater than zero as required.
The str_cmp() function is a legitimate implementation and is loosely based on a historically common implementation of strcmp().  It has slightly more care in the return value, but you can find two minor variants of it on p106 of Brian W Kernighan and Dennis M Ritchie
The C Programming Language, 2nd Edn (1988) — one using array indexing, the other using pointers:
int strcmp(char *s, char *t)
{
    int i;
    for (i = 0; s[i] == t[i]; i++)
        if (s[i] == '\0')
            return 0;
    return s[i] - t[i];
}

int strcmp(char *s, char *t)
{
    for ( ; *s == *t; s++, t++)
        if (*s == '\0')
            return 0;
    return *s - *t;
}

The K&R code might not return the expected result if the plain char type is signed and if one of the strings contains 'accented characters', characters from the range -128 .. -1 (or 0x80 .. 0xFF when viewed as unsigned values).  The casting in my str_cmp() code treats the data as unsigned char (via the cast); the (int) cast isn't really necessary because of the assignments.  The subtraction of two unsigned char values converted to int produces a result in the range -255 .. +255.  However, modern versions of the C library don't use the direct subtraction like that if they return only -1, 0 or +1.
Note that the C11 standard §7.24.4 String comparison functions says:

The sign of a nonzero value returned by the comparison functions memcmp, strcmp, and strncmp is determined by the sign of the difference between the values of the first pair of characters (both interpreted as unsigned char) that differ in the objects being compared.

You can look at How do I check if a value matches a string?. The outline there shows:

if (strcmp(first, second) == 0)    // first equal to second
if (strcmp(first, second) <= 0)    // first less than or equal to second
if (strcmp(first, second) <  0)    // first less than second
if (strcmp(first, second) >= 0)    // first greater than or equal to second
if (strcmp(first, second) >  0)    // first greater than second
if (strcmp(first, second) != 0)    // first unequal to second

Note how comparing to zero uses the same comparison operator as the test you're making.
You could (but probably shouldn't) write:
if (strcmp(first, second) <= -1)    // first less than second
if (strcmp(first, second) >= +1)    // first greater than second

You'd still get the same results, but it is not sensible to do so; always comparing with zero is easier and more uniform.
You can get a -1, 0, +1 result using:
unsigned char c1 = *s1;
unsigned char c2 = *s2;
return (c1 > c2) - (c1 < c2);

For unrestricted integers (rather than integers restricted to 0 .. 255), this is safe because it avoids integer overflows whereas subtraction gives the wrong result.  For the restricted integers involved with 8-bit characters, overflow on subtraction is not an issue.

A: Please re-read this bit

Negative value if lhs appears before rhs in lexicographical order.

Is -1 sufficient for this statement to be true?

Zero if lhs and rhs compare equal.
Positive value if lhs appears after rhs in lexicographical order.

Is 1 sufficient for this statement to be true?
So the sample code is acting as per spec.
EDIT
Just test the return value for zero, less than zero or more than zero. As per spec this should work in all implementations.
EDIT 2
I think this will fulfull the spec - have not tested :-(
 for (size_t i = 0; s1[i] && s2[i] &&s1[i] == s2[i]; ++i) {
     // Empty
   }
   return s2[i] - s1[i]; // This may be the wrong way around

This will return values other that 1, -1 or 0.

A: Here are a few examples of C libraries with strcmp() implementations that do not always return -1, 0 or +1:
The Bionic libc has a BSD based implementation of strcmp():
int
strcmp(const char *s1, const char *s2)
{
    while (*s1 == *s2++)
        if (*s1++ == 0)
            return (0);
    return (*(unsigned char *)s1 - *(unsigned char *)--s2);
}

The Dietlibc does the same. It is even non conforming version if configured for WANT_SMALL_STRING_ROUTINES:
int
strcmp (const char *s1, const char *s2)
{
#ifdef WANT_SMALL_STRING_ROUTINES
    while (*s1 && *s1 == *s2)
        s1++, s2++;
    return (*s1 - *s2);
#else
    // a more advanced, conforming implementation that tests multiple characters
    // at a time but still return the difference of characters as unsigned bytes
#endif
}

Glibc has this implementation of strcmp in its generic directory, used for exotic architectures:
int
strcmp (p1, p2)
     const char *p1;
     const char *p2;
{
  register const unsigned char *s1 = (const unsigned char *) p1;
  register const unsigned char *s2 = (const unsigned char *) p2;
  unsigned reg_char c1, c2;

  do
    {
      c1 = (unsigned char) *s1++;
      c2 = (unsigned char) *s2++;
      if (c1 == '\0')
    return c1 - c2;
    }
  while (c1 == c2);

  return c1 - c2;
}

Musl C library has a very compact implementation:
int strcmp(const char *l, const char *r)
{
    for (; *l==*r && *l; l++, r++);
    return *(unsigned char *)l - *(unsigned char *)r;
}

The newlib has this implementation:
int
_DEFUN (strcmp, (s1, s2),
    _CONST char *s1 _AND
    _CONST char *s2)
{
#if defined(PREFER_SIZE_OVER_SPEED) || defined(__OPTIMIZE_SIZE__)
  while (*s1 != '\0' && *s1 == *s2)
    {
      s1++;
      s2++;
    }

  return (*(unsigned char *) s1) - (*(unsigned char *) s2);
#else
  // a more advanced approach, testing 4 bytes at a time, still returning the difference of bytes
#endif
}

Many alternative C libraries seem to follow the same pattern and return the difference of bytes, which matches the specification. But the implementations you tested seem to consistently return -1, 0 or +1. Don't rely on this. It might change in future releases, or even with the same system using different compilation flags.


text:
Q: How to disable HTML email from adjusting with Dark mode? I'm new to HTML codes in general. I'm trying to create an HTML email using this template. Things are working fine except for one thing: the email colors are changing when my phone is on dark mode. How can I disable that?

A: Many people desire to have their phones or computers in a dark mode/theme for readability, battery-saving, and/or reduced eye strain. You should not seek to remove this.
Furthermore, the current landscape of email clients is such that you cannot necessarily control this.
Specifically, we cannot change Outlook 2019 (Windows) or Gmail.
See the full writeup on Litmus https://litmus.com/blog/the-ultimate-guide-to-dark-mode-for-email-marketers


text:
Q: WPF and ClickOnce MSDN does not list a WPF .exe as a supported type of application for ClickOnce

A ClickOnce application is any Windows Presentation Foundation
  (.xbap), Windows Forms (.exe), console application (.exe), or Office
  solution (.dll) published using ClickOnce technology.

http://msdn.microsoft.com/en-us/library/t71a733d.aspx
I do find evidence around the web that non-XBAP WPF apps work with ClickOnce, but are they officially supported?

A: Yes, ClickOnce does support WPF applications compiled to executables. ClickOnce is nothing more than an installation distribution method. The primary difference between creating an installation package and ClickOnce (other than being web-based) is that ClickOnce applications are installed within obfuscated folders within the end user's Windows directory.
The means that ClickOnce applications can be installed with a non-administrator account. The caveat to this method is that an application can not be installed on a PC and shared across other user accounts on the PC-- each user must re-install the application.
WPF requires the .NET 3.0+ framework. When you publish your ClickOnce application, you will need to include the .NET 3.0 (or 4.0) framework. Once you add the prerequisite to your project, ClickOnce will check the user's PC to see if the framework is installed. If not, it will pre-install it before installing and running your application. If it already exists, it will skip the download and installation of the framework.
If you need to install a third-party library or application, custom pre-requisites can be created and added to your projects. It is worth noting, prerequisites may need to be installed by an administrator, depending on the rights of the end user. This may seem a bit counter-intuitive, but it's just the nature of the installation process.
ClickOnce is a very simple, but robust installation mechanism, and I've used it extensively. It's not appropriate for every circumstance, but it can certainly accomplish what you are asking.

A: For ClickOnce, there is no difference between a Windows Forms executable and a WPF executable. Both are .NET executables and as such fully supported by ClickOnce...
I have personally deployed several WPF desktop applications using ClickOnce, and it worked exactly the same as with my Windows Forms applications...


text:
Q: Creating a WCF webservice with a single standard response object I've been asked to implement a webservice using WCF that will return a single standard response object that indicates whether the webservice call succeeds or fails and an error message if one occurs.
It looks to me like this is not how WCF is intended to be used, is that correct?
My problem is that I am using IDispatchMessageInspector.AfterReceiveRequest() to validate the request against an XSD prior to WCF deserializing it and calling my operation.
If it fails validation how do I return my standard response object? WCF seems to want me to throw a FaultException in this scenario but I want the interface to purely return one standard response object that contains any failure information.
So this would mean that you need to define both a custom Fault Exception that you can throw when the request you receive fails validation prior to deserialization etc, and the second standard response to send when the request succeeds.
Is that the right approach?
To achieve my goal of simply returning the one single response object if something like a validation error occurs, I've been trying to cheat and set the request object to null in AfterReceiveRequest() so it skips processing of the request.
 object IDispatchMessageInspector.AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
        {
            try
            {
                validateMessage(ref request);
            }
            catch (Exception e)
            {
                request = null;
                return new FaultException<string>(e.Message);
            }
            return null;

        }

and then perhaps I can create my own custom response object in BeforeSendReply().
 void IDispatchMessageInspector.BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            if (correlationState != null)
            {
                reply = CreateMyOwnResponse(((FaultException) correlationState));
            }
        }

But I know that this seems silly and is working against how WCF is meant to be used most likely. Is there a way to nicely achieve what I want or do I have to send an exception type when things go bad and a different "normal" response when things succeed?

A: WCF does not restrict the return object or force you to throw exceptions to communicate errorenous conditions. It depends on your needs and agreements you make on an overall scale in your architecture.
In my applications, I always tend to have an int type return argument that goes negative when an error occurs and is zero when the operation is completed successfully. You can also have more complex return arguments that have error structures in them, like:
[DataContract]
public class ReturnValue
{
  [DataMember]
  public int ReturnCode;

  [DataMember]
  public string ResultingDescription;

  // enum listing severities like Critical, Warning, etc.
  [DataMember]
  public Severity Severity;
}

If you need complex returned parameters as returns of your operation you could have the following signature:
[OperationContract]
ReturnValue MyOperation (int param1, string param2, out MyOperationResult result);

My rule of thumb is:

*

*Only throw an exception over service boundaries for unexpected and unhandled exceptions (things you didn't expect at time of development)

*For all other situations, return an error code using the return value of your operation (it is not an exception with that respect)


text:
Q: getView Custom Spinner Android not Called? I want to create custom spinner and this is CustomSpinnerAdapter  :
@Override
public int getCount() {
    // TODO Auto-generated method stub
    return (data == null) ? 0 : data.size();
}
@Override
public long getItemId (int position) {
    return position;
}

@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
    return getCustomView(position, convertView, parent);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    return getCustomView(position, convertView, parent);
}

public View getCustomView(int position, View convertView, ViewGroup parent) {

    View row = inflater.inflate(R.layout.spinner_item_ip, parent, false);
    TextView ip = (TextView) row.findViewById(R.id.ip);
    ip.setText(data.get(position).toString());
    return row;
}

and implement in Fragment
List<String> dataIpList = new ArrayList<String>();
dataIpList.add("192.168.1.1");
        dataIpList.add("192.168.1.2");
        dataIpList.add("192.168.1.3");
        dataIpList.add("192.168.1.4");

        _spinnerIpAdapter = new spinnerIpAdapter(getActivity(), R.layout.spinner_item_ip, dataIpList);
        publicIP.setAdapter(_spinnerIpAdapter);

the result is getDropDownView us called , but getView never called .
so how to fix it ?


text:
Q: Using Animation to swipe views I have a FrameLayout that recognize swipe gestures (up and down).
For example: if a swipe up are performed, I should animate the current view (that is MATCH_PARENT x MATCH_PARENT) to goes up at the same time a new view come from bottom.
I can achieve this with animations?

A: I solved this way:
private void swipeUp() {
    current.currentPage++;

    final View hidingView = currentView;
    TranslateAnimation hide = new TranslateAnimation(0, 0, 0, -getHeight());
    hide.setAnimationListener(new AnimationListenerAdapter() {
        @Override
        public void onAnimationEnd(Animation animation) {
            hidingView.setVisibility(View.GONE);
        }
    });
    hide.setDuration(1000);
    hidingView.startAnimation(hide);

    TranslateAnimation show = new TranslateAnimation(0, 0, getHeight(), 0);
    show.setFillAfter(true);
    show.setDuration(1000);

    View nextView = getView();
    addView(nextView, createLP());

    nextView.startAnimation(show);
    currentView = nextView;
}

A: If you want to actually switch views, you need to implement an AnimationListener that takes care of the animation.  If you want more complex behavior like a "finger following" scroller between views, you will likely have to use something a bit more complex, but if you're just saying
if(I flicked upwards)
    move view up

then AnimationListener is perfect for you.  Just make sure you set the listener to the Animation in code.
Hope this helps!


text:
Q: How to get target element index using html drag and drop API I would like to know how to get the source and target element index when I perform drag and drop using Drag and Drop web API on any element in my kanban board.
Basically, I want to add functionality to rearrange items in the same column. Right now, users can move cards from one column to another but they can't rearrange those cards in the same column.
Board.js
import { useEffect, useState } from "react";
import { columnsData } from "../../constants";
import Card from "../Card/Card";
import Badge from "../Reusable/Badge";

const Board = () => {
  const [columns, setColumns] = useState(
    JSON.parse(localStorage.getItem("data")) || columnsData
  );
  const [selectedCard, setSelectedCard] = useState({});

  const onDragOver = (e) => {
    e.preventDefault();
  };

  const onDrop = (e, columnName) => {
    if (selectedCard?.status === columnName) return;

    const newColumns = columns.map((column) => {
      // remove the card from the old column
      if (column.label === selectedCard.status) {
        return {
          ...column,
          items: column.items.filter((item) => item.id !== selectedCard?.id),
        };
      }

      // add card to the destination column and update the status
      if (column.label === columnName) {
        return {
          ...column,
          items: [...column.items, { ...selectedCard, status: columnName }],
        };
      }

      return column;
    });

    setColumns(newColumns);
    setSelectedCard({});
  };

  useEffect(() => {
    localStorage.setItem("data", JSON.stringify(columns));
  }, [columns]);
  return (

      {columns.map(({ label, items }) => {
        return (

              <Badge status={label} />
              {items.length}

 onDragOver(e)}
              onDrop={(e) => onDrop(e, label)}
            >
              {items.map((item) => {
                return (
                  <Card
                    key={item.id}
                    card={item}
                    setSelectedCard={setSelectedCard}
                  />
                );
              })}

        );
      })}

  );
};

export default Board;

Card code:
import { Link } from "react-router-dom";
import { trimString } from "../../utils";

const Card = ({ card, setSelectedCard }) => {
  const dragStart = () => {
    setSelectedCard(card);
  };

  return (
    <Link
      to={`/${card.id}`}
      className="block rounded-md bg-white hover:bg-gray-100 transition-colors border border-gray-300 cursor-pointer shadow-sm px-2 py-3 mb-1"
      draggable
      onDragStart={() => dragStart()}
      key={card._id}
    >

          {trimString(card.title, 30)}

    </Link>
  );
};

export default Card;


text:
Q: variable in javascript statement How does one add a variable string in this javascript statement?
where name may correspond to any valid string , say WebkitTransform or Moztransform,etc
document.getElementById('test').style.VARIABLE_NAME  =  'rotate(15deg)';

My code doesn't seem to work when i set the VARIABLE_NAME to WebkitTransform, but it works fine if I use WebkitTransform directly, as in without naming it via a variable.
Thanks in advance :)

A: There are 2 ways of accessing values in javascript objects. The first one is by using the dot operator(e.g. object.memberName). The second one is by using the square bracket notation(e.g. object['memberName']).

A: There are two ways to access members of a Javascript object.
Dot notation, which uses an identifier to access the member:
obj.member;

Bracket notation, which uses a string to access the member:
obj['member']

The latter uses a string to locate the member and you can just as easily use any expression. The value of the expression will be converted to a string so these are equivalent:
obj[{}]
obj['[object Object]']

If your expression is already a string it will be used as is, and in your case your variable holds a string so you can just do:
document.getElementById('test').style[VARIABLE_NAME]  =  'rotate(15deg)';


text:
Q: cakephp matching inputed data to textbox from database fields I am new to cakephp and I am currently working on this app where I need (for security purposes) to match data of inputted student ID on the data from my studentlist table. So in my studentlist table I have two fields one is the id and the other is the studentid so whenever a student wants to register to the website he/she needs to enter a studentid and when the studentid that is entered is not on the database he/she cannot register.
I have this view/add code
echo $this->Form->input('studentlist_id', array('type'=>'text', 'label'=>'Student ID'));

and my model code
var $name = 'Studentlist';
var $displayField = 'studentid';
var $validate = array(
    'id' => array(
        'notempty' => array(
            'rule' => array('notempty'),

and my users_controller code
$studentlists = $this->User->Studentlist->find('list');
    $this->set(compact('studentlists'));

please help... I've been searching and tweaking the codes but can't seem to find the answers... I am like really new to cakephp so I am really sorry in advance...

A: this may help you,
$count = $this->User->find('count', array('conditions'=>array('User.studentid'=>$_POST['studentlist_id'])));
if($count > 0){
echo "Student Exist";
}else {
***do something***
}


text:
Q: Visual Studio Express 2010 on x86-64: libcmt.lib missing The CCompilerDriver documentation explains that to use visual studio express on 64-bit targets, it's necessary to install the windows SDK after installing visual studio. I have done this, first installing visual studio express 2010 and then installing v7.1 of the windows SDK. However, I still have a problem due to a missing LIBCMT.LIB

Compiler`$CCompilerOptions={"ShellOutputFunction"->Print};
cFun=Compile[{{x}},x^2, CompilationTarget->"C"];

C:\Users\lev\AppData\Roaming\Mathematica\ApplicationData\CCompilerDriver\BuildFolder\lev-think-5052\Working-lev-think-5052-7032-1>call "C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\SetEnv.cmd" /x64

Setting SDK environment relative to C:\Program Files\Microsoft SDKs\Windows\v7.1\.
Targeting Windows 7 x64 Debug

Microsoft (R) C/C++ Optimizing Compiler Version 16.00.30319.01 for x64
Copyright (C) Microsoft Corporation.  All rights reserved.

compiledFunction0.c
Microsoft (R) Incremental Linker Version 10.00.30319.01
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:compiledFunction0.dll
/dll
/implib:compiledFunction0.lib
/implib:C:\Users\lev\AppData\Roaming\Mathematica\ApplicationData\CCompilerDriver\BuildFolder\lev-think-5052\Working-lev-think-5052-7032-1\compiledFunction0.lib
"/LIBPATH:C:\Program Files\Wolfram Research\Mathematica\8.0\SystemFiles\Links\MathLink\DeveloperKit\Windows-x86-64\CompilerAdditions\mldev64\lib"
"/LIBPATH:C:\Program Files\Wolfram Research\Mathematica\8.0\SystemFiles\Libraries\Windows-x86-64"
ml64i3m.lib
/out:C:\Users\lev\AppData\Roaming\Mathematica\ApplicationData\CCompilerDriver\BuildFolder\lev-think-5052\Working-lev-think-5052-7032-1\compiledFunction0.dll
compiledFunction0.obj
LINK : fatal error LNK1104: cannot open file 'LIBCMT.lib'

Has anyone managed to get this configuration working? How about with visual studio express 2008 and v7.0 of the SDK?
It took me several tries to get even this far, because I made the mistake of letting windows update install SP1 for visual studio express and this prevented installing the SDK, and I had had uninstall and reinstall everything a few times (it's not possible to simply uninstall SP1), so it's possible I've messed up my installation somehow. I can see that there is a LIBCMT.LIB in C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\lib which I presume is a 32-bit version of the library and not what the linker is looking for in this case.

A: Just thought I'd share.
I had the same problem after re-installing VS2010 Ultimate (I also have 2008).
To fix it, I copied the following

*

*libcmt.lib
libcmt.pdb
libcmtd.lib
libcmtd.pdb
oldnames.lib

from C:\Program Files\Microsoft Visual Studio 11.0\VC\lib
to C:\Program Files\Microsoft Visual Studio 10.0\VC\lib
Hope this helps someone.

A: I had the same issue. Repairing or reinstalling VS 2010 express didn't work either. Most of the lib files where missing. I ended up installing on another pc and copying the missing files. Then it worked like a charm. Hope this helps.


text:
Q: Como referenciar o userID e emitir uma notificação no firebase Eu estou tendo a seguinte estrutura do real time database:

E estou tentando criar um gatilho para que sempre que uma mensagem for adicionada no user003 eu envie uma notificação através do FCM minha função não está funcionando
const functions = require('firebase-functions');
const admin = require("firebase-admin");
admin.initializeApp();

exports.fcmSend = functions.database.ref('/messages/{userId}/{messageId}').onCreate(event => {

  console.log('event', event)

  const message = event.after.val()
  const userId  = event.params.userId
  const payload = {
        notification: {
          title: message.title,
          body: message.body,
          icon: "https://placeimg.com/250/250/people"
        }
      };

   admin.database()
        .ref(`/fcmTokens/${userId}`)
        .once('value')
        .then(token => token.val() )
        .then(userFcmToken => {
          return admin.messaging().sendToDevice(userFcmToken, payload)
        })
        .then(res => {
          console.log("Sent Successfully", res);
        })
        .catch(err => {
          console.log('err', err);
        });

});

A: Eu mudaria estas linhas aqui, da uma olhada no log as mensagens
return admin.database()
        .ref(/fcmTokens/${userId})
        .once('value')
        .then(snapshot => {
            console.log("token", snapshot.val() );
            return admin.messaging().sendToDevice(snapshot.val(), payload)
        })
        .then(res => {
            console.log("Sent Successfully", res);
        })
        .catch(err => {
            console.log('err', err);
        });