text:
Q: Is there a well-established naming convention for PHP namespaces? So far, I've seen many different naming conventions used for PHP namespaces. Some people use PascalCase\Just\Like\For\Classes, some use underscored\lower_case\names, some even use the Java convention for package names: com\domain\project\package.
The question is very simple -- can any of these (or other) conventions be called well-established? Why? Are any of them recommended by authorities like Zend or the developers of well-known PHP frameworks?

A: I don't think you can say there is anything well established at this point, but there is an RFC discussing it for PEAR2: http://wiki.php.net/pear/rfc/pear2_naming_standards
My take is that namespaces are a form of variables, and therefore should follow the same convention as they do. I genereally prefer lowercase_underscore for free variables (As opposed to object members), so the most natural for my taste would be namespace\ClassName. This also matches the most prevalent conventions from other languages. On the other hand, the same argument could be made for pre-5.3 pseudo-namespaces, but here the de-facto standard seems to be using CamelCase.

A: A PHP Standards Working Group made up of contributors to many different PHP frameworks and projects came up with the following proposal for appropriate namespace usage:
https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md

A: Personally I like writing classnames upper camelcase, class attributes and methods lower camelcase and class attributes prefixed with an underscore.
Other local variables i'm also writing lower camelcase without an underscore prefix. Object instances are always written uppper camelcase etc. etc. I don't really think that there is a best way, you just have to be consistent to your codingstandard. This gives you the advantage of reading faster through your code and it should give a faster insight in what's happening at which codelines.

A: Some might say that PascalCase except Acronyms/Initialisms is the preferred choice. So, for example, the following are appropriate versions:

*

*'Curl'

*'CurlResponse'

*'HTTPStatusCode'

*'URL'

*'BTreeMap' (B-tree Map)

*'Id' (Identifier)

*'ID' (Identity Document)

*'Char' (Character)

*'Intl' (Internationalization)

*'Radar' (Radio Detecting and Ranging)

Source: At wiki.php.net

Extend the coding standard to explicitly specify how abbreviations and acronyms/initialisms are to be handled when writing user-level class names. The current rule is:

Classes should be given descriptive names. Avoid using abbreviations
where possible. Each word in the class name should start with a capital
letter, without underscore delimiters (CamelCaps starting with a capital
letter). The class name should be prefixed with the name of the 'parent
set' (e.g. the name of the extension)...

Source: At github.com
While it is stated that abbreviations should be avoided, it is silent on what to do if they are used; especially in the case of acronyms/initialisms. There are essentially three choices possible now:

*

*PascalCase except Acronyms/Initialisms - Which is how the majority of user-level class names are written, and it matches the approach of
many other programming languages;

*Always PascalCase - Which is basically what PSR-1 defines, however, it would make most of the currently existing user-level class names
invalid;

*Do Nothing - Which of course automatically means that any approach is allowed, and the community discussions around this topic will
continue.
...
"What class naming style should we use?" (final result):

*

*PascalCase except Acronyms: 15

*Always PascalCase: 11

Source: At wiki.php.net

PSR-1

*Namespace and Class Names
...
Class names MUST be declared in StudlyCaps.
...

Source: At php-fig.org


text:
Q: Using kafka-python to consume kafka, will the local offset reset by the seek() be submitted to kafka? Using kafka-python to consume kafka, will the local offset reset by the seek method be submitted to kafka?
I am working on a solution to obtain the rpo index of the Kafka cluster in the dual-center computer room. Use kafka-python to obtain the largest timestamp of the Kafka cluster, and take the difference between the maximum timestamps of the Kafka cluster in the two computer rooms.
Use seek() to reset the offset to the maximum offset-1 of the partition, and then poll() to get the latest message, but the message can't be gotten in the loop, check the offset of the current consumer group, and find that the message is stacked Is 0
#reset offset to (max_offset-1)
for tp,offset in offsets_dict.items():
            offset = offset - 1
            if (offset)<0:
                effective_partition = effective_partition-1
                continue
            consumer.seek(tp,offset)
            kafkaoffset = consumer.position(tp)

        if effective_partition==0:
            consumer.close()
            return max_timestamp

        try:
            Counter=0
            while(True):
                message = consumer.poll(max_records=1)
                if not message:
                    continue
                for partition, msgs in six.iteritems(message):
                    for msg in msgs:
                        max_timestamp = max(max_timestamp,int(msg.timestamp))
                        self.logger.debug(f"{max_timestamp}")
                Counter = Counter +1
                if Counter == effective_partition:
                    break
        except Exception as ex:
            raise ex
        finally:
            consumer.close()
            return max_timestamp

A: If you commit after a seek, then that will be the new offset for the group, yes.
enable_auto_commit defaults to True, and if you set that to False, there is a KafkaConsumer.commit(offsets) function that you can use to manually control this behaviour
Calling .close() also defaults to do a commit, which you should probably leave alone unless you really only wanted to seek and read a handful of messages out-of-process with a normal linear consumer process

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unsure why this cast works i have the following code:
unsigned short a, b, c, d;
unsigned long result;

a = 30000;
b = 40000;
c = 50000;
d = 60000;

result = (unsigned long)(a + b + c + d) / 4;
printf("result is %i", result);

The result of this is (30000 + 40000 + 50000 + 60000) / 4 = 180000 / 4 = 45000 which is correct. But i wonder why. I would expect the addition of unsigned shorts to overflow because it is done in 16 bit and after the addition the overflowed result is converted to unsigned long and then divided by 4.
What am i missing here?

A: Your shorts were promoted to ints before addition.
http://en.cppreference.com/w/cpp/language/implicit_conversion (the link is about C++, but C rules are basically same)

Integral promotion
...arithmetic operators do not accept types smaller than int as arguments, and integral promotions are automatically applied...


text:
Q: How to pronounce the letter 'i' Every time I read a new and unknown word containing the letter 'i' I wonder how I should pronounce it. What's very frustrating for me is that, when I look up the words, I find out that my gut feeling was wrong for most of them.
A Google search only gave a few links talking about the pronunciation of this letter, but most times they are at a very low level.
From what I found and read, finally I daresay that:

*

*i is pronounce as /aɪ/ when i +  consonant + e as in: time, site, fire, to entire, ...

*i is pronounce as /aɪ/ when i is followed by gh as in: sigh, sight, thigh, ...

*i is pronounce as /aɪ/ when i is preceded by a as in: aisle, ...

*i is pronounce as /aɪ/ when i is written as y: to try, to fly, to cry, ...

*else i is pronounce as /ɪ/: to hit, ship, sick
But there are many exceptions, too many in my opinion:

*

*to give, to notice, clandestine (/ɪ/ instead of /aɪ/)

*to fail, to contain (/eɪ/ instead of /aɪ/)

*gravity, paucity, hierarchy (/i/ instead of /aɪ/)

*pie, title, vital, giant, modifier (/aɪ/ instead of /ɪ/)

The following words are very interesting, because the pronunciation is swapped to what I expected:

*

*indecisive

*library

My vocabulary is very rudimentary, but yet I know a lot of exceptions.
So, I know that it is hard to make pronunciation rules for English words. But how can I improve my gut feeling in pronouncing new words correctly?

A:
i is pronounce as /aɪ/ when i + consonant + e as in: time, site, fire, to entire, ...

This is a special case of the "magic e" rule: vowel + consonant + e = "long" vowel.  It's a fine rule that accurately describes pronunciation — most of the time.
Some silent e's do not lengthen the vowel, but serve other purposes:

*

*To prevent a word from ending in "v", as in "give" and "live".

*To "soften" a "c", as in "notice", "office", and "practice".

OTOH, some words ending in "ce" or "ve" do have a long vowel ("ice", "hive").
I can't determine why "engine" and "opposite" have short i's.

i is pronounce as /aɪ/ when i is followed by gh as in: sigh, sight, thigh, ...

"Eigh" is pronounced /eɪ/.  (Eight reindeer pull the weight of Santa's sleigh.)  Otherwise, I can't think of exceptions to this rule.

i is pronounce as /aɪ/ when i is preceded by a as in: aisle, ...

I'm afraid that I must raise an objection here.  The main pronunciation of "ai" is /eɪ/.  (The rain in Spain falls mainly on the plain.)
Again, all English spelling rules are certain to have exceptions, like the /ɪ/ in "mountain".
The word "said" seems to be unique in prouncing "ai" as /ɛ/.

Some more rules you could use are:

*

*"tion" is pronounced /ʃən/

*"ing" is prounounced /iŋ/ (or informally, /ɪn/)

*"oi" is pronounced /ɔɪ/

*"i" followed by a double consonant (or "ck", "dg", "tch") is pronounced /ɪ/.

So, I know (or I believe to know), that it is hard to make
  pronunciation rules for English words. But how can I improve my gut
  feeling, pronouncing new words correctly?

Start by learning the pronunciation first, and then learn the spelling.  You'll know that a word is spelled right when the wavy red line under it disappears.  That's what native speakers do.

A: As John says, there are a lot of things to consider when trying to figure out a specific word's pronunciation.  I will point out, though, that I think your rules 3 and 4 are wrong, and you could supplement them with a few other rules.
3: ai is (almost) always pronounced /eɪ/:  fail, pail, mail, curtail...  (aisle is an exception to this common rule.)
4: a y is not an i, it has its own rules.  :-)
5: ity at the end of a word is pronounced /ɪti/:  gravity, city, pity...
6: ie at the end of a word is (mostly) pronounced /aɪ/: pie, lie, die..., but is /i/ if it is unstressed, as a nickname or a diminutive: Sissie, Bettie, budgie.
7: ier at the end of a word depends on the pronunciation of the word without the er:  messy (mess-i) -> messier (mess-i-r), but deny (di-naɪ) -> denier (di-naɪ-r).  (But pier and tier, not being stem + -er forms, are pronounced with an /ɪəʳ/.)

A: I'll elaborate a bit on Barrie's point, which is correct, if disappointing.
The problem is that English spelling was not designed for Modern English. It was designed for Middle English, a very different language. When Middle English changed its pronunciation to become Modern English, English spelling did not change. Furthermore, English borrowed many thousands of words from other languages, which were of course pronounced differently, and spelled differently still.
The result is that one has to choose between two strategies in learning English words, however they are spelled -- this is not a problem confined to the letter I -- or else figure out some way to mix them.

Either you can actually learn the historical rules about pronunciation and learn to distinguish the different kinds of word each rule applies to -- which amounts to learning some basic linguistics,
Or you can do as Barrie suggested, and memorize 2 things about every word you learn -- (1) how it's spelled and (2) how it's pronounced (Kenyon and Knott is your friend here) -- and just ignore the possible but treacherous correspondences you might suspect between Middle English or foreign spellings and Modern English pronunciations.

The second option amounts to giving up all hope of making sense of English spelling. Most native English speakers do this, which is simpler for them, since they already know the pronunciation.
Since Anglophone education systems don't teach anything about English language, they never learn any different, and many still believe there should be a simple rule for pronouncing every letter.

A: The issue of spelling and pronunciation is really hard in English. The language is not spoken the way that it is written.
A simple example for this: when I was at prep school, I had a sophisticated, masters degreed, native English speaker (American) teacher. Even he was really sweating on some words. He could not write the exact word on the board while he could pronunce them correctly in class. The hardship of the issue can be understood by this example.
It is a really complicated subject for people who are learning English. As I learned, there are no rules for pronunciation. When I face a new word for me, I try to pronunce it like the words I know by figuring out the similarity between the words.

A: English is a language that borrows words and sounds from other languages like German, French, Greek, Latin, and so on, and sometimes a word's pronunciation or spelling is based on where the word comes from. For example, English words that come from Latin words usually pronounce i as /ɪ/, such as in ignition /ɪgˈnɪʃən/.
If it helps you, if you find out what language a word comes from and how that language pronounces sounds or spells words, you might be able to figure out how to pronounce the word in English.


text:
Q: Getting error while using flux with GPU in Julia %%julia

# Load the data
println("start")
x_train, y_train,x_valid, y_valid=h5open("./data.h5", "r") do file
    read(file, "tr_X","tr_Y","va_X","va_Y")
    end|> gpu
println("read done")
x_train = reshape(x_train, (80,80,3,:))|> gpu
x_valid = reshape(x_valid, (80,80,3,:))|> gpu
println("reshape done")
# Add the channel layer
#x_train = Flux.unsqueeze(x_train, 3)
#x_valid = Flux.unsqueeze(x_valid, 3)
# Encode labels
#y_train = onehotbatch(y_train, 0:1)
#y_valid = onehotbatch(y_valid, 0:1)
# Create the full dataset
train_data = DataLoader(x_train, y_train, batchsize=32)|> gpu
println("generator done")
model = Chain(

    Conv((3, 3), 3=>32, stride=1, relu),

    Conv((3, 3), 32=>64, stride=1, relu),
    MaxPool((2,2); pad = 0, stride = 1),
    Dropout(0.25),

    Conv((3, 3), 64=>64, stride=1, relu),
    MaxPool((2,2); pad = 0, stride = 1),
    Dropout(0.25),

    Conv((3, 3), 64=>128, pad=1, stride=1, relu),
    MaxPool((2,2); pad = 0, stride = 1),
    Dropout(0.5),
    GlobalMeanPool(),
    flatten,
    Dense(128, 64,relu),
    Dropout(0.5),
    Dense(64, 1,sigmoid)
)|> gpu
println("chain init done")
#ŷ = model(x_valid)
#println("Prediction of first image: $(ŷ[1])")
accuracy(ŷ, y) = mean(ŷ.== y) |> gpu
loss(x, y) = Flux.crossentropy(model(x), y) |> gpu
# learning rate
lr = 0.1|> gpu
opt = Descent(lr) |> gpu
ps = Flux.params(model) |> gpu
number_epochs = 10|> gpu
println("train start")
callback() = push!(loss_vector, loss(x_train, y_train))|> gpu
loss_vector = Vector{Float64}()|> gpu
@epochs number_epochs Flux.train!(loss, ps, train_data, opt,cb=callback) |> gpu
println("post epoch")
#accuracy(model(x_train), y_train) |> gpu
println("done!")

Above is my first deep lerarning project using flux and julia. Getting below error while trying to use GPU.
RuntimeError: <PyCall.jlwrap (in a Julia function called from Python)
JULIA: InvalidIRError: compiling kernel getindex_kernel(CUDA.CuKernelContext, CuDeviceArray{Float32,4,1}, CuDeviceArray{Float32,4,1}, NTuple{4,Int64}, Base.Slice{Base.OneTo{Int64}}, Base.Slice{Base.OneTo{Int64}}, Base.Slice{Base.OneTo{Int64}}, CuDeviceArray{Int64,1,1}) resulted in invalid LLVM IR
Reason: unsupported dynamic function invocation (call to pointerref(ptr::Core.LLVMPtr{T,A}, i::Int64, ::Val{align}) where {T, A, align} in LLVM.Interop at /root/.julia/packages/LLVM/F9DFY/src/interop/pointer.jl:7)
Any help woould be great. I am using Kaggle environment for this project.


text:
Q: Extracting coordinates from FeatureCollection to add to Dictionary as values I am trying to recreate this ui.Select function with data from an imported FeatureCollection.
In the original example the ui.Select function uses a dictionary that looks like this:
var places = {
  MTV: [-122.0849, 37.3887],
  PEK: [116.4056, 39.9097],
  ZRH: [8.536, 47.376]
};

So I would like to recreate with my own FeatureCollection. My attempt at code for creating the dictionary.
function get_coords(f){return f.centroid()}

var urban_areas = ee.Dictionary.fromLists(boroughs.aggregate_array('lad17nm'),
                                          ee.List(boroughs.map(get_coords)));
print (urban_areas)

My code is here.

A: I made a 'toy' example to illustrate a possible solution.
var selector = ui.Select({placeholder:'fetching data..'})

var test_dict = ee.Dictionary.fromLists(['one', 'two'], [[0, 0], [1, 1]])

// Async fetch
test_dict.evaluate(function(dict){
  selector.items().reset(Object.keys(dict))
  selector.onChange(function(key){
    // make your process with value
    var value = dict[key]
    print(value)
  })
  selector.setPlaceholder('Select item..')
})

Map.add(selector)

link: https://code.earthengine.google.com/b183e792df540d4b4c9fbcc8b9a57b2b


text:
Q: Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...>? (57:2)
FetchPlanet.js

import React, { Component, Fragment } from "react";
import { ListGroup, Container } from "react-bootstrap";
import "./components.css";
import ListSelected from "./ListSelected";
import { Tabs, Tab } from "react-bootstrap";
export default class FetchPlanets extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      planets: null,
      selectedPlanets: []
    };
  }
  async componentDidMount() {
    const url = "https://assignment-machstatz.herokuapp.com/planet";
    const res = await fetch(url);
    const data = await res.json();
    this.setState({ planets: data, loading: false });
    console.log(this.state.planets);
  }
  fetch = e => {
    const data = this.state.selectedPlanets;
    data.push(e.target.innerText);
    this.setState({
      selectedPlanets: data
    });
  };

  render() {
    const splanets = this.state.selectedPlanets.map(function(item) {
      return
 {item}
;
    });
    return (
      <React.Fragment>
<Container fluid>
        <Tabs defaultActiveKey="listplanets" id="uncontrolled-tab-example">

  <Tab eventKey="listplanets" title="Planets List">
  {this.state.loading || !this.state.planets ? (

Loading...

        ) : (
            <ListGroup>
              {this.state.planets.map((planetnames, index) => {
                return (
                  <ListGroup.Item
                    onClick={e => {
                      this.fetch(e);
                    }}
                    className="selectlg"
                  >
                    {planetnames.id}
                  </ListGroup.Item>
                );
              })}
  </ListGroup>
  </Tab>

  <Tab eventKey="selectedplanets" title="Selected Planets">

{splanets}

  </Tab>
  </Tabs>
        </Container>
        </React.Fragment>
        );
  }
}

** Did you want a JSX fragment <>...? (57:2), Here I'm trying to create react-Bootstrap tabs, but I'm getting error as adjacent jsx elements must be wrapped in an enclosing tag. I used Div tag also but it didn't help. I used React.Fragment also... still of no use**

A: You are missing )} after </ListGroup>
import React, { Component, Fragment } from "react";
import { ListGroup, Container } from "react-bootstrap";
import "./components.css";
import ListSelected from "./ListSelected";
import { Tabs, Tab } from "react-bootstrap";
export default class FetchPlanets extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      planets: null,
      selectedPlanets: []
    };
  }
  async componentDidMount() {
    const url = "https://assignment-machstatz.herokuapp.com/planet";
    const res = await fetch(url);
    const data = await res.json();
    this.setState({ planets: data, loading: false });
    console.log(this.state.planets);
  }
  fetch = e => {
    const data = this.state.selectedPlanets;
    data.push(e.target.innerText);
    this.setState({
      selectedPlanets: data
    });
  };

  render() {
    const splanets = this.state.selectedPlanets.map(function(item) {
      return
 {item}
;
    });
    return (
      <React.Fragment>
<Container fluid>
        <Tabs defaultActiveKey="listplanets" id="uncontrolled-tab-example">

  <Tab eventKey="listplanets" title="Planets List">
  {this.state.loading || !this.state.planets ? (

Loading...

        ) : (
            <ListGroup>
              {this.state.planets.map((planetnames, index) => {
                return (
                  <ListGroup.Item
                    onClick={e => {
                      this.fetch(e);
                    }}
                    className="selectlg"
                  >
                    {planetnames.id}
                  </ListGroup.Item>
                );
              })}
  </ListGroup>
   )}
  </Tab>

  <Tab eventKey="selectedplanets" title="Selected Planets">

{splanets}

  </Tab>
  </Tabs>
        </Container>
        </React.Fragment>
        );
  }
}


text:
Q: Unable to activate the feature while deploying the solution in sharepoint 2013? I tried to deploy our solution in visual studio while activating the feature it throws an error message like these

Error 2   Error occurred in deployment step 'Activate Features': Failed to load receiver assembly Branding, Version=1.0.0.0,

Culture=neutral, PublicKeyToken=f2aaa83e584920ed" for feature
  "Branding" (ID: 1c0ad1c9-62f4-4dcf-b092-1aec1c524e47).:
  System.IO.FileNotFoundException: Could not load file or assembly
  '.Branding, Version=1.0.0.0, Culture=neutral,
  PublicKeyToken=f2aaa83e584920ed' or one of its dependencies. The
  system cannot find the file specified. File name: Branding,
  Version=1.0.0.0, Culture=neutral, PublicKeyToken=f2aaa83e584920ed'
  at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName,
  String codeBase, Evidence assemblySecurity, RuntimeAssembly
  locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder,
  Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean
  suppressSecurityChecks)    at
  System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName
  assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly,
  StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean
  throwOnFileNotFound, Boolean forIntrospection, Boolean
  suppressSecurityChecks)    at
  System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString,
  Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr
  pPrivHostBinder, Boolean forIntrospection)    at
  System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString,
  Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean
  forIntrospection)    at System.Reflection.Assembly.Load(String
  assemblyString)    at
  Microsoft.SharePoint.Administration.SPFeatureDefinition.get_ReceiverObject()
WRN: Assembly binding logging is turned OFF. To enable assembly bind failure logging, set the registry value

[HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1. Note: There
  is some performance penalty associated with assembly bind failure
  logging. To turn this feature off, remove the registry value
  [HKLM\Software\Microsoft\Fusion!EnableLog].
      0   0   Branding

If I rename the Feature name means it's working sometimes, but first time I deploying the solution means it throwing this error,Please help me to solve this issue

A: I would recommend try to deploy using the powershell like this
Add-SPSolution -LiteralPath c:\solution.wsp

Install-SPSolution -Identity solution.wsp -GACDeployment

If you dont want to do this then try this

*

*Remove feature receiver

*Clean solution

*Close Visual Studio

*Delete SharePoint project's obj folder in Windows Explorer

*Delete SharePoint project's bin folder in Windows Explorer

*Open Visual Studio and re-add feature receiver

*Start Debugging

Check the reference here
Also check this


text:
Q: C++ Builder - Problem with TShape component I have this piece of code:
TShape* T[256];

/* Other code ... */

for (int i = 255; i > 0; i--) {
     T[i]->Brush->Color = T[i - 1]->Brush->Color;
     T[i]->Pen->Color = T[i - 1]->Pen->Color;
};

The cycle is executed by a TTimer each 100 milliseconds and the Color of the first TShape change each 100 milliseconds.
During this cycle, I see a blinking white horizontal lines, because before receiving the color of the other TShape, each TShape is invalidated and becomes white.
Is there a way to avoid this behaviour?
Maybe, I must override some method?

A: I think double buffering is the key to your problem. If you are using C++Builder 2009 or newer probably setting property Controls::TWinControl::DoubleBuffered for your current frame will be enough.

A: TShape invalidates itself every time you change its Brush and Pen properties, so your loop is double-invalidating each TShape.  As a workaround, try temporarily removing the OnChange event handlers that TShape assigns internally, and then Invalidate() the TShape only once after you have finished updating it.  For example:
for (int i = 255; i > 0; i--)
{
    TNotifyEvent OldBrushChange = T[i]->Brush->OnChange;
    T[i]->Brush->OnChange = NULL;

    TNotifyEvent OldPenChange = T[i]->Pen->OnChange;
    T[i]->Pen->OnChange = NULL;

    T[i]->Brush->Color = T[i - 1]->Brush->Color;
    T[i]->Pen->Color = T[i - 1]->Pen->Color;

    T[i]->Brush->OnChange = OldBrushChange;
    T[i]->Pen->OnChange = OldPenChange;
    T[i]->Invalidate();
};


text:
Q: Will a coin topple if the center of the coin is just on the corner of the square table? 3/4th of the coin is outside the table and 1/4th is on the inside. Also assume that the center of the coin is just on the inside.

A: As long as the center is inside the corner, the coin will not fall.  The reason is that although it seems 3/4 of the coin's weight is off the table, the coin's center of mass is supported by the corner of the table, and the coin effectively rests on its center of mass.
In this case, gravitational acceleration g does not vary over the extent of the coin. So the coin's center of mass coincides with its center of gravity, and the normal force between table and coin passes through the coin's center.  If such were not the case, for example if the center were outside the corner and off the table, the normal force and the weight of the coin would create torque and the coin would topple.
If the coin's center of gravity were exactly on the corner (instead of inside the corner), any slight air current or vibration might perturb the coin's equilibrium and topple the coin.


text:
Q: Functions Date() and today() giving error in Julia I want to find the difference in two dates in Julia. However, the functions Date() and today() are giving errors on executing. On executing the following code line by line,
import Dates
origin_date = Date(2000, 01, 01)
today_date = today()
days_elapsed = today_date - origin_date

the following errors occur:
julia> import Dates
julia> origin_date = Date(2000, 01, 01)
ERROR: UndefVarError: Date not defined
Stacktrace:
 [1] top-level scope at none:0
julia> today_date = today()
ERROR: UndefVarError: today not defined
Stacktrace:
 [1] top-level scope at none:0
julia> days_elapsed = today_date - origin_date
ERROR: UndefVarError: today_date not defined
Stacktrace:
 [1] top-level scope at none:0

A: With import Dates, use Dates.Date() and Dates.today().
julia> import Dates
julia> origin_date = Dates.Date(2000, 01, 01);
julia> today_date = Dates.today();
julia> days_elapsed = today_date - origin_date
7385 days

Or instead of using import Dates, to use the functions Date() and today() as they are, first execute using Dates.
julia> using Dates
julia> origin_date = Date(2000, 01, 01);
julia> today_date = today();
julia> days_elapsed = today_date - origin_date
7385 days

More information on dates in Julia can be found here https://docs.julialang.org/en/v1/stdlib/Dates/.


text:
Q: T-SQL is not working on DBeaver on Linux I am trying to run a basic T-SQL script
    DECLARE @temptable TABLE(
      abilityTypeId BIGINT NOT NULL,
      companyId BIGINT NOT NULL
    );

    INSERT INTO @temptable(abilityTypeId, companyId)
    VALUES (1, 2);

    SELECT * FROM @temptable;

but I get the following error:

SQL Error [1087] [S0002]: Must declare the table variable "@temptable".
  Must declare the table variable "@temptable".

MERGE INTO is also not working.
Is it possible to get this working on Linux or do I have to use Visual Studio for this?

A: DBeaver parses queries one by one using a statement delimiter (";" by default) and executes them consecutively.
Try removing the empty lines and those ";".
Check more details here.


text:
Q: Mismatching kernel versions during installation inside chroot I'm trying to install Artix on a QEMU virtual machine through an automated script i've wrote, in one of the latest installation steps, where i setup Rootless Docker, it's required to enable the ip_tables kernel module by running modprobe ip_tables inside the installation mount point with chroot
The problem is that i get the following error:
modprobe: FATAL: Module ip_tables not found in directory `/lib/modules/5.13.4-artix1-1

After some further inspection, i've noticed that pacman -Q linux returns versions 5.16.10-artix1-1, and the versions on my /lib/modules is 5.13.4-artix1-1
Does chroot has anything to do with that? or the problem lies somewhere else?

A: The Artix installation process gave the new installation the most up-to-date kernel version that was available in the Artix repository, not the outdated one from the boot media.
Just running
modprobe ip_tables

will not persist over a reboot anyway; you (or your script) should instead add persistent configuration to load the module at every system reboot, finalize the rest of the Artix installation if you have not yet done so, and set up a (second) script that will continue setting up Docker the first time the system boots on its own. The second script should then remove/disable itself after it's done it's job.
Then exit the chroot and reboot the VM. You're basically reaching the end of what you can conveniently do in the installer environment before the new OS installation is actually running.


text:
Q: Docker selenium gird unable to connect our client URL We have a automation script which runs in jenkins and grid in docker.
So when ever we try to run the selenium code it connects to the grid node chrome or ff and then executes on the basis of the selenium java code.
All this happens in linux server where docker is installed and we have four container- Jenkins, Selenium grid, chrome node and ff node.
But when I am trying to run the job from jekins it fails and give the below error-
runners.TestRunner > Scenario: Extract the Report.classMethod FAILED
org.openqa.selenium.remote.UnreachableBrowserException
Caused by: java.net.NoRouteToHostException
org.openqa.selenium.remote.UnreachableBrowserException
Caused by: java.net.NoRouteToHostException
org.openqa.selenium.remote.UnreachableBrowserException
Caused by: java.net.NoRouteToHostException

Now the same works fine when I dont run that from the docker set up and do it from IntelliJ.
private WebDriver createSTAGEDriver() throws MalformedURLException {
        switch (driverType) {
            case GridChrome :
                DesiredCapabilities cap = DesiredCapabilities.chrome();
                cap.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.IGNORE);
                driver = new RemoteWebDriver(new URL("http://xx.xx.xxx.xxxx:xxxxx/wd/hub"),cap);
                break;

Not able to figure out the problem.
Any help would be really appreciate.

A: This is fixed,
Actual instead of IP in createSTAGEDriver function, I need to mention the name of the ip which was defined in my docker .yml file
version: '2'
services:
 hub:
   restart: always
   image: selenium/hub:3.14
   ports:
     - "4444:4444"
   networks:
     - "selenium-grid_default"
 firefox:
   restart: always
   image: selenium/node-firefox:3.5
   environment:
    - HUB_PORT_4444_TCP_ADDR=hub
    - HUB_PORT_4444_TCP_PORT=4444
    - NODE_MAX_INSTANCES=2
    - NODE_MAX_SESSION=2
   links:
    - "hub"

so basically instead of ip, I need to use this hub which is defined in links.


text:
Q: Create nested list using list comprehension I have two lists:
L1 = [3, 5, 7, 8, 9, 5, 6, 7, 4, 3]
L2 = [1, 4, 5, 8, 3, 6, 9, 3, 5, 9]

And I need to create sub-list for each item in L2 that is smaller than 4, add it to all the numbers in L1 that are smaller than 4.
I tried doing this:
result = [(x+y) for x in L2 if x < 4 for y in L1 if y < 4]

But it resulted me this:
[4, 4, 6, 6, 6, 6]

While the outcome should look like this:
[[4, 4], [6, 6], [6, 6]]

any idea on how should I nest it in the right way?

A: Create a nested list comprehension
>>> [[(x+y) for y in L1 if y < 4] for x in L2 if x < 4]
[[4, 4], [6, 6], [6, 6]]

Here the inner list comprehension creates the inner lists which are then appended to a single list by the outer comprehension.

A: The numbers below 4 in L1 are:
L1_below_4 = [x for x in L1 if x < 4]

And for L2:
L2_below_4 = [y for y in L2 if y < 4]

Now it's easy:
[[x + y for x in L1_below_4] for y in L2_below_4]

Or as a one-liner:
[[x + y for x in L1 if x < 4] for y in L2 if y < 4]


text:
Q: How to solve this error: explode() expects parameter 2 to be string, object given? I'm trying to setup different user types and their respective permissions in my AppServiceProvider.php in my project, and I get the error
explode() expects parameter 2 to be string, object given
Nowhere in my code do I have an explode() at least that I can see. Before adding the Inertia::share(function(){}) there was no such error.
This is my code:
public function register()
{

    Inertia::version(function () {
        return md5_file(public_path('mix-manifest.json'));
    });

    Inertia::share(function () {
       $auth = null;
       if (Auth::user()) {
           $perms = [];
           $user = Auth::user();

           if ($user->isSuperAdmin() || $user->isAdmin()) {
               $perms = [
                   [
                       'url' => '/',
                       'icon' => 'fa fa-home',
                       'name' => 'Dashboard'
                   ],
                   [
                       //rest of permissions
                   ],
               ];
           }
           if ($user->isUser()) {
               $perms = [
                   [
                       'url' => '/',
                       'icon' => 'fa fa-home',
                       'name' => 'Dashboard'
                   ],
                   [
                       //rest of permissions
                   ],
               ];
           }

           $auth = [
               'id' => Auth::user()->id,
               'name' => Auth::user()->name,
               'card' => Auth::user()->card,
               'scard' => Auth::user()->scard,
               'user_type_id' => Auth::user()->user_type_id,
               'email' => Auth::user()->email,
               'perms' => $perms
           ];
       }
       return [
           'app' => [
               'name' => Config::get('app.name'),
           ],
           'auth' => [
               'user' => $auth,
           ],
           'flash' => [
               'success' => Session::get('success'),
           ],
           'errors' => Session::get('errors') ? Session::get('errors')->getBag('default')->getMessages() : (object)[],
    ]
});

What am I doing wrong? Where i'm getting the error it doesn't specify where the error is, just what it is, it signals the last line of the code I presented as where the error is, but all that's there is the closing parenthesis and brackets.

A: Knowing nothing of Inertia, it seems you are misusing the Inertia::share function. In their docs, I see 3 examples. The first two have parameter 1 being a string (eg. 'auth.user' or 'app.name'), and the last has parameter 1 being an associative array, so each element still has a unique string key.
In your code, you are passing a closure as the first parameter. I believe that you can fix it by simply adding a name as the first parameter:
Inertia::share('auth.user', function () {
    $auth = null;
    if (Auth::user()) {
        $perms = [];
        $user = Auth::user();

        if ($user->isSuperAdmin() || $user->isAdmin()) {
            $perms = [
                [
                    'url' => '/',
                    'icon' => 'fa fa-home',
                    'name' => 'Dashboard'
                ],
                [
                    //rest of permissions
                ],
            ];
        }
        if ($user->isUser()) {
            $perms = [
                [
                    'url' => '/',
                    'icon' => 'fa fa-home',
                    'name' => 'Dashboard'
                ],
                [
                    //rest of permissions
                ],
            ];
        }

        $auth = [
            'id' => Auth::user()->id,
            'name' => Auth::user()->name,
            'card' => Auth::user()->card,
            'scard' => Auth::user()->scard,
            'user_type_id' => Auth::user()->user_type_id,
            'email' => Auth::user()->email,
            'perms' => $perms
        ];
    }
    return [
        'app' => [
            'name' => Config::get('app.name'),
        ],
        'auth' => [
            'user' => $auth,
        ],
        'flash' => [
            'success' => Session::get('success'),
        ],
        'errors' => Session::get('errors') ? Session::get('errors')->getBag('default')->getMessages() : (object)[],
    ];
});


text:
Q: A question about Confidence Interval Recently, I have some trouble with confidence interval. The specific question is as follows:
Assuming that the return of an asset$(P_t)$ conforms to a normal distribution, if the average return$(\bar{x})$ and sample variance of the asset $(s^2)$are obtained through data collection, how to construct the confidence interval of the log return$(\ln \frac{P_t}{P_{t-1}})$?
Since the form of log return looks like a t(1) distribution under the normalization, my idea is to find the similar estimator to estimate. However, I can't manage to find it. Can anyone help me solve this question? Thank you.


text:
Q: How do I a read a useragent string? I'm tracking the user agent via PHP for an app I'm building for some troubleshooting.
How do I read these strings? (I'm looking for OS, browser, and version) Are they in a standard format? Here are a few examples:
Mozilla/5.0 (Linux; U; Android 2.3.3; en-us; HTC-A9192/1.0 Build/GRI40) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1

Mozilla/5.0 (Windows NT 6.0) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.106 Safari/535.2

Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; InfoPath.2; .NET4.0C; .NET4.0E; .NET CLR 3.0.04506; .NET CLR 3.5.21022; SLCC1)

A: This is why browser sniffing (reading the browser string), is usually considered bad practice, although it is sometimes necessary. There is not a real standard for this. In the examples above, the browser name is the beginning of the line untill the slash, which is followed by the version, and a space. After that follows some platform information between brackets. But, as you can see in the 3rd line, the first word doesn't need to be the platform, it can also specify a compatibility mode. And these are only some of the browser strings.


text: Q: Magento 2 product import by PHP (Configurable,Categories) In Magento 1 I use http://avstudnitz.github.io/AvS_FastSimpleImport/ for product/category tree import.For Magento 2 I found https://github.com/firegento/FireGento_FastSimpleImport2 but seems like it does not provide configurable products and product/category linking. Maybe there is some tool like in M1 that extends Import/Export module functionality with PHP endpoints ?


text:
Q: Inserting array data using mysql insert id and if statements Ok so whilst I have been working on my PHP and MySQL skills I am new to inserting data into multiple  tables in one go. I have done some reading around the subject and I appreciate the basics and the importance of normalised data etc and as such the need to put the information into various tables.
I have pieced the code below together from some of my previous work as well as the tutorial offered at http://www.desilva.biz/mysql/insertid.html . The issue I currently face is that the tutorial I learnt the code from for inputting into various tables was not based around an array of data and whilst I have got it to almost work I cannot use my fuelrecords_id because where I have to call it in my current code it has not yet been defined. Therefore to make my code work at present I just have to use a comma for the column.
Finally I would like to perfect a way to make the if statements work correctly with the array data so if a 0 or blank is submitted as part of the array a new row is not inserted with just 0's in my database tables for that respective row of data
<?php
$wedrf=trim($_POST['FR_WE']);
list($d, $m, $y) = explode('/', $wedrf);
$mk=mktime(0, 0, 0, $m, $d, $y);
$wed_refor=strftime('%Y-%m-%d',$mk);

$con = mysql_connect("ip","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("jbsrint", $con);

//New Code

$row_data = array();
foreach($_POST['VEH_LIST_REG'] as $row=>$VEH_LIST_REG) {
$WEDATE=$wed_refor;
$VEH_LIST_REG=mysql_real_escape_string($VEH_LIST_REG);
$FR_DIE_L=mysql_real_escape_string($_POST['FR_DIE_L'][$row]);
$FR_DIE_C=mysql_real_escape_string($_POST['FR_DIE_C'][$row]);
$FR_PET_L=mysql_real_escape_string($_POST['FR_PET_L'][$row]);
$FR_PET_C=mysql_real_escape_string($_POST['FR_PET_C'][$row]);
$FR_OIL_L=mysql_real_escape_string($_POST['FR_OIL_L'][$row]);
$FR_OIL_C=mysql_real_escape_string($_POST['FR_OIL_C'][$row]);
$row_data[] = "(',', '$VEH_LIST_REG', '$WEDATE')";
$row_data1[] = "(',','$FR_DIE_L', '$FR_DIE_C', ',')";
$row_data2[] = "(',', '$FR_PET_L', '$FR_PET_C', ',')";
$row_data3[] = "(',', '$FR_OIL_L', '$FR_OIL_C', '$FR_OIL_C')";
}
if (!empty($row_data)) {
$query = 'INSERT INTO fuelrecords(FR_ID, VEH_LIST_REG, FR_WE) VALUES '.implode(',', $row_data);
#$result = mysql_query( $query);

#  get fuelrecord id
$fuelrecords_ID = mysql_insert_id();

#  if the user submitted diesel information
if( isset($FR_DIE_L) )
{

#  and insert the diesel details
$sql = "INSERT INTO fuelrecords_die(FRD_ID,FR_DIE_L,FR_DIE_C,fuelrecords_ID) VALUES ".implode(',', $row_data1);
$result = mysql_query( $sql);
}

#  if the user submitted petrol information
if( isset($FR_PET_L) )
{

#  and insert the diesel details
$sql = "INSERT INTO fuelrecords_pet(FRP_ID,FR_PET_L,FR_PET_C,fuelrecords_ID) VALUES ".implode(',', $row_data2);
$result = mysql_query( $sql);
}

#  if the user submitted oil information
if( isset($FR_OIL_L) )
{

#  and insert the oil details
$sql = "INSERT INTO fuelrecords_oil(FRO_ID,FR_OIL_L,FR_OIL_C,fuelrecords_ID) VALUES ".implode(',', $row_data3);
$result = mysql_query( $sql);
}

if (mysql_query($query))
    echo 'Successful inserted';
else
    echo 'Insert failed';
}

?>

<?php
mysql_close($con)
?>

Tables are as follows:
fuelrecords
FR_ID (Auto increment)
VEH_LIST_REG
FR_WE

fuelrecords_die
FRD_ID (AUTO INCREMENT)
FR_DIE_L
FR_DIE_C
fuelrecords_ID (foreign ID from fuelrecords)

fuelrecords_pet
FRP_ID (AUTO INCREMENT)
FR_PET_L
FR_PET_C
fuelrecords_ID (foreign ID from fuelrecords)

fuelrecords_oil
FRO_ID (AUTO INCREMENT)
FR_OIL_L
FR_OIL_C
fuelrecords_ID (foreign ID from fuelrecords)

Basically the purpose is to log vehicle fuel usage and cost. As there wont always be data for petrol, diesel and oil hence the separate tables so only needed dat is logged.
Hope this clarifies
A always all help and assistance is much appreciated.

A: If I understand your code correctly you have 4 tables: fuelrecords, fuelrecords_die, fuelrecords_pet, fuelrecords_oil.
The 3 tables fuelrecords_die, fuelrecords_pet, fuelrecords_oil each have a foreign key fuelrecords_id to fuelrecords.fr_id.
You now want to insert multiple tuples into fuelrecords and, if additional data is provided, multiple tuples into the other 3 tables. I assume the fuelrecords.fr_id column is a auto incrementing primary key.
To insert multiple tuples into fuelrecords and to have them each have a new fr_id, you just don't pass a value for the column fr_id. This is equivalent to passing NULL as value. MySQL will then automatically insert unique consecutive numbers for each tuple.
After that you can call mysql_insert_id() to get the first inserted id. Using mysql_affected_rows() you can get the number of inserted tuples. This is enough information to get the id for all lastly inserted tuples. The first is mysql_insert_id()+0 the second is mysql_insert_id()+1, ..., the last is mysql_insert_id()+(mysql_affected_rows()-1).
In the next step you iterate over your input data again and insert the fuelrecords_id into each of the tuples for the other 3 tables, using the above mentioned method. If $i is the index of your input data $_POST['FR_DIE_L'][$i] (starting at $i==0), the fuelrecords_id will be mysql_insert_id()+$i. You are only allowed to iterate to mysql_insert_id()+mysql_affected_rows()-1, but you will probably have the same count of POST-data anyways.
A much simpler but slightly less efficient way is to just do one insert into fuelrecords and then one insert into the other 3 tables for each single POST-data object. You won't have to calculate the fuelrecords_id as mysql_insert_id() will give you the correct id after each insert.
<?php

$wedrf=trim($_POST['FR_WE']);
list($d, $m, $y) = explode('/', $wedrf);
$mk=mktime(0, 0, 0, $m, $d, $y);
$wed_refor=strftime('%Y-%m-%d',$mk);

$row_data = array();

// shorthand for mysql_real_escape_string
function esc($value) {
    return mysql_real_escape_string($value);
}

// all tuples for fuelrecords to be inserted
foreach($_POST['VEH_LIST_REG'] as $row => $VEH_LIST_REG) {
    $row_data[] = "(NULL, '".esc($VEH_LIST_REG)."', '".esc($wed_refor)."')";
}

if (!empty($row_data)) {
    $query = 'INSERT INTO fuelrecords(FR_ID, VEH_LIST_REG, FR_WE) VALUES '.implode(',', $row_data);
    $result = mysql_query($query);

    # get first fuelrecord id
    $first_fuelrecords_id = mysql_insert_id();

    // all tuples for the other 3 tables. insert only if data is givin.
    $die_data = array();
    $pet_data = array();
    $oil_data = array();
    foreach($_POST['VEH_LIST_REG'] as $row => $VEH_LIST_REG) {

        // calculate the right fuelrecords_id for this tuple
        $fuelrecords_id = (int)($first_fuelrecords_id + $row);

        // insert for fuelrecords_die
        if (isset($_POST['FR_DIE_L'][$row]))
        {
            $die_data[] = "(NULL, ".$fuelrecords_id.", '".esc($_POST['FR_DIE_L'][$row])."', '".esc($_POST['FR_DIE_C'][$row])."')";
        }

        // insert for fuelrecords_pet
        if (isset($_POST['FR_PET_L'][$row]))
        {
            $pet_data[] = "(NULL, ".$fuelrecords_id.", '".esc($_POST['FR_PET_L'][$row])."', '".esc($_POST['FR_PET_C'][$row])."')";
        }

        // insert for fuelrecords_oil
        if (isset($_POST['FR_OIL_L'][$row]))
        {
            $oil_data[] = "(NULL, ".$fuelrecords_id.", '".esc($_POST['FR_OIL_L'][$row])."', '".esc($_POST['FR_OIL_C'][$row])."')";
        }
    }

    // insert the tuples into fuelrecords_die
    if (!empty($die_data))
    {
        $sql = "INSERT INTO fuelrecords_die(FRD_ID, fuelrecords_ID, FR_DIE_L, FR_DIE_C) VALUES ".implode(',', $die_data);
        $result = mysql_query( $sql);
    }

    // insert the tuples into fuelrecords_pet
    if (!empty($pet_data))
    {
        $sql = "INSERT INTO fuelrecords_pet(FRP_ID, fuelrecords_ID, FR_PET_L, FR_PET_C) VALUES ".implode(',', $pet_data);
        $result = mysql_query( $sql);
    }

    // insert the tuples into fuelrecords_oil
    if (!empty($oil_data))
    {
        $sql = "INSERT INTO fuelrecords_oil(FRO_ID, fuelrecords_ID, FR_OIL_L, FR_OIL_C) VALUES ".implode(',', $oil_data);
        $result = mysql_query( $sql);
    }
}

?>

A small off-topic addition: Try not to use upper case variable names. Upper case identifiers are usually preserved for constants:
define("MY_SHORT_PI", 3.14159265);
define("MY_CONST", "foobar");

$my_variable = "bat";

echo "I am a constant ".MY_SHORT_PI;
echo "Me too ".MY_CONST;
echo "I am a variable ".$my_variable;

This won't have any effect on the PHP interpreter. It's just a common notation to make your code readable for others. There are many style guides out there like the one from PEAR.
Second Example (see comments)
<?php

$wedrf=trim($_POST['FR_WE']);
list($d, $m, $y) = explode('/', $wedrf);
$mk=mktime(0, 0, 0, $m, $d, $y);
$wed_refor=strftime('%Y-%m-%d',$mk);

// VALUES strings for fuelrecords
$row_data = array();

// temporary storage for just _L and _C values
$die_data_tmp = array();
$pet_data_tmp = array();
$oil_data_tmp = array();

// VALUES strings for the three tables
$die_data = array();
$pet_data = array();
$oil_data = array();

// shorthand for mysql_real_escape_string
function esc($value) {
    return mysql_real_escape_string($value);
}

// all tuples for fuelrecords to be inserted
foreach($_POST['VEH_LIST_REG'] as $row => $VEH_LIST_REG) {

    // check if diesel values are greater than 0
    if (0 < (int)$_POST['FR_DIE_L'][$row] && 0 < (int)$_POST['FR_DIE_C'][$row])
        $die_data_tmp[$row] = array($_POST['FR_DIE_L'][$row], $_POST['FR_DIE_C'][$row]);

    // check if petrolium values are greater than 0
    if (0 < (int)$_POST['FR_PET_L'][$row] && 0 < (int)$_POST['FR_PET_C'][$row])
        $pet_data_tmp[$row] = array($_POST['FR_PET_L'][$row], $_POST['FR_PET_C'][$row]);

    // check if oil values are greater than 0
    if (0 < (int)$_POST['FR_OIL_L'][$row] && 0 < (int)$_POST['FR_OIL_C'][$row])
        $oil_data_tmp[$row] = array($_POST['FR_OIL_L'][$row], $_POST['FR_OIL_C'][$row]);

    // check if at least one of the 3 tables will get tuples. if not just continue
    // with the next and don't assign this fuelrecord tuple to $row_data
    if (! isset($die_data_tmp[$row]) && ! isset($pet_data_tmp[$row]) && ! isset($oil_data_tmp[$row]))
        continue;

    // all values are at least 1, so add this tuple to our inserts
    $row_data[$row] = "(NULL, '".esc($VEH_LIST_REG)."', '".esc($wed_refor)."')";
}

if (!empty($row_data)) {
    $query = 'INSERT INTO fuelrecords(FR_ID, VEH_LIST_REG, FR_WE) VALUES '.implode(',', $row_data);
    $result = mysql_query($query);

    # get first fuelrecord id
    $current_fuelrecords_id = mysql_insert_id();

    // all tuples for the other 3 tables. insert only if data is givin.
    foreach($row_data as $row => $VEH_LIST_REG) {

        // insert for fuelrecords_die
        if (isset($die_data_tmp[$row]))
        {
            $die_data[] = "(NULL, ".$current_fuelrecords_id.", '".esc($die_data_tmp[$row][0])."', '".esc($die_data_tmp[$row][1])."')";
        }

        // insert for fuelrecords_pet
        if (isset($pet_data_tmp[$row]))
        {
            $pet_data[] = "(NULL, ".$current_fuelrecords_id.", '".esc($pet_data_tmp[$row][0])."', '".esc($pet_data_tmp[$row][1])."')";
        }

        // insert for fuelrecords_oil
        if (isset($oil_data_tmp[$row]))
        {
            $oil_data[] = "(NULL, ".$current_fuelrecords_id.", '".esc($oil_data_tmp[$row][0])."', '".esc($oil_data_tmp[$row][1])."')";
        }

        // increment the fuelrecords_id for the next tuple.
        ++$current_fuelrecords_id;
    }

    // insert the tuples into fuelrecords_die
    if (!empty($die_data))
    {
        $sql = "INSERT INTO fuelrecords_die(FRD_ID, fuelrecords_ID, FR_DIE_L, FR_DIE_C) VALUES ".implode(',', $die_data);
        $result = mysql_query( $sql);
    }

    // insert the tuples into fuelrecords_pet
    if (!empty($pet_data))
    {
        $sql = "INSERT INTO fuelrecords_pet(FRP_ID, fuelrecords_ID, FR_PET_L, FR_PET_C) VALUES ".implode(',', $pet_data);
        $result = mysql_query( $sql);
    }

    // insert the tuples into fuelrecords_oil
    if (!empty($oil_data))
    {
        $sql = "INSERT INTO fuelrecords_oil(FRO_ID, fuelrecords_ID, FR_OIL_L, FR_OIL_C) VALUES ".implode(',', $oil_data);
        $result = mysql_query( $sql);
    }
}

?>


text:
Q: How to force java object to instantiate it's instance variables in specific order? Having a class:
class Test {

  Object1 object1;
  Object2 object2;

  void setObject2 (Object2 newObject) {
    if (object1.someMethod()) {
      this.object2 = newObject;
    } else {
      someOtherMethod();
    }
  }
}

How can I force object instantiation that object1 must be instantiate before object2?
For now I can think to solve it
1.by making constructor with Object2 as parameter and instantiate it there
Test(Object1 object1) {
  this.object1 = object1;
}

2.by throwing exception from the method which try to set object2
void setObject2 (Object newObject) {
  if (object1 == null) {
    throw new Exception();
  }
  ...

Is there any other, more appropriate way to achieve it?
The reason I need it is that I have to create new advertisement campaign Test for a region object1 to advertise some of the region's sites object2. Before I can add site to campaign I want to check if the site belongs to the region.

A: You can limit the initialization of object2 so that it can only be instanciated if object has been.
public void setObject2 (Object2 newObject) {
    if(object1 == null){
        throw new IllegalStateException();
    }else{
        this.object2 = newObject;
    }
}

A: A cleaner way design-wise can be to use the Builder-pattern. This way you can setup and create your objects only in correct ways instead of getting exceptions at runtime.
The programmer doesn't need to read documentation or error messages to find out what he needs to do, since the API does the "guiding" itself.

A: Yes, Initializing the variables to appropriate state SHOULD be done using constructors, you can actually create a Test class constructor to achieve the same as shown below:
public Test(Object1 obj1, Object2 obj2) {
    //if objects are null throw an error
    if(obj1 == null) {
       throw IllegalStateException("Invalid Object1 passed");
    } else {
      this.obj1 = obj1;
     //check someMethod() returns true and then set object2
     if (obj1.someMethod()) {
      this.obj2 = obj2;
     } else {
       //obj1.someMethod() is false, call someOtherMethod()
       someOtherMethod();
    }
  }

It is best practice to throw Exception (like above) from the constructor if it's mandatory variables state is not initialized properly so that the object will not be in inconsistent state after it's creation.


text:
Q: schema.org event syntax for all day events and subEvents Tried to Google out but came empty handed. I'm looking for a snippet containing example markup.
How should I mark all-day events?
How should I mark concerts having multiple performances with varying locations (for same data multiple start and end dates) aka. subEvents? This is what I tried:

                Summary text

        Location name

            <time itemprop="startDate" datetime="2014-09-15T15:00:00+03:00">00:00</time>
            —
            <time itemprop="endDate" datetime="2014-09-15T17:00:00+03:00">00:00</time>

            <time itemprop="startDate" datetime="2014-10-10T20:00:00+03:00">00:00</time>
            —
            <time itemprop="endDate" datetime="2014-10-10T22:00:00+03:00">00:00</time>

        Description

A: Based solely on http://www.google.com/webmasters/tools/richsnippets
How should I mark all-day events?
For all day events it seems that the appropriate way is to give only datetime value. End date is not required.
2015/02/17
How should I mark concerts having multiple performances with varying locations (for same data multiple start and end dates) aka. subEvents?
Notice itemref to concert name.

Foo

      Wed 3.12.2014 10:05

         Concert Hall

      <meta itemprop="startDate" content="2014-12-03T10:05:00+02:00" />
      <meta itemprop="url" content="http://www.example.com/concert/8" />

      Fri 26.12.2014 10:05

         Concert Hall

      <meta itemprop="startDate" content="2014-12-26T10:05:00+02:00" />
      <meta itemprop="url" content="http://www.example.com/concert/8" />


text:
Q: Error calling method on Button click Android i read Could not find a method onClick(View) in the activity
and java.lang.IllegalStateException: Could not find a method onClick(View) but still cant solve this..
I just try to learning Android, and i try to refreshing a list with a button click..
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/OnlineShopping"
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight=".3"
            android:text="@string/onlineShopping"
            android:textSize="10sp" />

        <Button
            android:id="@+id/MyAccount"
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight=".3"
            android:text="@string/myAccount"
            android:textSize="10sp" />

        <Button
            android:id="@+id/CheckIn"
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight=".3"
            android:onClick="refresh"
            android:text="@string/checkIn"
            android:textSize="10sp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="0.45"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/PlacesListLabel"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="3sp"
            android:text="@string/retrievingPlaces" />

        <ListView
            android:id="@+id/PlacesList"
            android:layout_width="fill_parent"
            android:layout_height="0dip"
            android:layout_weight="1" />
    </LinearLayout>

</LinearLayout>

MainActivity.java
public class MainActivity extends Activity {

  private ListView placesList;
  private List<Place> places = null;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    placesList = (ListView) findViewById(R.id.PlacesList);

    new CheckInTask().execute();

    // start retrieving the list of nearby places
    new ListOfPlacesAsyncRetriever().execute();

    placesList.setOnItemClickListener(placesListClickListener);
  }

  /**
   * AsyncTask for calling Mobile Assistant API for checking into a
   * place (e.g., a store).
   */
  private class CheckInTask extends AsyncTask<Void, Void, Void> {

    /**
     * Calls appropriate CloudEndpoint to indicate that user checked into a place.
     *
     * @param params the place where the user is checking in.
     */
    @Override
    protected Void doInBackground(Void... params) {
      CheckIn checkin = new com.mobileshopping.checkinendpoint.model.CheckIn();

      // Set the ID of the store where the user is.
      checkin.setPlaceId("StoreNo123");

      Checkinendpoint.Builder builder = new Checkinendpoint.Builder(
          AndroidHttp.newCompatibleTransport(), new JacksonFactory(), null);

      builder = CloudEndpointUtils.updateBuilder(builder);

      Checkinendpoint endpoint = builder.build();

      try {
        endpoint.insertCheckIn(checkin).execute();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }

      return null;
    }
  }

  /**
   * AsyncTask for retrieving the list of places (e.g., stores) and updating the
   * corresponding results list.
   */
  private class ListOfPlacesAsyncRetriever extends AsyncTask<Void, Void, CollectionResponsePlace> {

    @Override
    protected CollectionResponsePlace doInBackground(Void... params) {

      Placeendpoint.Builder endpointBuilder = new Placeendpoint.Builder(
          AndroidHttp.newCompatibleTransport(), new JacksonFactory(), null);

      endpointBuilder = CloudEndpointUtils.updateBuilder(endpointBuilder);

      CollectionResponsePlace result;

      Placeendpoint endpoint = endpointBuilder.build();

      try {
        result = endpoint.listPlace().execute();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        result = null;
      }
      return result;
    }

    @Override
    @SuppressWarnings("null")
    protected void onPostExecute(CollectionResponsePlace result) {
      ListAdapter placesListAdapter = createPlaceListAdapter(result.getItems());
      placesList.setAdapter(placesListAdapter);

      places = result.getItems();
    }

    public void refresh(View test){

    }

    private ListAdapter createPlaceListAdapter(List<Place> places) {
      final double kilometersInAMile = 1.60934;
      List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
      for (Place place : places) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("placeIcon", R.drawable.ic_launcher);
        map.put("placeName", place.getName());
        map.put("placeAddress", place.getAddress());
        String distance = "1.2";
        map.put("placeDistance", distance);
        data.add(map);
      }

      SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, data, R.layout.place_item,
          new String[] {"placeIcon", "placeName", "placeAddress", "placeDistance"},
          new int[] {R.id.place_Icon, R.id.place_name, R.id.place_address, R.id.place_distance});

      return adapter;
    }

  }

  private OnItemClickListener placesListClickListener = new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
      Place selectedPlace = places.get((int) arg3);

      new CheckInTask().execute();

      PlaceDetailsActivity.currentPlace = selectedPlace;
      Intent i = new Intent(MainActivity.this, PlaceDetailsActivity.class);
      startActivity(i);
      }
  };

}

from that activity_main.xml i try to call function refresh on Activity class.. but from logcat i got this :
 03-18 03:51:43.615: E/AndroidRuntime(759):
 java.lang.IllegalStateException: Could not find a method refresh(View)
 in the activity class com.mobileshopping.MainActivity
 for onClick handler on view class android.widget.Button with id 'CheckIn'

Do i need to register somewhere else or i have some missing code??

A: You have the refresh(View) method inside of your ListOfPlacesAsyncRetriever class, instead of directly inside of your MainActivity class. Move it outside of that and you should be good.

A: You have placed the refresh() method inside the Asynctask that's why the system can't find the method. But it should be a method of MainActivity class.
Now, place your refresh() method outside the AsyncTask as below...
public class MainActivity extends Activity {

    private ListView placesList;
    private List<Place> places = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        placesList = (ListView) findViewById(R.id.PlacesList);

        new CheckInTask().execute();

        // start retrieving the list of nearby places
        new ListOfPlacesAsyncRetriever().execute();

        placesList.setOnItemClickListener(placesListClickListener);

    }

    public void refresh(View test){

    }

   .............

   ...........
}


text:
Q: Checking for null and set value is not allowed using `?` Why is setting a value using the new ? operator for pre-checking of not null is not usable for assignments?
For example:
var list = // ... Some list
var entry = list.FirstOrDefault();
entry?.Value = 123;

This does not compile due to the error:

The left-hand side of an assignment must be a variable, property or indexer.

But calling a method or some thing else works.
What is the reason for this compiler behavior?

A: C# compiler could definitely make this statement work by declaring that once the chain of ?s evaluates to null, all further processing stops.
The problem, however, is what to do when there are side effects on the right:
entry?.Value = CallSomeFunctionWithSideEffects(123);

Semantics of this is drastically different from other assignments, when the right-hand side is always evaluated. Here, however, evaluation of the right-hand side would need to be postponed until the left side is known to produce a non-null value.
Function invocation does not suffer from the same problem, because invocation target is processed ahead of parameters:
entry?.SetValue(CallSomeFunctionWithSideEffects(123));

A: Because entry?.Value might evaluate to null.
Then your code is equivalent to
null = 123;

which is not valid.


text:
Q: numpy: calculate cross-covariance, without calculating the whole covariance matrix The numpy.cov(x, y) with 1-d array inputs returns the entire 2x2 covariance matrix. Is there a way to calculate only the cross-covariance, i.e. E[xy] - E[x]E[y] without wasting time on calculating the two variances?
PS. How does one write equations on here? The $$ does not seem to work as it does on other Stack websites.

A: What's wrong with simply implementing the equation you wrote?
# E[xy] - E[x]E[y]
cov = (x * y).mean() - x.mean() * y.mean()


text:
Q: How do I use a code-cell print function only to render a hyperlink plus text in Jupyter notebook? The following link allows for a way to render an HTML URL inside a python3 print() function within a Jupyter notebook code cell,
https://github.com/jupyterlab/jupyterlab/issues/7393#issue-510053776,
which defines a custom URL class,
"""URL Wrapper."""

from dataclasses import dataclass

@dataclass(frozen=True)
class Url:
    """Wrapper around a URL string to provide nice display in IPython environments."""

    __url: str

    def _repr_html_(self):
        """HTML link to this URL."""
        return f'{self.__url}' # problem here (*)

    def __str__(self):
        """Return the underlying string."""
        return self.__url

The commentator notes that one must use str(url()) to achieve the desired result.
Unlike (I think) the now built-in rendering of this, I am trying to use this custom class thus:
linker = lambda my_string: str(Url('https://www.google.com/%s' % my_string))
print('URL for my_string is here',linker('search'))

I would like the linker('search') to render as the string 'search' with the full hyperlink (https://www.google.com/search) behind. The built-in behaviour does not render 'search' but rather the full hyperlink, and I cannot find a way to successfully modify the custom class to do this. At line (*) above I have tried:
return f'{self.__url}'
return f'{"test_text"}'

etc. but so far in vain.
This answer helps a bit but doesn't explicitly use the print function as per my requirements: https://stackoverflow.com/a/43254984/1021819
What am I missing?

A: This is a bit jank, but seems to work:

class RenderHyperlink(object):
    def __init__(self, key, link, *args):
        link = link + "/" if not link.endswith("/") else link

        for arg in args:
            link += arg + "/"

        self.__url = "{}".format(link, key)

    def __repr__(self):
        from IPython.core.display import display, HTML
        display(HTML(self.__url))
        return "" # hacky way to return a string despite not returning anything

# notice that you can also add other parameters to the link
print(RenderHyperlink("search", "https://www.google.com/search", "hello"))

Output:
The link points to "https://www.google.com/search/hello/"


text:
Q: Calling convention mismatch for x64 floating point functions I'm having a weird error. I have one module compiled by one compiler (msvc in this case), that calls code loaded from another module compiled by a seperate compiler (TCC).
The tcc code provides a callback function that for both modules are defined like this:
typedef float( * ScaleFunc)(float value, float _min, float _max);

The MSVC code calls the code like this:
    finalValue = extScale(val, _min, _max);
000007FEECAFCF52  mov         rax,qword ptr [this]
000007FEECAFCF5A  movss       xmm2,dword ptr [rax+0D0h]
000007FEECAFCF62  mov         rax,qword ptr [this]
000007FEECAFCF6A  movss       xmm1,dword ptr [rax+0CCh]
000007FEECAFCF72  movss       xmm0,dword ptr [val]
000007FEECAFCF78  mov         rax,qword ptr [this]
000007FEECAFCF80  call        qword ptr [rax+0B8h]
000007FEECAFCF86  movss       dword ptr [finalValue],xmm0

and the function compiled by TCC looks like this:
    float linear_scale(float value, float _min, float _max)
    {
        return value * (_max - _min) + _min;
    }
0000000000503DC4  push        rbp
0000000000503DC5  mov         rbp,rsp
0000000000503DC8  sub         rsp,0
0000000000503DCF  mov         qword ptr [rbp+10h],rcx
0000000000503DD3  mov         qword ptr [rbp+18h],rdx
0000000000503DD7  mov         qword ptr [rbp+20h],r8
0000000000503DDB  movd        xmm0,dword ptr [rbp+20h]
0000000000503DE0  subss       xmm0,dword ptr [rbp+18h]
0000000000503DE5  movq        xmm1,xmm0
0000000000503DE9  movd        xmm0,dword ptr [rbp+10h]
0000000000503DEE  mulss       xmm0,xmm1
0000000000503DF2  addss       xmm0,dword ptr [rbp+18h]
0000000000503DF7  jmp         0000000000503DFC
0000000000503DFC  leave
0000000000503DFD  ret

It seems that TCC expects the arguments in the integer registers r6 to r8, while msvc puts them in the sse registers. I thought that x64 (on windows) defines one common calling convention? What exactly is going on here, and how can i enforce the same model on both platforms?
The same code works correctly in 32-bit mode. Weirdly enough, on OSX (where the other code is compiled by llvm) it works in both modes (32 and 64-bit). Ill see if i can fetch some assembly from there, later.
---- edit ----
I have created a working solution. It is however, without doubt, the dirtiest hack i've ever made (bar questionable inline assembly, unfortunately it isn't available on msvc 64-bit :)).
// passes first three floating point arguments in r6 to r8
template<typename sseType>
    sseType TCCAssemblyHelper(ScaleFunc cb, sseType val, sseType _min, sseType _max)
    {
        sseType xmm0(val), xmm1(_min), xmm2(_max);
        long long rcx, rdx, r8;
        rcx = *(long long*)&xmm0;
        rdx = *(long long*)&xmm1;
        r8 = *(long long*)&xmm2;

        typedef float(*interMedFunc)(long long rcx, long long rdx, long long r8);

        interMedFunc helperFunc = reinterpret_cast<interMedFunc>(cb);
        return helperFunc(rcx, rdx, r8);
    }


text:
Q: C issues with extended ASCII characters I'm having trouble using variables in place of numeric values for characters in printf statements.
For example, printf("%c", 201) displays ╔ as I want it to but printf("%c", var) when var is of type char and var=201 displays ♫.
Anyone have any information as to what's going on?

A: In fact if there is no l modifer the argument is converted to unsigned char so that's why you didn't observe any change when you changed your variable types, what you actually need is
printf("%lc", var);

but in
signed char var = 201;

overflow indeed occurs, so you should be careful.


text:
Q: Is mappingFileUploadEnabled set to false by default for Firebase Crashlytics in Android Studio? I recently ran into an issue with my Firebase Crashlytics where the line of code that crashed was false, because the stack trace that led up to that moment was not even linked to that line of code.
I had a suspicion that the error may be caused because of Minifying the release apk. The file the line of code was from was already in the 'proguard-project.txt' as below:

-keepattributes Exceptions,InnerClasses,SourceFile,LineNumberTable,EnclosingMethod,Signature,*Annotation*

-keepclassmembers class com.SomeCompany.SomeClass.** {
    public static <fields>;
}

and this is what is going on in build.gradle:
        release {
            debuggable false
            minifyEnabled true
            proguardFile getDefaultProguardFile('proguard-android-optimize.txt')
            proguardFile 'proguard-project.txt'
            signingConfig signingConfigs.production
            ndk {
                abiFilters "armeabi-v7a", "arm64-v8a"
            }
            manifestPlaceholders = [xxx:"XXX"]

        }

I read some Google Documentation about Readable crash reports in Crashlytics Dashboard and they mentioned adding this (below) to your APK environments:
      firebaseCrashlytics {
        mappingFileUploadEnabled false // Or True
      }

So I was wondering, is mappingFileUploadEnabled already set to False by default? Or should I add that in? Would there be a difference if I added that in? (For context, I would like my Firebase crashes to be more readable)

A: As far as I know, the default is true. Insert the code below into proguard-rules.pro
-keepattributes SourceFile,LineNumberTable        # Keep file names and line numbers.
-keep public class * extends java.lang.Exception  # Optional: Keep custom exceptions.


text:
Q: k-Nearest Neighbors rundown I'm trying to follow an example on k-Nearest Neighbors and I'm not sure about the numpy command syntax. I'm supposed to be doing a matrix-wise distance calculation and the code given is
def classify(inputVector, trainingData,labels,k):
     dataSetSize=trainingData.shape[0]
     diffMat=tile(inputVector,(dataSetSize,1))-trainingData
     sqDiffMat = diffMat**2
     sqDistances = sqDiffMat.sum(axis=1)
     distances = sqDistances**0.5
     sortedDistIndicies = distances.argsort()
for i in range(k):
    voteIlabel = labels[sortedDistIndicies[i]]
    classCount[voteIlabel] = classCount.get(voteIlabel,0) + 1
    sortedClassCount = sorted(classCount.iteritems(), key=operator.itemgetter(1), reverse=True)
    return sortedClassCount[0][0]

def createDataSet():
     group = array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])
     labels = ['A','A','B','B']
     return group, labels

my question is how does sqDistances**0.5 amount to the distance equation ((A[0]-B[0])+(A[1]-B[1]))^1/2? I don't follow how tile influences it specifically how the matrix is made from (datasetsize,1)-training data.

A: I hope the following will explain the working.
Numpy tile : https://docs.scipy.org/doc/numpy/reference/generated/numpy.tile.html
Using this function, you are creating matrix from input vector same to the shape of training data. From this matrix you are subtracting training data which will give you some part from what you mentioned say test[0]-train[0] i.e. element wise difference.
Then you squared each obtained element by using diffMat**2 and then taken sum along axis = 1 (https://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html). This resulted in equations like (test[0] - train[0])^2 + (test[1] - train[1])^2.
Next by taking sqDistances**0.5 , it will give Euclidean distance.
To calculate Euclidean distance, this might be helpful
https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.euclidean.html#scipy.spatial.distance.euclidean


text:
Q: Upgrading to Windows 10 I bought a Dell XPS 15 almost 4 years ago. It had just 500 GB. So to recover space from recovery partition, I burnt dell recovery on to disks. It took 2 DVDs to burn the recovery image. Then I created ISOs of those DVDs. Finally I formatted recovery partition, that saved me some 10+ GBs. Now I have recovery disks and ISOs. However now my DVD drive is screwed up. It is not functioning well. And I am currently running Ubuntu.
Now that Microsoft made Windows 10 upgrade free, I thought I should get back to the factory Windows 7 by applying recovery and get the licensed Windows 10 by upgrading.
(1) But since I am not able to run recovery disks as my four year old DVD drive is not functioning well and
(2) I don't know if I can create recovery USB from recovery ISOs, I don't find any way to get back to my old factory Windows 7 and upgrade to Windows 10.
Is there any way to resolve this?


text:
Q: How can i prevent form the user to move the point beyond the pictureBox1 borders? This is all the events and functions in my Form1 what should i do ?
I need to detect the borders/bounds of the pictureBox1 control and stop the mouse move when its touching the borders.
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {

            if (e.Button == MouseButtons.Left)
            {
                label1.Text = e.X.ToString();
                label2.Text = e.Y.ToString();
                label1.Visible = true;
                label2.Visible = true;
                label3.Visible = true;
                label4.Visible = true;
                // find the index that is closest to the current mouse location
                MinDist = float.MaxValue;

                for (idx = 0; idx < Point_X.Count; ++idx)
                {
                    float dx = Point_X[idx] - e.X;
                    float dy = Point_Y[idx] - e.Y;
                    float dist = (float)Math.Sqrt(dx * dx + dy * dy);

                    if (dist < MinDist)
                    {
                        MinDist = dist;
                        selectedIndex = idx;
                    }
                }

                if (MinDist < 5)
                {
                    mouseMove = true;
                    OriginalX = Point_X[(int)selectedIndex];
                    OriginalY = Point_Y[(int)selectedIndex];

                    if (cyclicSelectedIndex.Count() == 2)
                    {
                        cyclicSelectedIndex[currentCyclicIndex] = (int)selectedIndex;
                        currentCyclicIndex++;
                        if (currentCyclicIndex > 1)
                        {
                            currentCyclicIndex = 0;
                        }
                        if ((cyclicSelectedIndex[0] == cyclicSelectedIndex[1]) || (cyclicSelectedIndex[0] == -1) || (cyclicSelectedIndex[1] == -1))
                        {
                            button2.Enabled = false;
                        }
                        else
                        {
                            button2.Enabled = true;
                        }

                        label13.Text = selectedIndex.ToString();
                        label13.Visible = true;
                        label14.Visible = true;

                        listView1.Items.Add(selectedIndex.ToString()).EnsureVisible();
                    }

                }

            }
        }

        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            if (mouseMove == true)
            {
                Point NewPoint = e.Location;
                Point_X[(int)selectedIndex] = NewPoint.X;
                Point_Y[(int)selectedIndex] = NewPoint.Y;
                label1.Text = NewPoint.X.ToString();
                label2.Text = NewPoint.Y.ToString();
                pictureBox1.Refresh();

                Point_X[(int)selectedIndex] = Math.Max(pictureBox1.Left, Math.Min(pictureBox1.Right, NewPoint.X));

            }

        }

        private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
        {
            if (mouseMove == true)
            {
                Point NewPoint = e.Location;
                Point_X[(int)selectedIndex] = NewPoint.X;
                Point_Y[(int)selectedIndex] = NewPoint.Y;
                mouseMove = false;
            }

        }

        private void button1_Click(object sender, EventArgs e)
        {
            halfX = pictureBox1.ClientRectangle.Width / 2;
            halfY = pictureBox1.ClientRectangle.Height / 2;
            Random rnd = new Random();
            offsetX = rnd.Next(-10, 10);
            offsetY = rnd.Next(-10, 10);
            addPoint(halfX + offsetX, halfY + offsetY);
            pictureBox1.Refresh();
            numberOfPoints++;
            label16.Text = numberOfPoints.ToString();
            label16.Visible = true;
            label15.Visible = true;

        }

        private void addPoint(float x , float y)
        {
            Point_X.Add(x);
            Point_Y.Add(y);
            label5.Text = x.ToString();
            label6.Text = y.ToString();
            label5.Visible = true;
            label6.Visible = true;
            label7.Visible = true;
            label8.Visible = true;
        }

private void pictureBox1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
        {
           Point connectionPointStart;
           Point connectionPointEnd;
           Graphics g = e.Graphics;
           g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
           SolidBrush brush = new SolidBrush(Color.Red);
           Pen p = new Pen(brush);
               for (int idx = 0; idx < Point_X.Count; ++idx)
               {
                   Point dPoint = new Point((int)Point_X[idx], (int)Point_Y[idx]);
                   dPoint.X = dPoint.X - 5; // was - 2
                   dPoint.Y = dPoint.Y - 5; // was - 2
                   Rectangle rect = new Rectangle(dPoint, new Size(10, 10));
                   g.FillEllipse(brush, rect);
               }

               for (int i = 0; i < connectionStart.Count; i++)
               {

                   int startIndex = connectionStart[i];
                   int endIndex = connectionEnd[i];

                   connectionPointStart = new Point((int)Point_X[startIndex], (int)Point_Y[startIndex]);
                   connectionPointEnd = new Point((int)Point_X[endIndex], (int)Point_Y[endIndex]);
                   p.Width = 4;
                   g.DrawLine(p, connectionPointStart, connectionPointEnd);

               }

        }

private void button2_Click(object sender, EventArgs e)
        {
            addConnection(cyclicSelectedIndex[0], cyclicSelectedIndex[1]);
            pictureBox1.Invalidate();
        }

        private void addConnection(int i, int j)
        {

            if (cyclicSelectedIndex[0] == -1)
            {
                return;
            }
            if (cyclicSelectedIndex[0] == cyclicSelectedIndex[1])
            {
                return;
            }

            if (connectionStart.Count() == 0)
            {
                connectionStart.Add(i);
                connectionEnd.Add(j);
                //label12.Text = i.ToString();
                //label11.Text = j.ToString();
                label12.Text = connectionStart[0].ToString();
                label11.Text = connectionEnd[0].ToString();
                label9.Visible = true;
                label10.Visible = true;
                label11.Visible = true;
                label12.Visible = true;
                return;
            }

            for (int f = 0; f < connectionStart.Count(); f++)
            {
                if ((connectionStart[f] == i && connectionEnd[f] == j) || (connectionStart[f] == j && connectionEnd[f] == i)) // this checking dosent work good !
                {
                    button2.Enabled = false;
                    return;
                }
                else
                {
                    label12.Text = connectionStart[f].ToString();
                    label11.Text = connectionEnd[f].ToString();
                    label9.Visible = true;
                    label10.Visible = true;
                    label11.Visible = true;
                    label12.Visible = true;
                }
            }

            connectionStart.Add(i);
            connectionEnd.Add(j);

        }

Im not sure how to explain it. But how can i do it ?
Thanks.

A: When calculating the X value use Math.Max with that and the left boundary of the image, and Min on the right boundary of the image.  Do the same with the Y value on the Top and Bottom.
Point_X[(int)selectedIndex] = Math.Max(imageLeft, Math.Min(imageRight, NewPoint.X));

I assume you can determine the left/right/top/bottom of the image?


text:
Q: Factories Not Found in Laravel 6 I'm stuck... I'm trying to get a set of factories working in Laravel 6, an continuously get the following error:
InvalidArgumentException with message 'Unable to locate factory with name [default] [User].'

There's several other posts about this on here and around the web, and I've tried all of those solutions. My code for the factories is as follows:
<?php

/** @var \Illuminate\Database\Eloquent\Factory $factory */

use App\Thread;
use Faker\Generator as Faker;

$factory->define(Thread::class, function (Faker $faker) {
    return [
        'user_id' => function () {
            return factory('App\User')->create()->id;
        },
        'title' => $faker->sentence,
        'body' => $faker->paragraph
    ];
});

I'm using php artisan tinker to try and generate DB entries so I can work on the rest of my models etc. The command I'm using is as follows:
factory('Thread',50)->create()

I've tried specifying the name space in the factory call, I've tried putting it in double quotes, I've tried adding the '::class' at the end. The controllers are there, the models are there, the migrations are working as expected, but every time I run the factory in tinker, it won't give it to me. Most of the documentation that I've found is referencing older versions of Laravel as well, so I'm not sure if they are providing me with correct syntax.
It's worth noting, the stock provided UserFactory doesn't work either. This is a fresh download of Laravel 6 that I did today to go through a course over at Laracasts. The course is older, focused on Laravel 5.4, but I can figure out the conversion... I just can't get this to work to save my life and I can't figure out why.
I've got the whole project uploaded here if you want to view additional code: https://github.com/aarpie100/laracasts_forum
Help?

A: Try sending Thread::class instead of Thread as a string. If you are sending as string it should be 'App\Thread' I think.

A: Factory function When you call
the class name you should write it like this (Thread :: class)


text:
Q: How to get values of checked multiple checkbox and also checked checkboxes dynamically from database. facing trouble to operate simultaneously vuejs: if i get values of checked box by v-model but not set checkbox checked dynaiclly from database. On other hand if i can set chechbox checked dynamically but not able to get values of checked checkbox.
With this i get value of checked checkbox but not set checked dynamically

   <input  type="checkbox" :value="swv.id" v-model="checkshifts"
    @change="shiftSwitch()"   />
     {{ swv.name}}

----------------------------------------
data :  {1: {id: 1, name: "Morning", active: true}, 2: {id: 2, name: "Afternoon", active: false},…}

if set checkbox checked dynamically with the following code but not able get values of checked check box.

   <input  type="checkbox"  v-model="swv.active"
    @change="shiftSwitch()"   />
     {{ swv.name}}

I expected that both operation should worked together. thanks

A: Firstly, updating database dynamically in such a way is not a very good idea, because it's an asynchronous operation and you can have a loads of concurrency issues with unpredictable results if someone checks/unchecks the checkbox several times before the previous update process is not finished. So you'd better have a special button to update the data an block the UI during update.
But if you insist on acting like this, the best way, I think, is to not set a model for a checked, but to bind it one way and on click toggle it directly in the model object. Something like this

   <input  type="checkbox"  :checked="swv.active"
    @click.prevent = "shiftSwitch(swv)"   />
     {{ swv.name}}

and in component
...
methods:{
    shiftSwitch:function(swv){
        swv.active = !swv.active;
        ...
    }
},
...

A: yes i resolved this trouble Firstly set checkbox checked dynaiclly from database  see the code below.
HTML

          <input class="js-small" type="checkbox"  v-model="swv.active"
            @change="shiftSwitch()"   />
            {{ swv.name}}

**Data**
appointment.switch_shift: {
1: {id: 1, name: "Morning", active: false}
2: {id: 2, name: "Afternoon", active: true}
3: {id: 3, name: "Evening", active: false}
}

 see one thing when i checked any of checkbox of Morning , Afternoon, Evening then corresponds data row active become true like below
{id: 1, name: "Morning", active: true}

and when uncheck then {id: 1, name: "Morning", active: false}
use data of this.appointment.switch_shift to post for updation in database.
Method
shiftSwitch:function(id){
  axios.post(this.switchshiftroute , {'opd_id':this.opdid , 'shifts': this.appointment.switch_shift})
      .then( (response)=>{
        this.getAppointments();
          console.log(response.data);
      }).catch((error)=>{
        console.log(error);
      })

    }


text:
Q: Update of a specific property in the list of objects I have a list of dataArray objects
I want to associate TextInput with a specific object in this list.
Every change of text must also change the dataArray in state
How to do it correctly? The code below does not work
export default class MyClass extends Component {
  constructor(props) {
    super(props);

    this.state = {
      dataArray: this.props.dataArray
    };
  }

  _renderContent = section => {
    let arrayIdx = this.state.dataArray.findIndex(
      x => x.title == section.title
    );
    return (
      <TextInput
        value={this.state.dataArray[arrayIdx].content}
        onChangeText={con =>
          this.setState({
            dataArray: update(this.state.dataArray, {
              arrayIdx: { content: { $set: con } }
            })
          })
        }
      />
    );
  };

  render() {
    return (
      <Container>
        <Content padder>
          <Accordion
            dataArray={this.state.dataArray}
            renderContent={this._renderContent}
          />
        </Content>
      </Container>
    );
  }
}

A: The issue is you are literally updating arrayIdx instead of the index that it refers to. You need to use a Computed Property Name like [arrayIdx].
[arrayIdx]: { content: { $set: con } }


text:
Q: Force next interface key to have the same type as the previous key interface X {
 a: any;
 b: the same as a;
}

Can I in some way force X.b to have the same type as the X.a?
an example:
fun(data: X) {
   ...
}

fun({a: 'text', b: 'otherText'}) <-- fine, because b is of type string as a.
fun({a: 'text', b: false}) <-- error because b doesn't match a type.

A: I think what your looking for is something called generics.
eg.
interface X<T> {
 a: T;
 b: T;
}

function fun(data: X<string>) {
}

fun({ a: "abc", b: "one" }); //ok
fun({ a: "abc", b: false }); //fail


text:
Q: Celery - ImportError: No module named tasks I want to use Celery in Flask. Here's my directory listing:-
c26_calendar
|-- c26_calendar
|   |-- celery_config.py
|   |-- __init__.py
|   |-- settings.py
|-- manage.py
|-- modules
|   |-- __init__.py
|   |-- __init__.pyc
|   |-- messages
|   |   |-- __init__.py
|   |   |-- models.py
|   |   |-- views.py
|   |   |-- tasks.py
|   |-- tasks
|   |   |-- __init__.py
|   |   |-- models.py
|   |   |-- views.py
|   `-- user
|       |-- fb_keys.json
|       |-- fb.py
|       |-- helpers.py
|       |-- __init__.py
|       |-- models.py
|       |-- tasks.py
|       |-- views.py
|-- __init__.py

My c26_calendar/c26_calendar/__init__.py is
from celery import Celery
from flask import Flask
from flask.ext.mongoengine import MongoEngine

app = Flask(__name__, static_url_path='')
app.config["MONGODB_SETTINGS"] = {'DB': "calendar"}
app.config["SECRET_KEY"] = ""

celery = Celery('c26_calendar')
celery.config_from_object('c26_calendar.celery_config')

db = MongoEngine(app)

def register_blueprints(app):
    from modules.user.views import user
    from modules.messages.views import messages
    from modules.tasks.views import tasks

    app.register_blueprint(user)
    app.register_blueprint(messages)
    app.register_blueprint(tasks)

register_blueprints(app)

if __name__ == '__main__':
    app.run()

My c26_calendar/celery_config.py is
CELERY_BROKER_URL = 'redis://localhost:6379/0'
CELERY_RESULT_BACKEND = 'redis://localhost:6379/0'
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TIMEZONE = 'Europe/Oslo'
CELERY_ENABLE_UTC = True
CELERY_IMPORTS = ('tasks')
CELERY_CREATE_MISSING_QUEUES = True
CELERY_DEFAULT_RATE_LIMIT = '10/m'
CELERYD_MAX_TASKS_PER_CHILD = 10

PS: There is a module called tasks which has nothing to do with celery tasks.
I want to include all the tasks from every module. I ran the following command from inside the root application directory, ie
celery -A c26_calendar.celery worker

It throws an error saying ImportError: No module named tasks. Following is the stack-trace:-
Traceback (most recent call last):
  File "/usr/local/bin/celery", line 11, in <module>
    sys.exit(main())
  File "/usr/local/lib/python2.7/dist-packages/celery/__main__.py", line 30, in main
    main()
  File "/usr/local/lib/python2.7/dist-packages/celery/bin/celery.py", line 81, in main
    cmd.execute_from_commandline(argv)
  File "/usr/local/lib/python2.7/dist-packages/celery/bin/celery.py", line 769, in execute_from_commandline
    super(CeleryCommand, self).execute_from_commandline(argv)))
  File "/usr/local/lib/python2.7/dist-packages/celery/bin/base.py", line 311, in execute_from_commandline
    return self.handle_argv(self.prog_name, argv[1:])
  File "/usr/local/lib/python2.7/dist-packages/celery/bin/celery.py", line 761, in handle_argv
    return self.execute(command, argv)
  File "/usr/local/lib/python2.7/dist-packages/celery/bin/celery.py", line 693, in execute
    ).run_from_argv(self.prog_name, argv[1:], command=argv[0])
  File "/usr/local/lib/python2.7/dist-packages/celery/bin/worker.py", line 179, in run_from_argv
    return self(*args, **options)
  File "/usr/local/lib/python2.7/dist-packages/celery/bin/base.py", line 274, in __call__
    ret = self.run(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/celery/bin/worker.py", line 212, in run
    state_db=self.node_format(state_db, hostname), **kwargs
  File "/usr/local/lib/python2.7/dist-packages/celery/worker/__init__.py", line 95, in __init__
    self.app.loader.init_worker()
  File "/usr/local/lib/python2.7/dist-packages/celery/loaders/base.py", line 128, in init_worker
    self.import_default_modules()
  File "/usr/local/lib/python2.7/dist-packages/celery/loaders/base.py", line 121, in import_default_modules
    tuple(maybe_list(self.app.conf.CELERY_INCLUDE))
  File "/usr/local/lib/python2.7/dist-packages/celery/loaders/base.py", line 103, in import_task_module
    return self.import_from_cwd(module)
  File "/usr/local/lib/python2.7/dist-packages/celery/loaders/base.py", line 112, in import_from_cwd
    package=package,
  File "/usr/local/lib/python2.7/dist-packages/celery/utils/imports.py", line 101, in import_from_cwd
    return imp(module, package=package)
  File "/usr/local/lib/python2.7/dist-packages/celery/loaders/base.py", line 106, in import_module
    return importlib.import_module(module, package=package)
  File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)

What wrong am I doing? How do I run the celery?

A: Your base path is /path/to/c26_calendar/. Every paths must be relative to base path.
Instead of
CELERY_IMPORTS = ('tasks')

use
CELERY_IMPORTS = ('modules/tasks',)