text:
Q: Не получается сделать ajax запрос на node js сервер Мне выдается ошибка:

No 'Access-Control-Allow-Origin' header is present on the requested
  resource. Origin 'null' is therefore not allowed access.

Я на php обходил её добавляя в headers Access-Control-Allow-Origin: *, но сделав тут response.writeHead(200, 'Access-Control-Allow-Origin: *'); ошибка не ушла.

A: Сталкивался с подобной проблемой и помогло следующее решение:
Правки на сервере node.js
1) добавляем библиотеку cors
const cors = require('cors'); // предварительно сделать npm install cors или yarn add cors

2) Если вы используете express
const app = express();
app.use(cors());

Мне помогло, надеюсь Вам тоже поможет!


text:
Q: In D3, why is setting a linear scale as a value equivalent to using an anonymous function, in which the scale is applied, to return the value? I'm looking at Mike Bostock's horizontal bar chart example, and am a little confused. Everything is pretty simple at first:
var data = [4, 8, 15, 16, 23, 42];

var width = 420,
    barHeight = 20;

var x = d3.scale.linear()
    .domain([0, d3.max(data)])
    .range([0, width]);

var chart = d3.select(".chart")
    .attr("width", width)
    .attr("height", barHeight * data.length);

var bar = chart.selectAll("g")
    .data(data)
  .enter().append("g")
    .attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });

bar.append("rect")
    .attr("width", x)
    .attr("height", barHeight - 1);

bar.append("text")
    .attr("x", function(d) { return x(d) - 3; })
    .attr("y", barHeight / 2)
    .attr("dy", ".35em")
    .text(function(d) { return d; });

But, when I get to the second to last block of code, where the rectangles are appended, I can't understand why he used .attr("width", x) to set the width value rather than .attr("width", function(d){return x(d);})
What, exactly, is going on here? I thought that you needed to supply the x scale with an argument, but this doesn't happen. FWIW, I ran both lines of code through, and got the exact same result — I just can't figure out why this is the case; how does this happen under the hood?

A: Suggested reading:
https://github.com/raganwald-deprecated/homoiconic/blob/master/2012/01/captain-obvious-on-javascript.md
And also:
http://www.wirfs-brock.com/allen/posts/166
FYI, You just have to check the parameters passed to x remember that doing .attr('width', x) will call x with the datum itself AND the index, if x doesn't do anything with the index then you're good to go :)

A: In this example x is a function which is simply passed by reference. By using .attr("width", function(d){return x(d);}) you are just wrapping x into another function, which doesn't add anything to your program.

A: x is a function that expect an argument an return an scaled result. D3 sends the data item as argument and this is the magic.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Drupal Installation PDOException http://localhost  got problem:

PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'drupal_test.semaphore' doesn't exist: SELECT expire, value FROM {semaphore} WHERE name = :name; Array ( [:name] => variable_init ) in lock_may_be_available() (line 165 of /var/www/drupal/includes/lock.inc).

This is my database configuration:
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'drupal_test',
      'username' => 'root',
      'password' => 'XXX',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

What to do?

A: This just happened to me. I manually added database information to settings.php and tried to run the install script by accessing http://localhost/mysubdirectory, instead of adding db info through the install script. Drupal saw the db information and thought it was installed, so it looked for its Drupal tables, couldn't find them, and threw the error.
The solution for me was simply to run the script manually (navigating to http://localhost/mysubdirectory/install.php). Hope this helps!

A: a lot of times simply uninstalling and trying again can fix bugs like this. It's possible that there was something wrong with the installation of maybe you gave it some incorrect information.

A: semaphore is core table for holding semaphores, locks, flags, etc. that cannot be stored as Drupal variables since they must not be cached. In some version updating (6.xx-6.yy) it was lost, so just create it:
CREATE TABLE IF NOT EXISTS `semaphore` (
  `name` varchar(255) NOT NULL DEFAULT '',
  `value` varchar(255) NOT NULL DEFAULT '',
  `expire` double NOT NULL,
  PRIMARY KEY (`name`),
  KEY `expire` (`expire`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

A: It try to read a table was not found.
If you install a new module, try to reinstall this module, or remove it . But if you don't install anything, you need to reinstall all drupal :(

A: This problem is related to your mysql database type. If you are moving your site another server, probably your database type is mismatch and using InnoDB. Because of that, you have to change your database table's type with this command.
ALTER TABLE **table_name** ENGINE = MyISAM;


text:
Q: Remove weekends in a formula I want to remove weekends from a calculated column calculation. I am having a formula which calculate daily target:
Daily MAL Target = [MAL_Qtarget_A] /
                   (ENDOFQUARTER(Marketing_targets_MALMEL[Date]) -
                   ENDOFQUARTER(PREVIOUSQUARTER(Marketing_targets_MALMEL[Date])))

In the marketing Targets table thers a seperate column to identify whether the date is working day or weekday as 1 and 0.
IsWorkDay = SWITCH(WEEKDAY([Date]),1,0,7,0,1)

I want to add "IsWorkingDate=1" to the above Daily Mal Target formula. It is a calculated column. I have tried so many ways but could not do it.
Can anyone help me on this?

A: You can use this DAX expression to check for weekdays:
= IF(OR(WEEKDAY([Date]) = 1, WEEKDAY([Date) = 7), "Calculation for Weekdays", "Calculation for Mo to Fr")

A: If it's a calculated column, you can use an if condition to make the value 0 or blank for weekends:
Daily MAL Target = IF(WEEKDAY(Marketing_targets_MALMEL[Date]) in {1,7},
                   BLANK(),
                   ([MAL_Qtarget_A] /
                   (ENDOFQUARTER(Marketing_targets_MALMEL[Date]) -
                   ENDOFQUARTER(PREVIOUSQUARTER(Marketing_targets_MALMEL[Date]))))

Hope this helps.


text:
Q: Failure to run WSL internal command from powershell I need to run WSL internal command from powershell script triggered by task scheduler on user logon. OS: Windows 11 22H2.
# waiting for wsl.exe to appear
# before adding this I was getting errors about no command wsl
# probably something about how MSIX packages work in Windows
while (-Not (Get-Command wsl.exe))
{
    Start-Sleep -Milliseconds 500
}

while (-Not (wsl.exe ip a))
{
    Write-Output $LastExitCode
    Start-Sleep -Milliseconds 500
}

Result in script logs is:
1
1
1
...

After logon the script runs infinitely. WSL commands are available, I can write in a console wsl.exe ip a and get the result and $LastExitCode is 0. But the script is still running until I stop the task in task scheduler. Somehow the script can not get access to WSL.
When I run the script from admin console, it works fine.
Task options in task scheduler:

*

*When running the task, use the following user account: <my account>

*(*) Run only when the user is logged on

*[x] Run with highest privileges

*Triggers: at log on: <my account>

*Actions: Start a program: powershell.exe -file "<path to the script>"

"Run with highest privileges" is necessary because the script needs to run netsh commands.
How can I fix it to run WSL command?
In Windows 10 the same script with the same task scheduler settings works fine.


text:
Q: C# Packet sending using TCP streams I'm trying to send multiple packets from a tcp server to a client using only read and write from the base "Stream" class. The problem is, I don't know what the size of the packet will be (client side). Should I send and int (4 bytes) before each packet so the client can ajust the buffer and receive only the nuber of bytes specified? I feel like there's already something in the tcp protocol that handles that but I can't seem to find it.

A: The process for what you are wanting to do is called Message Framing and there is no built in mecinism in TcpClient that does this for you. It is the responsibility of the higher level application layer to do it, be it your own code appending the length on the prefix of the message or some other library that handles message framing for you like WCF.
Here is a full example showing a length prefixed implementation like you suggested in your question.


text:
Q: Eclipse warning in EL (not empty) I use this rendered="#{not empty facesContext.messageList}" to render a form. All works fine but my eclipse marker says the following warnings:
Warning1:This empty expression always evaluates to false.  Only string, maps, arrays and collection have meaningful values for the empty operator.
Warning2: This not will always result a value of true.
I use Eclipse Kepler for it. Can i ignore this?


text:
Q: Estimation of Equatorial Bulge of the Earth My dynamics lecture notes repeat the Earth's equatorial bulge can be approximated as:
$$ \approx \frac{\Omega^2R}{g} \approx \frac{1}{300} $$
(Do they mean R/300?)
They also include statements like:
"The Earth's oblateness  $ \frac{I_3-I_1}{I_1}\approx \frac{\Omega^2R}{g} \approx \frac{1}{300} $"
Could anybody explain where this comes from? I have tried several ways to balance the gravitational and centripetal forces but I never seem to arrive at the correct result and cannot get my head around this concept.


text:
Q: Plotting 3d bars from torch tensors with matplotlib or seaborn I have two torch tensors, such as:
tensor([[[0.5000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
          0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.5000],
         [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
          0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
         [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
          0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
         [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
          0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
         [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
          0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
         [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
          0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
         [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
          0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
          [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
          0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
         [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
          0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
         [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
          0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
         [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
          0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
         [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
          0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
         [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
          0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
         [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
          0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
         [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
          0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
         [0.5000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
          0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.5000]],

     [[0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
      0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
     [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
      0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
     [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
      0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
     [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
      0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
     [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
      0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
     [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
      0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
     [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
      0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
     [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
      0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
     [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
      0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
     [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
      0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
     [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
      0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
     [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
      0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
     [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
      0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
     [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
      0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
     [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
      0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
     [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
      0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000]]],
   device='cuda:0', dtype=torch.float64)

It a 16x16 matrix representing a Density Matrix. And I have another similar one, 16x16, representing a reconstructed Density Matrix which is the output from a neural network.
I want to plot both such tensors such that the output is something like the image below:

I tried using bar3d from matplotlib, but without success. Can anyone give me a hint, piece of code, or reference in python, using matplot or seaborn, for such a task?


text:
Q: Is there a predefined DOM Event object for scroll event? I'm creating an event handler for a component in Angular.
The problem I'm having is right now is: I can't find a typed event for scroll, therefore in the handler's argument I must use any.
I see there are some other typed DOM Event like MouseEvent, DragEvent...Is there something like ScrollEvent ?
My sample code:
component.html
<div (scroll)="onScroll($event)">
    ...more elements here
</div>

component.ts
onScroll(scrollEvent: any) {
    // When debugging here, scrollEvent is of type "Event"
    // but if I declare "scrollEvent: Event", I must use "(e.target as any).offsetHeight"
    // because "Event" doesn't have offsetHeight property
    let offsetHeight = e.target.offsetHeight;
    ...more logic here
}


text:
Q: Fastest way in Metal to copy device data to threadgroup memory? To optimize buffer read in Metal, I intend to use threadgroup memory.
Buf it seems:
(1) There is no API like std::memcpy in MSL;
(2) Also, there is no API like [setBuffer: atIndex:] to set data for threadgroup memory.
The amount of data is 2~4KB. How can I get the fastest way to copy data from device data to threadgroup memory? THX!


text:
Q: Problems using local printer via RDP on windows 2003 sever The client is windows 7 machine, it have local printer attached. Necessary check-boxes are checked (at "share local resources" in remote desktop connection configuration windows), but the printer not appearing in "printers and faxes".
Questions: Do I need to install drivers for this printer?
What drivers should I install? For server, client or both?
If it willn't work natively, is it possible to use this printer using any 3-rd party programs (both computers server and client are behind the NAT)?
Thanks for suggestions.

A: You should install on server the same version of drivers you have on client. It's not necessary to add printer on server, just install drivers.
Also it's possible with 3-rd part software like ScrewDrivers but anyway you should install it on server and on client.
Windows 2008 Server Terminal Services offer Easy Print feature which allow to print from RDP session or RemoteApp application without installing printer drivers server on server.

A: With Windows 2003 remote desktop, the server must have the printer drivers installed in order to use the remote printers.
You need to install the drivers ON the server FOR the server. So install the drivers for Windows 2003 on your server.
Beware about lots of cheap printers which require direct connection to the printer. You can't use them with remote desktop. You can sometimes tweak things but this is not garanteed.
edit: as stated by Sergey, you only have to install the drivers. Installing the printers is not mandatory.


text:
Q: Initialize WordPress customizer variables I have recently starting integrating the wordpress customizer into my theme.
Given the fact that i already had a theme options page, i use these values as default values of my new options (in the add_setting parameter).
All my new options are held into a variable called 'theme_options' which is an array of values.
The problem i have is that a user has to visit the customization page and click "save" on his first install to populate the 'theme_options' variable.
I am wondering if there is a way to initialize this field on theme activation directly (just like many theme options framework do).
Thanks in advance !

A: I believe that all you need to do is pass defaults to get_option
function init_theme_options() {
  // check to see if theme options are set
  // Not sure how your options are organized but...
  $defaults = array(
    'opt1' => 'stuff1',
    'opt2' => 'stuff2'
  )
  $theme_options = get_option('theme_option_name',$defaults);
}

If you want to see a very complicated version of this, look at how Twenty Eleven does it.


text:
Q: Porting code using sizeof() from C++ to PHP I have some C++ code (segment seen below), I need to convert this to another language (namely PHP). The code, as seen, uses structs, which PHP doesn't do. I know I can "kind of" emulate structs through objects/arrays, however, this isn't the same. That is not my main problem though. I need a way to implement the sizeof() function found in C++ (since PHP's sizeof() function just counts the number of elements in an array/object).
typedef unsigned long Offset;
typedef unsigned long Size;

struct Location {
    Offset offset;
    Size size;
};

struct Header {
    unsigned long magic;
    unsigned long version;
    struct Location elements;
    struct Location ids;
    struct Location strings;
    struct Location integers;
    struct Location decimals;
    struct Location files;
};
int Build() {
    Header theheader;
    theheader.magic = *((unsigned long*)"P3TF");
    theheader.version = 272;
    theheader.elements.offset = sizeof(theheader);
    theheader.elements.size = element_offset;
    theheader.ids.offset = ((theheader.elements.offset + theheader.elements.size + 15) / 16) * 16;
    theheader.ids.size = ids_offset;
    theheader.strings.offset = ((theheader.ids.offset + theheader.ids.size + 15) / 16) * 16;
    theheader.strings.size = string_offset;
    theheader.integers.offset = ((theheader.strings.offset + theheader.strings.size + 15) / 16) * 16;
    theheader.integers.size = 0;
    theheader.decimals.offset = ((theheader.integers.offset + theheader.integers.size + 15) / 16) * 16;
    theheader.decimals.size = 0;
    theheader.files.offset = ((theheader.decimals.offset + theheader.decimals.size + 15) / 16) * 16;
    theheader.files.size = file_offset;
    theheader.padding[0] = 0;
    theheader.padding[1] = 0;
    fwrite(&theheader, 1, sizeof(theheader), file_handle);
}

Can anyone please point me in the right direction on how to do this?
Any help would be appreciated.

A: Obviously recreating sizeof from C will be a difficult feat, as C is statically-typed and, traditionally, sizeof is evaluated at run-time by the compiler. PHP is also pretty quiet about its memory usage.
One method of dynamically grabbing the size of an object is to use memory_get_usage (official PHP reference) before and after the allocation of the object in question. Of course, you'll run into some fun calculations when you compare the two memory usage values, as storing the values into variables will allocate memory also.
This is a pretty shaky method of recreating sizeof, but if it works it works.

A: You could simply sum all sizes of the objects in the array or object. However, that still only gets the length of strings, etc. If you want the actual size of the binary representation of the object, you'll have to do some additional math, such as converting all ints to 32 bits (or 64) and appending a null byte to all UTF-8 strings. If you're using charsets, do make sure that they are single-byte or at least measurable in bytes.
PHP does not have a function that checks the memory size of an object.


text:
Q: How to have google map auto reads from inputs I am building a site(something like yellow pages) which user will first choose from a pulldown menu on their country > states > city. Then they will be prompt to mark their own location on google map(or drag the market to an accurate location).
How can I send the city chosen from the pulldown menu into the map, so it display a zoom in of the city instead of a worldwide map.
Can i do it without the longitude and lattitude within the database of the pulldown menu?

A: You will have to make a geocoding request to google maps api and get the corodinates for the address in the drop down and then use the result to zoom the map on that address.
Read about geocoding in the google maps documentation. You will find examples of usage and anything you need there.
And to get the value of the drop downs and pass it to the js for making a request to google maps, you will need this function.


text:
Q: WCF hosted as Windows service - Custom HTTP header is not reflecting on Response header I have a standalone C# WCF service running as a Windows service. I have the requirement to add custom headers like "X-Xss-Protection" to all responses. I have tried with the following script in app.config file but this doesn't add any HTTP header to the response.
    <system.webServer>
            <httpProtocol>
                <customHeaders>
                    <remove name="X-Powered-By"/>
                    <remove name="X-AspNet-Version"/>
                    <remove name="HTTPServer"/>
                    <remove name="Microsoft-IIS"/>
                    <add name="Strick-Transport-Security" value="max-age=31536000;includeSubDomains"/>
                    <add name="Content-Security-Policy" value="script-src 'unsafe-eval' https://www.google.com 'self' 'unsafe-inline'"/>
                    <add name="X-Xss-Protection" value="1; mode=block"/>
                    <add name="Feature-Policy" value="geolocation 'none'"/>
                    <add name="Cache-Control" value="no-cache, no-store, must-revalidate, pre-check=0, post-check=0, max-age=0, s-maxage=0"/>
                    <add name="Pragma" value="no-cache"/>
                    <add name="Expires" value="0"/>
                </customHeaders>
            </httpProtocol>
        </system.webServer>

A: The reason why you cannot successfully insert the header through the IDispatchMessageInspector.BeforeSendReply method is probably because you did not add the [CustomBehavior] tag above the interface.
Add the tag like this:
[CustomBehavior]
Public interface IService


text:
Q: Interactive Grid- Automatic Row Processing (DML) : Character limitation in Code editor I have a requirement where 300 columns had to be processed. I am trying to achieve this using  IG automatic row processing (DML). When writing the code in the editor I get a error stating 'Value too long by 2015 characters'.
I suppose this is an Oracle Apex limitation. Can someone please share their views on this?

A:
When writing the code in the editor ...

I'd say that your problem isn't related to number of columns, but a large query which can't fit into "SQL Query" item of the Page Designer.
Which Apex version do you use? I can't tell for sure (as I don't know it), but my impression is that Apex up to version 4.2 had that item limited to VARCHAR2(4000) so - if your query is larger than that, it won't fit (such as in your case - query you wrote is 2015 characters longer than the maximum size the item allows). In 5.x version, you can put a whole lot of query into the item (as if it was modified to a CLOB).
Now, as you use Interactive Grid and it appeared in 5.x version, huh ... maybe what I wrote above isn't entirely true. Unfortunately, you can't switch to a query whose source is a function that returns query (such as in Classic Reports), as you could write a (stored) function and simply call it from Apex.
As you said that you used automatic row processing, did you put too much code somewhere in there?
On the other hand, I Googled a little bit, looking for limit of column numbers in the IG - couldn't find anything official, but someone complained (here, on StackOveflow) that they tried to create an IG with over 100 columns, and it didn't work.
So, yes - maybe you hit the limit, but I can't confirm it. Hopefully, someone who knows Apex better will be able to assist. Alternatively, consider asking the same question on OTN forums, as people who designed Apex answer questions there.


text:
Q: Conditional statement not activated for bouncing ball in p5.js I'm completely new to JavaScript and p5.js. I know this is not the most efficient code for bouncing ball, but I tried to write my own bouncing ball mechanic as self-learning.
function draw() {
    background (col); // background
    col = map(cir.x, 0, 600, 0, 255) // map function

    fill (350, 200, 200);
    ellipse (cir.x, cir.y, cir.diameter, cir.diameter);

    // Bounding ball mechanic
    var speed = 3;
    var hitRightWall = false;
    var hitLeftWall = false;

    if (cir.x >= 300) {
        hitRightWall == true;
        hitLeftWall == false;
    }
    else if (cir.x <= -50) {
        hitLeftWall == true;
        hitRightWall == false;
    }
    if (hitRightWall==true) {
        speed == -3;
    }
    else {
        speed == 3;
    }
    cir.x = cir.x + speed;
}

For some reason, the if (hitRightWall==True) condition is never activated even though if (cir.x >= 300) was activated. The ball keeps going to the right and off the screen.

A: There are a few things going on here. First off, you're resetting the value of hitRightWall and hitLeftWall to false every frame. Is that what you want?
Secondly, look at statements like this:
hitRightWall == true;

The == double equals is doing a comparison, not an assignment. You probably want something like this:
hitRightWall = true;

The = single equals assigns a value to a variable.
Finally, I'm not totally sure why you need these variables at all. Can't you modify the speed variable directly in your first if / else if statement?
Shameless self-promotion: here is a tutorial on collision detection. It's written for Processing, but the same ideas apply to P5.js.


text:
Q: Unknown SQL error I'm creating a table and its producing an SQL error and I can't see why.
    statement.executeUpdate("drop table if exists group");
    String group = "CREATE TABLE group" +
         "(groupId INT PRIMARY KEY NOT NULL, " +
         "groupLeader INT NOT NULL, " +
         "groupMembers INT NOT NULL, " +
         "goals INT NOT NULL)";
    statement.executeUpdate(group);

A: GROUP is  reserved word. Try with:
statement.executeUpdate("drop table if exists `group`");
    String group = "CREATE TABLE `group`" +
         "(groupId INT PRIMARY KEY NOT NULL, " +
         "groupLeader INT NOT NULL, " +
         "groupMembers INT NOT NULL, " +
         "goals INT NOT NULL)";
    statement.executeUpdate(group);


text:
Q: Access Denied while querying S3 files from AWS Athena within Lambda in different account I am trying to query Athena View from my Lambda code. Created Athena table for S3 files which are in different account. Athena Query editor is giving me below error:

Access Denied (Service: Amazon S3; Status Code: 403; Error Code: AccessDenied;

I tried accessing Athena View from my Lambda code. Created Lambda Execution Role and allowed this role in Bucket Policy of another account S3 bucket as well like below:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::2222222222:role/BAccountRoleFullAccess"
            },
            "Action": [
                "s3:PutObject",
                "s3:PutObjectAcl",
                "s3:GetObject"
            ],
            "Resource": "arn:aws:s3:::s3_bucket/*"
        },
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": [
                    "arn:aws:iam::111111111:role/A-Role",
                    "arn:aws:iam::111111111:role/B-Role"
                ]
            },
            "Action": "s3:*",
            "Resource": [
                "arn:aws:s3:::s3_bucket",
                "arn:aws:s3:::s3_bucket/*"
            ]
        }
    ]
}

From Lambda, getting below error:
    'Status': {'State': 'FAILED', 'StateChangeReason': 'com.amazonaws.services.s3.model.AmazonS3Exception:
        Access Denied (Service: Amazon S3; Status Code: 403; Error Code: AccessDenied; Request ID: 3A8953784EC73B17;
    S3 Extended Request ID: LfQZdTCj7sSQWcBqVNhtHrDEnJuGxgJQxvillSHznkWIr8t5TVzSaUwNSdSNh+YzDUj+S6aOUyI=),
    S3 Extended Request ID: LfQZdTCj7sSQWcBqVNhtHrDEnJuGxgJQxvillSHznkWIr8t5TVzSaUwNSdSNh+YzDUj+S6aOUyI=
 (Path: s3://s3_bucket/Input/myTestFile.csv)'

This Lambda function is using arn:aws:iam::111111111:role/B-Role Execution role which has full access to Athena and S3.
Someone please guide me.

A: To reproduce this situation, I did the following:

*

*In Account-A, created an Amazon S3 bucket (Bucket-A) and uploaded a CSV file

*In Account-B, created an IAM Role (Role-B) with S3 and Athena permissions

*Turned OFF Block Public Access on Bucket-A

*Added a bucket policy to Bucket-A that references Role-B:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::[ACCOUNT-B]:role/role-b"
            },
            "Action": [
                "s3:Get*",
                "s3:List*"
            ],
            "Resource": [
                "arn:aws:s3:::bucket-a",
                "arn:aws:s3:::bucket-a/*"
            ]
        }
    ]
}

*

*In Account-B, manually defined a table in the Amazon Athena console

*Ran a query on the Athena table. As expected, received Access Denied because I was using an IAM User to access the console, not the IAM Role defined in the Bucket Policy on Bucket-A

*Created an AWS Lambda function in Account-B that uses Role-B:

import boto3
import time

def lambda_handler(event, context):

    athena_client = boto3.client('athena')
    query1 = athena_client.start_query_execution(
        QueryString='SELECT * FROM foo',
        ResultConfiguration={'OutputLocation': 's3://my-athena-out-bucket/'}
    )
    time.sleep(10)

    query2 = athena_client.get_query_results(QueryExecutionId=query1['QueryExecutionId'])
    print(query2)

*

*Ran the Lambda function. It successfully returned data from the CSV file.

Please compare your configurations against the above steps that I took. Hopefully you will find a difference that will enable your cross-account access by Athena.
Reference: Cross-account Access - Amazon Athena


text:
Q: How to calculate f1(f2(...fn(x)...)) given a gerund? One can calculate f1(f2(f3(x))) as
*: +: >: 4                 NB. 100

Given a gerund of "unknown" length (eg. m1 =: *:`+:`>:, or m2 =: +:`>:) how can one calculate f1(f2(...(fn(x)) ...))?
So far I have only been able to evoke the gerund using m `: 0.
(*:`+:`>: `: 0) 4         NB. 16 8 5

A: Let:
   NB. an example gerund
   ] g=: *:`<:`+:`>:
┌──┬──┬──┬──┐
│*:│<:│+:│>:│
└──┴──┴──┴──┘
   NB. a sentence to evoke
   *: <: +: >: 4
81

1st approach (via dynamic programming)
1A. Compose the whole sentence then evoke it
Convert all elements in gerund to linear representation (LR), compose the sentence, then evoke it:
   NB. utility to find out a LR from an atomic
   NB. representation (AR) and parenthesize it
   NB. pLR=. plr AR
   plr=: 3 : 0
v=. y 5!:0
'(' , (5!:5 < 'v') , ') '
)
   NB. result=. gerund v1 input
   v1=: 4 : '". (; <@plr"0 x) , ": y'
   NB. evoke v1 with a gerund and input applied
   g v1 4
81

Pros: no
Cons:

*

*input data type should be exact (neither float nor complex) since Format (":) may truncate

*a verb applied to input can be a monad only

1B. Evoke component verbs sequentially
Take the current element from gerund, transform it to verb, apply that verb to accumulator, repeat for the next element from gerund:
   NB. result=. gerund v2 input
   v2=: >@(4 : '(x 5!:0)&.> y'/)@(, <)
   NB. evoke v2 with a gerund and input applied
   g v2 4
81

Pros:

*

*any data types for input are allowed

Cons:

*

*a verb applied to input can be a monad only

2nd approach (functional)
2A. Transform gerund to fork
   NB. a fork we are going to compose, in action
   ([: *: [: <: [: +: >:) 4
81
   NB. its structure
   ([: *: [: <: [: +: >:)
┌──┬──┬──────────────────┐
│[:│*:│┌──┬──┬──────────┐│
│  │  ││[:│<:│┌──┬──┬──┐││
│  │  ││  │  ││[:│+:│>:│││
│  │  ││  │  │└──┴──┴──┘││
│  │  │└──┴──┴──────────┘│
└──┴──┴──────────────────┘
   NB. how to compose it
   ('[:' ; g)@.0 1 0 2 0 3 4
┌──┬──┬──────────────────┐
│[:│*:│┌──┬──┬──────────┐│
│  │  ││[:│<:│┌──┬──┬──┐││
│  │  ││  │  ││[:│+:│>:│││
│  │  ││  │  │└──┴──┴──┘││
│  │  │└──┴──┴──────────┘│
└──┴──┴──────────────────┘
   NB. selector (ISO generator)
   NB. iso=. sel gerund
   sel=: (< < < _2) { (0 ,@,. #\)
   NB. let's test it
   sel g
0 1 0 2 0 3 4
   NB. sentence to assemble a fork
   ('[:' ; g)@.(sel g)
┌──┬──┬──────────────────┐
│[:│*:│┌──┬──┬──────────┐│
│  │  ││[:│<:│┌──┬──┬──┐││
│  │  ││  │  ││[:│+:│>:│││
│  │  ││  │  │└──┴──┴──┘││
│  │  │└──┴──┴──────────┘│
└──┴──┴──────────────────┘
   NB. an adverb executing that sentence
   NB. fork=. gerund a2a
   a2a=: 1 : '(''[:'' ; m)@.(sel m)'
   NB. evoke that adverb to transform a gerund to a fork
   g a2a
┌──┬──┬──────────────────┐
│[:│*:│┌──┬──┬──────────┐│
│  │  ││[:│<:│┌──┬──┬──┐││
│  │  ││  │  ││[:│+:│>:│││
│  │  ││  │  │└──┴──┴──┘││
│  │  │└──┴──┴──────────┘│
└──┴──┴──────────────────┘
   NB. apply a fork produced to input
   g a2a 4
81

Pros:

*

*any data types for input are allowed

*a verb applied to input can be of any valence (either monad, dyad or ambivalent)

Cons: no
2B. Transform gerund to conveyor
Join component verbs by At (@:) somehow. A resulting verb will be an At-chained sequence of component verbs.
2B1. Via arconj utility
Join component verbs to compose AR, then convert AR to verb by Define (5!:0).
   NB. a chain we are going to compose, in action
   *:@:<:@:+:@:>: 4
81
   NB. its structure
   *:@:<:@:+:@:>:
┌──────────────────┬──┬──┐
│┌──────────┬──┬──┐│@:│>:│
││┌──┬──┬──┐│@:│+:││  │  │
│││*:│@:│<:││  │  ││  │  │
││└──┴──┴──┘│  │  ││  │  │
│└──────────┴──┴──┘│  │  │
└──────────────────┴──┴──┘
   NB. its AR
   chain=. *:@:<:@:+:@:>:
   5!:1 < 'chain'
┌────────────────────────────────┐
│┌──┬───────────────────────────┐│
││@:│┌──────────────────────┬──┐││
││  ││┌──┬─────────────────┐│>:│││
││  │││@:│┌────────────┬──┐││  │││
││  │││  ││┌──┬───────┐│+:│││  │││
││  │││  │││@:│┌──┬──┐││  │││  │││
││  │││  │││  ││*:│<:│││  │││  │││
││  │││  │││  │└──┴──┘││  │││  │││
││  │││  ││└──┴───────┘│  │││  │││
││  │││  │└────────────┴──┘││  │││
││  ││└──┴─────────────────┘│  │││
││  │└──────────────────────┴──┘││
│└──┴───────────────────────────┘│
└────────────────────────────────┘
   NB. we'll compose it with AR utility (arconj) from addon
   load 'misc/miscutils/langexten'
   NB. an adverb assembling a chain
   NB. chain=. gerund a2b1a
   a2b1a=: 1 : '(''@:'' arconj~/ |. m) 5!:0'
   NB. evoke that adverb to transform a gerund to chain
   g a2b1a
┌──────────────────┬──┬──┐
│┌──────────┬──┬──┐│@:│>:│
││┌──┬──┬──┐│@:│+:││  │  │
│││*:│@:│<:││  │  ││  │  │
││└──┴──┴──┘│  │  ││  │  │
│└──────────┴──┴──┘│  │  │
└──────────────────┴──┴──┘
   NB. apply a chain produced to input
   g a2b1a 4
81

Pros:

*

*any data types for input are allowed

*a verb applied to input can be of any valence (either monad, dyad or ambivalent)

Cons: no
Notes:

*

*a2b1a can be simplified to produce a chain with a slightly different structure but the same functionality:
a2b1b=: 1 : '(''@:'' arconj/ m) 5!:0'

*arconj utility may be re-implemented manually as [1]:
arconj2=: (<'@:') ,@<@, <@,
a2b1c=: 1 : '({. arconj2/ m) 5!:0'

or as [1]:
arconj3=: 4 : '(x`:6)@(y`:6)`'''''
a2b1d=: 1 : '({. arconj3/ m) 5!:0'

2B2. Via Train (`:6)
Join component verbs, then apply Train (`:6) [2].
   NB. a chain we are going to compose, in action
   *:@:<:@:+:@:>: 4
81
   NB. its structure
   *:@:<:@:+:@:>:
┌──────────────────┬──┬──┐
│┌──────────┬──┬──┐│@:│>:│
││┌──┬──┬──┐│@:│+:││  │  │
│││*:│@:│<:││  │  ││  │  │
││└──┴──┴──┘│  │  ││  │  │
│└──────────┴──┴──┘│  │  │
└──────────────────┴──┴──┘
   NB. an adverb assembling a chain
   NB. chain=. gerund a2b2
   a2b2=: 1 : '(}: , m ,. <''@:'')`:6'
   NB. evoke that adverb to transform a gerund to chain
   g a2b2
┌──────────────────┬──┬──┐
│┌──────────┬──┬──┐│@:│>:│
││┌──┬──┬──┐│@:│+:││  │  │
│││*:│@:│<:││  │  ││  │  │
││└──┴──┴──┘│  │  ││  │  │
│└──────────┴──┴──┘│  │  │
└──────────────────┴──┴──┘
   NB. apply a chain produced to input
   g a2b2 4
81

Pros:

*

*any data types for input are allowed

*a verb applied to input can be of any valence (either monad, dyad or ambivalent)

*the simplest version

Cons: no
Notes
J Forums are the best place to ask if you prefer to get answer quicker.
References
[1]: [Jprogramming] Gerund composed application
by Raul Miller, 2017-09-25
[2]: System/Interpreter/Requests#verb pipelines by Dan Bron, 2007-12-21

A: This solution is not elegant, but it works.
Start by converting the gerund into a string form using Foreign Conjunctions Define (5!:0) adverb and Atomic Representation (5!:1) then unbox using Raze (;).
Then convert the y argument to a string using Default Format (":) and prepending a blank to give space to the gerund string.
Use Append (,) to create one string and apply Do (".) to that string for the result.
g=: 4 : 0
s=: ; (5!:1 <'t'[t=.x) 5!:0  NB. changes gerunds to string
a=:' ' , ": y                NB. makes argument into a string prefixed by blank
". s,a
)

or on one line
g1=: 4 : ' ". (; (5!:1 <''t''[t=.x) 5!:0 ), '' '' , ": y'

   *:` +:` >: g 4
100
   *:` +:` >: g1 4
100


text:
Q: Proving $e = (\Delta m) c^2$ by linear approximation
In relativity the mass is $\frac{m_0}{\sqrt{1-\frac{v^2}{c^2}}}$ at
  velocity $u$. By Problem 20 this is near $m_0 + $ _____
  for small $v$. Show that the kinetic energy $\frac 1 2 mv^2$
  and the change in mass satisfy Einstein's equation $e = (\Delta m) c^2$.

We start with $m \approx m_0 + \frac 1 2 \frac {v^2}{c^2}$. Then, we have $\Delta m \approx \frac 1 2 \frac {v^2}{c^2}$. This equation looks strange as there is mass on the left side and no unit on the right side. However, we ignore it and proceed. We now get $(\Delta m) c^2\approx \frac 1 2 v^2$. Why are we are missing an $m$ on the right side?

A: Recall from the binomial theorem that we have
$$\left(1-x\right)^{-1/2}=1+\frac12 x+O(x^2)$$
Now, using $x=v^2/c^2$ we have
$$m\approx m_0\left(1+\frac{v^2}{2c^2}\right) $$
so that
$$m-m_0=\frac12 m_0v^2/c^2$$
Finally, let $\Delta m=m-m_0$.  Then, we obtain
$$\Delta mc^2=\frac12 m_0v^2$$

A: The correct equation is $m\approx m_0(1+\frac{v^2}{2c^2})\implies \Delta m_0=\frac{m_0v^2}{2c^2}$ Then, the dimensions are matched.

A: According to relativity, if $m_0$ is the mass of a body at rest then the mass $m$ of a body at a velocity $v$ $$m=\frac{m_0}{\sqrt{1-\frac{v^2}{c^2}}}=m_0\left(1-\frac{v^2}{c^2}\right)^{-1/2}$$
apply binomial theorem for $v^2/c^2<<1$,  $$m=m_0\left(1-\left(-\frac12\right)\frac{v^2}{c^2}\right)$$
$$m=m_0\left(1+\frac{v^2}{2c^2}\right)$$
$$m=m_0+\frac{m_0v^2}{2c^2}$$
$$m-m_0=\frac{m_0v^2}{2c^2}$$
$$\Delta m=\frac{m_0v^2}{2c^2}$$
$$\Delta m c^2=\frac{1}{2}m_0v^2$$


text:
Q: fortran redirect only some output to stdout I am kind of new to fortran and have come across the following problem. Let us consider the following simple "output.for":
implicit none
character*10 str1,str2

call get_command_argument(1,setupfile)
open(20, file = setupfile)
read(20,*) str1, str2

write(6,*) str1        ! I want this to go to terminal output
write(6,*) str2        ! I'd like to have this redirected to a file

end

And now I invoke the code as: ./output setupfile > outfile.dat
How do I force "str1" to be printed to terminal output while "str2" to be redirected to outfile.dat?


text:
Q: Combining coverage I have a sql table with people and their coverage periods. Many people have multiple entries, and these should be condensed only where the coverage is continuous. The values are varchars but I can change to something else.
Name    effective   termination
John    20160101    20160315
John    20160316    20160501
John    20160601    20161101
John    20160701    20160731
John    20160801    20161231

Should be
John    20160101    20160501
John    20160601    20161231

A: Here is the idea.  Identify where each group of coverage begins.  Use this information to identify the groups.  Then aggregation gets what you want:
  select name, min(effective) as effective, max(termination) as termination
  from (select t.*,
               sum(case when tprev.name is null then 1 else 0 end) over (partition by name order by effective) as grp
        from t left join
             t tprev
             on t.name = tprev.name and
                t.effective = dateadd(day, 1, tprev.termination)
       ) t
  group by name, grp;


text:
Q: Negative Oscillating Signal with Op-Amp? I am trying to design a Wein Bridge oscillator that oscillates with frequency 1.5 kHz using LM741 Op-Amp. I simulate it in LT-Spice and obtained sinusoidal oscillation going both positive and negative. But when I fabricated it in perf-board, I am obtaining sinusoidal oscillation in the negative regime only. I would be really glad if someone could tell me if I am missing something on this.

The output that I obtained from simulation is like below:

Output obtained after soldering the circuit in perf-board is below(You can see that oscillation is in negative with upper peak at -360 mV and lower peak at -1.21 V(with Vpp of 850 mVpp):


text:
Q: Python Logging writing to terminal and log file I have two files: script.py and functions.py. In functions.py, I have logger setup, and a set of functions (made up one below):
class ecosystem():
    def __init__(self, environment, mode):
        self.logger = logging.getLogger(__name__)
            if os.path.exists('log.log'):
                os.remove('log.log')

            handler= logging.FileHandler('log.log')
            if mode.lower()== 'info':
                handler.setLevel(logging.INFO)
                self.logger.setLevel(logging.INFO)
            elif mode.lower()== 'warning':
                handler.setLevel(logging.WARNING)
                self.logger.setLevel(logging.WARNING)
            elif mode.lower()== 'error':
                handler.setLevel(logging.ERROR)
                self.logger.setLevel(logging.ERROR)
            elif mode.lower()== 'critical':
                handler.setLevel(logging.CRITICAL)
                self.logger.setLevel(logging.CRITICAL)
            else:
                handler.setLevel(logging.DEBUG)
                self.logger.setLevel(logging.DEBUG)

            #Logging file format
            formatter = logging.Formatter('    %(levelname)s | %(asctime)s | %(message)s \n')
            handler.setFormatter(formatter)
            #Add the handler to the logger
            self.logger.addHandler(handler)

            self.logger.info('Logging starts here')

    def my_function():
        self.logger.debug('test log'))
        return True

I'm trying to call ecosystem.my_function from script.py, but when I do, the logger.debug message shows up in both the terminal window AND log.log. Any ideas why this might be happening?
If it helps, I also import other modules into functions.py, if those modules import logging as well, could that cause issues?

A: It looks like you're initializing the logger with log.log file inside the __init__ method of ecosystem class. This means that any code that creates an object of ecosystem will initialize the logger. Somewhere in your code, in one the files, you are creating that object and hence the logger is initialized and writes to the file.
Note that you do not need to call __init__ yourself as it is called on object creation. ie. after this call
my_obj = ecosystem()

log files will be written.
You're asking why both stderr and file is used after your new file handler is attached. This is because of the propagate attribute. By default propagate is True and this means your log will bubble up the hierarchy of loggers and each one will continue handling it. Since default root logger is at the top of the hierarchy, it will be handling your log too. Set propagate to False fix this:
self.logger.propagate = False

You might want to read up a bit on logging. Also, if you want to keep your sanity regarding logging, check how you can use dict to configure logging.


text:
Q: running a simple locust scritp and getting No connection adapters error I am running a very simple Locust script that is using the standard requests module and Python 3.7.7
The error is:
'in get_adapter
raise InvalidSchema("No connection adapters were found for {!r}".format(url))
requests.exceptions.InvalidSchema: No connection adapters were found for '=https://.....'
Not sure where the '=' sign is coming from in the request url?

A: Sorry, found the answer I had mistyped the cmd line for launching locust and had an extra = in there


text:
Q: Swift - Как остановить таймер? Как остановить таймер?
Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { _ in
    if self.progressView.progress != 0 {
        self.progressView.progress -= 0.01
    } else {
        self.present(alertTimeIsOut, animated: true)
        // stop timer ???
    }
}

A: Можно вот так, например:
Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { timer in
    if self.progressView.progress != 0 {
        self.progressView.progress -= 0.01
    } else {
        self.present(alertTimeIsOut, animated: true)
        timer.invalidate()
    }
}


text:
Q: how can I change this condition to that I want I have a condition with two value. if the condition equal to 0 it return Absent and if equal to 1 it returns present.
now I want to add the third value into my condition. if the condition equal to 3 it returns Unacceptable absent.
this is my conditions with two value:
(status >= 1 ? "Present" : "Absent")

how can I change the condition?

A: you could add a failsafe status as "NA" and do it as follows :
status == 0 ? "Absent" : status == 1? "Present" : status == 3? "Unacceptable Absent" : "NA";

A: i recommend something more readable to  @Shubhams approach like this:
string foo(int status)
{
    if (status == 0)
        return ("Present");
    else if (status == 1)
        return ("Absent");
    else if (status == 2)
        return ("Somthing else");
    else
        return ("Outside");
}

A: status >= 1 ?(status >2?"third Value":"Present") : "Absent"

Like that

A: Best approach is to get rid of if else conditions as much as you can and this is how you do that:
public static class AppStartupConfig
{
    public static Dictionary<int,string> AttendanceStatus = new Dictionary<int,string>();

    public static void InitAppStuff(){
        //Bring basic data from database
        //fill the list looping data for e.g:
        if(AttendanceStatus.Count == 0){
           AttendanceStatus.Add(0,"Absent");
           AttendanceStatus.Add(1,"Present");
           AttendanceStatus.Add(3,"Unacceptable absent");
        }
    }
}

and to use it you won't need any if else anymore through out your app, just run this method at the point where your application is started and then just get your value by providing the key to this dictionary like:
    AppStartupConfig.InitAppStuff();
    Console.WriteLine(AppStartupConfig.AttendanceStatus[3]); //returns respective string value

C# fiddle

A: (status == 0 ? "Absent" : status == 1 ? "Present" : status == 3 ? "Unacceptable" : "Unknown status")

You can nest the operators, this way you kind of create a large if & else tree that's, in my opinion, sort of readable. A switch would be more readable.

A: You can use something like this:
status == 0 ? "Absent" : status == 1 ? "Present" : "Unacceptable"

But this code style isn't good readable. Better to use dictionary or switch/case statement etc.

A: Use a lookup dictionary.
//Initialized once in your program
var lookup = new Dictionary<int,string>
{
    { 0, "Absent"},
    { 1, "Present"},
    { 3, "Unacceptably Absent" }
};

//Call this whenever you need to convert a status code to a string
var description = lookup[status];

A: Using nested ternary operators sacrifices readability for brevity. I recommend using the humble switch statement instead:
string foo(int status)
{
    switch (status)
    {
        case 0:
            return "Present";
        case 1:
            return "Absent";
        case 3:
            return "Unacceptable absent";
        default:
            throw new ArgumentOutOfRangeException(nameof(status), $"What kind of person passes {status}?");
    }
}

A: Like that:
status == 0 ? "Absent" : status == 1 ? "present" : status == 3 ? "Unacceptable Absent" : 1==1

I hope to help you.

A: If you have to stick on with Ternary operator, you can modify the code to satisfy three values.
string tmp = (status == 0 ? "Absent" : (status == 1 ? "Present" : "NA"));


text: Q: The back of my laptop is kinda popping off The back isn't cracked or anything just popping off. It only starts to pop off when  I start to close it or adjust it any way that's towards the keyboard/me. I can pop it back in but it doesn't stick. Any advice?


text:
Q: How can I solve the following error in React Native? I'm making an app with react native.But i have a problem.
The problem is as follows.

It is a problem that it returns to the initial state even if a character is entered in the text input.
This is my code.
import React, {useState, Compomen, useEffect} from 'react';
import {SafeAreaProvider} from 'react-native-safe-area-context';
import {View, TextInput, StyleSheet, Text, TouchableOpacity, Image} from 'react-native';
import AsyncStorage from "@react-native-async-storage/async-storage";

function DetailScreen({ navigation, route }) {
  const { day } = route.params;
  const [title,setTitle] = useState("");

  const handleChangeTitle = (text) => {
    setTitle(text)
    _savediary();
  }

  const _readdiary = async () => {
    try {
      const hello = await AsyncStorage.getItem(dateString + "diary");
      if (hello == null) {
        setTitle("Write your day here.")
      }else{
        setTitle(hello);
      }
    } catch(error) {
      console.error(error);
    }
  }
  const _savediary = async () => {
    try {
      await AsyncStorage.setItem(dateString + "diary", title);
    } catch(error) {
      console.error(error);
    }
  }

  var dateString = "";
  for (var key in day) {
   console.log("key:" + key + "/" + day[key])
   dateString = day[key];
  }

  useEffect(() => {
    _readdiary();
  })

  return(
    <SafeAreaProvider>
      <View style={{flexDirection: 'column'}}>
        <View style={{flexDirection: 'row'}}>
          <Text style={styles.date}> {dateString}</Text>
          <TouchableOpacity activeOpacity={0.5} onPress={() => navigation.push('Mood', {day})}>
            <Image
               source={require('./assets/select.png')}
               style={styles.sticker}
            />
          </TouchableOpacity>
        </View>
        <TextInput
            style={{padding: 10}}
            onChangeText={handleChangeTitle}
            editable
            multiline
            value={title}
          />
      </View>
    </SafeAreaProvider>
  );
}

const styles = StyleSheet.create({
  input_container: {
    borderWidth: 0.5,
    padding: 15,
    fontSize: 16,
    marginTop: 20,
    borderRadius: 50,
  },
  date: {
    fontSize: 30,
    width: "75%"
  },
  sticker: {
    height: 50,
    width: 50,
  },
  center: {
    flex: 1,
    alignItems: "center"
},
});

export default DetailScreen;

I think this is a code flow issue, but I don't know how to solve it.
Is it correct that the code flow is causing this problem?
And do you know how to solve this problem?
If you know, please reply.
Thanks.

A: You were wrong with using useEffect hook.
_readdiary function will be calling every time.
There is a second parameter including [] like this:
  useEffect(() => {
    _readdiary();
  }, [])


text:
Q: Accessing global variables with node.js and CoffeeScript I'm trying to declare global variables for my applications that I'm writing using Node.js and CoffeeScript. So I'm declaring it in a common file that is concatenated to both applications after compilation. In that file I have for example:
root = exports ? this
root.myVariable = 300

So my first application is a HTML one. When I try to access this variable, for example by
console.log myVariable

There is no problem with it. But my other application is a server application lauched by node command and I cannot access that variable in that application. I tried:
console.log root.myVariable
console.log myVariable

With first line I'm getting 'undefined' printed (so it looks that root is defined) and with the second one, I'm getting ReferenceError - myVariable is undefined.
So how can I access this variable?
Here is an output code in Javascript that I get, I guess it might be helpful:
(function() {
  var root, _ref;

  root = (_ref = typeof module !== "undefined" && module !== null ? module.exports : void 0) != null ? _ref : this;

  root.myVariable = 300;

}).call(this);

(function() {

  console.log(root.myVariable);

  console.log(myVariable);

}).call(this);

A: You're close, but you need to change things just a little bit
# config.coffee
module.exports =
  foo: "bar"
  hello: "world"
  db:
    user: alice
    pass: password1

# lib/a.coffee
config = require "../config"

# lib/b.coffee
config = require "../config"

# lib/db.coffee
dbconfig = require("../config").db

A: Client and server JavaScript (or CoffeeScript) works differently. So, its a really difficult to write a module that'll work in both applications.
There is a lot of libraries to solve this problem, like RequireJS and Browserify.
But I have two simpler suggestions for your problem.

First one is to use JSON to store your global constants. On the server side you can simply require you JSON file:
root = require './config.json'

On the client side you may either parse it manually or serve it as pjson.

My second suggestion is to write really simple module that'll be compatible with both your applications. It'll look something like this:
root =
  myVariable: 300
  myOtherVariable: 400

modulte.exports = root if module?.parent?

This code should be compatible with both node.js require function and browser <script> tag.
Update:
I just reread you question and realized, that you've did almost as I suggested. But your code looks fine to me. You may try to use module.export instead of its alias exports, it may help:
root = modulte?.exports ? this
root.myVariable = 300

But, as I said, your code looks fine to me as well.


text:
Q: Proof that derivative operator cannot be written in terms of composition operator (without limits) Difference delta operator can be written without a limit:
$$\Delta[f(x)]=f(x+1)-f(x)$$
The same is true for any other finite difference operator. But what about derivative? Is there a proof that it cannot be expressed similarly without a limit?
Note that I know that derivative can be expressed without a limit if reals are extended to hyperreals, for instance, and with other extensions. But I am interested with standard reals.


text:
Q: Is it necessary to "escape" character "<" and ">" for javascript string? Sometimes, server side will generate strings to be embedded in inline JavaScript code. For example, if "UserName" should be generated by ASP.NET. Then it looks like.
<script>
   var username = "<%UserName%>";
</script>

This is not safe, because a user can have his/her name to be
</script><script>alert('bug')</script></script>
It is XSS vulnerability.
So, basically, the code should be:
<script>
   var username = "<% JavascriptEncode(UserName)%>";
</script>

What JavascriptEncode does is to add charater "\" before "/" and "'" and """. So, the output html is like.

       var username = "</script>alert(\'bug\')</script></script>";

Browser will not interpret "</script>" as end of script block. So, XSS in avoided.
However, there are still "<" and ">" there. It is suggested to escape these two characters as well. First of all, I don't believe it is a good idea to change "<" to "<" and ">" to ">" here. And, I'm not sure changing "<" to "\<" and ">" to "\>" is recognizable to all browsers. It seems it is not necessary to do further encoding for "<" and ">".
Is there any suggestion on this?
Thanks.

A: The cheap and easy way:
<script type="text/javascript">
    var username = "<%= Encode(UserName) %>";
</script>

where the encoding scheme in Encode is to translate each character of input into the associated \xABCD representation compatible with JavaScript.
Another cheap and easy way:
<script type="text/javascript">
    var username = decodeBase64("<%= EncodeBase64(UserName) %>");
</script>

if you are dealing only with ASCII.
Of course, pst hit the nail on the head with the strict way of doing it.

A: The problem has different answers depending on what markup language you are using.
If you are using HTML, then you must not represent them with entities as script elements are marked as containing CDATA.
If you are using XHTML, then you may represent them as CDATA with explicit CDATA markers, or you may represent them with entities.
If you are using XHTML, but serving it as text/html, then you need to write something which conforms to the rules of XHTML but still works with a text/html parser. This generally means using explicit CDATA markers and commenting them out in JavaScript.
<script type="text/javascript">
// <![CDATA[
  …
// ]]>
</script>

A while ago, I wrote a bit about the hows and whys of this.

A: No, you should not escape < and > using HTML entities inside <script> in HTML.

*

*Use JavaScript string escaping rules (replace \ with \\ and " with \")

*and replace all occurances of </ with <\/, to prevent escaping out of the <script> element.

In XHTML it's more complicated.

*

*If you send XHTML as XML (the way that's incompatible with IE) and don't use CDATA block, then you need to escape entities, in addition to JavaScript string escaping.

*If you send XHTML as XML and use CDATA block, then don't escape entities, but replace ]]> with ]]]]><![CDATA[> to prevent escaping out of it (in addition to JavaScript string escaping).

*If you send XHTML as text/html (what 99% of people does) then you have to use XML CDATA block, XML CDATA escaping and HTML escaping all at once.


text:
Q: Canvas background color not as white as I need I am setting the background color of my Canvas as 'white'. However when I compare my canvas with a vendor application, their canvas is 'whiter', which is the color I want for my canvas too. I have looked at all the color choices available for canvas background color but nothing makes my canvas any whiter than it is. Any suggestions would be appreciated.

A: Simple solution:
Use one of the browser plugins to get the actual "white" color of their app.
One example of a color-picker is Chrome plus the ColorZilla extension:
https://chrome.google.com/webstore/detail/colorzilla/bhlhnicpbhignbdhedgjhgdocnmhomnp


text:
Q: How to find the angle in between two triangles when one of them is the double of the other? The problem is as follows:

Using the figure from below find $x$

The problem is as follows:
$\begin{array}{ll}
1.&60^{\circ}\\
2.&40^{\circ}\\
3.&60^{\circ}\\
4.&70^{\circ}\\
5.&30^{\circ}\\
\end{array}$
This peculiar problem is confusing to me, what sort of identity can be used to solve this?. The only thing which I could spot there was:
$\beta+2x+\theta=180$
But that's it. I don't know what other relation can be established from the given information. Can someone help me here?. Please include a drawing in your answer as it becomes difficult for me to read from only algebraic expressions. Please be the most descriptive as possible and it would help me a lot to have a step-by-step solution as I am struggling with this figure.

A:
Note that we have $2x+\beta + \theta = \pi$. Notice that $\angle BDF+\angle CEG = \pi - \angle DAE = \pi - x$. Notice that the sum of the angles of $\triangle BDF$ and $\triangle CEG$ is $2\pi$: $2(\beta+\theta)+\gamma+\phi+\pi-x=2\pi$. Note that the sum of the angles of $\triangle AFG$ is $\pi$, so $2\pi-2(\gamma + \phi)+x=\pi$ Using these 3 equations we derived:
$$ $2(\beta+\theta)+\gamma+\phi+\pi-x=2\pi$$
$$2x+\beta + \theta = \pi$$
$$2\pi-2(\gamma + \phi)+x=\pi$$
We can find $x=\frac{\pi}{3}$. (Substitute $y=\beta+\theta,z=\gamma+\phi$, you have three equations and three variables)


text:
Q: Proving that certain subset of the Grassmannian is open in the Zariski topology. Let $\mathbb{G}(k,n)$ be the Grassmannian of $k$-planes in $\mathbb{P}^{n}$, and let $X\subseteq\mathbb{P}^{n}$ be an irreducible algebraic variety.
Fix a positive integer $m$. We define
$$
r=\mathrm{max}\{\mathrm{dim}\langle p_{1},\ldots,p_{m}\rangle:p_{1},\ldots,p_{m}\in X\}.
$$
I want to prove that
$$
S=\{\langle p_{1},\ldots,p_{m}\rangle:p_{1},\ldots,p_{m}\in X, \mathrm{dim}\langle p_{1},\ldots,p_{m}\rangle=r\}\subseteq\mathbb{G}(r,n)
$$
is an open subset of the Grassmannian $\mathbb{G}(r,n)$.
I have tried to find equations for $\mathbb{G}(r,n)-S$ taking into account that  $\mathbb{G}(r,n)$ is identified with an algebraic variety  via de Plücker embedding, but I have not been able. Any help would be appreciated.

A: Hint: $\dim\left<p_1,\dots,p_r\right>$ is the same as the rank of the matrix whose rows are $p_1,\dots,p_m$.  Now use the fact that a matrix has rank $<s$ if and only if all $s\times s$ minors vanish.

A: The intersction of all linear subspaces  $W\subset \mathbb P^n$ containing $X$ ( i.e. $W\supset X$) is a linear  subspace $V\subset \mathbb P^n$, whose dimension we call $r$.
For any integer $m$ and any choice of points $p_1,\cdots,p_m\in X$ we have $$\langle p,\cdots,p_m \rangle \subset V \quad (\bigstar)$$ and for at least one integer $M$ and one choice of points $q_1,\cdots,q_M\in X$ we have $$\langle q_1,\cdots,q_M \rangle = V \quad (\bigstar \bigstar)$$ There is only one linear subspace of $\mathbb P^n$  satisfying both $(\bigstar)$   and  $(\bigstar \bigstar)$ : that subspace is $V$ .
The corresponding point              $ [V]\in\mathbb G(r, \mathbb P^n)$ is a closed point of  $\mathbb G(r, \mathbb P^n)$ and   certainly not an open subset of that grassmannian.


text:
Q: Definition of an angle in a vector space, law of sines On a lecture in linear algebra we have been given this definition of an angle in vector space with scalar product $\langle , \rangle$:
$\cos \alpha=\frac{\langle u,v\rangle}{||u|||v||}$
Throughout the internet I found the same definition using $\cos$. And I was wondering, whether we can somehow define the angle in vector space by using sinus and scalar product.
How is it then defined? And why is it usually defined by cosinus? Thanks for answers
ADDED
I am asking because I have this task: Formulate and prove law of sines for vector space. I am kind of lost, so thanks for help

A: Scalar product defines orthogonality between two vectors: two vectors are orthogonal if the angle formed between them is $\frac{\pi}{2}$. Then if they are orthogonal and you calculate $\vec{v}\cdot\vec{w}$ you get zero.
If you define the product with the sine, you lose this property, so "orthogonal" in the scalar product sense means the vectors would be parallel.

A: The dot product, or scalar product (or sometimes inner product in the context of Euclidean space) between two Euclidean vectors u and v is defined as:
∙ = ‖‖‖‖cos , where  is the angle between  and      (1)
(see Wikipedia: dot product)
The scalar projection (orthogonal projection) of  on  is given by:
vu = ‖‖cos     (2)
The unit vector in the direction of  is given by:
$\hat{}$ = $\frac{}{‖‖}$    (3)
The vector of length vu in the direction of  is then:
 = vu $\hat{}$    (4)
We now have 2 legs ( and v). The third side h is chosen such that
 =  + h    (5)
Thus,
h =  -     (6)
We now have a right triangle formed by the vectors v,  and h; where v is the hypotenuse and the angle between  and h is 90 degrees.
By definition:
sin  = $\frac{‖\boldsymbol{h}‖}{‖‖}$    (7)
Using the trigonometric identity
tan  = $\frac{\text{sin}\  }{\text{cos}\ }$ = $\frac{‖\boldsymbol{h}‖}{‖_‖}$    (8)
the sine of the angle between u and v may then be expressed in terms of the dot product as
sin $\theta$ = $\frac{‖\boldsymbol{h}‖}{‖_‖}$ cos $\theta$ = $\frac{‖ - _‖}{‖_‖}$ $\frac{\cdot}{‖‖‖‖}$    (9)
Rearranging (7):
‖‖ = $\frac{‖\boldsymbol{h}‖}{\text{sin}\ }$    (10)
Similarly, for the other sides and angles:
‖‖ = $\frac{‖‖}{\text{sin}(\pi/2)}$    (11)
since  is the orthogonal projection of v on u, then the angle between h and  is 90 degrees
‖‖ = $\frac{‖_‖}{\text{sin}\ \alpha}$    (12)
where $\alpha$ is the angle between v and h
Equating the hypotenuse for all the sides gives the law of sines:
$\frac{‖\boldsymbol{h}‖}{\text{sin}\ }$ = $\frac{‖‖}{\text{sin}(\pi/2)}$ = $\frac{‖_‖}{\text{sin}\ \alpha}$    (13)


text:
Q: What's the most efficient way to recast a float pointer as a double pointer in C? I'm working with DSP in code that's a mashup of objective C++ and C.
The CoreAudio framework is providing me buffers of audio sample data as float pointers
e.g. float *bufferData = (float *)malloc(sizeof(float) * 1024);
The C function that I'm calling to do processing on the sample data requires a pointer of type double.
double returnAValue(double *sampleData, int samplecount);

What's the most CPU efficient way of converting my float pointer into a double pointer before passing it to this function?

A: One of the many functions that the Accelerate framework provides is vDSP_vspdp, which you can use like this:
float * singleBuf;
float * doubleBuf = malloc(nElements * sizeof(double));
vDSP_vspdp(singleBuf, 1, doubleBuf, 1, nElements);

If you're doing any kind of DSP programming on a Mac, you could save tons of time and gain tons of efficiency by learning about vDSP, CBLAS, and other Accelerate framework APIs. These APIs tend to go through the processor's vector unit (SSE, etc) and know about memory hinting, so they tend to be much more efficient than what you'd typically code by hand.

A: Changing the type of the pointer does not change the type of the underlying data.   If you are trying to link together two packages that expect different contents in the buffers, you are going to have to copy the data from one buffer to another, converting on the way.
So your question is: given a buffer full of floats, how do you convert it to a buffer full of doubles?   A simple for loop is probably your best bet.


text:
Q: Copy file from jar and write to a file without storing in memory I have a file in the jar file that I need to copy and store that file in a directory. What java api can I use to read/write file at the same time without having to cache it in memory first?
I know how to individually copy a file from jar and then write to a file but its caching it in memory first.
The below answer looks like is not caching in memory but I want to know the difference between caching vs non-caching in memory?
How to copy files out of the currently running jar

A: Here is a short example for copying a file with in memory caching:
    try {
        Path source = Paths.get(getClass().getClassLoader().getResource("resource").toURI());
        Path target = Paths.get("targetfile");

        // copy with in memory caching
        // read all bytes to memory
        byte[] data = Files.readAllBytes(source);
        // write bytes from memory to target file
        Files.write(target, data);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }

And the same example without in memory caching:
    try {
        Path source = Paths.get(getClass().getClassLoader().getResource("resource").toURI());
        Path target = Paths.get("targetfile");

        // copy without in memory caching
        Files.copy(source, target);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }

The important difference is, that in the first case, the complete contents of the file is read to a byte array, which is stored in memory. Depending on the size of the file, this can be really bad. In the second case, the copying operation knows the source and the target and is therefore able to copy the file in small parts until the file is copied completely. For example, one can always copy 2048 bytes at a time, like in the accepted answer to the linked question.


text:
Q: FBX animations not running properly with three js I am having an issue with animations on some fbx models. If I have, for example an animation that lasts 20 secs, the model will stay still for 19 secs and then all changes will happen within the last second or so. On other fbx models the animation runs correctly.
The code that I am using to run the animation is a follows:
The loader.load callback is:
var clock = new THREE.Clock();
var mixers = [];

function(object){
        object.position.set(0,0,0);
        object.mixer = new THREE.AnimationMixer(object);
        mixers.push(object.mixer);
        console.log(object);
        for (var a = 0; a < object.animations.length; a++){
            var action = object.mixer.clipAction(object.animations[a]);
            action.play();
            console.log(action);
        }

        scene.add(object);
        animate();
    }

And the animate code is:
function animate() {
    requestAnimationFrame(animate);
    for(var i = 0; i < mixers.length; i++){
        mixers[i].update(clock.getDelta());
    }
    render();
    stats.update();
}

function render() {
    if (mixer) {
        mixer.update(clock.getDelta());
    }
    renderer.render(scene, camera);
}

Any ideas? Thanks!

A: From experience, I can tell you that the fbx ascii export process (at least for Autodesk Maya) doesn't always give either

*

*the correct start and end times set in Maya or

*gives a set of numbers that threejs doesn't import properly.

What you end up getting is -- as you describe -- a lot of time in the animation where nothing happens.  As far as I've seen, it's usually trailing at the end, but it could certainly be at the beginning as well.
You could fix the fbx file manually, but it might be easier just add a function to set the beginning time to the time of your first frame (and if the first frame is the issue, start with the second frame).
I have the code for this somewhere, let me find it and then I'll add it to this answer.


text:
Q: Defining two o more functions in karate-config.js My karate-config.js is:
function config(){
    return karate.read('classpath:' + env_file());
}

function env_file(){
    var env_file = karate.env;
    if(!env_file){
        env_file = 'local.yml';
    }
    return 'env/' + env_file;
}

That was working fine until I upgraded my Java version to 17.
Now I'm getting the following exception:
org.graalvm.polyglot.PolyglotException: SyntaxError: Unnamed:5:0 Expected ) but found function

Is it possible now to define two functions in the same file?
Thanks in advance.

A: No. It was never supposed to have been supported, I'm surprised it worked.
Also refer: https://github.com/karatelabs/karate#multiple-functions-in-one-file


text:
Q: WSS from JavaScript to plain Java I am trying to create a websocket connection from JavaScript code to a Java server. I have managed to do this with a unsecure ws connection, but because the website that I want to use this code on is a secure https side, I have to use a secure websocket.
I have spend quite some time on research trying to get this to work, however I can't figure out how to get them connected. I have absolutely no experience with stuff like keystores or ciphers, but I don't need that security, I don't want to send any sensitive data.
Anyways, here is what I've tried:
SLLServerSocket server = (SSLServerSocket) SSLServerSocketFactory
        .getDefault().createServerSocket(1234);
SSLSocket client = (SSLSocket) server.accept();

with corresponding JavaScript code:
var socket = new WebSocket("wss://localhost:1234")
socket.onopen = () => console.log("Connected");
socket.onmessage = m => console.log("Message received:", m);

Running this resulted in a Caused by: javax.net.ssl.SSLHandshakeException: No available authentication scheme which I managed to fix by adding
System.setProperty("jdk.tls.server.protocols", "TLSv1.2");

Now I am getting the exception javax.net.ssl.SSLHandshakeException: no cipher suites in common. I've done some research on that as well but whatever I find seems assume that a keystore or something is already there, which it is not for me. In fact I don't really know what encryption it should use, I did not find anything about that
To be fair, part of the problem may very well be that I don't know what to actually search for, but that is why I am asking. There are already articles about these exceptions I am showing, I know them, and they didn't help.


text:
Q: Characteristic Polynomial Calculation I have a problem in my homework in which I have to find the characteristic polynomial of the following matrix:

I know the final solution is:

However, my answer keeps getting wrong whenever I calculate with the following way:
I know that I have to find the determinant of: (λI-A), but I decided to use some Gauss methods to simplify the matrix, so I won't get a x^3 in my final polynomial.
Therefore, I did the following actions:

Please help me get what I did wrong, and this would be a great help for me.
Thank you,
Alan


text:
Q: Get custom attribute in final price method I would like to add a custom attribute (bum) in the final_price.phtml file.
I put this code:

It doesn't work, nothing appears. Can you help me please?
When I tried, <?php echo $_product->getBum(); I have this error message :

Fatal error: Call to a member function getBum() on null in /home/magento/www/app/design/frontend/Smartwave/porto/Magento_Catalog/templates/product/price/final_price.phtml on line 33
Thanks,

A: If it is product custom attribute, you can try
echo $_product->getBum();


text:
Q: How to customize Google Play service notifications I'm using Google Play services to make a turn-based game. When a user invites friends or takes a turn while playing, Google will send a notification, but it can't directly open my game (instead, it will open the Google Play services app).
Can I modify that notification?
Can I use Parse to push my own notifications instead of using Google's default notification?
Thank you very much!

A: Your notification has to be handle in app side.
In notification you are sending some data may be in form of json,you have to parse data and using NotificationManager you can customise your operation i.e. open the app or open google play service.


text:
Q: deleting object keys which start with a vowel js I need to remove all keys, which start with the vowel from an object but I can't figure out how to do it. This is what I have so far. In this example only the 'chip' key should stay and all the others should be removed. Can you guys help me with this?
'use strict'

function removeVowelKeys(object) {
  for (let key in object) {
    if (key[0] === 'a' || key[0] === 'A' || key[0] === 'u' || key[0] === 'U' ||
    key[0] === 'i' || key[0] === 'I' || key[0] === 'o' || key[0] === 'O' ||
    key[0] === 'e' || key[0] === 'E' || key[0] === 'y' || key[0] === 'Y' ) {
      delete object.key
  }
}
}

console.log(removeVowelKeys({
  alarm: 'This is SPARTA!!!',
  chip: 100,
  isValid: false,
  Advice: 'Learn it hard',
  onClick: 'make it great again',
}));

A: You need to return your object from your function, but also you shouldn't delete keys from the object as you're looping over it.
Something like this will do it:

const removeVowelKeys = (obj) =>
  Object.fromEntries(
    Object.entries(obj).filter(
      ([k]) => !["a", "e", "i", "o", "u"].includes(k.toLowerCase()[0])
     )
  );

console.log(removeVowelKeys({
  alarm: 'This is SPARTA!!!',
  chip: 100,
  isValid: false,
  Advice: 'Learn it hard',
  onClick: 'make it great again',
}));

I also fixed up your original method to copy the object before iterating over it and also using [square bracket] notation to use your keys correctly:
function removeVowelKeys(obj) {
  for (let key in { ...obj }) {
    if (
      key[0] === "a" ||
      key[0] === "A" ||
      key[0] === "u" ||
      key[0] === "U" ||
      key[0] === "i" ||
      key[0] === "I" ||
      key[0] === "o" ||
      key[0] === "O" ||
      key[0] === "e" ||
      key[0] === "E" ||
      key[0] === "y" ||
      key[0] === "Y"
    ) {
      delete obj[key];
    }
  }
  return obj;
}

A: Here's how I went about it.
Make sure that you actually return something from your function...
Also note that y is not technically a vowel.

function removeVowelKeys(obj) {
    let output = {};
    for (let key in obj) {
        if (!(['a', 'e', 'i', 'o', 'u'].includes(key[0].toLowerCase()))) output[key] = obj[key];
    }
    return output;
}


text:
Q: VS 2010 Shortcut for debugging a specific project I have a solution with a dozen projects.
I use Ctrl+F9 to launch a specific project, however I have to select manually the desired project each time. I would be happy if I could assign a specific shortcut to debug each project.
I use AutoHotKey for global shortcuts to launch project applications outside of VS but for debugging I have no idea on how to achieve this.


text:
Q: Unable to set contentType when uploading Azure Blob via REST API I have the below code which successfully uploads an image to my Azure Blob storage container. However, by default it sets the ContentType of the stored file to application/octet-stream I would like to change this to image/jpg.
To do that I wrote the lines which are in comments below. They set the required content-type headers as far as I understand them from the Azure documentation, however the request now results in a 403 Unauthorized response instead of a 200.
private static void PutBlob(string filenameToSave)
{
    var requestMethod = "PUT";
    var urlPath = _storageContainer + "/" + filenameToSave;
    var storageServiceVersion = "2015-12-11";
    var date = DateTime.UtcNow.ToString("R", CultureInfo.InvariantCulture);
    var blobType = "BlockBlob";
    var imageBytes = GetImageBytes();
    var canonicalizedResource = "/" + _storageAccount + "/" + urlPath;

    // DOESN'T WORK:
    var canonicalizedHeaders = "x-ms-blob-type:" + blobType + "\nx-ms-blob-content-type:image/jpeg\nx-ms-date:" + date + "\nx-ms-version:" + storageServiceVersion;
    // WORKS:
    //var canonicalizedHeaders = "x-ms-blob-type:" + blobType + "\nx-ms-date:" + date + "\nx-ms-version:" + storageServiceVersion;

    // DOESN'T WORK:
    string stringToSign = requestMethod + "\nimage/jpeg\n\n" + imageBytes.Length + "\n\n\n\n\n\n\n\n\n" + canonicalizedHeaders + "\n" + canonicalizedResource;
    // WORKS:
    //string stringToSign = requestMethod + "\n\n\n" + imageBytes.Length + "\n\n\n\n\n\n\n\n\n" + canonicalizedHeaders + "\n" + canonicalizedResource;

    string authorizationHeader = GenerateSharedKey(stringToSign, _storageKey, _storageAccount);

    var uri = $"https://{_storageAccount}.blob.core.windows.net/{urlPath}";
    var request = (HttpWebRequest)WebRequest.Create(uri);
    request.Method = requestMethod;
    request.ContentType = "image/jpeg"; // DOESN'T WORK

    request.Headers.Add("x-ms-blob-content-type", "image/jpeg"); // DOESN'T WORK
    request.Headers.Add("x-ms-blob-type", blobType);
    request.Headers.Add("x-ms-date", date);
    request.Headers.Add("x-ms-version", storageServiceVersion);
    request.Headers.Add("Authorization", authorizationHeader);

    var stream = request.GetRequestStream();
    stream.Write(imageBytes, 0, imageBytes.Length);

    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    {
        // check the response status here, 200/201 means it worked

        Console.WriteLine("File uploaded");
    }
}

private static string GenerateSharedKey(string stringToSign, string key, string account)
{
    string signature;
    var unicodeKey = Convert.FromBase64String(key);
    using (var hmacSha256 = new HMACSHA256(unicodeKey))
    {
        var dataToHmac = Encoding.UTF8.GetBytes(stringToSign);
        signature = Convert.ToBase64String(hmacSha256.ComputeHash(dataToHmac));
    }
    return string.Format(CultureInfo.InvariantCulture, "{0} {1}:{2}", "SharedKey", account, signature);
}

I can see that the issue is with the generated authorizationHeader, but I cannot see why as I have followed the guide. Can anyone help me shed some light on this.
Also note that I have to do this through the REST API and not the Microsoft.WindowsAzure.Storage library (annoyingly, as I know it's a fraction of the code when done in that way).
Thanks.

A: I discovered one issue in your code:
// DOESN'T WORK:
    string stringToSign = requestMethod + "\nimage/jpeg\n\n" + imageBytes.Length + "\n\n\n\n\n\n\n\n\n" + canonicalizedHeaders + "\n" + canonicalizedResource;

Essentially ContentType should not be the 2nd parameter. 2nd parameter is Content-Encoding based on the documentation
StringToSign = VERB + "\n" +
               Content-Encoding + "\n" +
               Content-Language + "\n" +
               Content-Length + "\n" +
               Content-MD5 + "\n" +
               Content-Type + "\n" +
               Date + "\n" +
               If-Modified-Since + "\n" +
               If-Match + "\n" +
               If-None-Match + "\n" +
               If-Unmodified-Since + "\n" +
               Range + "\n" +
               CanonicalizedHeaders +
               CanonicalizedResource;

So once you change this, your code should work:
        string stringToSign = requestMethod + "\n" +
            "\n" + //Content Encoding
            "\n" + //Content Language
            imageBytes.Length + "\n" + //Content Length
            "\n" + //Content MD5
            "image/jpeg" + "\n" + //Content Type
            "\n" + //Date
            "\n" + //If - Modified - Since
            "\n" + //If - Match
            "\n" + //If - None - Match
            "\n" + //If - Unmodified - Since
            "\n" + //Range +
           canonicalizedHeaders + "\n" +
           canonicalizedResource;

Also, you don't need to specify both Content-Type and x-ms-blob-content-type. If you define x-ms-blob-content-type, then it should be included in canonicalizedHeaders.
Here's the code I used to test this:
    private static void PutBlob(string filenameToSave)
    {
        var requestMethod = "PUT";
        var urlPath = "<container-name>" + "/" + filenameToSave;
        var storageServiceVersion = "2015-12-11";
        var date = DateTime.UtcNow.ToString("R", CultureInfo.InvariantCulture);
        var blobType = "BlockBlob";
        var imageBytes = File.ReadAllBytes(@"File Path");
        var canonicalizedResource = "/" + accountName + "/" + urlPath;

        // DOESN'T WORK:
        //var canonicalizedHeaders = "x-ms-blob-type:" + blobType + "\nx-ms-blob-content-type:image/jpeg\nx-ms-date:" + date + "\nx-ms-version:" + storageServiceVersion;
        // WORKS:
        var canonicalizedHeaders = "x-ms-blob-type:" + blobType + "\nx-ms-date:" + date + "\nx-ms-version:" + storageServiceVersion + "\n";

        // DOESN'T WORK:
        //string stringToSign = requestMethod + "\nimage/jpeg\n\n" + imageBytes.Length + "\n\n\n\n\n\n\n\n\n" + canonicalizedHeaders + "\n" + canonicalizedResource;
        // WORKS:
        //string stringToSign = requestMethod + "\n\n\n" + imageBytes.Length + "\n\n\n\n\n\n\n\n\n" + canonicalizedHeaders + "\n" + canonicalizedResource;
        string stringToSign = requestMethod + "\n" +
            "\n" + //Content Encoding
            "\n" + //Content Language
            imageBytes.Length + "\n" + //Content Length
            "\n" + //Content MD5
            "image/jpeg" + "\n" + //Content Type
            "\n" + //Date
            "\n" + //If - Modified - Since
            "\n" + //If - Match
            "\n" + //If - None - Match
            "\n" + //If - Unmodified - Since
            "\n" + //Range +
           canonicalizedHeaders +
           canonicalizedResource;
        string authorizationHeader = GenerateSharedKey(stringToSign, accountKey, accountName);

        var uri = "https://" + accountName + ".blob.core.windows.net/" + urlPath;

        var request = (HttpWebRequest)WebRequest.Create(uri);
        request.Method = requestMethod;
        request.ContentType = "image/jpeg"; // DOESN'T WORK

        //request.Headers.Add("x-ms-blob-content-type", "image/jpeg"); // DOESN'T WORK
        request.Headers.Add("x-ms-blob-type", blobType);
        request.Headers.Add("x-ms-date", date);
        request.Headers.Add("x-ms-version", storageServiceVersion);
        request.Headers.Add("Authorization", authorizationHeader);

        var stream = request.GetRequestStream();
        stream.Write(imageBytes, 0, imageBytes.Length);

        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
            // check the response status here, 200/201 means it worked

            Console.WriteLine("File uploaded");
        }
    }


text:
Q: How to speed boot up Debian 10? My system boots up in approximately 1 - 1.5 minutes.
I was not able to find any way to speed the boot up.
Is there any method to do this?
Addition:
Allright, i got it, i guess.
These are the inputs.
systemd-analyze:
Startup finished in 10.355s (kernel) + 1min 2.918s (userspace) = 1min 13.274s
graphical.target reached after 1min 2.902s in userspace

systemd-analyze blame:
 33.715s plymouth-quit-wait.service
 21.690s ifupdown-pre.service
 18.122s NetworkManager-wait-online.service
 17.457s ModemManager.service
 16.895s snapd.service
 15.682s udisks2.service
 12.983s NetworkManager.service
 12.470s accounts-daemon.service
 11.650s dev-sda1.device
  9.820s apparmor.service
  9.391s dev-loop0.device
  8.665s vboxdrv.service
  8.664s rsyslog.service
  8.608s wpa_supplicant.service
  8.601s switcheroo-control.service
  8.597s avahi-daemon.service
  8.597s bluetooth.service
  8.594s systemd-logind.service
  8.411s dev-loop1.device
  8.075s alsa-restore.service
  4.585s networking.service
  4.467s snapd.seeded.service
  3.368s polkit.service
  1.967s exim4.service
  1.917s systemd-udevd.service
  1.713s gdm.service
  1.613s systemd-backlight@backlight:radeon_bl0.service
  1.266s upower.service
  1.138s keyboard-setup.service
   838ms systemd-tmpfiles-setup.service
   738ms systemd-udev-trigger.service
   734ms colord.service
   713ms dev-mqueue.mount

Which service(s) should i deactivate?
And when i try to use systemctl critical-chain command, i got this input:
Unknown operation critical-chain.


text:
Q: Archived web content without going to the website I want to fetch web data without going to the actual website.
http://archive.org/web/web.php is an example which keeps the snapshots of websites. Problem with this is that data is quite old (5-6 months).
Do we have any other archive storage where recent html content can be found?
Thanks

A: Do you want to curl the website?
you can use php to cURL some web page:
 http://php.net/manual/en/book.curl.php
or you can use command, wget or curl, in Unix:
 http://linux.about.com/od/commands/l/blcmdl1_curl.htm


text:
Q: Python Nested Try/Except/Else for Control Flow What I'd like to achieve in the most elegant Python way:
Try to find an object in the database on a certain filter. Only if there is no result, then try to find the object using another filter. If that returns no result, then the object does not exist, so insert a new instance.
What I'm thinking:
try:
    obj = session.query(model).filter_by(field_a).one()
except NoObjFound:
    try:
        obj = session.query(model).filter_by(field_b).one()
    except NoObjFound:
        insert_into_db(brand_new_obj)
else:
    update_the_obj(obj)

I'm not sure if this block is correct or the best way to handle what I'm trying to accomplish.

A: I would suggest something like:
for filter in (field_a, field_b):
    try:
        obj = session.query(model).filter_by(filter).one()
    except NoObjFound:
        pass # or 'continue'
    else:
        update_the_obj(obj)
        break
else:
    insert_into_db(brand_new_obj)

This will ensure that the correct things happen in the correct order, is more readable than nested try blocks and can easily be extended to add more filters.

A: This is incorrect. Assuming you want to update_the_obj(obj) after finding the object independent of which filter found it, the else clause at the end is hidden to the inner filter.
You can try:
obj = None
try:
    obj = session.query(model).filter_by(field_a).one()
except NoObjFound:
    try:
        obj = session.query(model).filter_by(field_b).one()
    except NoObjFound:
        insert_into_db(brand_new_obj)

if obj is not None:
    update_the_obj(obj)


text:
Q: Cakephp 3 - Image Upload - mimeType - Cannot validate mimetype for a missing file i think this is a bug within Cakephp 3 but i wanted to double check first.
Cakephp 3.2.3 - Windows 7 with XAMPP 3.2.2
View: file.ctp
 <div>
 <?= $this->Form->create($client, ['type' => 'file']) ?>
 <?= $this->Form->input('logo', ['type' => 'file']); ?>
 <?= $this->Form->button(__('Submit')) ?>
 <?= $this->Form->end() ?>
 </div>

Controller: ClientsController.php
public function file() {
    $client = $this->Clients->newEntity();

    if ($this->request->is('post') ) {
        $client = $this->Clients->patchEntity($client, $this->request->data);
        if (!is_null($client->logo)
            && !empty($this->request->data)
            && !empty($this->request->data['logo'])
            && !empty($this->request->data['logo']['name']))
            $client->logo = $this->request->data['logo'];

        $client->name = 'TEST';

        if ($this->Clients->save($client)) {
            $this->Flash->success(__('The client has been saved.'));
            return $this->redirect(['action' => 'file']);
        } else {
            $this->Flash->error(__('The client could not be saved. Please, try again.'));
        }
    }
    $this->set(compact('client'));
    $this->set('_serialize', ['client']);
}

Model: ClientsTable.php
public function validationDefault(Validator $validator)
{
    $validator
        ->add('logo', [
            'uploadError' => [
                'rule' => 'uploadError',
                'message' => __d('clients', 'The logo upload failed.')
            ],
            'mimeType' => [
                'rule' => array('mimeType', array('image/gif', 'image/png', 'image/jpg', 'image/jpeg')),
                'message' => __d('clients', 'Please upload images only (gif, png, jpg).')
            ],
            'fileSize' => [
                'rule' => array('fileSize', '<=', '1MB'),
                'message' => __d('clients', 'Logo image must be less than 1MB.')
            ],
        ])
        ->allowEmpty('logo');
  }

This is a simple ImageUpload-Test script which i tried over the last days.
The mimeType validation causes an exception if the filesize is above the upload boundaries. I don't mean the fileSize validation amount. I mean the value which is mentioned within PHP.ini (in my case upload_max_filesize=2M).
If i upload a file which is bigger than 2MB, i get this exception
2016-02-25 18:33:56 Error: [RuntimeException] Cannot validate mimetype for a missing file
Request URL: /pam/clients/file
Referer URL: http://localhost/pam/clients/file
Stack Trace:
#0 [internal function]: Cake\Validation\Validation::mimeType(Array, Array)
#1 C:\Users\D052192\OneDrive\xampp\htdocs\pam\vendor\cakephp\cakephp\src\Validation\RulesProvider.php(71): ReflectionMethod->invokeArgs(NULL, Array)
#2 [internal function]: Cake\Validation\RulesProvider->__call('mimeType', Array)
#3 [internal function]: Cake\Validation\RulesProvider->mimeType(Array, Array, Array)
#4 C:\Users\D052192\OneDrive\xampp\htdocs\pam\vendor\cakephp\cakephp\src\Validation\ValidationRule.php(138): call_user_func_array(Array, Array)
#5 C:\Users\D052192\OneDrive\xampp\htdocs\pam\vendor\cakephp\cakephp\src\Validation\Validator.php(1410): Cake\Validation\ValidationRule->process(Array, Array, Array)
#6 C:\Users\D052192\OneDrive\xampp\htdocs\pam\vendor\cakephp\cakephp\src\Validation\Validator.php(137): Cake\Validation\Validator->_processRules('logo', Object(Cake\Validation\ValidationSet), Array, true)
#7 C:\Users\D052192\OneDrive\xampp\htdocs\pam\vendor\cakephp\cakephp\src\ORM\Marshaller.php(193): Cake\Validation\Validator->errors(Array, true)
#8 C:\Users\D052192\OneDrive\xampp\htdocs\pam\vendor\cakephp\cakephp\src\ORM\Marshaller.php(466): Cake\ORM\Marshaller->_validate(Array, Array, true)
#9 C:\Users\D052192\OneDrive\xampp\htdocs\pam\vendor\cakephp\cakephp\src\ORM\Table.php(2073): Cake\ORM\Marshaller->merge(Object(App\Model\Entity\Client), Array, Array)
#10 C:\Users\D052192\OneDrive\xampp\htdocs\pam\src\Controller\ClientsController.php(102): Cake\ORM\Table->patchEntity(Object(App\Model\Entity\Client), Array)
#11 [internal function]: App\Controller\ClientsController->file()
#12 C:\Users\D052192\OneDrive\xampp\htdocs\pam\vendor\friendsofcake\crud\src\Controller\ControllerTrait.php(51): call_user_func_array(Array, Array)
#13 C:\Users\D052192\OneDrive\xampp\htdocs\pam\vendor\cakephp\cakephp\src\Routing\Dispatcher.php(114): App\Controller\AppController->invokeAction()
#14 C:\Users\D052192\OneDrive\xampp\htdocs\pam\vendor\cakephp\cakephp\src\Routing\Dispatcher.php(87): Cake\Routing\Dispatcher->_invoke(Object(App\Controller\ClientsController))
#15 C:\Users\D052192\OneDrive\xampp\htdocs\pam\webroot\index.php(37): Cake\Routing\Dispatcher->dispatch(Object(Cake\Network\Request), Object(Cake\Network\Response))
#16 {main}

the value within $this->request->data is:
Array
(
    [logo] => Array
        (
            [name] => Image6MB.jpg
            [type] =>
            [tmp_name] =>
            [error] => 1
            [size] => 0
        )
 )

This case always throws the exception if mimeType check is within the validation variable.
public static function mimeType($check, $mimeTypes = [])
{
    if (is_array($check) && isset($check['tmp_name'])) {
        $check = $check['tmp_name'];
    }

    if (!function_exists('finfo_open')) {
        throw new LogicException('ext/fileinfo is required for validating file mime types');
    }

   if (!is_file($check)) {
        throw new RuntimeException('Cannot validate mimetype for a missing file');
    }

This should be test case within the cake core tests. As the apache did not upload the data and set the error to 1. This should be handled by the code and not throw an exception.
I have 3 validation checks and anyhow end up with an exception. The uploadError can't even be displayed as the exception is raised. mimeType check and fileSize check can only be done if the file was uploaded successfully.
How should this case be handled?

A: This is the intended behavior, all validation rules are being run no matter if a previous one failed. So in your case, an upload error will be recognized, but validation will still proceed to the next rule, which is then going to fail hard as no file has been uploaded.
This behavior can be disabled by using the last option. Marking a rule as last will cause validation for that field to stop in case the rule fails.
'uploadError' => [
    'rule' => 'uploadError',
    'message' => __d('clients', 'The logo upload failed.'),
    'last' => true
],

// ...

See also Cookbook > Validation > Marking Rules as the Last to Run