text:
Q: When did initial-origin words (PRONOUNCED AS WORDS) start happening? Someone was just asking if there were words like lol formed, before, the txtmsg era.
Of course there were - for example "laser".
However .. in fact what was the earliest example of this in English?
Words pronounced as full words - but which started as initials or the initial parts of a series of words.
What is the earliest example of a word like "radar"?
Is there anything like "laser" (laser: 1960) before, let's say, the electric era?  Just a wild guess -- did this fad perhaps start with WW2?
So where and when did this begin in English, and what is the earliest example?

Note -- here's a somewhat related question, but the information there is utterly useless. It's astounding that people can't grasp the difference between laser or lol, and, CIA or INRI.

A: See: Wikipedia for a good discourse on the historical use of acronyms. I knew the Catholic church used the acronym INRI on top of the crucifix for at least 500 to 600 years. A qoute from the Wikipedia article: "Acronyms were used in Rome before the Christian era. For example, the official name for the Roman Empire, and the Republic before it, was abbreviated as SPQR (Senatus Populusque Romanus). "

A: Edit: Updated Answer
After more research, I verified that the OED does observe the distinction between initialisms and acronyms, invited by the distinct senses (in the OED) of 'initialism' and 'acronym' (as abbreviations pronounced as individual letters in the former, and abbreviations pronounced as words in the latter), in its Etymology notes. I respect that distinction in this answer.
That verity enabled the simplification of research into the earliest acronyms appearing in the OED. In the following historical breakdown, I only include words with clear, unequivocated acronymic etymologies. Thus,
Of words originating in English between c1000 and 1600, no acronyms appear in the OED.
Of words originating in English between 1600 and 1800, the noun 'abjad' is undoubtedly an acronym. It derives from the Arabic word 'abjad' (also acronymic), denoting the Arabic alphabet: the word is an acronymic abbreviation formed from the initial letters of the names of the first four letters of the Arabic alphabet. The first textual evidence of its use appeared in 1793:

1793   C. F. Greville Brit. India Analyzed I. 87   The first letter of the month Ahmudee is Alif, which, in the Abjud, stands for 1.

(op. cit.)
Thus, 'abjad' has the honor of being the earliest acronym in English documented by the OED. No other serious contenders for the earliest acronym were to be found in that period (1600-1800).
Being curious, I continued the exercise.
Of words originating between 1800-1900, there are several acronyms. In historical order, those are 'Tanach' (1835), 'SCOTUS' (1879), 'OUDS' (1885), 'AWOL' (1894), and 'POTUS' (1895).
A further search for acronymic words originating between 1900-2000 returned 287 results. I did not visit each entry (as I did for the earlier, more managable quantities of results) to verify that the reference to 'acronym' in the Etymology was clear and unequivocal, and to verify the date of the earliest acronymic use of the word.
Original answer
The question invites argument: "the earliest example" in the question could resolve as the date the abbreviation was first pronounced as a word, or the first recorded appearance of the abbreviation later to be pronounced as a word. If the former, how is that date to be documented?
Anyway, I'll throw a word into the ring:

AWOL, n. and adj.
...
1894   Rep. National Home for Disabled Volunteer Soldiers in Misc. Documents House of Representatives 1894-5 (1895) 431   November 25: Patient left the ward this date without leave. December 5: Patient returned from A. W. O. L.

(op. cit.)
Note that the OED distinguishs 'acronym' and 'initialism' on the basis of whether or not each letter or part is pronounced separately: for initialisms each letter or part is pronounced separately; acronyms, on the other hand, may have each letter or part pronounced separately or the whole may be pronounced as a single word.
Thus, my rather shaky assumption is that where the OED gives an etymology as "acronym" or "initialism", it maintains that distinction. This assumption is supported by the etymology given for 'awol':

Etymology: As noun, acronym < the initial letters of absence without leave ....
In early use sometimes an initialism; compare quot. 1949 at sense B. 2, and also:
1921   Outing June 137/1, I was surprised to find one day that unless I left the following morning to rejoin my regiment I would be an 'a-w-o-l'.
1957   B. Evans & C. Evans Dict. Contemp. Amer. Usage 9/2   awol..in World War I..was pronounced as four letters; in World War II, it was pronounced as a word.

(op. cit., italics mine)
Rather than helping, however, the OED's distinction leaves the question of when an initialism first becomes an acronym up in the air. Presumably, the question is unresolved because documentation will rarely answer it, and because the question is extraneous to the OED's primary concern with when the acronym/initialism was first recognizably used as a noun (adjective, whatever) as documented in textual records.
For somewhat hesitant and possibly unreliable support of my claim that awol was the first or among the first acronyms, as well as a disquisition emphasizing the distinction between acronyms and initialisms, see "Acronyms that became words".

A: An acronym is an abbreviation (or intialism) that's pronounced as a word. They're a relatively modern invention; there are a few earlier examples, but their use really took off during WWII.
INRI?
INRI may be old, but when was INRI introduced into the English language? What evidence is there for people pronouncing it as "inree" in the English language?

WWI
In Douglas Harper's rebuke, '"shit" is not an acronym', he writes that acronyms are very modern inventions. They were found in World War I, but still weren't the preferred way of abbreviation. Their use really took off and became common during World War II, and really accelerated during the cold war and US space programme.
He also notes the use of acrostics, a poem or puzzle such as cabal, where the first initial of an existing word is made of other significant words. However, Harper argues this wordplay had been around for centuries and they aren't really acronyms: the root word already existed and no-one was pretending the initials were the source.
Read the interesting article for more, here's a brief snippet:

Acronyms didn't becom a common method of word formation in English until World War II. The word acronym itself wasn't coined until 1943. The lack of a need for such a word suggests the degree to which acronyms previously were not a part of daily life. Their use accelerated with the U.S. space program and the Cold War, and by the time a "Dictionary of Acronyms, Initialisms and Abbreviations" was published in 1960 it had 12,000 entries.
...
So acronyms in English are on the whole a 20th century phenomenon. Among those with pre-1900 origins are A.D. and B.C. (both Latin) and P.D.Q. (1870s). The word OK (c.1839) is another rare exception (if the most accepted theory of its origins is the right one), as is n.g. for "no good" (1838). And note how these initialisms, even after more than 170 years, are still "felt" as abbreviations, pronounced as distinct letters, and require no elaborate Internet stories.

POTUS & SCOTUS
There are at least a couple of acronyms pronounced as words which predate World War I: POTUS (President of the United States) and SCOTUS (Supreme Court of the United States), from the Phillips Code used "for the rapid transmission of press reports by telegraph", are from 1895 and perhaps 1879. I'd guess that they weren't originally pronounced as words, but they are now.

A: I think @PaulDrye had the right instinct in his comment. As a Russian student, I strongly associate initialisms with Communist-era propaganda; they were the bread and butter of the political vocabulary of the Soviet Union.
However, this interesting source suggests there was a diachoric development of this phenomenon in the wake of the historical events of the early twentieth century, namely World War I (1914-1919), the Russian Revolution (1917-1920), and Roosevelt's New Deal (1930s): "The Bolshevik revolution brought about flourishing of acronyms of the syllabic type (Sovnarkom 'soviet narodnykh komissarov', 'soviet of people's commissar', Sovkhoz 'sovietsko'r'e khoziaistvo', 'soviet agrarian explotation'). Abbreviations like Comintern have been widely accepted around the world, thanks to the influence of the former Communist Party. President Franklin Roosevelt's programs spawned a torrent of "alphabet soup" that named agencies like NRA 'National Recovery Administration' [!]" (267). Rodriguez and Cannon go on to document an "explosive" growth in the use of initialisms and abbreviations around the world after World War II. They then give a very eloquently-presented linguistics of initialisms and abbreviations in English. For a comprehensive answer to your question, I can give you no better than this source, viz.:

Félix Rodriguez and Garland Cannon, 'Remarks on the Origin and
  Evolution of Abbreviations and Acronyms', in F. Fernández, et al.,
  eds., English Historical Linguistics 1992: Papers from the 7th
  International Conference on English Historical Linguistics, Valencia,
  22-26 September, 1992 (Amsterdam, 1994), pp. 262-72.

I also learned from this source that "sigla" may be another name for the type of constructed therm you're talking about; sigloe are "abbreviations formed by initials under new forms" (265).  Another interesting note:
"initials can either become words formed by literation, i.e. receive a letter-by-letter pronunciation (alphabetisms or initialisms), or else turn into orthoepically pronunced acronyms" (266). So it seems, at least according to this source, that the terms you're describing are more properly "acronyms" than "alphabetisms"/"initialisms." (For more notes on this taxonomy, see Algeo, John, 1975, "The acronym and its congeners," in The First LACUS Forum, 1974, ed. Adam Makkai and Valerie B. Makkai, pp. 217–234, and López Rúa, Paula 2004 Acronyms & Co.: A typology of typologies. Estudios Ingleses de la Universidad Complutense 12: 109−129. I have identified these two sources as interesting based on a quick read, but there are potentially lots of others; this seems to be a popular topic in linguistics indeed.)


text:
Q: Mongoose disconnecting after all save operations done I'm making save operations in loop. (I'm not collecting those promises, and not waiting for all saves to finish)
How do I disconnect from the db after all operations done?
I wanna do something like this:

Don't have enough memory to collect those promises

A: You can use .disconnect() to close the connection to from mongoose. See https://mongoosejs.com/docs/api.html#mongoose_Mongoose-disconnect
Regarding tracking when operations are done - that's what the promises are for.
A simple way to ensure every item has been created, would be something like:
var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
const Schema = mongoose.Schema;

const schema = new Schema({
  name: Number,
});
const model = mongoose.model('test', schema);

async function run() {
  mongoose.connect(`mongodb://localhost/test`);
  for (let i = 0; i < 1000; i++) {
    await model.create({ name: i });
  }
  mongoose.disconnect();
}

run()
  .then(() => {
    console.log('completed exec');
  })
  .catch((err) => {
    console.error('Error during exec', err);
  })

This is not a great implementation, but it gets the job done.
Things you should look into are:

*

*could you batch requests? eg. use insertMany

*Errorhandling/continueability - what happens if one fails during the run? Should we stop or continue, but log the error?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Calculating pressure drop speed in automation system I have a problem. How would you calculate pressure drop speed, if you only get data from a manometer? I need a specific drop speed in [bar/h], and can only read pressure in [bar]. I can't think of a way I can do that in my software, except for sampling measurement in some sample rate and than use dp=p(i-1)-p(i). Thanks in advance.

A: I agree with you, that the only way to get a pressure rate over time would be to sample the pressure, and calculate the rate that would be meaningful to your user.  This could be a rate between two samples, or the "best fit" line of a sample using linear regression. Any rate is really a slope.
I don't have enough REP to post a picture, so see this best fit line example here:
http://2.bp.blogspot.com/-d4LyN1FgyYc/T54PTebg3xI/AAAAAAAAYa8/aBNyp_pC7vQ/s1600/weightLossLinearRegression.JPG
You can think of it in terms of your car.  Your car provides you an instantaneous rate (Mi/h) and some newer cars will provide a rate over time, in the form of your average speed since you last reset the logging.


text:
Q: When does stripe actually deduct money from credit card I am new in payment gateway; I can't seem to figure out when does a payment actually gets deducted. So once the all card details are successfull the code below gets executed:
public partial class Charge : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e) {
        if (Request.Form["stripeToken"] != null)
        {
            var customers = new StripeCustomerService();
            var charges = new StripeChargeService();

            var customer = customers.Create(new StripeCustomerCreateOptions
            {
                Email = Request.Form["stripeEmail"],
                SourceToken = Request.Form["stripeToken"]
            });

            var charge = charges.Create(new StripeChargeCreateOptions
            {
                Amount = 500,
                Description = "Sample Charge",
                Currency = "usd",
                CustomerId = customer.Id
            });

            Console.WriteLine(charge.Id);
        }

    }
}

what I noticed is that if I enter and email of test@gmail. without the "com" in the end, the code above gets executed, but it will say the email is invalid on Email = Request.Form["stripeEmail"].
so the question is does the money gets deducted when I get the token Request.Form["stripeToken"] or the money gets charged/deducted when I created a Charge via:
var charge = charges.Create(new StripeChargeCreateOptions
{
    Amount = 500,
    Description = "Sample Charge",
    Currency = "usd",
    CustomerId = customer.Id
});

A: When using Stripe you create a token first either on its own, or as part of a customer object. This token is only a reference to the card details. The token ID on its own is not enough to do anything with the card, Stripe just stores the encrypted card details.
When you issue the charge, this is when you say which card need to be charged with what amount. Prior to this the card details haven't even left Stripe's domain.
The reason you get this error on Charge is simple - email only gets validated at that point. Prior to that it's the card details that get validated and stored as a token.


text:
Q: Why can't I view or add SQL and Network Performance Counters in Performance Monitor? I'm trying to add the below Performance Counters to a user-defined data collector set in a Performance Monitor on Windows Server 2012 R2.  I can see them when I dump them to a file (eg typeperf -q -o "C:\Temp\counters.txt"), but I'm not able to see them among the Available Counters of the Data Collection properties.  SQL Server Microsoft SQL Server 2014 - 12.0.2000.8 (X64) is installed on this machine, and it's running on VMWare (version to follow). I'm told I have admin rights and someone with full rights isn't able to see them either.  Why can't I see them?
SQL Statistics: Batch Requests/sec
SQL Statistics: SQL Compilations/sec
SQL Statistics: SQL Recompilations/sec
SQL Server: Wait Statistics
SQL Server: Buffer Manager Buffer Cache Hit Ratio
SQL Server: Wait Statistics Page IO latch waits
SQL Server:Buffer Manager Page Life Expectancy
Network: % Network Utilization

A: I ended up using the command-line tool typeperf.  You can use it to extract all
typeperf -q -o all_counters.txt

I pulled the counters I wanted from all_counters.txt and then I used the below to capture these pointers into a log file
typeperf -cf flip_perf_counters.txt -f tsv -si 05 -o log_file.txt


text:
Q: React сохраняет state при изменении роута Появилась проблема, когда имею вот такой линк
localhost:3000/users?id=2

При этом ложу в state объект пользователя, так как получил его из параметра id.
И когда нажимаю в браузере вернуться назад, тоесть на страницу
  localhost:3000/users

State сохраняется, и у меня там дальше лежит объект пользователя. Как пофиксить данную проблему?
 const { search } = useLocation();

    const fetchData = () => {
        console.log(window.location.search)
        const url = new URLSearchParams(
            search
        );
        console.log(url.get('id'))
        if (url.get('id')) {
            network({
                method: 'get',
                url: 'users/'+url.get('id'),
            }).then(response => {
                user = response.data
                setUser(user)
                console.log(user)
            })
        }else {
            loadUsers()
        }
    }
    useEffect(() => {
        console.log(search)
        fetchData();
    }, [search]);


text:
Q: Is it true that any 3-regular bipartite graph containing $K_{3,2}$ as subgraph must be non-planar? I asked a similar question previously at Is it true that any 3-regular graph containing K_{3,2} as subgraph must be non-planar? The requirement can be relaxed so that the $K_{3,2}$ "locally" respect the bipartite structure, namely there can't be edge connecting two vertices on the dangling side. Many thanks in advance.

A: Yes, it is true.
Combinatorially speaking, there is only one plane embedding of $K_{3,2}$: the one shown below.

To complete this graph to a $3$-regular bipartite graph, there must be at least one more vertex in the component containing copy of $K_{3,2}$. That vertex must be in the interior of one of the length-$4$ faces of this plane embedding. It doesn't matter which one, but let's put it in the interior of the face with corners $v_1, w_1, v_2, w_2$.
That vertex must be part of a fragment which is bipartite and nearly $3$-regular, except for an edge to one or both of $v_1, v_2$. Crucially, since $v_1$ and $v_2$ are in the same part of the bipartition, the edges to $v_1$ and/or $v_2$ must also come from the same side of the bipartition of the fragment.
But now, suppose that the fragment has $k$ vertices in one part and $\ell$ vertices in the other part (with the edges to $v_1$ and/or $v_2$ coming from the part of size $\ell$). Then there are $3k$ edges from the first part to the second, but either $3\ell-1$ or $3\ell-2$ edges from the second part to the first. This is a contradiction, so no bipartite $3$-regular planar graph can contain a $K_{3,2}$.

However, if we relax the condition "bipartite" to "triangle-free", then there are many counterexamples. Take your favorite bipartite, planar, $3$-regular graph $G$; delete an edge $u_1 u_2$ on the exterior boundary of a plane embedding of $G$, and splice it into the embedding above by adding edges $u_1v_1$ and $u_2v_2$ instead. (The result is no longer bipartite, because $u_1$ and $u_2$ were in different parts of the bipartition of $G$.)
We now have a planar triangle-free graph which is $3$-regular except for $v_3$. Take two copies of this graph and join them by an edge connecting $v_3$ and its copy, and we get a planar $3$-regular triangle-free graph that contains a copy of $K_{3,2}$.


text:
Q: Managing Dependency Hell with WiX and C# We are on the eve of product launch, and at the last minute I am being bombarded with crash reports that appear to be related to our installer, which is a WiX3 project with separate outputs for x86 and x64 builds. These have been an ongoing problem that I always thought were fixed, only to find out that they were still lurking.
The product itself is a collection of binaries that communicate with each other via .Net remoting, including a Windows Service and a small COM component that is loaded as an addon in another app. The service runs as SYSTEM, the COM piece runs in a low-rights context, while the other pieces run in normal user contexts. Other pieces include an third-party COM object library DLL and a shared DLL with the .net Remoting interfaces.
I've observed flat-out weird behavior with MSI, particularly on version upgrades. Between MS' anal strong-name implementation (specifically, the exact version check before loading a given assembly), a documented WiX/MSI bug that sees critical files erased on upgrades (essentially, if a file in the upgrade MSI has the same version number as the existing install, that file is deleted)(edit: having trouble producing said documentation...), and having to work around Wow64 virtualization (x86 MSI can only write to registry/HD locations via Wow64, yet x64 MSIs cannot run on x86 computers...), I am about ready to trash the whole thing and port it over to a different install system.
What I am looking for on tips + tricks, techniques, or suggestions on how to properly do things so that I am not fighting with Windows Installer's twisted sense of logic. I am tired of fighting with WiX/MSI/Windows Installer. All it needs to do is place files and registry keys where I tell it to, upgrade them when appropriate, and don't delete anything until the user uninstalls. Instead, dependencies are deleted willy-nilly, bringing up a whole bunch of uncatchable exceptions (can't wrap a try{} block around function declarations) and GPF'ing the whole app.
I am particularly interested in 'best practices' and examples regarding shared and dependency DLLs, and any tips on making sure if a file needs to go to GAC, that it actually goes to the GAC and stays there until it is appropriate to remove it.
Thanks!
Tom

A: Start off by reading The Definitive Guide to Windows Installer.
Done? Great. Now think about scrapping your existing install, starting from scratch and filing an application bug for everything you currently have to "workaround" in setup. For nearly every single bit of "twisted logic" that you've been fighting with is there for a purpose, to make your installation more reliable and repairable.
If you don't want the reliability and resiliency of Windows Installer, or if you're trying to bypass it in any way then use something else. Windows Installer does much, much more than simply just "place files and registry keys where I tell it to".
When you're writing an MSI package, you define how you want the target system to look. That's the way it looks after setup, the way it should automatically repair to if a file is deleted or a key data file is corrupted. You define how the system should roll back to if a user later cancels during an upgrade from 1.0 to 2.0. Windows Installer is 100% data driven. From a development point of view this is the hardest concept to understand, you can't just edit a config file or write some more data and expect it to persist. Once you get your head around this, Windows Installer becomes a real piece of cake and you design your programs and features to work within it's limitations, rather than trying to break free of them :)
A few other useful links...

*

*Tao of the Windows Installer, Part 1

*Understanding UAC in MSI

A: Assuming you're on at least Wix 3.0, you can make use of MakeSfxCA.exe to package dependencies in a single DLL. (This was an add-in from the DFT -- Deployment Tools Foundation.) Basically, start off by making sure project is copying your dependent DLLs. Make a CustomAction.config file. Test with a simple .bat file like:
REM MyMakeSfxCA.bat - Run under $(TargetDir); abs. paths reqd.
"%WIX%\SDK\MakeSfxCA" ^
    %cd%\Managed_custom_action_pkg.dll ^
    "%WIX%\SDK\x86\sfxca.dll" ^
    %cd%\Managed_custom_action.dll  ^
    %cd%\Dependent1.dll ^
    %cd%\Dependent2.dll ^
    %cd%\Microsoft.Web.Administration.dll ^
    %cd%\Microsoft.Deployment.WindowsInstaller.dll ^
    %cd%\CustomAction.config
Once that works, convert into a Post-Build Event:
"$(WIX)\SDK\MakeSfxCA" ^
    $(TargetDir)\Managed_custom_action_pkg.dll ^
    "$(WIX)\SDK\x86\sfxca.dll" ^
    $(TargetDir)\Managed_custom_action.dll  ^
    $(TargetDir)\Dependent1.dll ^
    $(TargetDir)\Dependent2.dll ^
    $(TargetDir)\Microsoft.Web.Administration.dll ^
    $(TargetDir)\Microsoft.Deployment.WindowsInstaller.dll ^
    $(TargetDir)\CustomAction.config
In your .wxs file, your Binary Key will look like:
< Binary Id="Managed_custom_action_CA_dll"         SourceFile="$(var.Managed_custom_action.TargetDir)$(var.Managed_custom_action.TargetName)_pkg.dll" / >
For they CustomAction.config, you can find examples online such as
This is the best way that I've found when working with managed code.

A: I'm kind of afraid to step into this one but the limitations are only there if you haven't followed best practices upstream.
Take the "delete files" "bug".   I haven't seen this one in a while, but if I recall, this is typically caused by the following scenario:
build A:
file 1: 1.0.0.0
build B:
file 1: 1.0.0.0
Now you go do a major upgrade where you have  RemoveExistingProducts scheduled after CostFinalize.   FindRelated Products detects the ProductCode to be removed,  Costing says oh I see I have 1.0.0.0 but 1.0.0.0 is already installed so nothing for me to do here and then RemoveExistingProducts comes by and removes the old version thereby deleting file1.
I always worked around this one by scheduling RemoveEXistingProducts way earlier then suggested by Microsoft.  It's been working for me for years.
As for dependency hell, I manage a software product line that consists of hundreds of features expressed by hundreds of merge modules and thousands of files ( 15,000 + )  consumed by dozens of installers on dozens of various feature, integration, main, maintenance and maintenance_integ branches.
How do I do it?  One fragment at a time and lot's of automation, SCM and virtual machines to make sure that everything does actually work the way it's intended.
Being this close to your product shipping, the only "answer" I can offer truely offer you is to let you know people like myself are always available for hire.  You'd be suprised how fast some of us can turn projects around and get software shipping.


text:
Q: How to get all tables with related data for foreignKey value in MySQL I do have a lot of tables. In every table there is a user_id as foreign_key pointing to user.id (user table, primary key). This is for recording which user inserted/changed data.
Now I want to know in which tables a user inserted data.
Is there a simple trick without joining all tables?

*

*I dont expect the data (can query that later)

*I dont need to know to which tables the foreign_key points to the user table (I already know)

*I want to know where user data is related

I could join all Tables, but this would be a huge performance issue. There are a lot tables and some are big, too.
I'm looking for something like:
SELECT tablename
FROM information_schema.foo
WHERE foreign_key = "key_name" AND foreign_key_value = 2;

A: I don't think there is any direct way, but you can use information_schema.key_column_usage to build queries for you.
SELECT
  concat('select \'',TABLE_NAME,
  '\' as `in_table`, IF (',COLUMN_NAME,' IS NOT NULL, \'Present\', \'Absent\') as exist from ',
 TABLE_NAME, ' where ', COLUMN_NAME, ' = 2; ') as `query`
FROM
  INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
  REFERENCED_TABLE_SCHEMA = 'testdb' AND
  REFERENCED_TABLE_NAME = 'users';

Now you have above query that will return queries for each table for user-id = 2.
You can create a procedure that take user-id as argument then execute above query.
Loop through the result something like:
select 'employees' as `in_table`, IF (user_id IS NOT NULL, 'Present', 'Absent') as exist from employees where user_id = 2;
select 'profile_documents' as `in_table`, IF (user_id IS NOT NULL, 'Present', 'Absent') as exist from profile_documents where user_id = 2;

and execute them one-by-one.
Then use the procedure to return the names of tables where user's info is present.


text:
Q: How to transform a string in a function? Indeed I have this code :
#include <iostream>

double a(){return 1.23;}
double b(){return 1.21;}

int main(){
std::string function0;
return EXIT_SUCCESS;
}

And what I want is this : if function0 = 'a' I would like to be able to transform the string function0 in the function a but I don't know how to do this. If function0 is equals to b I would like to call the function b.
Thank you for your help !

A: What you want to do is calling one of the functions depending on the value of the string variable. This is easily achievable.

*

*An if else construct in the main():
if (function0 == "a") {
    foo = a();
} else if (function0 == "b") {
    foo = b();
}

*Merge the function and modify the result, so it behaves differently depending on the input:
double newFunction (string input) {
     double valueForA = 1.23;
     double valueForB = 1.21;

     if (input == "a") {
         return valueForA;
     } else if (input == "b") {
         return valueForB;
     } else {
         //what if it's not "a" nor "b"?
         return 0;
     }
}

Usage:
double foo = newFunction(function0);

N.B:

*

*Don't neglect the return values of your function, if the returned value is not important use void function.

*Learn to use variables (instead of useless functions). You could have created 2 variables in the main, and that would be it.

*Visit this link to get started with C++. Without good references, you'll hate learning it, and that would be sad, or would it?

*Stop using the book/website you're currently using to learn programming. It's (probably) garbage.

A: function pointers may help.
double (*funcPtr)();
int main() {
  if (function0 == "a")
    funcPtr = &a;
  else
    funcPtr = &b;

  (*funcPtr)(); //calling a() or b()
}


text:
Q: How can I make my Flash movie automatically be fullscreen?
Possible Duplicate:
Is there a way to start the flash player (or program) in full screen through the shortcut target command?

I have a kiosk.  Its only reason for existence is to show content in a Flash movie, which lives on a webserver.  I don't want to have a keyboard and mouse hanging off the damn thing, so I've uninstalled or disabled everything that can possibly start a dialog in front of my content.

*

*The machine is running Windows 7.

*I have set the user to auto-login.

*I have set iexplore.exe to be the shell (using the winlogin registry key).

*I pass /k to IE so that it runs in kiosk mode, which is full screen.

*I set the homepage of IE to be the page with my Flash movie.

The last remaining problem is that it seems I need to click on the Flash movie with a mouse to make it full screen.  I don't want that.  I want to be able to just hard-reboot the machine in case of any problem and a few minutes later it's back up and running without any user intervention.
So, how can I do this?  I'm not married to anything in my setup other than Windows.  I don't have a mac and I am not going to install a different OS on the box.  But browser, shell, etc, can all change.  If there is a better container than a browser, great, let's do that then.  Pretty much any ideas are welcome.

A: I would use autohotkey and the Run + Click command. Look up the examples, its easy to implement. Start your browser by Run, use Sleep to wait till loaded and website loaded, double-click on the screen position
http://www.autohotkey.com/docs/commands/Click.htm
http://www.autohotkey.com/docs/commands/Run.htm
http://www.autohotkey.com/docs/commands/Sleep.htm


text:
Q: analysis of algorithm run time What would the big-O run time be? I'm mostly confused about the while loop run time. I know the run times for both for loops are O(n).
cin >> n >> min >> max;

for(int i = min; i < n; i++) {

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

        total = 1;

        while(total < n) {

             total = total *2;

        }

    }
}

A: The progression of target in the while loop is:
1 2 4 8 ... 2^P

You need log(2, n) steps -- i.e. log of n in base 2. That loop is O(log n).

A: First of all, it looks like you forgot to put braces. I'm your code, as it is, the whole loop is not inside the nested for loops. As it is, we have a pointless nested for loop that just sets total to 1, followed by an independent while loop. The complexity of the first is O((n - min) * max), and the second is O(log(n)). The total time complexity is the sum of these.
Probably what you really meant is this:
for(int i = min; i<n; i++) {

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

    total = 1;

    while(total < n) {
         total = total *2;
    }
  }
}

Here, we have the whole loop inside the nested for loops. The time complexity is the multiple of what we calculated earlier, so O((n - min) * max * log(n)). If min and max are constants, then we can reduce to O(n log n)


text:
Q: No ARIMA model able to be estimated Error in R forecast package - auto.arima I am using auto.arima from forecast package for multiple datasets in HPC server. The train data always has 24 data points with month-wise data for the past 2 years. The data also contains an external regressor. It has been working fine since long, but I encountered an error suddenly for one dataset alone.The error message says-
<simpleError in search.arima(x, d, D, max.p, max.q, max.P, max.Q, max.order,     stationary, ic, trace, approximation, xreg = xreg, offset = offset,     allowdrift = allowdrift, allowmean = allowmean, parallel = parallel,     num.cores = num.cores): No ARIMA model able to be estimated>

The code that I used is -
auto_arima <- ts(data$y, start=min(data$DATE), frequency=12)
auto_arima <- auto.arima(auto_arima, xreg = data$x1, stepwise=FALSE, approximation=FALSE, seasonal=TRUE)

The dataset that was producing the error is
structure(list(DATE = structure(c(17804, 17835, 17865, 17896,
17927, 17955, 17986, 18016, 18047, 18077, 18108, 18139, 18169,
18200, 18230, 18261, 18292, 18321, 18352, 18382, 18413, 18443,
18474, 18505), class = "Date"), x1 = c(21, 22, 21, 22, 22, 19,
22, 21, 22, 21, 22, 22, 21, 22, 21, 22, 22, 19, 22, 21, 22, 21,
22, 22), y = c(17532306871, 41826190703, 7748403270, 14959015398,
15241717931, 18655759009, 15393151016, 15251081090, 14516497716,
13974303432, 11254893416, 17410813458, 14446411746, 12876827127,
17609512917, 12179664532, 17473491954, 18447419416, 28262667160,
36623989143, 28711285833, 28711285833, 28711285833, 28711285833
)), row.names = c(NA, 24L), class = "data.frame")

When I run this code in my windows machine with Rversion 4.0.2 installed, it is working fine (ARIMA model (0,1,0) is being built) but when running the same code with the same data in HPC server, I am facing the error described above. I am facing the same error even when I try to execute the same code with Rversion 3.6.1 installed from RStudio in another windows machine.
Is this because of R version difference or am I missing something? Please help me with this.

A: The R version probably makes no difference here. The package version is what matters more. Here you are using the forecast package, and the auto.arima algorithm has had a few improvements and bug fixes over the years. The current CRAN version of forecast is v8.12 and it returns the ARIMA(0,1,0) model.


text:
Q: Google Drive Open URL development workaround it's possible to setup a Open URL for MIME type support at (console.developer.google.com). That's create and works fine for my application. But only for the product instance at Google Cloud. In detail:
I've released my application in version 1. It's AppEngine base and it supports a Open URL myapp.appspot.com/oauth2callback. So after the release I will going on with feature development for version 2. I use the local AppEngine dev setup. So I take my second client ID and change the Open URL to my local workstation mydev.workstation.com:8080/oauth2callback. That works fine, but it breaks my product instance. Is there any workaround to use Open URL for the production instance and a second Open URL for my dev instance? In my opinion the Drive SDK settings should be:
enable Authentication Production:
  Client ID: xxx
  Additional Scopes:
  Install URL:
  Open URL: https://myapp.appspot.com/oauth2callback
enable Authentication Development:
  Client ID: xxx
  Additional Scopes:
  Install URL:
  Open URL: http://devworkstation.com:8080/oauth2callback
Jens

A: Create separate projects in the console for prod/qa/dev

A: The answer from @SteveBazyl is the preferred one for all the reasons stated. A kludgy alternative would be to have the servlet that is bound to the Open URL detect when it is dealing with a test scenario and do a 301 redirect to your dev server.
Also, the API URL is pretty consistent, so once you've sniffed it once, it's not to difficult to path the host and use it in a curl script or browser bookmark for local testing.
As an aside "oauth2callback" is a slightly odd name for your Drive Open URL. It's not wrong, but "driveopen" would show the separate concerns.


text:
Q: How to get values of un-ordered html list in jquery through (.each loop)? I am trying to get index values for unordered list through each loop in jquery, i am struggling to get that.
I need the soltion with jquery each loop only, please help.
<!DOCTYPE html>
``

<title></title>

Link 1

Link 2

Link 3

A: You can try this one, I hope it will help
$(document).ready(function(){
   $('li a').each(function(index){
     $(this).text(index + " " + $(this).text());
   });
});

A: this should do it and append new elements to the page
$(document).ready(function(){
 $('li a').each(function(index){
 console.log(index, $(this).text());
 $(['
',index," ",$(this).text(),'
'].join('')).appendTo('body');
});
});


text:
Q: The image of a smooth idempotent function as smooth surface (manifold) Let $f \colon \mathbb R^n \to \mathbb R^n$ be a smooth function, and it satisfies that $f \circ f = f$.
How to prove that $S := f(\mathbb R^n)$ is a smooth surface?
Here the definition of a surface is that each point $x$ in $S$ has a neighbourhood $U$ in $S$ that is homeomorphic to $\mathbb R^k$, and a smooth surface is the case when the isomorphism from $\mathbb R^k$ to $U$ is also smooth (of class $C^{(m)}$, $m > 0$).
Examples like identity and linear projections indicates that the rank of the Jacobian $f'$ defines the dimension of the surface.
In fact, the derivative (Jacobian) of $f$ must satisfies:
$$
 f' f' = f',
$$
and therefore becomes a projection from $T_x\mathbb R^n$ to $T_{f(x)} S$.
Let $g(x) := f(x) - x$, we can see that $g(x) = 0 \leftrightarrow x \in S$.
But how to prove that $g$ has a rank $n - k$ at every point in $S$?
I don't see the constance of rank.
The question comes from Zorich Mathematics Analysis Chapter 12, §1, and my notations follows the book.


text:
Q: Induction - reducing the formula using algebra. I am having trouble to prove this reduction problem since I am stuck at showing how to reduce the function further using algebra. Any help would be appriciated.

Show: $$f(n) = (n*2^n)+7$$

Induction holds true so
hypothesis: $f(n-1) = ((n-1)*(2^{n-1}))+7$
Solving:
\begin{align}f(n) &= (2^n)-7+2*f(n-1)\\
 &= (2^n)-7+2*(((n-1)*2^{n-1})+7)\\
 & = (2^n)+7+(((n-1)*4^{n-1}))
\end{align}
After this, i am stuck trying to reduce it even further. If anyone could help me out, that would be great. What algebra method should I be using to reduce it farter to show that $f(n) = (n*2^n)+7$

A:
\begin{align}f(n) &= (2^n)-7+2*f(n-1)\\
 &= (2^n)-7+2*(((n-1)*2^{n-1})+7)\\
 & = (2^n)+7+(((n-1)*4^{n-1}))
\end{align}

You made a mistake going from the second to last line to the last line. In particular:
$$2*2^{n-1} \not = 4^{n-1}$$
Rather:
$$2*2^{n-1} = 2^n$$

A: \begin{align}f(n) &= (2^n)-7+2*f(n-1)\\
 &= (2^n)-7+2*(((n-1)*2^{n-1})+7)\\
 & = (2^n)+7+(n-1)*2^{n}\\
 & = n*2^n+7\\
\end{align}


text:
Q: Blurry Icons with HiDPI LibreOffice I've noticed that the icons for LibreOffice look rather bad on a HiDPI display. I've noticed this in stock Ubuntu 17.04, Kubuntu, and Ubuntu Gnome desktop. Is there a way to fix this?

A: I realize this is an old answer, but since I encountered the same problem on Ubuntu (Gnome) 20.04; LibreOffice 6.4.7.2 40, I will bother to answer anyway.
I am using an HDPI display (3840x2160 pixels; 192 dpi).
Under 'Settings' > 'Display' > 'Scaling' the display scaling was globally set to 200%.
Most applications deal well with this.
But the icons in LibreOffice remain blurry. Even, when .svg icon themes are selected.
This is related to this bug, and to my understanding has to do with the rendering of .svg files in the GTK3 version of the app.
Playing around with the GDK scale, as mentioned here,
I found that...
GDK_SCALE=1 SAL_FORCEDPI=192 libreoffice --writer
...solved this issue for me. You can add these environment variables to the .desktop files of the respective app launchers, if you do not wish to use the command line each time.
Explanation: The environment variable SAL_FORCEDPI=192
forces the application to start with the defined resolution, whose display support you can query using xrdb -query | grep -i dpi. The .svg icons were rendered in a crisp manner. But this also lead to a duplication of the scaling value in my case; likely, because LibreOffice multiplies several scaling values. This was negated by enforcing GDK_SCALE=1, which seems to fall back to the system-wide scaling of the correct 200% in my case.
Hope this helps.

A: On KDE Plasma you can go to "fonts" and force font dpi. In my case I forced "120".
Press the "Meta/Windows/Start" Button, type "fonts" open the fonts application. At the bottom of the windows is an option "Force fonds DPI". Check the box and set a DPI. Click here to see a picture of the fonts window


text:
Q: How do I redirect an address to another docker container using the nginx? Im trying to redirect to docker containers using nginx but when accessing my server from an 'external pc'(host and other vagrant machines) the address doesn't resolve. I have passed 'host.docker.internal:172.17.0.1' to the containers host file but still no success. Im testing this using vagrant. The server is running Ubuntu Server 21.10 and curling the address from here works.
default nginx conf:
server {
listen       80;
listen  [::]:80;
server_name  localhost;

#access_log  /var/log/nginx/host.access.log  main;
location /dockercontainer_1 {
    return 301 http://host.docker.internal:79;
}

location /dockercontainer_2 {
    return 301 http://host.docker.internal:34;
}

#error_page  404              /404.html;

# redirect server error pages to the static page /50x.html
#
error_page   500 502 503 504  /50x.html;
location = /50x.html {
    root   /usr/share/nginx/html;
}
}

nginx container host file:
127.0.0.1       localhost
::1     localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.17.0.1      host.docker.internal
172.17.0.4      35fced58d2eb

Ubuntu Server hosts file:
127.0.0.1 localhost
127.0.1.1 vagrant
127.0.0.1 host.docker.internal
# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

A: to access containers from external machine you need to tell nginx to serve on your public ip address so just edit the forth line of default nginx config file :
this line:
  server_name localhost;

To this:
  server_name 127.0.0.1  localhost;

change 127.0.0.1 to the public ip address of your machine.

A: Lets say that you initiate 2 nginx container with the following command
docker container run -d --name dockercontainer1 -p 8081:80 nginx
docker container run -d --name dockercontainer2 -p 8082:80 nginx

Then you should edit your localtion block in the host machine
location /dockercontainer_1 {
    return 301 http://localhost:8081;
}

location /dockercontainer_2 {
    return 301 http://localhost:8082;
}


text:
Q: SQL join with last date Hello I trying to join type from table by 2 columns that gives multiply rows, so this doesn't work
SELECT t1_id, t1.Company  t1_some_field, t2_type
FROM t1
LEFT JOIN t2 ON t1.Company = t2.Company AND t1_id = t2_t1_id

table t2
has multiply rows for t2.Company + t2_t1_id with different t2_date
I need to join the t2_type with last t2_date
I do it like this
SELECT t1_id, t1.Company  t1_some_field, t2_type
FROM t1
LEFT JOIN t2
ON t1.company = t2.company
AND t1_id = t2.t2_t1_id
LEFT JOIN
    (SELECT MAX(t2_date) AS Last_Date, company, t2_t1_id
        FROM t2
        GROUP BY company, t2_t1_id) last_t2
ON t1.company = last_t2.company
AND t1_id = last_t2.t2_t1_id

WHERE t2_date = Last_Date;

looks like this works, but I think should be an easier way.

A: Try this:
SELECT t1_id, t1.Company t1_some_field,
    (SELECT t2_type
    FROM t2
    WHERE t2.t2_t1_id = t1.id
    AND t1.company = t2.company
    AND NOT EXISTS(
        SELECT 'NEXT'
        FROM t2 t2next
        WHERE t2.t2_t1_id = t2next.t2_t1_id
        AND t2.company = t2next.company
        AND t2.t2_date > t2next.t2_date)
    )
FROM t1

A: It can be rewritten as follows, however, it will probably lead to the same query plan as in your case
SELECT t1_id, t1.Company  t1_some_field, t2_type
FROM t1
LEFT JOIN t2
ON t1.company = t2.company
AND t1_id = t2.t2_t1_id
WHERE t2.t2_date =
    (
        SELECT MAX(t2_date)
        FROM t2
        WHERE t1.company = t2.company AND
              t1.t1_id = t2.t2_t1_id
        GROUP BY company, t2_t1_id
    )

If you have MySQL supporting window functions (since version 8.0.0) then there is another way using row_number, but I recommend using your solution.

A: One method is a bit of a hack, using substring_index()/group_concat():
SELECT t1.t1_id, t1.t1.Company, t1.t1_some_field, last_t2.t2_type
FROM t1 LEFT JOIN t2
     (SELECT MAX(t2_date) AS Last_Date, company, t2_t1_id,
             SUBSTRING_INDEX(GROUP_CONCAT(t2.t2_type ORDER BY t2.t2_date DESC), ',', 1) as last_t2_type
      FROM t2
      GROUP BY company, t2_t1_id
     ) last_t2
     ON t1.company = last_t2.company AND t1_id = last_t2.t2_t1_id;

Another method uses a correlated subquery:
select t1.*,
       (select t2.t2_type
        from t2
        where t1.company = t2.company and t1.t1_id = t2.t2_t1_id
        order by t2.t2_date desc
        limit 1
       ) as t2_type
from t1;

With an index on t2(company, t2_t1_id, date), this may have the best performance.


text:
Q: Django form that updates multiple records I have 2 classes of users who can view a screen that lists all users in my app.  The type of user is controlled by a Boolean field on the User model. The screen currently lists out the Users and various details about them  (see below).  Project Managers should see a read only view of the page where as Administrators should have the ability to edit the Users as well.

HTML for the screen.

                      #
                      Username
                      First Name
                      Last Name
                      Is Contributor?
                      Is Project Manager?
                      Is is_administrator?

                    {% for user in users %}

                      {{ user.id }}
                      {{ user.username }}
                      {{ user.first_name }}
                      {{ user.last_name }}
                      {{ user.is_contributor }}
                      {{ user.is_projectmanager }}
                      {{ user.is_administrator }}
                      Edit
                      Delete

                    {% endfor %}

I want to create a version of the screen available to admin users which allows them to view and update users all at once.
How can I create a form that updates all the users at once?  I'm looking to build something that lists out the users with a list of the fields associated with the model and then gives the admin the ability to change those fields for multiple users at the same time, and then hit a save button to submit the form?

A: I was able to figure it out using Model form sets.
https://docs.djangoproject.com/en/3.2/topics/forms/modelforms/#model-formsets
I just created the form set as seen below.
    UserFormSet = modelformset_factory(User,fields=('username','first_name','last_name','email','is_contributor','is_projectmanager','is_administrator'))
formset = UserFormSet()
context = {
    # 'users':users,
    'formset':formset,
}
return render(request, 'bugtracker_app/users.html', context)

Then I looped through it in the template:

            {% for form in formset %}
            {{form}}
          {% endfor %}

It isn't formatted quiet the way I was picturing it yet (it renders the fields vertically as opposed to horizontally see below, but I'm sure I can find a way to fix that.


text:
Q: How to make curved rectangles in ThreeJS to show the relationship between two lists? I have two lists of data on the screen, one on the left and one on the right, I'm trying to show the relationship between the two lists. The lists should look somewhat like the ones in the middle of this image.
This image is from this webpage https://react-three-fiber-website-playground.vercel.app/ but this has been done in D3 I can see. I need to do the same in Three.js, ideally react-three-fiber. Would bezier curves help? Is there a proper name for this type of data visualization?

Just to show the current lines are drawing nicely based upon the example code given in answer here.

A: As an option, use CubicBezierCurve and bend PlaneGeometry in accordance to the curve:

body{
  overflow: hidden;
  margin: 0;
}
<script type="module">
import * as THREE from "https://cdn.skypack.dev/three@0.133.1";

let scene = new THREE.Scene();
let camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 1, 1000);
camera.position.set(0, 0, 10);
camera.lookAt(scene.position);
let renderer = new THREE.WebGLRenderer({
  antialias: true
});
renderer.setSize(innerWidth, innerHeight);
renderer.setClearColor(0x202020);
document.body.appendChild(renderer.domElement);

let basePoints = [ // start, end points
  new THREE.Vector3(-2, -3),
  new THREE.Vector3(2, 3)
];
let pathPoints = [
  basePoints[0],
  new THREE.Vector2().addVectors(basePoints[0], basePoints[1]).multiplyScalar(0.5).setY(basePoints[0].y),
  new THREE.Vector2().addVectors(basePoints[0], basePoints[1]).multiplyScalar(0.5).setY(basePoints[1].y),
  basePoints[1]
]
let curve = new THREE.CubicBezierCurve(pathPoints[0], pathPoints[1], pathPoints[2], pathPoints[3]);
let resultPoints = curve.getSpacedPoints(50);

let line = new THREE.Line(new THREE.BufferGeometry().setFromPoints(resultPoints), new THREE.LineBasicMaterial({
  color: "yellow"
}));
scene.add(line);

let width = [1, 3]; // start, end

let g = new THREE.PlaneGeometry(1, 1, 50, 1);
let pos = g.attributes.position;
for (let i = 0; i <= 50; i++) {
  let lrp = THREE.MathUtils.lerp(width[0], width[1], i / 50);
  pos.setXYZ(
    i, resultPoints[i].x, resultPoints[i].y + lrp * 0.5 * Math.sign(pos.getY(i)), 0
  );
  pos.setXYZ(
    i + 51, resultPoints[i].x, resultPoints[i].y + lrp * 0.5 * Math.sign(pos.getY(i + 51)), 0
  )
}
let m = new THREE.MeshBasicMaterial({
  color: "aqua",
  wireframe: true
});
let o = new THREE.Mesh(g, m);
scene.add(o);

window.addEventListener("resize", onResize);

renderer.setAnimationLoop(_ => {
  renderer.render(scene, camera);
})

function onResize(event) {
  camera.aspect = innerWidth / innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(innerWidth, innerHeight);
}

</script>

A: This is the same code (not exactly!) as prisoner849's answer modified to run in react-three-fiber, I use this now in my project and it is working. I think my forwardRef is not necessary, its just that I have useImperativeHandle in there for a reason.
This is a non-answer to the question as its a copy of his code just translated.
import React, {useLayoutEffect, useRef} from 'react'
import * as THREE from 'three'
import { useThree } from 'react-three-fiber'
const { forwardRef, useImperativeHandle } = React;

export const LineMapping = (forwardRef(({}, ref) => {
    const {
        camera,
        gl: { domElement }
    } = useThree()

    const ref3 = useRef()
    const ref2 = useRef()
    const meshRef = useRef()

    const randomFloat = (a: number, b: number): number => {
        return (Math.random() * (b-a)) + a
    }

    let width = [randomFloat(0.3, 2.0), randomFloat(0.3, 0.6)] // start, end
    let basePoints = [
        // start, end points
        new THREE.Vector3(-2, 0.9 + randomFloat(0.0, 3.0)),
        new THREE.Vector3(2, 0.9 + randomFloat(0.0, 3.0))
    ]

    let pathPoints = [
        basePoints[0],
        // @ts-ignore
        new THREE.Vector2().addVectors(basePoints[0], basePoints[1]).multiplyScalar(0.5).setY(basePoints[0].y),
        // @ts-ignore
        new THREE.Vector2().addVectors(basePoints[0], basePoints[1]).multiplyScalar(0.5).setY(basePoints[1].y),
        basePoints[1]
    ]

    // @ts-ignore
    let curve = new THREE.CubicBezierCurve(pathPoints[0], pathPoints[1], pathPoints[2], pathPoints[3])

    let resultPoints = curve.getSpacedPoints(50)
    const lineGeometry = new THREE.BufferGeometry().setFromPoints(resultPoints)

    useLayoutEffect(() => {
        if (ref3.current !== undefined && ref2.current !== undefined) {

            // @ts-ignore
            let pos = ref2.current!.attributes.position
            for (let i = 0; i <= 50; i++) {
                let iMod = i
                let lrp = THREE.MathUtils.lerp(width[0], width[1], i / 50)
                pos.setXYZ(i, resultPoints[iMod].x, resultPoints[iMod].y + lrp * 0.5 * Math.sign(pos.getY(i)), 0)
                pos.setXYZ(iMod + 51, resultPoints[iMod].x, resultPoints[iMod].y + lrp * 0.5 * Math.sign(pos.getY(i + 51)), 0)
            }

        }
    });

    // @ts-ignore
    useImperativeHandle(ref, () => ({
        testMe: () => {

        }
    }));

    return <>
            <group position={[2.2, 0, -5.5]}>

                <group position={[0, 0, 0]} visible={false}>
                <line ref={ref3} geometry={lineGeometry}>
                    <lineDashedMaterial attach="material" color={'#ffffff'} linewidth={1} />
                </line>
                </group>

                <mesh ref={meshRef} receiveShadow>
                    <planeBufferGeometry ref={ref2} attach="geometry" args={[7, 7, 50, 1]} />
                    <meshBasicMaterial attach="material" color="#2892D7" wireframe={false} />
                </mesh>
            </group>
        </>
}))


text:
Q: Installing new versions of ubuntu alongside /home folder I am thinking theoretically how ubuntu behaves when you want clean install of OS, but with not-touching /home partition. And what to do when /home is encrypted?
Can you delete partitions other than /home and make a clean install or what is recommended scenario.
I got 17.04 because of newest Linux kernel but when 18 LTS will be out I would like to upgrade (probably using clean install).
Hope it's not duplicate, didn't find exactly same question.

A: Yes, as long as you don't delete it (should go without saying) your /home partition (encrypted or not) will remain intact when you upgrade your Ubuntu OS to a future release.
The process I follow (which I believe is pretty typical) is to create several partitions: /, /home, and swap (/boot/efi is often required as well when using the newer UEFI BIOS).
Maintaining a separate /home partition makes it very easy to do an upgrade while allowing your personal data to persist across upgrades.
In my own case, I probably have ~10 years of data in one of my /home partitions... and it's survived innumerable upgrades with no problems.


text:
Q: 405 Error on Fetch to send Data from front to back I am working on a registration form in HTML.  The form uses script to take the data entered by user, and turn it into JSON format so that my backend can process it. My text editor is Visual Studio Code and I am checking the functionality of my code with Five Server extension. When I run the code, I get a 405 (method not allowed) message whenever I try to submit data. I suspect that when I make the fetch call, I am not properly referencing the resource.  Does my JavaScript file need to be in the same folder as my HTML file?  Or is my issue something else?
 <script>
        const form = document.getElementById('createAccount')
        form.addEventListener('submit', registerUser)
        // Will send Data as JSON
        async function registerUser(event) {
            event.preventDefault()
            const firstName = document.getElementById('signupFname').value
            const lastName  = document.getElementById('signupLname').value
            const email     = document.getElementById('signupEmail').value
            const username  = document.getElementById('signupUsername').value
            const password  = document.getElementById('signupPword').value

            //Is this right?
            const result = await fetch('/signup', {
                method: 'POST',
                headers: {
                    'Content-Type':'application/json'
                },
                body: JSON.stringify({
                    firstName,
                    lastName,
                    email,
                    password,
                    username

                })
            }).then((res) => res.json())

            console.log(result)
        }
    </script>

Here is my Javascript
const express = require("express");
const router = express.Router();
const path = require('path');
router.use('/', express.static(path.join(__dirname, 'static')));

// mongodb user model
const User = require("./../models/users");

// Password handler
const bcrypt = require("bcryptjs");

// Signup
router.post("/signup", (req, res) => {
  let { fname, lname, username, password, email } = req.body;
  fname    = fname.trim();
  lname    = lname.trim();
  username = username.trim();
  password = password.trim();
  email    = email.trim();

  if()
// Trimmed code for sake of space
)};


text:
Q: c# polymorphism + generics design - advice needed I have a hierarchy of TrendProviders which are used to provide a series of datapoints (trends) from different sources.
I have started with the generic interface:
public interface ITrendProvider<T> where T: TrendResult
{
    IEnumerable<T> GetTrends();
}

TrendResult is a result class with the obtained trend data and operation status code:
public class TrendResult
{
    public TrendResult()
    {
        Points = new Dictionary<DateTimeOffset, decimal>();
    }

    public TrendResultCode Code { get; set; }
    public string Name { get; set; }
    public string Identifier { get; set; }
    public Dictionary<DateTimeOffset, decimal> Points { get; set; }
}

TrendResultCode is as follows:
public enum TrendResultCode
{
    OK,
    DataParseError,
    NoData,
    UnknownError
}

There are also two types (so far) of more detailed interfaces:

*

*IFileTrendProvider - used to obtain trends from any files.

*IServerTrendProvider - used to obtain trends from remote servers, using FTP for example.
IFileTrendProvider goes like this:
public interface IFileTrendProvider : ITrendProvider<TrendResult>
{
    IFileReader FileReader {get; set}
    FileTrendDiscoveryPattern Pattern {get; set;}
}

IServerTrendProvider goes like this:
public interface IServerTrendProvider : ITrendProvider<TrendResult>
{
    IClient Client { get; set; }
    Dictionary<string, string[]> RequestedServerTrendIDs { get; set; }
}

The concrete classes that implements the interfaces are as follows:
One of FileTrend type:
public class GenericFileTrendProvider : IFileTrendProvider<TrendResult>
{
    public GenericFileTrendProvider() { }

    public IFileReader FileReader {get; set}
    public FileTrendDiscoveryPattern Pattern {get; set;}

    public IEnumerable<TrendResult> GetTrends()
    {
       // Some code to obtain trends from file using FileReader
    }
}

And one of the ServerTrend type:
public class ServerATrendProvider : IServerTrendProvider<TrendResult>
{
    public ServerATrendProvider () { }

    public IClient Client { get; set; }
    public Dictionary<string, string[]> RequestedServerTrendIDs { get; set;}

    public IEnumerable<TrendResult> GetTrends()
    {
       // Some code to obtain trends from remote server using Client
    }
}

Now, what I want to achieve and where I need your help and advice:
The IFileReader introduces its own error codes:
public enum FileReadResultCode
{
    OK,
    FileAlreadyOpen,
    FileNotFound,
    UnknownError
}

IClient also introduces its specific operation error codes:
public enum ClientCode
{
    OK,
    InvalidCredentials,
    ResourceNotFounds,
    UnknownError
}

As both: IFileReader and IClient also returns its own error codes, how could I intruduce them in the TrendResult object returned by GetTrends() method, so that in the end there will be also some information about the "internal" error, not only TrendResult specific error?
I would need some flexible solution - I was thinking about inheriting from TrendResult and create a FileTrendResult and ServerTrendResult for each of concrete providers, and also define a specific error enumerations for both so that they return its own result type, but can it be done in some other way?

A: Instead of having a pre-defined list of possible errors in the enumerations (TrendResultCode, FileReadResultCode, ClientCode, ...) you could change the TrendResult class to store a list of exceptions and get rid of the enumerations:
public class TrendResult
{
    // ...
    // public TrendResultCode Code { get; set; }
    public IEnumerable<Exception> Errors { get; set; }
    // ...
}

This way, you can store the complete information of the error including stack trace and other valuable information (or of several errors if there is more than one problem in a single TrendResult). Even for unexpected errors, you are able to store the details instead of having an unknown error that is hard to track down.
If a  TrendResult does not have any items in the enumeration, there are no problems with it. Otherwise, you can put the information to the log.
The implementation follows the Open/Closed principle, so you don't have to change the implementation that handles the TrendResults if there are new conditions that lead to an error.
For your business exceptions, e.g. parsing errors, you should create specific exception types so that you are able to analyze these errors later on based on their type.

A: Since IServerTrendProvider will be receiving TrendResults from other computers, you will not be able to use System.Exception in the general case.
In these cirumstances, people fall back to strings - which are always supported regardless of operating system.
public class TrendResult
{
   public string[] ErrorMessages;  // Error messages - could be the stack trace
   public int[]    ErrorCodes;     // Os-specific error numbers
}

Consider security when sending source-code fragments (e.g. names, stack traces) in error messages, because these could be of use to hackers.


text:
Q: Java separate MouseListener and performance Writing a game and using mouse events for the first time, but as I play with them, the various methods are getting bigger. I want to separate the listening stuff into a diffrent class, but I will still need access to my various objects that are stored in my main class (where the listener methods currently resides having used implements)
Another thing I have noticed, is that when performing the events, they seam to have a very variable perfomance speed, is there any way to improve this?
any help / suggestion are very much appreciated
Thanks

A: Move the fields from the main class to a "model" class (which contains a model of your game).
In the main class, create the model and then pass it to the listener.
As for the performance: I suggest move the mouse handling in a thread which waits for a signal (see Object.notify()). In the listener, update the current coordinate (use AtomicReference and a Point object) and then send the signal. This way, you handler can do its work as fast as possible but when it can't keep up with the mouse, it will skip ahead (instead of lagging behind).


text:
Q: Подходят ли книги описывающие Питон 3.4 для изучения Питона (последняя версия 3.6) Добрый день. Сразу скажу, что я новичок в программировании. Первым языком решил выбрать Python, так как хочу заниматься машинным обучением. Но возникла проблема с выбором литературы. Сомневаюсь в корректности выбора обучающей литературы.  Как уже понял, последняя версия Python - 3.6. Но учебники, которые я нашел, охватывают лишь 3.4. Стоил ли остановиться на этих ресурсах или же искать более современные учебники? Есть опасения, что в учебниках может быть представлена устаревшая информация и потом придется переучивать. Возможно я рассуждаю неправильно, не судите строго, я только делаю первые шаги в программировании. Прошу помощи в неравнодушных людей. Порекомендуйте действительно стоящие ресурсы, которые помогут в изучении. Актуальна ли информация в учебниках, которые были написаны пару лет назад? Заранее спасибо за помощь.

A: *

*"Стоил ли остановиться на этих ресурсах или же искать более современные учебники?" -- пока будете искать новые учебники  по версии 3.6 - выйдет версия 3.8. И дальше что? Вердикт - читайте любые книги по Python 3...  Если и будут изменения - потом будете разбираться именно в изменениях. Это всегда проще, чем учить "от печки".

*"в учебниках может быть представлена устаревшая информация и потом придется переучивать." -  так и есть. Если хотите заниматься программированием - будьте готовы к тому, что переучиваться придется постоянно, на протяжении всей (профессиональной) жизни. Особенности профессии, так сказать.

*"Актуальна ли информация в учебниках, которые были написаны пару лет назад?" - вполне актуальна с учетом сказанного в предыдущих двух пунктах.

*Учтите, что Python - это еще не машинное обучение. Это просто один из инструментов ДЛЯ машинного обучения. Поэтому да, Python -  учить надо, но не менее важно начать учить то, что  составляет базу машинного обучения (матанализ, линейная алгебра, теорвер,..... и в том числе -программирование), а затем и собственно методы машинного обучения.


text:
Q: How do I properly set width to a percentile and keep a min-width in pixels? So I have a header/navigation bar div, this div has a repeat-x background image.
Than I've got a horizontal navigation which is centered over this background, but needs a min-width and normal width.
I'd like for it to show up as 80% width, and min-width 1000px, and centered.
CSS
.center-wrap {
width: 80%;
min-width: 1000px;
margin: 0 auto;
}
#bar {
width: 100%;
height: 50px;
background-image: url(images/background.jpg);
background-repeat: repeat-x;
}

HTML
<div id="bar">
    <div class"center-wrap">
        UL LI HERE
    </div>
</div>

Error
Now the problem with this is if I resize the page to below 1000px the repeat-x background image cuts off (when scrolling -> to reveal the rest of the website).
How would I go about keeping my repeat-x background image on #bar and keeping the center-wrap centered and include a min-width and percentile width?

A: Add this to your Css, Magic! :D
body{min-width: 1000px;}

The problem is that the body is taking the window object width as max width, and the descendant are taking that width as heritage. What happens is:
You resize the window(browser) to 300px width, then body's width = 300px, then .center-wrap = 80% of 300px, so setting min-width of body to a fixed number fixes it


text:
Q: java calendar weekend of current week Java using calendar i want to get date of current weekend, any quick idea

A: Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
c.getTime(); // => Date of this coming Saturday.

A: Calendar currDate = Calendar.getInstance();;
currDate.add(Calendar.DAY_OF_YEAR, (Calendar.SATURDAY - currDate.get(Calendar.DAY_OF_WEEK) ));
System.out.println("weekend date is in the " + curreDate.get(Calendar.DAY_OF_MONTH));

A: Try this:
String dayNames[]={"lundi","mardi","mercredi","jeudi","vendredi","samedi","dimanche"};
        String nomthNames[]={"janvier","février","mars","avril","mai","juin","juillet","Août","septembre","octobre","novembre","decembre"};
        Calendar date = Calendar.getInstance();
        String dayName = dayNames[date.get(Calendar.DAY_OF_WEEK)];
        String dayMonth = nomthNames[date.get(Calendar.MONTH)];

        lblBonjour.setText("Bonjour, "+new Functions().getNomPrenom(myID)+"
"+
                "Ajourd'hui "+dayName+" "+date.get(Calendar.DATE)+" "+dayMonth+" "+date.get(Calendar.YEAR)+"
"+
                "Heure locale: "+date.get(Calendar.HOUR_OF_DAY)+":"+date.get(Calendar.MINUTE) );

A: Joda Time
new DateTime().withDayOfWeek(DateTimeConstants.SATURDAY)

A: Try this. It will give both the start and end of week days.
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, cal.MONTH);
cal.set(Calendar.WEEK_OF_MONTH, cal.WEEK_OF_MONTH);
int weekStart = cal.getFirstDayOfWeek();
cal.set(Calendar.DAY_OF_WEEK,weekStart);
Date WeekStartDate=cal.getTime();
cal.set(Calendar.DAY_OF_WEEK,weekStart+7);
Date WeekEndDate=cal.getTime(

A: tl;dr
LocalDate.now( ZoneId.of( "Pacific/Auckland" ) )                      // Today, in specific time zone.
         .with( TemporalAdjusters.nextOrSame( DayOfWeek.SATURDAY ) )  // Next Saturday, or today if already Saturday.
         .plusDays( 1 )                                               // Sunday

java.time
The modern approach uses the java.time classes that supplant the troublesome poorly-designed Date & Calendar classes.
Current date
The LocalDate class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still "yesterday" in Montréal Québec.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );

Moving to the next weekend
You can adjust from one date to another using an implementation of the TemporalAdjuster interface. Some handy implementations are provided in the TemporalAdjusters class, such as nextOrSame. Specify a day-of-week using a DayOfWeek enum object. Note that a DayOfWeek is an actual object rather than a mere number or string, providing type-safety and ensuring valid values.
LocalDate saturday = today.with( TemporalAdjusters.nextOrSame( DayOfWeek.SATURDAY ) ) ;
LocalDate sunday = saturday.plusDays( 1 ) ;

If you want to the same or previous weekend, call the previousOrSame adjuster.

About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?

*

*Java SE 8, Java SE 9, and later

*

*Built-in.

*Part of the standard Java API with a bundled implementation.

*Java 9 adds some minor features and fixes.

*Java SE 6 and Java SE 7

*

*Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

*Android

*

*Later versions of Android bundle implementations of the java.time classes.

*For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


text:
Q: Sort array of Custom Objects by date range Swift I am having an array of Custom Objects and each object having a date property of NSDate.I want to sort now the Array by using a start and end date.I want to get all the objects whose date matches with start date and end date and in between dates.
i really do not know about doing this.Any suggestions and sample code are much helpful and appreciated.

A: The simpliest way you can do this is:
- (NSArray *)selectObjectsWithBeginDate:(NSDate *)dateBegin endDate:(NSDate *)dateEnd {
    NSMutableArray *selections = [NSMutableArray array];
    for (CustomObject *obj in objectArray) {

        if ([obj.date compare:dateBegin] == NSOrderedDescending && [obj.date compare:dateEnd] == NSOrderedAscending) {
            [selections addObject:obj];
        }
    }
    return [NSArray arrayWithArray:selections];
}

You just need to be able ti compare two NSDate objects.


text:
Q: List all posts without at least one category assigned to them in admin I am trying to allow the admin user to list out CPT that have not already had a category assigned to them (This is to enable them to quickly find posts that require a category and edit them)
I have this so far -
function function_name( $query ) {
  global $post_type;
  if ( is_admin() && $post_type == 'product' ) {
    $query->set( 'cat', '' );
  }
}
add_action( 'pre_get_posts', 'function_name' );

This does not work however. Can someone help point me in the right direction?
Thanks

A: I have achieved what I need this way, if anyone else comes up with this question -
$terms = get_terms( array(
   'taxonomy' => 'category',
   'hide_empty' => false,
) );

$arr = array();

foreach ($terms as $term) {
   $arr[] = '-'.$term->term_id;
}

$query->set( 'cat', $arr );

I am simply getting all category id's. looping through these and appending them to another array with a munis "-" value and passing them through to the query as an argument.


text:
Q: .htaccess how to create an URLs like http://example.com/~someuser How do I can create and process an URLs like this via .htaccess rules: http://example.com/~someuser
And then get a parameter "username" as a part of $_GET array. Thanks in advance.

A: Something like this:
RewriteEngine On
RewriteRule ^~([^/]+)/?$ /script.php?user=$1 [L]

If those rules are placed in the htaccess file in your document root, then it'll capture the "someuser" part of the URL and rewrite it to the script.php script and set it as the $_GET['user'] variable. You can replace script.php with whatever name of the script you want the variable to go to.


text:
Q: pgfplots: set effective width of figure if no label given How to ensure that the set width of pgfplot figure is correctly applied in case I do not have a label?
Please consider the example below
\documentclass{article}

\usepackage{pgfplots,calc,filecontents,tikzscale}

\begin{filecontents*}{test.tikz}
    \begin{tikzpicture}%
        \begin{axis}[width=120pt,height=3cm]%
        \addplot[domain=-3:3] {sin(deg(x))};%
        \end{axis}%
    \end{tikzpicture}%
\end{filecontents*}

\begin{filecontents*}{test-label.tikz}
    \begin{tikzpicture}%
    \begin{axis}[width=120pt,height=3cm,ylabel=ylabel]%
    \addplot[domain=-3:3] {sin(deg(x))};%
    \end{axis}%
    \end{tikzpicture}%
\end{filecontents*}

\def\mymacro{\input{test.tikz}}
\def\mymacrolabel{\input{test-label.tikz}}

\def\mymacroscaleonlyaxis{\includegraphics[width=120pt,height=3cm]{test.tikz}}
\def\mymacrolabelscaleonlyaxis{\includegraphics[width=120pt,height=3cm]{test-label.tikz}}

\newlength{\test}
\begin{document}
    \mymacro%
    \settowidth{\test}{\mymacro}%

    \the\test

    \mymacrolabel%
    \settowidth{\test}{\mymacrolabel}%

    \the\test

    \mymacroscaleonlyaxis%
    \settowidth{\test}{\mymacroscaleonlyaxis}%

    \the\test

    \mymacrolabelscaleonlyaxis%
    \settowidth{\test}{\mymacrolabelscaleonlyaxis}%

    \the\test
\end{document}

The cases where a ylabel is set, are scaled almost correctly (ca. 118pt instead of the desired 120pt).
But the figures without label are not scaled correctly in either case.
How to fix that?

A: You can combine trim axis left (applied to the tikzpicture) with scale only axis (applied to the axis). If you only trim the axis, pgfplots will still allocate 45pt of space for tick marks and axis labels. If you only scale the axis, the axis decorations will add to the overall width.

\documentclass{article}
\usepackage{pgfplots,calc,filecontents,tikzscale}
\pgfplotsset{compat=1.16}

\begin{filecontents*}{test.tikz}
    \begin{tikzpicture}%
        \begin{axis}[width=120pt,height=3cm]%
        \addplot[domain=-3:3] {sin(deg(x))};%
        \end{axis}%
    \end{tikzpicture}%
\end{filecontents*}

\begin{filecontents*}{test-label.tikz}
    \begin{tikzpicture}%
    \begin{axis}[width=120pt,height=3cm,ylabel=ylabel]%
    \addplot[domain=-3:3] {sin(deg(x))};%
    \end{axis}%
    \end{tikzpicture}%
\end{filecontents*}

\begin{filecontents*}{test.tikz.scaled}
    \begin{tikzpicture}[trim axis left]%
        \begin{axis}[width=120pt,height=3cm,scale only axis]%
        \addplot[domain=-3:3] {sin(deg(x))};%
        \end{axis}%
    \end{tikzpicture}%
\end{filecontents*}

\begin{filecontents*}{test-label.tikz.scaled}
    \begin{tikzpicture}[trim axis left]%
    \begin{axis}[width=120pt,height=3cm,ylabel=ylabel,scale only axis]%
    \addplot[domain=-3:3] {sin(deg(x))};%
    \end{axis}%
    \end{tikzpicture}%
\end{filecontents*}

\def\mymacro{\input{test.tikz}}
\def\mymacrolabel{\input{test-label.tikz}}
\def\mymacroscaleonlyaxis{\input{test.tikz.scaled}}
\def\mymacrolabelscaleonlyaxis{\input{test-label.tikz.scaled}}

\newlength{\test}
\begin{document}
    \mymacro%
    \settowidth{\test}{\mymacro}\quad\the\test

    \mymacrolabel%
    \settowidth{\test}{\mymacrolabel}\quad\the\test

    \mymacroscaleonlyaxis%
    \settowidth{\test}{\mymacroscaleonlyaxis}\quad\the\test

    \mymacrolabelscaleonlyaxis%
    \settowidth{\test}{\mymacrolabelscaleonlyaxis}\quad\the\test
\end{document}


text:
Q: Does Git delete empty folders? I've committed and pushed a project to my GitHub account.
This project contained the following partial file structure:
server
|
--- conf
|
----- some files
|
--- java
|
--- lib

The java and lib folders are empty.
When downloading my project from GitHub, the resulting zip did not contain the java and lib folders.
Does Git delete empty folders?
I am using Atlassian's SourceTree as my Git client.

A: Git doesn't delete empty folders; Git cannot track empty folders (or any kind of folder) in the first place. Git only tracks files, the folders are incidental. Git only creates folders on disk in order to house files; a folder with no files in it does not exist in Git's world-view.
If you want to keep an "empty" folder in your Git repository, the convention is to add a hidden empty file to that directory, such as /java/.gitkeep


text:
Q: Как превратить map в объект класса? Есть map описывающий сущность, где пара  это имя поля и его значение. Подскажите пожалуйста, есть ли какой нибудь инструмент который позволит автоматически конвертировать эту мапу в объект соответствующего класса?

A: POJO класс все равно придется описать самостоятельно.
Конвертировать можно, например, через Jackson метод convertValue:
mapper.convertValue(map, MyPojo.class);


text:
Q: How to Get Autocomplete with Several Words I'm using autocomplete on a field in Azure Search... it works great, however I want the autocomplete results to return the next "x" number of words (like in the following screenshot https://learn.microsoft.com/en-us/azure/search/index-add-suggesters)
I've tried all three Autocomplete types "oneTerm", "twoTerms" and "oneTermWithContext" however none of those give me the expected results.
I expect to type "tom clan" and autocomplete should return "tom clancys rainbow six siege"

A: Excellent point about the documentation showing several words in the example and the autocomplete API only supporting up to two terms ahead.  I think we should update the example to better reflect the actual behavior of the API.
If you are interested, please create a feedback item for the API enhancement you suggested so it can collect some votes: https://feedback.azure.com/forums/263029-azure-search
Thanks!
Mike Carter
Azure Search product team


text:
Q: Change date format in echo function I have created a query which works fine, I just have a problem with this two dates which are "echoed" :
echo "du : $item->session_du | ";
echo "au : $item->session_au

";

Echo are displaying the date in the following format :

2016-01-11 23:00:00

I need the output in this format

lundi 11 janvier 2016

I haven't found a way to do it so I would appreciate if someone could advise me how to solve this issue.
Query :
$candidateid = JRequest::getVar('gprh_fabrik_user_enrollment___id');
$db = JFactory::getDbo();
   $query = $db->getQuery(true);
   $query
      ->select (array('gprh_fabrik_user_enrollment.id', 'gprh_fabrik_user_training_124_repeat.nom_formation', 'gprh_fabrik_user_training_124_repeat.intitule_session', 'gprh_fabrik_user_training_124_repeat.session_du', 'gprh_fabrik_user_training_124_repeat.session_au'))
  ->from('gprh_fabrik_user_enrollment')
  ->leftJoin('gprh_fabrik_user_enrollment_repeat_choix_formation ON gprh_fabrik_user_enrollment.id = gprh_fabrik_user_enrollment_repeat_choix_formation.parent_id')
  ->leftJoin('gprh_fabrik_user_training_124_repeat ON gprh_fabrik_user_enrollment_repeat_choix_formation.choix_formation = gprh_fabrik_user_training_124_repeat.id')
  ->leftJoin('gprh_fabrik_user_training ON gprh_fabrik_user_training_124_repeat.parent_id = gprh_fabrik_user_training.id')
  ->having('gprh_fabrik_user_enrollment.id = ' . $db->quote($candidateid))
  ->group('gprh_fabrik_user_enrollment.id, gprh_fabrik_user_training_124_repeat.nom_formation, gprh_fabrik_user_training_124_repeat.intitule_session, gprh_fabrik_user_training_124_repeat.session_du, gprh_fabrik_user_training_124_repeat.session_au');
   $db->setQuery($query);
   $row = $db->loadObjectList();
   echo "

";
   foreach ($row as $item)
   {
       echo "
 $item->nom_formation | ";
       echo "$item->intitule_session | ";
       echo "du : $item->session_du | ";
       echo "au : $item->session_au

";
       echo "
";
   }
   echo "

";

A: To translate the date to another language, you can do this:
setlocale(LC_TIME, 'fr_FR');
// with $item->session_du = "2016-01-11 23:00:00"
print strftime('du : %A %d %B %Y', strtotime($item->session_du));

Will output:
lundi 11 janvier 2016

strtotime() takes a date string and return a timestamp, strftime() takes that timestamp and apply a format, returning a string based in the setlocale() configuration.
More details, here:
http://php.net/manual/en/function.setlocale.php

A: Since your using an object orientated approch you really should use the DateTime class and IntlDateFormatter.
You can use a the same formatter for any dates you have as long as it's declared before it's used.
$formatter = new IntlDateFormatter('fr_FR', IntlDateFormatter::LONG, IntlDateFormatter::LONG);

$dt = new DateTime($item->session_du);
echo "du : {$formatter->format($dt)} | ";


text:
Q: Interface and Repository naming in PHP and Laravel I'm working with the repository pattern and interfaces in Laravel and find the naming to be verbose: UserRepositoryInterface or EventRepositoryInterface. Are there other naming conventions in use that are less verbose? I want my code to remain readable to future programmers. In DDD some have suggested naming UserRepositoryInterface simply Users or AllUsers, more here: How to name repository and service interfaces?.

A: The "good" way to name your interface should be UserRepository.
When implementing a class using an interface you are making a contract : this class will use a UserRepository. Not an interface but an actual repository.
Your class will depend on an implementation of the interface but don't care which implementation will be given when you will be wiring all your components.
You should name your implementations to reflect their specifities : EloquentUserRepository for a Eloquent based repository for instance.
It make no sense to have a DefaultUserRepository. None of your implementations should be better than an other and should get a special treatment.
I wrote "good" between brackets because at the end it's more a matter of convention in your team and you should do what works for you.
You can read more on this subject in this interesting blog post : http://verraes.net/2013/09/sensible-interfaces/

A: I am suggesting you to name interface UserRepository and implementation for instance EloquentUserRepository, MongoUserRepository et cetera. Leaving interface in interface name is nowadays unnecessary when majority IDEs are able to find proper file in a flash.


text:
Q: Error when trying to access frames from multithreading video capturing I am using ltbb to stream from two cameras. ltbb creates two threads(because of two cameras) for simultaneous streaming from two cameras. It makes use of concurrent queues for fetching frames. The following code snippet displays frames:
while (waitKey(20) != 27)
  {
    //Retrieve frames from each camera capture thread
    vector<Mat> iMats(capture_source.size());

    for (int i = 0; i < capture_source.size(); i++)
    {
      Mat frame;

      //Pop frame from queue and check if the frame is valid
      if (cam.frame_queue[i]->try_pop(frame))
      {
        //Show frame on Highgui window
        // IMats.push_back(frame);
        iMats[i] = frame;
        imshow(label[i], frame);
      }

    } // end of for - loop

    int x = opencv_tri(iMats);
  }

The problem is when I am doing iMats[i] = frame and pass it to other function, It's giving me an error. It works fine when I comment iMats and stop calling opencv_tri(iMats).
Error: Segmentation fault (core dumped)
Link to opencv_tri: opencv_tri.cpp
Can anyone please explain and help me to fix this?

A: Unfortunatly I can't comment.
I think your vector is empty, therefor you can not access the [i]'th element.
vector<Mat> iMats(capture_source.size());

This creates an empty Vector with capture_source.size() elements.

A: I did not go through the whole opencv_tri function that you linked, but I spot the possible error.
you have the following
for(int i = 0;i<imats.size();i+=2)
{

...
 Mat imgATest = imats[i];
 Mat imgBTest = imats[i+1];

when i is in imats.size()-1 it will try to access:
Mat imgBTest = imats[i+1];

This is an out of bounds. since i+1 is imats.size()
You have to loop up to imats.size()-1
for(int i = 0;i<imats.size()-1;i+=2)
{

this way it will not try to access the wrong value


text:
Q: SQL insert in php not working Im very new to php and trying to get a register up and working , my code at the minute is only loading the username into the database and nothing else. Although it does enter values into other fields of the database if I hard-code them into sql insert and dont use
$users_Password

etc. btw I know this is terrible code and passwords should be hashed etc but ive literally just tore this code apart because this wont work and will add everything back in after this is sorted out cheers , this is my code
form
<form id = "Register_form" action="Register.php" method="post">
            Username: <input type="text" name="Username">

            Password: <input type="password" name="Password">

            Confirm Password: <input type="password" name="ConfirmPassword">

            First Name: <input type="text" name="FirstName">

            Surname: <input type="text" name="Surname">

            Address Line 1: <input type="text" name="AddressLine1">

            Address Line 2: <input type="text" name="AddressLine2">

            City: <input type="text" name="City">

            Telephone: <input type="text" name="Telephone">

            Mobile: <input type="text" name="Mobile">

            <input type="submit">

then in the Register.php file
<?php
                // create connection
                $con=mysqli_connect("localhost","root","","book");
                // check connection
                if(mysqli_connect_errno($con)){
                    echo "Failed to connect to MySQL: " . mysqli_connect_error();
                }

                $users_Username = $_POST['Username'];
                $users_Password = $_POST['Password'];
                $users_ConfirmPassword = $_POST['ConfirmPassword'];
                $users_FirstName = $_POST['FirstName'];
                $users_Surname = $_POST['Surname'];
                $users_AddressLine1 = $_POST['AddressLine1'];
                $users_AddressLine2 = $_POST['AddressLine2'];
                $users_City = $_POST['City'];
                $users_Telephone = $_POST['Telephone'];
                $users_Mobile = $_POST['Mobile'];
                //Multiple Error checkings such as
                if ($users_Username == "")
                {
                    echo "Please enter a username";
                    echo "";
                }
                else if ($users_Password = "")
                {
                    echo "Please enter a password";
                    echo "";
                }
                else if ($users_ConfirmPassword == $users_Password)
                {
                    if (strlen($users_Password)<=6)
                    {
                        $sql = "INSERT INTO users VALUES ('$users_Username', '$users_Password', '$users_FirstName', '$users_Surname','$users_AddressLine1','$users_AddressLine2','$users_City','$users_Telephone','$users_Mobile')";

                        if($con->query($sql) === TRUE)
                        {
                            echo "User succesfully registered";
                            echo "";

                        }
                        else
                        {
                            echo "Unable to register user, Please try again";
                            echo "";
                        }

                        //echo "
\n$sql\n
\n";
                        mysql_query($sql);
                    }
                    else
                    {
                        echo "The password you entered is too long, max characters is 6";
                        echo "";
                    }
                }
                else
                {
                    echo "Passwords do not match, Please try again";
                    echo "";
                }

                mysqli_close($con);

        ?>

It seems like nothing will insert into the database except the username , any one have a way to fix this ?
Cheers

A: You had stuff all over the place and were mixing mysql and mysqli not to mention you left yourself wide open for SQL injection. Using the script you had I stuck with mysqli used prepared statements and split your validation and persistence up. There are comments that will explain some of this
<?php
    $users_Username = $_POST['Username'];
    $users_Password = $_POST['Password'];
    $users_ConfirmPassword = $_POST['ConfirmPassword'];
    $users_FirstName = $_POST['FirstName'];
    $users_Surname = $_POST['Surname'];
    $users_AddressLine1 = $_POST['AddressLine1'];
    $users_AddressLine2 = $_POST['AddressLine2'];
    $users_City = $_POST['City'];
    $users_Telephone = $_POST['Telephone'];
    $users_Mobile = $_POST['Mobile'];

    //LETS JUST DO ERROR CHECKING ONLY
    $valid = true; //Used to verify that user input is as expected.
    //All the validation as before just as ifs and will set the
    //$valid flag to false when validation fails.
    if ($users_Username == "")
    {
        $valid = false;
        echo "Please enter a username";
        echo "";
    }
    if ($users_Password = "")
    {
        $valid = false;
        echo "Please enter a password";
        echo "";
    }
    if (strlen($users_Password)>6)
    {
        $valid = false;
        echo "The password you entered is too long, max characters is 6";
        echo "";
    }

    if ($users_ConfirmPassword != $users_Password)
    {
        $valid = false;
        echo "Passwords do not match, Please try again";
        echo "";
    }

    //Separating validation and persistence mean you only
    //open a connection and persist when needed.
    if($valid)
    {
        //NOW WE ONLY CONNECT WHEN YOU NEED TO!
        $con=mysqli_connect("localhost","root","","book");

        // check connection
        if(!$con)
        {
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
        }
        //YOU MAY NEED TO SPECIFY THE COLUMNS YOU ENTER
        $stmt = mysqli_prepare($con, "INSERT INTO users VALUES (?,?,?,?,?,?,?,?,?)");
        //ASSUMING ALL 9 PARAMETERS ARE STRINGS hence the sssssssss
        mysqli_stmt_bind_param($stmt, 'sssssssss', $users_Username,$users_Password,$users_FirstName,$users_Surname,$users_AddressLine1,$users_AddressLine2,$users_City,$users_Telephone,$users_Mobile);

        if(mysqli_stmt_execute($stmt))
        {
            echo "User succesfully registered";
            echo "";
        }

        mysqli_close($con);
    }
?>

A: What content lands in your database?
Try the following in the appropriate line:
"INSERT INTO users VALUES ('".$users_Username."', '".$users_Password."', '".$users_FirstName."', '".$users_Surname."','".$users_AddressLine1."','".$users_AddressLine2."','".$users_City."','".$users_Telephone."','".$users_Mobile."')";

PHP Params cant be evaluated in ' ' so you have to use string concatenation.


text:
Q: Creating a variable name of a property in a JSON object I'm running this code.
var output = {"records": []};
for(i = 0; i < data.length; i++)
  output.records[i] = { propertyName : data[i][propertyName] }

I expected the output to be on the following form.
{ "cat" : "mjau" }
{ "dog" : "woff" }

Instead, I get to my surprise this.
{ "propertyName" : "mjau" }
{ "propertyName" : "woff" }

How can I get variable propertyName?
I'm trying to create a parser that will create a number of records that are all cat but, when called from an other place, the records should have dog property instead. I wish to avoid creating two different code pieces for that.
I've found this question, which I suspect contains the answer to my issue. However, due to ignorance, I don't get it.

A: Keys in object literals won't be evaluated in JavaScript. So, you need to create an empty object ({}) and then assign the key dynamically:
output.records[i] = {};
output.records[i][propertyName] = data[i][propertyName]

A: var a = {b:'c'}

is just like
var a = {};
a['b'] = 'c';

What you want is
a[b] = c

that is
output.records[i] = {};
output.records[i][propertyName] = data[i][propertyName];

You have in this MDN document : Working with objects.

A: In { propertyName : data[i][propertyName] } the property name part should be constant string. It you pass a variable it wont fetch its value.
What you have to do is
for(i = 0; i < data.length; i++){
  var a = {};
  a[propertyName] = data[i][propertyName];
  output.records.push(a);
}

A: You can try this:
'"' + propertyName + '"' : ...


text:
Q: InfoPath 2010 Default Value Dropdown list using External Data Source (XML) Is there a way to set a default value for a dropdown list using an XML data source?
I don't mind manually entering it to match the dropdown field but I just can't seem to find a place for it...
Thanks.

A: As far as I know you will have to use a rule to set the field's value.  You could do it on form load, but your requirements might dictate otherwise.


text:
Q: Read API Json Data I want to create a windows console application to read Json api data, retrieve all the type="folder" items and then save the data to database. How to access to the properties of the Json data?
Json data format:
    {
 asset:{
        path:{
                Children:[
                         0:{
                            id:xxxx,
                            type: folder

                            },
                         1:{
                            id:xxxxx,
                            type: folder
                            },
                         2:{
                            id:xxxx,
                            type: page

                            }
                            ...
                        ]
                }

       },
success:ok
}

FolderModel:
public class FolderModel
    {
        public string id { get; set; }
        public string type { get; set; }
    }

//main
static void Main(string[] args)
            {

                Task T = new Task(ApiCall);
                T.Start();
                Console.ReadLine();

            }

//apicall
static async void ApiCall()
        {
        using (var client = new HttpClient())
        {

            HttpResponseMessage response = await client.GetAsync("https://apiurl/");

            response.EnsureSuccessStatusCode();

            using (HttpContent content = response.Content)
            {
                string responseBody = await response.Content.ReadAsStringAsync();

                var items = JsonConvert.DeserializeObject<FolderModel>(responseBody);
                //items id and type are null here. how to retrieve those information ??

            }

        }
    }

A: Your JSON and c# model are not identical first you need to create models to deserialize json
   public class FolderModel
    {
        public string id { get; set; }
        public string type { get; set; }
    }

    public class Path
    {
        public List<FolderModel> Children { get; set; }
    }

    public class Asset
    {
        public Path path { get; set; }
    }

    public class ResponseModel
    {

        public Asset asset { get; set; }
        public string Success { get; set; }
    }

Now you can access deserialize using
   var response = JsonConvert.DeserializeObject<ResponseModel>(responseBody);

Now you can acess properties using linq or foreach loop
Using Linq
  var folderResponse =  response.asset.path.Children.Select(x => new
                                    FolderModel { id = x.id, type = x.type });

  //or you can access like this if you need to get all fields
  var folderResponse = response.asset.path.Children.Select(x => x);

ForEach
            foreach (var folder in response.asset.path.Children)
            {
                //folder.id
                //folder.type
            }

JSON to parse
{
  "asset": {
    "path": {
      "Children": [
        {
          "id": "xxxx",
          "type": "folder"
        },
        {
          "id": "xxxxx",
          "type": "folder"
        },
        {
          "id": "xxxx",
          "type": "page"
        }
      ]
    }
  },
  "success": "ok"
}