text:
Q: Test error : Status -> Expected: 422 Received: undefined I am trying to test the following Typescript code:
import express, { Request, Response } from "express";
import { validate } from "./validator";
import pgp from "pg-promise";
const app = express();
app.use(express.json());

app.post("/checkout", async function (req: Request, res: Response) {
  const connection = pgp()("postgres://postgres:dev123@localhost:5432/tdd-app");
  try {
    const isValid = validate(req.body.cpf);
    if (!isValid) throw new Error("Invalid cpf");

    const output: Output = {
      total: 0,
    };
    const items: number[] = [];
    if (req.body.items) {
      for (const item of req.body.items) {
        if (item.quantity <= 0) throw new Error("Invalid quantity");
        if (items.includes(item.idProduct)) throw new Error("Duplicated item");
        const [productData] = await connection.query(
          "SELECT * FROM cccat10.product WHERE id_product = $1",
          item.idProduct
        );
        output.total += parseFloat(productData.price) * item.quantity;
        items.push(item.idProduct);
      }
    }

    if (req.body.coupon) {
      const [couponData] = await connection.query(
        "SELECT * FROM cccat10.coupon WHERE code = $1",
        [req.body.coupon]
      );
      if (couponData.expire_date.getTime() >= new Date().getTime()) {
        const percentage = parseFloat(couponData.percentage);
        output.total -= (output.total * percentage) / 100;
      }
    }
    res.json(output);
  } catch (e: any) {
    res.status(422).json({
      message: e.message,
    });
  } finally {
    await connection.$pool.end();
  }
});

type Output = {
  total: number;
  message?: string;
};

app.listen(3000);

And my test are this:
test("Shouldnt create an order with duplicated item", async function () {
  const input = {
    cpf: "684.053.160-00",
    items: [
      { idProduct: 1, quantity: 1 },
      { idProduct: 1, quantity: 1 },
    ],
  };
  const response = await axios.post("http://localhost:3000/checkout", input);
  const output = response.data;
  expect(output.status).toBe(422);
  expect(output.message).toBe("Duplicated item");
});

When I put a console.log into the catch of the try catch code, you can confirm that the test is falling into the catch, but for some reason the status is not being sent, only the message.
If I remove the line
expect(output.status).toBe(422);

inside the test, it will be work.
The problem is with the output.status == undefined inside this specific test case.
I have other tests that can receive the status from the code:
 res.status(422).json({
  message: e.message,
});

like the test:
test("Shouldnt accept an order with an invalid cpf ", async function () {
  const input = {
    cpf: "406.302.170-27",
  };
  const response = await axios.post("http://localhost:3000/checkout", input);
  const output = response.data;
  expect(response.status).toBe(422);
  expect(output.message).toBe("Invalid cpf");
});

Can someone help me to fix this status code on the test "Shouldn't create an order with duplicated item" ?

A: In the first example you're checking output.status and in the second example you're checking response.status. So try response.status in the first one.


text:
Q: How to replace part of the string in a specific property present in all tags with Javascript/jQuery I'm trying to create a function that allows me to replace part of the content from a determined property present in several tags across the DOM.
example:
Text Here
Text Here

In the code above, PROPERTY is what i want to change, but only the part that says MEN, leaving the rest of the string as it is on each instance.
For the example I have used 2 instances but the real code will have close to 100 or more!
Not sure how to automate this process... any help would be welcome.

A: Here is a pure JavaScript option with RegEx:
var elements = document.getElementsByTagName('a');

for (var i = 0; i < elements.length; i++) {
    var currentElement = elements[i].getAttribute('property');
    currentElement = currentElement.replace(/\w*/, "[the value you want to replace with]");
    elements[i].setAttribute('property', currentElement);
}

This will target all  elements in the DOM and change wathever string is infront of the first -.
Good luck
Zorken17

A: Assign a class to all the a tags
Text Here
Text Here

Then use the class name to select the elements:
$(".to-replace").each(function (e) {
    var val = $(this).attr("property");
    val = val.replace("men", "something else");
    $(this).attr("property", val);
});

A: Simple:
$('a[property]').each(function() {
    var value = $(this).attr('property');
    $(this).attr('property', value.replace("men-", ""));
});

See it working:
http://jsfiddle.net/ct7ppynz/

A: With you help guys I have made some changes to your answers and actually sorted the puzzle! The solution is below:
$('a[property]').each(function() {
    var value = $(this).attr('property');
    var val = value.split("-_-", 1);
    $(this).attr('property', value.replace(val, "women"));
});

This will target the property across the entire DOM and replace ONLY THE FIRST part of the string regardless of what the first part actually is... So it can be MEN, WOMEN or KIDS, and will still replace it with he right gender when needed!
Thank you guys for your help!
LEP

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I make a custom block with Minecraft Addons? How can I add an entirely new block to Minecraft with addons, like mods on Java Edition?

A: Requirements

*

*Windows 10

*Minecraft Windows 10 Edition

*I also recommend getting a new text editor other than notepad, I use Notepad++
Before We Begin

*

*This answer assumes you know how to create a proper manifest, pack
icon, and pack dependency linking.

*A rule of thumb for naming is use only no cap a-z, _, and 0-9 where the first character is not a number.

Creating the Block File
Create a folder in your behavior pack called blocks. Then go into it. Create a .json file and call it what you want the ID for your block to be (Should use underscores _ instead of spaces, also no caps). I have made a file called beige_brick.json.
{
    "format_version":"1.16.0",
    "minecraft:block":{
        "description":{
            "identifier":"msab:beige_brick",
            "is_experimental":false,
            "register_to_creative_menu":true
        },
        "components":{
            "minecraft:destroy_time":1
        }
    }
}

Open it in your editor and paste that. What did we do?

*

*"identifier":"msab:beige_brick" - I made a block with ID msab:beige_brick. The thing before the colon : is your prefix. This will be the unique prefix for everything new your addon creates. Make it whatever you want, as long as it is not minecraft:. The part after that is what our item's unique ID is. The block's ID must be the same as the file name or it will not work.

*"minecraft:destroy_time:1" - We have a destroy time of one. In the latest full release, tools cannot affect destruction time at all. This is one of many components.

Adding & Registering a New Texture
In your resource pack, make a folder called textures. Then inside a new folder called blocks. Inside that put your PNG that you want your block to look like. Name it beige_brick (or whatever you made your ID)

*

*Default Minecraft Blocks are 16x16, although you can use any square size.
Go back to your textures folder and make a JSON file called terrain_textures.json. This is where we will actually register our textures. In it paste:

{
    "num_mip_levels":4,
    "padding":8,
    "resource_pack_name":"msab",
    "texture_data":{
        "msab:beige_brick":{
            "textures":"textures/blocks/beige_brick"
        }
    },
    "texture_name":"atlas.terrain"
}

All that matters here is that msab is our prefix and blocks/beige_brick is our file path. Obviously if you used a different ID/prefix, change these.
Resource Pack Texture Assignment
In your resource pack create a file called blocks.json. In it paste:
"format_version":[1,1,0],
    "msab:beige_brick":{
        "sound":"stone",
        "textures":"msab:beige_brick"
    }
}

We apply a sound and texture to our Beige Bricks. I set the sound to stone, but there are many others such as metal, and you can even add your own new sound, although I will not go over that right now. I also use the texture msab:beige_brick, which we registered before.
Language Files
Language files is how we name our item, for example, a lit pumpkin is called a Jack O' Lantern.
Make a folder called texts in your resource pack, and in that a file called en_US.lang. In that put this:
block.msab:beige_brick.name=Beige Brick

We do block.<prefix:ID>.name=<Block Name>. Pretty easy.
I also like to copy this file and have a second called en_GB for UK English.
We're Done
Try compressing and putting this into Minecraft!


text:
Q: Android generic layout for all screen sizes
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             xmlns:app="http://schemas.android.com/apk/res-auto"
             xmlns:tools="http://schemas.android.com/tools"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             tools:context="com.main.turkkusu.radyo.MessageFragment"
             android:id="@+id/scream_frame">

    <!-- TODO: Update blank fragment layout -->

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="120dp"
        android:layout_centerHorizontal="true"
        >

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <EditText

                android:textColor="@color/colorAccent"
                android:maxLength="150"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:inputType="textNoSuggestions|textCapSentences"
                android:ems="10"
                android:id="@+id/message_scream_text"
                android:layout_marginLeft="19dp"
                android:layout_marginStart="19dp"
                android:hint="Bir şeyler söyleyin..."
                android:windowSoftInputMode="adjustResize|adjustPan"
                android:layout_alignParentBottom="true"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true"
                android:layout_marginBottom="16dp" />

            <Button
                android:text="Gönder"
                android:layout_width="100dp"
                android:layout_height="wrap_content"
                android:layout_marginRight="19dp"
                android:layout_marginEnd="10dp"
                android:id="@+id/message_scream_button"
                android:layout_alignBaseline="@+id/message_scream_text"
                android:layout_alignBottom="@+id/message_scream_text"
                android:layout_alignParentRight="true"
                android:layout_alignParentEnd="true" />

            <ProgressBar
                style="?android:attr/progressBarStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_centerHorizontal="true"
                android:id="@+id/scream_progressbar" />

            <RelativeLayout
                android:layout_width="300dp"
                android:layout_height="300dp"
                android:layout_centerHorizontal="true"

                android:id="@+id/pool_layout">

                <ScrollView
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:id="@+id/scream_scroll"
                    android:layout_alignParentTop="true"
                    android:layout_alignParentLeft="true"
                    android:layout_alignParentStart="true">

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:orientation="vertical"
                        >

                        <TextView
                            android:textColor="@color/colorPrimary"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:id="@+id/message_pool_view"
                            />
                    </LinearLayout>
                </ScrollView>

            </RelativeLayout>

        </RelativeLayout>
    </FrameLayout>

</FrameLayout>

Above is my layout code and the appareances for the different screen densities. Even tought I use DP scale for the measurement, I get different results for different phones. Do I really have to make all different kinds of layouts for different densities?


text:
Q: HttpClient has disconnected. Attempted to read past the end of the stream I have a simple webApi app on IIS. There is a MessageController which is ControllerBase and [Route("api/[controller]"), ApiController]. There I have the only method [HttpPost] public IActionResult Send([FromBody] MessageViewModel message) with the model of two fields.
Then, I have an ApiConnector which sends messages to the webApi:
public class ApiConnector : IDisposable
{
    private readonly HttpClient _client = new HttpClient();
    private readonly string _apiUrl;

    public ApiConnector(string apiUrl) => _apiUrl = apiUrl;

    public void SendMessage(string sender, string message)
    {
        try
        {
            _client.PostAsJsonAsync($"{_apiUrl}/message", new { sender, message });
        }
        catch { }
    }
}

Everything is written with Asp Core 2.2. When I run ApiConnector from ConsoleApp (inside of while(true) loop) everything is ok. When I POST from Postman everything is ok. But, as soon as I try to do the same from any other place (app, without endless loop, I suppose) a Controller of WebApi crushes.
Message: The client has disconnected;
Inner message: Attempted to read past the end of the stream.
How to send this request properly?

Exception text anyway:
"Message":"The client has disconnected",
"Data":{},
"InnerException":{
   "ClassName":"System.IO.EndOfStreamException",
   "Message":"Attempted to read past the end of the stream.",
   "Data":null,
   "InnerException":null,
   "HelpURL":null,
   "StackTraceString":null,
   "RemoteStackTraceString":null,
   "RemoteStackIndex":0,
   "ExceptionMethod":null,
   "HResult":-2147024858,
   "Source":null,
   "WatsonBuckets":null},
"StackTrace":"
at Microsoft.AspNetCore.Server.IIS.Core.IO.AsyncIOOperation.GetResult(Int16 token)\r\n
at Microsoft.AspNetCore.Server.IIS.Core.IISHttpContext.ReadBody()\r\n
at System.IO.Pipelines.PipeCompletion.ThrowLatchedException()\r\n
at System.IO.Pipelines.Pipe.GetReadResult(ReadResult& result)\r\n
at System.IO.Pipelines.Pipe.GetReadAsyncResult()\r\n
at System.IO.Pipelines.Pipe.DefaultPipeReader.GetResult(Int16 token)\r\n
at Microsoft.AspNetCore.Server.IIS.Core.IISHttpContext.ReadAsync(Memory`1 memory, CancellationToken cancellationToken)\r\n
at Microsoft.AspNetCore.Server.IIS.Core.HttpRequestStream.ReadAsyncInternal(Memory`1 buffer, CancellationToken cancellationToken)\r\n
at Microsoft.AspNetCore.WebUtilities.FileBufferingReadStream.ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)\r\n
at Microsoft.AspNetCore.WebUtilities.StreamHelperExtensions.DrainAsync(Stream stream, ArrayPool`1 bytePool, Nullable`1 limit, CancellationToken cancellationToken)\r\n
at Microsoft.AspNetCore.Mvc.Formatters.JsonInputFormatter.ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)\r\n
at Microsoft.AspNetCore.Mvc.ModelBinding.Binders.BodyModelBinder.BindModelAsync(ModelBindingContext bindingContext)\r\n
at Microsoft.AspNetCore.Mvc.ModelBinding.ParameterBinder.BindModelAsync(ActionContext actionContext, IModelBinder modelBinder, IValueProvider valueProvider, ParameterDescriptor parameter, ModelMetadata metadata, Object value)\r\n
at Microsoft.AspNetCore.Mvc.Internal.ControllerBinderDelegateProvider.<>c__DisplayClass0_0.<<CreateBinderDelegate>g__Bind|0>d.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()\r\n   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()\r\n
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)\r\n
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)\r\n
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()\r\n
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()\r\n
at Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)\r\n
at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext)\r\n
at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)\r\n
at Microsoft.AspNetCore.Server.IIS.Core.IISHttpContextOfT`1.ProcessRequestAsync()","HelpLink":null,"Source":"Microsoft.AspNetCore.Server.IIS","HResult":-2146232800

P.S. I have tried to Wait() _client's result to no avail.

A: I googled more accurate and found an issue. This is known problem and already fixed, but not in a current release. I suppose anyone who face such a problem need to build proper dlls mentioned in the issue discuss.


text:
Q: NoClassDefFoundError when using a Maven project in an Android app Everything of a Maven projected imported to Eclipse appears to be fine. This Maven project has been added to an Android app's build path. The app can be built without any problem.  However, whenever a class of the Maven project is instantiated, java.lang.NoClassDefFoundError occurs. For testing, here is a simple class:
package com.my.maven;
public class Foo {

    public String sFoo;
    public Foo ()
    {
        sFoo = "Foo";
    }
}

Whenever the app reaches the following statement:
Foo foo = new Foo();

The following error occurs:
java.lang.NoClassDefFoundError: com.my.maven.Foo

There are a lot of posts about NoClassDefFoundError, and I have spent a lot of time reading and trying the solutions, but none has worked.
Any tip will be greatly appreciated.


text:
Q: How do I assign a gender randomly to turtle breeds in NetLogo? For an assignment in one of my classes we need to model disease spread and also have the turtles, whether sick or healthy, reproduce when a male and a female end up on the same patch, and it's also based on a slider with probability of reproduction. We're supposed to have the gender assigned randomly at birth so that the reproduction works properly. Any idea how to do this?
This is my code so far:
to setup
  clear-all
  ifelse netlogo-web? [set max-turtles 300] [set max-turtles 300]
  create-healthy-cows Population-Size [ set shape "cow"
     set color lime
     set infected? false
     set disease? false
     ask n-of (random Population-Size) turtles [set gender-male? true]
     set size 3
     setxy random-xcor random-ycor
     set age random 200
     set label-color black ]
end

and also:
to check-reproduction
 ask turtles [if gender-male? = false [
    ask turtles [if any? turtles-here with [gender-male? = true]
      [reproduce-cows] ]]]
end

to reproduce-cows
  ask turtles [ if max-turtles < 300 [
  ask turtles [if age >= 50 [if (random-float 100 < Reproduction-Rate)
      [hatch 1
        [set color blue] ]]]]]
end

Also I have gender-male? set as a turtles-own.

A: Have a look at one-of and see if you can come up with a solution. It's important to learn what you're doing and why, and not just ask for the answer, especially when its for a class assignment.
I've never seen or heard of NetLogo and it took me less than 5 minutes to come up with a solution and then find a second, better one.. Especially if this is an assignment you should be googling and researching instead of asking to be spoonfed!


text:
Q: python math.log(1/2) domain error I have a weird problem with python's math library's log function
>> math.log(1/2)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
ValueError: math domain error

>> math.log(0.5)
-0.6931471805599453

Why is this happening?
My python version is 2.7.9

A: 1/2 == 0 in python 2 and log(0) is -Inf, try:
math.log(1./2)


text:
Q: Counter sequential of specific values in R I have a column like that :
a = c(3, 1, 2, 3, 3, 3, 1, 3, 2, 3, 3, 1, 3, 2, 1, 3, 1)

I want to have a column that counts 1 and 2 sequentially to make a column like this:
   a b
1  3 0
2  1 1
3  2 2
4  3 2
5  3 2
6  3 2
7  1 3
8  3 3
9  2 4
10 3 4
11 3 4
12 1 5
13 3 5
14 2 6
15 1 7
16 3 7

A: We can use cumsum on a logical vector
df1$b <- cumsum(df1$a %in% c(1, 2))

data
df1 <- data.frame(a)


text:
Q: Replace a element (word) in a list with an element (word) from a different list I keep getting this error message for my code and I don't understand why.
error:
Please provide a message: darn it boy
Traceback (most recent call last):
  File "bleep.py", line 40, in <module>
    main()
  File "bleep.py", line 26, in main
    user_list_lower[item] = beep[0]
TypeError: list indices must be integers or slices, not str

code:
#x.strip() for x in
import sys

def main():

    if len(sys.argv) < 2:
        sys.exit("Must enter text. status code 1")

    with open(sys.argv[1], 'r') as f:
        content = f.read()

    content_list = content.split("\n")

    user_input = input("Please provide a message: ")

    user_list = user_input.split()

    while '' in content_list:
        content_list.remove('')

    user_list_lower = [x.lower() for x in user_list]

    for item in user_list_lower:
        if item in content_list:
            beep = [len(item) * '*']
            user_list_lower[item] = beep[0]
            print (user_list_lower)
            print(beep)
        else:
            break

    print(content_list)
    print(user_list_lower)

    return content

if __name__== "__main__":
    main()

As user input I use: Darn it boy. It does not change darn it to **** as it should.
In the command line argument I give a text file that contains few swear word, of which 'darn' is one. My code works but it just doesn't change the word darn to '****'

A: In the loop, you are trying to use item to index user_list_lower, but item is the list element, not its index. Try using enumerate:
for idx, item in enumerate(user_list_lower):
    if item in content_list:
        beep = [len(item) * '*']
        user_list_lower[idx] = beep[0]
        print (user_list_lower)
        print(beep)
    else:
        break

In addition to that, consider making content_list into a set, which will make checking if item in content_list much faster.


text:
Q: Which is the best way of parsing CSV-data in a logic app without using a custom connector? I have an SFTP trigger in a logic app which fires when a file is added to a certain file area. It is a CSV-formatted file and I want the rows to be parsed and coverted into json. Which is the best way to convert CSV-data into json without using any custom connectors?
I cannot find any built-in connectors doing this job. And as far as I know there are no logic apps functions doing the job either.

A: Right now, there is no connector/action in logic app that can provide the out of box solution for your requirement. You need to loop in through the array and perform the calculation as per your requirement but I will not suggest you leverage the loop, variables action as it may take time and cost you more.
The alternative would be leveraging the inline code (JavaScript code) to do the calculation as per your requirement. Please note that you will need Integration Account to run your inline code.
Please refer to javascript code and modified if needed according to your needs. I have used '_' for differentiating the nested objects. For more details you can refer to previous discussion here.
For complex calculation you can offload this functionality to azure function and write your code as per the supported languages and call azure function from logic app.

A: 1.Created logic app as shown below:

2 .Created container in storage account and uploaded a CSV file in container.

3.Next using compose action to split the contents of the CSV file on every new line into an array.
a. Here is the expression used in SplitLines compose action:
split(body('Get_blob_content_(V2)'),decodeUriComponent('%0D%0A'))

b. Follow the below MS Doc to write expressions:
4. Removing last(empty) line from previous output using another compose action as shown below ,
take(outputs('SplitLines'),add(length(outputs('SplitLines')),-1))

5.Separating filed names using compose action
split(first(outputs('SplitLines')), ',')

*Forming json as shown below using Select action,

**From**: **`skip(outputs('RemoveLastLine'), 1)`**
**Map:**
**`outputs('SplitFieldName')[0]`** **`split(item(), ',')?[0]`**
**`outputs('SplitFieldName')[1]`** **`split(item(), ',')?[1]`**

*Tested logic app and it is running successfully.

*Content of CSV file is as shown below:

*Csv data is formatted as json:

Reference:Use data operations in Power Automate (contains video) — Power Automate | Microsoft Docs
Credit:  @Iason Koulas


text:
Q: Is there a "collection-type" equivalent annotation in Hibernate? In Hibernate you can define a custom collection type by setting the "collection-type" attribute in hibernate xml mapping file.
I was wondering if there is an annotation equivalent.
PS: I tried using @Type but hibernate complains:
"Illegal attempt to map a non collection as a @OneToMany, @ManyToMany" ...

So I assume @Type is just for regular properties.
Thanks!

A: When this question was made there was no such an annotation. Since HHH-4417 is fixed in version 4.1.1 there is org.hibernate.annotations.CollectionType. Though I don't know does it work with mentioned EventList collection.


text:
Q: Splitting words in different lines to a list in Python I have a text file which has text as :
Hello All,

Hope you are enjoying learning Python
We have tried to cover every point in detail to avoid confusion
Happy Reading

I want to separate each word to a list in the following format,
['Hello','All,','Hope','you','are','enjoying','learning','Python','We','have','tried','to','cover','every','point','in','detail','to','avoid','confusion','Happy','Reading.
I have tried the below code which is working , but the only problem is the output is coming into double square brackets and in a new line as shown below
words = [open('example.txt').read().split()]
words

[['Hello',
'All,',
'Hope',
'you',
'are',
'enjoying',
'learning',
'Python',
'We',
'have',
'tried',
'to',
'cover',
'every',
'point',
'in',
'detail',
'to',
'avoid',
'confusion',
'Happy',
'Reading']]
I am new to python and learning . It would be of great help if someone can help me out. I want the output in single square bracket and in continuation.

A: words = open('example.txt').read().split()
print(words)

just remove the bracket.
or if you have to use the old code, you could use words[0].


text:
Q: symfony2 sql query to queryBuilder or createQuery How can I write my SQL query in Symfony2's query builder?
(
 SELECT t2.`year_defence`, 'advisor_id' AS col, t2.advisor_id AS val, COUNT(*) AS total
 FROM projects t2
 GROUP BY t2.`year_defence`, t2.advisor_id
)
UNION
(
 SELECT t2.`year_defence`, 'type_id' AS col, t2.type_id AS val, COUNT(*) AS total
 FROM projects t2
 GROUP BY t2.`year_defence`, t2.type_id
)
UNION
(
 SELECT t2.`year_defence`, 'technology_id' AS col, t2.technology_id AS val, COUNT(*) AS total
 FROM projects t2
 GROUP BY t2.`year_defence`, t2.technology_id
)
ORDER BY 1 , 2 , 3;

Doesn't work any possibilities which I've tried.

A: You mean something like that : http://doctrine-orm.readthedocs.io/projects/doctrine-orm/en/latest/reference/native-sql.html ?

A: You can try using:
$statement = $this->entityManager->getConnection()->executeQuery($sql);
$result    = $statement->fetchAll();

if you have just a static query.
Or if you have user inputs to validate use:
$connection = $this->entityManager->getConnection();
$statement = $connection->prepare("SELECT myvalues FROM mytable WHERE id = :id");
$statement->bindValue('id', 1);
$statement->execute();
$results = $statement->fetchAll();


text:
Q: Vending machine program java In this vending machine code of mine, if I input excess funds it doesn't give me the change back. What am I missing here?
public static void main(String[] args) {
    int Food = runMenu();
    int Price = retrievePrice(Food);
    int change = moneyInserted(Price);
}

public static int runMenu(){
    Scanner keyboard = new Scanner(System.in);
    int choice = 0 ;
    System.out.println("\n\nPlease enter your selection:"
                + "\n1: Snickers \t 125"
                + "\n2: Reeses Cup \t 130"
                + "\n3: Doritoes \t 150"
                + "\n4: Pepsi \t 185"
                + "\n5: Exit ");
    choice = keyboard.nextInt();
    return choice;
}

public static int retrievePrice(int menuChoice){
    if (menuChoice == 1)
        return 125;
    if (menuChoice == 2)
        return 130;
    if (menuChoice == 3)
        return 150;
    if (menuChoice == 4)
        return 185;
    else return 0;
}

public static int moneyInserted(int Price){
    Scanner keyboard = new Scanner(System.in);
    int money = 0;
    System.out.println("Your item costs: " + Price + " Please enter the amount of money:");
    money = keyboard.nextInt();
    while (money < Price){
        System.out.println("Please insert sufficient funds");
        money = money + keyboard.nextInt();
    }
    return money - Price ;
}

public static void changeOut(int change){
    int quarters = 0;
    int dimes = 0;
    int nickels = 0;
    while (change >= 25){
        quarters = quarters + 1;
        change = change - 25;
    }
    while (change >= 10){
        nickels = dimes + 1;
        change = change - 10;
        while (change >= 5){
            nickels = nickels + 1;
            change = change - 5;
        }
    }
}

A: Your code does return the change, you are just not using it.
Modify your code like this:

*

*After you calculate the change, pass it to your changeOut() method which is doing the change calculation in your code. To do that, add this line to the end of the main() method:
changeOut(change);

2.There is slight logical mistake in your changeOut() method. Modify it like this:
public static void changeOut(int change){
    int quarters = 0;
    int dimes = 0;
    int nickels = 0;
    while (change >= 25){
        quarters = quarters + 1;
        change = change - 25;
    }
    while (change >= 10){
        dimes = dimes + 1;
        change = change - 10;
    }
    while (change >= 5){
        nickels = nickels + 1;
        change = change - 5;
    }

    // to see the change, print it to the console perhaps
    System.out.printf("\nHere's your change:\n%d quarters, %d dimes, %d nickels and %d pennies!",
        quarters, dimes, nickels, change);
}

A: private static int totalNotes = 0;
private static int amount = 0;

private static void printAmount(int maxAmt) {
    amount = amount - maxAmt;
    totalNotes++;
    System.out.print(maxAmt + "-");
}

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter Amount");
    amount = scanner.nextInt();
    int maxAmt = 0;

    while (amount != 0) {
        if (amount >= 2000) {
            maxAmt = 2000;
        } else if (amount >= 500) {
            maxAmt = 500;
        } else if (amount >= 200) {
            maxAmt = 200;
        } else if (amount >= 100) {
            maxAmt = 100;
        } else if (amount >= 50) {
            maxAmt = 50;
        } else if (amount >= 20) {
            maxAmt = 20;
        }
        // as same you can do this for
        /*10, 5, 2, 1*/
        printAmount(maxAmt);
    }
    System.out.println("\nTotal notes : " + totalNotes);
}


text:
Q: Potential barrier, vertically shifted I'm attempting to solve the 1D Schrodinger Equation, approaching a potential barrier defined as follows:
$$V(x) = \begin{cases}-V_0&\quad\text{for}\quad x<0
\\0&\quad\text{for}\quad x>0\end{cases}$$
where the inbound particle has energy $-V_0 < E < 0$ (Approaching from the left).
I've started the solution, as I would normally, for a barrier defined as:
$$V(x) = \begin{cases}0&\quad\text{for}\quad x<0
\\V_0&\quad\text{for}\quad x>0\end{cases}$$
But I've got a feeling that I may be wrong- does the vertical shift of the barrier (and the energy of the incoming particle) actually change anything?
Do I instead need to solve:
$$(\frac{-\hbar^2}{2m} \frac{d^2}{dx^2} -V_0)\psi=E\psi$$
for the region $x<0$?

A: Proceed as normal. All that matters is the magnitude of the difference in energy, not the absolute energy. You are free to set 'zero' wherever you like, just as you do for gravitational potential energy when solving mechanics problems.
To clarify something, the inbound particle has at this point unknown energy. You must solve the Schrodinger Equation to determine the energy. The potential is $-V_0$.
Solve the Schrodinger equation as you have written it at the bottom of your question. You will arrive at:
$\frac{d^2}{dx^2}\psi=-\frac{2m}{\hbar^2}(E+V_0)\psi$,
and your solutions are still oscillatory as the would be in the $V_0>0$ case (as indicated by the minus sign on the right hand side). The only difference is that $E$ is now the same sign as $V_0$, where normally $E$ would have the opposite sign. This makes sense, because we are interested in energy differences, we've just happened to define our potential energy to be negative,
$\Delta E = E - (-V_0)=E+V_0$.

A: You get a different energy $E$ (as explained by aRockStr). That means that the wave functions will be the same except that when you look at the time dependence, one of them will have an extra phase $e^{-iV_0t}$. This phase does not affect the probability density $|\psi|^2$ and is in principle not measurable (in the absence of gravity).


text:
Q: How the XML transformation occurs While transforming the xml using xslt I get result as justin can some body explain the statement  marked as bold below ??
xsl:value-of select="//*[price='8.20']/@supplier"
<?xml version="1.0" encoding="ISO-8859-1"?>

<catalog>
    <cd>
        <title>Empire Burlesque</title>
        <artist>Bob Dylan</artist>
        <country>USA</country>
        <company>Columbia</company>
        <price>10.90</price>
        <year>1985</year>
    </cd>
        <cd supplier="justin">
        <title>Unchain my heart</title>
        <artist>Joe Cocker</artist>
        <country>USA</country>
        <company>EMI</company>
        <price>8.20</price>
        <year>1987</year>
    </cd>
</catalog>

xslt :
<?xml version="1.0" encoding="ISO-8859-1"?>

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">

My Supplier

    <xsl:value-of select="//*[price='8.20']/@supplier"/

</xsl:template>
</xsl:stylesheet>

A: Generally:
// - Traverse the whole document

//* - Any element in the document

//*[price = '8.20'] - Any element in the document that has a <price> child element
                      with the value 8.20

//*[price = '8.20']/@supplier - The @supplier attribute of any element in the document
                                that has a <price> child element with the value 8.20

Since there is only one node in the document that matches those criteria, and it has the value "justin", that is why the output is "justin".

A: * : Any element
// : at any hierarchy (the other method is to specify specific XPath
*[price='8.20'] : Any element having child element price = '8.20'
//*[price='8.20'] : Any element at any hierarchy having child element price = '8.20'
@supplier : An attribute of name supplier
//*/@supplier : attribute of name supplier under any element at any hierarchy.
//*[price='8.20']/@supplier : attribute of name supplier under any element at any hierarchy having child element price = '8.20' ..


text:
Q: sqlplus startup - failure in processing system parameters I am trying to do the startup command
This is what I have done:
set oracle_sid=ORCL
sqlplus /nolog
SQL> conn /as sysdba
startup

It shows this error message:

failure in processing system parameters
  could not open parameter file "C:\Program\11.2.0\DBhome_1\Database\initorcl.ora"

I checked and found out that "initoracl.ora" doesn't exist inside this path:
C:\Program\11.2.0\DBhome_1\Database

I found a init.ora file in:
C:\Program\11.2.0\dbhome_1\dbs

I tried doing this command:
startup pfile="C:\Program\11.2.0\dbhome_1\dbs\init.ora"

It shows this error:

invalid value given for the diagnostic_dest init.ora parameter
  the specified ADR Base Directory does not existed [C:\program\11.2.0\dbhome_1\database\]
  specific directory does not exist
  additional error information
   the filename, directory name, or volume syntax is incorrect.

What should I do?

A: You can manually create the init.ora file. Only two parameters are required - db_name and db_block_size.
Then run:
startup pfile='c:\program\11.2.0\dbhome_1\dbs\init.ora'

If you have a valid spfile then run:
create pfile from spfile

You should be able to startup your database.

A: Set the ORACLE_SID  and ORACLE_HOME  variables properly.  They must be in upper case letters.
Second, share the content of directory. ORACLE_HOME/dbs

A: There is 2 way to solve the problem.
One way is that,
there might be another *.ora file (e.g spfileyourdbname.ora).
If there is, just do the same thing as you did:
    SQL> startup pfile = 'C:\Program\11.2.0\dbhome_1\dbs\spfileyourdbname.ora'

Or
Another way is,
just copy the below codes, change the relevant directories and parameters, and  save in the required directory (e.g $ORACLE_HOME/dbs/) as 'spfileyourdbname.ora'. Then just do the same thing:
    SQL> startup pfile = 'C:\Program\11.2.0\dbhome_1\dbs\spfileyourdbname.ora'

'mydb' is the name of your database [SID].
Codes to copy:
    mydb.__data_transfer_cache_size=0
    mydb.__db_cache_size=255852544
    mydb.__java_pool_size=12582912
    mydb.__large_pool_size=8388608
    mydb.__oracle_base='/home/yeyintkoko/app/oracle'#ORACLE_BASE set from environment
    mydb.__pga_aggregate_target=180355072
    mydb.__sga_target=536870912
    mydb.__shared_io_pool_size=20971520
    mydb.__shared_pool_size=226492416
    mydb.__streams_pool_size=0
    *.audit_file_dest='/home/yeyintkoko/app/oracle/admin/mydb/adump'
    *.audit_trail='db'
    *.compatible='12.1.0.0.0'
    *.control_files='/home/yeyintkoko/app/oracle/oradata/mydb/control01.ctl','/home/yeyintkoko/app/oracle/fast_recovery_area/mydb/control02.ctl'
    *.db_block_size=8192
    *.db_domain=''
    *.db_name='mydb'
    *.db_recovery_file_dest='/home/yeyintkoko/app/oracle/fast_recovery_area'
    *.db_recovery_file_dest_size=4800m
    *.diagnostic_dest='/home/yeyintkoko/app/oracle'
    *.dispatchers='(PROTOCOL=TCP) (SERVICE=mydbXDB)'
    *.enable_pluggable_database=true
    *.log_archive_format='%t_%s_%r.dbf'
    *.open_cursors=300
    *.pga_aggregate_target=170m
    *.processes=300
    *.remote_login_passwordfile='EXCLUSIVE'
    *.sga_target=510m
    *.undo_tablespace='UNDOTBS1'


text:
Q: preventing parleyjs multiple steps to continue if a condition is not met I'm using parsleyjs to validate a form and I'm using the "multiple steps" script found at: http://parsleyjs.org/doc/examples/multisteps.html.
All works great on its own, but I have a set of fields (datetimepicker) that I reset if the end date is less then the start date.
What it does it is simply shows an alert and clears the field when the user clicks "Next".
I thought that with clearing the fields, since they are required the form would not proceed, but it continues to the next page. If I go back and then next again, then it prevents as expected. It's as if the click beats the textbox clearing.
Here is my example in step 2 if you add a start date less then the end date
https://www.blinn.edu/expansion/facilities-listing/form-2-a.HTML
and the code:

 // raul - 3-8-2019 - created a javascript to compare dates and pass them to the HTML file. this method had to be done this way becasue the Velocity file was converting the > sign into HTML entities

 //var startDate = "03/13/2019 9:39 AM"; //$(".datetimepicker1 input").val();
 var startDate = $(".datetimepicker1 input").val();

    var start_date = new Date(startDate);

 //var endDate = "03/13/2019 9:40 AM"; //$(".datetimepicker2 input").val();
 var endDate = $(".datetimepicker2 input").val();

 var end_date = new Date(endDate);

 //sample1 Fri Mar 08 2019 09:48:16 GMT-0600 (Central Standard Time)
 //sample2 Wed Mar 13 2019 09:40:00 GMT-0500 (Central Daylight Time)

   return compDate();

       function compDate() {

            if (end_date >= start_date) {

              //$('.form-control, .submit').attr('disabled', 'disabled'); //Disable
               //alert(end_date + " is greater than " + start_date);

             }
             else if (end_date < start_date){

              //$('.form-control, .submit').removeAttr('disabled'); //enable
                    alert(end_date + " is less than " + start_date);
                    $(".datetimepicker1 input").val(""); // reset the datetimepicker
                    $(".datetimepicker2 input").val(""); // reset the datetimepicker
                    e.preventDefault();
                    return false;

             }

             else {

                    $('.form-control, .submit').removeAttr('disabled'); //enable
                    //alert("no condition met");
             }

    }
// raul - 3-8-2019 - created a javascript to compare dates and pass them to the HTML file. this method had to be done this way becasue the Velocity file was converting the > sign into HTML entities

A: UPDATE:
I had to put all of that code in a function before the "multiple step" script and then call it before the previous/next script took place. Not the best solution, but it works for now. Still hope to find a more elegant soulution

$('.form-navigation .previous').click(function() {
/////////////added function here to call it before the "previous" occurred
    navigateTo(curIndex() - 1);
  });

  $('.form-navigation .next').click(function() {
/////////////added function here to call it before the "next" occurred

    $('.demo-form').parsley().whenValidate({
      group: 'block-' + curIndex()
    }).done(function() {
      navigateTo(curIndex() + 1);
    });
  });


text:
Q: How to conditionally show a WebControl? I'm quiet new to Sharepoint and ASP.NET and by far not an coding expert. I actually have a quiet simple question
I'm building a custom publishing site-layout with several WebControls (RichImageField,RichHtmlField,SummaryLinkFieldControl,Userfield ...). Each WebControl is wrapped in a
, some of them get extra markup like a
 (Title) or  (some description).
How do I output some code based on the condition of a WebControl (= field has Content or field has no content).
For Example: I want to output the following snippet, only if "TestField" has content.

Test Field

    <PublishingWebControls:SummaryLinkFieldControl runat="server" FieldName="TestField" />

Otherwise do not output anything. (I don't want to hide it via JS or CSS)
In PHP I simply can do:
<?php if (isset($foo)) {
    echo $foo;
} ?>

or
<?php if !empty($foo)) {
    echo $foo;
} ?>

Is there something like this in ASP?
Maybe I'm totally wrong and has to change the output of an WebControl itself somewhere else. Thanks for any advice.

A: I suggest that you create a custom WebControl of your own which you wrap around each of the controls in the Page Layout that should be hidden if empty.
You could have a property on your custom control that will be containing the ID of the control it should hide if the control is empty.
Example:
<MyControls:HideWhenEmpty runat="server" ID="HideWhenEmpty1" ControlToHideIfEmpty="SummaryLinkFieldControl1">

Test Field

        <PublishingWebControls:SummaryLinkFieldControl runat="server" ID="SummaryLinkFieldControl1" FieldName="TestField" />

</MyControls:HideWhenEmpty>

In your custom control's OnPreRender event you check if the control with the ID of the ControlToHideIfEmpty property is empty. You return false; (<- this will stop the rendering of HideWhenEmpty1 and everything within it) if it is empty and return true; if it is not.


text:
Q: Why file updates do not appear or impact in spring boot? It runs in Docker WSL I have a simple Spring Boot project.Create a controller and return a string.
@GetMapping("/test")
    public String test(){
        return "test done change";
    }

I used Docker file and docker-compose.yml file.
My Docker File:
FROM maven:3.8.6-amazoncorretto-11
COPY target/*.jar docker-spring.jar
CMD ["java","-jar","/docker-spring.jar"]

docker-compose.yml file:
version: '3'
services:
    app:
        container_name: docker-spring
        build: .
        ports:
            - "8080:8080"
        networks:
            - spring-cloud-network
networks:
    spring-cloud-network:
        driver: bridge

I used Windows, so I used docker in WLS2. I run mvnw pacakage and generate a .jar file  local environment. Then I move the whole project into my docker folder and run docker-composer up -d --build. Then it runs and builds containers. But when I changed the return string to controller , it was not updated. I also used another Dockerfile:
# FROM maven:3.8.6-amazoncorretto-11

# COPY .mvn .mvn
# COPY mvnw .
# COPY pom.xml .
# COPY src src

# RUN ./mvnw install

# RUN ./mvnw package
# COPY target/*.jar docker-spring.jar
# ENTRYPOINT ["java", "-jar", "docker-spring.jar"]

But show error.
File Structure:
Thank you.


text:
Q: How to sum values in VueJs Can someone help me in sum values in VueJs
im try to get a sum of products
All my products display in select options tag by v-for
Im add event on click and after this im get price value in method
If someone have info about solved this problem im so gratefull
this is my code in Vue component

  Продукты

    <multiselect selectLabel="Выбрать" deselectLabel="Удалить" selectedLabel="Выбрано" @input="setSelected"
      :taggable="true" v-model="formData.products" :options="this.$store.state.order.products" :multiple="true"
      :hideSelected="true" :custom-label="titleWithPrice" :close-on-select="false" :clear-on-select="false"
      :preserve-search="true" placeholder="Выберите продукты" label="title" track-by="id" :preselect-first="true">
      <template slot="selection" slot-scope="{ values, search, isOpen }">{{ values.length }} options selected</template>
    </multiselect>

this is my code in method
setSelected(value) {
            let prices = value;
            prices.forEach((price) => {
                this.price = price.price
            })
        }

this is my code in computed
 totalItem: function(){
            let sum = 0;
            this.items.forEach(function(item) {
                sum += (parseFloat(item.price));
            });

            return sum;
        }

A: If the formData.products is correctly setting the values selected, then you can directly get the sum of values from the computed section.
computed:{
  sum : function(){
    let products = this.formData.products;
    return products.reduce((a,b)=>{
      return parseFloat(a.price) + parseFloat(b.price);
    })
  }
}


text:
Q: Azure Repository: unlimited merge conflicts in pull request It seems like I am facing a bug within my Azure Devops repository.
Within my pull request I have merge conflicts.
Every time I solve these and resolve the matching comment, a new merge conflict appears.
Here you can see I resolved all the issues:

Next when I return to the overview page a new merge conflict is shown:

When I solve this and go back to the overview page a new merge conflict is shown.
This keeps on happening.

A: It is not a bug in Azure DevOps but Way of Working.
Every conflict when manually resolved from the AzureDevops Conflicts tab, will have a comment created. Before completing the PR approval, the peer reviewer needs to resolve this comment related to the conflict resolution.


text:
Q: ADF Skin.css -customizing issues I am working on ADF skin.css to create a customized web page. Lot of customizations that I do on the skin.css does not seem to reflect on the pages appropriately. For example, when i try to apply a gradient effect to a Panel Stretch Layout, it does not appear. Can anyone help with a good guide on how to go about this?
Thanks,
Geetha

A: Even though I am not an HTML expert, what I've found most effective is to look at generated HTML using Firefox with Firebug.
To shrink HTML size, ADF compresses the names stylesheet classes e.g.:
class="x10" and class="x2e"

But if you remove this compression, you will start to see in html something like this:
class="af_inputComboboxListOfValues_dropdown-table"

And this can be controlled through skinning like this:
af|inputComboboxListOfValues::dropdown-table {
    height:350px;
}

To disable CSS style compression, you need to place this cod snippet on your web.xml:
<context-param>
   <param-name>org.apache.myfaces.trinidad.DISABLE_CONTENT_COMPRESSION</param-name>
   <param-value>true</param-value>
</context-param>

A: You might want to start by working with the skin editor - here is a quick intro to what it can do - https://blogs.oracle.com/shay/entry/adf_faces_skin_editor_how


text:
Q: How to convert .ino file into .bin file with "sketch + WiFi settings" from arduinoIDE to upload in S3 ESP8266 by "ESP8266 download tool"? I want to flash S3 ESP8266 module by "ESP8266 download tool". In arduinoIDE, when my setUp is like, tools->Erase Flash: only sketch. I can easily convert the blink.ino code into .bin and can flash it to my S3 ESP8266 module via "ESP8266 download tool", and can really see it's BuiltIn led blinking.
But, when my setUp is like, tools->Erase Flash: sketch+WiFi settings. I can convert the blink.ino into .bin and can flash it to my S3 ESP8266 module via "ESP8266 download tool". But unfortunately it doesn't blink. My .ino code is simple.
void setup() {
  pinMode(4, OUTPUT);
}

void loop() {
  digitalWrite(4, HIGH);
  delay(1000);
  digitalWrite(4, LOW);
  delay(1000);
}

Options selected in ArduinoIDE's Tools,
Board : NodeMCU 1.0(ESP-12E Module)
Flash Size : "4M (No SPIFFS)"
I think this issue is because of "build options" changes, but I don't know about it's solution.
Is there anyThing that I am missing out ? Please help.


text:
Q: Lighting diagrams language and notation I know, the use case might be specific but more and more stuff in all industry sectors is digitalized—and so is the communication between different departments which sometimes talk in very different languages. I searched the internet, but I wasn't able to find a clear answer (either I didn't find the right search phrases or the internet itself just doesn't know).
Here's my scenario: I'm working with several departments which work with diagrams (for example a lighting setup). This diagram solves different purposes:

*

*which devices are used?

*where are they placed?

*where are they pointing?

*how are they configured (e.g. exposure)?

They tend to export their finalized diagram as either an image or a PDF— which is fine if you want to print it out but considerably less helpful if another department (mine) has to work with the raw information. That's where I wondered if there's some kind of industry standard (SVG, XML, JSON, etc.) which is both supported by the programs these departments used and can be interpreted by some sort of programming language. Do you know anything like that?
Thanks in advance!


text:
Q: Question on some coverings of the euclidean space Let $L$ be a maximal integral lattice in the euclidean $(\mathbf R^{8m},q)$ (thus the associated bilinear form $b(u,v)=q(u+v)-q(u)-q(v)$, once restricted to $L$, takes values in $2\mathbf Z$ and has discriminant $1$).
One may define the following :
$$X(L):=\bigcup_{s>0}\bigcup_{q(x)\equiv 1\text{ mod } s} B(\frac{x}{s},\frac{1}{s}) $$
($s$ runs over the natural number, and $B(x,\delta)$ is the open ball of radius $\delta$ centered at $x$).
Question 1 : Is $X(L)$ connected ?
Wouldn't there be the restriction on $q(x)$, this would be true, and in fact, $X(L)$ would be the whole $\mathbf R^{8m}$ (by Minkowski's convex body theorem).
I have checked that

*

*it is the case for $m=1,2,3$, but have no clue for the general case,

*the answer does not depend of the $L$ you choose (as long as it is maximal integral),

*the centers of the balls form a dense subset of $\mathbf R^{8m}$.
In fact, the first two of these remarks follow from the equivalence of the question with the following
Question 2 : Is the Coxeter graph for the (unique up to isomophism) maximal integral lattice (often denoted by $\text{II}_{1,8m+1}$) on the Lorentzian $\mathbf R^{8m+2}$ connected ?


text:
Q: Terminate a Python multiprocessing program once a one of its workers meets a certain condition I am writing a Python program using its multiprocessing module. The program calls a number of worker functions, each yielding a random number. I need to terminate the program once one of the workers has produced a number larger than 0.7.
Below is my program where the "how to do this" part is not yet filled out. Any idea? Thanks.
import time
import numpy as np
import multiprocessing as mp
import time
import sys

def f(i):
    np.random.seed(int(time.time()+i))

    time.sleep(3)
    res=np.random.rand()
    print "From i = ",i, "       res = ",res
    if res>0.7:
        print "find it"
        # terminate  ???? Question: How to do this???

if __name__=='__main__':
    num_workers=mp.cpu_count()
    pool=mp.Pool(num_workers)
    for i in range(num_workers):
        p=mp.Process(target=f,args=(i,))
        p.start()

A: There is a much cleaner and pythonic way to do what you want to do and it's achieved by using the callback functions offered by multiprocessing.Pool.
You can check this question to see an implementation example.

A: No process can stop another short of brute force os.kill()-like sledgehammers.  Don't go there.
To do this sanely, you need to rework your basic approach:  the main process and the worker processes need to communicate with each other.
I'd flesh it out, but the example so far is too bare-bones to make it useful.  For example, as written, no more than num_workers calls to rand() are ever made, so there's no reason to believe any of them must be > 0.7.
Once the worker function grows a loop, then it becomes more obvious.  For example, the worker could check to see if an mp.Event is set at the top of the loop, and just exit if it is.  The main process would set the Event when it wants the workers to stop.
And a worker could set a different mp.Event when it found a value > 0.7.  The main process would wait for that Event, then set the "time to stop" Event for workers to see, then do the usual loop .join()-ing the workers for a clean shutdown.
EDIT
Here's fleshing out a portable, clean solution, assuming the workers are going to keep going until at least one finds a value > 0.7.  Note that I removed numpy from this, because it's irrelevant to this code.  The code here should work fine under any stock Python on any platform supporting multiprocessing:
import random
from time import sleep

def worker(i, quit, foundit):
    print "%d started" % i
    while not quit.is_set():
        x = random.random()
        if x > 0.7:
            print '%d found %g' % (i, x)
            foundit.set()
            break
        sleep(0.1)
    print "%d is done" % i

if __name__ == "__main__":
    import multiprocessing as mp
    quit = mp.Event()
    foundit = mp.Event()
    for i in range(mp.cpu_count()):
        p = mp.Process(target=worker, args=(i, quit, foundit))
        p.start()
    foundit.wait()
    quit.set()

And some sample output:
0 started
1 started
2 started
2 found 0.922803
2 is done
3 started
3 is done
4 started
4 is done
5 started
5 is done
6 started
6 is done
7 started
7 is done
0 is done
1 is done

Everything shuts down cleanly:  no tracebacks, no abnormal terminations, no zombie processes left behind ... clean as a whistle.
KILLING IT
As @noxdafox pointed at, there's a Pool.terminate() method that does the best it can, across platforms, to kill worker processes no matter what they're doing (e.g., on Windows it calls the platform TerminateProcess()).  I don't recommend it for production code, because killing a process abruptly can leave various shared resources in inconsistent states, or let them leak.  There are various warnings about that in the multiprocessing docs, to which you should add your OS docs.
Still, it can be expedient!  Here's a full program using this approach.  Note that I bumped the cutoff to 0.95, to make this more likely to take longer than an eyeblink to run:
import random
from time import sleep

def worker(i):
    print "%d started" % i
    while True:
        x = random.random()
        print '%d found %g' % (i, x)
        if x > 0.95:
            return x # triggers callback
        sleep(0.5)

# callback running only in __main__
def quit(arg):
    print "quitting with %g" % arg
    # note: p is visible because it's global in __main__
    p.terminate()  # kill all pool workers

if __name__ == "__main__":
    import multiprocessing as mp
    ncpu = mp.cpu_count()
    p = mp.Pool(ncpu)
    for i in range(ncpu):
        p.apply_async(worker, args=(i,), callback=quit)
    p.close()
    p.join()

And some sample output:
$ python mptest.py
0 started
0 found 0.391351
1 started
1 found 0.767374
2 started
2 found 0.110969
3 started
3 found 0.611442
4 started
4 found 0.790782
5 started
5 found 0.554611
6 started
6 found 0.0483844
7 started
7 found 0.862496
0 found 0.27175
1 found 0.0398836
2 found 0.884015
3 found 0.988702
quitting with 0.988702
4 found 0.909178
5 found 0.336805
6 found 0.961192
7 found 0.912875
$ [the program ended]

A: As one of the other users mentioned, you need the processes to communicate with each other in order to get them to terminate their peers. While you can use os.kill to terminate the peer processes, it is more graceful to signal a termination.
The solution I used is a pretty simple one:
 1. find out the process ID (pid) of the main process, which spawns all the other worker processes. This connection information is available from the OS, which keeps track which child process was spawned from which parent process.
 2. when one of the worker processes reaches your end condition, it uses the parent process ID to find all the child processes of the main process (including itself), then goes through the list and signals them to end (making sure it is not signaling itself)
The code below contains the working solution.
import time
import numpy as np
import multiprocessing as mp
import time
import sys
import os
import psutil
import signal

pid_array = []

def f(i):
    np.random.seed(int(time.time()+i))

    time.sleep(3)
    res=np.random.rand()
    current_process = os.getpid()
    print "From i = ",i, "       res = ",res, " with process ID (pid) = ", current_process
    if res>0.7:
        print "find it"
        # solution: use the parent child connection between processes
        parent = psutil.Process(main_process)
        children = parent.children(recursive=True)
        for process in children:
            if not (process.pid == current_process):
                print "Process: ",current_process,  " killed process: ", process.pid
                process.send_signal(signal.SIGTERM)

if __name__=='__main__':
    num_workers=mp.cpu_count()
    pool=mp.Pool(num_workers)
    main_process = os.getpid()
    print "Main process: ", main_process
    for i in range(num_workers):
        p=mp.Process(target=f,args=(i,))
        p.start()

The output gives a clear idea of what is happening:
Main process:  30249
From i =  0        res =  0.224609517693  with process ID (pid) =  30259
From i =  1        res =  0.470935062176  with process ID (pid) =  30260
From i =  2        res =  0.493680214732  with process ID (pid) =  30261
From i =  3        res =  0.342349294134  with process ID (pid) =  30262
From i =  4        res =  0.149124648092  with process ID (pid) =  30263
From i =  5        res =  0.0134122107375  with process ID (pid) =  30264
From i =  6        res =  0.719062852901  with process ID (pid) =  30265
find it
From i =  7        res =  0.663682945388  with process ID (pid) =  30266
Process:  30265  killed process:  30259
Process:  30265  killed process:  30260
Process:  30265  killed process:  30261
Process:  30265  killed process:  30262
Process:  30265  killed process:  30263
Process:  30265  killed process:  30264
Process:  30265  killed process:  30266

A: You can terminate your Program simply by importing exit() from sys
import sys

sys.exit()


text:
Q: Deriving the Unit-Height Impulse Function from Limit of Difference of Heaviside Functions The unit-height impulse function can be defined as
$
I(x)=\begin{cases} 1,& \text{if } x = 0 \\
    0,              & \text{otherwise}
\end{cases}$
We can define the Heaviside Step Function as
$
H(x)=\begin{cases} 0,& \text{if } x < 0 \\
    1,              & \text{if } x > 0
\end{cases}$
(There are variants to this $H(x)$, such as the right-continuous Heaviside Step Function, which may possibly be more appropriate to choose for the question below.)
I am wondering, is it correct to say:
$I(x) = \lim\limits_{\Delta \to 0}(H(x- \Delta) - H(x+\Delta))$
or does
$\lim\limits_{\Delta \to 0}(H(x- \Delta) - H(x+\Delta)) = 0 \text{, for all } x$, including $x=0$?
Note, I am not talking about inside an integral, where $I(x)$ is equivalent to the function that is equal to zero for all $x$

A: The relation of $I(x) = \lim\limits_{\Delta \to 0}(H(x- \Delta) - H(x+\Delta))$ must in fact be$$I(x) = \lim\limits_{\Delta \to 0^-}(H(x- \Delta) - H(x+\Delta))$$this is because $H(-\Delta)=1+H(\Delta)=0$ for $\Delta<0$ and as long as $\Delta\to 0^-$ we have $\Delta\ne 0$.
For $x\ne 0$, we have $$(x-\Delta)(x+\Delta)=x^2-\Delta^2>0$$ for sufficiently small $|\Delta|$. So what does this lead to?


text:
Q: How to hide android status bar just for my application on Android Tabs2 fro Android version4.0.3? Can any one please tell me any way to hide status bar completely just for my application on all activities. My application only runs on android tabs with 4.0.3 Android. I actually want to remove the back, home and all the other click listeners on the status bar or just completely hide it. The requirement behind this is that if once my application starts on a tab it stays on until user switches off the device device and there should not be any exit point. I will be grateful for your humble response. I have added android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" manifest.xml.Still not able to disable the status bar. My activity class is given below
package com.plugin.myapp;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CordovaWebViewClient;
import org.apache.cordova.DroidGap;
import org.apache.cordova.CordovaChromeClient;

import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;

public class MainActivity extends DroidGap  {
     private static MainActivity instance;

    // private WebView mWebView;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.init();

        //getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
        getWindow().getDecorView().setSystemUiVisibility(View.STATUS_BAR_HIDDEN);
        super.loadUrl("file:///android_asset/www/tdc_tutorial.html");

    }
 // handler for the background updating
    Handler progressHandler = new Handler()
    {
        public void handleMessage(Message msg)
        {
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }
    };
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        // TODO Auto-generated method stub
        super.onConfigurationChanged(newConfig);

        System.out.println("onConfigurationChanged");
    }
  @Override
    public void init() {
    super.init((CordovaWebView) new WebView(this), new GWTCordovaWebViewClient(this), new CordovaChromeClient(this));
    }

   @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        //super.onBackPressed();
    }

   /* (non-Javadoc)
     * @see org.apache.cordova.DroidGap#onConfigurationChanged(android.content.res.Configuration)
     */

}

and my manifest.xml is given below
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.plugin.myapp"
    android:versionCode="1"
    android:versionName="1.0" >

     <uses-sdk
        android:minSdkVersion="15"
        android:targetSdkVersion="15" />

    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.WRITE_CONTACTS" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.BROADCAST_STICKY" />
    <uses-permission android:name="android.permission.INTERNET" />
<supports-screens
      android:largeScreens="true"
      android:normalScreens="true"
      android:smallScreens="true"
      android:xlargeScreens="true"
      android:resizeable="true"
      android:anyDensity="true"

      />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="Android Test"
        android:theme="@android:style/Theme.NoTitleBar.Fullscreen" >

        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main"
            android:screenOrientation="sensorLandscape"
            android:configChanges="orientation">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

A: Take a look at GMD HideBar for ICS.
I used it on my 4.0.3 tablet and it works very good! if you use dex2jar to get jar from apk file, I could import jar file in your buildpath and use function SystemUI.hidebar to hide or SystemUI.showbar to show :)

A: For devices without hardware key, unless you "Root" device, there's no way to completely hide the bar. You can, however, put it in "low profile" mode using setSystemUIVisiblity.

A: By default, you shouldn`t remove the statusbar, because it is a service from the Android UI. Then Google let you hide it, however if the user swipes it up, it will come back.
But, yes it is possible to do if you have root access on the device.
This code can hide and show the StatusBar by killing it`s proccess and calling it back again.
package com.example.statusbar;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;

public class MainActivity extends Activity {

    String commandToExecute;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);

        commandToExecute = "/system/xbin/su";
        executeShellCommand(commandToExecute);

        Button btHideStatusBar = (Button) findViewById(R.id.buttonHide);
        Button btShowStatusBar = (Button) findViewById(R.id.buttonShow);

        btHideStatusBar.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                commandToExecute = "/system/xbin/su -c /system/bin/service call activity 42 s16 com.android.systemui";
                executeShellCommand(commandToExecute);

            }
        });

    btShowStatusBar.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            commandToExecute = "/system/xbin/su -c /system/bin/am startservice -n com.android.systemui/.SystemUIService";
            executeShellCommand(commandToExecute);

        }
    });

    }

    private boolean executeShellCommand(String command) {
        try {

            Runtime.getRuntime().exec(command);

            return true;
        } catch (Exception e) {
            return false;

        }
    }

}


text:
Q: Javascript not accepting Date or String as parameters using Razor and MVVM I have a problem with my JavaScript method not firing or giving incorrect values.
Javascript:
function JSMethod(UserID, medalDate, medalCategory{
    //Do things.
};

HTML:
//MediaList consists of: int UserID, DateTime DateEarned, string Reason
@foreach (var medal in @Model.medalList)
{
    <a onclick="JSMethod(@medal.UserID, @medal.DateEarned.ToShortDateString(), @medal.Reason.ToString())" click here
}

The JavaScript method does not seem to take the @model.Reason as a parameter, is there a problem with passing in strings to Javascript functions?
When the date (@medal.DateEarned) is passed in it either ignores it or passes it in as ToString('DD/MM/YYYY') and it ends up dividing, for example, 12/03/2014 resulting in a passed in parameter of 0.00198...
Is there anyway of getting my JavaScript function to accept my datetime and string as parameters?
Any help is appreciated, thanks.

A: When mixing Razor and JavaScript, you have to remember the syntax for both languages: in this case, you need to use quotes in the JavaScript around your Razor-injected values:
<a onclick="JSMethod(@medal.UserID, '@medal.DateEarned.ToShortDateString()', '@medal.Reason.ToString()')" click here

Note the tick marks around the date and reason strings. If UserID is not numeric, it needs ticks as well.


text:
Q: Understanding the logic of an Excel INDEX formula which incorporates the MATCH function I'm doing an online Excel course and I'm trying to wrap my head around the internal logic of the formulas I'm being taught.  So far, so good, for the most part.  However, I'm trying to figure out the internal logic of a particular formula which incorporates both the INDEX and MATCH features, and I'm not getting anywhere.
The situation is this:  I have to write a formula to search the following array.  The formula must use INDEX and MATCH.  Here's a picture of the array

The values I have to search for are supposed to be input by a user.  So the user chooses a year from the list in column A, and then chooses either 'Impressions', 'Clicks', or 'Transactions' from the list along the top (cells B1 to D1).
For example, if the user picked 2004 and 'Clicks', the formula should return the value for C6 because that's the cell at the intersection of the row with 2004 in it, and the column which is headed 'Clicks'.
Here's the formula that I wrote for it:

In the formula, cell G2 is where the user picks any year from 2000 to 2016 using a drop-down menu.  Cell G3 is where the user picks either 'Impressions', 'Clicks', or 'Transactions' from another drop down menu.
So the above formula should be telling Excel: Look through cells A2-A18 for whatever the user has put in G2.  Then, look through cells B1-D1 for whatever the user has put in G3.  Then, once you've found those values, look for the cell where they intersect and return that value.
The problem is that the formula always returns the results one cell to the left of the cell that the user has picked.  I can't understand why that is.  I know how to fix it; I just change the last part of the formula to MATCH(G3, A1:D1, 0)) (so change B1 to A1).  The thing is, knowing how to fix it just isn't good enough for me.  I need to know why the original formula doesn't work.  It should work, as far as I can tell.  I'm asking Excel to find either 'Impressions', 'Clicks', or 'Transactions' and all those options are available in B1:D1, so I don't see why the formula only works if I type A1:D1.
If anyone could explain the underlying logic for me I'd very much appreciate it.

A: Match returns the relative location in the range as a Long.
With MATCH("Clicks", A1:D1, 0)  The relative location is the third cell in that range as a long, 3.
With MATCH("Clicks", B1:D1, 0)  The relative location is the Second cell in that range as a long, 2.
This number is passed to the INDEX range.  With the first formula it returns the 3rd column in A2:D18 which is Column C and with the second it returns the second column which is Column B.
To avoid this always make the rows or columns match between the INDEX and the MATCHES:
=INDEX(A2:D18,MATCH(G2,A2:A18,0),MATCH(G3, A1:D1, 0))

Or
=INDEX(B2:D18,MATCH(G2,A2:A18,0),MATCH(G3, B1:D1, 0))


text:
Q: concurrency in innodb i have a code like this
reserve.php
$r=mysql_query("select count(*) from ticket");
$rec=mysql_fetch_array($r);
if ($rec[0]==0)
{
insert into ticket values .....
}

i have 1 ticket only.
two users request reserve.php.
"a" user request reserve.php and available ticket is 0 . but before insert, for "b" user  available ticket is 0 yet. so two users reserve ticket.
table is Innodb.
how to prevent this? transaction , lock table or what?

A: In these situations I usually just use an UPDATE statement and check how many records were affected (mysql_affected_rows) by the update.
 UPDATE tickets SET ticket_count=ticket_count-1 WHERE ticket_id=123 AND ticket_count>0

If someone else decremented the counter first, then no update occurs and you don't give the user a ticket. Autocommit should be enabled so the update is a self-contained "transaction".
Alternatively, you can change your SELECT to be SELECT ... FOR UPDATE
http://dev.mysql.com/doc/refman/5.0/en/innodb-locking-reads.html

A: I would do it in a single transaction, without a roundtrip back to the application level - both SELECT count() .... and INSERT INTO being sent in a single command from PHP and embedded into a TRANSACTION with EXCLUSIVE LOCK


text:
Q: What is the difference between "struct *Stack stack" and "struct Stack* stack"? While writing a code when I am writing struct *Stack stack then code is not working and when I am writing it like struct Stack* stack code is working,can someone tell me the difference between these two code?

A:
While writing a code when I am writing struct *Stack stack then code is not working

This is because struct *Stack stack is not correct syntax. This would imply a pointer named Stack stack, which is not a valid name, pointing to a struct, which is not valid in c or c++, as you have to indicate what type of struct your pointer will be pointing to. The word struct is not standalone.

when I am writing it like struct Stack* stack code is working

On the other hand, the declaration :
struct Stack* stack;

implies a pointer named stack which points to a struct Stack (which you have defined somewhere).


text:
Q: Export-Import Android Studio AVD's I have been developing in Android Studio and have created a number of AVD's which suit my different app specifications. Now i am planning to do a system restore on my PC.
Is there a way to backup the AVD's and then import them on the new Android Studio installation, after i perform the system restore?
Thanks

A: The AVD's are stored in the folder:

*

*On Windows XP: C:\Documents and Settings\.android

*On Windows Vista and higher: C:\Users\.android

*On Linux / Mac: ~/.android/avd


text:
Q: How to force a cache clearing using Universal Image Loader Android? I am using UIL to load images in a listview.
When I long press an image in the listview, I show a dialog to modify that picture, replacing it with a new one using the camera.
If I take a new picture, when the dialog is dismissed my listview still shows the old image (since it is cached). If I close and restart my application when I go to my listview the new image is correctly there.
This is how I set up UIL:
// Get singletone instance of ImageLoader
    imageLoader = ImageLoader.getInstance();

    //set display options for image loader
    DisplayImageOptions displayOptions = new DisplayImageOptions.Builder()
    .cacheInMemory()
    .displayer(new FadeInBitmapDisplayer(500)) //fade in images
    .resetViewBeforeLoading()
    .build();

    //set image loader options
    ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this).defaultDisplayImageOptions(displayOptions).build();

    // Initialize ImageLoader with configuration.
    imageLoader.init(config);

If I remove .cacheInMemory() everything works though. I am just wondering if I can clear the cache when opening my dialog only. I tried to get hold of the ImageView selected and call myImageView.invalidate() when opening the dialog without success.
The images are loaded from file:
// Load and display image asynchronously
imageLoader.displayImage(file_prefix + image_path, image);

Any suggestions?
Edit: code to create  a context menu when long pressing an image, I tried to clear the cache there:
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);

    //get info about item selected
    AdapterView.AdapterContextMenuInfo info;
    try {
        // Casts the incoming data object into the type for AdapterView objects.
        info = (AdapterView.AdapterContextMenuInfo) menuInfo;
    } catch (ClassCastException e) {
        // If the menu object can't be cast, logs an error.
        Log.e("no info", "bad menuInfo", e);
        return;
    }
    Cursor cursor = (Cursor) getListAdapter().getItem(info.position);
    if (cursor == null) {
        // For some reason the requested item isn't available, do nothing
        return;
    }

    //remove selected image from cache (if it is an image)
    imageUrl = cursor.getString(cursor.getColumnIndex("image_path"));
    if (!imageUrl.equalsIgnoreCase("")) {
        MemoryCacheUtil.removeFromCache(imageUrl, imageLoader.getMemoryCache());
    }

    Log.i("imageUrl", imageUrl);

    //get defect row ID and text content to pass it to defect activity
    defect_row_id = cursor.getLong(cursor.getColumnIndex("_id"));
    defect_txt = cursor.getString(cursor.getColumnIndex("defect"));

    MenuInflater inflater = getMenuInflater();

    Log.i("cursor", DatabaseUtils.dumpCursorToString(cursor));

    //set project identifier in context menu header, mapping cursor sequence of values
    menu.setHeaderTitle(getString(R.string.select_an_option));
    inflater.inflate(R.menu.menu_defect_row, menu);

}

When a menu item (edit or delete) is selected
@Override
public boolean onContextItemSelected(MenuItem item) {
    //AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
    switch (item.getItemId()) {

    case R.id.edit:

        //open defect activity with the specified image and defect pre-loaded
        Intent editDefectIntent = new Intent(this, DefectActivity.class);

        editDefectIntent.putExtra("defect_row_id", defect_row_id);
        editDefectIntent.putExtra("imageUrl", imageUrl);

        startActivity(editDefectIntent);

        return true;
    case R.id.delete:

        askDeleteConfirm();

        return true;

    default:
        return false;
    }

}//onContextItemSelected

Edit: code to display list of images
@Override
public void onResume() {
    super.onResume();

    //open connection to db
    db = new DBAdapter(this);
    db.open();

    Log.i("DefectListActivity -> onResume", "called");

    // get all defects for this unit
    defectList = db.getAllDefectsByUnit(unit_id);
    // create an array adapter and let it to display our row
    defects = new SimpleCursorAdapter(this, R.layout.defect_row, defectList, new String[] { "defect", "image_path" }, new int[] { R.id.defect, R.id.image }, 0);

    //set custom view using ViewBinder
    SimpleCursorAdapter.ViewBinder binder = new SimpleCursorAdapter.ViewBinder() {
        @Override
        public boolean setViewValue(View view, Cursor cursor, int columnIndex) {

            int placeholder_id = getResources().getIdentifier("placeholder", "drawable", getPackageName());

            //get column name
            String name = cursor.getColumnName(columnIndex);

            //for the thumbnail column,if we have an image replace the placeholder
            if ("image_path".equals(name)) {

                ImageView image = (ImageView) view.findViewById(R.id.image);
                //Bitmap thumbnail;
                String image_path = cursor.getString(columnIndex);

                Log.i("image_path ->", image_path);

                if (!image_path.equalsIgnoreCase("")) {

                // Load and display image asynchronously
                imageLoader.displayImage(file_prefix + image_path, image);

                } else {

                    image.setImageResource(placeholder_id);

                    }

                return true;

            }

            //for the defect column, just add the text to the view
            if ("defect".equals(name)) {

                String defect_text = cursor.getString(columnIndex);

                TextView defect_holder = (TextView) view.findViewById(R.id.defect);
                defect_holder.setText(defect_text);

                return true;
            }

            return false;
        }
    };

    defects.setViewBinder(binder);

    setListAdapter(defects);

}//onResume

A: If you are caching it both in memory and disc, for example:
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
        .memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024))
        .discCache(new UnlimitedDiscCache(cacheDir))
.........

Ensure you remove it from both of them, then reload your image view.
MemoryCacheUtils.removeFromCache(url, ImageLoader.getInstance().getMemoryCache());
DiscCacheUtils.removeFromCache(url, ImageLoader.getInstance().getDiscCache());

A: This should work:
imageLoader.clearMemoryCache();

A: I think you should delete cached image in memory cache when opening dialog. Use MemoryCacheUtil for that:
MemoryCacheUtils.removeFromCache(imageUrl, imageLoader.getMemoryCache());


text:
Q: Access and SQL date comparison I have an Access 2010 front and sql2008 back. I am using a date parameter on a form and a view for the report. It doesn't give me any data. It's not understanding the access date paramter. I have tried converting the date in sql, but still no data. Here is the code I am using.
Private Sub Report_Open(Cancel As Integer)
LocationRpt
End Sub

Private Sub LocationRpt()

Dim frm As Form_frmSecRpt
Dim strSQL As String
Dim SchDt As Date
Set frm = Form_frmSecRpt
SchDt = frm.txtDate
strSQL = "Select * From vw_SecLocationWO Where ReSchDt =" & SchDt
Me.RecordSource = strSQL

End Sub

A: Access SQL expects date values to be delimited with hash marks (#), so try this instead:
strSQL = "SELECT * FROM vw_SecLocationWO WHERE ReSchDt = #" & Format(SchDt, "yyyy-mm-dd") & "#"


text:
Q: Analytic Continuation: Replacement of $t \rightarrow - i \tau$ Mathematical Justification It's commonly used in imaginary-time path integral that "analytic continuation" means replacing $t \rightarrow - i \tau$ or reparametrizing the theory in terms of imaginary time $\tau = i t$. For example, it's common practice to just replace the imaginary time $\tau \rightarrow i t$ to figure out the real time Green's function from the imaginary time Green's function.
I've been having trouble connecting this with the definition from math. My understanding here is to find the analytic continuation of an analytic function in domain $V_1$ around $z_1$: $f(z) = \sum_k a_k (z- z_1)^k$, we need to find $f_2$ defined in another domain $V_2$, which overlaps with $V_1$. And if $f_1 = f_2$ in $V_1 \bigcap V_2 $, then $f_2$ is an analytic continuation of $f_1$ on $V_2$.
How is the replacement justified from the definition in math?
P.S. There is a very similar question here but I don't think the answer was satisfying to me.
P.P.S QMechanic linked a post about Wick rotation, which is showing an integral along the real line is the same as the integral along imaginary axis. One can apply Cauchy theorem under the right conditions, but I thought "analytic continuation" by replacing arguments of $t$ is a strong statement: it's saying 1) there are no poles in the quadrants; 2) the contour integral connecting $t$ and $it$ are zero for all $t$. I suppose I could have missed some simple property about the Green's function, that might imply these two conditions?


text:
Q: C# Dictionary giving a KeyNotFoundException, not sure why I'm an amateur programmer, and this seems like a simple problem to fix, but I just can't figure out how.
Below is C# code that isn't acting like I want it to. I expect for this to return 3, yet instead throws a KeyNotFoundException. The Lists are the same, so shouldn't it be returning 3? Thanks for any help.
Dictionary<object, double> dict = new Dictionary<object, double>();
dict.Add(new List<object>() { "a", "b" }, 3);
double output = dict[new List<object>() { "a", "b" }];

A: List<T> is a reference type without a special Equals implementation. So, in your case, while both of your list instances have the same content, they are still different instances and as such are not considered equal upon key lookup.
Depending on your needs, you could use different solutions:

*

*If you always have the same amount of items in your list, you can use a Tuple:
Dictionary<Tuple<string, string>, double> dict =
    new Dictionary<Tuple<string, string>, double>();
dict.Add(Tuple.Create("a", "b"), 3);
double output = dict[Tuple.Create("a", "b")];

*If the amount of items differ, you can create your own list that compares its content.

A: Because there are two different objects/instances.

A: Both lists are separate instances, so ReferenceEquals returns false, but that is used by default. You could implement a custom IEqualityComparer<IList<object>> for the dictionary constructor:
public class ListComparer : IEqualityComparer<IList<object>>
{
    public bool Equals(IList<object> x, IList<object> y)
    {
        if (x == null || y == null) return false;
        return x.SequenceEqual(y);
    }

    public int GetHashCode(IList<object> list)
    {
        if (list == null) return int.MinValue;
        int hash = 19;
        unchecked // Overflow is fine, just wrap
        {
            foreach (object obj in list)
                if(obj != null)
                    hash = hash + obj.GetHashCode();
        }
        return hash;
    }
}

Now it works as expected:
var  dict = new Dictionary<List<object>, double>(new ListComparer());
dict.Add(new List<object>() { "a", "b" }, 3);
double output = dict[new List<object>() { "a", "b" }]; // 3.0


text:
Q: After transfer learning how to use original output layer and get both models predictions? I trained a new network using EfficientNet for object detection, instead of using the original output layer of EfficientNet i change it to 5 output dense (5 labels from the original layer).
in the training procedure, i locked all the layers and only train my custom output layer
i managed to achieve a better result in my custom output layer labels
 (in EfficientNet they achieve 84% i managed to get an average of 92% accuracy  )
i would like to get the original 1000 label and also my own 5 output layer
TLDR
what I am trying to achieve is this :
let's say I have 2 neural networks: A, B they both contains N-1 identical layers  and different output layer

*

*A (output layer) dim is 5

*B (output layer) dim is 1000

because they both identical up until the output layer they both will have the same output before the output layer
I would like to run model B then get the output of the dropout layer, run this output against model A output layer instead of running both of the models again
is it possible or I am facing an XY problem
?
what is the right way to create a neural network with 2 output layers?
I illustrated the problem :

A: I found how to do it just need to find the point of the split
copy the first layer and direct its input to the other model and then concatenate all layers together
efficientnet = efn.EfficientNetB0()
retrained_model = load_model(model_path, custom_objects=get_custom_objects())
top_conv = efficientnet.get_layer('top_conv')
top_conv._name = top_conv._name + str("ef0")

top_bn = efficientnet.get_layer("top_bn")
top_bn._name = top_bn._name + str("ef0")

top_activation = efficientnet.get_layer('top_activation')
top_activation._name = top_activation._name + str("ef0")

avg_pool = efficientnet.get_layer('avg_pool')
avg_pool._name = avg_pool._name + str("ef0")

top_dropout = efficientnet.get_layer('top_dropout')
top_dropout._name = top_dropout._name + str("ef0")

probs = efficientnet.get_layer('probs')

probs(top_dropout(
    avg_pool(top_activation(top_bn(top_conv(retrained_model.get_layer('block7a_project_bn').output))))))

model = Model(inputs=retrained_model.input,
                   outputs=[retrained_model.output, probs.get_output_at(0)])
model.summary()
model.save("/home/naor/projects/efficientnetretrainedmodel/bin/model-2-pred.h5")

the new model created as model A input and as output an [A.output ,B.output]


text:
Q: Processing multiple simultaneous uploads with Cordova I want to upload 4 images from an ionic app to server side made using sails js.
An user can upload many images so before submit a form so I save all images in an array as its shown below
var cameraOptions = {
                            quality: 100,
                            destinationType: Camera.DestinationType.NATIVE_URI,
                            sourceType : Camera.PictureSourceType.CAMERA,
                            encodingType: Camera.EncodingType.JPEG,
                            targetWidth: 500,
                            targetHeight: 500,
                            popoverOptions: CameraPopoverOptions,
                            saveToPhotoAlbum: false,
                            allowEdit:true
                        };
                        var success = function(data){
                            $mdDialog.hide();
                            if(key==null)
                            {
                                compteurImage =compteurImage+1;
                                $scope.$apply(function () {
                                    $scope.imgURI.push(data);

                                });
                                $scope.nombreImage=compteurImage;
                            }
                            else
                            {
                                $scope.$apply(function () {
                                    $scope.imgURI[key]=data;

                                });
                            }
                            $rootScope.image=$scope.imgURI;

                        };

After having had all the images in an array, I loop on the array and I send each image to the server as shown below
for (var i = 0; i<$rootScope.image.length;  i++) {
                      if (keepGoing) {
                        var options = new FileUploadOptions();
                        var params = {};
                        params.idArticle =response.article.idArticle;
                        var url=$rootScope.image[i].substr($rootScope.image[i].lastIndexOf('/') + 1);
                        options = {
                          fileKey: "file",
                          fileName:i+(url.split('?')[0]),
                          mimeType: "image/png",
                          idArticle: response.article.idArticle
                        };
                        options.params=params;
                        var failed = function (err) {
                            console.log(err);
                            keepGoing = false;
                        };
                        var success = function (result) {
                            count++;
                            if(count==$rootScope.image.length)
                            {
                              console.log("success");
                            }
                        };
                        var ft = new FileTransfer();
                        ft.upload($rootScope.image[i], Globals.urlServer + Globals.port + "/article/uploadImage", success, failed, options);
                      }

Server side the controller in charge of upload image is /article/uploadImage
 uploadImage:function(req,res)
{
    req.file('file')
        .upload({ dirname: '../../assets/imagesArticle'},function (err, uploadedFiles) {

            if (err) return res.serverError(err);
            else {
                var chemin = '';
                var type = '';
                uploadedFiles.forEach(function (file) {
                    chemin = require('path').basename(file.fd);
                    type = file.type;
                    Image.create({cheminImage:chemin, typeImage:type,article:req.body.idArticle}).exec(function(err,image){
                        if (err)
                        {

                            res.send({success:false});
                        }

                        if(image)
                        {
                           res.send({success:true});
                        }
                    })
                });

            }
        });
},

My issue is if regardless how many pictures I upload, when I look  image directory on server side, images are always identical and correspond to the last image of the images array. For example if I upload 3 differents images, on  server side I get 3 identicals images whose correspond to the third or last image in array.
how can I fix it ?


text:
Q: Best practice for Java EE application development using extjs and Sencha Architect I am a newbie to extjs and kind of new to javascript world also. I have developed applications in jsp/servlet, JSF etc.
We are planning to use extjs along with Sencha Architect to develop UIs for our application.
Being new I have several questions for which I am searching answers
Q1. How should we use Sencha Architect in multi developer environment in terms of versioning. Shall we checkin the Architect project into svn and ask each developer to work on same project.
Q2. What should be the structure of Sencha Architect project (Basically how to make sure each developer is working on his/her individual module without affecting others component).
Is there any best practice for this.
Q3. What is the best practice for developing an application which contains several pages along with navigation. Should we create a single html file (with lot of javascript to modify the body) or should we have multiple html?

A: *

*yes, it should certainly be in source control. you will want developer-specific settings to not be in source control however.

*the best way is to create an application "shell" with menu bars, and load in modules/plugins and have them register with the application, adding their own menus etc.

*definitely a single page application. security remains on the server though (for example in your REST API). security is irrelevant on the client as they have control over source code. you should just hide functionality that a user should not use.
How to load different views into viewport?


text:
Q: How to get the count from Unstructrued data I have unstructured data from my perf logs. I would like to capture the service details from it.  I can do delimiter, however I am not able to count or Print the column, since it doesn't have any header.
Kindly help me to figure out this issue.s
import pandas as pd

df = pd.read_csv (r'/Users/Myhome/Documents/Py_Learning/log.csv', sep = '|' , skipinitialspace=True)
#df = pd.read_csv (r'/Users/Myhome/Documents/Py_Learning/log.csv', sep =':|,|[|]', engine='python', header=None) ---> Multi separator is giving error.

#df.groupby("CLIENT")
SERVICE = df.columns[4]
print (SERVICE)

How can I find the unique service name in all lines and get the count. I would like to give it as a graph with last week data.
Sample data :
2019-10-22 15:35|Where:CARD|SERVICE:Dell|VERSION:1.0|CLIENT:HDD|OPERATION:boverdue|RESPONSETIME:0034|STATUS:100000:ERR_TRANSACTION_TIMED_OUT|SEVERITY:ERROR|STATUSCODE:SOAP-FAULT|STATUSMESSAGE:NA 2019-10-22 15:35|Where:Digital|SERVICE:Laptop|VERSION:1.0|CLIENT:mouse|OPERATION:connet|RESPONSETIME:3456|STATUS:NO_RECORDS_MATCH_SELECTION_CRITERIA|SEVERITY:INFO|STATUSCODE:1120|STATUSMESSAGE:NA

A: First, since you're data has no header, you need to set header=None.
df = pd.read_csv ('data.csv', sep = '|' , skipinitialspace=True, header=None)
And then to get service data, simply do
new_df = df.iloc[:,2].str.split(':', expand=True).iloc[:,1].value_counts()


text:
Q: Bootstrap columns break even inside rows and containers So I'm building a webpage using Bootstrap 3 and some LESS mixins.
Whenever I try to make a two column layout, say using .make-sm-column(4); and .make-sm-column(8); the right column always overflows to the next row.
I understand that to account for the padding-left and padding-right of 15px you need to have your columns within a row and that row be inside of a container. On a basic level, the LESS I am using looks like:
.container {
  .container();
  //...

  .content {
    .make-row();

    .col1 {
      .make-md-column(8);
    }

    .col2 {
      .make-md-column(4);
    }
  }
}

Still, for some reason, the columns seem to be too wide for the container and break over. Is there anything obvious that I'm missing that I can't see? My only fix for now is to remove the padding-left/right but that is hacky and of course removing this gutter doesn't make the two columns look clean next to each other without me needing to do any extra work.

A: When you remove the padding it gets fixed?
It must be a problem with the box-sizing. The padding makes the columns bigger than the width specified. Change the property to:
box-sizing: border-box; and that should do it.