text:
Q: rufus scheduler first day months I  try to execute a cron every first day of the month.
I see how do on every first monday but no on first day.
scheduler.cron('00 12 * * mon#1') do
     # ...
end

I try with:
scheduler.cron('00 12 * * #1') do
  # ...
end

how I can do it?

A: The format is:
┌───────────── min (0 - 59)
│ ┌────────────── hour (0 - 23)
│ │ ┌─────────────── day of month (1 - 31)
│ │ │ ┌──────────────── month (1 - 12)
│ │ │ │ ┌───────────────── day of week (0 - 6)
│ │ │ │ │
* * * * *

"0 12 1 * *"

Reference: https://en.wikipedia.org/wiki/Cron#Configuration_file


text:
Q: PyMC installation error with pip I am attempting to install PyMC using pip install pymc. I believe this command should install PyMC 2.3.6.
PyMC has a few dependencies, which I have in my PATH. I am running OSX 10.11.2 and my PATH includes Python 2.7.13, NumPy 1.12.0, Matplotlib 2.0.0, gcc, and gfortran.
Python (including pip) was installed using Homebrew. NumPy and Matplotlib were installed using pip. The gfortran compiler was downloaded and installed from the GCC Wiki for the purpose of this installation.
Executing pip install pymc yielded lots of output including the following lines.

Collecting pymc
  Using cached pymc-2.3.6.tar.gz
    Complete output from command python setup.py egg_info:
    running egg_info
    running build_src
    build_src
    building extension "pymc.flib" sources
    f2py options: ['skip:ppnd7']
    f2py:> build/src.macosx-10.11-x86_64-2.7/pymc/flibmodule.c
    creating build
    creating build/src.macosx-10.11-x86_64-2.7
    creating build/src.macosx-10.11-x86_64-2.7/pymc
    IOError: [Errno 2] No such file or directory: 'skip:ppnd7'. Skipping file "skip:ppnd7".
    updatevars:gradlike: attempt to change 'dimension(nx)' to 'dimension(na)'. Ignoring.
    updatevars:gradlike: attempt to change 'dimension(nx)' to 'dimension(nb)'. Ignoring.
    updatevars:gradlike: attempt to change 'dimension (nmu)' to 'dimension(nmu)'. Ignoring.
    updatevars:gradlike: attempt to change 'dimension (na)' to 'dimension(na)'. Ignoring.
    rmbadname1: Replacing "index" with "index_bn".
    Reading fortran codes...
        Reading file 'pymc/flib.f' (format:fix,strict)
    Line #34 in pymc/flib.f:"      PARAMETER (infinity = 1.7976931348623157d308)"
        get_parameters: got "unexpected EOF while parsing (<string>, line 0)" on ''

...
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/private/var/folders/2f/cr97n5v93mn04c3qbqd7r3q40000gn/T/pip-build-6Zmgcz/pymc/setup.py", line 124, in <module>
    **(config_dict))
  File "/usr/local/lib/python2.7/site-packages/numpy/distutils/core.py", line 169, in setup
    return old_setup(**new_attr)

...
    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/2f/cr97n5v93mn04c3qbqd7r3q40000gn/T/pip-build-6Zmgcz/pymc/

As suggested in these two pip installation threads about egg_info errors [1, 2], I ran pip install —upgrade setuptools and pip install ez_setup. Once these items were installed I ran into the same types of errors pasted above.
As noted in other package installation threads, I am willing to use conda to install PyMC if I cannot resolve these issues. However, I'd like to investigate this installation issue first.
Would anyone happen to know what my issue is here? Might there be some steps I can take to successfully install PyMC using pip?

A: I had the same problem. I don't understand the root cause, but I fixed it by downgrading numpy to version 1.10.1: pip install numpy==1.10.1

A: I also met this problem while trying to install pymc from pip or source code, but I found a solution that might be useful.
The reason that causes the problem might be the file setup.py, in which the script check the compile env. I didn't read the code very carefully, but in the function build_ext() I think the codes first check whether some compile environments have already been installed into OS. If installed, the script will use them as defaults; if not, use ones in somewhere else (the comment says 'from netlib sources').
I infer the problem is caused by the compile environments that have already been installed in the OS, so I modify the file setup.py to skip this part of codes, and let the script use the netlib source. Then I run sudo python setup.py install. There are some error and warning messages, but the folder 'pymc' emerges in python library, and some simple test codes run successfully.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Swift : UITableView Passing Calendar Event Data to DetailViewController I have a tableview, which loads the calendar events into rows dynamically. I'am checking for device's current day events. I set a detailview because I will pass that event data to the detailview labels. I am using storyboard segues. But I could not complete it yet. Can anyone help me what I am missing?
The error is "Cannot assign value of type 'EKEvent?' to type 'String?'"
Should I convert the EKEvent Date type to the string? or How, I need an example for that. I am practicing my swift skills.
Here is my code below;
class MainViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var needPermissionView: UIView!
@IBOutlet weak var calendarsTableView: UITableView!
@IBOutlet weak var dateLabel: UILabel!

var event : [EKEvent]?
var calendars: [EKCalendar]?
let eventStore = EKEventStore()

override func viewDidLoad() {
    super.viewDidLoad()
    loadEvents()

    calendarsTableView.delegate = self
    calendarsTableView.dataSource = self

    calendarsTableView.estimatedRowHeight = 44
    calendarsTableView.rowHeight = UITableViewAutomaticDimension

    calendarsTableView.reloadData()

}

    override func viewWillAppear(_ animated: Bool) {
    checkCalendarAuthorizationStatus()
}

    func checkCalendarAuthorizationStatus() {
    let status = EKEventStore.authorizationStatus(for: EKEntityType.event)

    switch (status) {
    case .notDetermined:
        requestAccessToCalendar()
    case .restricted, .denied:
        needPermissionView.fadeIn()
    case .authorized:
        loadCalendars()
        loadEvents()
        refreshTableView()
    }
}

func requestAccessToCalendar() {
    eventStore.requestAccess(to: .event) { (accessGranted, error) in
        if accessGranted == true {
            DispatchQueue.main.async {
                self.loadCalendars()
                self.loadEvents()
                self.refreshTableView()
            }
        } else {
            DispatchQueue.main.async {
                self.needPermissionView.fadeIn()
            }
        }
    }
}

func loadCalendars() {
    self.calendars = eventStore.calendars(for: EKEntityType.event)
}

func refreshTableView() {
    calendarsTableView.isHidden = false
    calendarsTableView.reloadData()
}

func loadEvents(){
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat =  "yyyy-MM-dd"

    let date = Date()
    let dateString = dateFormatter.string(from: date)

    print(dateString)
    dateLabel.text = dateString

    var components: DateComponents = DateComponents()
    components.setValue(1, for: .day)

    let expirationDate = Calendar.current.date(byAdding: components, to: date)
    //print(expirationDate ?? "expirationDate")

    let endString = dateFormatter.string(from: expirationDate!)

    // Create start and end date NSDate instances to build a predicate for which events to select
    let startDate = dateFormatter.date(from: dateString)
    let endDate = dateFormatter.date(from: endString)

    if let startDate = startDate, let endDate = endDate{
        let eventStore = EKEventStore()

        // Use an event store instance to create and properly configure an NSPredicate
        let eventsPredicate = eventStore.predicateForEvents(withStart: startDate, end: endDate, calendars: calendars)

        // Use the configured NSPredicate to find and return events in the store that match
        self.event = eventStore.events(matching: eventsPredicate).sorted(by: { (e1, e2) -> Bool in
            return e1.startDate.compare(e2.startDate) == ComparisonResult.orderedAscending
        })
    }
}

@IBAction func goToSettingsButtonTapped(_ sender: UIButton) {
    let openSettingsUrl = URL(string: UIApplicationOpenSettingsURLString)
    UIApplication.shared.openURL(openSettingsUrl!)
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if let events = self.event {
        return events.count
    }

    tableView.rowHeight = UITableViewAutomaticDimension
    tableView.estimatedRowHeight = 90
    return 0
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

    if let events = self.event {
        let eventName = events[(indexPath as NSIndexPath).row].title
        cell.textLabel?.text = eventName

        let eventDate = events[(indexPath as NSIndexPath).row].startDate
        let dateFormatter = DateFormatter()

        dateFormatter.dateFormat = "dd MMM yyyy  HH:mm"
        dateFormatter.timeZone = TimeZone(abbreviation: "GMT+3")

        let timeStamp = dateFormatter.string(from: eventDate!)
        print(timeStamp)
        cell.detailTextLabel?.text = timeStamp
    } else {
        cell.textLabel?.text = "Unknown Calendar Name"
    }

    cell.textLabel?.numberOfLines = 0
    return cell
}

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "showDetail" {
        if let indexPath = calendarsTableView.indexPathForSelectedRow {
            let destVC = segue.destination as! DetailViewController
            destVC.taskNameLabel.text = event?[indexPath.row]
        }
    }
}

A: Your problem is here EKEvent var can't be assigned to text which is of type String
destVC.taskNameLabel.text = event?[indexPath.row]

you need to
destVC.sendedEvent = event?[indexPath.row]

//
class DetailViewController {
  var sendedEvent: EKEvent?
}

Then assign sendedEvent title or anything inside viewDidLoad of DetailViewController


text:
Q: Removing Semaphore after last sem_release in PHP I have an operation in PHP that checks if an object with an ID is in a DB and creates an entry for it if it isn't. A request for the same ID can happen concurrently, so I want to prevent the ID from being inserted twice.
I am currently using the following code to lock/unlock access to the DB for that particular key:
$semaphore = sem_get($keyForID, 1);

sem_acquire($semaphore);

// 1.) check for id
// 2.) insert object if it doesn't exist

sem_release($semaphore);

My question is: Since I'm creating an individual semaphore for every object-ID, do I explicitly have to remove those semaphores with sem_remove or does PHP do that automatically after sem_release?
If I do have to remove the semaphore explicitly, is there an easy and reliable way of checking if that semaphore is currently acquired by another thread so that latter doesn't crash on sem_release? Using shared memory comes to mind, but that would require yet another semaphore to read/write the number of threads.

A: sem_remove explicitly destroy a given semaphore, which will make it unavailable for further computation for any other running process or thread, until it is recreated using sem_get. For instance, if 3 processes are trying to access the same semaphore (with only 1 concurrent access), and the first one destroy it before the two others manage to acquire it, the two latter processes may end up running concurrently, instead of sequentially (as expected).
You really don't want to call sem_remove, unless you know that all other running processes won't use it anymore.
Anyway, in your situation, I would recommend relying on the DB itself for concurrent accessing. If you need to have only one entry created in your DB, use transactions. If you are using a DB which isn't supporting transactions such as the MyISAM engine on MySQL, either switch to an engine supporting transactions, or in the specific case of MyISAM, try using atomic operations.


text:
Q: Insert a formatted footnote using Microsoft.Interop.Office.Word I am trying to inset formatted footnotes into an open word document using a WinForms application.
While I am able to use Interop.Word to set plain text footnotes and so long as I use plain text it works fine.  However, I also want the user to be able to paste rich text formatted text from a rich text box into the footnote.  This never works and always shows the rich text codes.
I know that footnotes can take formatting because if I put the rich text int a clipboard and paste it into a footnote the formatting is preserved.
I have even tried putting the rich text into the clipboard and then setting the string (s) to the clipboard contents using "s = Clipboard.GetText(TextDataFormat.Rtf);"  It seems as if this should be exactly what I am pasting, but if I paste into the footnote it works.  If the program sets it using the code below it does not work.
I appreciate any help.
application = (Microsoft.Office.Interop.Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");

application.ActiveDocument.Footnotes.Add(application.Selection.Range, "", s);

A: Cindy's answer was helpful.  I fixed the problem by doing the following:

*

*Saving the current selected position in the document and current clipboard contents.

*Inserting a blank footnote.

*Selecting the footnote.

*Putting the string into the clipboard as rich text format.

*Sending/pasting the information from the clipboard to Word.

*Restoring the clipboard and original selected position in the document.


text:
Q: Difference between specifications of fread and fgets? What is the difference between fread and fgets when reading in from a file?
I use the same fwrite statement, however when I use fgets to read in a .txt file it works as intended, but when I use fread() it does not.
I've switched from fgets/fputs to fread/fwrite when reading from and to a file. I've used fopen(rb/wb) to read in binary rather than standard characters. I understand that fread will get /0 Null bytes as well rather than just single lines.
  //while (fgets(buff,1023,fpinput) != NULL) //read in from file
  while (fread(buff, 1, 1023, fpinput) != 0) // read from file

I expect to read in from a file to a buffer, put the buffer in shared memory, and then have another process read from shared memory and write to a new file.
When I use fgets() it works as intended with .txt files, but when using fread it adds a single line from 300~ characters into the buffer with a new line. Can't for the life of me figure out why.

A: fgets will stop when encountering a newline. fread does not. So fgets is typically only useful for text files, while fread can be used for both text and binary files.
From the C11 standard:
7.21.7.2 The fgets function

The fgets function reads at most one less than the number of characters specified by n from the stream pointed to by stream into the array pointed to by s. No additional characters are read after a new-line character (which is retained) or after end-of-file. A null character is written immediately after the last character read into the array.

7.21.8.1 The fread function

The fread function reads, into the array pointed to by ptr, up to nmemb elements whose size is specified by size, from the stream pointed to by stream. For each object, size calls are made to the fgetc function and the results stored, in the order read, in an array of unsigned char exactly overlaying the object. The file position indicator for the stream (if defined) is advanced by the number of characters successfully read. If an error occurs, the resulting value of the file position indicator for the stream is indeterminate. If a partial element is read, its value is indeterminate.

This snippet maybe will make things clearer for you. It just copies a file in chunks.
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char ** argv)
{
    if(argc != 3) {
        printf("Usage: ./a.out src dst\n");
        printf("Copies file src to dst\n");
        exit(EXIT_SUCCESS);
    }

    const size_t chunk_size = 1024;

    FILE *in, *out;
    if(! (in = fopen(argv[1], "rb"))) exit(EXIT_FAILURE);
    if(! (out = fopen(argv[2], "wb"))) exit(EXIT_FAILURE);

    char * buffer;
    if(! (buffer = malloc(chunk_size))) exit(EXIT_FAILURE);

    size_t bytes_read;

    do {
        // fread returns the number of successfully read elements
        bytes_read = fread(buffer, 1, chunk_size, in);

        /* Insert any modifications you may */
        /* want to do here                  */

        // write bytes_read bytes from buffer to output file
        if(fwrite(buffer, 1, bytes_read, out) != bytes_read) exit(EXIT_FAILURE);
   // When we read less than chunk_size we are either done or an error has
   // occured. This error is not handled in this program.
    } while(bytes_read == chunk_size);

    free(buffer);
    fclose(out);
    fclose(in);
}

You mentioned in a comment below that you wanted to use this for byteswapping. Well, you can just use the following snippet. Just insert it where indicated in code above.
for(int i=0; i < bytes_read - bytes_read%2; i+=2) {
    char tmp = buffer[i];
    buffer[i] = buffer[i+1];
    buffer[i+1] = tmp;
}


text:
Q: rxjs mongo stream backpressure Lately I've been having backpressure-problems with rx.js from a mongo-cursor-readable. The task is basically:

*

*Query DB A (Mongo), use its readable and convert it to an observable

*Perform various async transformations to the input stream, e.g.
2.1 Query another DB B (Mongo, whatever) for additional data for an item (or a batch of items), then perform (possibly async) operations on it
2.2 Query another DB B (Mongo, whatever) for an item (or a batch of items), then perform filtering with that additional data

*Count the Input stream and compare it to the output stream (as filtering can occur)

Although I do have a solution for all of the problems, I'm dealing with backpressure from the very first Mongo-DB, as 2. or 2.1/2.2 can be potentially very time intensive, but the initial query is much more performant (a.k.a consumers are slow, producers are fast)
Right now, my only solution is to limit 1. to a reasonable amount to reduce initial throughput, but this results obviously in slower throughput for the whole transformation-chain (long waiting periods for the producer until the whole chain is done working)
How do I realize a transformation chain, which is always busy, but doesn't suffer from backpressure?
I'm thinking here to reduce the speed of the producer dynamically based on the current (or projected) performance of its consumers (e.g. time taken for a transformation), but this doesn't seem very intuitive to me.


text:
Q: best_in_place error id for nil In my rails app , I create a ratings for rates my sound.And in the rating , the user can add information , like why he give this marks etc..
My ratings work good , but now i want add with best_in_place the edit input for the info.
So In my view #Sound show
 <%= best_in_place @rating, :info, :type => :textarea, :nil => "Ajouter un commmentaire à votre vote !" %>

And in my controller : Ratings :
 def create
      @sound = Sound.find_by_id(params[:sound_id])
                @rating = Rating.new(params[:rating])
                @rating.sound_id = @sound.id
                @rating.user_id = current_user.id
                if @rating.save
                    respond_to do |format|
                        format.html
                        format.js
                    end
                end
        end

        def update
            @sound = Sound.find_by_id(params[:sound_id])
                @rating = current_user.ratings.find_by_sound_id(@sound.id)
                @rating.sound_id = @sound.id
                if @rating.update_attributes(params[:rating])
                    respond_to do |format|
                        format.html
                        format.js
                    end
                end

        end

But when I want edit  "info" with best_in_place , I have this mistake :

Called id for nil, which would mistakenly be 4 -- if you really wanted
  the id of nil, use object_id

And the lane is :

@rating = current_user.ratings.find_by_sound_id(@sound.id)

I hope you understand my problem , and you can help me for the in_place_editing works.
Thank you

A: I think the best in place gem uses ajax, so you need to add some code to your controller.
The docs show that the gem comes with a controller helper for responding to json.
 respond_to do |format|
if @rating.update_attributes(params[:rating])
  format.html { redirect_to(@sound, :notice => 'Rating was successfully updated.') }
  format.json { respond_with_bip(@rating) }
else
  format.html { render :action => "edit" }
  format.json { respond_with_bip(@rating) }
end
end

You also may need to add the jQuery initializer to you document anywhere:
$(document).ready(function() {
jQuery(".best_in_place").best_in_place();
});

Hope that works! Also, this is my first stack overflow answer ever!


text:
Q: Which horses to bet on, given known probability of winning Say that I have calculated a probability of winning for every single horse in a collection of races (say, all the races on one day). The odds being offered by the bookmaker can be converted into an implied probability of winning. So (assuming that my probability of winning calculations are better than the bookmaker's) I could bet on a horse so long as:
my Pwin > bookie's implied Pwin
(this could be true for more than one horse per race)
But given a maximum budget for placing my bets, how would I distribute my bets amongst all the horses in all the races in order to get the highest expected return? I realise that this question may be a bit broad for a complete answer here, but I dare say that it's a well analysed problem, so just knowing where to look would be very helpful.
FYI: The relationship between implied probability of winning and the decimal odds offered by the bookie is:
Pwin = 1 / decimal odds

A: Given that you are trying to maximize your expected profit, you don't really care about the bookie's implied chance of winning.  Assuming your $Pwin$ is correct, you only care about that and your winnings (or losses). So,
$$E[profit] = \sum_{Race \in Races} (Pwin_{Race}*Bet_{Race}*(Odds_{Race}-1) - (1-Pwin_{Race}) * Bet_{Race}) \\
= \sum_{Race \in Races} Bet_{Race} (Pwin_{Race}*Odds_{Race} - Pwin_{Race} + Pwin_{Race} - 1 ) \\
= \sum_{Race \in Races} Bet_{Race} (Pwin_{Race}*Odds_{Race} - 1)$$
Note that if $Pwin_{Race}*Odds_{Race} = 1$, then your expected profit is 0.
Now, if we assume the same bet for any race, then you want to choose races that maximize $$Bet*\sum_{Race \in Races} (Pwin_{Race}*Odds_{Race} - 1 ) \\ = -Bet*n_{bets}+Bet*\sum_{Race \in Races} Pwin_{Race}*Odds_{Race})$$
where $n_{bets}$ is the number of races where you place a bet.


text:
Q: DIV's overlapping when they're displayed as blocks On this site:
http://stmc.modulemedia.co.uk/HossIntropia
I have code that's generated by a CMS, I have stripped things back as much as possible, removing the .net code and things generated by the CMS, but still cannot see why the text (that starts Hoss Intropia...) is overlapping.
There are basically two DIVS LeftCol and RightCol, that I have moved from being side-by-side to LeftCol being above RightCol.
This is a project I'm taking over, so I'm limited as to what can be changed.
Thanks for your help!

A: I think you just need to increase the height of the div inside #LeftCol that is containing stuff.
Try changing the height on .menu to height: 480px. Or perhaps even remove the height.

A: div.Menu has a height property, and since the content is spilling out beyond that height, it overlaps the div#RightCol content.
if you remove the height from div.Menu, it works

A: settting the margin of the right cols should solve the problem:
#RightCol {
    margin:120px 0 0 0 !important;
}


text:
Q: How Weka draw ROC curve from KNN (IBk)? I have read a lot about ROC curve before posting.
So, I didn't understand how Weka draw the ROC curves. I can't find the thereshold to variate to generate the points in the curve.  Thanks,

A: Weka uses a class called TheresholdCurve from a method in the Evaluation class.
In this class there are all the points of the ROC Curve.
The threshold will variate depending on the classification used. See here for more details.


text:
Q: Java 9 HttpClient exception when using certain characters in URL query parameters Here is my sample code. The query is encoded to UTF-8:
HttpRequest request = HttpRequest.newBuilder()
    .header("content-type", "application/json;charset=UTF-8")
    .uri(URI.create("http://localhost:8080/test?param1=test%C5%84"))
    .GET()
    .build();

HttpClient.newBuilder()
    .version(HttpClient.Version.HTTP_2)
    .build()
    .send(request, HttpResponse.BodyHandler.asString(Charset.forName("UTF-8")));

After I run this example I get the following exception:
java.lang.IllegalArgumentException: char=324
at jdk.incubator.httpclient/jdk.incubator.http.internal.hpack.Huffman.codeOf(Huffman.java:559)
at jdk.incubator.httpclient/jdk.incubator.http.internal.hpack.Huffman.lengthOf(Huffman.java:524)
at jdk.incubator.httpclient/jdk.incubator.http.internal.hpack.StringWriter.configure(StringWriter.java:79)
at jdk.incubator.httpclient/jdk.incubator.http.internal.hpack.StringWriter.configure(StringWriter.java:62)
at jdk.incubator.httpclient/jdk.incubator.http.internal.hpack.IndexNameValueWriter.value(IndexNameValueWriter.java:64)
at jdk.incubator.httpclient/jdk.incubator.http.internal.hpack.Encoder.literal(Encoder.java:422)
at jdk.incubator.httpclient/jdk.incubator.http.internal.hpack.Encoder.header(Encoder.java:245)
at jdk.incubator.httpclient/jdk.incubator.http.internal.hpack.Encoder.header(Encoder.java:198)
at jdk.incubator.httpclient/jdk.incubator.http.Http2Connection.encodeHeadersImpl(Http2Connection.java:927)
at jdk.incubator.httpclient/jdk.incubator.http.Http2Connection.encodeHeaders(Http2Connection.java:878)
at jdk.incubator.httpclient/jdk.incubator.http.Http2Connection.encodeHeaders(Http2Connection.java:951)
at jdk.incubator.httpclient/jdk.incubator.http.Http2Connection.sendFrame(Http2Connection.java:984)
at jdk.incubator.httpclient/jdk.incubator.http.Stream.sendHeadersAsync(Stream.java:547)
at jdk.incubator.httpclient/jdk.incubator.http.Exchange.lambda$responseAsyncImpl0$8(Exchange.java:322)
at java.base/java.util.concurrent.CompletableFuture$UniCompose.tryFire(CompletableFuture.java:1072)
at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:506)
at java.base/java.util.concurrent.CompletableFuture.complete(CompletableFuture.java:2073)
at jdk.incubator.httpclient/jdk.incubator.http.internal.common.SSLFlowDelegate.setALPN(SSLFlowDelegate.java:164)
at jdk.incubator.httpclient/jdk.incubator.http.internal.common.SSLFlowDelegate.access$200(SSLFlowDelegate.java:81)
at jdk.incubator.httpclient/jdk.incubator.http.internal.common.SSLFlowDelegate$Reader.processData(SSLFlowDelegate.java:340)
at jdk.incubator.httpclient/jdk.incubator.http.internal.common.SSLFlowDelegate$Reader$ReaderDownstreamPusher.run(SSLFlowDelegate.java:215)
at jdk.incubator.httpclient/jdk.incubator.http.internal.common.SequentialScheduler$SynchronizedRestartableTask.run(SequentialScheduler.java:175)
at jdk.incubator.httpclient/jdk.incubator.http.internal.common.SequentialScheduler$CompleteRestartableTask.run(SequentialScheduler.java:147)
at jdk.incubator.httpclient/jdk.incubator.http.internal.common.SequentialScheduler$TryEndDeferredCompleter.complete(SequentialScheduler.java:315)
at jdk.incubator.httpclient/jdk.incubator.http.internal.common.SequentialScheduler$CompleteRestartableTask.run(SequentialScheduler.java:149)
at jdk.incubator.httpclient/jdk.incubator.http.internal.common.SequentialScheduler$SchedulableTask.run(SequentialScheduler.java:198)
at jdk.incubator.httpclient/jdk.incubator.http.internal.common.SequentialScheduler.runOrSchedule(SequentialScheduler.java:271)
at jdk.incubator.httpclient/jdk.incubator.http.internal.common.SequentialScheduler.runOrSchedule(SequentialScheduler.java:224)
at jdk.incubator.httpclient/jdk.incubator.http.internal.common.SSLFlowDelegate$Reader.incoming(SSLFlowDelegate.java:242)
at jdk.incubator.httpclient/jdk.incubator.http.internal.common.SubscriberWrapper.incomingCaller(SubscriberWrapper.java:388)
at jdk.incubator.httpclient/jdk.incubator.http.internal.common.SubscriberWrapper.onNext(SubscriberWrapper.java:343)
at jdk.incubator.httpclient/jdk.incubator.http.internal.common.SubscriberWrapper.onNext(SubscriberWrapper.java:58)
at jdk.incubator.httpclient/jdk.incubator.http.SocketTube$InternalReadPublisher$InternalReadSubscription.read(SocketTube.java:739)
at jdk.incubator.httpclient/jdk.incubator.http.SocketTube$SocketFlowTask.run(SocketTube.java:171)
at jdk.incubator.httpclient/jdk.incubator.http.internal.common.SequentialScheduler$SchedulableTask.run(SequentialScheduler.java:198)
at jdk.incubator.httpclient/jdk.incubator.http.internal.common.SequentialScheduler.runOrSchedule(SequentialScheduler.java:271)
at jdk.incubator.httpclient/jdk.incubator.http.internal.common.SequentialScheduler.runOrSchedule(SequentialScheduler.java:224)
at jdk.incubator.httpclient/jdk.incubator.http.SocketTube$InternalReadPublisher$InternalReadSubscription.signalReadable(SocketTube.java:675)
at jdk.incubator.httpclient/jdk.incubator.http.SocketTube$InternalReadPublisher$ReadEvent.signalEvent(SocketTube.java:829)
at jdk.incubator.httpclient/jdk.incubator.http.SocketTube$SocketFlowEvent.handle(SocketTube.java:243)
at jdk.incubator.httpclient/jdk.incubator.http.HttpClientImpl$SelectorManager.handleEvent(HttpClientImpl.java:769)
at jdk.incubator.httpclient/jdk.incubator.http.HttpClientImpl$SelectorManager.run(HttpClientImpl.java:731)

char=324 means decoded ń from query
When I read stack trace I found jdk.incubator.http.Stream<T> this method in the class:
private void setPseudoHeaderFields() {
    HttpHeadersImpl hdrs = requestPseudoHeaders;
    String method = request.method();
    hdrs.setHeader(":method", method);
    URI uri = request.uri();
    hdrs.setHeader(":scheme", uri.getScheme());
    // TODO: userinfo deprecated. Needs to be removed
    hdrs.setHeader(":authority", uri.getAuthority());
    // TODO: ensure header names beginning with : not in user headers
    String query = uri.getQuery();
    String path = uri.getPath();
    if (path == null || path.isEmpty()) {
        if (method.equalsIgnoreCase("OPTIONS")) {
            path = "*";
        } else {
            path = "/";
        }
    }
    if (query != null) {
        path += "?" + query;
    }
    hdrs.setHeader(":path", path);
}

In this method uri.getQuery() is used which gives us the decoded query and causes the above exception.
When I used uri.getRawQuery() in debug mode (which gave us the encoded query) everything went fine.
My question is: is that a bug or intentional usage? If it is not a bug, how do I avoid the exception?

A: It is a bug:

java.lang.IllegalArgumentException with jdk.incubator.httpclient when using some UTF-8 characters

  Some UTF-8 characters like "š" can't be used with HttpClient. However
  others like "å" can be.

See: https://bugs.openjdk.java.net/browse/JDK-8201238

Java 9/10 HttpClient is incubated. It's not production-ready. It states so very clearly in the package name. As such, it's quite possible that it may contain bugs.
It will be released properly in Java 11 (currently scheduled for release 25th September 2018) as part of JEP 321.


text:
Q: Issue connecting pub/sub from PCF I'm trying to connect google Pub/Sub from PCF environment(Spring boot app). The app is successfully loaded the credentials from credentials.json file and it printed Project ID.  but it is printing below error after started.
c.g.a.oauth2.ComputeEngineCredentials : Failed to detect whether we are running on Google Compute Engine.
ERROR 13 --- [nio-8080-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.IllegalStateException: Expected the service InnerService [FAILED] to be RUNNING, but the service has FAILED] with root cause
java.io.IOException: The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information.
Here is the code which I'm using and I'm invoking this method from a sample rest controller.
public static void subscribeAsyncExample(String projectId, String subscriptionId) {
ProjectSubscriptionName subscriptionName =
    ProjectSubscriptionName.of(projectId, subscriptionId);
System.out.println("Processing messages...");
MessageReceiver receiver =
    (message, consumer) -> {
      System.out.println("Id : " + message.getMessageId());
      System.out.println("Data : " + message.getData().toStringUtf8());
      consumer.ack();
    };
Subscriber subscriber = null;
try {
  subscriber = Subscriber.newBuilder(subscriptionName, receiver).build();
  subscriber.startAsync().awaitRunning();
  subscriber.awaitTerminated();
} finally {
  if (subscriber != null) {
    subscriber.stopAsync();
  }
}

}
pom.xml
Spring boot: 2.3.2.RELEASE
spring-cloud-gcp.version: 1.1.3.RELEASE
`
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-gcp-starter-pubsub</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud-pubsub</artifactId>
</dependency>

<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud-storage</artifactId>
</dependency>

`
Log:
The default project ID is *******
Default credentials provider for service account *****-client-account@*******.gserviceaccount.com
Scopes in use by default credentials: [https://www.googleapis.com/auth/pubsub, https://www.googleapis.com/auth/trace.append, https://www.googleapis.com/auth/spanner.admin, https://www.googleapis.com/auth/cloudruntimeconfig, https://www.googleapis.com/auth/sqlservice.admin, https://www.googleapis.com/auth/devstorage.read_only, https://www.googleapis.com/auth/devstorage.read_write, https://www.googleapis.com/auth/cloud-platform, https://www.googleapis.com/auth/spanner.data, https://www.googleapis.com/auth/datastore, https://www.googleapis.com/auth/cloud-vision]


text:
Q: Erro ao tentar executar função de Insert PDO - PHP estou tentando criar uma função PDO para executar duas inserções, uma em seguida da outra, mas estou com dificuldades.
O código da função é:
public function double_cad(array $dados){
    $pdo = parent::getDB();
    $double_cad = $pdo->prepare("insert into login(nome, login, senha, role)values(?,?,?,?)");
    $double_cad->bindValue(1, $dados[0]);
    $double_cad->bindValue(2, $dados[1]);
    $double_cad->bindValue(3, $dados[2]);
    $double_cad->bindValue(4, $dados[3]);
    $double_cad->execute();

    $id_usr = $pdo->lastInsertId();

    $double_cad = $pdo->prepare("insert into transacoes(codigo_transacao, referencia, status_transacao, ".$id_usr. ", id_servico, tipo_pagamento, data_transacao)values(?,?,?,?,?,?,?)");
    $double_cad->bindValue(1, $dados[0]);
    $double_cad->bindValue(2, $dados[1]);
    $double_cad->bindValue(3, $dados[2]);
    $double_cad->bindValue(4, $dados[3]);
    $double_cad->bindValue(5, $dados[4]);
    $double_cad->bindValue(6, $dados[5]);
    $double_cad->bindValue(7, $dados[6]);
    $double_cad->execute();

}

O que estou tentando fazer é inserir os dados do usuário na tabela "login", recuperar seu id e, logo em seguida, inserir na tabela "transacoes" os dados da transação desse usuário (a linha "$id_usr = $pdo->lastInsertId();" é justamente para recuperar o id do usuário para inserir como chave estrangeira na tabela de transações).
Porém, ao executar esta função, exibe o erro:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1, id_servico, tipo_pagamento, data_transacao)values('nome do usuário','email do usuário' at line 1' in C:\wamp\www\xxxx\lib\class\Transacao.php on line 44

A linha 44 é justamente o segundo execute da função. Como resolver?

A: A sintaxe do insert é:
INSERT INTO TABELA (CAMPO1, CAMPO2, CAMPO3) VALUES (VALOR_CAMPO1, VALOR_CAMPO2...)

Mas nessa linha você usa o id que retornou da ultima query para listar as colunas:
insert into transacoes(codigo_transacao, referencia, status_transacao, ".$id_usr. ", id_servico, tipo_pagamento, data_transacao)values(?,?,?,?,?,?,?)");

Gerando um insert na coluna "1" por exemplo então se você não tiver uma coluna com o nome 1 ele não vai inserir.


text:
Q: php не отправляется запрос Есть простая форма регистрации
<form action="" method="POST">
    <input name="login">
    <input name="password" type="password">
    <input type="submit">
</form>

Реализую регистрацию следующим образом
session_start();

$host = 'localhost';
$user = 'root';
$pass = '';
$name = 'users';

$link = mysqli_connect($host, $user, $pass, $name);

if (!empty($_POST['login']) and !empty($_POST['password'])) {
    $login = $_POST['login'];
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);

    $query = "SELECT * FROM users WHERE login='$login'";
    $result = mysqli_query($link, $query);
    $user = mysqli_fetch_assoc($result);

    if (empty($user)) {
        $query = "INSERT INTO users SET login='$login', password='$password'";
        mysqli_query($link, $query);

        $_SESSION['auth'] = true;
        $id = mysqli_insert_id($link);
        $_SESSION['id'] = $id;
    } else {
        echo 'Login is unavailable';
    }
}

Первый запрос в базу проходит (проверяю логин), а вот второй на вставку в бд (собственно регистрация) - нет. Просветите в чем беда.


text:
Q: In Slime REPL (GNU EMACS), what is the shortcut to clear the current input In Slime, I would like to clear the input I have currently typed into the REPL topline. What is the shortcut?
For example, if I type the below, it is missing one parenthesis and will not execute. How do I simply clear the whole text from my input line? I.e. instead of having to manually press delete on each character
 (let* ((x 5) (y (+ x x))
  (print y))

I could not find anything here:
https://common-lisp.net/project/slime/doc/html/REPL-commands.html
These solutions seem to be different (but please correct me if I'm wrong) and relate to the whole screen, while I'm interested in clearing what I have typed but not yet evaluated:
emacs cider clear REPL buffer
In emacs, how do I bind C-l to clear screen in slime?

A: It's C-c C-u, which is slime-repl-kill-input.  A good trick is to use C-h b which will cause Emacs to show you the current bindings in a help buffer: you can then search through them looking for likely candidates.  C-h m is also useful to show help on the current mode, which should show you the bindings as well (but may not: I'm not sure if it always does).  The advantage of these things is that they show you what actually exists rather than what the manual thinks exists which may not be the same thing (even when there is a manual...).


text:
Q: Group objects based on similar value in array of objects I have an array of objects I want to group/merge the objects which have similar branches and environments and concat their pools at the same time.
const data = [
  {
    branch: "master",
    environment: "dev",
    pool: "6g",
    service: "amex",
  },
  {
    branch: "master",
    environment: "dev",
    pool: "6g",
    service: "amex",
  },
  {
    branch: "feature/rest",
    environment: "dev",
    pool: "2g",
    service: "amex",
  },
  {
    branch: "master",
    environment: "dev",
    pool: "4g",
    service: "amex",
  },
  {
    branch: "hotfix/23",
    environment: "test",
    pool: "9g",
    service: "amex",
  },
  {
    branch: "hotfix/23",
    environment: "test",
    pool: "1g",
    service: "amex",
  },
];

I want the result in the below format removing duplicate objects as well I tried to reduce it but as array reduce returns a single object as a result and the other objects are being omitted from the response what data structure or way I can use to achieve the result?
const result = [
  {
    branch: "master",
    environment: "dev",
    pool: "6g, 4g",
    service: "amex",
  },
  {
    branch: "feature/rest",
    environment: "dev",
    pool: "2g",
    service: "amex",
  },
  {
    branch: "hotfix/23",
    environment: "test",
    pool: "9g,1g",
    service: "amex",
  },
];

A:

const data = [{
    branch: "master",
    environment: "dev",
    pool: "6g",
    service: "amex",
  },
  {
    branch: "feature/rest",
    environment: "dev",
    pool: "2g",
    service: "amex",
  },
  {
    branch: "master",
    environment: "dev",
    pool: "4g",
    service: "amex",
  },
  {
    branch: "hotfix/23",
    environment: "test",
    pool: "9g",
    service: "amex",
  },
  {
    branch: "hotfix/23",
    environment: "test",
    pool: "1g",
    service: "amex",
  },
];

var cacheMix = {};

for (var i = 0; i < data.length; i++) {

  var item = data[i];
  var compositeKey = item.environment + "~" + item.branch;

  if (cacheMix[compositeKey]) {
    cacheMix[compositeKey].pools[item.pool] = 1;
  } else {
    var pools = {}; pools[item.pool] = 1; //to avoid dublicate pools
    cacheMix[compositeKey] = {
      branch: item.branch,
      environment: item.environment,
      service: item.service,
      pools: pools
    }
  }
}

var result = [];

for (var key in cacheMix) {

  var item = cacheMix[key];
  result.push({
    branch: item.branch,
    environment: item.environment,
    service: item.service,
    pool: Object.keys(item.pools).join(", ")
  });
}

console.log(result);

A: Just create a dictionary out of them and fill in the values.
const data=[{branch:"master",environment:"dev",pool:"6g",service:"amex"},{branch:"feature/rest",environment:"dev",pool:"2g",service:"amex"},{branch:"master",environment:"dev",pool:"4g",service:"amex"},{branch:"hotfix/23",environment:"test",pool:"9g",service:"amex"},{branch:"hotfix/23",environment:"test",pool:"1g",service:"amex"},]

let x = {};
data.forEach(y => x[y.branch + "|" + y.environment] = y);

var res = Object.values(x).map(y => Object.assign({}, y)).map(y =>
{
    y.pool = data.filter(d => d.branch == y.branch && d.environment == y.environment).map(x => x.pool).join(",");
   return y;
})

If you do not care about immutability(original objects in data change), then remove Object.assign map  and it will yield the same results

A: data.reduce((prev, curr) => {
  const container = prev.find(
    el => (el.branch === curr.branch) && (el.environment === curr.environment)
  );
  if (container) {
    container.pool = container.pool + `,${curr.pool}`
    return prev;
  } else {
    return prev.concat({...curr})
  }
}, [])

but I would suggest to instead create an object with keys equal to branch names.

A: I'd suggest using Array.reduce() for this, creating a map of the data using a key created from the branch and environment.
Once we have the map object, we can use Object.values() to return an array of the desired results.

const data = [ { branch: "master", environment: "dev", pool: "6g", service: "amex", }, { branch: "feature/rest", environment: "dev", pool: "2g", service: "amex", }, { branch: "master", environment: "dev", pool: "4g", service: "amex", }, { branch: "hotfix/23", environment: "test", pool: "9g", service: "amex", }, { branch: "hotfix/23", environment: "test", pool: "1g", service: "amex", }, ];

const result = Object.values(data.reduce((acc, { branch, environment, pool, service }) => {
    // Our grouping key...
    const key = `${branch}-${environment}`;
    acc[key] = acc[key] || { branch, environment, pool: '', service };
    acc[key].pool += ((acc[key].pool ? ", " : "" ) + pool);
    return acc;
}, {}))

console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; }

A: This is one way to do it:

const data=[{branch:"master",environment:"dev",pool:"6g",service:"amex"},{branch:"feature/rest",environment:"dev",pool:"2g",service:"amex"},{branch:"master",environment:"dev",pool:"4g",service:"amex"},{branch:"hotfix/23",environment:"test",pool:"9g",service:"amex"},{branch:"hotfix/23",environment:"test",pool:"1g",service:"amex"},]

const res = data.reduce((acc, cur) =>
{
    let isMatch = false
    acc.forEach((el, idx) => {
        if(el.branch === cur.branch && el.environment === cur.environment) {
            if(acc[idx].service !== cur.service) {
                acc[idx].service += `, ${cur.service}`
            }
            if(acc[idx].pool !== cur.pool) {
                acc[idx].pool += `, ${cur.pool}`
            }
            isMatch = true
        }
    })
    if(!isMatch) {
        acc.push(cur)
    }

    return acc
}, [])

console.log(res)


text:
Q: Дочерний блок шире родительского блока с ограниченной шириной. Как сделать? Имеется колонка с текстом. На странице она одна и занимает примерно 70% от всей ширины страницы. Расположена по-центру.

Внутри текст и некоторые другие элементы, включая изображения.
Нужно сделать так, чтобы изображения занимали, скажем, 90% от ширины всей страницы.

Тут все дело вот в чем.

*

*Использовать position: absolute не получится, потому как часть текста не будет видна, ибо будет находиться за картинкой.

*Просто указать ширину равную, скажем, 180% для изображения тоже нельзя, иначе результат будет примерно следующий.

*Также стоит учесть, что изображения могут быть разные по ширине. Из этого следует, что нужно сделать следующее: более мелкие изображения, которые не дотягивают до ширины колонки, нужно растягивать так, чтобы они занимали 100% ширины род. элемента. А те, что шире нужно растягивать так, чтобы занимали не более 90% от ширины всей страницы. Грубо говоря все это дело должно выглядеть примерно так:

img {
    min-width: 100%; /* от ширины родителя */
    max-width: 90%; /* от ширины всей страницы */
}

Как подобное можно реализовать? Допускается обрамлять img в div'ы и другие теги.
Вспомнил об еще одном не подходящем способе: вариант обрамления всего содержимого кроме картинок в дополнительный тег и придание ему margin или padding. Этот вариант не подходит как минимум по двум причинам: задача заключается в том, чтобы разрешить картинке быть на всю (почти) ширину страницы, оставаясь при этом по-центру, а не сместить все кроме картинок, чтобы они казались растянутыми (1). И использование дополнительных тегов (что будет крайне неудобно делать каждый раз) (2).

A: Достаточно использовать относительные единицы измерения.

body {
  background-color: #eee;
}
.container {
  background-color: #fff;
  max-width: 70%;
  margin: 0 auto;
  padding: 10px; /* Для красоты */
}
img {
  display: block;
  transform: translateX(-50%);
  margin-left: 50%;
  max-width: 90vw;
  min-width: 100%;
}

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ullam optio quasi sapiente labore enim nisi sit, facere adipisci corrupti distinctio. Fuga eos in debitis, recusandae rerum minus nulla sint doloribus ducimus dolore non, repellendus, ullam quia.
    Molestiae enim ratione eaque?

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Velit nemo sit qui dolorem, minima quibusdam. Cumque aperiam sint odio culpa totam alias explicabo suscipit voluptates officiis adipisci temporibus, amet ipsum, vero voluptatibus consequatur
    rerum, aut ullam. Sequi iusto, similique. Quis eaque, veritatis sapiente ea amet, veniam neque voluptatem repellendus possimus laboriosam quasi nam aliquam ullam similique, expedita. Quo aliquam molestias ratione nemo pariatur sed velit, sint nulla
    tempore eveniet maiores nesciunt explicabo quas! Nesciunt, reprehenderit! Soluta voluptatibus perferendis quod nam.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Pariatur a saepe eveniet similique laudantium non aut delectus, facere libero ut vitae, enim tempore magnam eligendi adipisci cum minus. Eius doloremque molestias, dolores consequatur hic! Culpa
    eveniet, velit nam dolor dignissimos!

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ullam optio quasi sapiente labore enim nisi sit, facere adipisci corrupti distinctio. Fuga eos in debitis, recusandae rerum minus nulla sint doloribus ducimus dolore non, repellendus, ullam quia.
    Molestiae enim ratione eaque?

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Velit nemo sit qui dolorem, minima quibusdam. Cumque aperiam sint odio culpa totam alias explicabo suscipit voluptates officiis adipisci temporibus, amet ipsum, vero voluptatibus consequatur
    rerum, aut ullam. Sequi iusto, similique. Quis eaque, veritatis sapiente ea amet, veniam neque voluptatem repellendus possimus laboriosam quasi nam aliquam ullam similique, expedita. Quo aliquam molestias ratione nemo pariatur sed velit, sint nulla
    tempore eveniet maiores nesciunt explicabo quas! Nesciunt, reprehenderit! Soluta voluptatibus perferendis quod nam.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ullam optio quasi sapiente labore enim nisi sit, facere adipisci corrupti distinctio. Fuga eos in debitis, recusandae rerum minus nulla sint doloribus ducimus dolore non, repellendus, ullam quia.
    Molestiae enim ratione eaque?

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Velit nemo sit qui dolorem, minima quibusdam. Cumque aperiam sint odio culpa totam alias explicabo suscipit voluptates officiis adipisci temporibus, amet ipsum, vero voluptatibus consequatur
    rerum, aut ullam. Sequi iusto, similique. Quis eaque, veritatis sapiente ea amet, veniam neque voluptatem repellendus possimus laboriosam quasi nam aliquam ullam similique, expedita. Quo aliquam molestias ratione nemo pariatur sed velit, sint nulla
    tempore eveniet maiores nesciunt explicabo quas! Nesciunt, reprehenderit! Soluta voluptatibus perferendis quod nam.

Разверните пример на всю страницу. Так лучше видно, что картинки 90% шириной.

A: Вариант расчёта через проценты от ширины родительского блока
Родительский блок занимает 70% окна и расположен по центру. Изображение занимает 90% от ширины окна. То есть, оно будет выступать влево и вправо на 10% от ширины окна. Это составляет 10% / 70% = 0,1428571429 от ширины родительского блока.
А ширина изображения составит 90% / 70% = 1,2857142857 от ширины родителя.
Значит, нужно задать изображению такие свойства:
margin: 0 -14.28571429%;
width: 128.57142857%;

Проверяем:

.container {
  background: #9c6;
  margin: 0 auto;
  padding: 100px 0;
  width: 70%;
}
.container img {
  margin: 0 -14.28571429%;
  width: 128.57142857%;
}


text:
Q: Create an entry in index without creating a Chapter or Section title My thesis is about a project I developed in a company. During the project, I generate several official documents that I'm appending at the end (using includepdf package). These documents have their own cover, so it's not necessary to create an almost blank page with only "Appendix A - Lorem ipsum", but if I don't include this I lose my reference in the index. What should I do?
Thanks in advance!

A: You can use option addtotoc provided by package pdfpages for the included pdf:
\documentclass{report}
\usepackage{lipsum}% only for dummy text
\usepackage{pdfpages}

\begin{document}
\tableofcontents
\includepdf[pages=-,addtotoc={1,chapter,0,First included pdf,incl:first}]{dummy.pdf}
\chapter{Another chapter}
\lipsum
\includepdf[pages=-,addtotoc={1,chapter,0,Second included pdf,incl:second}]{dummy.pdf}
\end{document}

Or with the same result:
\documentclass{report}
\usepackage{lipsum}% only for dummy text
\usepackage{pdfpages}

\begin{document}
\tableofcontents
\clearpage
\refstepcounter{chapter}\label{incl:first}
\addcontentsline{toc}{chapter}{\protect\numberline{\thechapter}{First included pdf}}
\includepdf[pages=-]{dummy.pdf}
\chapter{Another chapter}
\lipsum
\clearpage
\refstepcounter{chapter}\label{incl:second}
\addcontentsline{toc}{chapter}{\protect\numberline{\thechapter}{First included pdf}}
\includepdf[pages=-]{dummy.pdf}
\end{document}

Note that the order of \clearpage, \addcontentsline and \includepdf is important to get the right page number in ToC.
If there should be unnumbered chapter entries for the included pdfs:
\documentclass{report}
\usepackage{lipsum}% only for dummy text
\usepackage{pdfpages}

\begin{document}
\tableofcontents
\clearpage
\addcontentsline{toc}{chapter}{First included pdf}
\includepdf[pages=-]{dummy.pdf}
\chapter{Another chapter}
\lipsum
\clearpage
\addcontentsline{toc}{chapter}{Second included pdf}
\includepdf[pages=-]{dummy.pdf}
\end{document}

A: This should work
\clearpage
\addcontentsline{toc}{chapter}{name that appear in the toc}
\includepdf{file.pdf}

the first option "toc" stays for table of contents (where you will add the entry).
the second let you to choose between chapter or section depending on your need.
the third is the name that appear in the index
(Maybe you should compile it twice to make it work)


text:
Q: Issue with frame closing Tkinter I am having a issue with my frame switching after I click a button for my results. My button is hooked up to for inserting the fields into a database and it does do that but after it does it pulls the login screen back to the toplevel of the screen and just stay on the same screen how can I prevent this from happening? I am thinking its happening once the db closes. I don't get any errors.
if self.first == "":
    ms.showerror('Please enter a first name')
elif self.last == "":
    ms.showerror('Please enter a last name')
elif self.date == "":
    ms.showerror('Please enter a username')
elif self.addr == "":
    ms.showerror('Please enter a password')
elif self.phoneNum == "":
    ms.showerror('Please enter a password')
else:
    findSql = 'SELECT firstname, lastname FROM client WHERE firstname =? and
    lastname=? '
c.execute(findSql, [(self.first),(self.last)])
    f = c.fetchall()
    if f:
        ms.showerror('User already exist')
    else:
        ms.showinfo('Account has been created')
        self.insert = 'INSERT INTO client(firstname, lastname, birthdate,
    address, phone, symptom1, symptom2, symptom3, symptom4, symptom5)
    VALUES(?,?,?,?,?,?,?,?,?,?)'
c.execute(self.insert,[self.first, self.last, self.date, self.addr,
    self.phoneNum, self.sym1, self.sym2, self.sym3, self.sym4, self.sym5])
db.commit()
db.close()
# runs calculation accuracy for random forest
a = Algo()
a.randomForest(self.master,self.Symptom1, self.Symptom2, self.Symptom3, self.Symptom4,self.Symptom5)


text:
Q: Creating a column in SQL based on condition across multiple columns I am looking to create a column in SQL table with the column names of those fields that match a condition(columns that contain value 1 for a TID)
Here the first table gives the SQL table I want to work on. And the below one gives the output I am expecting

A: The two additional columns that you are trying to create don't have any new information that isn't already present or can't be computed already.
The two columns can be thought of as a result of a function with which takes in the original 5 columns, gives in some result.
You can should take a look at virtual columns. Your use case should be solved with it.
More specifically if you are using Postgres , refer this and this.
And this for MySQL.

A: You can unpivot using cross apply and filter:
select t.*, v.*
from t outer apply
     (values ('field1', field1), ('field2', field2), ('field3', field3), ('none', 0)
     ) v(matchedfield, counter)
where (matchedfield = 'none' and field1 + field2 + field3 = 0) or
      (matchedfield <> 'none' and field1 + field2 + field3 > 0) ;


text:
Q: Closed subsets of rational functions when the coefficients are endowed an Euclidean topology Suppose $\text{rat}(n)$ denotes the collection of proper rational functions such that: if $f \in \text{rat}(n)$, then
\begin{align*}
  f(z) = \frac{ b_{n-1} z^{n-1} + \dots + b_0 }{z^n + a_{n-1}z^{n-1} + \dots + z_0}.
\end{align*}
In other words, the numerator is a polynomial of degree at most $n-1$ and the denominator is a monic polynomial of degree $n$. Endow the coefficients $(a_0, \dots, a_{n-1}, b_0, \dots, b_{n-1}) \in \mathbb R^{2n}$ the Euclidean topology. I read in a book without proof that the subset of $\text{rat}(n)$ (togologize the coefficients) that has no common factor (in the numerator and denominator) is an open subset. It states that having a common factor is an open condition. How do I prove this fact?

A: Let $f,g$ be polynomials in a variable $z$. They have a common factor iff there exists some $a$ such that $f(a)=g(a)=0$. This immediately tells you that having a common factor is a closed condition. Consequently, having no common factor is an open condition.

A: I realized the answer lies in the resultant of two polynomials. If $f, g$ has no common factor, then the resultant $\text{res}(f, g) = 0$. And apparently $\text{res}(f, g)$ is a polynomial in the coefficients, which is precisely a closed condition on the coefficients.


text:
Q: php вычислить разницу дат Не получается написать скрипт. Смысл с в том, что мне нужно сравнить время которое записано у пользователя в бд, с текущим, и если разница составляет более 2 минут, выполнить запрос.  В данный момент выдает ошибку след:

PHP Warning:  strtotime() expects parameter 1 to be string, array given in
  PHP Fatal error:  Uncaught Error: Unsupported operand types in line 28

28 строка

$diff = abs($currentTime - $date);

$currentTime = date("Y-m-d H:i:s");

 $connect_to_db = mysqli_connect($domain, $username, $password, $db)
or die(mysqli_connect_error()($connect_to_db));

$qr_result2 = mysqli_query($connect_to_db, "select date from users ")
  or die(mysqli_error($qr_result2));
while($date = mysqli_fetch_array($qr_result2, MYSQLI_BOTH)){
$need_time = 120;
$date1 = strtotime($date);
$date2 = strtotime($currentTime);
$diff = abs($currentTime - $date);
if($diff > $need_time) {
тут будет sql запрос

}

A: Сам разобрался. Если кому надо бдует
$diff = ("0:2:0");
$curDate = new DateTime($currentTime ); //текущее время
$diffDate = new DateTime($date[0]); //время записанное у пользователя
$difference = $curDate->diff($diffDate);

echo $difference->format("%H:%I:%S");
if ($difference>$diff){
$qr_result = mysqli_query();
}


text:
Q: Tracking app installation and campaign details without Third-party APIs For my iOS App, I am using Campaign Links from App Store Connect for advertisement purposes, and sometimes use Branch links.
Is it possible to get Campaign details inside app after installation is done  natively without using  any third party SDKs?
I would like to know from which campaign the installation came from with apple provided technology.
Is it possible to get the details inside the app programatically?

I have heard that In Android, they can achieve the functionality using InstallReferrerClient of the library com.android.installreferrer:installreferrer
Do we have any similar option for iOS?

Please guide, Thank you.


text:
Q: What is needed to mirror both an iPad and a late-2016 MacBook Pro to an HDTV (non-concurrently)? I want to be able to mirror an iPad Air and a late-2016 MacBook Pro to an HDTV. Not simultaneously, just one at a time. I know I could just get both the lightning to digital av adapter and the usb-c (thunderbolt 3) to digital av adapter, but is there a way to do it where I wouldnt need both? Like maybe a female usb-c to male lightning adapter (but it would need to be able to pass both video and audio).
If it helps reduce the amount of stuff I'd need to purchase, I already have HDMI to HDMI, HDMI to mini HDMI, and HDMI to mini DP (thunderbolt 2).

A: Do you happen to have an Apple TV?
If so, that would be how I'd do it, using Airplay.
If not, then any Apple TV (2nd generation and above) supports Airplay and you already have the cable (i.e. HDMI to HDMI) that you need to connect it to your HDTV.
The advantage of this is that you also get all the benefits of having the Apple TV as well, not to mention the fact you won't have your iPad or MBP tethered with a cable (or cables) to your HDTV (i.e. the mirroring happens via WiFi and you're able to have the iPad or MBP anywhere you want while mirroring).
If your question is about connecting these devices to any HDTV that you may need to connect to (i.e. not a single one at your home, but to various models in various locations) or you do not want/need an Apple TV, then I'm not aware of a single solution that will pass both video and audio from both devices, but perhaps someone else will have a solution.
[EDIT]
Just checked and Apple are selling refurbished 3rd generation Apple TVs for $59. At that price, it'd be hard to warrant spending the money on cables and/or adaptors, unless you intend to carry them with you in your travels.
You can also buy brand new Apple TV 3 units from places like Target who still have them in stock (since they've been superseded).


text:
Q: Mapboxgl:Always show layer icon while zoom in and out after certain zoom level I am trying to disable disappearing MapboxGl.Layer icon while zoom in out.Is there any metadata or property configuration to show layer all icon at onces.
for example after minzoom:7.4 as below given in layer instance i want to show all geojson data.
{
  "id": "Car",
  "type": "symbol",
  "source": {
    "type": "geojson",
    "data": {
      "type": "FeatureCollection",
      "features": [
        {
          "type": "Feature",
          "properties": {
            "icon": "Car"
          },
          "geometry": {
            "type": "Point",
            "coordinates": [
              -117.42187500000001,
              57.51582286553883
            ]
          }
        },
      ...
      ...
      ]
    }
  },
  "layout": {
    "icon-image": "{icon}",
    "icon-size": 0.04,
    "visibility": "visible"
  },
  "minzoom": 7.4,
  "metadata": {
    "imageurl": "dist/images/Mapboxgl/Entities/Car.png",
    "center": [
      -119.09913365922579,
      56.054006240841346
    ],
    "zoom": [
      12
    ]
  }
}

How to display all data together at zoom level 7.4?
Added example:
Codesandbox
JSFiddle
click on addLayer button.
Actual result:Only displying layer 3 icons.
Expected result:Want to show all Layer icon show.
please any help.
Thanks.


text:
Q: Unable to get Polymer 2 iron-flex-layout to work Banging my head against the wall here. Barebones Polymer 2.0 project, able to create my custom components, I can't get iron-flex-layout or iron-flex-layout-classes to work.
Installed Polymer CLI, and installed Polymer using bower.
Directory structure:
/bower_components
    polymer, webcomponentsjs, iron-flex-layout, shadycss

index.html

Inside index.html:

    <meta charset="UTF-8">

    <link rel="import" href="/bower_components/polymer/polymer.html"/>

    <link rel="import" href="bower_components/iron-flex-layout/iron-flex-layout.html">
    <link rel="import" href="/bower_components/iron-flex-layout/iron-flex-layout-classes.html">

Horizontal

A

B

C

Vertical

A

B

C

I run polymer build, and upload the build/default directory to my server. Refreshing the page, I expect to see "Horizontal A B C" to use .horizontal.layout style provided by iron-flex-layout-classes.html, and "Vertical A B C" to use @apply rule from style inside head element of the page.
Neither of those things are happening. I believe I followed the guide to the T and it doesn't work. Here's what I see in the inspector when I inspect the first element:

And here's second:

As you can see, in the CSS area of the inspector, "inherited from html" chunk is displaying all the mix-ins. I'm pretty sure it's not supposed to show up in there like that. And here's close up:

Lines that contain @apply in CSS var definitions are crossed out. I'm totally confused. Is my installation of Polymer messed up somehow? I get no errors, however, and my custom elements appear to work (except for the iron-flex stuff, classes or @apply).
I tried using paper components, which also work, but appear un-styled.
Any clues?
Thanks in advance.

A: I'm thinking you can't get to the styles in iron-flex-layout-classes.html because they are masked by the Shadow DOM. You should use the CSS variables to get to them. Also, you must wrap your
    </custom-style>

Horizontal

A

B

C

Vertical

A

B

C

A: You just need to wrap your
  </custom-style>

  <custom-style>

  </custom-style>

Horizontal

A

B

C

Vertical

A

B

C


text:
Q: Decimal Value error I'm writing a program that grabs 2 inputs from the user: 1) the price of an item 2) the amount payed. It will then return the difference of the two (change due) and it will then compute how many bills and coins would be given back. I'm having trouble when finding the decimal (coin values accurately):
int one, five, ten, twenty,qs, ds, ns, ps, rem ;
    double price, pay,change;
    String user;
    Scanner input = new Scanner(System.in);
    do {
        System.out.print("Price: $");
        price = input.nextDouble();
        System.out.print("From: $");
        pay = input.nextDouble();
        change = pay - price;

        twenty =  (int) (change / 20.00);
        rem =  (int) (change % 20.00);
        ten =  (int) (rem / 10.00);
        rem =  (int) (rem % 10.00);
        five =  (int) (rem / 5.00);
        rem =  (int) (rem % 5.00);
        one =  (int) (rem);
        //
        qs = (int) rem / 25;
        rem = (int) rem % 25;
        ds = (int) rem / 10;
        rem = (int) rem % 10;
        ns = (int) rem / 5;
        rem = (int) rem % 5;
        ps = (int) rem;
        System.out.println("Computed change: $" + change);
        System.out.println(twenty + " x $20 bills, \n" + ten
                + " x $10 bills, \n" + five + " x $5 bills, \n" + one
                + " x $1 bills, \n" + qs + " x 25c coins \n" + ds
                + " x 10c coins \n" + ns + " x 5c coins \n" + ps
                + " x 1c coins \n");

        System.out.println("Would you like to enter another "
                + "quantity? (Y or N):");
        input.nextLine();
        user = input.nextLine();

        if (!user.equalsIgnoreCase("y")) {
            System.out.println("Goodbye!");
        }
    } while (user.equalsIgnoreCase("y"));
    input.close();
    // System.exit(0);

I'm almost sure the problem lies in casting the value of the remainder as an int, which would discard any value after the decimal point. I've tried dividng and modulo operation with .25, .10, .5, .1 but that doesn't seem to work. There is something I'm not seeing.

A: Compute the price in cents, this way you can avoid using decimal places.

A: You should not use double or float for currency as their precision is not perfect. You might want to convert the entire number as a Long representing the cents, then format to output the decimal. That way, your math calculus will be decimal free.
Something like
Long price = Long.parseLong(input.nextLine().replace(",", ""));
NumberFormat n = NumberFormat.getCurrencyInstance(Locale.US);
String s = n.format(price / 100.0);
System.out.println(s);

Now, you should be able to easily resolve your issue.


text:
Q: Designing an attendance system using QR code with Firebase I'm doing a academic project. simply the idea is creating an Attendance system that goes like this:

*

*The Teacher logs in to his account in the website.

*Teacher selects a section.

*Teacher generates a QR Code to let the students scan it to attend.

*The Student Sign in into his account using an android app.

*Students Opens the scanner to scan the QR Code.

*The system marks the attendance of that student in that specific section and in a specific date.

here is my design of the firebase database that i'm using
db{

    Teachers{
         "cEEbohuR2bK6opZJ1z5RoPrbbrx1":{ //auth uid
              tchName:"Jason",
              tchID:"24123"
    }
    Students:{
         "GsBEVEtZ9CeqzztDWEQd9GluVJJ3":{  //auth uid
              studentName:"Mark",
              stuID:"37294"
}
    Courses:{
         "JAVA101":{  //courseID
              courseName:"Java Programing",
}
    Sections:{
        "56345":{ //secID
         tchID:"24123", //acts like a foreign key
         courseID:"JAVA101", //acts like a foreign key
           Students:{
            "37294":{
               studentName:"Mark"
       }
   }
}

    Attendance:{
        "56345":{ //secID
           "1-8-2018":{ //auto generated date?
               "37294":{ //stuID
                  attended:"true" // sets to true after scanning the qr code
            }
          }
        }
     }
  }

My idea of the qr code thing is when the teacher generates it the value in the QR would be the Section ID then somehow I need to merge it with student ID when the student scans it, after getting the two values I need to auto generate the date of the lecture
,so i would have 3 values(secID,stuID,date) to insert it into the Attendance tree and make the "attended" attribute sets to "true"
Now my questions are:

*

*is there any better way to design my DB?

*is my qr idea above possible to execute or is there a better way?

A: Do you need the instructor to retrieve the attendance list? The nested object you show above could be flatter if your needs were different. In Firebase, you need to create your DB structure after your views (e.g., what you will retrieve from DB to show to users). Nesting is strongly discouraged against and duplication of data is acceptable.
For example if I wanted users to read the list of attendees by choosing a  section ID and date, I would create a table like this:
Attendance:{
    "123456":                //section ID
       {"01-08-2019":        //date
           {"865768": true}  //student ID: attendance status
       }
           }

I can retrieve the list of attendees using the reference:
`Attendance/${sectionID}/${date}/`

Or I can have a flatter list if I wanted my users to click on a student's ID and retrieve all attendance records by the student:
AttendanceRecord: {
     "865768": {     //student ID
     "LxLy1a":   {   //unique attendance record key
               date: "01-08-2019",
               sectionId: "123456",
               status: true
                }
                   }

If my app's views were different, I would have to structure my database differently so that data is easier to read from Firebase without going too deep into the nested object.
You must not be too afraid to duplicate your data. Change your database based on the views in your app.


text:
Q: Send message to SQL Server message queue from C# Win CE I have a queue called log_line_queue in database cja on SQL Server ITSERVER.
I have a C# Win CE application running on a mobile device. I want to send a message from this application to log_line_queue.
This is my code so far:
var myQueue = new System.Messaging.MessageQueue("FormatName:Direct=OS:itserver\\private$\\dbo.cja.log_line_queue");

myQueue.Send("My Message Data.", MessageQueueTransactionType.Automatic);

It results in
System.Messaging.MessageQueueException: Message Queue service is not available.
   at System.Messaging.MessageQueue.MQCacheableInfo.get_WriteHandle()
   at System.Messaging.MessageQueue.StaleSafeSendMessage(MQPROPS properties, IntPtr transaction)
   at System.Messaging.MessageQueue.SendInternal(Object obj, MessageQueueTransactionType transactionType)
   at System.Messaging.MessageQueue.Send(Object obj, MessageQueueTransactionType transactionType)
   at cjaTest1.MessageQueue.FrmSendToQueue.button1_Click(Object sender, EventArgs e)
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnClick(EventArgs e)
   at System.Windows.Forms.ButtonBase.WnProc(WM wm, Int32 wParam, Int32 lParam)
   at System.Windows.Forms.Control._InternalWnProc(WM wm, Int32 wParam, Int32 lParam)
   at Microsoft.AGL.Forms.EVL.EnterModalDialog(IntPtr hwnModal)
   at System.Windows.Forms.Form.ShowDialog()
   at cjaTest1.FrmMainForm.button9_Click(Object sender, EventArgs e)
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnClick(EventArgs e)
   at System.Windows.Forms.ButtonBase.WnProc(WM wm, Int32 wParam, Int32 lParam)
   at System.Windows.Forms.Control._InternalWnProc(WM wm, Int32 wParam, Int32 lParam)
   at Microsoft.AGL.Forms.EVL.EnterMainLoop(IntPtr hwnMain)
   at System.Windows.Forms.Application.Run(Form fm)
   at cjaTest1.Program.Main()

I'm sure I'm doing many things wrong. Suggestions are welcome.

A: System.Messaging.MessageQueue is used to interact with MSMQ. A queue called log_line_queue in database cja on SQL Server ITSERVER is either a table or a Service Broker Queue. This is Apples and Oranges, MSMQ has nothing to do with SQL Server. To send messages to a SQL Server queue you must use the SEND T-SQL verb, and you must be connected to a SQL Server instance.


text:
Q: Show default Gmap winforms I was using Gmap in winform,
while gmap loading will be show default like this :

I wanna Gmap show default map in my local(latitude - longitude) which I give before Gmap load
and with zooming like I want like this

A: Solution:
GMap.NET.WindowsForms.GMapControl map;
map.Position = new PointLatLng(Latitude, Longitude);


text:
Q: jmeter parametrization for appending 0 to all values of csv file In have to parameterize csv file in my Jmeter scenario.
All values in csv start from zero like
0123456789
0234567899
0112312312
0423423433
0423423422

Since all values are as zero therefore csv is not supporting it which causes parametrization is not working.
How to avoid this?

A: CSV Data Set config doesn't have any validation of input so values starting from zero should be fine.
The most common mistake for beginners is incorrect location of CSV Data Set Config in Test Plan. Try adding it inside Loop Controller (or alternatively configure your Thread Group Loop Count parameter) and put CSV Data Set Config as a child if the request, you're trying to parametrize.


text:
Q: how to show a varibal in text flutter I'm trying to make the dollar sign recognize the   snapshot.data[i]['name']   But she only gets to know snapshot
plz help me DropdownSearch(items: [ for (i=0 ; i < 10; i++) "$snapshot.data[i]['name']", ])

A: I am writing what I understand from your question
"${snapshot.data[i]['name']"}, ]


text:
Q: Install ctags from npm: no such option --no-parallel I recently installed node and npm to try it out but during an installation of a module it stuck on the ctags package which it depended on. Trying to only install ctags resulted in a weird error which I could not find a solution for.
henje@mymachine:~/test/node-ctags$ npm install
npm http GET https://registry.npmjs.org/grunt
npm http GET https://registry.npmjs.org/nan/0.8.0
npm http GET https://registry.npmjs.org/bindings
npm http GET https://registry.npmjs.org/grunt-contrib-coffee
npm http GET https://registry.npmjs.org/event-stream
npm http GET https://registry.npmjs.org/grunt-shell
npm http GET https://registry.npmjs.org/node-gyp
[...]

> ctags@0.11.0 install /home/henje/test/node-ctags
> node-gyp rebuild

Usage: gyp_main.py [options ...] [build_file ...]

gyp_main.py: error: no such option: --no-parallel
gyp ERR! configure error
gyp ERR! stack Error: `gyp` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onCpExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:340:16)
gyp ERR! stack     at ChildProcess.EventEmitter.emit (events.js:98:17)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (child_process.js:797:12)
gyp ERR! System Linux 2.6.36.4-vs2.3.0.36.39-nc
gyp ERR! command "node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /home/henje/test/node-ctags
gyp ERR! node -v v0.10.26
gyp ERR! node-gyp -v v0.13.0
gyp ERR! not ok

npm ERR! ctags@0.11.0 install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the ctags@0.11.0 install script.
npm ERR! This is most likely a problem with the ctags package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node-gyp rebuild
npm ERR! You can get their info via:
npm ERR!     npm owner ls ctags
npm ERR! There is likely additional logging output above.
npm ERR! System Linux 2.6.36.4-vs2.3.0.36.39-nc
npm ERR! command "node" "/usr/local/bin/npm" "install"
npm ERR! cwd /home/henje/test/node-ctags
npm ERR! node -v v0.10.26
npm ERR! npm -v 1.4.6
npm ERR! code ELIFECYCLE
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     /home/henje/test/node-ctags/npm-debug.log
npm ERR! not ok code 0

I am not sure if this is a general issue or just. I tried npm install ctags as well as cloning from github. I also checked if I have a recent gcc, etc. for gyp and have no idea left. I appreciate any answers.

A: I have also faced this issue while trying to install pm2 module.
As a workaround, removing gyp solved this problem for me:
sudo apt-get remove gyp
Here is the issue itself listed in pm2 repository: https://github.com/Unitech/pm2/issues/434


text:
Q: php encrypt and decrypt can anyone tell me how to encrypt and decrypt a URL string ?
I want to encrypt a hyperlink ...

A: If you can use database,you could create a table to map a file to an id.
Create a 'mapping_table'
id - integer
file_location - string

Your URL would look something like localhost/waterwell/e_book.php?id=12 .

A: make links that return to your server with querystring GET params identifying the file. the server  can then do echo file_get_contents() after you figure out which  file from the inputs
In your example it's trivial. simply omit the portion of the url you don't want shown and fill it back in on the server.

A:     $confirmpassword = $_POST['confirmpassword'];
            $value_check = true;
            $ciphering = "AES-128-CTR";
            $options = 0;
            $encryption_iv = '1234567891011121';
            $encryption_key = "GeeksforGeeks";
            $confirmpasswordencryption = openssl_encrypt($confirmpassword, $ciphering,$encryption_key, $options, $encryption_iv);

$encryption = "pABqPJhobIMHzqai"
                                                        $ciphering = "AES-128-CTR";
                                                        $options = 0;
                                                        $decryption_iv = '1234567891011121';

// Store the decryption key
$decryption_key = "GeeksforGeeks";

// Use openssl_decrypt() function to decrypt the data
$decryption=openssl_decrypt ($encryption, $ciphering,
        $decryption_key, $options, $decryption_iv);

// Display the decrypted string
echo "Decrypted String: " . $decryption;


text:
Q: What is the total resistance of circuit with transistor and 10K (for example) resistor (+pic)? Should it be more or less than 10K and why? I doubt that it can be less than 10К, because such current (voltage/10K) should go through base-emitter at least, and all other current should go via collector-emitter junction.

A: This circuit is non-linear and does not have a well-defined single number for "total resistance"; it will behave differently depending on whether the transistor remains in cutoff, or enters forward active mode. However, it's clear that its effective "resistance" can be far less than 10k, with the following proof by (counter)example.
Suppose that the voltage on the terminals is 1.0 V, and assume that Vbe is approximately 0.7 V in this configuration. The drop across the resistor is 300 mV, hence 30 uA flows to the base. If the hFE of the transistor is 100 (a reasonable assumption) then the collector current is 3 mA. 1.0 V / 3 mA is approximately 300 ohms.
You can differentiate all terms in the above derivation to convince yourself that the small-signal impedance around this operating point is also on the order of approx. 300 ohms.
On the other hand, for a voltage of 0.1 V, the resistance is indeed very large. The B-E junction of the transistor is reverse-biased, and no current aside from leakage can flow.

A: Unless you know the voltage it is undefined

A: If the voltage is less than a few hundred mV the effective "resistance" is far more than 10K.
If the voltage is greater than half a volt or so, it will be less, assuming the transistor has an hFE >> 1.
From a simulation:

The crossover in this simulation is at about 563mV. At higher voltages (above a few volts) it appears more like a 50-65\$\Omega\$ resistance. Self-heating is not simulated here. At 100mV it appears more like a ~50G\$\Omega\$ resistor.


text:
Q: OpenMP: Shared variables in single, nowait construct so I have this little snippet of code:
int a = 10;
bool finished = false;

#pragma omp parallel num_threads(3) shared(a, finished)
{
    while(!finished) {

        #pragma omp single nowait
        {
            printf("[%d] a is: %d\n", omp_get_thread_num(), a);
            a--;
            finished = true;
        }

    }
}

The output is
[0] a is: 10
[2] a is: 10
[1] a is: 10

Which is not what I expect at all. I realise that all the threads may make it into the single construct before exiting the while loop, but why do they all say the same a? The second thread that enters should have a = 9, and the third one a = 8.
I've tried #pragma omp flush and #pragma omp atomic on a but to no use. I'd like to use a for a comparison in that block (i.e. if(a == 10)) so it's crucial that the value is updated once another thread enters the single block. What am I doing wrong?

A: The problem with your code is that the single directive has basically no effect. By specifying the nowait clause other threads will not wait at the end of the block and instead enter the next loop iteration immediately.
That means, the first thread arriving at the single construct will execute the block in the first iteration. The remaining threads will skip the block  and immediately arrive again at the single construct in their second iteration. One of the two remaining threads then enters the block as well (since it's a new iteration and thus another occurence of the block). The other again skips and enters immediately in its third iteration. At the end, all threads execute nearly concurrently and print the initial value of a since none of the threads has succeeded to decrement a until this point in time.
You will see a changing if you swap the statements inside the single block as follows. However, the values and their order will be undetermined.
#pragma omp single nowait
{
    a--;
    printf("[%d] a is: %d\n", omp_get_thread_num(), a);
    finished = true;
}

A: I don't believe you want a single thread performing your code block, but rather you want to ensure that each thread is not stomping over the other threads' data in a and finished. This is accomplished with #pragma omp critical. Furthermore, you cannot have a nowait clause because by definition, the other threads will not enter the code block until the other thread has finished the critical region.
while(!finished) {

    // only 1 thread will enter this region at a time
    #pragma omp critical
    {
        printf("[%d] a is: %d\n", omp_get_thread_num(), a);
        a--;
        finished = true;
    }

}

Also, note that having this sort of thread inter-dependence is likely to kill performance. I would suggest you avoid this and change your algorithm unless you see no other way to do it.

A: I really am not sure what you try to achieve here... Actually, without any sort of work done by other threads outside of the single block, I don't see the point of the structure.
Anyway, I tried to extrapolate a bit and extended your example by adding a printf() statement outside of the block which also prints the value of a to see how this is transmitted to the other threads. Moreover, since you used a single directive, I assumed you wanted only one thread executing the block, even if it is on a while() loop. So it looked very well suited for the use of OpenMP locks...
Here is what I came up with:
#include <stdio.h>
#include <omp.h>
#include <unistd.h>

int main() {
    int a = 10;
    bool finished = false;
    omp_lock_t lock;
    omp_init_lock( &lock );
    #pragma omp parallel num_threads( 3 ) shared( a, finished )
    {
        while( !finished ) {
            if ( omp_test_lock( &lock ) ) {
                printf( "[%d] a is: %d\n", omp_get_thread_num(), a );
                #pragma omp atomic update
                a--;
                usleep( 10 );
                finished = true;
                #pragma omp flush( finished )
                omp_unset_lock( &lock );
            }
            #pragma omp flush( finished, a )
            printf( "[%d] outside of if block, a is: %d\n", omp_get_thread_num(), a );
        }
    }
    return 0;
}

I've added a call to usleep() to delay a bit the execution of the instructions inside the if block and give the other threads the opportunity to print something. I've tested it with gcc version 4.9 and 5.3 and Intel compiler 16.0, and all 3 give me the same sort of output, (with obviously some variations in the order and number of printings between runs).
The results looks like this:
~/tmp$ icpc -fopenmp omplock.cc
~/tmp$ ./a.out
[0] a is: 10
[1] outside of if block, a is: 10
[1] outside of if block, a is: 9
[1] outside of if block, a is: 9
[1] outside of if block, a is: 9
[1] outside of if block, a is: 9
[1] outside of if block, a is: 9
[2] outside of if block, a is: 10
[1] outside of if block, a is: 9
[0] outside of if block, a is: 9

Would this approach address your needs?


text:
Q: FileNotFoundException When entering a string after input prompt I'm not sure if I'm not entering my code the right way, or where the error in my actual code is. I'm relatively new to "try" "catch" and when I run the coverage of my code in Java it shows that after I enter the inputted string it goes straight to the error. Their is more than one class for this code's purpose but the code doesn't run through all of the classes before the error. The purpose of the code is to enter information about students and through the code determine if they match together. This class specifically is the main class of the program. The problem comes when i enter a string like "Abey," and I'll get the error.
ERROR:
Please give the student name:
Abey
java.io.FileNotFoundException: Abey (The system cannot find the file specified)
MY CODE
import java.io.FileNotFoundException;

import java.io.FileReader;

import java.util.NoSuchElementException;

import java.util.Scanner;

public class Match {

 public static void main(String[] args) {

  Student[] arr = new Student[100];

  System.out.println("Please give the student name: ");

  Scanner input = new Scanner(System.in);

  String filename = input.next();

  Scanner nameInput;
  try {
   nameInput = new Scanner(new FileReader(filename));

   int i = 0;

   while (nameInput.hasNextLine()) {

    Scanner ab = new Scanner(nameInput.nextLine());

    ab.useDelimiter("[\t-]");

    String name = ab.next();

    String gender = ab.next();

    String date = ab.next();

    Scanner birthDateReader = new Scanner(date);

    birthDateReader.useDelimiter("-");

    int month = birthDateReader.nextInt();

    int day = birthDateReader.nextInt();

    int year = birthDateReader.nextInt();

    int quietTime = ab.nextInt();

    int music = ab.nextInt();

    int reading = ab.nextInt();

    int chatting = ab.nextInt();

    Date birthdate = new Date(month, day, year);

    Preference pref = new Preference(quietTime, music, reading, chatting);

    Student studentAdd = new Student(name, gender.charAt(0), birthdate, pref);

    arr[i++] = studentAdd;

   }

   int max = i;

   for (i = 0; i < max; i++) {

    if (!arr[i].getMatch()) {

     int bestScore = 0;
     int bestMatch = 0;

     for (int j = i + 1; j < max; j++) {

      if (!arr[j].getMatch()) {

       int tmp = arr[i].compare(arr[j]);

       if (tmp > bestScore) {

        bestScore = tmp;

        bestMatch = j;

       }

      }

     }

     if (bestScore != 0) {

      arr[i].setMatched(true);

      arr[bestMatch].setMatched(true);

      System.out.println(arr[i].getName() + " can match with " + arr[bestMatch].getName() + " with the score " + bestScore);

     } else

     if (!arr[i].getMatch())

      System.out.println(arr[i].getName() + " Does not have any matches.");

    }

   }

   input.close();
  } catch (NoSuchElementException e) {
   System.out.println(e);

  } catch (FileNotFoundException e) {
   System.out.println(e);
  }

 }

}

A: The process cannot find the Abey file relative to the working directory. Try to specify the full path:
File root = new File("/path/to/data/files");
...
String filename = ....;
File datafile = new File(root, filename);
try (FileReader reader = new FileReader(datafile)) {
  ....
}

A: The main Problem is, Program is searching as relative path. You need to provide the complete path of the file.
String completePath = "/opt/java/path/"
Scanner input = new Scanner(System.in);

String filename = input.next();

Scanner nameInput;
try {
nameInput = new Scanner (new FileReader(completePath+filename));

This will be the modified code for you.
Here completePath variable contains path of the folder on which you have stored files by student name.


text:
Q: HTML formatting in Rmarkdown I used this solution from stefan to automatically create tables in R-markdown as below.
It works great but I would like to add some formatting to the code. I have tried to add some html code to the tags in the functions, but I am not getting the expected results. As an example of the formatting I would like to add the formatting below, taken from this link:
<!DOCTYPE html>

HTML Table

The orginal solution is as follows:
---
title: "HTML Table"
date: '2022-04-19'
output: html_document
---

```{r echo=FALSE}
dat <- structure(list(
  row = structure(c(
    1L, 1L, 1L, 1L, 1L, 2L, 2L,
    2L, 2L, 2L, 3L, 3L, 3L, 4L, 4L, 4L
  ), .Label = c(
    "Lower threshold",
    "Upper threshold", "Category W", "Category M"
  ), class = "factor"),
  value = c(
    0, 25, 50, 100, 250, 25, 50, 100, 250, 500, 5,
    38, 5, 0, 3, 5
  ), width = c(
    50, 50, 50, 50, 50, 50, 50, 50,
    50, 50, 100, 100, 100, 100, 100, 100
  ), colspan = c(
    NA, NA,
    NA, NA, NA, NA, NA, NA, NA, NA, 1, 2, 2, 1, 2, 2
  )
), row.names = c(
  NA,
  -16L
), class = "data.frame")
```

```{r}
head(dat)
```

```{r echo=FALSE}
make_html_table_row <- function(row, label) {
  htmltools::tagList(
    htmltools::tags$td(label, width = "150"),
    purrr::pmap(row, function(row, value, width, colspan) {
      htmltools::tags$td(value, width = width, colspan = if (!is.na(colspan)) colspan)
    })
  ) |>
    htmltools::tags$tr()
}

make_html_table <- function(x) {
  x_split <- split(x, x$row)
  purrr::imap(x_split, make_html_table_row) |>
    htmltools::tagList() |>
    htmltools::tags$table(border = "1") |>
    htmltools::tags$html()
}
```

```{r results='asis'}
make_html_table(dat)
```

DATA
Code used to create the data.
dat <- list(
  data.frame(
    row = "Lower threshold",
    value = c(0, 25, 50, 100, 250),
    width = 50,
    colspan = NA
  ),
  data.frame(
    row = "Upper threshold",
    value = c(25, 50, 100, 250, 500),
    width = 50,
    colspan = NA
  ),
  data.frame(
    row = "Category W",
    value = c(5, 38, 5),
    width = 100,
    colspan = c(1, 2, 2)
  ),
  data.frame(
    row = "Category M",
    value = c(0, 3, 5),
    width = 100,
    colspan = c(1, 2, 2)
  )
) |>
  dplyr::bind_rows()

dat$row <- factor(dat$row, levels = c("Lower threshold", "Upper threshold", "Category W", "Category M"))

Could anyone show me where the tags should go, either in the function or in the data?

A: A quick and dirty approach to achieve your desired result would be to add the CSS directly to your markdown file:
---
title: "HTML Table"
date: '2022-04-19'
output: html_document
---

```{r echo=FALSE}
dat <- structure(list(
  row = structure(c(
    1L, 1L, 1L, 1L, 1L, 2L, 2L,
    2L, 2L, 2L, 3L, 3L, 3L, 4L, 4L, 4L
  ), .Label = c(
    "Lower threshold",
    "Upper threshold", "Category W", "Category M"
  ), class = "factor"),
  value = c(
    0, 25, 50, 100, 250, 25, 50, 100, 250, 500, 5,
    38, 5, 0, 3, 5
  ), width = c(
    50, 50, 50, 50, 50, 50, 50, 50,
    50, 50, 100, 100, 100, 100, 100, 100
  ), colspan = c(
    NA, NA,
    NA, NA, NA, NA, NA, NA, NA, NA, 1, 2, 2, 1, 2, 2
  )
), row.names = c(
  NA,
  -16L
), class = "data.frame")
```

```{r}
head(dat)
```

```{r echo=FALSE}
make_html_table_row <- function(row, label) {
  htmltools::tagList(
    htmltools::tags$td(label, width = "150"),
    purrr::pmap(row, function(row, value, width, colspan) {
      htmltools::tags$td(value, width = width, colspan = if (!is.na(colspan)) colspan)
    })
  ) |>
    htmltools::tags$tr()
}

make_html_table <- function(x) {
  x_split <- split(x, x$row)
  purrr::imap(x_split, make_html_table_row) |>
    htmltools::tagList() |>
    htmltools::tags$table() |>
    htmltools::tags$html()
}
```

```{r results='asis'}
make_html_table(dat)
```


text:
Q: How to give an error in one of the cells when both cells contain certain text? For example, A1 and A2 both contains the text "Upper Case", and I can't allow A1 and A2 to both contain "Upper Case", so I want the excel to give an error in A2
11: https://i.stack.imgur.com/JQK5M.png


text:
Q: Magento rewrite tags url I had created tag called test in Magento but its default url is like tag/product/list/tagId/1/ but i need the url  to be like the tag/test.
I tried magento-tag-url-rewrite-and-generate and magento-tag-url-rewrite, but it returns 404 page not found on accessing the url like tag/test.
Please Help Me.
Thanks in Advance

A: Take a look at this: https://stackoverflow.com/q/24608684/2047249.
You can find the code provided in the answer as an extension here: https://github.com/tzyganu/EasylifeTag.
The main idea is to create a custom router that handles the urls like tag/something and to rewrite the tag model so the urls generated will be tag/something instead of tag/product/list/tagId/1/

A: Tag is the module name while product or test (in your case) are the controller name. You can't get the tag/test/.. url unless you have testController.php in  Tag module's controller folder. As this is custom url so the simple way is to create this file and place in app/code/local/Mage/Tag/controllers/ and then code in that file according to your requirements.


text:
Q: How many ways can we construct $(a,b,c,d)$ such that $a \geq b, c \geq d$ and $a+b \geq c+d$? I've been stuck on the counting problem described below for a while. I'm constructing ordered sequences of four positive integers of the form $(a,b,c,d)$, each of which are bounded above. i.e. $$a,b,c,d \in \{1,2,...,N\}$$ so that each of the variables can take on $N$ possible values. Of course, the number of lists we can form this way is $N^4$. Now, I impose that both $a\geq b$ and $c \geq d$. Since these conditions are independent, one can consider the number of ways to construct the first two elements of the list and square it. The number of ways to construct $(a,b)$ such that $a \geq b$ is simply $\frac 12 N(N+1)$, so the answer to this problem is $$\left(\frac 12 N(N+1) \right)^2=\frac 14 N^2(N+1)^2.$$ Now, where I'm getting stuck is the addition of a third constraint. This is to require that $a+b \geq c+d$, thus making the first two and last two components dependent on each other. My question is therefore: How many ordered lists of the form $(a,b,c,d)$ such that $$a,b,c,d \in \{1,2,...,N\}$$
$$a \geq b, \qquad c\geq d$$
$$a+b \geq c+d$$ are there?

A: I agree with the previous analysis.  We know that the number of ways
$a+b > c+d$ equals the number of ways $a+b < c+d$.  We find the number
of ways $a+b = c+d$, calling it $f(n)$.  Then the answer to the
problem is
 $$ \frac{\displaystyle\frac{n^2(n+1)^2}{4}-f(n)}{2} + f(n)
  = \frac{n^2(n+1)^2}{8} + \frac{f(n)}{2}.$$
The value of $f(n)$ depends upon the parity of $n$.  If $n$ is even,
  $$ f_e(n) = \frac{n(2n^2+3n+4)}{12}. $$
If $n$ is odd,
  $$ f_o(n) = \frac{(n+1)(2n^2+n+3)}{12}. $$
The function for odd and even $n$ were reached by establishing a
pattern using numbers and then using induction.