Q: Spring Profiles odd behavior I am trying to figure out how to use Spring Profiles for testing. I think I do everything according to spring docs. And in the end I got results that I cannot explain Here is the listing of my program:
Here is the main config:
package com.test.profiles;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

import java.util.HashMap;
import java.util.Map;

@Configuration
@ComponentScan("com.test.profiles")
public class MainConfig {

@Autowired
private String helloMsg;

@Autowired
private Map<String,String> profileDependentProps;

@Bean
@Profile("default")
public String helloMsg() {
    return "Hello default";
}

@Bean
@Profile("default")
public Map<String,String> profileDependentProps() {
    Map<String,String> props = new HashMap<>();
    props.put("1", "default");
    props.put("2", "default");
    props.put("3", "default");
    return props;
}
}

Test configuration:
package com.test.profiles;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

import java.util.HashMap;
import java.util.Map;

@Configuration
@Profile("dev")
public class TestConfig {

@Bean
public String helloMsg() {
    return "Hello dev";
}

@Bean
public Map<String,String> profileDependentProps() {
    Map<String,String> props = new HashMap<>();
    props.put("1", "dev");
    props.put("2", "dev");
    props.put("3", "dev");
    return props;
}
}

And finally my test class:
package com.test.profiles;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.annotations.Test;

import java.util.Map;

@ContextConfiguration(classes = MainConfig.class)
@ActiveProfiles("dev")
public class ProfileTester extends AbstractTestNGSpringContextTests {

@Autowired
private String string;

@Autowired
private Map<String,String> profileDependentProps;

@Test
public void profileTest() {
    System.out.println("TEST: "+string);
    for(Map.Entry<String,String> entry : profileDependentProps.entrySet()) {
        System.out.println(entry.getKey() + "=" + entry.getValue());
    }
}
}

And odd output:
[TestNG] Running:
C:\Users\nikopol\.IntelliJIdea13\system\temp-testng-customsuite.xml

15:36:34,893  INFO GenericApplicationContext:513 - Refreshing org.springframework.context.support.GenericApplicationContext@7ecdc69b: startup date [Mon Mar 10 15:36:34 EET 2014]; root of context hierarchy

TEST: Hello dev
helloMsg=Hello dev

===============================================
Custom suite
Total tests run: 1, Failures: 0, Skips: 0
===============================================

15:36:35,105  INFO GenericApplicationContext:873 - Closing org.springframework.context.support.GenericApplicationContext@7ecdc69b: startup date [Mon Mar 10   15:36:34 EET 2014]; root of context hierarchy

What's with this line? --- helloMsg=Hello dev
Where is my map?

A: By default when Spring encounters a auto wiring field of type Map<String, [type]> it will inject a map of beans of the specific [type]. In your case String. You will not get your configured map.
See: http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-autowired-annotation.
You are basically running into a corner case as you have a map with String as keys. To get your bean you will either have to put an @Qualifier("profileDependentProps") next to the @Autowired or use @Resource("profileDependentProps") instead of @Autowired.


Q: Why is the notion of a function as a relation important? I am reading Bartle and Sherbert's "Intro to Real Analysis" and in motivating the definition of a function as a relation they make the statement, "To the mathematician of the the early nineteenth century, the word "function" meant a definite formula .... This understanding excluded the case of different formulas on different intervals, so that functions could not be defined "in pieces" ". (They then go on to make some generalizations about problems with distinguishing between a function and its values and the difficulty with interpreting the phrase "rule of correspondence")
I find this statement unconvincing for 2 reasons: first, we commonly define piecewise functions (like signum for example), and nobody really has any trouble understanding what is meant by this. Secondly, it seems like whenever I try to work a proof using the definition of a function as a relation, it seems much more difficult and complicated.
Are there applications or maybe areas of math one encounters later, where it is genuinely useful to view functions from this point of view, or is this more like a "Bourbaki" definition for purists. The only case I can see where this definition is actually useful at the level of math I'm studying is if I simply want to draw a graph of some general function (without a formula) and claim it is a function (b/c it is a subset of the Cartesian plane, which by observation, I can see passes the vertical line test).
Thanks,
Matt

A: First of all, in set theory it is very useful to see functions as sets of ordered pairs. This allows us to use $\subseteq$ to order them, and this is used in forcing quite often, and forcing is one of the main corner stones of modern set theory.
Secondly, if you want to put your mathematics on a certain foundation, you want to be able and formalize it in some context. Function, indeed any mathematical object, needs to be formalized in a rigorous way. It's not enough that we understand what does it mean, it is important that we are able to say "There is an object in our universe which represents this notion".
Moreover this opens the door for a possibly terrifying understanding. Almost no function from $\Bbb R$ to itself is continuous. We can develop the notion of "almost all" and show that almost all continuous functions are not differentiable, and from those which are almost none is differentiable with a continuous derivative, and so on.
If a function was just "some formula using some basic and elementary operations, perhaps piecewise" then we wouldn't be able to have this understanding. We couldn't have said that most continuous functions don't have a derivative.
And finally, this allows the extension of the notion of "function" from just real values to an arbitrary notion. If we have two spaces, then we can say what is considered a function between them, this awesome generality is exactly the heart and soul of mathematics. It is what mathematics strives to be, and where it thrives the most.

A: I think you need to understand the historical perspective. Although I am not a historian of mathematics, from whatever sources I have read on this topic I find that before the concept of function was formulated in set theoretic terms (like a relation with some specific properties) a function was supposed to be given by a formula which consisted of algebraic/trigonometric/etc operations.For example $f(x) = x^{2}/(1 + x)$ used to be a function, but the following example could not be called a function: $f(x) = 0$ when $x$ is rational and $f(x) = 1$ if $x $ is irrational.
During the time when mathematicians were studying Fourier series and its implications they found they had to deal with many weird kind of functions which could possibly never be represented by a formula yet possessed Fourier series (which are basically sums of sines and cosines). Then there were many more issue involved with the concept of integral of a function and it turned out that many weird discontinuous kinds of functions were integrable. These difficulties led to the notion of function as a relation (or a rule of correspondence) and the need for a formula was removed. In this regard I advise that you do read the marvelous books "A Radical Approach to Real Analysis" and "A Radical Approach to Lebesgue's Theory of Integration" by David M. Bressoud. These two books deal in detail with the problems which mathematicians faced with intuitive definition of a function based on the formula.
I also understand that you don't find any issue with defining a function without a formula precisely because mathematicians have already drilled this set theoretic definition into our books and minds for 1 or 2 centuries. But before such notions were developed it was very difficult to deal with pathological functions.


Q: how to order by date django post view How can I order my posts from latest to oldest? I Use ordering = ['-date_posted'] for class based views. how can I do the exact thing for a function based view?
this is my view function:
def blog_view(request):
    posts = Post.objects.all()
    paginator = Paginator(posts, 3)
    page = request.GET.get('page')
    posts = paginator.get_page(page)
    common_tags = Post.tags.most_common()[:]
    context = {
        'posts':posts,
        'common_tags':common_tags,
    }
    return render(request, 'posts/blog.html', context)

A: you can do
posts = Post.objects.all().order_by('-date_posted')

or in your models add a meta class
 class Meta:
        ordering = ['-date_posted']


Q: Merging Corresponding MySQL Records I have a MySQL table called "objecttable" that has the following structure and data in it. (The data is just a sequence, there is a whole lot more).
ID    |  Name              |  posX  |  posY   | posZ |rotX | rotY | rotZ | rotW  |
3562  |   LODpmedhos1_LAe  |  2062  |  -1703  |  16  |  0  |  45  |  22  |  1    |
3559  |   LODpmedhos5_LAe  |  2021  |  -1717  |  15  |  0  |  45  |  34  |  1    |
3561  |   LODpmedhos3_LAe  |  2021  |  -1717  |  15  |  0  |  45  |  34  |  1    |

I want to figure out which records have the same posX, posY, posZ, rotX, rotY and rotZ values and insert them into a table called "matchtable", and in the end I want it to look like this (I have the table structure ready)
ID1     |       Name            |   ID2     |   Name          |
3559    |   LODpmedhos5_LAe     |   3561    |  LODpmedhos3_LAe|

I'd appreciate if someone could give me the correct SQL query for it. I don't have more than two matching coordinates and not all coordinates match.
Sorry if the table representations suck, I'll try to make a HTML table if necessary.
Thanks!

A: This query will do the trick, but the number of results might be a LOT more than required. For example, if there are 5 rows satisfying your query, then the results will be 20( = n*(n-1) ) in number.
SELECT ot.ID AS ID1, ot.Name AS Name1, ot2.ID AS ID2, ot2.Name AS Name
FROM objecttable ot
JOIN objecttable ot2
    ON ot.ID > ot2.ID
        AND ot.posX = ot2.posX
        AND ot.posY = ot2.posY
        AND ot.posZ = ot2.posZ
        AND ot.rotX = ot2.rotX
        AND ot.rotY = ot2.rotY
        AND ot.rotZ = ot2.rotZ

EDIT
In reply to lserni's comment:
ON ot.ID <> ot2.ID

The above condition is there to remove the result like:
ID1     |       Name            |   ID2     |   Name          |
3559    |   LODpmedhos5_LAe     |   3559    |  LODpmedhos5_LAe|

A: try this:
-- insert into matchtable -- uncomment to insert the data
select alias1.Id,
    alias1.Name,
    alias2.Id
    alias2.Name
from objecttable as alias1
    join objecttable as alias2
        on alias1.posx = alias2.posx
            and alias1.posy = alias2.posy
            and alias1.posz = alias2.posz
            and alias1.roty = alias2.roty
            and alias1.roty = alias2.roty
            and alias1.rotz = alias2.rotz
            and alias1.Id > alias2.Id


Q: Getting find: bad option -o -name abc -o -name xyz when perform search for *.properties excluding set of directories from search #!/usr/bin/ksh

# *****************************************************************************************
# copy_properties.sh
# This script copies *.properties files from all directory excluding the
# ones provided as the args. to a folder location of our choice.
#
# *****************************************************************************************

echo "Starting the find and replace process for :" "$1"
set -x
# **************** Change Variables Here ************

startdirectory=$2 #"/home/ardsingh/test_properties/properties_files"
destinationFolder=$3

if [ -n "$4" ]; then
listOfFolderTobeIgnored=$4
#@list = split(/ /, $listOfFolderTobeIgnored);
#mapfile -t list << ($listOfFolderTobeIgnored)
IFS=' '
set -A list $listOfFolderTobeIgnored
foldersToBeIgnored="-o -name "${list[0]}
unset 'list[0]'
for item in "${list[@]}"
do
foldersToBeIgnored="$foldersToBeIgnored -o -name "
foldersToBeIgnored="$foldersToBeIgnored$item"
done
else
  echo "No input provided for folders to be ignored."
fi

#echo $foldersToBeIgnored

find "$startdirectory" -type d \( -name properties_file_folder_02_25 -o -name brmsdeploy -o -name TempJobs -o -name tmp -o -name logs -o -name deploy "$foldersToBeIgnored" \) -prune -o -name "*.properties" -type f -print -exec cp {} "$destinationFolder" \;

Getting below error:
find: bad option -o -name abc -o -name xyz
find: [-H | -L] path-list predicate-list

A: Rather than building up a string with command line options for ignoring directories with certain names, use an array. This way, the options for find that you add dynamically from the command line would be properly delimited.
The following script is a very basic one that takes a single search path, a destination directory, followed by any number of directory names to ignore.  The code builds up a set of options for find in $@, the array of positional parameters.
#!/usr/bin/ksh

searchpath=$1
destdir=$2
shift 2

ignore=( brmsdeploy TempJobs tmp logs deploy )

if [ ! -d "$destdir" ]; then
    printf 'Destination directory "%s" does not exist\n' >&2
    exit 1
fi

# Process the directories to ignore from the command line.
# This replaces the positional parameters.
for name do
    set -- "$@" -o -name "$name"
    shift
done

# Process the directories that we always ignore.
# This adds to the positional parameters.
for name in "${ignore[@]}"; do
    set -- "$@" -o -name "$name"
done

shift # shift off the first -o

find "$searchpath" \( -type d \( "$@" \) -prune \) -o \
    \( -type f -name '*.properties' -exec cp {} "$destdir" \; \)

To use:
./script.sh /path/to/topdir /path/to/destdir somename someothername fluff

This would execute find, ignoring directories with names somename, someothername, and  fluff.  Note that this also allows these names to contain spaces, tabs and newlines (if they are quoted on the command line).
The actual find command executed by this command would be
find /path/to/topdir '(' -type d '(' -name somename -o -name someothername -o -name fluff -o -name brmsdeploy -o -name TempJobs -o -name tmp -o -name logs -o -name deploy ')' -prune ')' -o '(' -type f -name '*.properties' -exec cp '{}' /path/to/destdir ';' ')'


Q: send automated messages to various whatsApp users using this xpath to click send started not to work I used send automated messages to various whatsApp users using this xpath code to click on the send button.
navegador.find_element_by_xpath('//*[@id="main"]/footer/div[1]/div[2]/div/div[2]').send_keys(Keys.SEND)
It recently stopped working saying that it can't find the xpath.
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="main"]/footer/div[1]/div[2]/div/div[2]/button"} (Session info: chrome=91.0.4472.124)
I've tried updating the xpath as it seams to have changed to:
//*[@id="main"]/footer/div[1]/div[2]/div/div[2]/button
But I still get the same error message.
I've also seen one thread suggesting that the driver may not be set for the current page. If so, how do I fix that?
selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable (Session info: chrome=81.0.4044.138)
What am 'I missing?
Thanks in advance for any help on this mater.

A: Possibly your locator is not correct.
Also, the send element button appears with a short delay after the text is inserted into the message text area.
Try this:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(driver, 20)

wait.until(EC.visibility_of_element_located((By.XPATH, '//span[@data-testid="send"]'))).click()


Q: Lua/Wow: UseInventoryItem() issue My goal is to create a script that warns when you are disenchanting a piece you don't want. When disenchanting an item straight from inventory, I could use the UseInventoryItem() API. Since UseInventoryItem() seems to work only on inventory slot right click, I created this script, based on GetMouseFocus() API, that works with the original interface of the game: but if someone used an addon, would it still work?
Of course, better solutions are welcome
local mt = {
    __index = {
        isvalue = function(t, value)
            local is = false
            for k, entry in ipairs(t) do
                if (entry == value) then
                    is = true
                    break
                end
            end
            return is
        end
    }
};

local protected = { "item1", "item2", "item3", "etch." }; -- items I want to protect
setmetatable(protected, mt);

local disenchanting;
local antidisenchant = CreateFrame("Frame");

antidisenchant:RegisterEvent("UNIT_SPELLCAST_SENT");

antidisenchant:SetScript("OnEvent", function(self, event, ...)
    if (event == "UNIT_SPELLCAST_SENT") then
        if (arg2 == "Disenchant") then
            disenchanting = true
        end
    end
end);

antidisenchant:SetScript("OnUpdate", function()
    if GetMouseFocus() then -- GetMouseFocus() returns the frame that currently has mouse focus.
        local TargetItemID = GetInventoryItemID("player",GetMouseFocus():GetID()) -- The IDs of each inventory slot frame have the same id as the slot (16 for main hand, 17 for off hand etc.).
        if (TargetItemID) and (string.find(GetMouseFocus():GetName(),"Slot")) then -- Inventory slot frame are named like "CharacterMainHandSlot".
            local name, link = GetItemInfo(TargetItemID)
            if (disenchanting) and (protected:isvalue(name)) then
                DEFAULT_CHAT_FRAME:AddMessage("WARNING! YOU'RE DISENCHANTING "..link,1,0,0)
            end
        end
    end
end)


Q: Groovy Template Engine rendering contents I'm trying to separate some contents in the body section of my layout.tpl. For instance, I have carousel slider in my index.tpl, but it's not necessary to include it inside the login.tpl. Moreover, I need to add another page specific contents too. So, layout.tpl, and index.tpl are like in the following:
layout.tpl
  body {
    headerContents()
    div(class:'container') {
        div(class:'row') {
            div(class:'col-lg-12') {
                content()
            }
        }
    }
  }

index.tpl
layout 'layouts/layout.tpl',
title:'Home',
headerContents: contents {
   h1('Test Header')
}
content: contents {
   h1('Test Content')
}

But h1('Test Content) cannot be rendered. I checked the docs but I couldn't find anything about how to render two different contents. Does template engine support to do this or not?


Q: How is gRPC used to enhance Microservice interaction in PHP? I'm studying gRPC and noticed they assist in building quality microservice interactions.
Currently I use RESTful requests to interact between services with typical tools like Guzzle etc.
How does gRPC improve the way Microservices would interact with each-other?

A: gRPC offers several benefits over REST (and also some tradeoffs).
The three primary benefits are:

*

*Protocol Buffers are efficient. Because both sides already have the protobuf definitions, only the data needs to be transferred, not the structure. In contrast, for some JSON payloads, the names of the fields can make the payload significantly larger than just the data. Also, protobuf has a very compact representation "on the wire". Finally, you don't have the overhead of the HTTP headers for every request. (Again, for some smaller requests, the headers could be significantly larger than the request body itself.)

*gRPC can be bidirectional. gRPC services can have "streams" of data which can go both directions. HTTP must always have a request and response matched together.

*gRPC tries to make you think about version compatibility. Protocol Buffers are specifically designed to help you make sure you maintain backwards compatibility as your data structures change. If done properly, this can make future upgrades easier to implement.

With all those upsides, why not use gRPC for everything?
In my view, the main downside of gRPC is that it requires more tooling. Just about any programming language can handle HTTP and there are many debugging tools, but for gRPC you have to compile your .proto files for each language and share them. There also aren't as many testing tools.


Q: Unable to pass a string from VBA (Excel) to my COM object I am experimenting with creating a COM interface for my application in order to allow eg. VBA to drive certain parts of my application.
I have my COM library up and running and installed, even to the part where a routine called in Excel can be debugged in the Delphi IDE.
Here's the VBA code that I activate from Excel using a button:
Sub TestAMQMOLE_OpenProject()
  Dim vConnection As String
  Dim vAMQM As Object
  Dim vAMProject As Object

  vConnection = "$(MYSRC)\LCCAMQM38\UnitTestData\AnalyseSortingAndGrouping"
  Set vAMQM = CreateObject("LCCAMQM_AX.LCCAMQM_Application")
  vAMQM.Connect
  Set vAMQMProject = vAMQM.OpenProject(vConnection) 'This parameter does not get through
  Set vAMQMProject.Active = True
  Set vAMQMProject = Nothing

  vAMQM.Disconnect
  Set vAMQM = Nothing

End Sub

And the part in Delphi handling it looks like this:
function TLCCAMQM_Application.OpenProject(const aFolderOrAlias: WideString): ILCCAMQM_Project;
begin
  try
    Result:=TLCCAMQM_Project.Create(aFolderOrAlias); // wrapper om TdmAMEditBase
  except
    SHowMessage(ExceptionToString(ExceptObject,ExceptAddr));
  end;
end;

Where the code fails because the aFolderOrAlias parameter string is empty. I added the exception handler in order to debug outside the Delphi IDE. when debugging inside the IDE, the parameter string indeed appears as empty.
I have also tried to pass the parameter as a Variant, or const Variant (and adjusting the type library accordingly), but in that case I get a VT_RECORD variant type (0x0024) which does not make any sense to me.
Here is what the interface definition of the type library looks like.
....
 [
    uuid(EDD8E7FC-5D96-49F1-ADB7-F04EE9FED7B5),
    helpstring("Dispatch interface for LCCAMQM_Application Object"),
    dual,
    oleautomation
  ]
  interface ILCCAMQM_Application: IDispatch
  {
    [id(0x000000C9)]
    int _stdcall Connect(void);
    [id(0x000000CA)]
    int _stdcall Disconnect(void);
    [id(0x000000CB)]
    ILCCAMQM_Project* _stdcall OpenProject([in] BSTR aFolderOrAlias);
    [propget, id(0x000000CC)]
    HRESULT _stdcall Connected([out, retval] VARIANT_BOOL* Value);
  };

  [
    uuid(590DBF46-76C9-4877-8F47-5A926AFF389F),
    helpstring("LCCAMQM_Application Object")
  ]
  coclass LCCAMQM_Application
  {
    [default] interface ILCCAMQM_Application;
  };
....

I am fairly sure there must be a way to pass strings from VBA to COM objects. But after fiddling around for several hours I am lost :s.

A: As it turned out, ComIntern and Remy were right. I had completely misunderstood the whole stdcall and safecall interfaces.
The .ridl file now looks like this:
....
  interface ILCCAMQM_Application: IDispatch
  {
    [id(0x000000C9)]
    int _stdcall Connect(void);
    [id(0x000000CA)]
    int _stdcall Disconnect(void);
    [propget, id(0x000000CC)]
    HRESULT _stdcall Connected([out, retval] VARIANT_BOOL* Value);
    [id(0x000000CB)]
    HRESULT _stdcall OpenProject([in] BSTR aFolderOrAlias, [out, retval] ILCCAMQM_Project** Value);
  };
....

And the generated ...TLB.pas file looks like this:
....
// *********************************************************************//
// Interface: ILCCAMQM_Application
// Flags:     (4416) Dual OleAutomation Dispatchable
// GUID:      {EDD8E7FC-5D96-49F1-ADB7-F04EE9FED7B5}
// *********************************************************************//
  ILCCAMQM_Application = interface(IDispatch)
    ['{EDD8E7FC-5D96-49F1-ADB7-F04EE9FED7B5}']
    function Connect: SYSINT; stdcall;
    function Disconnect: SYSINT; stdcall;
    function Get_Connected: WordBool; safecall;
    function OpenProject(const aFolderOrAlias: WideString): ILCCAMQM_Project; safecall;
    property Connected: WordBool read Get_Connected;
  end;

// *********************************************************************//
// DispIntf:  ILCCAMQM_ApplicationDisp
// Flags:     (4416) Dual OleAutomation Dispatchable
// GUID:      {EDD8E7FC-5D96-49F1-ADB7-F04EE9FED7B5}
// *********************************************************************//
  ILCCAMQM_ApplicationDisp = dispinterface
    ['{EDD8E7FC-5D96-49F1-ADB7-F04EE9FED7B5}']
    function Connect: SYSINT; dispid 201;
    function Disconnect: SYSINT; dispid 202;
    property Connected: WordBool readonly dispid 204;
    function OpenProject(const aFolderOrAlias: WideString): ILCCAMQM_Project; dispid 203;
  end;
....

And the OpenProject now works from my internal unit test (written in delphi) as well as from Excel-VBA.
Now I am struggling with properties to set and get through Excel VBA as well as through an OleVariant in delphi. But I will have to put that in another Q.


Q: Table with an array, return hash I have an array ["1","1","a","b","y"] and table1:
table1

POSITION    NAME     VALUE     CODE
1           Animal   Dog       1
1           Animal   Cat       2
1           Animal   Bird      3
2           Place    USA       1
2           Place    Other     2
3           Color    Red       a
3           Color    Blue      b
3           Color    Orange    c
4           Age      Young     a
4           Age      Middle    b
4           Age      Old       c
5           Alive    Yes       y
5           Alive    No        n

For each element in the array, I would like to find a matching POSITION-CODE combination in table1, where POSITION is the index of the element (base 1) and CODE is the element in the array. Then, I want to return a hash that contains  the corresponding NAME and VALUE for the matches as a key and its value. The output would be:
{"Animal" => "Dog", "Place" => "USA", "Color" => "Red", "Age" => "Middle", "Alive" => "Yes"}

How would I go about this?

A: I assume you want to map several codes arrays against the same table. Suppose you first read the table into an array:
a = [["1", "Animal", "Dog", "1"],
     ["1", "Animal", "Cat", "2"],
     ["1", "Animal", "Bird", "3"],
     ["2", "Place", "USA", "1"],
     ["2", "Place", "Other", "2"],
     ["3", "Color", "Red", "a"],
     ["3", "Color", "Blue", "b"],
     ["3", "Color", "Orange", "c"],
     ["4", "Age", "Young", "a"],
     ["4", "Age", "Middle", "b"],
     ["4", "Age", "Old", "c"],
     ["5", "Alive", "Yes", "y"],
     ["5", "Alive", "No", "n"]]

and
codes = ["1","1","a","b","y"]

Then you could do this:
codes.zip(a.chunk { |a| a.first }).map { |l,(_,b)|
  b.find { |c| c.last == l}[1...-1] }.to_h
  #=> {"Animal"=>"Dog", "Place"=>"USA", "Color"=>"Red",
  #    "Age"=>"Middle", "Alive"=>"Yes"}

The steps:
enum0 = a.chunk { |a| a.first }
  #=> #<Enumerator:
  #   #<Enumerator::Generator:0x007f8d6a0269b8>:each>

To see the contents of the enumerator,
enum0.to_a
  #=> [["1", [["1", "Animal", "Dog", "1"], ["1", "Animal", "Cat", "2"],
  #           ["1", "Animal", "Bird", "3"]]],
  #    ["2", [["2", "Place", "USA", "1"], ["2", "Place", "Other", "2"]]],
  #    ["3", [["3", "Color", "Red", "a"], ["3", "Color", "Blue", "b"],
              ["3", "Color", "Orange", "c"]]],
  #    ["4", [["4", "Age", "Young", "a"], ["4", "Age", "Middle", "b"],
  #           ["4", "Age", "Old", "c"]]],
  #    ["5", [["5", "Alive", "Yes", "y"], ["5", "Alive", "No", "n"]]]]

p = codes.zip(enum0)
  #=> [["1", ["1", [["1", "Animal", "Dog", "1"],
  #                 ["1", "Animal", "Cat", "2"],
  #                 ["1", "Animal", "Bird", "3"]]]],
  #    ["1", ["2", [["2", "Place", "USA", "1"],
  #                 ["2", "Place", "Other", "2"]]]],
  #    ["a", ["3", [["3", "Color", "Red", "a"],
  #                 ["3", "Color", "Blue", "b"],
  #                 ["3", "Color", "Orange", "c"]]]],
  #    ["b", ["4", [["4", "Age", "Young", "a"],
  #                 ["4", "Age", "Middle", "b"],
  #                 ["4", "Age", "Old", "c"]]]],
  #    ["y", ["5", [["5", "Alive", "Yes", "y"],
  #                 ["5", "Alive", "No", "n"]]]]]

l,(_,b) = enum1.next
l #=> "1"
b #=> [["1", "Animal", "Dog", "1"], ["1", "Animal", "Cat", "2"],
  #    ["1", "Animal", "Bird", "3"]]
enum1 = b.find
  #=> #<Enumerator: [["1", "Animal", "Dog", "1"],
  #                  ["1", "Animal", "Cat", "2"],
  #                  ["1", "Animal", "Bird", "3"]]:find>
c = enum1.next
  #=> ["1", "Animal", "Dog", "1"]
c.last == l
  #=> true

so enum1 returns
d = ["1", "Animal", "Dog", "1"]
e = d[1...-1]
  #=> ["Animal", "Dog"]

So the first element of x.zip(y) is mapped to ["Animal", "Dog"].
After performing the same operations for each of the other elements of enum1, x.zip(y) equals:
f = [["Animal", "Dog"], ["Place", "USA"], ["Color","Red"],
     ["Age",  "Middle"], ["Alive", "Yes"]]

The final steps is
f.to_h
  #=> {"Animal"=>"Dog", "Place"=>"USA", "Color"=>"Red",
  #    "Age"=>"Middle", "Alive"=>"Yes"}

or for < v2.0
Hash[f]


Q: Oracle 'after create' trigger to grant privileges I have an 'after create on database' trigger to provide select access on newly created tables within specific schemas to different Oracle roles.
If I execute a create table ... as select statement and then query the new table in the same block of code within TOAD or a different UI I encounter an error, but it works if I run the commands separately:
create table schema1.table1 as select * from schema2.table2 where rownum < 2;

select count(*) from schema1.table1;

If I execute them as one block of code I get:
  ORA-01031: insufficient privileges

If I execute them individually, I don't get an error and am able to obtain the correct count.
Sample snippet of AFTER CREATE trigger
 CREATE OR REPLACE TRIGGER TGR_DATABASE_AUDIT AFTER
 CREATE OR DROP OR ALTER ON Database
 DECLARE
    vOS_User              VARCHAR2(30);
    vTerminal             VARCHAR2(30);
    vMachine              VARCHAR2(30);
    vSession_User         VARCHAR2(30);
    vSession_Id           INTEGER;
    l_jobno               NUMBER;

 BEGIN

   SELECT sys_context('USERENV', 'SESSIONID'),
          sys_context('USERENV', 'OS_USER'),
          sys_context('USERENV', 'TERMINAL'),
          sys_context('USERENV', 'HOST'),
          sys_context('USERENV', 'SESSION_USER')
   INTO   vSession_Id,
          vOS_User,
          vTerminal,
          vMachine,
          vSession_User
    FROM Dual;

    insert into schema3.event_table VALUES (vSession_Id, SYSDATE,
    vSession_User, vOS_User, vMachine, vTerminal, ora_sysevent,
    ora_dict_obj_type,ora_dict_obj_owner,ora_dict_obj_name);

    IF ora_sysevent = 'CREATE' THEN
       IF (ora_dict_obj_owner = 'SCHEMA1')  THEN
           IF DICTIONARY_OBJ_TYPE = 'TABLE' THEN
              dbms_job.submit(l_jobno,'sys.execute_app_ddl(''GRANT SELECT
              ON '||ora_dict_obj_owner||'.'||ora_dict_obj_name||' TO
              Role1,Role2'');');
           END IF;
       END IF;
    END IF;
 END;

A: Jobs are asynchronous.  Your code is not.
Ignoring for the moment the fact that if you're dynamically granting privileges that something in the world is creating new tables live in production without going through a change control process (at which point a human reviewer would ensure that appropriate grants were included) which implies that you have a much bigger problem...
When you run the CREATE TABLE statement, the trigger fires and a job is scheduled to run.  That job runs in a separate session and can't start until your CREATE TABLE statement issues its final implicit commit and returns control to the first session.  Best case, that job runs a second or two after the CREATE TABLE statement completes.  But it could be longer depending on how many background jobs are allowed to run simultaneously, what other jobs are running, how busy Oracle is, etc.
The simplest approach would be to add a dbms_lock.sleep call between the CREATE TABLE and the SELECT that waits a reasonable amount of time to give the background job time to run.  That's trivial to code (and useful to validate that this is, in fact, the only problem you have) but it's not foolproof.  Even if you put in a delay that's "long enough" for testing, you might encounter a longer delay in the future.  The more complicated approach would be to query dba_jobs, look to see if there is a job there related to the table you just created, and sleep if there is in a loop.


Q: Likelihood ratio test Problem 47, pg 296 from Jun Shao: Mathematical statistics
Let $(X_1, \dots, X_n)$ be a random sample from $N(\mu, \sigma^2)$. Suppose that $\sigma^2 = \gamma \mu^2$ with unknown $\gamma >0$ and $\mu \in \mathbb{R}$. Find likelihood ratio test for testing $H_0: \gamma=1$ vs. $H_1: \gamma\neq 1$
I first found the MLE for both $\mu$ and $\gamma$: $\hat{\mu}=\frac{1}{n}\sum_{i=1}^n X_i$ and $\hat{\gamma} = \frac{\frac{1}{n}\sum_{i=1}^n (X_i-\bar{X})^2}{\bar{X}^2}$.
The $LR(\theta_0) = 2 \Bigg(L(\hat{\theta_n}) - L(\theta_0)\Bigg) \sim \chi^2(1)$ as $n \to \infty$.
My log-likelihood is $$L(\mu,\gamma) = -n \log\sqrt{2\pi} -n \log \sqrt{\gamma} - n \log{\mu} - \frac{\sum_{i=1}^n (X_i-\mu)^2}{2 \mu^2 \gamma}$$
I plug everything $(\gamma_0=1)$ in and end up with
$$|LR(\gamma_0)| =| 2 \Bigg(L(\hat{\gamma_n})- L(\gamma_0)\Bigg)|= | n \log \Bigg(\frac{\frac{1}{n}\sum_{i=1}^n (X_i-\bar{X})^2}{\bar{X}^2} \Bigg) - n + \frac{\sum_{i=1}^n (X_i-\bar{X})^2}{\bar{X}^2}| > \chi^2(1,\alpha)$$
Is my analysis correct? (It's a different approach than the book is presenting)


Q: take minus(-) sign number from sting and use in in different procedure I have variable
DECLARE @Routs NVARCHAR(1024)
@i int
SET @Routs = N'6,4,-5,8'

I need to extract  any number from this sting, where it have minus sign before it  (-5 in example)
and use it as input parameter with out (-) sing for example @i in different stored procedure.

A: Pass in you're @Routs parameter to a table valued function that will split the list into a table and then loop through the table and if the value is a negative number execute stored procedure or whatever you want or do nothing if its not negative.
--table function to split parameter by comma
ALTER FUNCTION [dbo].[SplitListOfInts] (@list nvarchar(MAX))
RETURNS @tbl TABLE (number int NOT NULL) AS
BEGIN
DECLARE @pos        int,
       @nextpos    int,
       @valuelen   int

if len(rtrim(@list)) > 0
begin

   SELECT @pos = 0, @nextpos = 1

   WHILE @nextpos > 0
   BEGIN
      SELECT @nextpos = charindex(',', @list, @pos + 1)
      SELECT @valuelen = CASE WHEN @nextpos > 0
                              THEN @nextpos
                              ELSE len(@list) + 1
                         END - @pos - 1
      INSERT @tbl (number)
         VALUES (convert(int, substring(@list, @pos + 1, @valuelen)))
      SELECT @pos = @nextpos
   END
  end

  RETURN
 END

-- stored procedure that calls that split function and uses @routs parameter
  CREATE TABLE #values(nbrValue int)
 INSERT INTO #values(nbrValue
 EXEC [dbo].[SplitListOfInts] @routs

--if you don't care about non-negatives delete them here
 DELETE FROM #values
 where nbrValue >= 0

DECLARE @i int
DECLARE @countrows = (SELECT COUNT(nbrValue) FROM #values)

WHILE @countrows >0
SET @i = (SELECT TOP 1 nbrValue FROM #values)

...do what you want
DELETE FROM #values where nbrValue=@i
set @countrows = (SELECT COUNT(nbrValue) FROM #values)
END


Q: Mock lodash .isEqual Nodejs Jest Framework Super Test I am bit stuck testing lodash library lodash library using jest and super test
A.routes.js
import express from 'express';
const router = express.Router();
const _ = require('lodash');
router.post('/', async (req, res, next) => {
    try {
      let data = req.body
      if(!_.isEqual(data,{"hello":"hello"}){
               console.log('Not Equal') // This line is not getting covered in Code Coverage
            }
     }.catch(e=>{
      console.log(e);
  })
});

export default router;

A.route.test.js
import a from 'A.route'
import express from 'express';
import supertest from 'supertest';
let _ = require('lodash');

_.isEqual = jest.fn();

describe('API Calls', () => {
    const app = express();
    let request;

    beforeAll(() => {
        request = supertest(app);
    });

    beforeEach(()=>{
        jest.resetModules();
    });

test('Successful call to post /', async () => {
        const body= {
            "Hello": "Not Hello"
        };

        _.isEqual.mockResolvedValueOnce(false);
        await request.post('/')
            .set('Content-Type', 'application/json')
            .set('Authorization', 'authToken')
            .send(body);

    });
});

Code coverage is not able to cover console.log('Not Equal');I tried with _.isEqual.mockImplementation (()=>return false); also tried with _.isEqual.mockReturnValueOnce(false)

A: You should test the behaviour of this API. This means you should care about the response rather than the implementation details. You should pass in an input, such as req.body, to assert whether the result is in line with your expectations.
Since your code cannot be executed, I will arbitrarily add some code to demonstrate
E.g.
a.router.js:
import express from 'express';
const router = express.Router();
const _ = require('lodash');

router.use(express.json());
router.post('/', async (req, res, next) => {
  try {
    let data = req.body;
    console.log('data: ', data);
    if (!_.isEqual(data, { hello: 'hello' })) {
      res.send('Not Equal');
    } else {
      throw new Error('Equal');
    }
  } catch (e) {
    res.send(`Error: ${e.message}`);
  }
});

export default router;

a.router.test.js:
import a from './a.router';
import express from 'express';
import supertest from 'supertest';

describe('API Calls', () => {
  const app = express();
  let request;

  beforeAll(() => {
    app.use(a);
    request = supertest(app);
  });

  test('Successful call to post /', async () => {
    const body = {
      Hello: 'Not Hello',
    };
    const res = await request
      .post('/')
      .set('Content-Type', 'application/json')
      .set('Authorization', 'authToken')
      .send(body);
    expect(res.text).toEqual('Not Equal');
  });

  test('should handle error', async () => {
    const body = {
      hello: 'hello',
    };
    const res = await request
      .post('/')
      .set('Content-Type', 'application/json')
      .set('Authorization', 'authToken')
      .send(body);
    expect(res.text).toEqual('Error: Equal');
  });
});

test result:
 PASS  examples/67536129/a.router.test.js (8.606 s)
  API Calls
    ✓ Successful call to post / (48 ms)
    ✓ should handle error (5 ms)

  console.log
    data:  { Hello: 'Not Hello' }

      at examples/67536129/a.router.js:9:13

  console.log
    data:  { hello: 'hello' }

      at examples/67536129/a.router.js:9:13

-------------|---------|----------|---------|---------|-------------------
File         | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-------------|---------|----------|---------|---------|-------------------
All files    |     100 |      100 |     100 |     100 |
 a.router.js |     100 |      100 |     100 |     100 |
-------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        9.424 s


Q: Dynamicly adding paramteters to an ajax call based on a variables state I have an ajax call that has a list of parameters that it needs to pass to its data object. But this list changes based on a certain category. So I'm trying to find a way to filter through the ones I need and the ones I don't need.
$.ajax({
    url:'......',
    type:'post',
    dataType:'json',
    data: {
        'api': 'myApilist',
        'address' : 'someaddress',
        'callTime' : _this.get('calltime'),
        'id1' : _this.get('id1'),
        'id2' : _this.get('id2'),
        'type' : _this.get('type'),
        'options': _this.get("options"),
        'mode' : _this.get('mode'),
        'time' : _this.get('time')
        'method' : 'POST'
    },

Sometimes id1 and id2 are not needed based on a state I have setup. So if the state="time" then the id1 and id2 don not need to be part of the data list. And if the state="id" then both ids need to be in there.
I was trying to use the filter loops in _underscore to try and filter out these options based on my state but it didn't work as I don't understand them correctly. How would I go about this.
_this.get("options") is referring to a Backbone model.

A: You have to build your data string before you pass it in the ajax call. This is one way you can do:
var dynData = new Object();
dynData.api = <value>;
dynData.address = <value>;

Looks static as of now. Now based on your 'state', you can add properties to the javascript object on the fly using the following:
dynData["newProperty"] = <value>;

Now using JSON and json2.js, you can create your JSON string using:
data:JSON.stringify(dynData);

Mark as answer if this worked :)


Q: PHP - UTF8 problem with German characters I'm at my wits end with this one, then I remember stack overflow.
I have a site, http://bridgeserver3.co.uk/disklavier/de/ , the language is stored in a simple PHP file which looks like..
$translations["welcome_text_3"]="Zum Lieferumfang eines jeden Disklaviers gehren bereits zahlreiche Lieder und das Angebot lsst sich jederzeit erweitern. Unsere neuen Modelle warten sowohl mit akustischen als auch mit digitalen Errungenschaften auf, darunter die Wiedergabe von Audio- und MIDI-CDs sowie die revolutionre ãPianoSmartªÓ-Funktion fr die Synchronisation Ihrer Klavieraufzeichnungen mit handelsblichen Audio-CDs. Und wenn Sie schon eine Weile davon trumen, eines Tages zumindest passabel Klavier spielen zu knnen, hilft Ihnen die neue ãSmartKeyªÓ-Technologie beim Einstudieren Ihrer ersten Stcke und versieht Ihr Spiel sogar mit professionellen Verzierungen.";

(The characters show up perfectly in the file, but not on SO).
This text was exported from an excel spreadsheet and the flat file created manually.
The page encoding is UTF8, and I've added:
header("Content-type: text/html; charset=UTF-8");

to the php file, yet when I echo out the string it lose the German characters.
Can anyone offer any tips?
James

A: I found the problem...
Excel exported the text with Windows encoding, so it looked correct even in TextMate on my mac. When I reopen with UTF8 encoding the problem was visible in the translations file.
To resolve I used EditPadPro on a PC to convert to UTF8.
Phew.

A: Maybe you could try adding this inside your <head> tag?
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

A: I use Coda but I think textmate has to offer some option like Text->Encoding->Unicode UTF-8, activate it and then your file will be encoded properly and then save it.
Anyway if you are going to put some forms and you are not sure the people is using the correct encoding mode you'll have the same problem.
Use something like this:
<?php

$not_utf8 = "An invalid string"; //Put here the bad text for testing
$not_utf8 = mb_convert_encoding($not_utf8, 'UTF-8', mb_detect_encoding($not_utf8));

echo htmlspecialchars($not_utf8, ENT_QUOTES, 'UTF-8'); //The output should be ok, see the source code generated and search for the correct html entities for these special chars

?>

Hope this help you!
Luis.

A:
The page encoding is UTF8, and I've added:

Probably not. Make sure that the php file is actually saved with utf-8 encoding.


Q: How to assign names to dynamically generated text boxes and retrieve their values? I have dynamically generated textboxes. I want to assign names and id to the textboxes and also retrieve the values of dynamically generated textboxes to insert into database. How can it be done?

<select id="sel2" multiple>
<option value="first">first option</option>
<option value="second">sec option</option>
<option value="third">third option</option>
<option value="fourth">fourth option</option>
<option value="fifth">fifth option</option>
<option value="sixth">six option</option>
</select>

<button id="add" value="Add">Add</button>

A: Try like below , It will help you...
$("#tab2 tbody").append("
"+selectval[i]+"	<input type='text' id='text" + i + "' />
");

It will generate Id like text0, text1, text2...
To Get the value from the Text box add the below codes and try it...
Fiddle Example : http://jsfiddle.net/RDz5M/4/
HTML :

<button id="Get" value="Get">Get</button>

JQuery :
$("#Get").click(function(){
$('#tab2 tr').each(function(){
    $("#divResult").html($("#divResult").html() + ($(this).find("input[id^='text']").val()) + "
")
});
});


Q: Massive inserts kill arangod (well, almost) I was wondering of anyone has ever encountered this:
When inserting documents via AQL, I can easily kill my arango server. For example
FOR i IN 1 .. 10
  FOR u IN users
    INSERT {
        _from: u._id,
        _to: CONCAT("posts/",CEIL(RAND()*2000)),
        displayDate: CEIL(RAND()*100000000)
    } INTO canSee

(where users contains 500000 entries), the following happens

*

*canSee becomes completely locked (also no more reads)

*memory consumption goes up

*arangosh or web console becomes unresponsive

*fails [ArangoError 2001: Could not connect]

*server is still running, accessing collection gives timeouts

*it takes around 5-10 minutes until the server recovers and I can access the collection again

*access to any other collection works fine

So ok, I'm creating a lot of entries and AQL might be implemented in a way that it does this in bulk. When doing the writes via db.save method it works but is much slower.
Also I suspect this might have to do with write-ahead cache filling up.
But still, is there a way I can fix this? Writing a lot of entries to a database should not necessarily kill it.
Logs say
DEBUG [./lib/GeneralServer/GeneralServerDispatcher.h:411] shutdownHandler called, but no handler is known for task

DEBUG [arangod/VocBase/datafile.cpp:949] created datafile '/usr/local/var/lib/arangodb/journals/logfile-6623368699310.db' of size 33554432 and page-size 4096

DEBUG [arangod/Wal/CollectorThread.cpp:1305] closing full journal '/usr/local/var/lib/arangodb/databases/database-120933/collection-4262707447412/journal-6558669721243.db'

bests

A: The above query will insert 5M documents into ArangoDB in a single transaction. This will take a while to complete, and while the transaction is still ongoing, it will hold lots of (potentially needed) rollback data in memory.
Additionally, the above query will first build up all the documents to insert in memory, and once that's done, will start inserting them. Building all the documents will also consume a lot of memory. When executing this query, you will see the memory usage steadily increasing until at some point the disk writes will kick in when the actual inserts start.
There are at least two ways for improving this:

*

*it might be beneficial to split the query into multiple, smaller transactions. Each transaction then won't be as big as the original one, and will not block that many system resources while ongoing.

*for the query above, it technically isn't necessary to build up all documents to insert in memory first, and only after that insert them all.  Instead, documents read from users could be inserted into canSee as they arrive. This won't speed up the query, but it will significantly lower memory consumption during query execution for result sets as big as above. It will also lead to the writes starting immediately, and thus write-ahead log collection starting earlier. Not all queries are eligible for this optimization, but some (including the above) are. I worked on a mechanism today that detects eligible queries and executes them this way. The change was pushed into the devel branch today, and will be available with ArangoDB 2.5.


Q: smartfield annotation - valuehelp dropdown I have a value help field and want to see only descriptions (not codes) in the dropdown. After selection, want to store the code in another field which would be in hidden mode. For this, I have defined the following annotation:
<Annotations Target="Metadata.CallReport/DivisionText">
  <Annotation Term="Common.ValueList">
    <Record Type="Common.ValueListType">
      <PropertyValue Property="CollectionPath" String="CustomizingDivisionSet" />
      <PropertyValue Property="Parameters">
        <Collection>
          <Record Type="Common.ValueListParameterOut">
            <PropertyValue Property="LocalDataProperty" PropertyPath="DivisionText" />
            <PropertyValue Property="ValueListProperty" String="Text" />
          </Record>
          <Record Type="Common.ValueListParameterOut">
            <PropertyValue Property="LocalDataProperty" PropertyPath="Division" />
            <PropertyValue Property="ValueListProperty" String="Value" />
          </Record>
        </Collection>
      </PropertyValue>
      <PropertyValue Property="SearchSupported" Bool="false" />
    </Record>
  </Annotation>
</Annotations>

And the view definition..
<!-- ... -->
<smartField:SmartField textLabel="Division" value="{DivisionText}">
  <smartField:configuration>
    <smartField:Configuration controlType="dropDownList" displayBehaviour="descriptionOnly" />
  </smartField:configuration>
</smartField:SmartField>
<!-- ... -->

Everything works fine; the code for the description I have selected is copied to Division field. However, when I change this dropdown field, the selection works, but the code does not get copied to Division field.


Q: Does this sentence violate the 'be nice' policy? In a chat at a site where an election was held, they were commenting the fact that only half of the members who visited the polls (earning the Caucus badge) had gotten the Constituent badge, and therefore actually cast a ballot.

*

*one user explained it saying: "..they couldn't find a palatable candidate"

*another wrote: "...It's better to not vote than to elect somebody who will do damage"
This site is frequented by mods of many SE sites. Can you tell me if that policy is implemented with same strictness on all sites and chat-rooms and if there is any chance the above chat messages may be considered offensive or inappropriate, and, if reported, a censure to their authors might ensue?
I take (the votes mean) that nobody thinks the above statements are inappropriate and they should not possibly be sanctioned.

A: I'm not a moderator on any site, but spent a while around and learned a thing or two.
From my experience, and own point of view, such a sentence is valid in chat:

*

*It's not directed towards any specific person.

*It's just a general statement that is result of frustration, and said in context of the elections.

Actually even saying something like "I believe John Doe will cause damage as a moderator" is valid in my opinion, it's part of having elections: people should be allowed to express their feelings. It's not saying "John Doe is stupid", which is indeed invalid.


Q: iOS location icon everyone. I don't know whether you used app name Moves or not. If not,you can to download from app store. And you can find a issue, that display gps icon in status bar always(even though app was killed). At "Setting-privacy-location service",if you turn off the app,icon disappear. Turn on again, icon purple display. Why purple display,app is updating location?

A: If an app uses, for example, significant change service, the icon stays on even if the app is killed (because with significant change service, the app will be automatically re-awaken when iOS determines that a significant change has taken place; i.e. the iOS is effectively still tracking your location on behalf of the app, even though the app has been manually terminated). This is the documented behavior of significant change service, which, while less accurate than can be rendered by standard location services, continues tracking you even after the app has been terminated. The purple icon of location services won't be turned off until the app explicitly disables significant change service, or the app has been uninstalled.


Q: Possible to retrieve selected children list from database only by using JPA/Hibernate-Annotation? Guess this might be a difficult one. Well, at least for me. I need some help with JPA/Hibernate-Annotations and I was wondering, if there is a way to solve my problem. Unfortunately, my own skills seem too limited to solve that problem by myself. That's why I'm hoping to find anyone here who might have a good grasp on jpa-annotations and relational databases (here: oracle).
Task:
I have three tables (see attached image! Please don't change this part, since the tables aren't supposed to be created! They already exist with exactly these names, may not be changed and the primary key + foreign key part is just to provide more information about these already existing tables that I uploaded here as an image! Thank you.):
CONSTANT (PRIMARY KEY CONSTANT(ID) + FOREIGN KEY (PARENT_CONSTANT_ID) REFERENCES CONSTANT(ID)),
COUNTRY (PRIMARY KEY COUNTRY(ID)),
COUNTRY_TO_CONSTANT (PRIMARY KEY COUNTRY_TO_CONSTANT(COUNTRY_ID, CONSTANT_ID))

as shown here: Tables-Image
Java-Beans look like that:
Constant.java
@Id
@Column(name = "ID")
private Integer id;

@Basic
@Column(name = "CODE")
private String code;

@Basic
@Column(name = "SORT_KEY")
private int sortKey;

@ManyToOne
@JoinColumn(name = "CONSTANT_TYPE_ID", referencedColumnName = "ID")
private ConstantType constantType;

@ManyToOne
@JoinColumn(name = "parent_constant_id", referencedColumnName = "ID")
private Constant parent;

@OneToMany(mappedBy = "parent", targetEntity = Constant.class)
private List children;

...

public Collection<Constant> getChildren() {
    return children;
}

CountryToConstant.java
@Id
@Basic
@Column( name = "COUNTRY_ID" )
private Integer countryID;

@Id
@Basic
@Column( name = "CONSTANT_ID" )
private Integer constantID;

Country.java
@Id
@Column( name = "ID" )
@SequenceGenerator( name = "CountrySequence", sequenceName = "COUNTRY_ID_SEQ" )
@GeneratedValue( generator = "CountrySequence" )
private Integer id;

@Basic
@Column( name = "CODE" )
private String code;

@Basic
@Column( name = "NAME" )
private String name;

@Basic
@Column( name = "LANGUAGE_CODES" )
private String languageCodes;

I left out all getters + setters for brevity except for the constant.java-getter of the 'children'-attribute, since this is the only getter needed for this issue. To make it more difficult: The structure of the java-beans shown above may not be changed, but is allowed to be expanded. This is due to not destroying the already existing (very complex) programm structure.
private List children (Constant.java) is mapped by the attribute private Constant parent. Let's assume that by the other program logic a list with 'parent' CONSTANT ids (e.g. id = {11, 12}) is used here to iterate through and handed over one after another to create 1 parent-object. As a result this will create one private List children after another. Therefore, the result of the example would be 2 separate children lists due to the iteration:

*

*parent-id 11 -> children-id-list: {111, 112, 113, 114, 115, 116}

*id 12 -> id-list: {121, 122, 123}) for each parent-object.

What I need to get instead is a specific list corresponding to the COUNTRY_TO_CONSTANT table, only by using annotations. For example: If the person uses a browser in Germany, the locale is set to de_DE resulting in the COUNTRY.id '1001'. And based (only) on the country code (not the locale), the result for the iteration example above (CONSTANT.id = {11, 12}) should be these two lists:

*

*parent-id 11 -> children-id-list: {111, 112, 113} (leaving out constant-id 114, 115, and 116)

*parent-id 12 -> children-id-list: {121} (leaving out constant-id 122, and 123)

Idea is that depending on the country code and the CONSTANT.IDs put in the table COUNTRY_TO_CONSTANT, every list is created individually corresponding to the related database entries.
Since private List children cannot be changed in definition, what I need is a second attribute (e.g. private List children2) that works exactly like private List children with the only difference that only the country related children (see COUNTRY_TO_CONSTANT table) should be mapped by private Constant parent.
I was thinking about something like:
@OneToMany(mappedBy = "parent", targetEntity = Constant.class)
//Any annotation to get what I need.
private List children2

or maybe:
@ManyToMany(mappedBy = "children", targetEntity = Constant.class)
//Any annotation to get what I need.
private Set children2

Is that even possible to achieve just by using annotations?
Hope, things are clearly explained so far. If not, what kind of workaround could I use here? If any info is missing, please let me know.
Thanks a lot.


Q: One site with 2 different physical paths (2 different subfolders) is it possible to that I can configure a site in IIS Manager with two different physical paths (2 subfolders)?
Thank you ;-)

A: No, you can only specify one path for the site, that is the path for loading the site's default document and configuration file (web.config) etc. But you can add multiple virtual directory for the website.


Q: Non-generators of $A_n$ It is known that all alternating groups $A_n$ can be generated by 2 elements, this goes back to 1901 (Miller). Moreover, the long lasting conjecture by Netto that the probability that 2 elements of $A_n$ chosen uniformly at random generate the whole of $A_n$ tends to $1$ as $n \rightarrow \infty$ was proved some 40 years ago by Dixon. So almost all pairs of elements from $A_n$ generate $A_n$.
In the case $n=5$, what's the easiest way of finding all the pairs of elements which do NOT generate the whole group?

A: This is a pretty easy method: I just asked GAP. :-)
It computes conjugacy classes of non-generators. It displays their size, the group they generate (instead of A5), and representatives of the generators. About 36% of pairs are non-generators.
``
gap> non:=Filtered(Combinations(AsSet(AlternatingGroup(5)),2),x->Size(Group(x))<60);;
gap> orbs:=Orbits(AlternatingGroup(5),non,OnSets);;
gap> PrintArray(List(orbs,o->[Size(o),o[1]]));
[ [ 20,      C3,               [ (), (3,4,5) ] ],
  [ 15,      C2,            [ (), (2,3)(4,5) ] ],
  [ 12,      C5,           [ (), (1,2,3,4,5) ] ],
  [ 12,      C5,           [ (), (1,2,3,5,4) ] ],
  [ 10,      C3,          [ (3,4,5), (3,5,4) ] ],
  [ 60,      A4,       [ (3,4,5), (2,3)(4,5) ] ],
  [ 60,      A4,          [ (3,4,5), (2,3,4) ] ],
  [ 30,      A4,          [ (3,4,5), (2,3,5) ] ],
  [ 60,      S3,       [ (3,4,5), (1,2)(4,5) ] ],
  [ 60,      A4,       [ (3,4,5), (1,3)(4,5) ] ],
  [ 30,      A4,          [ (3,4,5), (1,3,5) ] ],
  [ 15, C2 x C2,    [ (2,3)(4,5), (2,4)(3,5) ] ],
  [ 30,      S3,    [ (2,3)(4,5), (1,2)(4,5) ] ],
  [ 30,     D10,    [ (2,3)(4,5), (1,2)(3,4) ] ],
  [ 30,     D10,    [ (2,3)(4,5), (1,2)(3,5) ] ],
  [ 60,     D10,   [ (2,3)(4,5), (1,2,4,5,3) ] ],
  [ 60,     D10,   [ (2,3)(4,5), (1,2,5,4,3) ] ],
  [ 12,      C5,  [ (1,2,3,4,5), (1,3,5,2,4) ] ],
  [ 12,      C5,  [ (1,2,3,4,5), (1,4,2,5,3) ] ],
  [  6,      C5,  [ (1,2,3,4,5), (1,5,4,3,2) ] ],
  [  6,      C5,  [ (1,2,3,5,4), (1,4,5,3,2) ] ] ]

A: According to Maple, there are $630$ such pairs in $A_{5}$.
> with( GroupTheory ):
> L := select( gens -> GroupOrder( Group( gens ) ) < 60, combinat:-choose( Elements( Alt( 5 ) ), 2 )  ):
> nops( L );
                  630

> L[ 1 ];
            {1,  (3, 4, 5)}

> L[ 2 ];
        { (3, 4, 5),  (1, 3, 4)}

You could do an equivalent computation in other computer algebra systems like GAP or Magma.


Q: NSWindowFlipper build error I am trying to use Mizage's window flipper library in my Mac app.
When I tried to build it, the following error occurs:
Undefined symbols for architecture x86_64:
"_kCAGravityCenter", referenced from:
  -[NSWindow(Flipper) flipWithArguments:] in NSWindowFlipper.o
"_CATransform3DMakeRotation", referenced from:
  -[NSWindow(Flipper) flipWithArguments:] in NSWindowFlipper.o
"_kCAMediaTimingFunctionEaseInEaseOut", referenced from:
  -[NSWindow(Flipper) flipWithArguments:] in NSWindowFlipper.o
"_CATransform3DIdentity", referenced from:
  -[NSWindow(Flipper) flipWithArguments:] in NSWindowFlipper.o
"_CATransform3DRotate", referenced from:
  -[NSWindow(Flipper) flipWithArguments:] in NSWindowFlipper.o
"_OBJC_CLASS_$_CALayer", referenced from:
  objc-class-ref in NSWindowFlipper.o
"_OBJC_CLASS_$_CABasicAnimation", referenced from:
  objc-class-ref in NSWindowFlipper.o
"_OBJC_CLASS_$_CAMediaTimingFunction", referenced from:
  objc-class-ref in NSWindowFlipper.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

My base SDK is 10.7 and have ARC enabled. I am new to Cocoa and have not seen this kind of error before. Can someone suggest what's the problem here and possibly how to resolve it? Thanks.

A: You need to link with the QuartzCore framework.
Linking to a Library or Framework


Q: Selecting an intersection with a fixed given percentage between two tables I working with PostgreSQL and I have two tables:
Serieses
SeriesID
716
718
214
210

Viewers
ViewID    SeriesID
10          716
12          718
10          718
15          770
10          210
12          214
12          210

How can I create a query which for each viewer if it has series intersection more than 70% with table serieses I add it to the final result?
In our example we will get:
Result:
ViewerID
10
12

A: NOT tested in Postgres, but it should be similar to:
SELECT V.ViewerID
FROM   Viewers AS V
GROUP BY V.ViewerID
HAVING CAST(COUNT(*) AS NUMERIC)
       >
       (0.7 * CAST((SELECT COUNT(*) FROM Serieses) AS NUMERIC))

A: I did the following:
Created the tables:
CREATE TABLE my_series
(
  series_id INTEGER NOT NULL
);

CREATE TABLE viewer
(
  view_id INTEGER NOT NULL,
  series_id INTEGER NOT NULL,
  CONSTRAINT viewer_pk PRIMARY KEY (view_id, series_id)
);

Input your sample data:
INSERT INTO my_series VALUES (210), (214), (716), (718), (770);
INSERT INTO viewer VALUES (10, 210), (10, 716), (10, 718), (12, 210), (12, 214), (12, 718);

Ran the following query:
SELECT v.view_id, COUNT(v.view_id) AS "View count"
FROM viewer v
GROUP BY v.view_id
HAVING COUNT(v.series_id) >= 0.70 * (SELECT COUNT(*) FROM my_series)

-- >= 0.7 * COUNT = a threshold of 70% as per the question

Result:
view_id View count
     10          3
     12          3

All this is available at the fiddle here!
For future reference, you are more likely to get better and faster answers if you provide a fiddle. It also reduces the chances of errors (either with data input or answers) on our part and helps reduce duplication of work. These sites are a  great resource and you will get all the more out them if you take the trouble to follow the guidelines.


Q: RegEx multiple steps in ruby Given the string below:
"oxcCFC/video.mp4 "GET /accounts/6/videos/xboxcCFC/video.mp4 HTTP/1.1" 206 - 2 697898511 56 56 "-""

How would I create a regular expression that first finds "HTTP, then finds "-", and then captures the next indiviual number or consecutive numbers that occurs in the sequence?
I'm trying to use rubular but struggling big time.

A: Not a lot to go on, but I think it should be something like this:
/^.*\s+HTTP.*\s+-\s+(\d+)\s+/

A backreference will then hold the value you're after.

A: I'd see if you can use the apachelogregex gem... http://rubydoc.info/gems/apachelogregex/0.1.0/frames

A: Short answer: /HTTP[^-]*-([\d\s]+)/
then, call split on the result.
This regexp translates to:
"HTTP", followed by any number of non-hyphen characters, followed by a hyphen, followed by the largest string consisting only of digits and spaces.


Q: Why do I get this NullReferenceException C# I've been working in some codes for an application to manage connected users and Equipments via Active directory queries.
Then I get this error "NullReferenceException was unhandled" for about a week, working with the code this is the only thing stopping the application now.
And this is the code of the background worked I used:
private void backgroundWorker2_Dowork(object sender, DoWorkEventArgs e)
{
    try
    {
        e.Result = "";

        int val = 6000;

        for (int a = 1; a <= val; a++)
        {
            counter.Text = Convert.ToString(a);
            if (txtWorkGroupName.Text == "") return;

            DataTable dt = new DataTable();
            dt.Clear();

            dt.Columns.Add(new DataColumn("ComputerName", typeof(String)));                        //0
            dt.Columns.Add(new DataColumn("IP", typeof(String)));            //1
            dt.Columns.Add(new DataColumn("MAC", typeof(String)));       //2
            dt.Columns.Add(new DataColumn("Descubierto", typeof(String)));       //3
            //int i = 0;

            try
            {
                // Datos del grupo WinNT://&&&&(Nombre del grupo de trabajo)
                DirectoryEntry DomainEntry = new DirectoryEntry("WinNT://" +  txtWorkGroupName.Text + "");
                DomainEntry.Children.SchemaFilter.Add("Computer");

                ///*************************************************
                /// Interacting with pc's in the domain
                ///*************************************************

                foreach (DirectoryEntry machine in DomainEntry.Children)
                {
                    string strMachineName = machine.Name;
                    string strMACAddress = "";
                    IPAddress IPAddress;
                    DateTime discovered;

                    try
                    {
                        IPAddress = getIPByName(machine.Name);
                    }
                    catch
                    {
                        continue;
                    }//try/catch

                    ///*************************************************
                    /// Get Mac
                    ///*************************************************
                    strMACAddress = getMACAddress(IPAddress);

                    discovered = DateTime.Now;
                    ///*************************************************
                    /// Add lines in the grid
                    ///*************************************************

                    DataRow dr = dt.NewRow();

                    dr[0] = machine.Name;
                    dr[1] = IPAddress;
                    dr[2] = strMACAddress;
                    dr[3] = Convert.ToString(discovered);
                    dt.Rows.Add(dr);

                ///*************************************************
                /// SETTING DATASOURCE
                ///*************************************************
                    dgvComputers1.DataSource = dt;

                    Thread.Sleep(2000);

                }//foreach loop

            catch (Exception ex)
            {
                {
                    MessageBox.Show(ex.Message);
                }
            }

            if (backgroundWorker2.CancellationPending)
            {
                e.Cancel = true;
                return;
            }
        }
    }
    catch (NullReferenceException ex)
    {
        MessageBox.Show("error:" + ex);
    }
    catch (NoNullAllowedException ex)
    {
        MessageBox.Show("error:" + ex);
    }
    catch (AccessViolationException ex)
    {
        MessageBox.Show("error:" + ex);
    }
}

This is the exception details, sorry that they are in Spanish.
    System.NullReferenceException was unhandled
    Message="Object reference not set to an instance of an object."
      Source="System.Windows.Forms"
    StackTrace:
   en System.Windows.Forms.DataGridViewRowHeaderCell.PaintPrivate(Graphics graphics,   Rectangle clipBounds, Rectangle cellBounds, Int32 rowIndex, DataGridViewElementStates dataGridViewElementState, Object formattedValue, String errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts, Boolean computeContentBounds, Boolean computeErrorIconBounds, Boolean paint)
   en System.Windows.Forms.DataGridViewRowHeaderCell.Paint(Graphics graphics, Rectangle  clipBounds, Rectangle cellBounds, Int32 rowIndex, DataGridViewElementStates cellState,  Object value, Object formattedValue, String errorText, DataGridViewCellStyle cellStyle,  DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
   en System.Windows.Forms.DataGridViewCell.PaintWork(Graphics graphics, Rectangle  clipBounds, Rectangle cellBounds, Int32 rowIndex, DataGridViewElementStates cellState,  DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle,   DataGridViewPaintParts paintParts)
   en System.Windows.Forms.DataGridViewRow.PaintHeader(Graphics graphics, Rectangle  clipBounds, Rectangle rowBounds, Int32 rowIndex, DataGridViewElementStates rowState,   Boolean isFirstDisplayedRow, Boolean isLastVisibleRow, DataGridViewPaintParts paintParts)
   en System.Windows.Forms.DataGridViewRow.Paint(Graphics graphics, Rectangle clipBounds, Rectangle rowBounds, Int32 rowIndex, DataGridViewElementStates rowState, Boolean isFirstDisplayedRow, Boolean isLastVisibleRow)
   en System.Windows.Forms.DataGridView.PaintRows(Graphics g, Rectangle boundingRect, Rectangle clipRect, Boolean singleHorizontalBorderAdded)
   en System.Windows.Forms.DataGridView.PaintGrid(Graphics g, Rectangle gridBounds, Rectangle clipRect, Boolean singleVerticalBorderAdded, Boolean singleHorizontalBorderAdded)
   en System.Windows.Forms.DataGridView.OnPaint(PaintEventArgs e)
   en System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer, Boolean disposeEventArgs)
   en System.Windows.Forms.Control.WmPaint(Message& m)
   en System.Windows.Forms.Control.WndProc(Message& m)
   en System.Windows.Forms.DataGridView.WndProc(Message& m)
   en System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   en System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   en System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   en System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   en       System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.        IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
   en System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason,   ApplicationContext context)
   en System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   en System.Windows.Forms.Application.Run(Form mainForm)
   en NetworkScanner.Program.Main() en C:\Project Sigma 6\New Power  move\discover\Program.cs:línea 17
   en System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
   en System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   en Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   en System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   en System.Threading.ExecutionContext.Run(ExecutionContext executionContext,  ContextCallback callback, Object state)
   en System.Threading.ThreadHelper.ThreadStart()

A: It's a multithreading issue. At some point you're trying to change the datasource of your datagrid at the exact same time it's painting itself on screen.
 dgvComputers1.DataSource = dt;

Try replacing that by:
 this.Invoke(delegate(DataTable table)
 {
     dgvComputers1.DataSource = table;
 }, dt);

A: Have you tried this?
dr[1] = IPAddress ?? "(unknown)";

A: Try putting a breakpoint in (if you are using Visual Studio) and checking each line and see where the error occurs.
Then, after getting to the line, check in the watch window to see what is null.
Then go: if(nullThing == null) return; before the line where the error occurs, of course, you shouldn't always do this, but find out WHY it is null, and sort it out.
That should do the job.

A: Check this out:
`private void backgroundWorker2_Dowork(object sender, DoWorkEventArgs e)

Delete that
`

It should be:
private void backgroundWorker2_Dowork(object sender, DoWorkEventArgs e)


Q: netlify-function Netlify functions is one of the services offered in the Netlify platform.
It uses AWS's serverless Lambda functions, but allows users to access them without an AWS account, and with management of the functions all done by Netlify. Netlify functions can be built with either JavaScript or Go.
Learn more about Netlify Functions and their abilities here.


Q: iPhone 4, only emergency calls I bought new Neverlock (sim free) iPhone 4 with 4.3.5 firmware. Then I would like to return it to factory settings and click "Restore" in iTunes. But after restoring i received unlocking device with "only emergency calls" message. What can i do now?

A: You bought one? From where? I ask because once you've restored in iTunes if it's a properly unlocked device it'll let you straight back in, emergency calls only means it's not been registered against a network, or unlocked.


Q: how to select columns from another dataframe , where these columns are list of value of column in different dataframe I am using spark-sql 2.3.1v with java8.
I have data frame like below
 val df_data = Seq(
  ("G1","I1","col1_r1", "col2_r1","col3_r1"),
  ("G1","I2","col1_r2", "col2_r2","col3_r3")
 ).toDF("group","industry_id","col1","col2","col3")
.withColumn("group", $"group".cast(StringType))
.withColumn("industry_id", $"industry_id".cast(StringType))
.withColumn("col1", $"col1".cast(StringType))
.withColumn("col2", $"col2".cast(StringType))
.withColumn("col3", $"col3".cast(StringType))

+-----+-----------+-------+-------+-------+
|group|industry_id|   col1|   col2|   col3|
+-----+-----------+-------+-------+-------+
|   G1|         I1|col1_r1|col2_r1|col3_r1|
|   G1|         I2|col1_r2|col2_r2|col3_r3|
+-----+-----------+-------+-------+-------+

val df_cols = Seq(
  ("1", "usa", Seq("col1","col2","col3")),
  ("2", "ind", Seq("col1","col2"))
 ).toDF("id","name","list_of_colums")
.withColumn("id", $"id".cast(IntegerType))
.withColumn("name", $"name".cast(StringType))

+---+----+------------------+
| id|name|    list_of_colums|
+---+----+------------------+
|  1| usa|[col1, col2, col3]|
|  2| ind|      [col1, col2]|
+---+----+------------------+

Question :
   As shown above I have columns information in "df_cols" dataframe.
   And all the data in the "df_data" dataframe.
   how can I select columns dynamically from "df_data" to the given id of "df_cols" ??

A: Initial question:
val columns = df_cols
  .where("id = 2")
  .select("list_of_colums")
  .rdd.map(r => r(0).asInstanceOf[Seq[String]]).collect()(0)

val df_data_result = df_data.select(columns(0), columns.tail: _*)

+-------+-------+
|   col1|   col2|
+-------+-------+
|col1_r1|col2_r1|
|col1_r2|col2_r2|
+-------+-------+

Updated question:
1) We may just use 2 lists: static columns + dynamic ones
2) I think that "rdd" is ok in this code. I don't know how to update to "Dataframe" only, unfortunately.
val staticColumns = Seq[String]("group", "industry_id")
val dynamicColumns = df_cols
  .where("id = 2")
  .select("list_of_colums")
  .rdd.map(r => r(0).asInstanceOf[Seq[String]]).collect()(0)

val columns: Seq[String] = staticColumns ++ dynamicColumns
val df_data_result = df_data.select(columns(0), columns.tail: _*)

+-----+-----------+-------+-------+
|group|industry_id|   col1|   col2|
+-----+-----------+-------+-------+
|   G1|         I1|col1_r1|col2_r1|
|   G1|         I2|col1_r2|col2_r2|
+-----+-----------+-------+-------+


Q: Open a new tab in a browser with the response to an ASP request It's a bit complicated this one...   Lets say I have a listing of PDF files displayed in the user's browser.  Each filename is a link pointing not to the file, but to an ASP page, say
<--a href="viewfile.asp?file=somefile.pdf">somefile.pdf

I want viewfile.asp to fetch the file (I've done that bit OK) but I then want the file to be loaded by the browser as if the user had opened the PDF file directly.  And I want it to open in a new tab or browser window.
here's (simplified) viewfile.asp:
<%
var FileID   = Request.querystring ("file") ;
var ResponseBody = MyGETRequest (SomeURL + FileID) ;

if (MyHTTPResult == 200)
    {
    if (ExtractFileExt (FileID).toLowerCase = "pdf")
        {
        ??????  // return file contents in new browser tab
        }
....
%>

A: As Daniel points out you can control whether to open in a new window but not a new tab.  If the user has configured their browser so that new windows should open in new tabs (like I do) then you're golden.  If not it will open in a new window.  You can't control tabs.

A: I would do this.
somefile.pdf

That way this opens in a new window/tab. Any server side language does not have control of the browser.
To serve it as a PDF, call
<% response.ContentType="application/pdf" %>


Q: Import an binary image with non-standard header I have binary images with an fixed sized header.
These can be converted into PGM images, provided cutting the header, and putting the appropriate information using linux/OSX tools as "head -c", "tail -c", and "cat". I can later import these images in Mathematica for further treatment.
I would like to create an importer in Mathematica as treated in the documentation which could do all this so the import can be done on a Windows station without using the linux/OSX tools.
I have not been able to manage this problem.
The only Idea I had is to use the functions BinaryReadList or BinaryRead. But since the information I get with them is not the same as what I get with ImageData[Import[file, "PGM"]]. I am stuck.
The difference can be directly verified with binread-module based an answer of Sjoerd C. de Vries. And also with a little code I wrote to show the difference on readable files
    (* PGM : filename for output *)

    PGM= "/Users/thomas/Documents/Mathematica/LM.pgm";
    Dim = {25,25};
    f[x_,y_]:=2^16*E^(-(2/3) (x^2-0.5` x y+0.25` y^2));

    (* Creating now an small Image *)

    LittleMat=IntegerPart[Array[f,Dim,{{-6,6},{-6,6}}]+1];
    (*LittleMat= RandomInteger[{1,2^16},Dim];*)
    ArrayPlot[LittleMat, ImageSize->{300,300},AspectRatio->Full]

    (* Exporting and re-importing the small Image *)

    Export[PGM,Image[LittleMat,"UnsignedInteger16"],"PGM"];
    ReImp = Import[PGM,"PGM"];
    RI = IntegerPart[2^16*ImageData[ReImp]];

    ArrayPlot[RI, ImageSize->{300,300},AspectRatio->Full]

    (* Information is luckily still the same *)
    (*LittleMat-RI*)

    (* Now reading the file binary, bitwise *)

    Bytestest = FileByteCount[PGM]
    N[Bytestest /(25*25)]

    (* Why is the ImageSize in bits twice the pixel-number? *)

    HeaderL = Bytestest -2*25*25

    stream=OpenRead[PGM,BinaryFormat -> True];
    SetStreamPosition[stream,HeaderL];
    MyPGM = BinaryReadList[stream,"UnsignedInteger16",ByteOrdering->-1];
    SetStreamPosition[stream,0];
    Close[stream];

    (* MyPGM list of the same size as pixel-number *)

    PGMmat = Partition[MyPGM,25];
    ArrayPlot[PGMmat, ImageSize->{300,300},AspectRatio->Full]

    (* Information not the same aby more *)

    ArrayPlot[PGMmat-RI, ImageSize->{300,300},AspectRatio->Full]

A: you are one byte off when you set stream position, and have the wrong byte ordering.
This makes it work:
SetStreamPosition[stream, HeaderL - 1];
MyPGM = BinaryReadList[stream, "UnsignedInteger16",
   ByteOrdering -> 1];

The combined errors happen to make every value < 256 correct, which makes the image look sort-of right.  I think 16 bit PGM is always big endian regardless of your file system.
just by the way you can directly request the integer data from ImageData as:
RI = ImageData[ReImp, "Bit16"];


Q: Writing from System.out.println to a file I've replaced many strings and outputted the result and now am trying to write those lines into a text file. Here's what I did. I created a new file:
File newfile = new File("/Users/Bill/Desktop/newfile.txt");
    if (newfile.exists()) {
        System.out.println("File exists");
    } else {
        newfile.createNewFile();
        System.out.println("New file created");

    }

And then I tried to write to the created file the result of System.out.println(lines[i]);
    try {
    WriteToFile newFile = new WriteToFile(newfile, true);
    newFile.write(lines[i]);
    // lines[i] is what I used to print out System.out.println(lines[i])
    }

    catch (IOException e) {
        System.out.println("Error.");
    }

I'm not getting what I'm expecting, though. Any suggestions?
WRITETOFILE:
public class WriteToFile {
private String path;
private boolean append = false;

public WriteToFile(String filename) {
    path=filename;
}

public WriteToFile(String filename, boolean appendfile){
    path=filename;
    append=appendfile;
}

public void write(String text) throws IOException {
    FileWriter filewrite = new FileWriter(path, append);
    PrintWriter print = new PrintWriter(filewrite);

    print.printf("%s" + "%n", text);
    print.close();
}
}

A: Every time you call WriteToFile.write, it reopens the file for writing, truncating the file's original contents. You should open the file once, in the constructor (and store the PrintWriter in a field), and add a close method that calls close for the PrintWriter.
On the calling side, do this:
WriteToFile writer = new WriteToFile(filename);
try {
    // writer.write(...);
} finally {
    writer.close();
}

By having the close call in a finally block, you ensure the file is closed even if an exception causes the function to quit early.

A: Look at the 2nd argument of the FileWriter constructor in your code.
FileWriter filewrite = new FileWriter(path, append);

See, it says "append". Guess what it does. Read the documentation if you're unsure.
Now, look how you initialized append.
private boolean append = false;

This code is fully behaving as expected. It's just a developer's fault. Fix it :)

A: Just set fileName on System using the method
System.setOut(fileName);
Then whenever we want to print using System.out.println() it will directly print to the fileName you mention.


Q: How to convert 32-bit tiff to 16-bit png? Grayscale displacement texture I need to convert 32bit tif to 16bit, but preserve all range of details.
I've tried convert -normalize, convert -depth 16, convert -depth 16 -normalize and it just gets rid of all the details and part of the texture is just black.
The image I got is here, displacement texture of the moon
Image:
  Filename: ldem_64.tif
  Format: TIFF (Tagged Image File Format)
  Mime type: image/tiff
  Class: DirectClass
  Geometry: 23040x11520+0+0
  Resolution: 100x100
  Print size: 230.4x115.2
  Units: PixelsPerInch
  Colorspace: Gray
  Type: Grayscale
  Endianness: LSB
  Depth: 32/16-bit
  Channel depth:
    Gray: 16-bit
  Channel statistics:
    Pixels: 265420800
    Gray:
      min: -597319  (-9.1145)
      max: 704960 (10.757)
      mean: -34039.6 (-0.519411)
      median: -52133.1 (-0.7955)
      standard deviation: 144682 (2.2077)
      kurtosis: 0.855997
      skewness: 0.540128
      entropy: 0.244393
  Rendering intent: Undefined
  Gamma: 0.454545
  Matte color: grey74
  Background color: white
  Border color: srgb(223,223,223)
  Transparent color: none
  Interlace: None
  Intensity: Undefined
  Compose: Over
  Page geometry: 23040x11520+0+0
  Dispose: Undefined
  Iterations: 0
  Compression: None
  Orientation: TopLeft
  Properties:
    comment: IDL TIFF file
    date:create: 2019-06-05T20:21:05+00:00
    date:modify: 2019-06-05T20:21:05+00:00
    date:timestamp: 2022-11-24T22:57:25+00:00
    quantum:format: floating-point
    signature: cb63f78e418cec4a32935a7eeb388c3dc541bf2ed95d46de2d35e70c2e3ad805
    tiff:alpha: unspecified
    tiff:document: ldem_64.tif
    tiff:endian: lsb
    tiff:photometric: min-is-black
    tiff:rows-per-strip: 1
    tiff:software: IDL 8.7.2, Harris Geospatial Solutions, Inc.
    tiff:timestamp: 2019:05:20 12:47:07
  Artifacts:
    verbose: true
  Tainted: False
  Filesize: 1012.59MiB
  Number pixels: 265.421M
  Pixel cache type: Memory
  Pixels per second: 59.0163MP
  User time: 3.672u
  Elapsed time: 0:05.497
  Version: ImageMagick 7.1.0-52 Q16-HDRI x64 04ee6ce:20221106 https://imagemagick.org

aodhasdoashdoasd cannot post the question cuz alot of "code"

A: I am not sure what you want, but perhaps just -auto-level in Imagemagick.
Input:
I downloaded a smaller version, ldem_4.tif (1440x720) and using IM 7 (which you need for the HDRI compile since your image is outside the normal range of 16-bit integers).
magick ldem_4.tif -auto-level x.png


Q: ruby on rails: solid method to change logged in client's browser location on time X even when they reload pages? Im in the need of changing a client's browser location on a certain time X. It has to be solid even if a user reloads page it should redirect to location X
Below is my current (imperfect) implementation of this:
Im in the need to a way to make this solution solid OR an alternative solution if that would fit better. ITs to complex to share code snippets so I would like to reframe from that and discuss the concept instead and discuss how to code wise implement the missing gaps to keep this question overseen able.
Current solution:

*

*Im currently using redis and faye to send data to a subscribed channel (at the client) at time X

*This means that a jquery event (redirect of url ) will be triggered when the redis background scheduler pushes/sends this data at a certain time X ( which is always in future)

The problem is this is not solid, since on a page reload the pushed/send data is never received and rendered useless.
Even if it would be possible to save the last 10 sends/pushes in lets call it a "history" one could read it but say a user drops connection the excecution of this data would be useless since it will be to late and not in time.
*How could I overcome this problem? I prefer to keep the load server side and not use a client polling the server every 1 seconds to check if there is data received. that would not scale at all and would become a big problem if usage of the app grows.*
What ideas on this concept to make it solid or use another method to get a solid implementation of this idea? any comments ideas suggestions welcome thanks in advanche!


Q: Working with Real/Imaginary/Modulus parts of an complex Interpolating Function? From solving n times a numerical (complex) equation, like:
n = 10;
eq = Range[n];

For[a = 1, a < (n + 1), a++,
 eq[[a]] =
  NDSolve[{y''[x] + a*y[x] == 0, y[0] == 1 + I, y'[0] == 1 + 0 I},
  y, {x, 0, 30}]]

I get the (complex) n solutions in the variable value:
value = Range[n];

For[a = 1, a < (n + 1), a++,
 value[[a]] =
   With[{exp = Through[({y} /. First[eq[[a]]])[#]]}, exp &]];

Which is a list of 10 complex interpolating functions. I can plot the real and imaginary parts of each element of value with no problem.
Now, I'm interested in working with the squared modulus of value, i.e. its squared real part plus its squared imaginary part. I'm trying to define two new variables as the real and imaginary parts of value:
valuereal = Range[n];
valueim = Range[n];

For[a = 1, a < (n + 1), a++,
 valuereal[[a]] =
   Re[value[[a]]]];

For[a = 1, a < (n + 1), a++,
 valueim[[a]] =
   Im[value[[a]]]];

But it seems that I can't plot these new variables (maybe I can't define the real/imaginary parts in this way?). How can I work correctly with the real/imaginary part of value (an complex interpolating function)?
Question: How can work with the real/imaginary parts of an complex Interpolating function?
Note: I tried to work with:
Abs[value[[a]]]

But I had the same problem.
I'd appreciate all kind of answers a lot.

A: Your problem is that you cannot distinguish f[g][x] and f[g[x]]
All your code are in a form like defining com=Im[sol], but when plotting, you plot like com[x] which, after inserting com's definition, becomes Im[sol][x] instead of Im[sol[x]] which will generate the correct result.
So, try use LeftComposition instead of your method.
com=Im@*sol
Plot[com[x],{x,0,1}]

This code will yield desired result.
Hope this post can help you~


Q: multiply form values from form array with JS I have html form with arrays:
     <form method="post" id="formaa" name="form">

<input type="text" name="ite[]" id="item" /><input type="text" name="q[]" id="quantity" class="quant" size="3" />
<input type="text" name="pr[]" id="price" size="10" class="kaina" onkeyup="update();"/><input type="text" name="sum[]" id="suma" size="10" disabled="disabled"/>

    <input type="button" name="nw" id="new" value="ADD" onClick="naujas('laukeliai');" />

    Total: <input type="text" name="sumaa[]" id="suma" size="10" disabled="disabled"/>
    </form>

Each time I push forms ADD button, inside the
 is included new div block
 I need multiply qp[] and pr[] values and dynamicaly add to sum field, need do multiply price and quantity of each product seperately and get final each product price (not all products total).
first tried to get all values and filter these two, but couldnt figure out...
var form = document.getElementsByName('form')[0];
var inputs = form.getElementsByTagName('input');
for (var i = 0, j = inputs.length; i < j; i++) {
    var element = inputs[i];
    alert(element.value);
}

How to extract from this array only needed values and multiply? Thanks for advices.

A: you can read form array in way as below

frmRefer = document.getElementByTagName("form")[0];
for(i= 0 ; i<frmRefer.elements["ite[]"].length;i++){
    alert(frmRefer.elements["ite[]"][i].value );
}
for(i= 0 ; i<frmRefer.elements["quant[]"].length;i++){
    alert(frmRefer.elements["quant[]"][i].value );
}
for(i= 0 ; i<frmRefer.elements["pr[]"].length;i++){
    alert(frmRefer.elements["pr[]"][i].value );
}

A: Assuming you want to generate the sum of the prices for all the products and quantities you bought, you would first rewrite your HTML as:
<form id="example_form">

  <input type="text" name="item" class="item"></input>
  <input type="text" name="quant" class="quant"></input>
  <input type="text" name="price" class="price"></input>

  <input type="text" name="item" class="item"></input>
  <input type="text" name="quant" class="quant"></input>
  <input type="text" name="price" class="price"></input>

<input type="text" disabled id="sum" name="sum"></input>
</form>

Use jQuery to make field access easier. Using JQuery, you would use the following JS:
function update() {
  var total = 0;
  $("#example_form div.row").each(function(i,o){
    total += $(o).find(".quant").val() *
        $(o).find(".price").val();
  });
  $("#example_form #sum").val(total);
}

This will update totals for you. To do this each time any number is changed, you would need to register it with the corresponding fields, using something like
$("#example_form div.row input").change(update);

Have I convinced you of using JQuery? See it working at http://jsfiddle.net/UnYJ3/2/


Q: Quicksort with Lists in C++ I am working on a comparison for how different data structures effect the performance of an algorithm. I am trying to get the "List" data structure to work with Quicksort. When I try to run it however, my application crashes and gives me the error "list iterator not derefencable". Anyone know what could be going wrong? It is quite possible that there is some kind of iteration problem, because I am very unfamiliar with it.
void quickSortList(List& arr, int left, int right, int trialnr)
{// prepare iterators
    list<int>::iterator i = arr.begin();
    while(*i != left)
    {
        i++;
    }
    list<int>::iterator j = arr.end();
    while (*j != right)
    {
        j--;
    }
    int pivot = *i + *j / 2;

// inititate partitioning while the values on both left and right are not equal
while (*i <= *j)
{
    while (*i < pivot)
    {
        i++;
    }
    while (*j > pivot)
    {
        j--;
    }
    if (*i <= *j)
    {
        // while partitioning is in process, swap the corresponding arrays
        swap(i, j);
        i++;
        j--;
    }
}

// repeat the process until the array is sorted
if (left < *j)
{
    quickSortList(arr, left, right, trialnr);
}
if (*i < right)
{
    quickSortList(arr, left, right, trialnr);
}
}


Q: Sample mean and sample covariance canonical forms Let $(x_1, x_2,\dotsc, x_n)$ be a sequence of vectors: ($\forall i=1,\dots,n$)
\begin{pmatrix}
   x_i^1  \\
   x_i^2\\
   \vdots\\
   x_i^m
\end{pmatrix}
In statistics, one often has to compute the sample mean vector:
 $$X = \frac{1}{n}\sum_{i=1}^n x_i$$
and the sample covariance (or variance-covariance) matrix:
$$\mathbb{V} = \frac{1}{n-1}\sum_{i=1}^n (x_i - X)(x_i - X)^T$$
where $x^T$ is the transpose of $x$.
My questions are:

*

*what canonical form of information would I suggest
to represent the sequence $(x_1, x_2, \dotsc, x_n)$ in order to compute the sample mean vector and the sample covariance matrix?

*How can I verify that all the desirable properties of canonical information are satisfied: Existence and Uniqueness, Completeness, Elementary, Empty, Combination, Update, and Compactness and Efficiency.

*What are the minimum number of observations $n$ for which $X$ and $\mathbb{V}$ are defined?
Thanks in advance.


Q: Inclusion exclusion, calculus-physics-chemistry
There are 360 people in my school. 15 take calculus, physics, and chemistry, and 15 don't take any of them. 180 take calculus. Twice as many students take chemistry as take physics. 75 take both calculus and chemistry, and 75 take both physics and chemistry. Only 30 take both physics and calculus. How many students take physics?

I ended up getting 110. Let me explain my thought process. 15 people aren't taking classes, so we're really only considering 360 - 15 = 345 people here. How do we get the 15 that take all 3? Using inclusion-exclusion, it's 345 - 2P - P - 180 + 75 + 75 + 30 = 15. Solving for P gets us 110. Is this correct?
Update: According to a commenter, there is an answer given here:
https://web2.0calc.com/questions/please-help-me-i-have-one-trie-lefft

There are 360 people and 345 people taking courses. 15 take all 3 and 60 only take Calculus because 75+30+15+60=180.

Next, to find the total number of people who are only taking physics or only taking chemistry, I subtracted 240 from 345 because 240 (69+75+75+30) is everyone taking courses except for the people only taking physics of chemistry. I found that 105 are either only taking phy. or only taking chem.

lets say z=only physics

y=only chemistry

105=y+z or y=105-z

Also, x=the total number of people taking physics (so 2x is the total number of people taking chemistry)

Now:

2x=75+75+15+y

x=45+y-z

75+45+z=45+y-z

75+2z=y and from before: y=105-z

75+2z=105-z

z=10 so 10 people only take physics

Finally, the number of people taking physics is 10 (only) + 75 (phy. and chem) +30 (and calc) + 15 (all three) = 130. 130 students are taking physics.

But they get a different answer - 130 compared to my 110. Who's correct here?

A: Your answer of $(110)$ is right.  My alternative approach uses a truth table.
\begin{array}{| r | r | r | r| r |}
\hline
  \text{Calculus} & \text{Physics} & \text{Chemistry} & \text{Variable} & \text{Value} \\
  T & T & T & x_1 & 15 \\
  \hline
  T & T & F & x_2 & 15 \\
  \hline
  T & F & T & x_3 & 60 \\
  \hline
  T & F & F & x_4 & 90 \\
  \hline
  F & T & T & x_5 & 60 \\
  \hline
  F & T & F & x_6 &    \\
  \hline
  F & F & T & x_7 &   \\
  \hline
  F & F & F & x_8 & 15 \\
  \hline
\end{array}
For the moment, ignore the posted values.  Constraints:
$$x_1 + x_2 + x_3 + \cdots + x_8 = 360.\tag1 $$
$$x_1 = 15.\tag2 $$
$$x_8 = 15.\tag3 $$
$$x_1 + x_2 + x_3 + x_4 = 180.\tag4$$
$$x_1 + x_3 = 75.\tag5 $$
$$x_1 + x_2 = 30.\tag6 $$
$$x_1 + x_5 = 75.\tag7 $$
$$x_1 + x_3 + x_5 + x_7 = 2(x_1 + x_2 + x_5 + x_6).\tag8$$
$$x_1 + x_2 + x_5 + x_6 = ?.\tag9$$
Equations (2), (3), (5), (6), and (7) above lead immediately to the posted values for $x_1, x_8, x_2, x_3,$ and $x_5$.
With $x_1, x_2, x_3$ now determined, equation (4) solves for $x_4$.
It remains to solve for $x_6$.
With all variables but $x_6, x_7$ determined, equations (1) and (8) yield:
$$x_6 + x_7 = 105.$$
$$135 + x_7 = 2(90 + x_6) \implies $$
$$x_7 = 45 + 2x_6 = 105 - x_6 \implies $$
$$3x_6 = 60 \implies x_6 = 20.$$
Now, equation (9) can be solved:
$$x_1 + x_2 + x_5 + x_6 = 15 + 15 + 60 + 20 = 110.$$

A: I agree with your answer that 110 take physics.
In the solution linked to:
"There are 360 people and 345 people taking courses. 15 take all 3 and 60 only take Calculus because 75+30+15+60=180."
There is a sign problem here.  We should be subtracting the $15$ and not adding.  We might say, $75+30-15+90=180$ or $x + (75-15) + (30-15) = 180$ and solving for $x$ gives $x = 90.$
I have no clue what the next line is trying to say.
So, let's just stop there.