text:
Q: How can I pass images to a CSS Paint Worklet? I am trying to create a custom background for a h1-tag using the CSS Paint API. The background should be clipped to the text, so essentially I would like to 'color' it.

*

*Unfortunatly '-webkit-canvas' was deprecated. A requirement is to actually use a h1 tag, and not just render text in a canvas and use composition modes.

*I would like to pass in multiple images to draw with ctx.drawImage.

The spec is pretty clear on this:

CSS.registerProperty({
  name: '--my-image',
  syntax: '<image> | none',
  initialValue: 'none',
  inherits: false,
});

class MyWorklet {
  static get inputProperties() {
    return ['--my-image'];
  }

  paint(ctx, geom, properties) {
    const img = properties.get('--my-image');
    console.log(img);
    ctx.drawImage(img,10,10,150,180);
  }
}
registerPaint('myworklet', MyWorklet);

However, Chromium has no support for this. The current workaround seems to be to pass the images through the background-image: , property. This will unfortunatly collide with registering the paint worklet as background-image (background-image: paint(worklet); background-clip: text;).
What are other ways to pass images into the paint worklet? Doesn't necessarily have to be through css variables. I am fine with hardcoding or importing images directly into the paint worklet.


text:
Q: Wi-Fi disconnect and has to reboot my computer to fix I have my ASUS laptop
When its on for a while i get the WiFi not working
it disconnect me and when I try to reconnect again it does not
The only way to resolve this is by restarting the laptop.
I tried to disable the wifi card from Devices menu and enable it back, but that does not make the WiFi work again
I had to restart to fix it.
I wonder if anyone has a fast solution to get the WiFi working without the need of restarting the laptop.
P.S.
* The Router is OK, I got other devices connected to the same Router and no problems at all.
* When I get this problem I try to connect to other routers (WiFi connections) and nothing works.
Thanks

redpajama_set_name: RedPajamaStackExchange


text:
Q: How is CPU usage calculated? On my desktop, I have a little widget that tells me my current CPU usage. It also shows the usage for each of my two cores.
I always wondered, how does the CPU calculate how much of its processing power is being used? Also, if the CPU is hung up doing some intense calculations, how can it (or whatever handles this activity) examine the usage, without getting hung up as well?

A: There's a special task called the idle task that runs when no other task can be run. The % usage is just the percentage of the time we're not running the idle task. The OS will keep a running total of the time spent running the idle task:

*

*when we switch to the idle task, set t = current time

*when we switch away from the idle task, add (current time - t) to the running total

If we take two samples of the running total n seconds apart, we can calculate the percentage of those n seconds spent running the idle task as (second sample - first sample)/n
Note that this is something the OS does, not the CPU. The concept of a task doesn't exist at the CPU level! (In practice, the idle task will put the processor to sleep with a HLT instruction, so the CPU does know when it isn't being used)
As for the second question, modern operating systems are preemptively multi-tasked, which means the OS can switch away from your task at any time. How does the OS actually steal the CPU away from your task? Interrupts: http://en.wikipedia.org/wiki/Interrupt

A: One way to do it is as follows:
Pick a sampling interval, say every 5 min (300 seconds) of real elapsed time.  You can get this from gettimeofday.
Get the process time you've used in that 300 seconds. You can use the times() call to get this.  That would be the new_process_time - old_process_time, where old_process_time is the process time you saved from the last time interval.
Your cpu percentage is then (process_time/elapsed_time)*100.0
You can set an alarm to signal you every 300 seconds to make these calculations.
I have a process that I do not want to use more than a certain target cpu percentage.  This method works pretty good, and agrees well with my system monitor.  If we're using too much cpu, we usleep for a little.

A: The CPU doesn't do the usage calculations by itself. It may have hardware features to make that task easier, but it's mostly the job of the operating system. So obviously the details of implementations will vary (especially in the case of multicore systems).
The general idea is to see how long is the queue of things the CPU needs to do. The operating system may take a look at the scheduler periodically to determine the number of things it has to do.
This is a function Linux in (ripped from Wikipedia) that performs said calculation:
#define FSHIFT   11  /* nr of bits of precision */
#define FIXED_1  (1<<FSHIFT) /* 1.0 as fixed-point */
#define LOAD_FREQ (5*HZ) /* 5 sec intervals */
#define EXP_1  1884  /* 1/exp(5sec/1min) as fixed-point */
#define EXP_5  2014  /* 1/exp(5sec/5min) */
#define EXP_15 2037  /* 1/exp(5sec/15min) */

#define CALC_LOAD(load,exp,n) \
    load *= exp; \
    load += n*(FIXED_1-exp); \
    load >>= FSHIFT;

unsigned long avenrun[3];

static inline void calc_load(unsigned long ticks)
{
    unsigned long active_tasks; /* fixed-point */
    static int count = LOAD_FREQ;

    count -= ticks;
    if (count < 0) {
        count += LOAD_FREQ;
        active_tasks = count_active_tasks();
        CALC_LOAD(avenrun[0], EXP_1, active_tasks);
        CALC_LOAD(avenrun[1], EXP_5, active_tasks);
        CALC_LOAD(avenrun[2], EXP_15, active_tasks);
    }
}

As for the second part of your question, most modern operating systems are multi-tasked. That means the OS is not going to let programs take up all the processing time and not have any for itself (unless you make it do that). In other words, even if an application appears hung, the OS can still steal some time away for its own work.

A: To get CPU usage, periodically sample the total process time, and find the difference.
For example, if these are the CPU times for process 1:
kernel: 1:00:00.0000
user:   9:00:00.0000

And then you obtain them again two seconds later, and they are:
kernel: 1:00:00.0300
user:   9:00:00.6100

You subtract the kernel times (for a difference of 0.03) and the user times (0.61), add them together (0.64), and divide by the sample time of 2 seconds (0.32).
So over the past two seconds, the process used an average of 32% CPU time.
The specific system calls needed to get this info are (obviously) different on every platform. On Windows, you can use GetProcessTimes, or GetSystemTimes if you want a shortcut to total used or idle CPU time.

A: there is a number of ways you can do it:
Processor maintains several counters which measure performance, you can access them using Papi interface.  for example here is a brief introduction: http://blogs.oracle.com/jonh/entry/performance_counter_generic_events
also: http://www.drdobbs.com/tools/184406109
the counter you may want is PAPI_TOT_CYC which is number of busy cycles (if I remember correctly)

A: This is my basic understanding from having a little exposure to similar code. Programs like Task Manager or your widget access system calls like NtQuerySystemInformation() and use the information gathered from the OS to make the simple calculation of the percent of time a CPU is idle or being used (in a standard amount of time). A CPU knows when it is idle so it can therefore determine when it's not idle. These programs can indeed get clogged up...my crummy laptop's Task Manager freezes all the time when calculating CPU usage when it's topping out at 100%.
A cool bit of example code can be found on MSDNs website that shows function calls for calculating CPU usage for a set of instructions: http://msdn.microsoft.com/en-us/library/aa364157(VS.85).aspx
What these system calls do is access kernel code I believe... which is beyond the scope of my understanding.

A: Well, as far as I understand it there's a giant
while(true){}

loop that the operating systems spins up. Your process is managed from within that loop. It allows external code to be executed directly on the processor in chunks. Without exaggerating too much, this is an uber-simplification of what is actually going on.

A: *

*The CPU does not get 'hung' up, it is simply operating at peak capacity, meaning it is processing as many instructions as it is physically capable every second.
The process that is calculating CPU usage is some of those instructions. If applications try to do operations faster than the CPU is capable, then simply they will be delayed, hence the 'hung up'.

*The calculation of CPU utilization is based on the total available utilization. So if a CPU has two cores, and one core has 30% usage, and the other is 60%, the overall utilization is 45%. You can also see the usage of each individual core.


text:
Q: Removing CrossOver Games from Unity Start panel I'm new to Ubuntu and  recently installed CrossOver Games Trial on Ubuntu 12.04, didn't like it, tried to uninstall it but simply refused to go away , so I just went on and deleted the folders in the File System.
Problem is that now there are 4 icons left on the Unity Start Panel under "installed applications", and I don´t know how to remove it. Actually, could anyone tell me how to delete any shortcut that is created on the Start Panel? Is there a way to do it?
Thank you very much!

A: The shortcut that you are talking about are called .desktop files.  They are in one of two places.
/usr/local/share/applications
or
home/.local/share/applications   Note that the .local is a hidden file so you will need to show hidden files Ctrl+h to see them
Most likely the files are in the usr/local so you will need to use sudo to delete them.
When you delete these .desktop files they will no longer show up in your Dash under Installed applications but will still show up in the recent history until you open enough other programs to push them out.


text:
Q: MSAccess - dbSeeChanges error? I have a database that has been working well for a couple years until this morning.  When I attempt to copy the contents of a remote table into a local backend, I am presented with an err:  "Error 3622 - You must use the dbSeeChanges option..."
The remote table is on a server and does have an AutoNumber attribute.  The backend table is a simple readonly/static snapshot that does not care about the auto numbering datatype and is defined simply as Number - I just need the table (snapshot) to be local for performance concerns.
I added the dbSeeChanges variable without success - complains about "Too few Parameters" on the db.execute line (below).
Here are some details from my db:
Dim db As Database
dim strSQL as string
Set db = CurrentDb()

strSQL = "INSERT INTO Item " & _
    "SELECT dbo_Item.* " & _
    "FROM dbo_Item " & _
    "WHERE dbo_Item.MASTER_INVID=  " & TempVars!my_InvID

    db.Execute strSQL, dbFailOnError + dbSeeChanges

What am I missing? Any suggestions to avoid/correct.

A: Another way to do this is to make a copy of the linked table then covert that to a local table:
localTableName = "Item"
DoCmd.CopyObject , localTableName , acTable, "dbo_Item"
DoCmd.SelectObject acTable, localTableName , True
RunCommand acCmdConvertLinkedTableToLocal


text:
Q: Integrat Ecwid shopping cart with my android application My client want to integrate his Ecwid acoount with android application...
i get products information from Ecwid using diffrent available apis,also able to place order but cant able on further procedure for payment...
some one please help me

A: Ecwid provides Custom Payments API that should be the proper solution in your case. The documentation is here: http://kb.ecwid.com/w/page/49187841/AuthorizeNet%20Emulation#Custompaymentgateways
Hope that helps.


text:
Q: build `remarkjs` without `highlighterjs` I am already using highlighterjs and would rather use the externally included highlighter(js and css) and build a version of remarkjs that is much smaller. I can't figure out how to accomplish this. The included make.js file is supposed to build the highlighter only if the highlighter target is explicitly specified, but seems to automatically include it even if not specified. Suggestions?

A: See https://github.com/gnab/remark/wiki/Contributing#building for instructions on how to build remarkjs without the highlighting library, and still use it with an externally included library for highlighting code.


text:
Q: Where to get multiple Public IP addresses from? I have a broadband connection that has one single Public IP address,
Now I want to set up a home datacenter with OpenStack,
My problem is that whenever I launch a new VPS in my master server, each VPS needs a Public IP address in order to be accessible from the outer world.
I understand that I can add IP address and pools,
However, How can I get those extra IP address?
From my ISP?
And how costly can it be?
How many ip addresses can I have? is there a limit?
Sorry, noob here.

A: You do not necessarily need more IPv4 addresses, you might be able to use IPv6 or NAT.
However, if you determine that you do need/want more IPv4 addresses, they must be from your ISP, either your current or another that provides multiple IPs, as they must be routed to you.
In general, there is a shortage of IPv4 addresses, so you usually have to specify a reason why you would need them, in addition to recurring payments.


text:
Q: Custom 24 hour format to calculate difference between dates in Excel I have reported date & time in the format (MM/DD/YYYY HH:MM) and resolved date & time in the same format. I would like to calculate the difference between the reported date & time and resolved date & time, excluding weekends (which are Friday and Saturday). Also, for ex: if the reported time is 10 PM it should count 1 day if it the resolved time is on or after 10pm the next day.

A: Assuming your data starts in row 2, column A
If you have the start time in A2, and the resolved time in B2.
Since your data is cleanly in a Date/Time format, you can simply subtract the greater time period from the lesser.
This will give you the amount of days, and hour in decimals (hours as a percent of hours in the day).
=(B2-A2) ' Days and hours to resolve

=(B2-A2)*24 ' Hours it took to resolve


text:
Q: Отключение эмуляции запросов php 7.2 при выставлении атрибуту PDO::ATTR_EMULATE_PREPARES значения FALSE, возникает ошибка:
Fatal error: Uncaught Error: Call to a member function bindValue() on boolean in
На локальной машине и VPS-хостинге (LAMP Ubuntu), на веб-хостинге атрибут принимает значение false
Также при запросе ошибок:
Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'time.dp.date_start' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by in
Запрос:
select dp.*,msp.sale
from discount_products dp inner join ms_products msp on msp.ms_id=dp.product_ms_id
where dp.date_end >= :date group by dp.product_ms_id order by dp.date_start

более того, это не единственный запрос, возвращающий fatal error


text:
Q: Can I show/hide a certain cell in an UITableView depending on the state of another cell? I have a UITableView with style "Grouped" which I use to set some options in my App. I'd like for one of the cells of this UITableView to only show up depending on whether another of this UITableView's cells is activated or not. If it's not, the first cell should show up (preferably with a smooth animation), if it is, the first cell should hide.
I tried returning nil in the appropriate -tableView:cellForRowAtIndexPath: to hide the cell, but that doesn't work and instead throws an exception.
I'm currently stuck and out of ideas how to solve this, so I hope some of you can point me in the right direction.

A: Here's a handy post in which the author provides some source code for performing animations on the currently selected cell:
http://iphonedevelopment.blogspot.com/2010/01/navigation-based-core-data-application.html
He's using this in a NSFetchedResultsController context, but you can see how he's using various calls to add/remove cells & sections.
Now, in your case, you'll need to modify whatever array you're using to host the data used to generate the rows in your tableView when you "activate" your cell, then selectively use:

*

*tableView:insertRowsAtIndexPaths:withRowAnimation:

*tableView:deleteRowsAtIndexPaths:withRowAnimation:

*tableView:insertSections:withRowAnimation:

*tableView:deleteSections:withRowAnimation:

to adjust things accordingly (you can start with tableView:reloadData:, but it's inefficient).
I realize that the API can be a bit daunting, but take the time to read through it and understand what the various calls do.  Understanding how the UITableView uses its datasource and delegate, as well as the chain of events that occur when cells are selected/deleted/etc., is important if you want to get things just right (and crash-free).

A: [tableView beginUpdates];
[tableView deleteRowsAtIndexPaths:withRowAnimation:]; // or insertRowsAtIndexPaths:withAnimation:
[tableView endUpdates];

A: You should remove the data behind the hidden cells from the table view's data source.
For example, if you are using an array, when an action occurs that causes a cell to be hidden, you would remove the object for that row from the array. Then, as the table view's data source, the array will return one less total count and only return valid cells for every row in that count (no nil).
This approach may require maintaining a second array with all of the objects (including hidden).
To update the view, check out reloadRowsAtIndexPaths:withRowAnimation:.

A: Before cellForRowAtIndexPath is called, numberOfRowsInSection is called. You should return the appropriate value of cells in the section there, so if you only want to show 1 cell, return one. The logic what cells are shown has to be implemented partially in both methods


text:
Q: How to use hyperledger getnative API for example getState and putState I came across the getNative API through which one call chaincode from Hyperledger composer. See here: https://github.com/hyperledger/composer/issues/3120
Can someone please tell me exactly how to use getState() and putState()?

A: Composer is built on top of Fabric. So although the fabric has getState() and putState() the composer generated API does not have same API call. Use the GET to call the Assets or Transactions. Also, read about Historian API. That might help you out. Late move away from composer as its deprecated.


text:
Q: How to find the center of gravity or center of mass of an irregular body with uniform mass distribution? Recently I was trying to solve a small AI problem but got stuck in between as I could not find the center of mass of the various bodies.
I was wondering if any one of you could help me out with this one.
Problem explanation: Assume that i have a 2D body which is very irregular in shape and has a uniform mass distribution throughout. It's like the body is made up of 'n' tiny particles each of unit mass and hence though the body is very irregular in shape but the mass distribution is uniform. How can I locate the center of mass or center of gravity of this body?
Avanish!!

A: Calculating a polygon's center of mass:
Simplify your body into a polygon, and find its centroid, because (quoting wikipedia):

If an object has uniform density then
  its center of mass is the same as the
  centroid of its shape.

This approach is faster if there are lots of particles, uniformly distributed within the polygon.
Calculating the mean location of all particles:
If you're having n particles, calculate the mean of their X and Y coordinates; That's the center of mass.
Quoting wikipedia again:

The center of mass  of a system of
  particles is defined as the average of
  their positions, weighted by their
  masses:

Your particles have the same mass, so your denominator equals n. The code in @tkerwin's answer calculates that fraction.
This approach works well if you don't have too many particles.
Edit:
Probabilistic calculation:
If you have too many points to efficiently calculate their mean location, try picking up some random points. Calculating their mean location would give you an excellent approximation of the entire mean. The more points you pick, the better is your approximation - according to the Law Of Large Numbers.

A: The center of mass is the average position of each particle weighted by the mass of that particle.  Since your particles are of the same mass, you only need to take the average position.
That is:
center_x = 0
center_y = 0
for p in particles:
    center_x += p.x
    center_y += p.y
center_x /= len(particles)
center_y /= len(particles)

A: OK. I get it now. You have a vast number of discrete particles to work with. With emphasis on the big number.
Well, why didn't you say?
You can't do it exactly (i.e. without approximation) any faster than iterating though all the points. At least not without providing more relevant information.
Adam's sampling suggestion is a good way to obtain an approximation if you have random access to the data.
An alternative that won't be faster for a single operation, but might be useful if you are going to have to recalculate often is to reduce the working set to a smaller group of heavier points. Something like this:

*

*Divide space into a grid of N_x * N_y * N_z cells of sizes (l_x,l_y,L_z).

*Compute the total mass and location of the center of mass for all the points in each cell.

*Discard any cells with no points contained, and use the results as the new working set.

For this to represent an improvement, you'll want to have an average of 10 or more original points per cell, but not so many that the introduced grandularity washes out the signal you are looking for.
How best to do step 2 depends on how the original data is organized and on how much room you have in memory to store intermediate results. With lots of memory available:

*

*Prepare and initialize to zero four (N_x,N_y,N_z) arrays called M, Rx, Ry, and Rz (or one scalar array M and one vector array R, that depends on your implementation language)

*Walk the main list on time, incrementing the values in the appropriate cell for each mass

*Walk the intermediate arrays to figure the collected masses and locations.

With relatively little memory but lots of time available for pre-calculation you would walk the main list once for every cell (but if you have that kind of time you probable can just do this straight).


text:
Q: Javascript toggle working but shows unstyled menu On my ruby on rails 5 app I have a menu button that uses javascript to toggle the menu, the toggle function is showing and hiding the menu but the menu is not styled with css anymore
onclick the menu toggles like it should but all the elements are not styled, I dont know if its related to rails or I am missing something here

//Toggle between adding and removing the "show_for_mobile" class to admin_side_bar when the user clicks on the icon
function toggleNav() {
  var x = document.getElementById("admin_side_bar");
  console.log(x.className)
  if (x.className === "admin_side_bar") {
    x.className += "show_for_mobile";
  } else {
    x.className = "admin_side_bar";
  }
}
.admin_side_bar {
  width: 70%;
  height: 50vh;
  background-color: #e2e6e8;
  position: absolute;
  left: 0;
  top: 60px;
  padding: 20px 10px;
  display: none;
}

//show side bar on click
.show_for_mobile {
  display: block;
}

.admin_side_bar>ul {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

.admin_side_bar>ul>a {
  color: #3d3d3d;
  font-size: 19px;
  text-decoration: none;
}

.admin_side_bar>ul>a:hover {
  color: #06bed3;
}

.admin_side_bar .fas {
  margin-right: 20px;
  color: #afaeae;
}

.admin_side_bar .fas:hover {
  color: #7a7a7a;
}

.admin_side_bar>ul>a>li {
  margin-bottom: 20px;
}

Home

Items

Orders

Stats

Blog

A: When you add the .show_for_mobile class the original display:none from .admin_side_bar still takes precedence. If all you really want to do is show the nav then you can use x.style.display = "block"; to overwrite display:none from the admin_side_bar class
x.style.display="block" works because it adds inline style which is the highest CSS specificity (it overwrites all other css rules).
From CSS specificity

Inline styles added to an element (e.g., style="font-weight:bold") always overwrite any styles in external stylesheets, and thus can be thought of as having the highest specificity.

document.getElementById("toggleButton").addEventListener("click", toggleNav);
//Toggle between adding and removing the "responsive" class to topnav when the user clicks on the icon
function toggleNav() {
  var x = document.getElementById("admin_side_bar");
  if (x.className === "admin_side_bar") {
    x.className += " show_for_mobile";
    x.style.display = "block";
  } else {
    x.className = "admin_side_bar";
    x.style.display = "none";
  }
}
.admin_side_bar {
  width: 70%;
  height: 50vh;
  background-color: #e2e6e8;
  position: absolute;
  left: 0;
  top: 60px;
  padding: 20px 10px;
  display: none;
}

//show side bar on click
.show_for_mobile {
  display: block !important;
}

.admin_side_bar>ul {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

.admin_side_bar>ul>a {
  color: #3d3d3d;
  font-size: 19px;
  text-decoration: none;
}

.admin_side_bar>ul>a:hover {
  color: #06bed3;
}

.admin_side_bar .fas {
  margin-right: 20px;
  color: #afaeae;
}

.admin_side_bar .fas:hover {
  color: #7a7a7a;
}

.admin_side_bar>ul>a>li {
  margin-bottom: 20px;
}
<button id="toggleButton">Toggle Nav</button>

Home

Items

Orders

Stats

Blog


text:
Q: Connection refused for a few hours I use a Linode server, and have had about a half-dozen domains running on it for the past couple years without issue. It's running Ubuntu 10.04 and Apache.
Today, for about 3 hours, all http requests were refused. I was able to ssh in without issue, and looked at the Apache error log and saw nothing interesting other than scores of 'the mysql server went away' errors.
The system is set up to ping me if the io rate gets very high, which does happen when the Drupal sites do a mysql backup, but that didn't happen today.
I also did a netstat -aon and verified that the listeners for :80 and :8080 were running (Varnish on :80), though some of the instances had TIME_WAIT instead of LISTEN.
A few minutes after rebooting everything was back to normal. What could be the cause of this?

A: You checked the apache error_log, but not the mysql log. It's highly likely that mysql is what caused this problem. The "the mysql server went away" error should have clued you into this.
Anyway, check your mysql error log, and I'll bet you find something interesting.
In regards to your TCP TIME_WAIT states, that's not unexpected, nor is it anything to be concerned about.

A: Something else to look at is your firewall.  If this were to happen again I would run a iptables -L just to make sure a process is not putting a firewall rule in place.


text:
Q: Mathematica NIntegrate problem Here is my code:

The problem is that I always see these messages every time I run it

They always say " something has evaluated to a non-numerical values of all sample points in the region"
I try to add ?NumericQ in my function but it seems that I still get same errors.
I am entirely new to Mathematica. I hopes someone could help me. Thank you in advance.


text:
Q: R: Looping and syntax when grouping rows My data is 18 rows by 8 columns. It contains both numerical and word data. I want to assing each row an ID number. I want to group the rows with the same info in the first 5 columns by the same ID number. For some reason I don't think I am looping properly. Any thoughts?
sampdata<-read.csv("xxx")

sampdata["ID"] <- 0 #ID column

count<-1 #to subtract from 10000

for (p in 1:18) {

if (sampdata[p,9] == 0){

count<-count+1

sampdata[9,p]<-10000-count

for (i in 1:5){ #column index for current check (only check defining info)

  for (j in 1:18) { #row index for current check

    for (k in 1:18){ #column index for current check against

      if (sampdata[i,j]==sampdata[i,k])

        sampdata[j,9]<-sampdata[9,p] #assign same ID number

    }
  }
}

}
}

A: Assuming your data looks something like this
mm<-matrix(c(
1,1,2,2,3, 1,1,2,2,3,
2,2,2,3,3, 2,2,2,3,3,
4,3,2,1,2, 1,1,2,2,3,
3,1,1,2,2
), byrow=T, ncol=5)

dd<-data.frame(mm[,1:3],
    X4=letters[mm[,4]], X5=mm[,5],
    matrix(runif(nrow(mm)*(18-ncol(mm))), nrow=nrow(mm)))

Where your data is in dd and the first 5 columns define a group. You can use interaction() to assign a unique ID to each group like this
dd$ID <- as.numeric(interaction(dd[,1:5], drop=T, lex.order=T))


text:
Q: "People in sneakers are fast out of desperation, not wealth." What does it mean? I came across a sentence from an old New Yorker article:

The New Yorker, August 7, 1978 P. 18
Illustrated talk story about gauging people's income by their shoes and how fast they walk. Writer's observations were inspired by a young millionaire whom he followed up Fifth Ave. and lost because the tycoon walked twice as fast as anybody else. In the area around Broadway and 72nd St. writer sees a girl in saddle shoes who probably gets money from home, an old man shuffling along on Social Security, a woman in gold high heels with an estimated 5-figure income. Sandals are low-income. People in sneakers are fast out of desperation, not wealth.

Does the adverb fast mean firmly here? I can't understand what the sentence means. People in sneakers are firmly out of desperation? What is not wealth?

A: Fast just means quick here. Out of means because of, due to.

People in sneakers are fast because of desperation, not wealth.

The writer is trying to contrast people who wear sneakers with the young millionaire mentioned earlier who walked quickly. The millionaire's shoes weren't mentioned, just his pace. The author wants to clarify that speed does not always indicate wealth.


text:
Q: my code in php doesn't open the desired output I'm just learning PHP, and during the process of learning, the tutor asked me to create two files: a HTML file and a PHP file. The HTML file (named name.html) looks like this:
<!DOCTYPE html>

    <title> Today’s Date </title>
    <meta name="viewport" content="width=device-width">
    <meta http-equiv="content-type" content="text/html; charset=utf-8">

    Hi, I’m Kevin!

while the PHP file (named name.php) is this:
<!DOCTYPE html>

    <title> Today’s Date </title>
    <meta name="viewport" content="width=device-width">
    <meta http-equiv="content-type" content="text/html; charset=utf-8">

    <?php
       $name = $_GET['name'];
       echo 'Welcome to our website, ' . $name . '!';
    ?>

Now the problem is this: the php file should output "Welcome to our website, Kevin!" after the link on the html file has been clicked according to the author. But mine doesn't, in fact it doesn't output anything at all.
I wonder if there is a problem with my code. Any php expert in the house should please put me through.
thanks.

A: It seems you don't have a PHP server running,
if you are on Windows, you should try WAMP (http://www.wampserver.com)

A: if you are running  in localhost then you are url should be like
http://localhost/a.html
also make sure in wamp or xampp ,apache running or not.

A: You have to run this file under localhost (server). The reason why nothing appears in the browser is that by default browser would make <?php ... ?> as  if viewed without being parsed by the server.
Fix: View it on a server.


text:
Q: C++ Sending vector with socket loosing data Im trying to send an Image with sockets from the server to the client, but for some reason im losing a lot of data.
this is my server:
#include <opencv2/imgcodecs.hpp>
#include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
#include <string>

#define PORT 8080

using namespace cv;
using namespace std;

int main(int argc, char const *argv[])
{
    int server_fd, new_socket, valread;
    struct sockaddr_in address;
    int opt = 1;
    int addrlen = sizeof(address);
    char buffer[1024] = {0};

    // Creating socket file descriptor
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0)
    {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }

    // Forcefully attaching socket to the port 8080
    if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT,
                                                &opt, sizeof(opt)))
    {
        perror("setsockopt");
        exit(EXIT_FAILURE);
    }
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons( PORT );

    // Forcefully attaching socket to the port 8080
    if (bind(server_fd, (struct sockaddr *)&address,
                                sizeof(address))<0)
    {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }
    if (listen(server_fd, 3) < 0)
    {
        perror("listen");
        exit(EXIT_FAILURE);
    }
    if ((new_socket = accept(server_fd, (struct sockaddr *)&address,
                    (socklen_t*)&addrlen))<0)
    {
        perror("accept");
        exit(EXIT_FAILURE);
    }

  Mat image = cv::imread("Rio.jpg",IMREAD_COLOR); //BGR
  std::vector< uchar > buf;
  cv::imencode(".jpg",image,buf);

  cerr << send(new_socket , buf.data() , buf.size(),0);
  cerr << buf.data();

  return 0;
}

The output of this file is:
562763����
562763 should be the size of data that is send to the client and ���� should be the data.
This is my Client:
#include <opencv2/imgcodecs.hpp>
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <string>
#include <stdlib.h>
#include <netinet/in.h>
#include <iostream>
#define PORT 8080
using namespace std;
using namespace cv;
int main(int argc, char const *argv[])
{
    int sock = 0, valread;
    struct sockaddr_in serv_addr;

    char buffer[1024] = {0};
    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        printf("\n Socket creation error \n");
        return -1;
    }

    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(PORT);

    // Convert IPv4 and IPv6 addresses from text to binary form
    if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr)<=0)
    {
        printf("\nInvalid address/ Address not supported \n");
        return -1;
    }

    if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
    {
        printf("\nConnection Failed \n");
        return -1;
    }

    int l = 0;
    std::string data = "";
    do{
        data += buffer;
            l += strlen(buffer);
        valread = read( sock , buffer, 1024);

    }while(valread != 0);

    cerr << l;
    char* c = const_cast<char*>(data.c_str());
    std::vector<uchar> vec(c,c+l);

    Mat image2 = cv::imdecode(vec, 1);

    // cv::imwrite("test22.jpg",image2);

    return 0;
}

The output i get is:
87567Corrupt JPEG data: 175 extraneous bytes before marker 0xec
87567 should be the size of the data received and because there is data missing the jpeg cant be created
When im sending a message like "This is a test" the full text is received by the client.

A: In your client you are using buffer before you have read anything to it. You also are assuming that it is null terminated.
Something like this seems better
std::string data = "";
for (;;)
{
    valread = read( sock , buffer, 1024);
    if (valread <= 0)
        break;
    data.append(buffer,valread);
}

A: You have two major flaws, one which could lead to an infinite loop, and one which leads to the problem you experience:

*

*The infinite loop problem will happen if read fails in the client and it returns -1. -1 != 0, and then read will continue to read -1 forever.

*The second and main problem is that you treat the data you send between the programs a strings which it is not. A "string" is a null-terminated (i.e. zero-terminated) sequence of characters, your image is not that. In fact, it might even contain embedded zeros inside the data which will give you invalid data in the middle as well.
To solve both problem I suggest you change the reading loop (and the variables used) to something like this:
uchar buffer[1024];
ssize_t read_result;
std::vector<uchar> data;

// While there's no error (read returns -1) or the connection isn't
// closed (read returns 0), continue to append the received data
// into the vector
while ((read_result = read(sock, buffer, sizeof buffer)) > 0)
{
    // No errors, no closed connection
    // Append the new data (and only the new data) at the end of the vector
    data.insert(end(data), buffer, buffer + read_result);
}

After this loop, and if read_result == 0, then data should contain only the data that was sent. And all of it.


text:
Q: SAP Export that always change the columns orders and lead to query breaks So I have a Query that its source is an SAP exported excel file, problem is that people always export that report using their layouts so exported tables had different column orders and sometimes miss some columns from one person to another so I can't make a unified query source that everyone can work on.
the query act based on only 4 columns from that exported SAP excel and am sure everyone is exporting those columns, However, how can I avoid query breaks and how can I let these people just copy and paste the exported SAP table with wtv. headers order they want without causing any breaks to my query.

A: Set up a query based on a pasted range. From then on, people can just paste over it
Delete the default Changed Type step that powerquery like to make which looks like
= Table.TransformColumnTypes(Source,{{"Column1Name", Int64.Type}, {"Column1Name", Int64.Type}, {"c", Int64...

Remove all other columns but your desired four by click selecting them then right-clicking and using remove other columns. That generates:
= Table.SelectColumns(Source,{"Column1Name", "Column2Name", "Column3Name", "Column4Name"})

go from there
sample full code
let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Removed Other Columns" = Table.SelectColumns(Source,{"Column1Name", "Column2Name", "Column3Name", "Column4Name"})
in #"Removed Other Columns"


text:
Q: Order dictionary by key with numerical representation I have this input, where each value has a range of 200:
d = {'600-800': 3, '1800-2000': 3, '1000-1200': 5, '400-600': 1, '2600-2800': 1}

And I am looking for this expected order:
{'400-600': 1, '600-800': 3, '1000-1200': 5, '1800-2000': 3, '2600-2800': 1}

Already tried something like this, but the order is just wrong:
import collections
od = collections.OrderedDict(sorted(d.items()))
print od

A: You can split the key into parts at '-' and use the first part as integer value to sort it. The second part is irrelevant for ordering because of the nature of your key-values (when converted to integer):
d = {'600-800': 3, '1800-2000': 3, '1000-1200': 5, '400-600': 1, '2600-2800': 1}
import collections
od = collections.OrderedDict(sorted(d.items(),key =lambda x: int(x[0].split("-")[0])))
print od

Output:
OrderedDict([('400-600', 1), ('600-800', 3), ('1000-1200', 5),
             ('1800-2000', 3), ('2600-2800', 1)])

Doku:

*

*sorted(iterable,key)
Related:

*

*How to sort a list of objects based on an attribute of the objects?  for more "sort by key" examples

*Are dictionaries ordered in Python 3.6+? .. which lets you omit the OrderedDict from 3.7+ on (or 3.6 CPython)

A: If you want to order your dictionary by the first year first (and then by the second year if needed, which is unnecessary in the given example, but feels more natural), you need to convert to integers and set a custom key:
d = {'600-800': 3, '1800-2000': 3, '1000-1200': 5, '400-600': 1, '2600-2800': 1}

sorted(d.items(), key=lambda t: tuple(map(int, t[0].split("-"))))
# [('400-600', 1),
#  ('600-800', 3),
#  ('1000-1200', 5),
#  ('1800-2000', 3),
#  ('2600-2800', 1)]

The conversion to integers is needed because e.g. "1000" < "200", but 1000 > 200. This list can be passed to OrderedDict afterwards like in your code, if needed.


text:
Q: Possible bug/issue in ASP.NET 3.5 related to Request.RawUrl property I posted a query for 301-redirect using ASP.NET 3.5 here:
Redirecting default.aspx to root virtual directory
Based on the replies I got there, I realized there might be a bug in ASP.NET's Request.RawUrl method which is unable to return the actual raw url (without /default.aspx) when being used in a sub-directory, i.e. the /default.aspx page is inside a subdirectory.
Can someone please shed some light on this possible bug?
Thanks,
Asif

A: i found a good explanation here
http://codeasp.net/blogs/vivek_iit/microsoft-net/873/301-redirect-from-default-aspx-to-site-root
Thanks

A: If you suspect this is a bug, then the place to go is Microsoft Connect, where you can report and discuss the bug directly with Microsoft.
Edit: I was able to reproduce the look per your comments.
I was unable to reproduce the infinite loop, however. I injected code into the Global.asax Application_BeginRequest handler of a web application and got the expected behavior of a single redirect.
There are other, and IMO much better, options for handling global redirect rules. On IIS7, I use the URL Rewrite module to configure rewrite rules in IIS. You can read more about it and download it here: http://www.iis.net/download/urlrewrite. The appeal of a solution such as this is that you can customize and update your rewrite rules without recompiling the application.
Edit: I was able to retrieve the raw URL without the default.aspx (after the redirect) by using instead:
Request.ServerVariables["CACHE_URL"]

It's worth a shot.

A: Have you looked at the IIS settings for your virtual directory? If there is a default document set to default.aspx then this will explain the infinite loop that you are experiencing. You are telling the website to redirect to the virtual directory without the "default.aspx" and IIS is detecting this on the next request and putting it back in ad infinitum.
Right click your virtual directory, select Properties and then the Documents tab. If default.aspx is in the list then that is what you will get. The Url of the request will be passed to the ASP.NET worker process as /folder/default.aspx rather than /folder/
This is not a bug. If IIS didn't do this, you would get a page not found error.
Sounds to me like you need to investigate URL rewriting: http://msdn.microsoft.com/en-us/library/ms972974.aspx


text:
Q: Why am I getting multiple instances of IEntityChangeTracker? I get the following error:

An exception of type 'System.InvalidOperationException' occurred in
  EntityFramework.dll but was not handled in user code
Additional information: An entity object cannot be referenced by
  multiple instances of IEntityChangeTracker.

When this runs:
public bool AddUser(string username, string clanName) {

            if (userRankValid(clanName))
            {
                var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
                ApplicationUser recruit = userManager.FindByNameAsync(username).Result;
                Clan clan = uow.ClansRepository.Get(u => u.Name == clanName).FirstOrDefault();

                if (clan != null && recruit != null)
                {
                    var ctum = uow.ClanToUserRepository.Get(u => u.User.UserName == username).Where(u=>u.Clan.Name == clanName).FirstOrDefault();
                    if(ctum == null)
                    {
                        ClanToUserMap recMap = new ClanToUserMap();
                        recMap.Clan = clan;
                        recMap.User = recruit;
                        recMap.Rank = "Private";
                        recMap.User = recruit;
                       //clan.Members.Add(recMap);
                      //  recruit.Clans.Add(recMap);
                        uow.ClanToUserRepository.Insert(recMap);
                        uow.Save();
                        return true;
                    }
                }
            }
            return false;
        }

Now then, I realise this must be because there are multiple instances of a context. What I don't understand is why there are... All the calls are get and then a final insert. But I am implementing .AsNoTracking() in my generic repository for any GET call, so I don't understand why the contexts are getting confused:
public virtual IEnumerable<TEntity> Get(
            Expression<Func<TEntity, bool>> filter = null,
            Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
            string includeProperties = "")
        {
            IQueryable<TEntity> query = dbSet;

            if (filter != null)
            {
                query = query.Where(filter).AsNoTracking();
            }

            foreach (var includeProperty in includeProperties.Split
                (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
            {
                query = query.Include(includeProperty).AsNoTracking();
            }

            if (orderBy != null)
            {
                return orderBy(query).AsNoTracking().ToList();
            }
            else
            {
                return query.AsNoTracking().ToList();
            }
        }

The error occurs on the INSERT


text:
Q: Add content to a very large Excel file using Apache POI (run out of alternatives...) I have a large xlsx file which has an empty "data source sheet" and other sheets containing lots of formulas that use the data source sheet. My application should generate the data, open the file, fill the empty sheet up with that data and save it. I'm trying to do all that with Apache POI.
The problem is that opening the file takes an unacceptable amount of memory and time. I've read other threads and couldn't find a solution.
This is how I open the file:
pkg = OPCPackage.open(filename);
wb = new XSSFWorkbook(pkg);

Please note that using SXSSFWorkbook does not work as its constructors take a XSSFWorkbook which I'm unable to create in the first place.
What I need is just to fill one empty sheet in the file, I don't need to completely load it in memory. Any Ideas??
Thank you!!

A: You could try working only with the OPCPackage without creating a Workbook. But then we must work at the lower level org.openxmlformats.schemas.spreadsheetml.x2006.main objects. This means we have not the support from the XSSF objects while storing string values as data (SharedStringsTable) and evaluating formulas.
The example takes a Excel workbook with at  least 4 worksheets. The third worksheet is your "data source sheet". It must exist and will be overwritten with new data. The fourth worksheet is the worksheet in which formulas are referencing the  "data source sheet". Since we can't use an evaluator, we must set FullCalcOnLoad true. If we would not do that, we had to press [Ctrl]+[Alt]+[Shift]+[F9] to force fully recalculation.
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;

import org.apache.poi.xssf.model.SharedStringsTable;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;

import org.openxmlformats.schemas.spreadsheetml.x2006.main.WorksheetDocument;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheetData;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRst;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCell;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCellType;

import  org.openxmlformats.schemas.officeDocument.x2006.relationships.STRelationshipId;

import org.apache.xmlbeans.XmlOptions;
import org.apache.xmlbeans.XmlException;

import javax.xml.namespace.QName;

import java.util.List;
import java.util.Map;
import java.util.HashMap;

import java.util.regex.Pattern;

class ReadAndWriteTest5 {

 public static void main(String[] args) {
  try {

   File file = new File("ReGesamt11_3Test.xlsx");
   //we only open the OPCPackage, we don't create a Workbook
   OPCPackage opcpackage = OPCPackage.open(file);

   //if there are strings in the SheetData, we need the SharedStringsTable
   PackagePart sharedstringstablepart = opcpackage.getPartsByName(Pattern.compile("/xl/sharedStrings.xml")).get(0);
   SharedStringsTable sharedstringstable = new SharedStringsTable();
   sharedstringstable.readFrom(sharedstringstablepart.getInputStream());

   //create empty WorksheetDocument for the "data source sheet"
   WorksheetDocument worksheetdocument = WorksheetDocument.Factory.newInstance();
   CTWorksheet worksheet = worksheetdocument.addNewWorksheet();
   CTSheetData sheetdata = worksheet.addNewSheetData();

   //put some data in for the "data source sheet"
   for (int i = 0; i < 10; i++) {

    CTCell ctcell= sheetdata.addNewRow().addNewC();

    CTRst ctstr = CTRst.Factory.newInstance();
    ctstr.setT("DataRow " + i);
    int sRef = sharedstringstable.addEntry(ctstr);
    ctcell.setT(STCellType.S);
    ctcell.setV(Integer.toString(sRef));

    ctcell=sheetdata.getRowArray(i).addNewC();
    ctcell.setV(""+(i*100+(i+1)*10+(i+2))+"."+((i+3)*10+(i+4)));

   }

   //write the SharedStringsTable
   OutputStream out = sharedstringstablepart.getOutputStream();
   sharedstringstable.writeTo(out);
   out.close();

   //create XmlOptions for saving the worksheet
   XmlOptions xmlOptions = new XmlOptions();
   xmlOptions.setSaveOuter();
   xmlOptions.setUseDefaultNamespace();
   xmlOptions.setSaveAggressiveNamespaces();
   xmlOptions.setCharacterEncoding("UTF-8");
   xmlOptions.setSaveSyntheticDocumentElement(new QName(CTWorksheet.type.getName().getNamespaceURI(), "worksheet"));
   Map<String, String> map = new HashMap<String, String>();
   map.put(STRelationshipId.type.getName().getNamespaceURI(), "r");
   xmlOptions.setSaveSuggestedPrefixes(map);

   //get the PackagePart of the third sheet which is the "data source sheet"
   //this sheet must exist and will be replaced with the new content
   PackagePart sheetpart = opcpackage.getPartsByName(Pattern.compile("/xl/worksheets/sheet3.xml")).get(0);
   //save the worksheet as the third sheet which is the "data source sheet"
   out = sheetpart.getOutputStream();
   worksheet.save(out, xmlOptions);
   out.close();

   //get the PackagePart of the fourth sheet which is the sheet on which formulas are referencing the "data source sheet"
   //since we can't use Evaluator, we must force recalculation on load for this sheet
   sheetpart = opcpackage.getPartsByName(Pattern.compile("/xl/worksheets/sheet4.xml")).get(0);
   worksheetdocument = WorksheetDocument.Factory.parse(sheetpart.getInputStream());
   worksheet = worksheetdocument.getWorksheet();
   //setFullCalcOnLoad true
   if (worksheet.getSheetCalcPr() == null) {
    worksheet.addNewSheetCalcPr().setFullCalcOnLoad(true);
   } else {
    worksheet.getSheetCalcPr().setFullCalcOnLoad(true);
   }
   out = sheetpart.getOutputStream();
   worksheet.save(out, xmlOptions);
   out.close();

   opcpackage.close();

  } catch (InvalidFormatException ifex) {
     ifex.printStackTrace();
  } catch (FileNotFoundException fnfex) {
     fnfex.printStackTrace();
  } catch (IOException ioex) {
     ioex.printStackTrace();
  } catch (XmlException xmlex) {
     xmlex.printStackTrace();
  }
 }
}


text:
Q: Add Array values to NSMutableDictionary I ran into a problem and I can't find the method to get over it. basically I need to make a mutable dictionary with some values. All values are dynamic and I get them from web service or from other variables.
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    [dict setObject:comment.text forKey:@"Comment"];
    [dict setObject:name.text forKey:@"Name"];
    [dict setObject:[NSString stringWithFormat:@"%d",isPublic] forKey:@"VisibleForAll"];
po dict
{
    Comment = "no comment";
    Name = "test";
    VisibleForAll = 1;
    -> carts
}

Furthermore I want to add the following tree to my dictionary but I can't figure how to do this.
I have the necessary items in 2 NSArray artID and qty but I don't know how to create the bottom part so I can add it to the dict.
Carts {
       Cart {
             ArticleID : 22
             Quantity : 1
            }
       Cart {
             ArticleID : 45
             Quantity : 3
            }
       ...
      }

I will add it with [dict setObject:carts forKey:@"Cart"] but I don't know how to add values in such a manner that I will make my dictionary on the form I presented you.
Also, don't forget that the numbers or Carts is flexible. I will get it from a Product.count.
Thanks in advance.

A: If your both array artID and qty have value at the same index for create a dictionary you can try like this
NSMutableArray *carts = [[NSMutableArray alloc] init];
for(NSInteger i=0; i<products.count; i++) {
    //If you have custom class `cart` than use that
    Cart *cart = [[Cart alloc] init];
    cart.ArticleID = [[products objectAtIndex:i] valueForKey:@"pid"];
    cart.Quantity = [[products objectAtIndex:i] valueForKey:@"qty"];

    //If you not have any custom class than use Dictionary
    NSMutableDictionary *cart = [[NSMutableDictionary alloc] init];
    [cart setObject:[[products objectAtIndex:i] valueForKey:@"pid"] forKey:@"ArticleID"];
    [cart setObject:[[products objectAtIndex:i] valueForKey:@"pid"] forKey:@"Quantity"];
}

Now add this carts array to Dictionary with key
[dict setObject:carts forKey:@"carts"];

A:  NSArray *pid = [products valueForKey:@"pid" ];
    NSArray *qty = [products valueForKey:@"qty"];

    NSMutableArray *carts = [[NSMutableArray alloc] initWithCapacity:products.count];

    for(NSInteger i=0; i<products.count; i++) {
        NSMutableDictionary *cart = [[NSMutableDictionary alloc] init];
        NSMutableDictionary *cartemp = [[NSMutableDictionary alloc] init];

        [cart setObject:[pid objectAtIndex:i] forKey:@"ArticleId"];
        [cart setObject:[qty objectAtIndex:i] forKey:@"Quantity"];
        [cartemp setObject:cart forKey:@"Cart"];
        [carts addObject:cartemp];
    }

    [dict setObject:carts forKey: @"Carts"];


text:
Q: Importing multiple sheets from an excel file into multiple tables by sheet name Hi there and thanks for your help. I'm putting together a seemingly simple Access data management solution for use in our office here and I'm having trouble as my background in vba is minimal at best.
What I have here are two related but disconnected Access 2007 applications and I need a system for the user to easily import and export this information. I've got a script working now to export all the tables from the application into a single excel file with each table as a different worksheet, the issue is that when I go to import it only seems to find the first sheet for import.
What I'm hoping to find is a method to iterate over each worksheet, grab the sheet name, and then merge that data into the table based on the sheet name.
To clarify:

*

*Multiple copies of App A are sent to various departments

*App A: Users enter information into the tables

*App A: Users press command to run export macro

*Excel file is created with each table as a sheet with matching names (e.g. tblCourse, tblStudent, tblFaculty, etc.)

*Users of App B receive excel spreadsheet

*App B: Users press command to run import script (This is the solution I'm looking for)

*

*User is prompted for file location

*Import script opens excel workbook

*Script iterates over each sheet, reads name, and imports data to table of matching name

Thanks in advance for any help you can  provide, much appreciated.
Edit
Working script (Thanks greatly to grahamj42's help here):
Private Sub Command101_Click()

'Dim excelapp As New Excel.Application
Dim excelApp As Object
Set excelApp = CreateObject("Excel.Application")
'Dim excelbook As New Excel.Workbook
Dim excelbook As Object
Set excelbook = excelApp.Workbooks.Add
'Dim excelsheet As New Excel.Worksheet
'Dim excelsheet As Object
'Set excelsheet = excelbook.Sheets
Dim intNoOfSheets As Integer, intCounter As Integer
Dim strFilePath As String, strLastDataColumn As String
Dim strLastDataRow As String, strLastDataCell As String

strFilePath = "C:\Users\UserName\Documents\Export\DatabaseExport03-28-2013.xlsx"

Set excelbook = excelApp.Workbooks.Open(strFilePath)

 intNoOfSheets = excelbook.worksheets.Count

 Dim CurrSheetName As String

 For intCounter = 1 To intNoOfSheets
  excelbook.worksheets(intCounter).Activate
   DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, ActiveSheet.Name, _
   strFilePath, True, _
   excelbook.Worksheets(intCounter).Name & "!" & _
   Replace(excelbook.Worksheets(intCounter).UsedRange.Address, "$", "")
 Next

excelbook.Close
excelApp.Quit
Set excelApp = Nothing

End Sub

Note that in the DoCmd.TransferSpreadsheet command there is a HasFieldNames property that is set to 'True' here because my spreadsheets export with the field names as column headers.

A: Your use of Selection without selecting anything will refer to the selected cell in the worksheet when it was saved. While I don't see, in your case, why this should be outside the table, you could do better like this without selecting anything by using Worksheet.UsedRange:
For intCounter = 1 To intNoOfSheets

  DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, Activesheet.Name, _
    strFilePath, True, _
    excelbook.Worksheets(intCounter).Name & "!" & _
    Replace(excelbook.Worksheets(intcounter).UsedRange.Address, "$", "")

Next

A: I did a little combining of two different pieces of code, as I didn't want to hard code the location or file name.
Dim excelApp As Object
Dim excelbook As Object
Dim dlg As FileDialog
Dim StrFileName As String, intcounter, intNoOfSheets As Integer

Set excelApp = CreateObject("Excel.Application")
Set dlg = Application.FileDialog(msoFileDialogFilePicker)

With dlg
    .Title = "Select the Excel file to import"
    .AllowMultiSelect = False
    .Filters.Clear
    .Filters.Add "Excel Files", "*.xlsx", 1
    .Filters.Add "All Files", "*.*", 2

    If .Show = -1 Then

        StrFileName = .SelectedItems(1)
        Set excelbook = excelApp.Workbooks.Open(StrFileName)
        intNoOfSheets = excelbook.worksheets.Count
        'DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel8, "COR Daily",     StrFileName, True
        For intcounter = 1 To intNoOfSheets
            excelbook.worksheets(intcounter).Activate
            DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel8,     excelbook.Activesheet.Name, StrFileName, True, _
            excelbook.worksheets(intcounter).Name & "!" & _
            Replace(excelbook.worksheets(intcounter).UsedRange.Address, "$", "")

        Next

    Else
        Exit Function

    End If

End With
End Function


text:
Q: AdView and ViewPager I have Android application with ViewPager implemented like this :
http://www.youtube.com/watch?v=C6_1KznO95A
I don't know how to implement AdView below the ViewPager. I have tried to put AdView below the ViewPager programmatically and in xml. There is no errors but ads are not showing.
My xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical">

<android.support.v4.view.ViewPager
 android:id="@+id/pager"
 android:layout_width="match_parent"
 android:layout_alignParentBottom="top"
 android:layout_height="0dp"
 android:layout_weight="1"/>

<com.google.ads.AdView
 android:id="@+id/ad"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_alignParentLeft="true"
 android:layout_alignParentRight="true"
 android:layout_alignParentBottom="true"
 android:layout_below="@+id/pager"
 ads:adSize="BANNER"
 ads:adUnitId="@string/admob_publisher_id"
 ads:loadAdOnCreate="true" >
</com.google.ads.AdView>
</RelativeLayout>

A: First, there is no android:layout_weight for a RelativeLayout.
Second, there is no android:orientation for a RelativeLayout.
If you want to use those, use a LinearLayout, not a RelativeLayout. If you do that, get rid of the three android:layout_alignParent* attributes from the AdView, along with android:layout_below, as those are for RelativeLayout, not LinearLayout.
The result should work, assuming that AdView works with android:layout_height="wrap_content".
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical">

  <android.support.v4.view.ViewPager
   android:id="@+id/pager"
   android:layout_width="match_parent"
   android:layout_height="0dp"
   android:layout_weight="1"/>

  <com.google.ads.AdView
   android:id="@+id/ad"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   ads:adSize="BANNER"
   ads:adUnitId="@string/admob_publisher_id"
   ads:loadAdOnCreate="true" >
  </com.google.ads.AdView>
</LinearLayout>


text:
Q: repopulating form: PHP or Javascript I have a form that submits to a third-party service that runs some validation. On error, it redirects to the same page as the form but appends a query string containing the original form values along with an error message.
Because of this query string, the browser sees it as a "new page" and the form is blank.
I've tried one method using PHP (see Code Review question) that boils down to: "grab the GET value for each field, on an individual basis, and then set these as the value on the form." It sort of works, but:

*

*the radio buttons are tricky to deal with

*I don't have full PHP functionality. I'm in WordPress with a PHP-in-pages plugin that can run certain PHP but is choking on defining a function and then re-using it

What is the recommended method (PHP or JavaScript... and I do have jQuery on the site also) for re-populating this form?

A: Javascript because PHP forces an extra load on the server. But validating userinput should be done both clientside (JS) as well as (serverside) PHP

A: Unless you are dynamically assembling your fields, it won't be easy to dynamically repopulate them using PHP. If you are, you can do something like this:
PHP
$fields = [
    'username' => ['type' => 'text', 'value' => $_GET['username']],
    'setting1' => ['type' => 'radio', 'value' => $_GET['radio']]
];
foreach( $fields as $name => $input ) {
    echo "<input type='{$input['type']}' name='{$name}' value='{$input['value']}'>";
}

If not, you can use a combination of PHP and JavaScript like this. I'm using jQuery to simplify things.
PHP and JavaScript
$fields = $_GET;
echo '<script type="text/javascript">
var errors = { ';
foreach( $fields as $name => $value ) {
    echo $name . " : '{$value}',\n";
}
echo '};

$.each(errors, function(name, value) {
    $("input[name="+name+"]").val(value);
});
</script>';

This is untested and I know there is at least one bug (extra comma in the errors array) but should be a good starting point. The goal of the second method is to assemble an array using PHP which the JavaScript can then use and execute a loop to assign those values to each input field. But again - the logic for select boxes and radio buttons and so on will be complex. Instead of just assigning val you would have to set checked properties, etc.
Unfortunately I don't know if there are any libraries or jQuery plugins which already do this.

A: This is jquery code to check the radiobutton:
     $("form :radio:checked").before("CHECKED"); //selects only checked buttons

This is code to prevent the form from submission and repopulate your fields:
function prepareEventhandlers() {
document.getElementById("formname").onsubmit = function() {
if (document.getElementById("email").value == "") { // e.g. if no email was given
    document.getElementById("errormessage").innerHTML = "it didnt work!";
    return false;
} else {
    document.getElementById("errormessage").innerHTML = "";
    return true;
}
};
}

window.onload = function () {
prepareEventhandlers();
}

good luck!


text:
Q: Spring security: My Authorization filter authorizes my request even tho the URL is permited In my security configuration class i have permitted the request to the welcome url and any other url which follows the "welcome/**" format.
this is my securityconfiguration class:
@EnableGlobalMethodSecurity(prePostEnabled = true)
//@Configuration
@EnableWebSecurity
public class JwtSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    private final CustomerDetailsService customerDetailsService;

    @Autowired
    private JwtAuthenticationEntryPoint unauthorizedHandler;

    @Autowired
    public JwtSecurityConfiguration(CustomerDetailsService customerDetailsService) {

        this.customerDetailsService = customerDetailsService;
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .userDetailsService(customerDetailsService)
                .passwordEncoder(passwordEncoderBean());
    }

    @Bean
    public PasswordEncoder passwordEncoderBean() {
        return new BCryptPasswordEncoder();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {

        web.ignoring().antMatchers("**/resources/static/**")
                .and()
                .ignoring()
                .antMatchers(
                        HttpMethod.GET,
                        "/",
                        "/*.html",
                        "/favicon.ico",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js",
                        "/index_assets/**"
                );
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/welcome/login").permitAll()
                .antMatchers("/welcome").permitAll()
                .antMatchers("/welcome/signup").permitAll()
                .antMatchers("admin/rest/**").authenticated()
                .and()
                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler)
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        //http.addFilterBefore(new JWTAuthenticationFilter(authenticationManager()), UsernamePasswordAuthenticationFilter.class);

         http.addFilterBefore(new JWTAuthorizationFilter(authenticationManager(),customerDetailsService),UsernamePasswordAuthenticationFilter.class);

        // disable page caching
        http
                .headers()
                .frameOptions().sameOrigin()  // required to set for H2 else H2 Console will be blank.
                .cacheControl();

        //http.headers().cacheControl();

    }
}

but I noticed that in my JWTAuthorizationFilter.class the doFilterInternal() method picks up this URL
public class JWTAuthorizationFilter  extends OncePerRequestFilter {

    private final CustomerDetailsService customerDetailsService;

    @Autowired
    DefaultCookieService defaultCookieService;

    public JWTAuthorizationFilter(AuthenticationManager authenticationManager, CustomerDetailsService customerDetailsService) {

       // super(authenticationManager);

        this.customerDetailsService = customerDetailsService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {

        String header = request.getHeader(HEADER);

        if(Objects.isNull(header) || !header.startsWith(TOKEN_PREFIX)){

            return;

        }

        UsernamePasswordAuthenticationToken usernamePasswordAuth = getAuthenticationToken(request);

        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuth);

        chain.doFilter(request,response);

    }

    private UsernamePasswordAuthenticationToken getAuthenticationToken(HttpServletRequest request){

        String token = request.getHeader(HEADER);

        if(Objects.isNull(token)) return null;

        String username = Jwts.parser().setSigningKey(SECRET)
                .parseClaimsJws(token.replace(TOKEN_PREFIX,""))
                .getBody()
                .getSubject();

        UserDetails userDetails = customerDetailsService.loadUserByUsername(username);

        return username != null ? new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()) : null;
    }
}

What is the cause of this ?

A: Filter is suppose to pick up each and every request. It doesn't matter if that you have permitted or not in security configuration.
You have got two options:

*

*If you don't want welcome/** to go through the filter you add it to web ignore
@Override
public void configure(WebSecurity web) throws Exception {

    web.ignoring().antMatchers("**/resources/static/**")
            .and()
            .ignoring()
            .antMatchers(
                    HttpMethod.GET,
                    "/",
                    "/*.html",
                    "/favicon.ico",
                    "/**/*.html",
                    "/**/*.css",
                    "/**/*.js",
                    "/index_assets/**",
                    "/welcome/**"
            );
}

But note, it will skip all filters and you may not want that.

*In doFilterInternal method skip it when you find welcome/** pattern.


text:
Q: APP_INITIALIZER is not working in angular 5 I need to load configuration from service at the Angular initial level.
So, For demo I have created boot module, boot class and load APP_INITIALIZER from the Angular core into the boot module.
Check the following file, I not able see the console.log("Init Function works") as well as console.log("GET CONFIG WORKS")
Please correct me if anything wrong.
// Module file
boot.modue.ts
import { APP_INITIALIZER, NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Boot, Config, Menu } from './../../core/classes';
import { MenusService } from './../services/';

export function init(_boot: Boot) {
  console.log("Init Function works");
  return () => {
    return _boot.getConfig();
  };
}

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [],
  providers: [Boot,
    { provide: APP_INITIALIZER,
      useFactory: init,
      deps: [Boot], multi: true
    }]
})

export class BootModule {
  constructor() { }
}

// Class file
boot.ts
import 'rxjs/add/operator/toPromise';

export class Boot {
    /**
     * getConfig
     */
    public getConfig(): Promise<any> {
        console.log("getConfig");
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                console.log("GET CONFIG WORKS");
                resolve();
            }, 3000);
        });
    }

    /**
     * initMenus
     */
    public initMenus() {

    }
}


text:
Q: Fixed block element hides on window resize I noticed a behavior that drives me crazy.
I have two divs, that have both similar css:
.one, .two {
   position: fixed;
   bottom: 6%
}

One div is for navigation, and other is for content, that has max 300px height. The problem is, that if the user resizes the browser window to really small one, the scrollbar is not shown.
I tried to change position to absolute, but then the ajaxify plugin breaks the position if new page is loaded. I couldn't find other ideas, how to position those divs at fixed position at bottom.
p.s. I pasted a sample test on http://pastebin.com/Bp1490dj

A: the background-green div is at the bottom with position:absolute;
from what I know a position:fixed; and or position:absolute; will never make a scroll. (please correct me if I'm wrong) so a way to go arround this is to set a min-height to body
body {
    min-height:200px;
}

have a look at the fiddle  http://jsfiddle.net/u2ZWa/
also, there is a fix with a scroll now. But you have to know the fixed elements will never be scrollable because they're fixed

A: Scrollbars are not compatible with a fixed positioning.


text:
Q: Relocate the SBT target/ directory (compiled classes) to ramdisk/temporary directory In a given SBT project's target/ directory, can occur quite a fair amount of disk I/O.
Given the use of an SSD (Solid State Drive), or maybe even to just improve compilation performance when I/O is slow, it may become desirable to relocate the target directory to a ramdisk such as /tmp.
Ideally, this would be a user-global setting specified in ~/.sbt/0.13/global.sbt so that the project-specific settings are not bound to the specific developer's set-up.
How can I relocate the target/ directory to another location in the filesystem, ideally including automatic sub-directories for projects to prevent conflicts?
I found the following:
target <<= (name) { file("/tmp/sbt/") / _ }

on a forum, but this seems to use the outdated <<= operator, and I can't figure out how I can rewrite this using modern syntax.

A: How you can make a setting depend on another setting is described in the official documentation. In your case it could look like this:
target := file("/tmp/sbt") / name.value


text:
Q: RGB and CMYK are turning into hyperlinks in view In my view layer I have a span class with some text inside with some RBG and CMYK values. These values are just strings to be displayed on the page. For some reason when the view is rendered this text is displayed as a hyperlink.
CMYK 94/29/9/0
RGB 33 167 230

what view looks like


text:
Q: How should I handle docstrings of subclass methods? I have an abstract class structured somewhat like this:
class AbstractQuery(object, zip_code):
    def execute(self):
        """
        Retrieve information about a zip code
        The information returned will depend on the subclass
        """
        url, params = self._build_query(zip_code)
        response = requests.get(url, params=params)
        if self._is_valid(response):
            # etc.

    def _build_query(self, zip_code):
        """
        Returns a tuple (url, params) where
        url is the url of the API to query and
        params are the query params for the API call
        """
        raise NotImplementedError

    def _is_valid(self, response):
        """
        Returns True if response contains information necessary
        to continue processing
        """
        raise NotImplementedError

_build_query for example is always going to do the same thing, there's just going to be minor implementation differences. Do I just keep the docstring in the base class? Or copy/paste it down and violate DRY? What would a user or maintainer of these classes want to see?

A: From PEP 257:

The docstring for a class should summarize its behavior and list the public methods and instance variables. If the class is intended to be subclassed, and has an additional interface for subclasses, this interface should be listed separately (in the docstring). The class constructor should be documented in the docstring for its __init__ method. Individual methods should be documented by their own docstring.
If a class subclasses another class and its behavior is mostly inherited from that class, its docstring should mention this and summarize the differences. Use the verb "override" to indicate that a subclass method replaces a superclass method and does not call the superclass method; use the verb "extend" to indicate that a subclass method calls the superclass method (in addition to its own behavior).

So if you want to follow Python standards, use language indicating that the method is overriden in your subclass docstring.

A:
Do I just keep the docstring in the base class?

If your derived class has nothing to add to the description, this seems like the right choice - Python 3.5 and onwards will walk the inheritance to find a docstring:
import inspect

class Base:
    def method(self):
        """Do something"""

class Derived(Base):
    def method(self):
        pass

print(inspect.getdoc(Derived.method)) # prints "Do something"

Note that this does not work if Derived is defined in an interactive console, but that shouldn't matter.


text:
Q: Cannot get node.js to connect to pubnub from corporate network I cannot get the pubnub node.js starter program here (https://github.com/pubnub/javascript/tree/master/node.js) to work.
I keep getting

FAILED! RETRY PUBLISH! { message: 'timeout' }

so it looks like some kind of network issue.  I am behind corporate proxy and have set the http proxy env variables
I tried the (javascript browser sdk) and it works.

A: PubNub Node and Proxies
You need to pass in the Proxy info in the configuration, will look similar to the code below.
pubNubClient = require('pubnub')({
  ssl          : true,
  publish_key  : "YOUR_PUBLISH_KEY",
  subscribe_key: "YOUR_SUBSCRIBE_KEY",
  proxy: {
     hostname: "http://google.com",
     port: "1234"
  }
});


text:
Q: rake db:migrate does not change table I have a db with columns (name, path). Now I have a migration file that changes the columns to be (name, pathorig, pathjson, scramble).
Doing rake db:reset and rake db:migrate doesn't update the table. Why can this happen?
my migration file:
class CreateUploads < ActiveRecord::Migration
  def change
    create_table :uploads do |t|
      t.string :name
      t.string :pathorig
      t.string :pathjson
      t.string :scramble

      t.timestamps
    end
  end
end

The schema.rb file:
ActiveRecord::Schema.define(version: 20131029072745) do

  create_table "uploads", force: true do |t|
    t.string   "name"
    t.string   "path"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

end

A: Difference between rake db:migrate db:reset and db:schema:load has a great explanation of what the various rake db:* commands do.
Because rake db:reset performs a db:schema:load, it's loading the old columns from your table, rather than calling db:migrate, this is why your migration isn't being run.
Consider writing a migration that changes the names of those columns, rather than re-creates an existing table, or manually run rake db:drop; rake db:create db:migrate


text:
Q: Permission denied while trying to install opencv4nodejs in Ubuntu I was trying to install opencv4nodejs in Ubuntu-20.04 using the following command and my node version is v12.19.0
sudo npm i -g opencv4nodejs

But getting those errors
info install installing opencv version 3.4.6 into directory: /usr/lib/node_modules/opencv4nodejs/node_modules/opencv-build/opencv
ERR! Error: Command failed: mkdir -p opencv
mkdir: cannot create directory 'opencv': Permission denied

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! opencv-build@0.1.9 install: `node ./install.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the opencv-build@0.1.9 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2020-10-28T06_33_21_090Z-debug.log

A: *

*Running NPM install with sudo might be causing a permissions problem. You could try completely removing the node_modules directory and re-running NPM install it without sudo.

*Also make sure you have permission to write to the directory you're installing in?

*If it still doesn't work please follow this:
sudo npm install -g opencv4nodejs --unsafe-perm=true --allow-root

A: This is complete guide to install opencv4nodejs to Linux OS or Raspberry pi (Raspberry Pi OS )
configuration
   01- sudo raspi-config  expand file system  // this is for raspberry pi
   After Reboot (sudo reboot now)
   02- df -h (To check expand file system)
   03- sudo apt-get update && sudo apt-get upgrade -y
   04- sudo passwd root  // set up your root password
   Reboot

To Install NodeJS
   01- sudo apt-get install git -y
   02- curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash -  // replase 12 with latest nodejs (LTS) version
   03- sudo apt-get install nodejs -y
   04- sudo apt-get install gcc g++ make

To Install opencv4nodejs
01. sudo apt-get install cmake -y
02. sudo npm install -g node-gyp

I am using this steps for raspberry pi os
03. sudo nano /etc/dphys-swapfile
    (Increase the CONF_SWAPSIZE from 100 to 1024)
        sudo /etc/init.d/dphys-swapfile stop
        sudo /etc/init.d/dphys-swapfile start

cd to home dir..
04. mkdir opencv
05. cd opencv
06. sudo npm init -y

07. su
    // Enter your setup root password

08. sudo npm install --save opencv4nodejs

09. sudo nano /etc/dphys-swapfile
    (Set the CONF_SWAPSIZE back to 100)

In index.js and node_modules in same folder
const cv = require("opencv4nodejs");

In index.js and  node_modules in not in same folder
const cv = require("path/opencv/node_modules/opencv4nodejs");

! you don't need to install opencv4nodejs for each folders
You can simply call that above way
Hope guys you can understand it...
Any questions feel free to ask...
Thank you


text:
Q: D3 Add Tooltip to Stacked Area Chart I would like to add tooltip on mouseover event for the below stacked area chart:
https://observablehq.com/@d3/stacked-area-chart?collection=@d3/d3-shape
The tooltip should contain current mouse position's graph type (e.g. Wholesale and Retail Trade), x position (e.g. year 2001) and y position (e.g. 500).
I tried getting data for mouseover event however it includes all data range of y-axis of current graph type (e.g. Wholesale and Retail Trade). I tried searching online for various examples but could not find a matching example. Has anyone created similar tooltip on stacked area chart?
I have created the below sample chart to demonstrate the issue:
https://jsfiddle.net/3gqf8x5d/
Mouseover event code:
d3.selectAll("path")
  .on('mouseover', function(d) {
    console.log(d);
  })


text:
Q: Multiple Meta_values As you an see I use a get_pages() function and it all works fine.
$city_ids = get_pages(array("hierarchical" => 0, "sort_column" => "menu_order", "sort_order" => "desc", "meta_key" => "page_type", "meta_value" => 1));

But now I want multiple meta_values.
I tried things like:
"meta_value" => 1,3
"meta_value" => 1 AND 3

But they both don't work.
Is there any way to do this?
Thanks in advance.

A: $args = array(
    "numberposts" => -1,
    'post_type' => 'page',
    'meta_query' => array(
    'relation' => 'OR',
        array(
            'key' => 'page_type',
            'value' => 1,
            'compare' => '='
        ),
        array(
            'key' => 'page_type',
            'value' => 3,
            'compare' => '='
        )
    )
);

$city_ids = get_posts($args);


text:
Q: POST Rest API call to servicenow using C# I am trying to send information to the event queue in servicenow as below. But I get at message as

Id = 3, Status = WaitingForActivation, Method = "{null}", Result = "{Not yet computed}".

Any suggestions?
public void PostEvent()
{
    string jsonFilePath = @"{""records"": [{""source"": ""Test"",""event_class"": ""Test Class"",""node"": ""test"",""message_key"": ""Test Incident for Test 1"",""severity"": ""5"",""description"": ""Test Incident for Test 1 Desc"",""additional_info"":'{""name"": ""Test System"",""short_des"": ""Test Incident for Test 1 Short Desc"",""ASSIGNMENT_GROUP"": ""xyz""}'}]}";

    var client = new HttpClient();
    client.BaseAddress = new Uri("https://abcdev.service-now.com/api/global/em/jsonv2");
    client.DefaultRequestHeaders.Clear();
    var jsonBody = (new JavaScriptSerializer()).Serialize(jsonFilePath);
    client.PostAsync("test", new StringContent(jsonBody, Encoding.UTF8, "application/json"));
}

A: You are using the async version of Post without awaiting it. Make your method async Task and await/ or put .Result (that way you can await an async call in synchronous code) after your last line. But prefer await over Result (the error handling is different)

A: You are using async version of POST, So you have to create function as async and you have to await for Post function.
public async Task PostEvent()
{
    string jsonFilePath = @"{""records"": [{""source"": ""Test"",""event_class"": ""Test Class"",""node"": ""test"",""message_key"": ""Test Incident for Test 1"",""severity"": ""5"",""description"": ""Test Incident for Test 1 Desc"",""additional_info"":'{""name"": ""Test System"",""short_des"": ""Test Incident for Test 1 Short Desc"",""ASSIGNMENT_GROUP"": ""xyz""}'}]}";

    var client = new HttpClient();
    client.BaseAddress = new Uri("https://abcdev.service-now.com/api/global/em/jsonv2");
    client.DefaultRequestHeaders.Clear();
    var jsonBody = (new JavaScriptSerializer()).Serialize(jsonFilePath);
    await client.PostAsync("test", new StringContent(jsonBody, Encoding.UTF8, "application/json"));
}

You can also use async version of post without await keyword. but for that you have to add aviator Result. this will wait until request execution will get completed.
public void PostEvent()
{
    string jsonFilePath = @"{""records"": [{""source"": ""Test"",""event_class"": ""Test Class"",""node"": ""test"",""message_key"": ""Test Incident for Test 1"",""severity"": ""5"",""description"": ""Test Incident for Test 1 Desc"",""additional_info"":'{""name"": ""Test System"",""short_des"": ""Test Incident for Test 1 Short Desc"",""ASSIGNMENT_GROUP"": ""xyz""}'}]}";

    var client = new HttpClient();
    client.BaseAddress = new Uri("https://abcdev.service-now.com/api/global/em/jsonv2");
    client.DefaultRequestHeaders.Clear();
    var jsonBody = (new JavaScriptSerializer()).Serialize(jsonFilePath);
    client.PostAsync("test", new StringContent(jsonBody, Encoding.UTF8, "application/json")).Result;
}


text:
Q: How do we set color to an underline for text in textView programatically I am new to Android. I created a table and set textView inside it .I would like to give underline to the text I input in textView. I created an underline by the following code :
SpannableString content=new SpannableString(Regions)
content.setSpan(new UnderlineSpan(),0,Regions.length(),0);
where region is the string containing text.
Can anyone tell me how do we set a color based on our choice to the underline?

A: I faced the same issue, there is no straight way to do it. You can check my solution below :
Modify the text view as below in your layout :
<TextView
            android:id="@+id/residential_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:button="@null"
            android:background="@drawable/only_one_bottom_line"
            android:layout_margin="12dp"
            android:paddingBottom="4dp"
            android:text="test string"
            android:textColor="@drawable/re_option_highlight"
            android:textSize="11sp" />

only_one_bottom_line.xml
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle" >
            <solid android:color="@android:color/transparent" />
        </shape>
    </item>
    <item android:top="-4dp" android:right="-4dp" android:left="-4dp">
        <shape>
            <solid android:color="@android:color/transparent"/>
            <stroke
                android:width="3dp"
                android:color="#0093dd" >
            </stroke>
        </shape>
    </item>
</layer-list>

This background have only one bottom line, and you can change the color from #00 93dd to any color you want. This solution is more easier to implement than creating a custom text view and making hell lot of changes there.

A: To give color to perticuler string you can use Spannable
String s="your text";
    SpannableString ss=  new SpannableString(s);
    ss.setSpan(new ForegroundColorSpan(Color.GREEN), 0, 5, 0);
    tv.setText(ss);


text:
Q: Getting "expected expression" error on a do while loop #include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, string argv[])
{
    //Get the plain text
    do
    {
        string pt = get_string("plaintext: ");
    }
    while (argc == 1);
    else
    {
        printf("Usage: ./caesar key\n");
        return 1;
    }

}

Any reason I am getting an "expected expression" error on the "else" line? It says the expected expression is
"else {" but even when I move the bracket to the same line as the else, it still gives me the error. Also my first time posting on stack and one of my first programs so please let me know if I need to post additional details about the issue.

A: else cannot stand by itself. You need to have an if before the else. Apparently what you want is
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, string argv[])
{
    //Get the plain text
    if(argc == 1)
    {
        string pt = get_string("plaintext: ");
    }
   else
    {
        printf("Usage: ./caesar key\n");
        return 1;
    }
}

Even if your program had compiled it would have looped forever if argc was 1, since the value of argc would never have changed and the condition while(argc == 1) would have been true forever.

A: "else" needs "if" statement preceding it somewhere in the code...
Example:
if{
 ...
}
else {
 ...
}


text:
Q: How to resolve formatting issue with PHP cURL? I am using an API and the documentation for cURL from terminal formats data like this:
 -d '{
    "from_country": "US",
    "from_zip": "92093",
    "from_state": "CA",
    "from_city": "La Jolla",
    "from_street": "9500 Gilman Drive",
    "to_country": "US",
    "to_zip": "90002",
    "to_state": "CA",
    "to_city": "Los Angeles"
    //etc
}'

I'm using PHP cURL to submit data, and I get this error:
{"error":"Bad Parameter Format","detail":"parsing JSON, got 822: unexpected token at 'from_country:US,from_zip:11111,from_state:CO,from_city:Denver,from_street:17282+Glenarm+Street%2C+Suite+400,to_country:US,to_zip:80602,to_state:Colorado,to_city:Thornton,to_street:1551+Claude+Ct,amount:1099,shipping:0,'","status":"400"}

It looks like my some spacing getting urlencoded with "+" and "%2C" adding a "" at the end. Here is my PHP cURL code:
$url = "https://api.sandbox.webservice.com/v2/data";
    //POST vars
    $to_country     = $_POST['Country'];
    $to_zip         = filter_var($_POST["Zip"], FILTER_SANITIZE_STRING);
    $to_state       = $_POST['State'];
    $to_city        = filter_var($_POST["City"], FILTER_SANITIZE_STRING);
    $to_street      = filter_var($_POST["Address"], FILTER_SANITIZE_STRING);
    $amount         = "1099";
    $shipping       = "0";

    //fields
    $fields = array(
        "to_zip"=>urlencode($to_zip),
        "to_state"=>urlencode($to_state),
        "to_city"=>urlencode($to_city),
        "to_street"=>urlencode($to_street),
        "amount"=>urlencode($amount),
        "shipping"=>urlencode($shipping)
    );

    foreach($fields as $key=>$value) { $fields_string .= $key.':'.$value.'&'; }
    $fields_string = rtrim($fields_string,'& ');
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Authorization: Bearer xxxxxxxxx',
        'Content-Type: application/json'
    ));
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($ch);
    echo $output;
    curl_close($ch);

I have tried removing the urlencode from my $fields array - no difference. How can I format the cURL data I send w/PHP to "key":"value"?
I changed:
foreach($fields as $key=>$value) { $fields_string .= $key.':'.$value.'&'; }
$fields_string = rtrim($fields_string,'& ');

To
json_encode($fields);

and get this error {"error":"Bad Parameter Format","detail":"parsing JSON, got 822: unexpected token at '------------------------------9dcc56a2c7b4\r\nContent-Disposition: form-data; name="from_country"\r\n\r\nUS\r\n------------------------------9dcc56a2c7b4\r\nContent-Disposition: form-data; name="from_zip"\r\n\r\n80541\r\n------------------------------9dcc56a2c7b4\r\nContent-Disposition: form-data; name="from_state"\r\n\r\nCO\r\n------------------------------9dcc56a2c7b4\r\nContent-Disposition: form-data; name="from_city"\r\n\r\nDenver\r\n------------------------------9dcc56a2c7b4\r\nContent-Disposition: form-data; name="from_street"\r\n\r\n1333+Glenarm+Street%2C+Suite+400\r\n------------------------------9dcc56a2c7b4\r\nContent-Disposition: form-data; name="to_country"\r\n\r\nUS\r\n------------------------------9dcc56a2c7b4\r\nContent-Disposition: form-data; name="to_zip"\r\n\r\n80602\r\n------------------------------9dcc56a2c7b4\r\nContent-Disposition: form-data; name="to_state"\r\n\r\nColorado\r\n------------------------------9dcc56a2c7b4\r\nContent-Disposition: form-data; name="to_city"\r\n\r\nThornton\r\n------------------------------9dcc56a2c7b4\r\nContent-Disposition: form-data; name="to_street"\r\n\r\n14683+Street+Ct\r\n------------------------------9dcc56a2c7b4\r\nContent-Disposition: form-data; name="amount"\r\n\r\n1099\r\n------------------------------9dcc56a2c7b4\r\nContent-Disposition: form-data; name="shipping"\r\n\r\n0\r\n------------------------------9dcc56a2c7b4--\r\n'","status":"400"}


text:
Q: Update a specific field for each document based on a function I have ~10k documents in my collection, with 3 fields(name, wait, utc).
The timestamps are too granular for my use, and I want to round them down to the last 10 minutes.
I created a function to modify these timestamps (I am rounding them via a function called round_to_10min(), which I import from another python file I have called utility_func.py).
It's not slick or anything but it works:
from datetime import datetime as dt

def round_to_10min(my_dt):
  hours = my_dt.hour
  minutes =(my_dt.minute//10)*10
  date = dt(my_dt.year,my_dt.month,my_dt.day)
  return dt(date.year, date.month,date.day, hours, minutes)

Is there a way for me to update the 'utc' field for each document in my collection, without taking the cursor and saving it into a list, iterating through it?
An example of what I would like to avoid having to do(doesn't seem efficient):
alldocs = collection.find({})
for x in alldocs:
  id = x['_id']
  old_value = int(x['utc'])
  new_value = utility_func.round_to_10min(old_value)
  update_val = {"$set":{"utc":new_value}}
  collection.update_one({"_id":ObjectId(id)},update_val)

Here's where I think I should be headed, but the update argument has me stumped...
update_value = {'$set':{'utc':result_from_function}}
collection.update_many({},update_value)

Is this achievable in pymongo?

A: The mechanism you are seeking will not work.
Pymongo supports MongoDB operations only. If you can find a way to achieve your goal using MongoDB operations, you can perform this in a single update_many or aggregate query.
If you prefer to use python, then you're limited to your original approach of find, loop, update_one.