text:
Q: Dynamodb scan with condition I have a table in dynamodb like this:
TableName : "User",
KeySchema: [
    { AttributeName: "id", KeyType: "HASH"}  //Partition key
],
AttributeDefinitions: [
    { AttributeName: "id", AttributeType: "S" }
],
ProvisionedThroughput: {
    ReadCapacityUnits: 10,
    WriteCapacityUnits: 10
}

Now I am trying to search a user:
var params = {
    TableName: 'User',
    FilterExpression: 'contains(id, :value)',
    ExpressionAttributeValues: {
    ':value': 'ronaldo'
    }
};

dynamodb.scan(params, function(err, data) {
    if (err) ppJson(err); // an error occurred
    else ppJson(data); // successful response
});

It's very simple, but I got a lot errors:
"message": "Expected params.ExpressionAttributeValues['value'] to be a structure"

Anyone got this ?

A: You can try this code:
I got the same issue.
Here structure meaning we should supply DataType while passing the value to It.
        var params = {
            TableName: 'User',
            FilterExpression: 'contains(id, :value)',
            ExpressionAttributeValues: {
                ':value': {
                    'S': 'ronaldo'
                }
            }
        };

        dynamodb.scan(params, function(err, data) {
            if (err) ppJson(err); // an error occurred
            else ppJson(data); // successful response
        });

Where S means String Data type.


text:
Q: symfony2 tinymce doesn't shows up i ve installed the bundle  stfalcon/tinymce-bundle and i followed the doc (https://github.com/stfalcon/TinymceBundle), I have a <textarea class = "tinymce"></textarea>
 , but when i put  {{ tinymce_init() }} into my template, there is nothing.
But when i press CTRL+U i can see that the JS files are loaded (from web folder). There is no exception, just nothing besides my html textarea.
I've been on the web for hours but no solution is working for me.
Can you help me?
Thanks

redpajama_set_name: RedPajamaStackExchange


text:
Q: Spy on a field assignment using Jasmine How could I spy on a field assignment using Jasmine?
E.g. I have the object under test:
const testObj = {
    testObjField: null,
    testObjFunc: function() { this.testObjField = "foo"; }
}

Now I want to assert that the testObj.testObjFunc will assign the "foo" to the testObj.testObjField. How should I proceed?
Here is what I tried:
  //arrange
  const testObj = {
    testObjField: null,
    testObjFunc: function () {
      this.testObjField = 'foo';
    }
  };

  const testObjTestObjFieldSpy = spyOnProperty(testObj, 'testObjField', 'set');

  //act
  testObj.testObjFunc();

  //assert
  expect(testObjTestObjFieldSpy).toHaveBeenCalledWith('foo');

But I am getting the error:

Error:  : Property testObjField does not have access type set

A: You can't spy on fields, only on methods.
I would do this:
//arrange
  let testObj = {
    testObjField: null,
    testObjFunc: function () {
      this.testObjField = 'foo';
    }
  };

  // !! Get a copy of the original
  const originalTestObj = { ...testObj };

  //act
  testObj.testObjFunc();

  //assert
  expect(testObj.testObjField).toBe('foo');

  // !! Reset testObj to what it was if that is required
  testObj = { ...originalTestObj };


text:
Q: Where is HP Procurve route type "ICMP" coming from? I've got the following test network:
Architecture:
edge_a: 192.168.e.1    [edge vlan]  (edge switch, no acl) [admin vlan] 192.168.m.1/24

core:   192.168.m.2/24 [admin vlan] (core router, yes acl) [admin vlan]

edge_b: 192.168.m.3/24 [admin vlan] (edge switch, no acl) [edge2 vlan] 192.168.e2.1

Topology:
edge_a <--[admin vlan ]--> core <--[admin vlan]--> edge_b

The edge switches do not support ACL's, only a small subset of IP Routing functionality (HP Procurve 2600, or 2800).
The Core supports ACL's (Procurve 5308xl).
Old architecture: All VLAN's ran back to the core router which was the "default gateway" for each.
I'm trying to move the "default gateway" for each vlan to the relevant edge switches.
However, the edge switches will happily route between directly connected vlans such as the Admin vlan. Nodes have no business on that network.
To block access into the admin vlan I'm applying an ACL to the "admin vlan OUT" interface of the core. The theory is that responses to a non-admin source will have no route back and so will always route through the core; therefore, filtering the TCP response.
This does not work, however, a ICMP ping succeeds and results in the following routing table on an edge switch:
remote edge switch# sh ip route

                                                                IP Route Entries

  Destination        Gateway         VLAN Type      Sub-Type   Metric     Dist.
  ------------------ --------------- ---- --------- ---------- ---------- -----
  0.0.0.0/0          192.168.m.2     101  static               0          250
  192.168.m.0/24     Admin_Vlan      101  connected            0          0
  192.168.e.226/32   192.168.m.1     101  icmp                 0          255

I suspected maybe this was to do with IRDP, however this protocol is disabled on all three switches in this example.
Where is this "ICMP" route coming from?
This architecture is the best solution I know and this ICMP thing is really wrenching my works.


text:
Q: Error during installing apk to virtual device on Android Studio Im getting this error during apk installation on android studio. It appears to be an error with the manifest file. Before getting this error I got another error due to a declared xml file in my manifest which I had deleted prior. After deleting the field as suggested by android studio, my project was built however during installation I got this error. Below is the log during the apk installation.

5:23 PM   Executing tasks: [:app:assembleDebug] in project
  D:\Documents\projects_and_practice\HowNormalAmI
5:23 PM   Gradle build finished in 12 s 73 ms
5:23 PM   Failed to commit install session 1049913730 with command cmd
  package install-commit 1049913730. Error:
  INSTALL_PARSE_FAILED_MANIFEST_MALFORMED: Failed parse during
  installPackageLI: /data/app/vmdl1049913730.tmp/base.apk (at Binary XML
  file line #28):  requires an android:value or
  android:resource attribute
5:23 PM   Session 'app': Installation did not succeed.
                The application could not be installed: INSTALL_PARSE_FAILED_MANIFEST_MALFORMED
                Retry

Here is my manifest file. All I have is one activity, two layouts and some views, I also have google firebase setup.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.hownormalami">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <meta-data
            android:name="com.google.android.actions"
            />

        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Before I had an xml decleration in my meta-data tag. The xml file was deleted however the decleration was still present in my meta-data section. Not sure if that was the cause and if it is how can I fix it?
Edit: It was the culprit, as far as I understand every "name" tag in meta data requires an accompanying "value" tag. I have since deleted the meta data field altogether, however my app simply crashes upon launching now.
Edit: App will run on no emulator, android AVD will not even boot up anymore, bluestacks wont work either. Not sure what's the issue.

A: I've managed to figure it out. My initial problem was due to my meta data tag. Android studio would not install my app because meta data contained a key but no value, i.e meta data runs on key value pairs and I didn't provide a value line. Deleting the key and leaving the meta data tag empty also resolved in an error. I deleted the entire meta data tag as it was not needed at this moment for my application. All errors after that, were due to errors in my java code. Fixing those errors got my app running again.


text:
Q: Java Jersey JSON service doesn't return quoted string? Here is a simple Web Service written using Jersey
@GET
@Produces(MediaType.APPLICATION_JSON)
public Object interpretationJson() {
    String o = "a simple string";
    return o;
}

The response for this is:
HTTP/1.1 200
Content-Type: application/json
Content-Length: 15
Date: Mon, 02 Oct 2017 23:18:14 GMT

a simple string

Shouldn't the string in the response body be quoted? I don't believe this is valid JSON. Shouldn't the response be:
HTTP/1.1 200
Content-Type: application/json
Content-Length: 15
Date: Mon, 02 Oct 2017 23:18:14 GMT

"a simple string"

This caused me a bit of confusion. I originally thought the problem was on the client side, but now I think the problem is the string returned from Jersey is not valid JSON - C# Parsing json that may have simple types

A: Here is a quote attributed to Jackson's developer (Tatu Saloranta / cowtowncoder) about why a simple string is treated this way.

This is not the reason String is declared untouchable. Rather, choice is
  between:
Write input String as JSON String, i.e. surround it with double-quotes
  and escape necessary characters, or
Write String exactly as-is, assuming user wanted to produce exactly that
  output (presumable hand-encoded JSON).
Since there is no metadata to tell what is user's intention, Jackson is
  being conservative and using latter choice.
  This is also prudent considering that JSON Specification only considers
  JSON Objects and JSON Arrays as valid JSON content -- so strictly speaking,
  returning a JSON String would produce invalid JSON anyway.

Referenced issue...
"Untouchable" is Jackson's term for a type that will be returned exactly as is.
You can easily return a string with quotes if you want to and there are several ways to do it. But that was not your question, I think.

A: public class TestGetterSetter{

private String name ;

public void setName(String name){
    this.name = name ;
}

public String getName(String name){
    return this.name ;
}}

Using this POJO class Set the value and return this POJO Class Object


text:
Q: Assigning workbook and worksheet properly VBA I have searched for this issue already, but all the examples are way too complicated.
I just cannot use "Set workbook" and "Set worksheets" object. I will get error 1004: Object-defined error.
I would like to read path from the destination file sheet "Path": C:\Users\Holger\Documents\VBA\WB_data.xlsx
Please someone help.
Sub Get_numbers()

'I have got 2 sheets
Dim WB_dest As Workbook
Dim WB_data As Workbook

'I need 3 worksheets
Dim path_sheet As Worksheet
Dim dest_sheet As Worksheet
Dim data_sheet As Worksheet

'Data worksheet's path
Dim path As String

'Counter
Dim i As Byte

'I run this sub from destination file sheet "PATH" which is already open
Set WB_dest = ThisWorkbook
Set path_sheet = WB_dest.Worksheets("Path")
Set dest_sheet = WB_dest.Worksheets("TO")

'I set worksheet from the Excel taht I do not need to open, just reading
Set WB_data = Workbooks.Open(path)
Set data_sheet = WB_data.Worksheets("FROM")

'Data sheet contains three numbers in the first column
'and destination sheet also contains only three numbers in the first coulm
'I would like to add data_sheet numbers after dest_sheet numbers
For i = 4 To 6
    dest_sheet.Cells(i, 1) = data_sheet(i, 1)
Next i

A: Try this...
Sub Get_numbers()

'I have got 2 sheets
Dim WB_dest As Workbook
Dim WB_data As Workbook

'I need 3 worksheets
Dim path_sheet As Worksheet
Dim dest_sheet As Worksheet
Dim data_sheet As Worksheet

'Data worksheet's path
Dim path As String

'Counter
Dim i As Byte

path = "C:\Users\Holger\Documents\VBA\WB_data.xlsx"

'I run this sub from destination file sheet "PATH" which is already open
Set WB_dest = ThisWorkbook
Set path_sheet = WB_dest.Worksheets("Path")
Set dest_sheet = WB_dest.Worksheets("TO")

'I set worksheet from the Excel taht I do not need to open, just reading
Set WB_data = Workbooks.Open(path)
Set data_sheet = WB_data.Worksheets("FROM")

'Data sheet contains three numbers in the first column
'and destination sheet also contains only three numbers in the first coulm
'I would like to add data_sheet numbers after dest_sheet numbers

data_sheet.Range("A4:A6").Copy
dest_sheet.Range("A4").PasteSpecial xlPasteValues
'For i = 4 To 6
'    dest_sheet.Cells(i, 1) = data_sheet(i, 1)
'Next i

End Sub


text:
Q: Elixir try rescue I'm not sure how best to do this:
I've got a function that looks up an IP and returns the country it's from.
country = Geolix.lookup(remote_ip).country.registered_country.name

Sometimes it fails, and in that case, none of the array keys are defined.
In other languages, I might do something like:
try do
  country = Geolix.lookup(remote_ip).country.registered_country.name
rescue
  country = nil
end

I'm really struggling to get the syntax right. This also doesn't feel very 'clean'; is there a better way?

A: You can also use case ... do with pattern matching, if the result of the case has all the keys you need it matches the first one, where you extract the name, if not it means whatever you got from Geolix.lookup/1 doesn't conform to the pattern you want and you return nil
country =
       case Geolix.lookup(remote_ip) do
          %{country: %{registered_country: %{name: name}}} -> name
          _ -> nil
       end

A: You don't do this with try macro. It is not designed to control the flow.
I'd recommend using Kernel.SpecialForms.with/1:
country =
  with %{country: country} <- Geolix.lookup(remote_ip),
       %{registered_country: rc} <- country,
       %{name: name} <- rc, do: name

Kernel.get_in/2 might also work:
get_in Geolix.lookup(remote_ip), ~w[country registered_country name]a

FWIW, here is the correct Kernel.SpecialForms.try/1 syntax:
country =
  try do
    Geolix.lookup(remote_ip).country.registered_country.name
  rescue
    _ -> nil
  end

The answer provided by @m3characters is also very good.


text:
Q: Connecting AC wires to a PCB I am working on a project where I am using a microcontroller to control a 5V DC relay to control a mains device (an airconditioner).
In this circuit, I would need to connect the AC wires to my PCB at sereval points:

*

*as an input to a 12V transformer -> 5V voltage regulator

*to the 5V DC relay

My questions are:

*

*How to ensure the safe connection of the mains wire. After soldering them to the PC is there some kind of glue or something i can cover the solder with to ensure safety ?

*Do i connect all the grounds (AC ground , micro controller ground) together or should they remain separate?

*while designing PCB what do i need to keep in mind for the track widths for tracks handing AC current/voltage ?

Sorry if these questions sound newbish .. first time handling AC/DC together.

A: No, just putting some hot glue over dangerous points on a PCB is not enough.  You will never pass safety certification that way.  You need some kind of enclosure such that probing fingers can't get at the hot spots.  Saftey standards will usually require a fuse in series with the AC hot line as soon as possible after it enters your box, then you can connect that to a PCB.  The rest of the system must mechanically ensure that those nodes are ineccessible.
If this is a one-off for your lab bench, then hot glue, electrical tape, epoxy, etc is OK, but you have to keep in mind how these things can fail and treat everything accordingly.  When working with AC power line on a bench, it's a good idea to use a isolation transformer.  That adds one level of safety in that there won't be a conduction path from any of the high voltage to ground.  However, keep in mind this changes if you connect a grounded scope, computer communication cable, etc, to any part of the circuit.
Something to consider:  Don't use a 5V relay, use one instead intended to run directly off the AC line.  This may lower the current requirements of the 5V supply so that you don't need a transformer at all anymore.  For a few mA you can use a capactive charge pump, which might be enough to run your micro.  In that case the whole circuit will be floating over the AC line voltage range, so you have to consider all of it dangerous.  But, if this will ultimately be a sealed unit that only activates a relay, then that should be fine.  After all, every AC line power circuit will have some parts at line voltage.  The issue is how to deal with that properly.
Another method is to get a off the shelf "power brick" to embed into your product.  These are switching power supplies that make isolated DC, in your case 5V, that you can then safely run the rest of your circuit on.  In that case it would be easier to use a 5V relay as you originally said.
If your power requirements are only a few Watts or less, then you can push the power supply external.  In that case you use a wall wart type power supply and only the isolated DC ever enters your unit.  These are small sealed units with only the AC prongs exposed and come pre-certified to various safety specs.  Customers understandably find them annoying, but the economics usually dictate something like that for up to around 5-10 Watts.

A: Borrowing Olin's writ:

*

*"If this is a one-off for your lab bench, then hot glue, electrical tape, epoxy, etc is OK," ...

... IF you do not mind dying every now and then.
Buy connectors that are DESIGNED & SOLD as mains connectors.
 Talk to a local supplier of such components.
If YOU can access metal *(wire or whatever) at mains potential then somebody else can as well.
Hot melt glue fails to bind  in from months to a few years.
Answers from here about track widths,clearances,copper thicknesses and more are a useful guide BUT you MUST have a complete and traceable information source on such things if you are going to live long and prosper. Find websites on such and ask advice from knowledgeable people on how useful they are. Usually a web page creator has spent tens to 100s of hours on a page or set of pages - far more than will usually be possible for a single question here .


text:
Q: Prove this property of the Hessian I have been reading about the hessian for a scholar work about optimization and I find this property:
Let be $H_{P_0}$ the determinant of the hessian matrix for the Lagrangian function $\mathscr{L}(x,y,\lambda)$ evaluated in the critical point $P_0$, then:

*

*if $H_{P_0}< 0$, $P_0$ in a minimum

*if $H_{P_0}>0 , P_0$ is a maximum

But I didn´t found the prove and I was wondering what happens when the determinat is cero?

A: In the 1D case, the second derivative test is inconclusive when the second derivative vanishes at the critical point. You can see this by looking at $f(x)=x^3,g(x)=x^4,x_0=0$; the second derivative test gives the same information but the behavior is different. The analogous thing happens in higher dimensions, including in constrained problems.
tl;dr: You can't get any information in this case.


text:
Q: Wordpress + PHP+ apache +mysql, mysql crash every 1/ month On a server i have multiple rails apache + postgres apps and a mysql + php. The only PHP app is a wordpress. Except for wordpress everything runs fine.
Every 40-50 days, mysql stop to work.
Here is the messages that are logged before a crash :
160408 19:20:31 [Warning] Using unique option prefix myisam-recover instead of myisam-recover-options is deprecated and will be removed in a future release. Please use the full name instead.
160408 19:20:31 [Note] Plugin 'FEDERATED' is disabled.
160408 19:20:31 InnoDB: The InnoDB memory heap is disabled
160408 19:20:31 InnoDB: Mutexes and rw_locks use GCC atomic builtins
160408 19:20:31 InnoDB: Compressed tables use zlib 1.2.3.4
160408 19:20:31 InnoDB: Initializing buffer pool, size = 128.0M
InnoDB: mmap(137363456 bytes) failed; errno 12
160408 19:20:31 InnoDB: Completed initialization of buffer pool
160408 19:20:31 InnoDB: Fatal error: cannot allocate memory for the buffer pool
160408 19:20:31 [ERROR] Plugin 'InnoDB' init function returned error.
160408 19:20:31 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
160408 19:20:31 [ERROR] Unknown/unsupported storage engine: InnoDB
160408 19:20:31 [ERROR] Aborting

160408 19:20:31 [Note] /usr/sbin/mysqld: Shutdown complete

The error logs are empty except on the day of the crash, and this message is repeated 4 times starting at 19:20:25.
To restore wordpress, I just restart mysql and it works. I already increased the ram of the server in the past, it only increased the time before a crash. The number of visits on this wordpress are around 1000 a month.
How can i prevent mysql from crashing?
Maybe it would be easier just to restart mysql every week?
EDIT : the VM has 1200 mo of ram, I may have some config problem related to memory, what should i do?

A: seems to be a common error, perhaps InnoDB is configured to use more memory than you physically have, have you looked here:
https://stackoverflow.com/questions/12114746/mysqld-service-stops-once-a-day-on-ec2-server/12683951#12683951


text:
Q: Changing domain of PDE (should be easy) Suppose I have a PDE
$$u_t(x,t) + f(x,t)\cdot \nabla u(x,t) = 0 \quad \text{on $\gamma(t)$}$$
where $\gamma(t)$ is a curve for each fixed t in $\mathbb{R}^2$ and $f$ is given.
We have that $\gamma(t)$ is parametrised by the function $X(s,t)$ for each $t$. So $X(s,t) = x \in \gamma(t)$ for some $s$. So $x \in \mathbb{R}^2$, $s \in S^1$ or some interval in the real line.
I want to write the PDE as a function of $(s,t)$ instead of $(x,t).$ So basically I want to solve a PDE for the unknown function $v(p,t) = u(X(p,t), t)$. How can I convert my PDE to this domain? I can't find any expressions for $u_t$ and $\nabla u$ in terms of $v$..

A: Start with
$$ v(s,t) = u(X(s,t),t) $$
By the chain rule you get
$$ \begin{cases} v_t(s,t) &= X_t(s,t) \cdot \nabla u(X(s,t),t) + u_t(X(s,t),t) \\
v_s(s,t) &= X_s(s,t) \cdot \nabla u(X(s,t),t) \end{cases}$$
To solve for $u_t$ and $\nabla u$, you need to solve for three scalar functions. But you only have two equations here. Clearly the system is underdetermined, so in general one cannot solve for $u_t$ and $\nabla u$ interms of $v$.
Plugging in the above into the equation you get
$$ v_t - X_t\cdot \nabla (u\circ X) + f \cdot \nabla (u\circ X) = 0 $$
So if $f - X_t \propto X_s$, that is, if $f - X_t = \alpha(t,s) X_s$, we can plug in
$$ v_t + \alpha X_s \nabla (u\circ X) = 0 \implies v_t + \alpha v_s = 0$$

The condition that $f - X_t \propto X_s$ above is a integrability condition. Given $\gamma(t)$ it specifies a two-dimensional surface is $\mathbb{R}^3 = \{t\}\times \mathbb{R}^2$. Your equation can be regarded as a transport equation in $\mathbb{R}^3$, that a certain vector field $V = (1,f)$ acts on $u$ to give zero. Generically one may expect the vector field $V$ to be transverse to the surface $\gamma(t)$: in that case your equation is underdetermined: values on the surface $\gamma(t)$ depends on values of $u$ off the surface, and in that case it is impossible to write the equation in terms of $v$, which is essentially just the value of $u$ on the surface $\gamma(t)$.
The condition $f - X_t \propto X_s$ ensures that the vector $(1,f)$ is in fact tangential to the surface $\gamma(t)$. This way your vector field $(1,f)$ restricts to a tangent vector field of $\gamma(t)$ and it makes sense to study the equation restricted to the surface.


text:
Q: No output hebrew XeLaTeX Here is MWE:
I have MacOS with Monterey and TeXLive 2020
\documentclass[a4paper, 10pt ]{article}
\usepackage[no-math]{fontspec}
\setmainfont{Lucida Grande}
\newfontfamily{\He}{Corsiva Hebrew}
\usepackage{bidi}

\begin{document}
\RL{יהוה}
\end{document}

A: here's a MWE with XeLatex/Polyglossia
%!TEX TS-program = xelatex
%!TEX encoding = UTF-8 Unicode
\documentclass{article}
\usepackage{fontspec}
\setmainfont{Times New Roman}
\setsansfont{Arial}
\usepackage{polyglossia}
\setdefaultlanguage{hebrew}
\setotherlanguage{english}
\begin{document}

שלום, זהו ניסיון

קטע עברי משולב עם \RL{english} באמצע משפט

\begin{english}
A L-to-R paragraph with some \RL{עיברית} in the middle
\end{english}

\end{document}

which gives the pdf
  (if it doesn't show, see link)


text:
Q: AS3 load new URLRequest through a string I want to load a new URL (which is in a array), everytime I press the button. I have the following code to do so:
    public function selectRadio(radio:Radio):void {
        var soundR:Sound = new Sound();

        if(!playing) {
            soundR.load(new URLRequest(radio.getURL()));
            soundChannel = soundR.play();
            playing = true;
        }
        else{
            soundChannel.stop();
            playing = false;
        }

        trace("You are now listening to " + radio.getTitle());
    }

But it gives me this error:
"implicit coercion of a value of type flash.net:URLRequest to an unrelated type string"
It works if I just leave it like this:
soundR.load(radio.getURL());

But if i do so, I can only press play and stop 4 times. After the fourth there is no sound, like it can't load the URL.
Is it possible to fix this?

A: Radio.getURL() should return a string instead of a URLRequest?
Ah nevermind I see you tried avoiding that by removing URLRequest, but you are having problems with only 4 connections.

In all but the simplest cases, your application should pay attention to the sound's loading progress and watch for errors during loading. For example, if the click sound is fairly large, it might not be completely loaded by the time the user clicks the button that triggers the sound. Trying to play an unloaded sound could cause a run-time error. It's safer to wait for the sound to load completely before letting users take actions that might start sounds playing.

http://help.adobe.com/en_US/as3/dev/WS5b3ccc516d4fbf351e63e3d118a9b90204-7d25.html
If you can't wait for the sound to completely load you may need NetStream:
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/NetStream.html


text:
Q: What is the exact impact of following content of `.gitignore` file in one of subdirectories? What is the exact impact of the following content of .gitignore file in one of the subdirectories:
*

!.gitignore

A: The * means "everything". ! is the negation operator. So basically, this means ignore everything except the .gitignore file. Or another words, ignore everything in this directory except the fact that you're ignoring everything.


text:
Q: get selected value from dropdown in a table i am try to fetch the values from dropdown in a table i get same value on every click.....

        @{
            var tempId=1;
            foreach (var item in lst)
            {
                var username = _lst.Where(x => x.UserName == @item.UserName);
                if (username.Count() > 0)
                {

                        <input type="hidden" id="@tempId" name="tempId_@tempId">
                        @username.Select(x => x.UserName).FirstOrDefault()
                         @*@Html.DropDownList("UserRoleTypeId", "Select")*@

                        @Html.DropdownListCustom("UserRoleTypeId" + @tempId, "", (IEnumerable<SelectListItem>)ViewBag.UserRoleTypeId)

                            @Html.Hidden("Id", i = username.Select(x => x.Id).FirstOrDefault())

                        <input type="button" data-id="@item.UserName" value="set" class="btn-update" />

                }
                else
                {

                        @item.UserName
                         @*@Html.DropDownList("UserRoleTypeId", "Select")*@
                            @*@Html.DropdownListCustom("UserRoleTypeId_" + @tempId, "", (IEnumerable<SelectListItem>)ViewBag.UserRoleTypeId, new { @id = "UserRoleTypeId" })*@
                       @Html.DropdownListCustom("UserRoleTypeId" + @tempId, "", (IEnumerable<SelectListItem>)ViewBag.UserRoleTypeId)

                            @Html.Hidden("Id", i)

                        <input type="button" data-id="@item.UserName" value="set" class="btn-update" />

                }
                tempId = tempId + 1;
            }
        }

jquery code is:
 }

on Top i'm create a table where i have dropdown and text.What i need is on button click get particular row value .I'm try but i get only first td value(username)

A: Try this to access dropdownlist
 UserRoleTypeId = $(this).parent().siblings().find("select").val();


text:
Q: Fast solution to get NaN and ignore None in numpy array I have an array like this:
array = np.random.randint(1, 100, 10000).astype(object)
array[[1, 2, 6, 83, 102, 545]] = np.nan
array[[3, 8, 70]] = None

Now, I want to find the indices of the NaN items and ignore the None ones. In this example, I want to get the [1, 2, 6, 83, 102, 545] indices. I can get the NaN indices with np.equal and np.isnan:
np.isnan(array.astype(float)) & (~np.equal(array, None))

I checked the performance of this solution with %timeit and got the following result:
243 µs ± 1.32 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Is there faster solution?

A: array != array

The classic NaN test. Writing NaN tests like this is one of the reasons that motivated the NaN != NaN design decision, since the IEEE 754 designers couldn't assume programmers would have access to an isnan routine.
This significantly outperforms the code in the question when I try it:
In [1]: import numpy as np

In [2]: array = np.random.randint(1, 100, 10000).astype(object)
   ...: array[[1, 2, 6, 83, 102, 545]] = np.nan
   ...: array[[3, 8, 70]] = None

In [3]: %timeit array != array
139 µs ± 46.6 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)

In [4]: %timeit np.isnan(array.astype(float)) & (~np.equal(array, None))
755 µs ± 123 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)

And of course, it does give the same output:
In [5]: result1 = array != array

In [6]: result2 = np.isnan(array.astype(float)) & (~np.equal(array, None))

In [7]: np.array_equal(result1, result2)
Out[7]: True


text:
Q: Find maximum number of dots that can be distributed on a rectangle when dimensions, distance are given When a rectangle's width and length are W and L.
Find maximum number of dots that can be distributed on the rectangle.
Each dots must be apart D distance from each other.
The dots can be put on the sides of the rectangle.
For example, a rectangle's width and length are 8.
The distance that dots need to be apart from each other is $\sqrt8$.
How many dots can be put in the rectangle?
This question made me want to know how it can be generalized by changing the rectangle's width, length and the distance between dots to variables.
I got this problem from this video: https://www.youtube.com/watch?v=2-mxYrCNX60.
I tried to solve it by myself for a few hours but I couldn't think of a good way. I would be glad if you let me know how to solve it or related stuff to help solve this problem.


text:
Q: How to dynamically find the position of string in sql server? Example:
string= What is <#1#/>?
How to find position of number inside the tag dynamically and how to trim this tag <# #/>?

A: To find a position of a substring in a string you can use CHARINDEX()
If you want to extract the number from your string you can do
SELECT SUBSTRING(s,
                 CHARINDEX('<#', s) + 2,
                 CHARINDEX('#/>', s) - CHARINDEX('<#', s) - 2) number
  FROM
(
  SELECT 'What is <#1#/>' s
) q

Here is SQLFiddle demo


text:
Q: Change the date to fiscal year I want to write a function in Excel to change the date. The logic is like this: if the month is (Jan, Feb or March) the result show me one year past (-1 year) and if the month is (April to -December) the result show the current year (which year the date shows).

example: if date is 02,Jan,2012 the result show me 2011 else show me 2012.

A: =IF(MONTH(G3) >=4, YEAR(G3), YEAR(G3) - 1) where G3 is the date to test, is one way.

A: Please try:
=IF(OR(MONTH(A1)=1,MONTH(A1)=2,MONTH(A1)=3),2011,2012)

A: With 02-Jan-2012 in A1 try,
=YEAR(A1)-(MONTH(A1)<4)

For a full date use one of these,
=DATE(YEAR(A1)-(MONTH(A1)<4), MONTH(A1), DAY(A1))
=EDATE(A1, -(MONTH(A1)<4)*12)

A: Already plenty of answers, but thought I'd throw another one up:
=YEAR(DATE(YEAR(A1),MONTH(A1)-3,DAY(A1)))

A: To extract fiscal year use:
=YEAR(A1) + IF(MONTH(A1)>=4,1,0)

I think in your case you would need:
=YEAR(A1) - IF(MONTH(A1)>=4,0,1)

If the months is before 4th month then subtract 1 year, else keep the same year. I wouldn't convert it to a full date DD/MM/YYYY with a 1 year subtracted, to avoid confusion keep it as year only YYYY.


text:
Q: Problem when masking UIImage I took a sample code from the following URL: how to mask an image in order to mask an image.
The code is working perfectly on the iPhone simulator but works incorrectly on iPhone 4 simulator (that's when high-res images are loaded...)
Here is my code and the mask function:
- (void)someMethod {

    UIImage* image = [UIImage imageNamed:@"image.png"];  // image@2x.png is loaded for high-res device

    UIImage* mask = [UIImage imageNamed:@"mask.png"];  // mask@2x.png is loaded for high-res device

    UIImage* maskedImage = [self maskImage:image withMask:mask];

    // ... Some code here displaying maskedImage

}

- (UIImage *)maskImage:(UIImage *)image withMask:(UIImage *)maskImage {

    UIImage* maskedImage = nil;

    CGImageRef maskRef = maskImage.CGImage;

    CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
                                    CGImageGetHeight(maskRef),
                                    CGImageGetBitsPerComponent(maskRef),
                                    CGImageGetBitsPerPixel(maskRef),
                                    CGImageGetBytesPerRow(maskRef),
                                    CGImageGetDataProvider(maskRef), NULL, false);

    CGImageRef masked = CGImageCreateWithMask([image CGImage], mask);
    maskedImage = [UIImage imageWithCGImage:masked];

    return maskedImage;
}

On the iPhone 4 simulator the image@2x.png and mask@2x.png are loaded and then the resulted maskedImage is cropped.
Any idea what am I doing wrong?

A: Use this method instead of above
- (UIImage*) maskImage:(UIImage *)image withMask:(UIImage *)maskImage {

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

    //UIImage *maskImage = [UIImage imageNamed:@"mask.png"];
    CGImageRef maskImageRef = [maskImage CGImage];

    // create a bitmap graphics context the size of the image
    CGContextRef mainViewContentContext = CGBitmapContextCreate (NULL, maskImage.size.width, maskImage.size.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);

    if (mainViewContentContext==NULL)
        return NULL;

    CGFloat ratio = 0;

    ratio = maskImage.size.width/ image.size.width;

    if(ratio * image.size.height < maskImage.size.height) {
        ratio = maskImage.size.height/ image.size.height;
    }

    CGRect rect1  = {{0, 0}, {maskImage.size.width, maskImage.size.height}};
    CGRect rect2  = {{-((image.size.width*ratio)-maskImage.size.width)/2 , -((image.size.height*ratio)-maskImage.size.height)/2}, {image.size.width*ratio, image.size.height*ratio}};

    CGContextClipToMask(mainViewContentContext, rect1, maskImageRef);
    CGContextDrawImage(mainViewContentContext, rect2, image.CGImage);

    // Create CGImageRef of the main view bitmap content, and then
    // release that bitmap context
    CGImageRef newImage = CGBitmapContextCreateImage(mainViewContentContext);
    CGContextRelease(mainViewContentContext);

    UIImage *theImage = [UIImage imageWithCGImage:newImage];

    CGImageRelease(newImage);

    // return the image
    return theImage;
}

A: My guess would be to not trust UIImage to deliver the highrez format to CGImageRefs etc.  I think you will need to do it manually.


text:
Q: How do I import 'umap' package in python? After install 'umap' package, I can't import
I tried reinstall pre version (1.3.10, 1.4.0rc1).
But, It's not working
How can I do?
!pip3 install umap-learn
!pip3 install umap-learn[plot]
import umap

This is the error I get:

No module named 'umap'

A: you probably confused umap and umap-learn libs,
if that's the case, the code below'll solve your problem
https://umap-learn.readthedocs.io/en/latest/basic_usage.html
pip uninstall umap

pip install umap-learn

import umap.umap_ as umap
reducer = umap.UMAP()


text:
Q: Automapper inner model attribute returns null so I have an entity model using Entity Framework Core which is used in ASP.NET Core Web API.
I have created two entity models:
public class FishCategory
{
    [Key]
    [Required]
    public int ID { get; set; }
    [Required]
    [MaxLength(50)]
    public string Category { get; set; }
    public IEnumerable<Fish> Fish { get; set; }
}

public class Fish
{
    [Key]
    public int ID { get; set; }
    [Required]
    [MaxLength(50)]
    public string Name { get; set; }
    [MaxLength(100)]
    public string Description { get; set; }
    [Required]
    public float WeightKg { get; set; }
    [Required]
    public int Stock { get; set; }
    [Required]
    public float Price { get; set; }
    [Required]
    public int CategoryID { get; set; }
    public FishCategory Category { get; set; }
    public int UserID { get; set; }
    public User Seller { get; set; }
    public Item Item { get; set; }
}

These 2 entities have one to many relationship
Then here is the 2 DTO models for both of the entities
public class FishReadDTO
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public float WeightKg { get; set; }
    public int Stock { get; set; }
    public float Price { get; set; }
    public FishCategoryReadDTO Category { get; set; }
    public UserReadDTO Seller { get; set; }
}

public class FishCategoryReadDTO
{
    public int ID { get; set; }
    public string Category { get; set; }
}

Here the repository for the Fish entity model
public Fish GetFishById(int id)
{
    return _databaseContext.Fishes
        .Where(fish => fish.ID.Equals(id))
        .Select(fish => new Fish()
        {
            ID = fish.ID,
            Category = fish.Category,
            CategoryID = fish.CategoryID,
            Description = fish.Description,
            Item = fish.Item,
            Name = fish.Name,
            Price = fish.Price,
            Seller = fish.Seller,
            Stock = fish.Stock,
            UserID = fish.UserID,
            WeightKg = fish.WeightKg
        }).FirstOrDefault();
}

Here's the Profile class for the DTO
public class EFishingProfile : Profile
{
    public EFishingProfile()
    {
        CreateMap<User, UserReadDTO>();
        CreateMap<FishCategory, FishCategoryReadDTO>();
        CreateMap<Fish, FishReadDTO>();

        CreateMap<FishCreateDTO, Fish>();
    }
}

Here's the controller that executes this method to get the data
[HttpGet("{id}", Name = "GetFishById")]
public ActionResult<FishReadDTO> GetFishById(int id)
{
    var fish = _repository.GetFishById(id);
    if(fish == null)
    {
        return NotFound();
    }

    return Ok(_mapper.Map<FishReadDTO>(fish));
}

[HttpPost]
public ActionResult<Fish> CreateFish(FishCreateDTO fishCreateDTO)
{
    var fishModel = _mapper.Map<Fish>(fishCreateDTO);
    _repository.CreateFish(fishModel);

    var fishRead = _mapper.Map<FishReadDTO>(fishModel);

    return CreatedAtRoute(nameof(GetFishById), new {Id = fishRead.ID}, fishRead);
}

The result of posting a "Fish" data returns me a "Fish" entity model mapped to the "FishReadDTO" model but I would like to map it to the FishReadDTO but it return me a null value for property of "category" and "fish" in the Fish DTO model itself. Here is an example of it
{
    "id": 12,
    "name": "Test 3",
    "description": "Test 3",
    "weightKg": 76.25,
    "stock": 10,
    "price": 50.0,
    "category": null,
    "seller": null
}

Here's what I want which uses the FishDTO when getting a single "Fish" entity model mapped to the DTO which is working via the API method called "GetFishById(int id)". You can refer the method in my controller code posted.
{
    "id": 9,
    "name": "Northern Pike",
    "description": "A predatorial fish found in the waters of canal and rivers",
    "weightKg": 76.25,
    "stock": 10,
    "price": 50.0,
    "category": {
        "id": 1,
        "category": "Salt Water/Sea Fish"
    },
    "seller": {
        "id": 1,
        "username": "AdrianJ",
        "name": "Adrian Joseph",
        "email": "adrianjoseph@efishing.com"
    }
}

Is there any way to basically get the "category" and "seller" being mapped and not getting null?
**Note that while using the "GetByFishId(int id)" API method which invoked my "FishRepository", without using the ".Include(...)" method in the repository I still get the values for "category" and "seller", the issue is at the API method where I create/post a new Fish which is this method"
[HttpPost]
public ActionResult<Fish> CreateFish(FishCreateDTO fishCreateDTO)

" into my database and it returns me a 201 Created using "CreatedAtRoute" is when I received the response of a "FishReadDTO" with null values of "category" and "seller" only.**

A: You need to fetch relations from the database. When you load an entity from the DbContext, its relations are not loaded, so you get null.
In your repository, if you change
_databaseContext.Fishes
        .Where(fish => fish.ID.Equals(id))

to
_databaseContext.Fishes
        .Include(e => e.Category)
        .Include(e => e.Seller)
        .FirstOrDefault(fish => fish.ID.Equals(id))

then DbContext will load those relations and navigation properties Category and Seller will be populated. Then AutoMapper can map those objects to DTOs like you expect.
For reference, see docs


text:
Q: .NET 6 - Set SelectListItem to Selected? I have a DropDownList which I populate like below:
Controller
IEnumerable<Category> categories = _db.Category.ToList();

var selectList = _db.Category.Select(i => new SelectListItem()
{
    Text = i.Name,
    Value = i.Id.ToString()
});

ViewBag.categoriesSelectList = selectList;

And use in view like so:
<select asp-for="Category" name="categoryID" asp-items="@ViewBag.categoriesSelectList" class="form-control">
        <option>Vælg Kategori:</option>
</select>

However, I can't seem to figure out how I can set the already selected value, so the dropdown "starts" on that value. I tried enumerating over the selectList and changing the Selected attribute of the SelectListItem, but it doesn't work since it won't save the changes I make.
Hope my question makes sense :) thanks all.

A: Option 1:
Modify your code to include Selected property when creating list of SelectListItem items:
var selectList = _db.Category.Select(i => new SelectListItem()
        {
            Text = i.Name,
            Value = i.Id.ToString(),
            Selected = /* Some condition that is true when the current item should be selected  */
        });

Option 2:
Define a view model with structure that might be referenced in the <select> tag:
public class SelectViewModel
{
    public string Category { get; set; }
    public List<SelectListItem> Categories { get; set; }
}

The action method:
public IActionResult Categories()
{
    var model = new SelectViewModel() ;
    model.Categories = _db.Category.Select(i => new SelectListItem()
        {
            Text = i.Name,
            Value = i.Id.ToString()
        });

    model.Category = ... your_code_to_set_default_selection;

    return View(model);
}

The view:
@model SelectViewModel

<select asp-for="Category" asp-items="@Model.Categories"></select>

Can find some mode information in the documentation: The Select Tag Helper


text:
Q: What's the cost of scan including column that has been added recently? Assuming I have an old table with a lot of data. Two columns are there - user_id existing from very beginning and data added very recently, say, a week ago. My goal is to join this table on user_id but retrieve only the newly created column data. Could it be the case that because data column didn't exist so far, there is no point of scanning whole user_id range and, therefore, query would be cheaper? How is the price calculated for such operation?

A: According to the documentation there are 2 pricing models for queries:

*

*On-demand pricing

*Flat-rate pricing
Seeing that you use On-demand pricing, you will only be billed by the number of bytes processed, you can check how data size is calculated here. In that sense the answer would be: yes, scanning user_id partially would be cheaper. But reading through the documentation you'll find this sentence:

When you run a query, you're charged according to the data processed in the columns you select, even if you set an explicit LIMIT on the results.

So probably the best solution would be creating another table with the data that has to be processed and run the query.


text:
Q: tag:ReactJS Context.Provider value is not updated i'am trying to useContext() but the Provider doesnt pass the value, even if I use a fake value like:
<TestContext.Provider value="2000">
and keep the default value where the Context is initialised:
export const TestContext = createContext(5000);
so there is the code:
PARENT COMPONENT
import React, { useState, useEffect, createContext } from "react";
import Axios from "axios";
import { makeStyles } from "@material-ui/core/styles";
import Button from "@material-ui/core/Button";
import Card from "@material-ui/core/Card";
import CardActions from "@material-ui/core/CardActions";
import CardContent from "@material-ui/core/CardContent";
import Container from "@material-ui/core/Container";
import Divider from "@material-ui/core/Divider";
import Grid from "@material-ui/core/Grid";
import ListItemText from "@material-ui/core/ListItemText";
import Paper from "@material-ui/core/Paper";
import Typography from "@material-ui/core/Typography";

// import style
const useStyles = makeStyles({
    root: {
        minWidth: 275,
    },
    title: {
        fontSize: 14,
    },
    pos: {
        marginBottom: 12,
    },
});

export const TestContext = createContext(5000);

function User() {
    const classes = useStyles();

    /* get all users */
    const [allUsers, setAllUsers] = useState([{}]);
    const getAllUsers = () => {
        const url = `http://localhost:5000/api/users`;
        Axios.get(url)
            .then((response) => response.data)
            .then((data) => setAllUsers(data));
    };

    useEffect(() => {
        return getAllUsers();
    }, []);

    /* get one user */
    const [user, setUser] = useState([{}]);
    const getOneUser = (userId) => {
        const url = `http://localhost:5000/api/users/${userId}`;
        Axios.get(url)
            .then((response) => response.data)
            .then((data) => setUser(data));
    };

    useEffect(() => {
        getOneUser();
    }, [allUsers]);

    /* init energy */
    const [energyConsuption, setEnergyConsuption] = useState({});
    const calcDailyEnergyConsumption = () => {
        // for a male
        const basalMetabolicRate =
            1.083 *
            Math.pow(weight, 0.48) *
            Math.pow(height, 0.5) *
            Math.pow(age, -0.13) *
            191;
        const dailyEnergyConsumption = basalMetabolicRate * activity;

        return setEnergyConsuption({
            mb_rate: basalMetabolicRate.toFixed(2),
            daily_energy: dailyEnergyConsumption.toFixed(2),
        });
    };

    useEffect(() => {
        calcDailyEnergyConsumption();
    }, [user]);

    /* init Proteins, Lipids, Glucids state */
    const [PLG, setPLG] = useState({});

    /* init info needed by user */
    const weight = user.weight;
    const height = user.height;
    const age = user.age;
    const activity = 1.4;

    /* calculate proteins / lipids / glucids ratio */
    const calcLipGlucProt = () => {
        // DEC means Daily Energy Consuption
        let DEC = energyConsuption.daily_energy;

        const proteins = user.weight * 1.8;
        DEC = DEC - proteins * 4;

        const lipids = user.weight * 1;
        DEC = DEC - lipids * 9;

        const glucids = DEC / 4;

        return setPLG({
            proteins: proteins.toFixed(2),
            lipids: lipids.toFixed(2),
            glucids: glucids.toFixed(2),
        });
    };

    useEffect(() => {
        calcLipGlucProt();
    }, [energyConsuption]);

    return (
        <Container>

{energyConsuption.daily_energy}

            <TestContext.Provider value="2000">
                <Grid container spacing={1}>
                    {allUsers.map((userDetail) => (
                        <Grid item xs={2}>
                            <Paper>
                                <Button
                                    onClick={() => getOneUser(userDetail.id)}
                                >
                                    {userDetail.id} {userDetail.firstname}
                                </Button>
                            </Paper>
                        </Grid>
                    ))}
                </Grid>
                <Card className={classes.root}>
                    <CardContent>
                        <Typography
                            variant="h5"
                            component="h2"
                            gutterBottom
                        >{`Bonjour ${user.firstname} ${user.lastname}`}</Typography>
                        <Divider />
                        <Typography
                            className={classes.pos}
                            color="textSecondary"
                        >
                            age : {user.age} ans
                        </Typography>
                        <Typography
                            className={classes.pos}
                            color="textSecondary"
                        >
                            taille : {user.height} m
                        </Typography>
                        <Typography
                            className={classes.pos}
                            color="textSecondary"
                        >
                            poid : {user.weight} kg
                        </Typography>
                        <Typography
                            className={classes.pos}
                            color="textSecondary"
                        >
                            activité : {user.id_activity} (sédentaire)
                        </Typography>
                        <Typography
                            className={classes.pos}
                            color="textSecondary"
                        >
                            objectif : {user.id_goal}(perdre du poid)
                        </Typography>
                        <Divider />
                        <Typography display="block" paragraph gutterBottom>
                            Votre métabolisme basal est de

                                {" "}
                                {energyConsuption.mb_rate} calories
                            {" "}
                            et votre dépense énergétique journalière est
                            de

                                {energyConsuption.daily_energy} calories

                        </Typography>
                        <Typography display="block">
                            Vous devez consommer idéalement
                            <ListItemText href="#simple-list">
                                - {PLG.proteins} grammes de protéines
                            </ListItemText>
                            <ListItemText href="#simple-list">
                                - {PLG.lipids} grammes de lipides
                            </ListItemText>
                            <ListItemText href="#simple-list">
                                - {PLG.glucids} grammes de glucides
                            </ListItemText>
                        </Typography>
                        <Divider />
                        <Typography
                            variant="caption"
                            display="block"
                            gutterBottom
                        >
                            Ces informations ne remplace en aucun cas l'avis
                            médical d'un expert.
                        </Typography>
                    </CardContent>
                    <CardActions>
                        <Button size="small">Mettre à jour mes infos</Button>
                    </CardActions>
                </Card>
            </TestContext.Provider>
        </Container>
    );
}

export default User;

CHILD COMPONENT
import React, { useState, useEffect, useContext } from "react";
import { TestContext } from "../Users/Users";
import Axios from "axios";
import Container from "@material-ui/core/Container";
import Grid from "@material-ui/core/Grid";
import Typography from "@material-ui/core/Typography";
import Card from "@material-ui/core/Card";
import CardActions from "@material-ui/core/CardActions";
import CardContent from "@material-ui/core/CardContent";
import Button from "@material-ui/core/Button";
import TextField from "@material-ui/core/TextField";
import Paper from "@material-ui/core/Paper";

function Recipes() {
    const value = useContext(TestContext);
    // console.log("Context", TestContext);

    const [allFoods, setAllFoods] = useState([{}]);
    const [food, setFood] = useState([{}]);
    const [foodQuantity, setFoodQuantity] = useState(0);

    const getAllFoods = () => {
        const url = "http://localhost:5000/api/foods";
        Axios.get(url)
            .then((response) => response.data)
            .then((data) => setAllFoods(data));
    };
    useEffect(() => {
        return getAllFoods();
    }, []);

    const getOneFood = (foodId) => {
        const url = `http://localhost:5000/api/foods/${foodId}`;
        Axios.get(url)
            .then((response) => response.data)
            .then((data) => setFood(data));
    };
    useEffect(() => {
        getOneFood();
    }, [allFoods]);

    const getFoodName = allFoods.map((foodDetail) => (
        <Button onClick={() => getOneFood(foodDetail.id)}>
            <Paper>{foodDetail.name}</Paper>
        </Button>
    ));

    const calcFoodQuantity = () => {
        const total = 100 * (calories / food.calories);
        setFoodQuantity(total.toFixed(2));
    };

    return (
        <Container>
            <Card>
                <Grid container spacing={1}>
                    {getFoodName}
                </Grid>
                <Typography variant="h2" gutterBottom>
                    Calculer une recette pour {value} calories
                </Typography>
                <CardContent>
                    <Typography>{food.name}</Typography>
                    <Typography>{food.calories} cals</Typography>
                </CardContent>
                <CardActions>
                    <Button
                        size="small"
                        color="secondary"
                        onClick={() => calcFoodQuantity()}
                    >
                        Calculer
                    </Button>
                    <Typography>
                        il vous faut {foodQuantity} grammes de {food.name} pour
                        atteindre votre dépense énergétique journalière
                    </Typography>
                </CardActions>
            </Card>
        </Container>
    );
}

export default Recipes;

By advance thanks for your help

A: The Provider from docs:
https://reactjs.org/docs/context.html#contextprovider

Accepts a value prop to be passed to consuming components that are descendants of this Provider

Your Provider is at top of User component, which means that all components inside the provider gets the context value. Your Recipes component is not part of that tree but the App component itself.
You might need to add the Provider to the top of 'App' or re-structure your components accordingly.
for eg., this will solve your case as Recipes is part of the hierarchy.
function App() {
  return (
    <Container>
      <TestContext.Provider value="TEST"> // My wealth for my family under me
        <Users /> //Users and all child components get them
        <Menu /> // Me too. my family tree gets context
        <Switch>
          <Route exact path="/" />
          <Route path="/aliments" component={Foods} /> // Me too. my family gets context
          <Route path="/recettes" component={Recipes} /> // Me too. my family gets context
          <Route path="/repas" component={Meals} /> // Me too. my family gets context
          <Route path="/planning" component={Planning} /> // Me too. my family  gets too
        </Switch>
      </TestContext.Provider>
   </Container>
  );
}


text:
Q: Excel formula contains =+ I have a formula like this:
=+SUMSQ(B14:B45)-MMULT(TRANSPOSE(L13:L16);K58:K61)
What does do =+ operator in Excel?
How to use it?

A:
What does the =+ do in this formula? =+SUMSQ(B14:B45)

Absolutely nothing. It is a throwback to Lotus style formulas and does no harm but is completely unnecessary. The equals sign at the left side is necessary to initiate the use of a worksheet function but the plus sign is redundant. The formula could just as easily be written as =SUMSQ(B14:B45).
That said, do not confuse this with a double-minus (e.g. -- or double unary). This is typically intended to convert a TRUE/FALSE result to a numerical one by mathematically flipping the sign (positive/negative nature of result) with the first minus then flipping it back with the second. In this way, a TRUE becomes a 1 and a FALSE a 0. While its predominant use is conversion of boolean values to numerical, the double unary can also be used to convert text that looks like a number to an actual number; e.g. =--RIGHT("ABC123", 3) is equal to 123, not text that looks like 123.
See Overview of Formulas for more information on the construction of formulas.


text:
Q: Powershell hash table call external command I have a powershell script that I schedule to check the previous ten days's dated "transaction" files and sorts by LastWriteTime because the year-to-date data is always growing. There are no changes over the weekend, and if there are none during the week I know the process on the server didn't run.
The resulting table has columns "Name", "Size (KB)" (converted "Length" from bytes to KB), and LastWriteTime. I'd like to add an "MD5" column. I have an md5sum.exe command on my computer. I'd like to construct the hash table such that it calls the external command within the expression field using the $_.FullName property.
I found how to calculate the MD5 checksum using PS natively from this post and I've integrated it as a one-liner into the expression value for the new column. I'd still like to know if it's possible to call an external command inside a hash table though.
Here's the original code:
$LOOKBACKXDAYS=( Get-Date ).AddDays(-10)
$SrcMachine='TheServerInQuestion'

if( -not ( Test-Path -Path \\$SrcMachine\C$ ) ) { net use \\$SrcMachine\C$ /user:mydomain\administrator }

Get-ChildItem -Path \\$SrcMachine\C$\temp transactions*.tab | `
    Where-Object {$_.LastWriteTime -ge $LOOKBACKXDAYS } | `
        Select-Object `
            -Property `
                Name , `
                @{name='Size (KB)'; expression={[string]([math]::ceiling($_.Length / [math]::pow(2, 10)))}} , `
                LastWriteTime | `
            Sort-Object `
                -Property `
                    'Size (KB)', `
                    LastWriteTime, `
                    Name | `
                Out-Host
Write-Host -ForegroundColor Green "`n`nAll Done!`n`n"
pause

and it produces output that looks like this:
Name                          Size (KB) LastWriteTime
----                          --------- -------------
transactions for 12172018.tab 13783     2018-12-17 12:05:04
transactions for 12182018.tab 13824     2018-12-18 12:05:06
transactions for 12192018.tab 13869     2018-12-19 12:05:16
transactions for 12202018.tab 13901     2018-12-20 12:05:14
transactions for 12212018.tab 13901     2018-12-21 12:05:12
transactions for 12222018.tab 13931     2018-12-22 12:05:16
transactions for 12232018.tab 13931     2018-12-23 12:05:12
transactions for 12242018.tab 13954     2018-12-24 12:05:14
transactions for 12252018.tab 13954     2018-12-25 12:05:16
transactions for 12262018.tab 14001     2018-12-26 12:05:26

This is the modified code that produces lower case, hyphen removed MD5 checksums, and I added a column that shows a 'Y' if the day of the week is a weekend so I can ignore an identical file. I changed some other stuff too.
$LOOKBACKXDAYS=( Get-Date ).AddDays(-10)
$SrcMachine='TheServerInQuestion'

if( -not ( Test-Path -Path TabFiles:\temp ) ) {
    New-PSDrive `
        -PSProvider FileSystem `
        -Name TabFiles `
        -Root \\TheServerInQuestion\C$ `
        -Credential mydomain\administrator
}

Get-ChildItem -Path TabFiles:\temp transactions*.tab | `
    Where-Object {$_.LastWriteTime -ge $LOOKBACKXDAYS } | `
        Select-Object `
            -Property `
                Name , `
                @{name='Size (KB)'; expression={[string]([math]::ceiling($_.Length / [math]::pow(2, 10)))}} , `
                @{name='MD5'; expression={ [System.BitConverter]::ToString($(New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider).ComputeHash([System.IO.File]::ReadAllBytes($_.FullName))).replace('-','').ToLower() }}, `
                @{name='Is Weekend'; expression={ $( if ($_.LastWriteTime.dayofweek -match 'Saturday|Sunday'){return 'Y'} else{return ''} ) } }, `
                LastWriteTime | `
            Sort-Object `
                -Property `
                    'Size (KB)', `
                    LastWriteTime, `
                    Name | `
                Format-Table
Write-Host -ForegroundColor Green "`n`nAll Done!`n`n"
pause

This is the output for the script above:
Name                          Size (KB) MD5                              Is Weekend LastWriteTime
----                          --------- ---                              ---------- -------------
transactions for 12172018.tab 13783     e825b1a58954203da9f8a16c454d9441            2018-12-17 12:05:04
transactions for 12182018.tab 13824     4de56734ceacd02db11bdd8a3dcdc628            2018-12-18 12:05:06
transactions for 12192018.tab 13869     1e4401afd2734004da372bfcf1e90395            2018-12-19 12:05:16
transactions for 12202018.tab 13901     49b1c5e29ea4da7e8a7a72bf610cecd6            2018-12-20 12:05:14
transactions for 12212018.tab 13901     49b1c5e29ea4da7e8a7a72bf610cecd6            2018-12-21 12:05:12
transactions for 12222018.tab 13931     36e40a546c6049e550b0feac9aa7adc7 Y          2018-12-22 12:05:16
transactions for 12232018.tab 13931     36e40a546c6049e550b0feac9aa7adc7 Y          2018-12-23 12:05:12
transactions for 12242018.tab 13954     9c97ccf81ce4cbb583fff348a739cc66            2018-12-24 12:05:14
transactions for 12252018.tab 13954     9c97ccf81ce4cbb583fff348a739cc66            2018-12-25 12:05:16
transactions for 12262018.tab 14001     ad18d544c8dea1d3d9cf1512c4a772e4            2018-12-26 12:05:26

There's ignorable duplicate data over the weekend and from Christmas Eve to Christmas, but there was inexcusable duplicate data from the 20th and 21st.

A: To answer your question, it is possible to call executable from the calculated property expression field as this correspond to a standard scriptblock.
The following should work
$md5exepath = "C:\Program Files\Git\usr\bin\md5sum.exe"
#Make sure you have a few png on your desktop or change the get-childitem so it matches something.
$Items = get-childitem -Path "$($Env:USERPROFILE)\desktop" -Filter '*.png' | Select -First 5

$Items | Select Name,
        @{n='md5';e={(& $md5exepath $_.FullName).split(' ')[0]}},
        @{n='test';e={(& 'cmd' "/c echo test")}}

Assuming you can see the test" from the echo command, then it confirms the external call works for you too.
Regarding md5sum.exe, validate the following.

*

*Make sure to use the correct path to your md5sum.exe.

*Try running from the windows command line : "c:\windows\md5sum.exe" "C:\windows\system32\notepad.exe" and make sure it produces the desired output and do not throw any error.

*Try running the script as an administrator

I copied md5sum.exe to the Windows folder and had empty results too.
As I found out, since Powershell did not produce any errors, while I copied the tool, I did not copy its dependencies and it was failing for that reason.


text:
Q: Subject operator does not provide the correct answers Would you please let me know why the total summation in the below posted code is 14?? I expected it to be 10
I was reading a tutorial about using rx in java 8. But i want to make sure that the totsl summation is as expected.
Please have a look at the below code:
code:
Integer subscriber1 = 0;
Integer subscriber2 = 0;
Observer<Integer> getFirstObserver() {
return new Observer<Integer>() {
    @Override
    public void onNext(Integer value) {
       subscriber1 += value;
    }

    @Override
    public void onError(Throwable e) {
        System.out.println("error");
    }

    @Override
    public void onCompleted() {
        System.out.println("Subscriber1 completed");
    }
};
}

Observer<Integer> getSecondObserver() {
 return new Observer<Integer>() {
    @Override
    public void onNext(Integer value) {
        subscriber2 += value;
    }

    @Override
    public void onError(Throwable e) {
        System.out.println("error");
    }

    @Override
    public void onCompleted() {
        System.out.println("Subscriber2 completed");
    }
};
}

PublishSubject<Integer> subject =
PublishSubject.create();
subject.subscribe(getFirstObserver());
subject.onNext(1);
subject.onNext(2);
subject.onNext(3);
subject.subscribe(getSecondObserver());
subject.onNext(4);
 subject.onCompleted();

 assertTrue(subscriber1 + subscriber2 == 14)

A: Let's do it step by step.
When subscribe first observer subject.subscribe(getFirstObserver());
 and post 1,2,3 - after that your subscriber1 = 6. Then you subscibe second observer subject.subscribe(getSecondObserver()); (but don't unsubscribe first one, so first observer will receive events) and post 4 - after that subscriber1 = 10 and subscriber2 = 4. So you result will be 14.
If you wan't disable your first observer after subscribing new, you should save Disposable returned by subject.subscribe(getFirstObserver()); and dispose it before subsribing new observer.


text:
Q: Select in M-N relationship I have the following tables:
product{
    id
    name
}
product_keyword{
    prod_id
    keyword_id
}
keyword{
    id
    keyword
}

Where a given product can have multiple keywords and a keyword can belong to multiple products.
Now I would like to, given a certain product, select all the "keyword-related" products. That is, if "prod" have keywords "key1" and "key2" I would like to select all products that have either "key1" or "key2" as keywords.

A: You can do this with joins:
select distinct p1.id, p1.name
from product p1
inner join product_keyword pk1 on pk1.prod_id = p1.id
inner join product_keyword pk2 on pk2.keyword_id = pk1.keyword_id
inner join product p2 on p2.id = pk2.prod_id
where p2.name = ?

The question mark represents the name of the product whose associated products you want to bring.


text:
Q: Phonegap Dialog Plugin is Working on android API (level 16) and it is not working on API (level 10) I Have just written the simple code the when user press back key on the device it should ask the user "Are you sure you want to exit"? if user press yes then user will exit from the application and on pressing no button it will do nothing.
I am using phonegap 3.6.3 and Phonegap dialog Plugin I have added the plugin using
phonegap plugin add org.apache.cordova.dialogs
In Config xml I have added
<gap:plugin name="org.apache.cordova.dialogs"/>

And I have also checked
<preference name="android-minSdkVersion" value="7" />

JS Code :-
var app = {
// Application Constructor
initialize: function() {
    this.bindEvents();
},
// Bind Event Listeners
//
bindEvents: function() {
    document.addEventListener('deviceready', this.onDeviceReady, false);
    document.addEventListener('backbutton', onBackKeyDown, false); //Listen to the User clicking on the back button
},
// deviceready Event Handler
//
onDeviceReady: function() {
    navigator.notification.alert("PhoneGap is working!!");
    initApp();
},
}};

function onBackKeyDown() {
navigator.notification.confirm(
"Are you sure you want to exit ?",  // message
onConfirm,                          // callback to invoke with index of button pressed
"Confirmation",                     // title
["Yes","No"]);                      // buttons label
// Prompt the user with the choice
}
function onConfirm(buttonIndex) {
if(buttonIndex==2){//If User selected No, then we just do nothing
    return;
}else{
    navigator.app.exitApp();// Otherwise we quit the app.
}
}

Same above code works fine in emulator for samsung galaxy s2 4.2.x (API 16)
Image link
Same code when i run it on emulator for samsung galaxy s2 2.3.x (API10) it is giving error
"NoSuchMethodError"
Image link
I have read the document about the plugin and it say it support all android device.
so what am I doing wrong here?
So please help.
Thanks.

A: Update: I have removed my old message because below would be enough for everyone to make this Plugin work on all Android version.

Cordova/PhoneGap: How to make dialog plugin work on all Android devices

Here is the solution code: https://github.com/aahad/Cordova-Plugin-dialogs--Android-all-versions/tree/master

Since Oct 16, 2014 (commit: 23bebf96f7a3388c7483afc0091faecf943692d3), the dialog Plugin supports API 17 on-wards.
This commit was to properly format right-to-left and left-to-right languages, as shown below in the snapshot. (Check for setTextDirection API level)
Example: without any code modification

Now if there is NO need to properly format localized strings (or no use of localization at all) then if these lines are removed then the plugin support will be available from API 14 on-wards.
Bring down to API 14 or 11
Currently dialog plugin is using device's light theme (AlertDialog.THEME_DEVICE_DEFAULT_LIGHT) that is available since API 14. So if it can be changed with something else like AlertDialog.THEME_HOLO_LIGHT, AlertDialog.THEME_HOLO_DARK  or AlertDialog.THEME_TRADITIONAL as these are present since API 11. In this way we can make the plugin work on API 11.
I tried AlertDialog.THEME_HOLO_LIGHT and found exactly same results as of with AlertDialog.THEME_DEVICE_DEFAULT_LIGHT.
Using AlertDialog.THEME_TRADITIONAL, I see following result

Using AlertDialog.THEME_HOLO_DARK, I see following result

Bring down to API 7
AlertDialog.Builder(Context context, int theme) was used to create instance of AlertDialog and this two parameter based constructor was added in API 11. While the basic original AlertDialog constructor that takes single parameter was present since API 1. So if there is NO hard need for a specific theme then by skipping the two parameter based constructor and by using single parameter based constructor we can easily get down to API 7.
1. Notification - Since API 14 onwards
This is for someone who doesn't need localization formatting in their app.
Note: - Even after removing these lines, still localized strings/text will appear as shown below; but the proper formatting will be out. Though it's not visible in the snapshot but it is expected.
Results:

2. Notification - Since API 7 onwards
This is for someone with NO hard requirement for any specific theme or localization and just need dialog functionality to work on older devices.
Results:


text:
Q: $Ax + By = C$ where $A, B, C$ are positive whole numbers. Is it possible to have an infinite number of solutions to this? $Ax + By = C$ where $A, B, C$ are positive whole numbers. Is it possible to have an infinite number of solutions to this or will it have a specific number of solutions or just a single solution? (solutions being positive whole numbers too, i.e. both $x$ and $y$ should be positive whole numbers too.)

A: There can be no solution (e.g. $x+y=1$), exactly one solution (e.g. $x+y=2$),
or multiple solutions (e.g. $x + y = 3$).
In any case, the number of solutions is finite, since
$0 < x < \frac CA$ and  $0 < y < \frac CB$.

A: Since all numbers are positive, we have
$$1\le x,y <Ax+By,\quad\text{hence}\quad 1\le x,y\le C-1,$$
so there can't be more than $(C-1)^2$ solutions.

A: Since $B\neq0$ any $x$ there is at most one $y$ that satisfies $Ax+By=C$.
Also for $x$ large enough we have $Ax>C$ so that $Ax+\text{ any positive number}>C$
Since $x$ is demanded to positive we conclude that there are only a finite number of $x$'s  for wich there is an $y$ that satisfies $Ax+By=C$.


text:
Q: jQuery .load() - load content from external page into the same page via link in loaded content i'm loading external contents inside a page with .load().
in my index.html i have this code:
$(document).ready(function(){
   $("#conteudo_mostrar").load("inicial.html");
});

and

so, in my inicial.html i have another link to contact.html, and when someone clicks that link (contact link inside of inicial.html) I need to replace the inicial.html to contain contact.html inside the same div #conteudo_mostrar on the page index.html
How to do that??

A: You can use .get() and suppose you have a link for contact.html:
Contact

Then:
$(document).ready(function() {
    $.get('inicial.html', function(data) {
        $('#conteudo_mostrar').html(data);
    });

    $('#lnkContact').live('click', function(e) {
        e.preventDefault();
        $.get((this).attr('href'), function(data) {
            $('#conteudo_mostrar').html(data);
        });
    });
});

If in case you're going to add more links, you'll just do the same for every id. If you have another link, let's say for gallery.html:
Gallery

You'll just need to append it in your code, just like the one in lnkContact, just change it to lnkGallery:
$('#lnkGallery').live('click', function(e) {
    e.preventDefault();
    $.get((this).attr('href'), function(data) {
        $('#conteudo_mostrar').html(data);
    });
});

Your whole code will now be:
$(document).ready(function() {
    $.get('inicial.html', function(data) {
        $('#conteudo_mostrar').html(data);
    });

    $('#lnkContact').live('click', function(e) {
        e.preventDefault();
        $.get((this).attr('href'), function(data) {
            $('#conteudo_mostrar').html(data);
        });
    });

    $('#lnkGallery').live('click', function(e) {
        e.preventDefault();
        $.get((this).attr('href'), function(data) {
            $('#conteudo_mostrar').html(data);
        });
    });
});

And for every other links, you just need to make the same changes. Provided that you have an id attribute to distinguish each link.
A more efficient way by Preston
Tag each link by link class:
Contact
Gallery

Then:
$(document).ready(function() {
    $.get('inicial.html', function(data) {
        $('#conteudo_mostrar').html(data);
    });

    $('.link').live('click', function(e) {
        e.preventDefault();
        $.get((this).attr('href'), function(data) {
            $('#conteudo_mostrar').html(data);
        });
    });
});

A: REVISION based on question clarifiations:
It's simple enough.  You just need to use live to the link class/id.  This binds the link to elements that may not yet exist on the page.  Then, within the bind click event, just load the content.html like so:
$(document).ready(function(){
    // Load the initial content
    $("#conteudo_mostrar").load("inicial.html");
    $("#contact_link").live("click", function() {
        $("#conteudo_mostrar").load("contact.html");
    }
});


text:
Q: Bitwise operations, how to check for 0 or 1? I have an integer like:
0x10000010

I would like to know if a particular bit is 1 or 0. For example, something like:
int number = 0x10000010;
for (int i = 0; i < 8; i++) {
    if (ith bit == 1) {
        System.out.println("bit " + i + " is 1.");
    } else {
        System.out.println("bit " + i + " is 0.");
    }
}

---- output ----
bit 0 is 1
bit 1 is 0
bit 2 is 0
bit 3 is 0
bit 4 is 0
bit 5 is 0
bit 6 is 1
bit 7 is 0

I've forgotten how to do this, and what this type of operation is called,
Thanks

A: number & (1 << i) will be 0 if the bit wasn't set, non-zero if it was.

A: Similar to dty's answer
int number = 0b10000010; // you are assuming this is binary not hex.
for (int i = 0; i < 8; i++) {
    if((number >> i) & 1 != 0)
        System.out.println("bit " + i + " is 1.");
     else
        System.out.println("bit " + i + " is 0.");
}

or
int number = 0b10000010; // you are assuming this is binary not hex.
for (int i = 0; i < 8; i++)
    System.out.println("bit " + i + " is " + ((number >> i) & 1));


text:
Q: Android with Eclipse Buttons I'm just starting out with the Android/Eclipse SDK and I have no previous Java experience.
I've seen lots of tutorials for running Toasts onclick but I'm trying to make it so that when a button is clicked a text field is populated with the text of that button.
In other words if I press a button which is labelled as 'Hello' then the contents of a textfield will become 'Hello'.
Any help is greatly appreciated.

A: write code in onClick()
String text = view.getText();
// use toast here to display text..

A: TextView mText=(TextView)findViewById(R.id.textview1);
Button mbutton=(Button)findViewById(R.id.button1);

    mbutton.setOnClickListener(new Button.OnClickListener() {

            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                mText.setText("Hello");

            }
        });

Hope i may works..

A: Wrapping it up. You must have a "button1" and a "textview1" defined in your main.xml.
package my.dummy.hello;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.view.View;
import android.view.View.OnClickListener;

public class HelloActivity extends Activity implements OnClickListener {
    Button b=null;
    TextView tv=null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        b=(Button)findViewById(R.id.button1); // button1 set in main.xml
        b.setOnClickListener(this);
        tv=(TextView)findViewById(R.id.textview1); // textview1 set in main.xml
    }

    public void onClick( View v ) {
        if (v == b) {
            tv.setText( b.getText() );
        }
    }
}

A: Suppose your button's id is button1, and textview's id is textview1

Button My_Button=(Button)findViewById(R.id.button1);

TextView textView = (TextView)findViewById(R.id.textview1);

My_Button.setOnClickListener(new OnClickListener(){
      public void onclick(View v){
           textView.setText("hello");
      }
);


text:
Q: Backup SQLite Database in Android I need to make an offline backup of the SQLite database in the mobile's internal storage or the SD Card. But I am clueless, how's this possible.
I followed many threads here on SO, but they suggest copying the DB one location to other, which is not suitable for me, neither to the Google Drive.
Any guidance would be precious.

A: I used this approach.
public string DATABASE_NAME = "YOUR DATABASE NAME HERE";

   public void exportDB(){
        try {
            File sd = Environment.getExternalStorageDirectory();
            File data = Environment.getDataDirectory();

            if (sd.canWrite()) {
                Log.d("TAG", "DatabaseHandler: can write in sd");
                //Replace with YOUR_PACKAGE_NAME and YOUR_DB_NAME
                String currentDBPath = "filepath here"+DATABASE_NAME;
                //Replace with YOUR_FOLDER_PATH and TARGET_DB_NAME in the SD card
                String copieDBPath = DATABASE_NAME;
                File currentDB = new File(data, currentDBPath);
                File copieDB = new File(sd, copieDBPath);
                if (currentDB.exists()) {
                    Log.d("TAG", "DatabaseHandler: DB exist");
                    @SuppressWarnings("resource")
                    FileChannel src = new FileInputStream(currentDB).getChannel();
                    @SuppressWarnings("resource")
                    FileChannel dst = new FileOutputStream(copieDB).getChannel();
                    dst.transferFrom(src, 0, src.size());
                    src.close();
                    dst.close();
                }
            }
        } catch  (Exception e) {
            e.printStackTrace();
        }

    }

A: Finally, with this GitHub sample I successfully implemented whatever customization I needed. And it's live now.


text:
Q: ElasticSearch - specify range for a string field I am trying to retrieve the mentions of years between 1933 and 1949 from a string field called text. However, I cannot seem to find the working range query for that. What I tried to so far crashes:
   {"query":
        {"query_string":
              {
                "text": [1933 TO 1949]
               }
         }
    }

I have also tried it like this:
   {"query":
         {"filtered":
               {"query":{"match_all":{}},
                 "filter":{"range":{"text":[1933 TO 1949]}
                }
         }
    }

but it still crashes.
A sample text field looks like the one below, containing a mention of the year 1933:
"Primera División 1933 (Argentinië), seizoen in de Argentijnse voetbalcompetitie\n* Primera Divisió         n 1933 (Chili), seizoen in de Chileense voetbalcompetitie\n* Primera División 1933 (Uruguay), seizoen in de Uruguayaanse voetbalcompetitie\n \n "
However, I also have documents not containing any years inside, and I would like to filter all the documents to preserve only the ones mentioning years in a given period. I read here http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html that the range query can be applied to text fields as well, and I don't want to use any intermediate solution to identify dates inside texts.
What I basically want to achieve is to be able to get the same results as when using a search URI query:
     urltomyindex/_search?q=text:%7B1933%20TO%201949%7D%27

which works perfectly.
Is it still possible to achieve my goal? Any help much appreciated!

A: This should do it:
GET index1/type1/_search
{
  "query": {
    "filtered": {
      "filter": {
        "terms": {
          "fieldNameHere": [
            "1933",
            "1934",
            "1935",
            "1936",
            "1937",
            "1938",
            "1939",
            "1940",
            "1941",
            "1942",
            "1943",
            "1944",
            "1945",
            "1946",
            "1947",
            "1948",
            "1949"
          ]
        }
      }
    }
  }
}

If you know you're going to be needing this kind of search frequently it would be much better to create a new field "yearPublished" or something like that so you can search it as a number vs a text field.


text:
Q: CSS in react-native - syntax error  I'm new to js, react and css so this is going to be very basic but it's not to me. I have these containers and I'm trying to put a text field inside one of them but I'm getting syntax error at Text. Does it have something to do with < > />? Thank you

    <View style={styles.top}

    />
    <MapView style={styles.map}
    region ={{
    latitude:lat,
    longitude:long,
    latitudeDelta: 0.1,
    longitudeDelta: 0.1,

}}
   >

    </MapView>
    <View style={styles.bottom} />

  </View>

);

A: Indeed it does. You need to close your jsx View tag.
<View style= {styles.container}>
  <View style={styles.top}>
    <Text> Hi there</Text>
  </View>
</View>

A: The render method can only render a single root node i.e you only define one parent root in render method.
You can define multiple child root under one parent.


text:
Q: Show flash message without redirect (eg forward). Messages shown twice Is it possible to show flash messages in Symfony 2 without redirect? Or editing core files in another possible solution on google groups?
//Symfony\Component\HttpFoundation\Session
public function setFlash($name, $value, $persist = true)
{
    if (false === $this->started) {
        $this->start();
    }
    $this->flashes[$name] = $value;
    if($persist) {
        unset($this->oldFlashes[$name]);
    }
    else {
        $this->oldFlashes[$name] = $value;
    }
}

UPDATE
Oh actually I noticed if I just used a forward, flash messages will show, but it will still show on next request

A: Why using flashes if you don't want them to be persisted until next request ?
Couldn't you find other ways to display feedback like template parameters ?
If not, you could add this in your templates (according you are displaying flashes like below):
{% if app.session.hasFlash('notice') %}
<div class="flash-notice">
    {{ app.session.flash('notice') }}
    {{ app.session.removeFlash('notice') }}
</div>
{% endif %}

So that any template that displays these flashes before redirection will remove them from session before returning the response. I think it's the last better solution.

A: I will speak in general terms, because you want something that is not a ready standard.
At this time Symfony flash messages appear after the request, they are this way, and to preserve it, you need to find an alternative, usign an ajax call.
You need to call an action script using an ajax request, serializing the data of a form, getting the message to return and then display it the way it server you better.
I used http://jquery.bassistance.de/message/demo/ along with this sample jquery call in some projects, works good:
 $.post("/product/saveAjax", { $("#product").serialize() },
 function(data){
  $().message(data.message);
 }, "json");

The return from saving an item with ajax is different, in this case i´m encoding the data using JSON, so, if you want to perfom another actions you can inject more variables in the JSON array, manipulating them inside function(data) { ... }
Hope that helps

A: Flash messages have been created in order to live through the redirection you usually do after a form submission success. That's why they live for 2 requests.
If you want to manage soem user notifications in your app, make a controller managing a notification TWIG block in your layout. This block can embed flash messages AND these notifications you handle with the controller. You'll have to set them in your session, remove them in your NotificationController and it's alright...


text:
Q: export odbc/database (data dictionary) into excel I have searched high and low for ways to report back / export the data dictionary that already exists in my database. All I can find are one line codes but I have no clue how to implement that into something i can work with.
Right now I access my database in Excel using MS Query. I create my own "reports" in excel using formulas and functions. I need a Bible (of sorts) to look for fields in each table. Within MS Query I can View the data dictionary but I would prefer to dump the entire thing.
Someone somewhere along the way created one, which i use today but it is outdated and I would like to find out how to do it myself.


text:
Q: AT&T UNIX System V Release 4 - How do I create a new "Administrator" user? I am running AT&T UNIX System V Release 4 Version 2.1 inside VirtualBox, and want to create a new "user account" for myself.  At first, I simply created a new user with the useradd command, but didn't specify a group.  When I logged in, I didn't even have a high enough permission level to create a new directory in my home folder.  I then deleted my account and recreated it using the same command, except that I specified that the group is "adm".  After doing this, I was able to create a new directory.  This indicates to me that I now have a higher permission level.
Is this the correct way to add an administrator user?  If so, what limitations are still in place?

A: I'm not familiar with ATT SVR4 — it was old before my time. But from your description, I think I can provide enough guidance to solve your problem.
Unix doesn't exactly have a notion of "administrator user". That's a Windows name that doesn't map directly to a Unix concept. Under Unix, the only administrator account is root, user ID 0. Accounts that belong to physical users don't have such characteristics. An administrator is someone who knows the password to the root account. On systems that use sudo, such as Ubuntu, you can say that an administrator account is an account that is allowed to run programs as root through sudo, but sudo is not a historical Unix tool and is not bundled with SVR4. The traditional way to become root is with the su command, and that requires knowing the root password.
Accounts do belong to one or more groups, which can indirectly confer privileges, but that's more varied than having "administrator users". I remember systems where the adm group gives the permission to read system log files (it's even the case in some recent Linux distributions); but that's only one thing among many. In some Unix variants (I don't know about SVR4), running su has an additional prerequisite, that the user must belong to the wheel group.
In any case, you don't need any special permission to create a subdirectory in your home directory. It's possible that the adduser command on SVR4 doesn't create the new user's home directory, or requires an option to do so; the syntax of useradd is not standardized, so check the man page on your system.
In summary:

*

*To create an account, use useradd. If you need to create the user's home directory by hand, you can use these commands (as root of course):
mkdir /home/bob
chown bob /home/bob
chgrp users /home/bob      # or whatever bob's primary group is
chmod 755 /home/bob

*To create an administrator user, create a user, and give the person who'll be using the account the root password. If required, add the user to the wheel group (either with built-in tools, if provided on your Unix variant, or by editing the /etc/group file manually).

A: On old unix when you create a user,you must tell to create
home.
So correct way is
useradd -g other -m -d /home/utente
passwd utente
chown utente /home/utente
chgrp utente /home/utente
chmod 755 /home/utente

of course replace utente with your name.
If you want admin user,must use root as group
,but is dangerous,better use normal user and use
su -

for admin templates.
And if you want you can create a script for automatic creation of user.
How to do?
Simply google for it ;)


text:
Q: ElasticSearch: Exact match for multiple fields How can I generate a query like this?
select * from topic where field1 = "abc" and field2 = "xyz"

I've tried the following but I can't get the correct syntax:
curl -X POST "localhost:9200/topic/_search" -H 'Content-Type: application/json' -d'
{
  "query": {
    "terms" : {
       "field1": "abc",
       "field2": "xyz"
    }
  }
}
'

A: How about...
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "field1": "abc"
          }
        },
        {
          "term": {
            "field2": "xyz"
          }
        }
        ]
      }
  }
}

The Terms Query doesn't do what you want. Instead it searches for different values within the same key.


text:
Q: How to control sequence of tasks inside a data flow in SSIS? I am creating an SSIS package, it has one execute SQL task and one data flow task.
In the data flow task, the data is moved from from different source tables to the respective target tables.
Can we control the order in which the ETL execution takes place, so that each table transformation completes before the next one starts?
I don't want to create multiple packages, need to handle it one package.
For e.g., in the data flow task, we have the below code executing:

*

*S1->data conversion transf->T1

*S2->data conversion transf->T2,

*S3->data conversion transf->T3,

*S4->data conversion transf->T4,...................

And the data load sequence must be as follows:

*

*S1->data conversion transf->T1,

*S4->data conversion transf->T4,

*S3->data conversion transf->T3,

*S2->data conversion transf->T2,...............

Please let me know how to achieve it.

A: I think the best approach to deal with different and constrained data flows is by creating different data flow tasks to handle the requirements of each of them. You could place them in a sequence container using precedence constraints. For example:

You can define the constraints in the way you would like the tasks to complete, being it in regards of the exit status (failure, success or completion) and expression (let's say, you create a variable that controls the precedence constraints), for example:

In this case, the data flow task S2 to T2 will only execute if the value of the variable myvarevaluates to true AND the data flow task S3 to T3 exits with a success status
Hope this helps.


text:
Q: Suppose $f$ is a continuous function on $[0, 1]$. Suppose $\int_0^1 f(x)dx = 1$ Show that $\exists c \in [0, 1]: f(c) = 3c^2$. Suppose $f$ is a continuous function on $[0, 1]$. Suppose $\int_0^1 f(x)dx = 1$ Show that $\exists  c \in [0, 1]: f(c) = 3c^2$.
(Hint: consider $g(x) = f(x) − 3x^2$)
This is what I have so far. Let $g(x) = f(x) − 3x^2$.Then since $f$ is continuous and $3x^2$ is continuous, so is $g$. Hence it is Riemann integrable. Taking the Riemann integral at endpoints $[0,1]$, you get $\int_0^0 g = 0$ and $\int_0^1 g = 0$. Then $g$ is the constant $0$ or there exists a turning point in $g$ in the interval $[0,1]$. If constant, $0=c$. If $g$ is not constant, there is a turning point given by $G'(x) = 0$ where $G(x) = \int g$. Then $G'(x) = 0 \implies g(x) = 0 \implies f(x) − 3x^2 = 0 \implies f(x) = 3x^2$ and hence x=c.
I feel like I'm missing some justifications. Any help here would be appreciated.

A: From the observation $\int_0^1 g(t) \, dt = 0$, you can immediately use the integral variant of the mean value theorem to arrive at the desired conclusion (there exists $c \in [0,1]$ such that $g(c)=0$).

A: Here is an alternative  proof: $g$ is continuous  If it has  zeros then it  is always positive or always negative. Suppose $g(x) >0$ for all $x$. Then $\int_0^{1}f(x)dx>\int_0^{1} 3x^{2}dx=1$ a contradiction. Similar argument holds when $g(x) <0$ for all $x$.


text:
Q: Why is my Django FormModel is not submitted when I click submit button? I am working on simple login and signup pages on Django.
This is how they work:
You create an account in the signup page. After the process is complete, it redirects you to the login page.
However, when you click a button to submit information on the signup page, it is not submitted.
Here are the codes:
urls.py
from django.urls import path, include
from . import views

urlpatterns = [
    path('account/login', views.login_page, name='login'),
    path('account/signup', views.signup_page, name='signup')
]

models.py
from django.db import models

class User(models.Model):
    username = models.CharField(max_length=30,)
    password = models.CharField(max_length=255)
    firstName = models.CharField(max_length=255)
    lastName = models.CharField(max_length=255)
    emailAddress = models.EmailField(max_length=255)

    def __str__(self):
        return self.username

forms.py
from .models import User
from django.forms import ModelForm, TextInput, PasswordInput, EmailInput

class UserForm(ModelForm):
    class Meta:
        model = User
        fields = ['username',
                  'password',
                  'firstName',
                  'lastName',
                  'emailAddress']
        widgets = {
            'username': TextInput(attrs={
                'class': 'signup_input',
                'placeholder': 'Username'
            }),
            'password': PasswordInput(attrs={
                'class': 'signup_input',
                'placeholder': 'Password'
            }),
            'firstName': TextInput(attrs={
                'class': 'signup_input',
                'placeholder': 'First Name'
            }),
            'lastName': TextInput(attrs={
                'class': 'signup_input',
                'placeholder': 'Last Name'
            }),
            'emailAddress': EmailInput(attrs={
                'class': 'signup_input',
                'placeholder': 'Email Address'
            })
        }
        labels = {
            'username': '',
            'password': '',
            'firstName': '',
            'lastName': '',
            'emailAddress': ''
        }

views.py
from django.shortcuts import render, redirect
from .forms import UserForm

def login_page(request):
    return render(request, 'Account/login_page.html')

def signup_page(request):
    if request.method == 'POST':
        form = UserForm(request.POST)
        form.save()
        return redirect('login')
    else:
        form = UserForm()
        context = dict()
        context['form'] = form
        return render(request, 'Account/signup_form.html', context=context)

signup_page.html
{% load static %}
<!DOCTYPE html>
<head>
  <style>
    * {
      box-sizing: border-box;
    }
    html {
      min-height: 100%;
      height: 100%;
      margin: 0;
    }
    body {
      height: 100%;
      padding: 1px;
      margin: 0;
    }

    #signup_form_container {
      height: 600px;
      width: 450px;
      border: 1px black solid;
      margin-left: auto;
      margin-right: auto;
      margin-top: 100px;
    }
    .signup_input {
      display: block;
      height: 46px;
      width: 250px;
      margin-left: auto;
      margin-right: auto;
      margin-top: 15px;
      border-radius: 15px;
    }
    .signup_btn {
      display: block;
      height: 46px;
      width: 250px;
      border-radius: 15px;
      margin-left: auto;
      margin-right: auto;
    }
  </style>
</head>
<body>
  <div id="signup_form_container">
    {% block form%}
    {% endblock %}
    <input type="submit" class="signup_btn" value="Submit"/>
    <button class="signup_btn">Cancel</button>
  </div>
</body>

signup.form.html
{% extends 'Account/signup_page.html' %}

{% block form %}
  <form method="post" action={% url 'signup' %}>{% csrf_token %}
    {{form}}
  </form>
{% endblock %}

Everything works fine except submitting the information. When I click submit button, nothing happens. It seems like post method is not working properly for some reason. I've been google searching and checking my codes to find out if there is something missing but I could not find the solution for the issue. I'd be very appreciated if somebody could solve this issue!

A: The submit button needs to be contained in the <form> tag to submit that form when clicked. Move the button to signup.form.html and remove it from signup_page.html
signup.form.html
{% extends 'Account/signup_page.html' %}

{% block form %}
  <form method="post" action={% url 'signup' %}>{% csrf_token %}
    {{form}}
    <input type="submit" class="signup_btn" value="Submit"/>
  </form>
{% endblock %}