text:
Q: mixed up on multiple hosts if one heavily in processing I use two different ports for hosting two similar sites (8082 for staging and 80 for production). Normally they are working fine in co-existence. However, when there is a heavy testing in staging site, somehow people in production get into the staging site. Can anyone point to me on where I might be wrong on my Apache setup? Thanks a lot.
I use WAMP from Bitnami (Apache 2.4).
in httpd.conf:
...
Listen 80
Listen 8082
ServerName localhost:80
DocumentRoot "C:/Bitnami/wampstack-5.4.40-0/apache2/htdocs"

Options Indexes FollowSymLinks

AllowOverride None

Require all granted

Include "C:/Bitnami/wampstack-5.4.40-0/apache2/conf/bitnami/bitnami.conf"
...
In bitnami.conf:
NameVirtualHost *:80

DocumentRoot "C:/Bitnami/wampstack-5.4.40-0/apache2/htdocs"

Options Indexes FollowSymLinks

AllowOverride All

<IfVersion < 2.3 >
  Order allow,deny
  Allow from all
</IfVersion>
<IfVersion >= 2.3 >
  Require all granted
</IfVersion>

# Bitnami applications installed with a prefix URL (default)
Include "C:/Bitnami/wampstack-5.4.40-0/apache2/conf/bitnami/bitnami-apps-prefix.conf"

NameVirtualHost *:8082

DocumentRoot "C:/Bitnami/wampstack-5.4.40-0/apache2/htdocs"

Options Indexes FollowSymLinks

AllowOverride All

<IfVersion < 2.3 >
  Order allow,deny
  Allow from all
</IfVersion>
<IfVersion >= 2.3 >
  Require all granted
</IfVersion>

# Bitnami applications installed with a prefix URL (default)
Include "C:/Bitnami/wampstack-5.4.40-0/apache2/conf/bitnami/bitnami-apps-prefix2.conf"

...
In bitnami-apps-prefix.conf:
Include "C:/Bitnami/wampstack-5.4.40-0/apps/sci02/conf/httpd-prefix.conf"
In bitnami-apps-prefix2.conf:
Include "D:/Bitnami/wampstack-5.4.40-0/apps/sci02/conf/httpd-prefix.conf"
where C: and D: goes to its real site configuration respectively

A: It turned out that the issue was not port mixing which I was misled. It was due to the mixing of environment variables (.env) which are used to define database, web title and others. Still don't know why this happened, as each site has its own .env and normally they work properly. Anyway it can be resolved now via by-pass, i.e. directly set relevant variables in the application code not through .env.


text:
Q: How to access html data in python flask I have html file which contain the different information.Example
<!DOCTYPE html>

welcome

I want to access the welcome in python file which is in the flask server.How we can access that data.

A: Use the package BeautifulSoup:
from bs4 import BeautifulSoup

html_doc = """
<!DOCTYPE html>

welcome

 """

soup = BeautifulSoup(html_doc, 'html.parser')
print(soup.h1.text)
# 'welcome'

redpajama_set_name: RedPajamaStackExchange


text:
Q: Computing p-values for averaged correlation coefficients I would like to measure the accuracy of an algorithm at predicting a certain target value. Since there is some variance in the algorithm's output, I've run it a few times and computed the Pearson correlation between the predictions and the targets each time. Afterwards, I took the average of the correlations using Fisher z-transform.
Can I compute the p-value for this averaged correlation the standard way for Pearson correlations with t-distribution? (i.e. http://www.jeremymiles.co.uk/usingstatistics/chapter8/sigofrexcel.html) The number of samples is the same each time the algorithm is run (the target values are the same), so there does not appear to be any weighting required.
There were quite a few related questions, but none of them seemed to have the particular answer I was looking for:
p-value of an Average Correlation Coeficient
Averaging correlation values
Significance of average correlation coefficient


text:
Q: Pass a variable from a get query in javascript I am trying to pass the value of a parameter outside a $.get jQuery in javascript. I read that I should somehow do that in synchronous mode but I couldn't find a solution.
Here is my code:
var flag;
var t = $.get("mutalyzer.php?id="+variation.value, function(data) {
    flag=data;
});
document.write(flag);

where I get undefined as a result.
Thanks!

A: write it inside the callback function
try this
var t = $.get("mutalyzer.php?id="+variation.value, function(data) {
   //this is the callback function and runs when get gets  completed
   flag=data;
   document.write(flag);
 });


text:
Q: Is $f \in C^k$ smooth if and only if any if its derivatives are smooth? Let $f \in C^k \mathbb R, f: \mathbb R \to \mathbb R$, where $f$ may or may not belong to a higher differentiability class. Then the derivatives $f^1, f^2, ..., f^k$ exist, and $f^k$ is continuous. Each $f^i$, which I understand is such that $f^i \in C^{k-i}\mathbb R$, may or may not belong to a higher differentiability class. Do we have the following?
$$f \in C^{\infty} \iff f^1 \in C^{\infty} \iff ... \iff f^k \in C^{\infty}$$
I'm wondering because I haven't seen anything like that on wikipedia or stackexchange. Maybe it's so obvious that no one mentions it, or it's wrong.

A: If $f^{(k)}$ (that's how I have learned to denote the $k$th derivative) is not smooth, then that must be because for some integer $n$ it doesn't have a continuous $n$th derivative. Now try to differentiate $f$ a total of $(k+n)$ times to see that $f$ isn't smooth either.


text:
Q: How to get a chrome tab source code in javascript I try to develop a chrome extension and I need to be able to get the source code of the current tab, so I follow the chrome example and I have three files:
manifest.json:
{
    "manifest_version": 2,
    "name": "Source code getter",
    "description": "This extension is a test to get current tab source code",
    "version": "0.1",
    "browser_action": {
         "default_icon": "icon.png",
        "default_popup": "popup.html"
    },
    "permissions": [
        "tabs"
  ]
}

popup.html:
<!doctype html>
 <html>
    <head>
        <title>Get source popup</title>
         <style>
             body {
                min-width: 357px;
                min-height: 357px;
                overflow-x: hidden;
            }
        </style>
        <script src="popup.js"></script>
     </head>
    <body>
    </body>
</html>

and the popup.js
document.addEventListener('DOMContentLoaded', function() {
    chrome.tabs.query({currentWindow: true, active: true}, function(tabs) {
        var tab = tabs[0];
        console.debug(tab.id);
        var source = document.createElement("div");
        chrome.tabs.sendMessage(tab.id, {action: "getHtml"}, function(response) {
            console.debug(response.html);
         if (response.html) {
                source.textContent = response.html;
            } else {
                source.textContent = 'I did not get the source code.';
            }
        });
        document.body.appendChild(source);
    });
});

I build the popup.js by searching across the web and I must confess I don't really know how the sendMessage works exactly, also with the doc but I think the second parameter ask the source code wich must be return in the parameter of function response, but it doesn't, here are the JS log:
430 popup.js:4
> Error in event handler for (unknown): Cannot read property 'html' of undefined
> Stack trace: TypeError: Cannot read property 'html' of undefined
>    at chrome-extension://boefdmhphdcngpckofecmjnihbgphmch/popup.js:7:35
>    at disconnectListener (extensions::messaging:338:9)
>    at Function.target.(anonymous function) (extensions::SafeBuiltins:19:14)
>    at EventImpl.dispatchToListener (extensions::event_bindings:397:22)
>    at Function.target.(anonymous function) (extensions::SafeBuiltins:19:14)
>    at Event.publicClass.(anonymous function) [as dispatchToListener] (extensions::utils:93:26)
>    at EventImpl.dispatch_ (extensions::event_bindings:379:35)
>    at EventImpl.dispatch (extensions::event_bindings:403:17)
>    at Function.target.(anonymous function) (extensions::SafeBuiltins:19:14)
>    at Event.publicClass.(anonymous function) [as dispatch] (extensions::utils:93:26)

so I got the right tab but i don't get a correct response form sendMessage function, someone can explain me why ? Thanks.

A: Judging from your manifest, you've got nothing listening for your sendMessage.
No content script defined in the manifest, so nothing loaded in the page; no executeScript calls in the popup code, so nothing gets loaded from there.
So, nothing to process your message, and the callback gets called with an error set. Your message {action: "getHtml"} does not magically mean anything; you need a script on the page's side to receive it and form a response.
What you need is a content script that will add a listener for chrome.runtime.onMessage, that will process your request. Let's call it content.js. Then you can do this:
chrome.tabs.executeScript({code: "content.js"}, function() {
  if(chrome.runtime.lastError) {
    console.error(chrome.runtime.lastError.message);
    return;
  }
  chrome.tabs.sendMessage(tab.id, {action: "getHtml"}, function(response) {
    /* process response */
  });
});

Code for the appropriate content.js is outside the scope of this question. Have a look at the Architecture Overview too, it's a good introduction of how content scripts work.


text:
Q: using sidekiq to remove class from html I have really never used background processing before with rails. I know that sidekiq is probably the most notable so I'm going with that. RUNDOWN: I have assignment that have a start_time. I want to make sure users cannot start the assignment until the start_time is an hour away form Time.current. The way I would like to do this is remove a disabled class from the html so the user can access the assignment. So if the user set the start_time of the assignment to 5:00 pm the class will be removed from the html at 4:00 PM. Does this make sense? and if so, Is using Sidekiq the proper way to go about this?

A: Background processes are used to perform long-running tasks in a way that doesn't tie up other users from using your site. For example: sending mail, doing something with an external API, calculating things. I don't think you'll need Sidekiq for what you're wanting to do.
Instead, you already have start_time in the db, just use it! You can do something like this in your view:
<div class="<%= 'hidden' if @assignment.start_time > 1.hour.from_now %>">


text:
Q: How much time ENTITY FRAMEWORK spent to materialize query results into entities? Is it possible that I can measure how much time EntityFramework spends to materialize a single object or a list of objects after being loaded from Db.
Any advise?
Thanks!

A: You cannot get the exactly what you want. But it can be estimated. Entity framework takes several actions when executing a query, such as:

*

*Metadata loading

*View generation

*Parameter evaluation

*Query translation

*Materializer generation

*Database query execution

*Object materialization

*Identity lookup

But, when you execute warm query (second query execution) most of loadings and generations are replaced by lookups as below:

*

*Metadata lookup

*View lookup

*Parameter evaluation

*Query lookup

*Materializer lookup

*Database query execution

*Object materialization

*Identity lookup

In this case, the cost of most steps are Low, except:

*

*Database query execution - Potentially high

*Object materialization - Medium

*Identity lookup - Medium.

What you can do here is execute warm query, calculate time it takes, then subtract query execution time from total time and divide it by 2 (because of two medium cost). Yes, I know that will be very rough result, but it is better from nothing :). Here is demo:
// Let Entity Framework to load metadata, generate views and etc.
using (TestContext context = new TestContext())
{
    var query = context.Set<Message>().AsNoTracking();
    Message first = context
        .Set<Message>()
        .AsNoTracking()
        .FirstOrDefault();
}

// Execute warm query
using (TestContext context = new TestContext())
{
    // Log the queries to be able to subtract query execution time.
    context.Database.Log = Console.WriteLine;

    var query = context.Set<Message>().AsNoTracking();

    Stopwatch stopwatch = new Stopwatch();
    stopwatch.Restart();

    Message first = query.FirstOrDefault();

    stopwatch.Stop();
    Console.WriteLine("Elapsed {0} milliseconds.", stopwatch.ElapsedMilliseconds);
}

Then you can subtract query execution time (from logs) from total elapsed time and divide it by 2.
See this link for more info.


text:
Q: Time Interval Partitioning in SQL Server I have a table with time stamp (UTC) and for several reasons, like purging from this table (done at later point of ETL), I am trying to find out the feasibility of partitioning the table by 5 minutes or so. I have records pumped into this table in a real time scenario and my ETL process will be running in parallel.
Below is the schema of my table which I am interested in and my SQL Server version is 2016. Kindly suggest if partitioning can be an optimal way to deal with this scenario.
CREATE TABLE [dbo].[F_DATA_EVENTS]
(
    [RECID] [nvarchar](255) NOT NULL,
    [XMLRECORD] [nvarchar](max) NULL,
    [EVENT_TIMESTAMP] [numeric](38, 6) NULL
)

GO

ALTER TABLE [dbo].[F_DATA_EVENTS] ADD CONSTRAINT [DF_EVENT_TIMESTAMP]
DEFAULT (CONVERT([numeric](30,6),concat(datediff(second,'19700101 00:00:00:000',getdate()),'.',datepart(millisecond,getdate())))) FOR [EVENT_TIMESTAMP]


text:
Q: is there any way to compile some specific forms of C# project I'm working on a windows forms application with eight forms and I want to have different versions of the compiled application. For example:
Demo version: I want form1, form2, form4, form5
Full version: I want form1, form3, form4, form6, form8
How do I do that?

A: You can achieve that with single project by editing .csproj file. Just move forms to the separate ItemGroup elements with Condition attribute based on project Configuration:
<ItemGroup Condition=" '$(Configuration)' == 'Demo' ">
  <Compile Include="Form1.cs">
    <SubType>Form</SubType>
  </Compile>
  <Compile Include="Form1.Designer.cs">
    <DependentUpon>Form1.cs</DependentUpon>
  </Compile>
</ItemGroup>

<ItemGroup Condition=" '$(Configuration)' == 'Full' ">
  <Compile Include="Form2.cs">
    <SubType>Form</SubType>
  </Compile>
  <Compile Include="Form2.Designer.cs">
    <DependentUpon>Form2.cs</DependentUpon>
  </Compile>
</ItemGroup>

Also for these conditions to work you will need to create Demo and Full configurations using solutions's Configuration Manager.

A: You could create them as different projects, but add the same code files to each:

*

*Add existing file to demo project

*Select the form file from the full version

*Add as link

A: Compiler flags. Moving the forms into separate assemblies and repplacing them. Putting all forms int othe same program and have a factory select the right one (again listley based on a license key or a compiler flag).

A: How about something like this demo using CDKEY 00 full version 11, then encrypt that key md5 hash maybe then write that in registry key, when the program runs it read first that key sample  if(cdkey==11){ //full version } else { //demo  }.


text:
Q: How to make a interactive command in discord.js I am wondering how in discord.js to make a interactive giveaway command like the giveaway bot
I am in V11/12
For example when I do g!giveaway start, it starts a interactive setup what will work like this
The bot will say
"Time"
Then I set the type it will last with variables (m for minutes, d for days, w for weeks)
Then it will say
"Okay! Now what do you want to giveaway?"
Then I just say what I want to giveaway
And then it will say
"Great! What channel will the giveaway be in?"
Then I put the channel
Then the bot says
"Good! The giveaway for (prize) has started in (channel) and will last (time) seconds/days/weeks
Please can I get some help here, thanks!

A: Send a message and await a response using a collector (awaitMessages)
We will want to wait for a message after asking, so we will use a collector.
Async TextChannel.awaitMessages() (read docs) can be used to collect messages. It needs a filter to know which messages to accept, as well as some options to know when to stop collecting.
// accepted messages will be those from the same author, we compare IDs to make sure
const filter = msg => msg.author.id == message.author.id;

// the only option needed will be maxMatches, to only take one message before ending the collector
const options = {
  maxMatches: 1
};

The collector will then return a Collection of messages, we will always be taking .first() since there will only be one, and store its content.
// assuming you have the `channel` object, and are inside an async function
let collector = await channel.awaitMessages(filter, options);
let answer = collector.first().content;

Use the above after every channel.send() for each different answer you're looking from the user.
Example on how to use the Collector
client.on("message", async message => {
  if (message.content === "!color") {
    // request
    message.channel.send("What's your fav color?");

    // collector
    let collector = await message.channel.awaitMessages(filter, options);
    let answer = collector.first().content;

    // response
    await message.reply("your fav color is " + answer + "!");
  }
});

Note that this is just an example and in a real implementation you must handle errors properly. Here's the example result:

If you need more inputs just create more collectors and answers, and do with that information however you need to.

A: You need to use MessageCollectors. For example:
let opt = {
    prize: null,
    time: null
};
message.channel.send("Whats the prize?");
let collector = new Discord.MessageCollector(message.channel, () => true);
collector.on("collect", (m) => {
    if(opt.prize && !opt.time){
       opt.time = m.content;
       message.channel.send("Giveaway started! (prize:"+opt.prize+", time:"+opt.time+")");
       collector.stop();
    }
    if(!opt.prize && !opt.time){
         opt.prize = m.content;
         message.channel.send("ok! So what's the time?");
    }
});

You can add as many opt as you want, follow the same logic.
You can use my npm package, discord-giveaways to create giveaways easily.


text:
Q: SharePoint 2013 Standard vs Enterprise Search In SharePoint 2013, What are the differences between Standard vs Enterprise Search?
And does it comes with different licensing when purchasing the SharePoint 2013 Enterprise version?

A: Check out the following comparison chart:

*

*SharePoint 2013 feature comparison chart all editions

*Official SharePoint 2013 feature comparison chart all editions
It boils down to this:

*

*The new Content Search WebPart is not available without Enterprise

*The content processing pipeline is not as extensible with Standard

*Advanced query rules are not available with Standard

The advanced search stuff not many companies use - the Content Search WebPart is interesting though. Licensing is done through CALs (Client Access License) per User. That means you would need a Standard/Enterprise license per user who uses Enterprise features. If you're talking about search, it might very well be all your users. There is a price difference between the Standard and the Enterprise CAL.


text:
Q: How to organize jar files in a libraries folder in Eclipse? I have a Java Project in Eclipse, and a Java Dynamic Web Project in Eclipse.  In the former, all the jar files are shown individually under the top-level project folder.  In the latter, the jar files are under a Libraries folder and the navigation is more convenient.
Is it possible to organize them in the same way in the Java Project also? If so, how?
Update: It is the Project Explorer View. For the Java Project, I see: "my_project_name" with the arrow expanded to point downwards, then I see: "package_icon src/main/java" and below that "package_icon src/main/resources" and then 20 jar files one below the other: "jar_icon activation-1.1.jar", ...
For the Java Dynamic Web Project I see: "my_project_name" as above, then I see: "JAX-WS Web Services" (unexpanded), then "Deployment Descriptor" (unexpanded), then "Java Resources" which I have expandeded, so I see the components of it below, of which the first is: "package_icon src/main/java", then below it, "package_icon src/main/resources", then below it "libraries_icon Libraries" instead of 20 jars!  I have the option of expanding Libraries if I really need to see the 20 jars.

A: The only option I found to make things prettier in Eclipse Kepler is to:

*

*In the Project Explorer window there is a down arrow in the upper right corner. Select that and then Customize View.

*Select 'Libraries from external' and then OK.
Kind of cheesy...
EDIT: Of course I had to go and do some more digging...and it looks like I'll have to try this and see how it works.

A: I noticed this "feature" on Eclipse Juno (latest version), when you have a jar file added to the build path it is not shown as a single file on the project.
Try removing one of the jars from the build path to see if it shows up again.
I couldn't find how to turn it off though.
BTW... the project layout for your "Java Project" is more akin to a "Maven Project", which is a bit more powerful.

A: Similar to M Miller's answer (but for Juno), click Show 'Referenced Libraries' Node in the dropdown of the Package Explorer window:

I'm using:
Eclipse IDE for Java Developers

Version: Juno Release
Build id: 20120614-1722

A: You should change into the Package Explorer by Window > show View. It will display all the referenced libraries in a Referenced Libraries folder.


text:
Q: Natural Color Mixing in Processing I am trying to naturally mix green tint on one photo (elephant) and red tint on another photo (ship) by placing the two opaque and tinted photos on top of one another. While both photos appear with equal prominence, when the program is run and both colors can be observed, the red tint (because it is the last tint applied) is more dominant and there is no discernable yellow color in the image no matter which tint is applied first. If anyone knows how to naturally mix colors in processing I would love to hear your advice. I also do not want to simply apply a yellow tint as the last tint. Thanks!
PImage elephant;
PImage ship;
void setup(){
   size(695,473);
   elephant = loadImage("elephantRider.png");
   ship = loadImage("ship.jpg");
   ship.filter(OPAQUE);
   elephant.filter(OPAQUE);
}
void draw(){
   background(255);
   tint(0,255,0, 127);
   image(elephant, 0,0);
   tint(255,0,0,127);
   image(ship, 0,0);
}

A: Think of Processing as painting. What you're doing now is a little bit like drawing one color to the screen, and then drawing another color on top of the first color.
Instead, what you want to do is mix the two colors together before you draw the result to the screen. Think of this as mixing two paints together to make a new color.
You can do this by taking the average of the two colors, something like this:
PImage img;

void setup() {
  size(695, 473);
  img = loadImage("image.jpg");
}

void draw() {
  background(255);

  //green
  tint(0, 255, 0, 127);
  image(img, width/2, height/2, 50, 50);

  float blendedRed = (0 + 255) / 2;
  float blendedGreen = (255 + 0) / 2;
  float blendedBlue = (0 + 0) / 2;

  // blended
  tint(blendedRed, blendedGreen, blendedBlue, 127);
  image(img, mouseX, mouseY, 50, 50);
}

This example is a little contrived because the averages are pretty trivial, but this approach should work for any color.
If you want something more advanced, note that color averaging is a pretty advanced topic. Googling "color averaging" is probably a good start.


text:
Q: Allow for acrylic to be not turned off when focus is lost from app? Acrylic is by far the best thing in fluent design system, it just makes the app looks so good. And I am totally fine with optimization of it; turning of the transparency when battery is in saving mode.
But I don't want it to be turned off when the user looses the focus over the app. Is there any workarounds for it?

When the user looses the focus over the app, acrylic is turned off and fallback color is used!

A: Unfortunately acrylic background effect is currently limited to run only when the application window is active, as stated in the documentation

In addition, only background acrylic will replace its transparency and texture with a solid color
When an app window on desktop deactivates
When the UWP app is running on phone, Xbox, HoloLens or tablet mode


text:
Q: Latest Angular package.json I'm trying to keep my app to the latest version of Angular and everytime I try to update to latest version of Angular components I'm getting the same error...
npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR!
npm ERR! While resolving: salarizare@0.0.0
npm ERR! Found: @angular-devkit/build-angular@14.2.1
npm ERR! node_modules/@angular-devkit/build-angular
npm ERR!   @angular-devkit/build-angular@"14.2.6" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! @angular-devkit/build-angular@"14.2.6" from the root project
npm ERR!
npm ERR! Conflicting peer dependency: @angular/compiler@14.2.7
npm ERR! node_modules/@angular/compiler
npm ERR!   peer @angular/compiler@"14.2.7" from @angular/localize@14.2.7
npm ERR!   node_modules/@angular/localize
npm ERR!     @angular/localize@"14.2.7" from the root project
npm ERR!     peerOptional @angular/localize@"^14.0.0" from @angular-devkit/build-angular@14.2.6
npm ERR!     node_modules/@angular-devkit/build-angular
npm ERR!       @angular-devkit/build-angular@"14.2.6" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:\Users\User 12\AppData\Local\npm-cache\eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\User 12\AppData\Local\npm-cache\_logs\2022-10-21T11_58_38_546Z-debug-0.log

My package.json looks like this (everything is on the latest version...)
{
  "name": "salarizare",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test"
  },
  "private": true,
  "dependencies": {
    "@angular-devkit/build-angular": "14.2.6",
    "@angular/animations": "14.2.7",
    "@angular/cdk": "14.2.5",
    "@angular/common": "14.2.7",
    "@angular/compiler": "14.2.7",
    "@angular/compiler-cli": "14.2.7",
    "@angular/core": "14.2.7",
    "@angular/forms": "14.2.7",
    "@angular/localize": "14.2.7",
    "@angular/material": "14.2.5",
    "@angular/platform-browser": "14.2.7",
    "@angular/platform-browser-dynamic": "14.2.7",
    "@angular/router": "14.2.7",
    "@fortawesome/angular-fontawesome": "0.11.1",
    "@fortawesome/fontawesome-svg-core": "^6.2.0",
    "@fortawesome/free-brands-svg-icons": "^6.2.0",
    "@fortawesome/free-regular-svg-icons": "^6.2.0",
    "@fortawesome/free-solid-svg-icons": "^6.2.0",
    "@ng-bootstrap/ng-bootstrap": "^13.1.0",
    "@ng-select/ng-select": "9.0.2",
    "@popperjs/core": "^2.11.6",
    "@types/async": "^3.2.15",
    "@types/jquery": "^3.5.14",
    "@types/lodash": "^4.14.186",
    "@types/toastr": "^2.1.40",
    "ace-builds": "1.12.3",
    "angular2-hotkeys": "^13.1.0",
    "async": "^3.2.4",
    "axios": "^1.1.3",
    "bootstrap": "5.2.2",
    "core-js": "^3.25.5",
    "dayjs": "^1.11.6",
    "fast-xml-parser": "^4.0.11",
    "jquery": "^3.6.1",
    "lodash": "^4.17.21",
    "ng-table-virtual-scroll": "^1.4.1",
    "ngx-bootstrap": "^9.0.0",
    "ngx-editor": "15.0.1",
    "ngx-infinite-scroll": "14.0.0",
    "ngx-socket-io": "4.3.1",
    "ngx-spinner": "14.0.0",
    "ngx-toastr": "^15.2.1",
    "reflect-metadata": "^0.1.13",
    "rxjs": "7.5.7",
    "tslib": "^2.4.0",
    "typescript": "4.8.4",
    "xlsx-js-style": "^1.2.0",
    "zone.js": "^0.11.8"
  },
  "devDependencies": {
    "@angular/cli": "14.2.6",
    "@types/jasmine": "^4.3.0",
    "@types/node": "^18.11.3",
    "jasmine-core": "^4.4.0",
    "karma": "^6.4.1",
    "karma-chrome-launcher": "^3.1.1",
    "karma-coverage": "~2.2.0",
    "karma-jasmine": "~5.1.0",
    "karma-jasmine-html-reporter": "~2.0.0"
  },
  "browser": {
    "os": false
  }
}

Am I missing something? :( If i downgrade to an older version everything works great... Btw, I'm updating from 14.0.0 to 14.2.6/7 so it shouldn't be such a huge leap if I'm not wrong... can it be a problem from NPM ?
EDIT: If I try with ~14.0.0 I get the following conflict xD
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: salarizare@0.0.0
npm ERR! Found: typescript@4.8.4
npm ERR! node_modules/typescript
npm ERR!   typescript@"4.8.4" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer typescript@">=4.6.2 <4.8" from @angular/compiler-cli@14.0.7
npm ERR! node_modules/@angular/compiler-cli
npm ERR!   @angular/compiler-cli@"~14.0.0" from the root project
npm ERR!   peer @angular/compiler-cli@"^14.0.0" from @angular-devkit/build-angular@14.0.7
npm ERR!   node_modules/@angular-devkit/build-angular
npm ERR!     @angular-devkit/build-angular@"~14.0.0" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:\Users\User 12\AppData\Local\npm-cache\eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\User 12\AppData\Local\npm-cache\_logs\2022-10-21T12_32_32_151Z-debug-0.log

A: Run:

*

*npm uninstall -g angular-cli

*npm cache clean or npm cache verify (if npm > 5)

*npm install -g @angular/cli@latest

*

*link: https://www.angularjswiki.com/angular/update-angular-cli-version-ng-update-to-latest-6-7-versions/#:~:text=Steps%20To%20update%20Angular%20CLI,angular%2Fcli%40latest%20command.

*I'm still getting errors with compiler localize and bootstrap...


text:
Q: How to Fetch date from DateTime Object How to Fetch date from DateTime Object?
Output is:
Array (
    [0] => stdClass Object (
        [instrument_token] => 16796674
        [exchange_token] => 65612
        [tradingsymbol] => DABUR18MAR445CE
        [name] =>
        [last_price] => 0.05
        [expiry] => DateTime Object (
            [date] => 2018-03-28 00:00:00.000000
            [timezone_type] => 3
            [timezone] => asia/kolkata
        )
        [strike] => 445
        [tick_size] => 0.05
        [lot_size] => 2500
        [instrument_type] => CE
        [segment] => NFO-OPT
        [exchange] => NFO
    )
)

A: The DateTime Object here is a string representation of the object (see __toString()).
You could use DateTime::format() to get a string as you want :
$date_str = $array[0]->expiry->format('Y-m-d H:i:s');


text:
Q: Is there a single word for "moving unhinderedly"? For example, in a novel, if someone is so powerful that no one can stop him, something like this would be said:

He [insert word] in the continent [or some other location].

"Moved unhinderedly" somewhat fits it, but it doesn't really seem like the right term.
The word I'm looking for describes a few things:

*

*Should have an implication that the person himself is powerful

*That person can go wherever he wishes to, and cannot be stopped because of his strength

*That person can do whatever he wishes to, and like above, cannot be stopped because of his strength
The other word I have is "swept", i.e.:

He swept through the continent.

I used "swept" because when you sweep the floor, nothing stops you and everything is swept away, similar to the example. However, the dictionary definitions don't match up, so that isn't the word either.
Any suggestions?

A: I suggest powered
He powered through Africa, driving all before him.  (example made up by me)

power verb  (STRENGTH)
[I usually + adv/prep] to act with great strength or in a forceful way:
Halfway through, she powered into the lead and went on to win the race.
http://dictionary.cambridge.org/dictionary/british/power

Incidentally, I know you have already rejected it but swept is very commonly used in this situation, e.g.

After conquering Syria in 332 BCE, Alexander the Great swept down into Egypt with his army.
Ancient History Encyclopedia
http://www.ancient.eu/alexandria/

A: Stormed, swept, blew, breezed, strode, powered, rampaged, stomped, sailed, barged et all, are all fine verbs for the singular act of moving through a place without resistance. Each has its own subtle connotation too, so pick wisely.
To indicate that someone can do so habitually, you may need more than a word.
To have free reign indicates that someone can do with something or go wherever they please within an area. He had free reign of the continent.
To be unimpeded is to encounter no resistance of movement. He travelled the continent unimpeded.
There is a particular meaning to the word check that indicates withholding or limiting something; hence the phrase unchecked power. He moved around the continent unchecked.
One of the beauties of the English language is that for a concept like this, you're not only likely to find dozens of existing examples of florid description, but there is still plenty of untilled fertile ground for further invention. If this concept is central to your story, perhaps coin your own!

A: Perhaps storm (as a verb)

to use force to enter a place and take control of it

Macmillan
While this is often used in the context of a battle or a police action, it can have a more figurative meaning, such as

His theatrical performances throughout Europe were amazing. He stormed the continent!

Or you might use the phrase take by storm.  Collins offers these two definitions

*

*to capture or overrun by a violent assault

*to overwhelm and enthral

A: Stride might be suitable. It has a lot of subtly different meanings but the 1st verb definition implies power and arrogance and the idiom "take in stride" implies confidence and success:

stride verb (used without object), strode, stridden, striding.
  1. to walk with long steps, as with vigor, haste, impatience, or arrogance.
  Idioms
  15. take in stride, to deal with calmly; cope with successfully: She was able to take her sudden rise to fame in stride.

(reference.com)
Therefore, I think it has the desired connotations. The use in the example would be:

He strode through the continent.

A: You might be able to user steamroller or steamroll.
Dictionary.com Unabridged:

verb (used without object)

*to proceed with implacable force.

He steamrolled across the continent.

A: tear-assing or tearassing -UD

2: To move quickly about.

The First of the Ninth was a old cavalry division that traded in their horses for helicopters and went tear-assing around 'Nam looking for the shit... –Apocalypse Now
The Air Cav was very powerful and had the ability to [traverse] the countryside unhindered. They went wherever they wanted, did whatever they wanted to and could not be stopped easily.
I like most of the answers here but the majority of them would be best if followed by unhindered. Tearassing gets the point across without it: went tearassing about the countryside.
The adverb, unhinderingly just sounds wrong to me and I don't think unhinderedly is a word. Use the adjective, unhindered.

A: If it's just one person, travelling, (and not for example a whole army, conquering) then perhaps "ranged": e.g. "he ranged over Africa".
Alternatively (and more peacefully) "toured": e.g. "he toured Africa".

A: to advance (verb):
move forwards in a purposeful way

'the troops advanced on the capital'

inexorably (adverb):
in a way that is impossible to stop or prevent
Source: ODO
If you combine the above terms, the sentence given becomes:

'He advanced inexorably across the continent.'

A: ("Unhindered" does not need or allow the adverb suffix.  You can move unhindered about the continent.)
The two closest words I have seen for this use are "bull" and "parade", with very different connotations.
"Bulling about the place" is going where you wish and doing as you will, despite the rules and knowing you will never suffer for any damage you might cause, as a bull might in his own pasture, unimpeded and unconcerned.
"Parading around a place" is making a show of your entitlement to do as you wish, since parades stop traffic, etc., and everyone works around them because they represent something important.  This person is unimpeded, but is very much aware of and concerned with being unimpeded.
If it is more about his ability to move, than his actually doing so, you could use something like "had free rein".  Metaphorically, his power is a horse that can take him anywhere, he need only choose.  I don't think there is a single word related to this notion.

A: I'd say roam. There is some air of freedom to it. Like a gypsy.

A: Well, "moving unhinderedly" is basically "coasting".  However, your further description makes it clear that you are not talking about "unhinderedly" but rather about "not slowed down".  "Swept through" is not bad but implies extensive impact.  How about "barreled across"?

A: He marched across the continent, leaving stories in his wake. It is beyond your power to hinder a march, whether it is the determined march of an army, or the inexorable march of time.

A: To these great answers, I add charged.
"The unstoppable Juggernaut charged through continents, unstoppably."
I also propose a new verb: Juggernauted.  I hope it helps you.

A: Try "he romped across the continent" — this clearly conveys that travel was free, easy and unimpeded but does not necessarily carry connotations of conquest. It has an upbeat or joyous sense so would not work well for "the great  emperor's funeral procession travelled unimpeded across the continent" but would work well for a powerful individual who was enjoying or excelling in their task: "the wealthy businessman romped across the continent, treating with governments in every capital and signing deals in every commercial centre of note".
It's often used in racing where a leader is not involved in any trouble or tussle: "he romped home for the easiest victory of his career", which is similar to the "unimpeded" sense you want.
TheFreeDictionary gives two relevant meanings:

To run or advance in a rapid or easy manner.
Slang To win a race or game easily.

A: You could say he cut through the continent.

To pass through or across; cross: a sailboat cutting the water.

(thefreedictionary.com)


text:
Q: How to list the permissions needed for a role / user to run a query / view successfully (in an automated manner)? Suppose I have queries / views like this:
select
    internal.companies._cid,
    internal.companies.name,
    src1.employees.year,
    src1.employees.count
from internal.companies
    join src1.employees using (_cid)

In this example, I know that a role will need these privileges:

*

*usage on schemas internal and src1

*select on tables internal.companies and src1.employees

*and may be usage and select on any sequences (in case it's an insert statement)

I can, of course, browse through all the code and note them down manually. But it will take time. The intention, obviously, is to follow the "least privilege" principle instead of lazily granting all permissions on all tables / schemas.
Is there an automatic way of knowing the exact privileges a role / user would need to run a query successfully?

A: No, not that ships with PG14. Add in views, triggers, and row-level security and I doubt its even possible to statically determine the set of grants needed.


text:
Q: Codeigniter and Facebook PHP SDK - error posting to user wall I am using the FB PHP SDK to post a message to a user's wall.
Once the user is authenticated via FB I allow them to post a message using this helper function
function post_facebook($fb) {

    $CI =& get_instance();

    $CI->load->library('facebook');

    $config = array(
        'appId'  => '123123123123',
        'secret' => '567567567567'
    );

    $facebook = new Facebook($config);
    $user_id  = $facebook->getUser();

    if ($user_id) {

        $facebook->api('/me/feed', 'POST', array(
                                              'message' => $fb['post_text'],
                                           )
                   );
     }
}

This actually sends the post to FB and it shows on the wall.
But in Firebug I can see this error

A PHP Error was encountered

Severity: Warning

Message:  Missing argument 1 for Facebook::__construct(), called in /var/www/vhosts/example.com/httpdocs/system/core/Loader.php on line 1099 and defined

Filename: libraries/Facebook.php

Line Number: 36

A PHP Error was encountered

Severity: Notice

Message:  Undefined variable: config

Filename: libraries/Facebook.php

Line Number: 40

Any idea what I'm doing wrong?

A: The error you see is from the call to $this->load->library('facebook'), you should pass the $config array as a parameter to it and access the library from the CI object, like this:
$config = array(
    'appId'  => '123123123123',
    'secret' => '567567567567'
);
$CI->load->library('facebook', $config);

$user_id  = $CI->facebook->getUser();

Read more about the loader here:
http://codeigniter.com/user_guide/libraries/loader.html


text:
Q: Can't mock a module method when importing by name I don't understand why I can't do this operation when trying to mock time.sleep() -- the sleep() method will still delay the given time:
import unittest
from unittest.mock import patch

from time import sleep

class TestTime(unittest.TestCase):

    @patch('time.sleep', return_value=None)
    def test_time(self, mock_time):
        sleep(10) # still delays 10s

if __name__ == '__main__':
    unittest.main()

This works properly:
import unittest
from unittest.mock import patch

import time

class TestTime(unittest.TestCase):

    @patch('time.sleep', return_value=None)
    def test_time(self, mock_time):
        time.sleep(10) # instant

if __name__ == '__main__':
    unittest.main()

This results in an error TypeError: Need a valid target to patch. You supplied: 'sleep':
import unittest
from unittest.mock import patch

from time import sleep

class TestTime(unittest.TestCase):

    @patch('sleep', return_value=None) # error
    def test_time(self, mock_time):
        sleep(10)

if __name__ == '__main__':
    unittest.main()

Is there a proper way to mock sleep() without needing to change all the modules I'm trying to test to use time.sleep()?
My setup:

*

*Python version: 3.8.12

*OS: Windows 10 21H1 (19043.1766)

A: The reason importing sleep by name doesn't allow patch to work in the examples is that patch is looking for attribute names on an object in order to patch it.  When importing by name, the object isn't provided and thus why there is a TypeError.  The sleep method is now in the namespace of the module importing it, so you can use that to properly patch sleep.
To import sleep by name and properly patch it, the following will work:
import unittest
from unittest.mock import patch

from time import sleep

class TestTime(unittest.TestCase):

    @patch('__main__.sleep', return_value=None)
    def test_time(self, mock_time):
        sleep(10)

if __name__ == '__main__':
    unittest.main()

As a caveat, if you have a module named my_module that uses from time import sleep and a separate file for tests, you can do the following within the test file to patch sleep within my_module:
@patch('my_module.sleep', return_value=None)


text:
Q: Как добавить ресурсные файлы в jar Не добавляются ресурсные файлы в jar при сборке мавеном:
- answers.txt
- questions.txt
- rightAnswers.txt

В pom.xml описаны:
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>questions.txt</include>
                <include>answers.txt</include>
                <include>rightAnswers.txt</include>
            </includes>
        </resource>
    </resources>

Чтение в Main.class первый вариант:
    FileReader readerQuestions = new FileReader("questions.txt");
    FileReader readerAnswers = new FileReader("answers.txt");
    FileReader readerRightAnswers = new FileReader("rightAnswers.txt");

Второй вариант:
    FileReader readerQuestions = new FileReader(new String(Files.readAllBytes(Paths.get("questions.txt"))));
    FileReader readerAnswers = new FileReader(new String(Files.readAllBytes(Paths.get("answers.txt"))));
    FileReader readerRightAnswers = new FileReader(new String(Files.readAllBytes(Paths.get("rightAnswers.txt"))));

Реп - https://github.com/MichelShumaher/System-of-Testing.git


text:
Q: How to set pts, dts and duration in ffmpeg library? I want to pack some compressed video packets(h.264) to ".mp4" container.
One word, Muxing, no decoding and no encoding.
And I have no idea how to set pts, dts and duration.

*

*I get the packets with "pcap" library.

*I removed headers before compressed video data show up. e.g. Ethernet, VLAN.

*I collected data until one frame and decoded it for getting information of data. e.g. width, height. (I am not sure that it is necessary)

*I initialized output context, stream and codec context.

*I started to receive packets with "pcap" library again. (now for muxing)

*I made one frame and put that data in AVPacket structure.

*I try to set PTS, DTS and duration. (I think here is wrong part, not sure though)

*7-1. At the first frame, I saved time(msec) with packet header structure.
*7-2. whenever I made one frame, I set parameters like this : PTS(current time - start time), DTS(same PTS value), duration(current PTS - before PTS)
I think it has some error because :

*

*I don't know how far is suitable long for dts from pts.

*At least, I think duration means how long time show this frame from now to next frame, so It should have value(next PTS - current PTS), but I can not know the value next PTS at that time.
It has I-frame only.
// make input context for decoding

AVFormatContext *&ic = gInputContext;

ic = avformat_alloc_context();

AVCodec *cd = avcodec_find_decoder(AV_CODEC_ID_H264);

AVStream *st = avformat_new_stream(ic, cd);

AVCodecContext *cc = st->codec;

avcodec_open2(cc, cd, NULL);

// make packet and decode it after collect packets is be one frame

gPacket.stream_index = 0;

gPacket.size    = gPacketLength[0];

gPacket.data    = gPacketData[0];

gPacket.pts     = AV_NOPTS_VALUE;

gPacket.dts     = AV_NOPTS_VALUE;

gPacket.flags   = AV_PKT_FLAG_KEY;

avcodec_decode_video2(cc, gFrame, &got_picture, &gPacket);

// I checked automatically it initialized after "avcodec_decode_video2"

// put some info that I know that not initialized

cc->time_base.den   = 90000;

cc->time_base.num   = 1;

cc->bit_rate    = 2500000;

cc->gop_size    = 1;

// make output context with input context

AVFormatContext *&oc = gOutputContext;

avformat_alloc_output_context2(&oc, NULL, NULL, filename);

AVFormatContext *&ic = gInputContext;

AVStream *ist = ic->streams[0];

AVCodecContext *&icc = ist->codec;

AVStream *ost = avformat_new_stream(oc, icc->codec);

AVCodecContext *occ = ost->codec;

avcodec_copy_context(occ, icc);

occ->flags |= CODEC_FLAG_GLOBAL_HEADER;

avio_open(&(oc->pb), filename, AVIO_FLAG_WRITE);

// repeated part for muxing

AVRational Millisecond = { 1, 1000 };

gPacket.stream_index = 0;

gPacket.data = gPacketData[0];

gPacket.size = gPacketLength[0];

gPacket.pts = av_rescale_rnd(pkthdr->ts.tv_sec * 1000 /

    + pkthdr->ts.tv_usec / 1000 /

    - gStartTime, Millisecond.den, ost->time_base.den, /

    (AVRounding)(AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX));

gPacket.dts = gPacket.pts;

gPacket.duration = gPacket.pts - gPrev;

gPacket.flags = AV_PKT_FLAG_KEY;

gPrev = gPacket.pts;

av_interleaved_write_frame(gOutputContext, &gPacket);

Expected and actual results is a .mp4 video file that can play.


text:
Q: Paypal API Reference transactions Deprecated I see that Paypal API Reference Transactions is deprecated https://developer.paypal.com/docs/classic/express-checkout/integration-guide/ECReferenceTxns/
It redirects you to https://developer.paypal.com/docs/integration/direct/express-checkout/integration-jsv4/ but it hardly does the same thing.
If I will like to create an agreement for several purchases but without redirecting you paypal, which paypa api do you think I should use.

A: Express Checkout does deprecated but the Application such Recurring Payment, Billing Agreement and Reference Transaction are still available.


text:
Q: Second monitor flashes static when viewing Netflix in Chrome or Firefox NOTE: This happens in other HD-streaming apps, too, but it doesn't happen in the MS Edge browser.
I have two identical Samsung 27D850T monitors, running at 60Hz connected on DisplayPort and HDMI respectively.  This also happens when they are both on the DP ports (but I had some sleep-related powerup issues and it works better like this).
After a few seconds (up to a minute or so) the secondary monitor will flicker and flash with static. As soon as I stop the stream (having to return to the browse page) the flickering stops immediately.
This happens in Chrome and Firefox (latest).
One thing I've noticed is that while Chrome and Firefox show the image when dragging the browser from monitor to monitor, Edge doesn't.  It blanks out the image in the 'target' monitor until the whole browser has moved across.  This makes me think it's something to do with HDCP.
Any ideas what I can do about it?  Are there some Chrome flags anyone knows about that might help with this?  Can I disable HDCP or something?
Cheers!


text:
Q: what's the difference between by passing a symbol and string in where clause with joins I have two models User and Book. User have username and email field, Book have author and title field. When I am using joins to get the users based on associated data with conditions passed in where clause, I am getting different results

*

*When I run this
User.joins(:books).where('author = ? ','xxxx')

Mysql query generated is :
 "SELECT `users`.* FROM `users` INNER JOIN `books` ON `books`.`user_id` = `users`.`id` WHERE (author = 'xxxxx' )"

gives me the user whose book include xxxx author whereas

*When I run this
User.joins(:books).where(author: 'xxxx')

Mysql query generated is:
"SELECT `users`.* FROM `users` INNER JOIN `books` ON `books`.`user_id` = `users`.`id` WHERE `users`.`author` = 'xxxx'">

gives Mysql2::Error: Unknown column 'users.author' in 'where clause':
 SELECT `users`.* FROM `users` INNER JOIN `books` ON `books`.`user_id` = `users`.`id` WHERE `users`.`author` = 'xxxx'

ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'users.author' in 'where clause': SELECT users.* FROM users INNER JOIN book ON book.user_id = users.id WHERE users.author = 'Dan Brown'
My question : is when I am passing a string encapsulated field and value in where clause it gives me result but when I pass a symbol in where clause it gives me mysql unknown column error. So how does ruby interpreter know from where to fetch data in symbol passing and string passing

A: When we join the tables especially in rails the rails has a power to take the aliasing of the joined tables.
Your query,
     User.joins(:books).where(author: 'xxxx') searches for the author field in the user table
User.joins(:books).where(author: 'xxxx') always takes the field of first table and
User.joins(:books).where('author = ? ','xxxx') searches in both the tables
For example, User.joins(:books).where('id = ? ','xxxx'), try this query.
In the above You will get an error because id field is present in both the tables and it gets confused
but,
User.joins(:books).where(id: 'xxxx') works because it searches only in the users table.
so, you can use, refer author through books books: {author: 'xxxx'}
User.joins(:books).where(books: {author: 'xxxx'})   // your required query

or
User.joins(:books).where('author = ? ','xxxx')

A: User.joins(:books).where('author = ? ','xxxx') is free from sql injection but User.joins(:books).where(author: 'xxxx') is not .
It is good to use User.joins(:books).where('author = ? ','xxxx') as it is easier to write more complex where clause.
When you are writing User.joins(:books).where(author: 'xxxx') rails interpreter will try to interpret as users.author = 'xxxx'
You can check the link for more info.


text:
Q: Replacing words in vba how do I replace words in vba? For example I have a column of words but some ends with U and E and I want to remove the U and E, how do I do that?
Cells.Replace What:="/*-", Replacement:="", LookAt:=xlPart, SearchOrder _
    :=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False

I used this to change for example "AAA/&-" to "AAA". How do I do the same for "AAA U" to "AAA", I cant use the same formula, as "U" is a common letter? My columns of words consist of about 20+ different words that ends with U so I can't hardcode the word as well.
Please help, thank you!

A: Just loop over the cells, examining the last character of each one:
Sub Remove_E_and_U()
    Dim r As Range

    For Each r In ActiveSheet.UsedRange.Cells.SpecialCells(xlCellTypeConstants)
        v = r.Value
        If v <> "" Then
            If Right(v, 1) = "U" Or Right(v, 1) = "E" Then
                r.Value = Mid(v, 1, Len(v) - 1)
            End If
        End If
    Next r
End Sub

EDIT#1:
To restrict the macro to columns F through H, replace:
ActiveSheet.UsedRange.Cells.SpecialCells(xlCellTypeConstants)

with:
Range("F:H").Cells.SpecialCells(xlCellTypeConstants)

A: Maybe regex?
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")

Pattern = "(\w+\s)(U|E)"
replacement = "$1"
RE.Pattern = Pattern

Regex = RE.Replace(Range("A1").Value, replacement)

EDIT; This will keep the space AAA if you want to remove the space move the \s part of the Pattern to the other () like: "(\w+)(\sU)"


text:
Q: ASP.NET MVC with NHibernate
I want to know few things about ASP.NET MVC with NHibernate.

*

*Is NHibernate the best ORM used with ASP.NET MVC?

*If so, will NHibernate slow down the application?

*What can be done to improve performance of an ASP.NET MVC application with NHibernate?

A: I use NHibernate with ASP.NET MVC for GarageCommerce.com and it is very fast even on pretty low budget hardware. The overhead of NHibernate is negligible compared to the raw cost of talking to a database.
There is a strong community, proven patterns to follow and support tools like NHibernate Profiler. It's likely that you would end up with a more efficient application than if you had rolled your own database access.
You have a better chance of solving scalability issues with a powerful tool like NH. You can turn on it's 2nd level cache and back it with memcache. There is also work on NHiberate.Shards to help you horizontally partition your data.

A: *

*There is no best ORM to use with
ASP.NET MVC. The best ORM is the one
which meets your needs.

*No, there is nothing inherent in
NHibernate that will slow down your
application.

*Don't worry so much about
performance unless it becomes a
problem in the future. Is there a
good reason why you have such high
performance requirements?

A: *

*Depends. If you are a total newbie you might want to try entity framework because it contains all the ORM designer classes that allows you to create entity class by drag and drop.

*No, it won't. NHibernate is used by a lot of sites, and it has first and second level caching feature that would speed things up by caching the previous operation, so performance isn't really an issue.

*You can only improve your app after you identify the bottleneck. Don't premature optimize.

A: Michael, nHibernate is great for CRUD operations and handling of complex operations on business objects. Though it can handle rather complex queries, when it comes to reporting, I'd stick to Crystal reports... and if you have lots of stored procedures, no ORM likes them too much.

A: just curious...we use crystal reports for our web-based reporting environment...heavy, complex stored procedures that tie up the db for a long time then exporting to pdf.
does converting to an html based solution using an ORM like NHibernate make sense there? seems like there's more flexibility in terms of performance tweaks?


text:
Q: Android SDK tools fail I have trouble with android SDK. I try to compile with buildozer but I have problem when sdkmanager is run. There is log of buildozer but even if I run command ./sdkmanager itself I fot same error from commandline.
Any idea? (I have near same configuration on my laptop with same xubuntu 18.04 and there works)
# Check configuration tokens
# Ensure build layout
# Check configuration tokens
# Read available permissions from api-versions.xml
# Preparing build
# Check requirements for android
# Run 'dpkg --version'
# Cwd None
Debian 'dpkg' package management program version 1.19.0.5 (amd64).
This is free software; see the GNU General Public License version 2 or
later for copying conditions. There is NO warranty.
# Search for Git (git)
#  -> found at /usr/bin/git
# Search for Cython (cython)
#  -> found at /home/slavko/.local/bin/cython
# Search for Java compiler (javac)
#  -> found at /usr/lib/jvm/java-8-openjdk-amd64/bin/javac
# Search for Java keytool (keytool)
#  -> found at /usr/lib/jvm/java-11-openjdk-amd64/bin/keytool
# Install platform
# Run '/usr/bin/python -m pip install -q --user \'appdirs\' \'colorama>=0.3.3\' \'jinja2\' \'six\' \'enum34; python_version<"3.4"\' \'sh>=1.10; sys_platform!="nt"\' \'pep517\' \'pytoml\' \'virtualenv\''
# Cwd None
# Apache ANT found at /home/slavko/.buildozer/android/platform/apache-ant-1.9.4
# Android SDK found at /home/slavko/.buildozer/android/platform/android-sdk
# Android NDK found at /home/slavko/.buildozer/android/platform/android-ndk-r17c
# Installing/updating SDK platform tools if necessary
# Run '/home/slavko/.buildozer/android/platform/android-sdk/tools/bin/sdkmanager tools platform-tools'
# Cwd /home/slavko/.buildozer/android/platform/android-sdk
Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema
    at com.android.repository.api.SchemaModule$SchemaModuleVersion.<init>(SchemaModule.java:156)
    at com.android.repository.api.SchemaModule.<init>(SchemaModule.java:75)
    at com.android.sdklib.repository.AndroidSdkHandler.<clinit>(AndroidSdkHandler.java:81)
    at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:73)
    at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:48)
Caused by: java.lang.ClassNotFoundException: javax.xml.bind.annotation.XmlSchema
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
    ... 5 more
# Command failed: /home/slavko/.buildozer/android/platform/android-sdk/tools/bin/sdkmanager tools platform-tools
#
# Buildozer failed to execute the last command
# The error might be hidden in the log above this error
# Please read the full log, and search for it before
# raising an issue with buildozer itself.
# In case of a bug report, please add a full log with log_level = 2

A: seems that jdk-11 is culpruit as with jdk-8 works


text:
Q: Filtering through XML results I need to go through some data and pick out certain items which match my criteria. I'm using Client-side scripting to return XML which looks like this:
<List DocTemplateUrl=
      "" DefaultViewUrl="/TestWeb1/Lists/Announcements/AllItems.aspx"
      ID="{8A98E2E5-B377-4D0E-931B-3AC25BD09926}" Title="Announcements"
      Description="Use the Announcements list to post messages on the
         home page of your site."
      ImageUrl="/_layouts/images/itann.gif"
         Name="{8A98E2E5-B377-4D0E-931B-3AC25BD09926}"
      BaseType="0" ServerTemplate="104"
         Created="20030613 18:47:12" Modified="20030613 18:47:12"
      LastDeleted="20030613 18:47:12" Version="0" Direction="none"
         ThumbnailSize="" WebImageWidth=""
      WebImageHeight="" Flags="4096" ItemCount="1"
         AnonymousPermMask="" RootFolder="" ReadSecurity="1"
      WriteSecurity="1" Author="1"
         EventSinkAssembly="" EventSinkClass=""
         EventSinkData="" EmailInsertsFolder=""
      AllowDeletion="True" AllowMultiResponses="False"
         EnableAttachments="True" EnableModeration="False"
      EnableVersioning="False" Hidden="False" MultipleDataList="False"
         Ordered="False" ShowUser="True" />

In this result there are certain list nodes which contain the property serverTemplate="101". I'm trying to find the specific lists which have this template using jQuery find.
I have something like this: $(xData.responseXML).find("List").each(function() to get all the lists but how can I refine this to get all the lists which have the property serverTemplate="101"?

A: Use attribute equals selector
$(xData.responseXML).find('List[serverTemplate="101"]')


text:
Q: Output response from API post call - Javascript - 400 Bad Request I have a script that I want to use to make a api POST call to retrieve a access token, which I would like to output. It works in postman but within my script step I get a 400 error
I can only make post call, am i making a mistake not passing any data? Fell like I'm doing something wrong with the response.emphasized text
Postman
POST /incident/oauth2/token?grant_type=client_credentials& scope=%2Fincident HTTP/1.1
Host: APM-ext
API-KEY: 'xxx-xxx-xxx-xxx
Authorization: Basic  xxxxxxxxxxxxxxxxxxxxxxxxxxxx
cache-control: no-cache
Postman-Token: ee96a8af-dcfe-ffgr-8853-8ef83cd14845

Script
var incident = NO12345;
console.log(incident)

var apiRequest = http.request({
    'endpoint': 'APM-ext',
    'path':'/incident/oauth2/token?grant_type=client_credentials&scope=/incident',
    'API-KEY': 'xxx-xxx-xxx-xxx',
    'method': 'POST',
    "headers": {
    "Authorization": "Basic xxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    "Content-Type": "application/json"
    }
});

var data = {};
var apiResponse = apiRequest.write(data);

if (apiResponse.statusCode == 200) {

    var response = JSON.parse(apiResponse.body);
    output.access_token = response.access_token;
}

Expected Response (successful from postman)
{
    "token_type": "Bearer",
    "access_token": "00000044444444333333333333322222222222228888888888888885555555555555555",
    "expires_in": 3600,
    "consented_on": 1599709455,
    "scope": "/incident"
}

Actual Response (from script)
< HTTP/1.1 400 BAD_REQUEST Bad Request
< Content-Type: application/json
< Access-Control-Allow-Origin: *
< Access-Control-Expose-Headers: APIm-Debug-Trans-Id, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-Global-Transaction-ID
< X-Backside-Transport: FAIL FAIL
< Connection: close
{ "error":"unknown" }


text:
Q: ! not making important properties tailwind in svelte I am trying to make a box with display:block to display: flex. So I used tailwind and marked it as important by using !. But it is not working. I am using svelte in my project.
my code looks like this

to install tailwind I followed this tutorial
but it doesn't work


text:
Q: Identifying the conformal equivalence class of a 2-torus subgroup of the cubical 3-torus Let K, L, M be integers with gcd(K,L,M) = 1. They determine a connected Lie subgroup G = G(K,L,M) of the cubical 3-torus (ℝ/ℤ)3 via
G  =  {(x,y,z) ∊ (ℝ/ℤ)3  |  Kx + Ly + Mz = 0}
(where 0 denotes the identity element of ℝ/ℤ).
G is a 2-torus and inherits a Riemannian metric of everywhere zero Gaussian curvature from (ℝ/ℤ)3, which belongs to a unique conformal equivalence class of Riemann surfaces of genus 1 (or at most two such classes, depending on the choice of orientation of G).
As is well-known, every Riemannian flat 2-torus is conformally equivalent to the quotient  ℂ/L for some lattice L  =  ⟨1, ⟩ for some  in the set
X  =  {z ∊ ℂ  |  Im(z) > 0  and  |z| ≥ 1  and  |Re()| ≤ 1/2}.
Such a  is determined uniquely unless i ≠  ∊ ∂X, in which case the boundary points  and conj(-) correspond to the same class. Now suppose we have chosen an orientation for G.
In terms of (K,L,M), what is the parameter  corresponding to the Riemannian flat torus G ?  Equivalently, what is the j-invariant of G ?

A: This may be easier than I thought.  Assume WLOG that |K| ≥ |L| ≥ |M| with gcd(K,L,M) = 1 as above.
Then the subgroup H  ⊂  ℤ3 of integer translations of ℝ3 that preserves the 2-plane P, defined by
P  =  {(x,y,z) ∊ ℝ3  |  Kx + Ly + Mz  =  0}
(where 0 denotes 0) is generated by v = (-L,K,0) and w = (0,-M,L):
H  =  ⟨v, w⟩  ⊂  P
as a subgroup of P, which itself is a subgroup of ℝ3.  We can assume the counterclockwise angle in P from v to w is less then pi radians, and this condition will determine the orientation on P.
But the 2-torus in question is the quotient P / H.  Therefore the parallelogram generated by v = (-L,K,0) and w = (0,-M,L) is a fundamental domain in P for this group action.
Therefore the parameter  is determined a) by cos(angle(1,))  =  cos(angle(v,w)), where
cos(angle(v,w)  =  -KM / (√(K^2 + L^2) √(L^2 + M^2))
and b) by the condition that ||  =  ||v|| / ||w||, where
||v|| / ||w||  =  √(K^2+L^2) / √(L^2+M^2).

The above assumes that either division by zero is a valid operation, or else that the case (K,L,M) = (1,0,0) is excluded a priori as trivial.


text:
Q: Image cropper before uploading in laravel I am looking for any library in jQuery for image crop before upload. like: http://foliotek.github.io/Croppie/ but it makes images size 6 to 7 times bigger. i.e. image of 800kb would be upload of 7mb or 8mb.

A: There are a lot of libs to do that. Just need to google a little bit.
Some are:
https://github.com/supnate/icropper
https://github.com/fengyuanchen/cropperjs

A: You should use canvas image cropper.

A: Croppie
   $uploadCrop.croppie('result',
    {
        type: 'canvas',
        size: 'original',
        quality:  0.7,
        format: 'jpeg',
    }

A: With document **Image Cropper**

you may use it I used with laravel 5.6
http://odyniec.net/projects/imgareaselect/usage.html#styling-options


text:
Q: How to send location updates while device is idle using Android O? In my code sample, location updates are not sent on an Android O device when it goes into idle (doze) mode.  Has anyone gotten this to work? There are no issues on any devices prior to Android O (before API 26 added the location update throttling)
The code in question is here:
https://github.com/jcraw/api_26_location_updates_idle
The MainActivity binds to a foreground service which puts the location updates into logcat.
The code was tested as follows:

*

*Create virtual device (Pixel API 26)

*In the 'extended controls' for the virtual device, load and then start a GPX file

*Use power button on virtual device to disable screen

*adb shell dumpsys battery unplug

*adb shell dumpsys deviceidle step

*repeat step 5 until device is in IDLE state


text:
Q: .htaccess - remove query string from URL (no redirection) My URL is http://www.example.com/eg1?redirect=xyz, which should be http://www.example.com/eg1
The rewrite rule written for this is as follows:
RewriteCond %{Query_STRING} ^redirect=xyz$
RewriteRule ^(.*)$ /examples/$1? [L]

The redirection is working fine, but the query string remains appended. When i put [R] flag the question mark (?) at end works great and removes the query string, but with [L] flag its not working. And in my case I do not have redirection, just passing it to another directory which holds the content.

A: The rules are fine:
RewriteCond %{Query_STRING} ^redirect=xyz$
RewriteRule ^(.*)$ /examples/$1? [L]

If you want it to reflect at the address bar you will have to specify an external redirect. i.e. R with Temporary Redirect (R=302) or Permanent Redirect (R=301). Along with L. By default R does a temporary redirect.
RewriteRule ^(.*)$ /examples/$1? [R,L]

From comments:
Add L along with flsg R.
RewriteRule ^(.*)$ $1? [R,L]


text:
Q: Error when Sending Json data using Post I'm trying to add a new element using Post method, using the following function. But i'm getting error :

readyState=0, status =0 ,statusText=error.

So what could be the error, is it from the url, that I'm trying to send (I changed in the snippet)?

$('document').ready(function() {
  sendData();
});

function sendData() {
      console.log("start");
      var arr = { api_token: 'fb24085da58dad6decb9271fb170ef2ed8c80617',restaurantId : 500 ,name: 'cookies' ,img:'images'};

      $.ajax({
          url: 'http://URLChanged?api_token=fb24085da58dad6decb9271fb170ef2ed8c80617',
          type: 'POST',
          data: JSON.stringify(arr),
          contentType: 'application/json; charset=utf-8',
          dataType: 'json',
          async: true,

          success: function(response){
              console.log("success");
              console.log(JSON.stringify(response));
          },
          error: function(err){
              console.log("error");
              console.log(JSON.stringify(err));
          }
      });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

I'm getting in console this error :
XMLHttpRequest cannot load http://ChangedURL/restaurants/3/menus?api_token=fb24085da58dad6decb9271fb170ef2ed8c80617. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
testAjax.html:115 {"readyState":0,"status":0,"statusText":"error"}


text:
Q: ASP Search and Results in a single page I have a single Classic ASP page that I wish to display a search form and the associated results.
When a user first comes to this page, I want to display a search form and the 10 latest properties. If a user decides to use the search form to retrieve more relevant properties, then i want the default 10 latest properties to be replaced with the users' paged search results.
So far my code looks like this;

    <title>Search</title>

Search form

<form id="form1" name="form1" method="post" action="gist188770.asp">
Street: <input type="text" name="searchStreet" value="<%=Server.HtmlEncode(Request("searchStreet") & "") %>" />
Town: <input type="text" name="searchTown" value="<%=Server.HtmlEncode(Request("searchTown") & "") %>" />
<input type="submit" name="Submit" value="Submit" />
</form>

<%

if (Request.ServerVariables("REQUEST_METHOD") = "POST") then

'arrived via post get form values and do search
Dim myRecordSet
Dim myRecordSet_numRows

Set myRecordSet = Server.CreateObject("ADODB.Recordset")
myRecordSet.ActiveConnection = MM_dbconn_STRING

'collect the form input
set objDBParam = objDBCommand.CreateParameter("@ContentStreet",200,1,100)
    objDBCommand.Parameters.Append objDBParam
    objDBCommand.Parameters("@ContentStreet") = Request.QueryString("searchStreet")
set objDBParam = Nothing
set objDBParam = objDBCommand.CreateParameter("@ContentStreet",200,1,100)
    objDBCommand.Parameters.Append objDBParam
    objDBCommand.Parameters("@ContentTown") = Request.QueryString("searchTown")
set objDBParam = Nothing
set objDBParam = objDBCommand.CreateParameter("@ContentStreet",200,1,20)
    objDBCommand.Parameters.Append objDBParam
    objDBCommand.Parameters("@ContentPostcode") = Request.QueryString("searchPostcode")
set objDBParam = Nothing

'check for a match
myRecordSet.Source = "SELECT *"
myRecordSet.Source = myRecordSet.Source& "FROM ("
myRecordSet.Source = myRecordSet.Source& "SELECT id"
myRecordSet.Source = myRecordSet.Source& "FROM ("
myRecordSet.Source = myRecordSet.Source& "SELECT id"
myRecordSet.Source = myRecordSet.Source& "FROM VWTenantPropertiesResults"
myRecordSet.Source = myRecordSet.Source& "WHERE ContentStreet LIKE '%" & "@ContentStreet" & "%'"
myRecordSet.Source = myRecordSet.Source& "UNION ALL"
myRecordSet.Source = myRecordSet.Source& "SELECT id"
myRecordSet.Source = myRecordSet.Source& "FROM VWTenantPropertiesResults"
myRecordSet.Source = myRecordSet.Source& "WHERE ContentTown LIKE '%" & "@ContentTown" & "%'"
myRecordSet.Source = myRecordSet.Source& "UNION ALL"
myRecordSet.Source = myRecordSet.Source& "SELECT id"
myRecordSet.Source = myRecordSet.Source& "FROM VWTenantPropertiesResults"
myRecordSet.Source = myRecordSet.Source& "WHERE ContentPostCode LIKE '%" & "@ContentPostcode" & "%'"
myRecordSet.Source = myRecordSet.Source& ") qi"
myRecordSet.Source = myRecordSet.Source& "GROUP BY"
myRecordSet.Source = myRecordSet.Source& "id"
myRecordSet.Source = myRecordSet.Source& "HAVING COUNT(*) >= 2"
myRecordSet.Source = myRecordSet.Source& ") q"
myRecordSet.Source = myRecordSet.Source& "JOIN VWTenantPropertiesResults r"
myRecordSet.Source = myRecordSet.Source& "ON r.id = q.id"
myRecordSet.Source = myRecordSet.Source& "WHERE ContentBedrooms BETWEEN 1 AND 4"
myRecordSet.Source = myRecordSet.Source& "AND ContentPrice BETWEEN 50 AND 500"
myRecordSet.Source = myRecordSet.Source& "ORDER BY"
myRecordSet.Source = myRecordSet.Source& "ContentPrice"

'display the results
if myRecordSet.BOF then
response.write("Latest properties:
")
do until myRecordSet.EOF
%>

")

<%=myRecordSet("ContentTitle")%>

<%=myRecordSet("ContentStreet")%>

<%=myRecordSet("ContentTown")%>

<%=myRecordSet("ContentPostcode")%>

<%
myRecordSet.MoveNext
loop
end if

else
    'arrived via get show last 10 results
    Dim myRecordSet2
    Dim myRecordSet2_numRows

    Set myRecordSet2 = Server.CreateObject("ADODB.Recordset")
    myRecordSet2.ActiveConnection = MM_dbconn_STRING
    myRecordSet2.Source = "SELECT TOP 10 FROM VWTenantPropertiesResults ORDER BY ContentPrice"

    'display the results
    if myRecordSet2.BOF then
    do until myRecordSet2.EOF
    %>

")

<%=myRecordSet2("ContentTitle")%>

<%=myRecordSet2("ContentStreet")%>

<%=myRecordSet2("ContentTown")%>

<%=myRecordSet2("ContentPostcode")%>

<%
    myRecordSet2.MoveNext
    loop
end if

end if
%>

But when I view the page, I get the following error;
ADODB.Recordset error '800a0e78'

Operation is not allowed when the object is closed.

/welcome/gist188770.asp, line 98

Line 98 is as follows;
if myRecordSet2.BOF then

I wondered if anyone might be able to help me solve this issue? Thank you for any help offered.
Neil.

A: You haven't opened the recordset at the point of you using BOF.
In addition you are creating a command object but not assigning the SQL text to it instead you are assigning the sql text directly to the recordset.
You sould assign the SQL to the CommandText property of the command object and then retrieve a recordset by calling the Command objects Execute method.
Edit:
More stuff that needs fixing
Your SQL concatentation doesn't include any vbCrLf or whitespace on the end of each line.  The SQL will not execute.
Do not assign connection string directly to ActiveConnection, whilst that works ADODB doesn't manage connection pooling correctly doing it that way.  Always instance a Connection object and assign that to the ActiveConnection property.
Edit 2:
Yet another issue
Your code is accessing the criteria from the Request.QueryString yet your form element specifies method="post" in which case you should be using Request.Form instead.


text:
Q: Entity Framework 7 DbContext OnModelCreating specify foreign key for ApplicationUser field I am trying to achieve something very similar to what is happening in this EF7 fluent API documentation, but it is not the exact case.
I have a model that looks like this:
public class BlogPost
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
    public string CreatedBy {get; set; }

    public ApplicationUser CreatedByUser { get; set; }
}

My ApplicationUser class does not have anything related to BlogPost in it. So the connection doesn't really need to go both ways.
Can someone tell me how for my situation how I can tell entity framework that I want to populate CreatedByUser when using Include based on the CreatedBy field in BlogPost equaling the Username field in AspNetUsers table?
Here is what I want to be able to do in my repository:
using (var blogContext = new BlogContext())
{
  return blogContext .BlogPosts
    .Include(bp => bp.CreatedByUser)
}

This is my best attempt:
protected override void OnModelCreating(ModelBuilder builder)
{
    builder.Entity<BlogPost>()
        .HasOne(fp => fp.CreatedByUser)
        .WithMany()
        .HasForeignKey(fp => fp.CreatedBy)
        .IsRequired();
}

I feel like the trick here is not adding a parameter to .WithMany() since in my model I do not have a List property inside of my ApplicationUser model.
The main thing that is causing me issues is that by default EF is trying to use the Id field as the key in the AspNetUsers table. I want to tell it to use Username as the key, not the guid.

A: I figured out a solution that is working perfectly on my end.
Here is the Fluent API code that needs to be put in your DbContext file in order to get this to work:
protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);

    // Need to do this because if using as a foreign key it must match the length of the principal key
    builder.Entity<BlogPost>()
        .Property(fp => fp.CreatedBy)
        .HasMaxLength(256);

    // A BlogPost has one CreatedByUser (notice we must specify the PrincipalKey to be UserName from the AspNetUsers table otherwise EF would attempt to use the Id (Guid) field by default)
    builder.Entity<BlogPost>()
        .HasOne(bp => bp.CreatedByUser)
        .WithMany()
        .HasForeignKey(bp => bp.CreatedBy)
        .HasPrincipalKey(u => u.UserName)
        .IsRequired();
}

Then in my repository I can simply do the following to make sure CreatedByUser is bound:
public IEnumerable<BlogPost> GetBlogPosts()
{
    return _context.BlogPosts
    .Include(bp => bp.CreatedByUser)
    .ToList();
}

Here is what my models look like:
public class BlogPost
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
    // Foreign Key
    public string CreatedBy { get; set; }
    // Navigation Property
    public ApplicationUser CreatedByUser { get; set; }
}

public class ApplicationUser : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Since almost all of my objects have a CreatedBy field where I will need to obtain the entire User to be able to display things like FirstName, LastName, Email in my Views I am assuming I will be doing this a lot. I will probably rarely ever need to retrieve a list of any of my entities through the user, but if I did I would add a List MyObjects to ApplicationUser model and then specify something in the .WithMany(b => b.MyObjects) params.
If anyone has any feedback or additional comments please let me know.


text:
Q: Unable to find button element SELENIUM I have the following code for a button :
HTML CODE :

<button type="button" i-id="logout-ok">确定</button>
<button type="button" i-id="logout-cancel" class="cancel">取消</button>

CODE using Xpath as inspect :
element  = driver.findElement(By.xpath("/html/body/div[7]/div/table/tbody/tr[3]/td/div[2]/button[1]")).click();

I have try to use
 element =
driver.findElement(By.cssSelector("button.logout-ok")).click();

It seems not working for , Kindly advise from my mistake . Thanks you

A: please try with the xpath as below
driver.findElement(By.xpath("//button[@i-id='logout-ok']")).click();

Hope it will help you :)


text:
Q: Object inside an object in React Native I'm getting an odd error with object inside an object in React Native. I set some state variables in my constructor:
this.state = {
   payAmount: 0,
   selectedPaymentMethod: 0,
   btnDisabled: true,
   cardDetails: {
     cardName: '',
     cardNumber: '',
     cardCVV: '',
     cardExpiration: '',
     cardPostalCode: ''
   }
};

Then, when I try to access "cardDetails", it returns Can't find variable: cardName
Code:
const data = { cardName, cardNumber, cardCVV, cardExpiration, cardPostalCode } = this.state.cardDetails;

Can't I use object inside an object in react native?
Thank you!

A: const { cardName, cardNumber, cardCVV, cardExpiration, cardPostalCode } = this.state.cardDetails;

and yes, You can create object inside object.


text:
Q: re.sub is replacing the text in my file with blanks. Not sure why Recently tried some revisions to see if my I could trace down the issue and see if my regex string was even being matched. No luck on the match, however I am not certain it's all correct. Top code is most recent.
import os
import re

progNumber = 1
text_to_replace = re.compile("^BOWL_PROG6_14G$")
replace_string = 'Bowl_Prog1'

def sub_ftext(file_path='W:\\BOWL PROGRAMS 14G'):
    old_text = text_to_replace
    count = progNumber
    for d_name, dirs, files in os.walk(file_path):
        for f_name in files:
            f_path = os.path.join(d_name, f_name)
            if f_name.endswith('.ls'):
                with open(f_path) as txt:
                    s = txt.read()
                    for line in txt:
                        if text_to_replace.search(line):
                        # Substitute the contents
                            new_text = replace_string + str(count)
                            s = re.sub(old_text, new_text, s)
                            # Write it back into the file
                            with open(f_path, "w") as txt:
                                txt.write(s)
                            count += 1
                            print(s)
                            print(old_text)

     # for text in text_to_replace:
     #        print(text)
        # dirnames = set(os.path.join(d_name, d) for d in dirs)
        #     # Traverse subfolders
        # if dirnames.startwith('BOWL-'):
        #     for subs in dirnames:

sub_ftext()

`The program finds the string I am looking for but replaces it with nothing in every file.
import os
import re

os.chdir('W:\\BOWL PROGRAMS 14G')
progNumber = 1
text_to_replace = re.compile("^BOWL 14G$")
replacement = ("Bowl_Prog_14G" + str(progNumber))

for d_name, dirs, files in os.walk("."):
    for f_name in files:
        f_path = os.path.join(d_name, f_name)
        if f_name.endswith('.ls'):
            with open(f_path) as txt:
                for line in txt:
                    s = txt.read()
            #s = s.replace(text_to_replace, replacement)
            with open(f_path, "w") as txt:
                txt.write(s)
                print(re.sub(text_to_replace, replacement, line))
                progNumber += 1

A: Just some minor touch-ups to your existing code. You don't really need to substitute the contents line by line, hence I have removed that line.
import os
import re

progNumber = 1
text_to_replace = re.compile("^BOWL_14G$")

def sub_ftext(file_path, text_to_replace, progNumber):
    for d_name, dirs, files in os.walk(file_path):
        for f_name in files:
            replacement = ("Bowl_Prog_14G" + str(progNumber))
            f_path = os.path.join(d_name, f_name)

            if f_name.endswith('.ls'):
                with open(f_path) as txt:
                    sl = txt.read()
                # Substitute the contents
                sl = re.sub(text_to_replace, replacement, sl)
                # Write it back into the file
                with open(f_path, "w") as txt:
                    txt.write(sl)

                progNumber += 1

    # Traverse subfolders
    dirnames = set(os.path.join(d_name, d) for d in dirs)
    if dirnames:
        for subs in dirnames:
            sub_ftext(subs, text_to_replace, progNumber)

if __name__ == '__main__':
    sub_ftext(r'C:\Documents\TestFolder', text_to_replace, progNumber)

Edit: If you need to traverse the subfolders as well, one way to do it is to wrap the lines above up into a function, which you can then call recursively. There are probably other ways to do it as well

A: import os
import re

def sub_text(file_path):
    os.chdir(file_path)
    prog_number = 1
    text_to_replace = re.compile("BOWL_PROG[0-9]*_14G")
    for d_name, dirs, files in os.walk("."):
        for f_name in files:
            replacement=("Bowl_Prog" + str(prog_number))
            f_path = os.path.join(d_name, f_name)
            if f_name.endswith('.ls'):
                with open(f_path) as line:
                        ls = line.read()
                with open(f_path, "w") as line:
                        ls = re.sub(text_to_replace, replacement, ls)
                        line.write(ls)
                        print(line)
                        prog_number += 1
                        print(prog_number)
                        print(replacement)

if __name__ == '__main__':
    sub_text(r"W:\\BOWL PROGRAMS 14G")


text:
Q: Can prometheus don't resolve alert when metric data missing? There is my Prometheus alert rule
avg_over_time(metricName[1m]) > 100
After alert fired, when the metrci data missing for more than 1 minute, the alert will resolved.
Is there any way to stop the change of alert status?

A: You can do this by leveraging last_over_time() as in my answer here.
(Answering this old question because it's still a high ranking Google result)


text:
Q: hover not working on div element with textarea without using z-index I couldn't get the div values while hover that element.

helo

<textarea style="width:150px;height:150px;position:relative;background:none;"></textarea>

how to get that test id value when hover that text ( without giving z-index to textarea) ?

A: See if that's what you're wanting to happen :

var s_val = document.getElementById("span").innerHTML;
var tArea = document.getElementById("test");

tArea.addEventListener("mouseover", function test(){
    alert(s_val);
    });
#main {
  width:150px;
  height:150px;
  position:absolute;
  background: none 0% 0% / auto repeat scroll padding-box border-box rgb(255, 255, 255);
}

#test {
  width:150px;
  height:150px;
  position:relative;
  background:none;
}

  helo

<textarea id="test"></textarea>

Just get the value of the  using the innerHTML event (stored into a var for better view) and call it on the alert().


text:
Q: How to align box items so buttons I want to align the buttons but the 2 line text makes it different than the 1 line text. Can anyone help me?

A: You can achieve this if you set display: flex on your cards and then add the magic margin-top: auto to your button.
I recreated your Code:

.container{
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-items: stretch;
  gap: 4em;
  width: 100%;
}

article{
  display: flex;
  flex-direction: column;
  background: lightgray;
  padding: 1em;
  min-width: 200px;
  max-width: 200px;
}
button{
  margin-top: auto; /* the magic */
}

title title title title title title title

      <button>Button</button>

title

      <button>Button</button>

title

      <button>Button</button>

title

      <button>Button</button>

A: maybe using flex-box and set flex-end style to your button and flex-start to your text will help you.


text:
Q: STM32F746G-Disc code examining QSPI flash data transfer consecutively fail/pass by resetting MCU Programming STM32F746 MCU with below code (read and write, then compare on N25Q128A NOR flash memory) result change after each time resetting MCU by it's botton or under debug session:
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_QUADSPI_Init();
  /* USER CODE BEGIN 2 */

  QSPI_CommandTypeDef sCommand;
  uint32_t address = 0;
  uint8_t BUFFERSIZE=20;
  uint8_t txbuf[20]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
  uint8_t rxbuf[20]={0};

//  QSPI_ResetMemory(&hqspi);
//  HAL_Delay(100);

  sCommand.InstructionMode   = QSPI_INSTRUCTION_1_LINE;
  sCommand.AddressSize       = QSPI_ADDRESS_24_BITS;
  sCommand.AlternateByteMode = QSPI_ALTERNATE_BYTES_NONE;
  sCommand.DdrMode           = QSPI_DDR_MODE_DISABLE;
  sCommand.DdrHoldHalfCycle  = QSPI_DDR_HHC_ANALOG_DELAY;
  sCommand.SIOOMode          = QSPI_SIOO_INST_EVERY_CMD;

  QSPI_DummyCyclesCfg(&hqspi);

/*******Erase sequence*********/
  QSPI_WriteEnable(&hqspi);
  sCommand.Instruction = SECTOR_ERASE_CMD;
  sCommand.AddressMode = QSPI_ADDRESS_1_LINE;
  sCommand.Address     = address;
  sCommand.DataMode    = QSPI_DATA_NONE;
  sCommand.DummyCycles = 0;
  HAL_QSPI_Command(&hqspi, &sCommand,HAL_QPSI_TIMEOUT_DEFAULT_VALUE);
  HAL_Delay(100);//HAL_QSPI_Abort(&hqspi);
  /***********Transmission sequence***********/
  QSPI_WriteEnable(&hqspi);
//  HAL_Delay(50);//HAL_QSPI_Abort(&hqspi);
  sCommand.Instruction = QUAD_IN_FAST_PROG_CMD;
  sCommand.AddressMode = QSPI_ADDRESS_1_LINE;
  sCommand.DataMode    = QSPI_DATA_4_LINES;
  sCommand.NbData      = BUFFERSIZE;
  HAL_QSPI_Command(&hqspi, &sCommand, HAL_QPSI_TIMEOUT_DEFAULT_VALUE);HAL_Delay(100);
  HAL_QSPI_Transmit(&hqspi, txbuf,1000000);
  HAL_Delay(40);//HAL_QSPI_Abort(&hqspi);
  /***********Reception sequence***********/
//  QSPI_DummyCyclesCfg(&hqspi);
  sCommand.Instruction = QUAD_OUT_FAST_READ_CMD;
  sCommand.DummyCycles = DUMMY_CLOCK_CYCLES_READ_QUAD;
  //sCommand.NbData      = BUFFERSIZE;
  HAL_QSPI_Command(&hqspi, &sCommand, HAL_QPSI_TIMEOUT_DEFAULT_VALUE);
  HAL_QSPI_Receive(&hqspi, (uint8_t*)rxbuf,1000000);
  HAL_Delay(100);
  HAL_Delay(1);
//  HAL_Delay(100);//HAL_QSPI_Abort(&hqspi);

  /************Test result********/
  uint8_t index=0;
  for (index = 0; index < BUFFERSIZE; index++)
            {
              if (rxbuf[index] != txbuf[index])
              {
                HAL_GPIO_WritePin(LED_GPIO_Port,LED_Pin,GPIO_PIN_SET);
              }
            }
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

static void QSPI_WriteEnable(QSPI_HandleTypeDef *hqspi)
{
  QSPI_CommandTypeDef     sCommand;
  QSPI_AutoPollingTypeDef sConfig;

  /* Enable write operations ------------------------------------------ */
  sCommand.InstructionMode   = QSPI_INSTRUCTION_1_LINE;
  sCommand.Instruction       = WRITE_ENABLE_CMD;
  sCommand.AddressMode       = QSPI_ADDRESS_NONE;
  sCommand.AlternateByteMode = QSPI_ALTERNATE_BYTES_NONE;
  sCommand.DataMode          = QSPI_DATA_NONE;
  sCommand.DummyCycles       = 0;
  sCommand.DdrMode           = QSPI_DDR_MODE_DISABLE;
  sCommand.DdrHoldHalfCycle  = QSPI_DDR_HHC_ANALOG_DELAY;
  sCommand.SIOOMode          = QSPI_SIOO_INST_EVERY_CMD;

  if (HAL_QSPI_Command(hqspi, &sCommand, HAL_QPSI_TIMEOUT_DEFAULT_VALUE) != HAL_OK)
  {
    Error_Handler();
  }

  /* Configure automatic polling mode to wait for write enabling ---- */
  sConfig.Match           = 0x02;
  sConfig.Mask            = 0x02;
  sConfig.MatchMode       = QSPI_MATCH_MODE_AND;
  sConfig.StatusBytesSize = 1;
  sConfig.Interval        = 0x10;
  sConfig.AutomaticStop   = QSPI_AUTOMATIC_STOP_ENABLE;

  sCommand.Instruction    = READ_STATUS_REG_CMD;
  sCommand.DataMode       = QSPI_DATA_1_LINE;

//  if (HAL_QSPI_AutoPolling(hqspi, &sCommand, &sConfig, HAL_QPSI_TIMEOUT_DEFAULT_VALUE) != HAL_OK)
//  {
//    Error_Handler();
//  }
}

/***********************************************/

static void QSPI_DummyCyclesCfg(QSPI_HandleTypeDef *QSPIHandle)
{
  QSPI_CommandTypeDef sCommand;
  uint8_t reg;

  /* Read Volatile Configuration register --------------------------- */
  sCommand.InstructionMode   = QSPI_INSTRUCTION_1_LINE;
  sCommand.Instruction       = READ_VOL_CFG_REG_CMD;
  sCommand.AddressMode       = QSPI_ADDRESS_NONE;
  sCommand.AlternateByteMode = QSPI_ALTERNATE_BYTES_NONE;
  sCommand.DataMode          = QSPI_DATA_1_LINE;
  sCommand.DummyCycles       = 0;
  sCommand.DdrMode           = QSPI_DDR_MODE_DISABLE;
  sCommand.DdrHoldHalfCycle  = QSPI_DDR_HHC_ANALOG_DELAY;
  sCommand.SIOOMode         = QSPI_SIOO_INST_EVERY_CMD;
  sCommand.NbData            = 1;

  if (HAL_QSPI_Command(QSPIHandle, &sCommand, HAL_QPSI_TIMEOUT_DEFAULT_VALUE) != HAL_OK)
  {
    Error_Handler();
  }

  if (HAL_QSPI_Receive(QSPIHandle, &reg, HAL_QPSI_TIMEOUT_DEFAULT_VALUE) != HAL_OK)
  {
    Error_Handler();
  }

  /* Enable write operations ---------------------------------------- */
  QSPI_WriteEnable(QSPIHandle);//optional

  /* Write Volatile Configuration register (with new dummy cycles) -- */
  sCommand.Instruction = WRITE_VOL_CFG_REG_CMD;
  MODIFY_REG(reg, 0xF0, (DUMMY_CLOCK_CYCLES_READ_QUAD << POSITION_VAL(0xF0)));

  if (HAL_QSPI_Command(QSPIHandle, &sCommand, HAL_QPSI_TIMEOUT_DEFAULT_VALUE) != HAL_OK)
  {
    Error_Handler();
  }

  if (HAL_QSPI_Transmit(QSPIHandle, &reg, HAL_QPSI_TIMEOUT_DEFAULT_VALUE) != HAL_OK)
  {
    Error_Handler();
  }
  HAL_Delay( 40 );
}

Actually in first run rxbuff fills correctly after reset it returns just 1 on every bit but after reset again everything is ok and it repeats!!
I've doubled receive commands and buy debugging understood that unprogrammed bytes are all 1 and maybe the program or write commands are not working after each they execute correctly at the same address.

A: After erasing sequence HAL_Delay(400); has been placed and problem has been vanished. It mean erasing operasion was needing more time!

A: The datasheet says sector erase can take up to 3 seconds, so yes, obviously 100ms or even 400ms may not be enough.
Either, use a long enough delay, or, poll when the operation is complete, maybe with timeout to see if an operation fails.


text:
Q: Setting collection view layout to compositional layout using storyboard How would I be able to change collection view flow layout to a compositional layout from storyboard. So I have a TabBarController class that contains 3 nav controllers that I init from storyboard looks like this.
//Storyboard is an enum that contains strings IDs that belong to controllers from main storyboard.
private func createNewViewController(storyboardIdentifier: Storyboard.Controller) -> UIViewController {
    let controller = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: storyboardIdentifier.indentifer)

    return controller
}

This is how I add the controllers to the tab bar controller.
viewControllers = [
        SearchCollectionVC(),
        //createNewViewController(storyboardIdentifier: .searchNav),
        createNewViewController(storyboardIdentifier: .todayNav),
        createNewViewController(storyboardIdentifier: .appsNav)

    ]

If I try to add my SearchCollectionVC with the commented line my app crashes. It executes the line fatalError() in the required init from the SearchCollectionVC. This is how I create the layout.
init() {
    super.init(collectionViewLayout: SearchCollectionVC.createCollectionLayout())
}

required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

static func createCollectionLayout() -> UICollectionViewCompositionalLayout {
    let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .fractionalHeight(1))
    let item = NSCollectionLayoutItem(layoutSize: itemSize)

    let grupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(250))
    let group = NSCollectionLayoutGroup.horizontal(layoutSize: grupSize, subitems: [item])

    let section = NSCollectionLayoutSection(group: group)
    section.interGroupSpacing = 20

    let layout = UICollectionViewCompositionalLayout(section: section)

    return layout
}

Now I tried doing this in the SearchCollectionVC viewDidLoad().
collectionView.collectionViewLayout = SearchCollectionVC.createCollectionLayout()

This works with the comment line and without the init. The thing is when I rotate the screen this happens.

This doesn't happen when I add the controller using SearchCollectionVC() and when using the init. Now, I don't know why this is happening. Can someone please let me know how would I be able to init a storyboard controller and change the layout to the compositional layout I created, without having the collection view getting cut in half.Thanks

A: Just found out how to do. Had to create a new collection view like this.
 collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: SearchCollectionVC.createCollectionLayout())