text:
Q: SQL Server : BULK INSERT FAILED IID_IColumnsInfo I use a BULK insert in a procStock, and got this Error Message:

Msg 4866, Level 16, State 8, Line 2
  The bulk load failed. The column is too long in the data file for row 1, column 1. Verify that the field terminator and row terminator are specified correctly.
Msg 7301, Level 16, State 2, Line 2
  Cannot obtain the required interface ("IID_IColumnsInfo") from OLE DB provider "BULK" for linked server "(null)".

I look for post in Stack and find some solution advice to use ROWTERMINATOR='0x0a', but I still got the same error.
    SET @sir_de_executat = '
    BULK INSERT #test
    FROM ''d:\scripts\test.csv''
    WITH (
        FIRSTROW=2
        , FORMATFILE=''d:\scripts\aaa2.fmt''
        , FIELDTERMINATOR = '';''
        , ROWTERMINATOR = ''0x0a''
    )'

Thanks for your help.
Here is a csv sample
BPARTNER;ME_TITLE_0208;BP_LSTNAME_0209;BP_FSTNAME_0210;STR_SUPPL1_0211;STR_SUPPL2_0212;HOUSE_NUM1_0213;HOUSE_NUM2_0214;STREET60_0215;STR_SUPPL4_0216;POSTALCODE_0217;CITY_1_0218;TEL_NUMBER_0219;FAX_NUMBER_0220;ZCHASSNR;ZFAHRZEUG__ZBRAND;ZFAHRZEUG__ZMODELKEY;ZFAHRZEUG__ZFISCHP;ZFAHRZEUG__ZMOTRVAR;ZFAHRZEUG__ZZULASSG;ZCREGDAT;/BIC/ZDDEALER;/BIC/Z_REGRNO_0124;ZFAHRZEUG__ZMOTR_KB4;ZFAHRZEUG__ZMODJAHR
6016562635;0002;FOO;BAR;;;823;;RUE DE LA SOUTE;;60400;CUTS;;;AZEZZZ8U0HR067422;AU;8UGBGY;0008;D;20170803;20170803;FRAA01612;EP-803-RP;DFTA;2017

Here is the fmt format file
10.0
25
1       SQLCHAR             0       20      "\t"      1     bpartner                                               SQL_Latin1_General_CP1_CI_AS
2       SQLCHAR             0       30      "\t"      2     title                                                  SQL_Latin1_General_CP1_CI_AS
3       SQLCHAR             0       256     "\t"      3     last_name                                              SQL_Latin1_General_CP1_CI_AS
4       SQLCHAR             0       256     "\t"      4     first_name                                             SQL_Latin1_General_CP1_CI_AS
5       SQLCHAR             0       256     "\t"      5     street2                                                SQL_Latin1_General_CP1_CI_AS
6       SQLCHAR             0       256     "\t"      6     street3                                                SQL_Latin1_General_CP1_CI_AS
7       SQLCHAR             0       60      "\t"      7     house_number                                           SQL_Latin1_General_CP1_CI_AS
8       SQLCHAR             0       60      "\t"      8     house_number_completion                                SQL_Latin1_General_CP1_CI_AS
9       SQLCHAR             0       256     "\t"      9     street                                                 SQL_Latin1_General_CP1_CI_AS
10      SQLCHAR             0       256     "\t"      10    street5                                                SQL_Latin1_General_CP1_CI_AS
11      SQLCHAR             0       30      "\t"      11    postal_code                                            SQL_Latin1_General_CP1_CI_AS
12      SQLCHAR             0       256     "\t"      12    city                                                   SQL_Latin1_General_CP1_CI_AS
13      SQLCHAR             0       128     "\t"      13    tel_number                                             SQL_Latin1_General_CP1_CI_AS
14      SQLCHAR             0       128     "\t"      14    fax_number                                             SQL_Latin1_General_CP1_CI_AS
15      SQLCHAR             0       50      "\t"      15    chassis_number                                         SQL_Latin1_General_CP1_CI_AS
16      SQLCHAR             0       10      "\t"      16    brand                                                  SQL_Latin1_General_CP1_CI_AS
17      SQLCHAR             0       15      "\t"      17    model_key                                              SQL_Latin1_General_CP1_CI_AS
18      SQLCHAR             0       15      "\t"      18    fiscal_horse_power                                     SQL_Latin1_General_CP1_CI_AS
19      SQLCHAR             0       60      "\t"      19    engine_option                                          SQL_Latin1_General_CP1_CI_AS
20      SQLCHAR             0       24      "\t"      20    first_registration_date                                ""
21      SQLCHAR             0       24      "\t"      21    current_registration_date                              ""
22      SQLCHAR             0       100     "\t"      22    sales_dealer                                           SQL_Latin1_General_CP1_CI_AS
23      SQLCHAR             0       100     "\t"      23    licence_plate                                          SQL_Latin1_General_CP1_CI_AS
24      SQLCHAR             0       60      "\t"      24    engine_code                                            SQL_Latin1_General_CP1_CI_AS
25      SQLCHAR             0       12      "\r\n"    25    year                                                   ""

A: When you'are creating your fmt file, you have to specify the Field Terminator to be same as used in your CSV file.
Documentation is given for bcp command  , you have to specify the -t option
bcp AdventureWorks..myDepartment in C:\myDepartment-c-t.txt -c -t ; -r \n -T

As explained  in this documentation , the default field terminator is the \t, it seems to be the problem.


text:
Q: Insert an image into SQL using VB? How can I insert an image from my computer into SQL using VB 2012?
Consider that the image name is XYZ, located in "My Documents". the image is to be inserted into a field named ABC.

A: You need to have a binary field for that. I found this on the internet.
CREATE TABLE Images(image varbinary(max))
INSERT INTO Images(image)
SELECT * FROM
OPENROWSET(BULK N'C:\My Documents\Image1.jpg', SINGLE_BLOB)

Give this a try, or change it to fit your tables. Notice that the C:\ is the disk of the sql server.
This is however the SQL CODE not in VB. But you can simply put this statement into a New SqlCommand
I found the code here: http://forums.asp.net/t/1867959.aspx
EDIT
This article here shows a example of how it can be done in vb.
http://social.msdn.microsoft.com/Forums/vstudio/en-US/d9068625-ec19-44c9-9650-816e6f12af72/vb-net-codessaving-image-direct-to-sql-table?forum=vbgeneral

A: You need to create a binary column in the table first, as has been suggested by Kay Nelson, however I imagine the file to store is not on the server, so to store it in the table, you need to open a filestream and write it to the server.
Have a look at How to save a PDF file in a SQL Server column using vb.net code - it's in C# but it's very easy to translate to VB.NET.

redpajama_set_name: RedPajamaStackExchange


text:
Q: gRPC endpoint with non-root path Maybe (hopefully) I'm missing something very simple, but I can't seem to figure this out.
I have a set of gRPC services that I would like to put behind a nghttpx proxy. For this I need to be able to configure my client with a channel on  a non-root url. Eg.
channel = grpc.insecure_channel('localhost:50051/myapp')
stub = MyAppStub(channel)

This wasn't working immediately through the proxy (it just hangs), so I tested with a server on the sub context.
server = grpc.server(executor)
service_pb2.add_MyAppServicer_to_server(
    MyAppService(), server)
server.add_insecure_port('{}:{}/myapp'.format(hostname, port))
server.start()

I get the following
E1103 21:00:13.880474000 140735277326336 server_chttp2.c:159]
{"created":"@1478203213.880457000","description":"OS Error",
"errno":8,"file":"src/core/lib/iomgr/resolve_address_posix.c",
"file_line":115,"os_error":"nodename nor servname provided, or not known",
"syscall":"getaddrinfo","target_address":"[::]:50051/myapp"}

So the question is - is it possible to create gRPC channels on non-root urls?

A: As confirmed here, this is not possible. I will route traffic via subdomains in nghttpx.


text:
Q: Adding a DeclarativeComponent in a UIComponent at runtime. Oracle JDeveloper 12c I've been working in this project for abou a week and haven't find a solution to my problem.
For testing purposes I create a simple new DeclarativeComponent which is a panelGroupLayout that contains 2 OutputText. After that I deploy the jar file and add it to my other Fusion web application libraries.
I want to add this DeclarativeComponent in another UIComponent at runtime by pressing a button which contains the next code in the javabean:
`public void addComponent(ActionEvent actionEvent)
{
    // Add event code here...
    createOutputComponent();
}

private void createOutputComponent()
{
    CuadroDeTextoComponent ui = new CuadroDeTextoComponent(); //This is my Declarative Component
    UIComponent parentUIComponent = getPglComponente(); This is the panelGrouopLayout in which i want to add my declarativeComponent
    addComponent(parentUIComponent, ui);
}

public void addComponent(UIComponent parentUIComponent, UIXDeclarativeComponent  childUIComponent)
{
    parentUIComponent.getChildren().add(childUIComponent);
    AdfFacesContext.getCurrentInstance().addPartialTarget(parentUIComponent);

}`

I have tried draging the declarative component and it works, but when I do it dynamically the component doesn't display

A: For your component to display you may need to add a PPR refresh to it's parent element :
In your case :
public void addComponent(ActionEvent actionEvent)
{
    // Add event code here...
    createOutputComponent();
}

private void createOutputComponent()
{
    CuadroDeTextoComponent ui = new CuadroDeTextoComponent(); //This is my Declarative Component
    UIComponent parentUIComponent = getPglComponente(); This is the panelGrouopLayout in which i want to add my declarativeComponent
    addComponent(parentUIComponent, ui);
    addPPR(parentUIComponent); //Refresh the parent component
}

public void addComponent(UIComponent parentUIComponent, UIXDeclarativeComponent  childUIComponent)
{
    parentUIComponent.getChildren().add(childUIComponent);
    AdfFacesContext.getCurrentInstance().addPartialTarget(parentUIComponent);

}

public static void addPPR(UIComponent component) {
    if (component != null) {
        AdfFacesContext.getCurrentInstance().addPartialTarget(component.getParent());
    }
}


text:
Q: Knockout Js Dictionary Display MVC I am stuck on something quite basic I believe, therefore I require some expertise to help me achieve this task.
I have a dictionary which takes an integer and string as values in order to store a list of results (which I will show below). My View Model and Controller have this code, that post the data as a JSON String to the Knockout:
[Code for ViewModel]
public class ResultModel
{
    public Dictionary<int, string> dictResult { get; set; }
    public string dictResultJson { get; set; }

    public ResultModel()
    {
        dictResult = new Dictionary<int, string>();
    }
}

[Code for cshtml file]

Results

In my cshtml file I am parsing the returned object from the MVC Controller and converting it into an array. Now the problem is that it is not displaying any data, but the variable dataFromServer contains proper data. It has this data:
Object {1: "Kate", 3: "Alex", 4: "Jane"}
Now, how am I supposed to loop this json Result in order to display it in a table format, such as
Table
1   Kate
3   Alex
4   Jane
Thanks in advance
Jesmond

A: If you want to display the values in the table as text you need to use the text binding instead of value

And there is one other problem with your code. When you call new ResultModel(dataFromServer) the dataFromServer is already contains the data in the right format. So you don't need m.DictJson in the ResultModel function:
var ResultModel = function(m) {
        var self = this;
        self.dictResultJson = ko.observableArray(mapDictionaryToArray(m));
};


text:
Q: How do I configure WebApi to seralise objects without changing the casing of their property names When I directly return a dynamic object (obtained from Dapper) from a WebApi2 method, the casing of the properties is unmolested and exactly matches the column name casing defined in the query SQL.
The object in question is a row set, and if I operate on it with LINQ and return the resultant IEnumerable, suddenly the json is camel-cased.
This is tangentially relevant: Web API 2: how to return JSON with camelCased property names, on objects and their sub-objects
How can I configure serialisation to mind its own damn business and pass names through unchanged?
Not forced to camel case or Pascal case, just passed through.

A: An answer does not seem forthcoming, and my position on the best tactic has changed anyway, so I will answer my own question by describing how I dealt with the underlying problem of inconsistent serialisation behaviour.
In fact the business of forcing a casing pattern is all about consistency and predictability. It doesn't really matter what the behaviour is, as long as it's predictable.
Forcing improves predictability: it's one or the other, and you can change all the results from a web api with a single setting. So forcing is better, and the question changes from "How can I prevent forcing?" to "How can I cause dynamics to be forced like all other types?"
The answer to that lies here: .NET Core json serialization of properties on dynamic (ExpandoObject)
That answer is for Core 1, here's how to do the same with Core 2
// in Startup.cs
public void ConfigureServices(IServiceCollection services)
{
  . . .
  services.AddMvc().AddJsonOptions(options =>
  {
    options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
  });
  . . .
}


text:
Q: Set Screen off on click home button I would like to set screen off on press HOME_BUTTON.
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

    if (keyCode == KeyEvent.KEYCODE_HOME) {
        System.out.println("home button");
        finish();
                WindowManager.LayoutParams params = getWindow().getAttributes();
                params.flags |= LayoutParams.FLAG_KEEP_SCREEN_ON;
                params.screenBrightness = 0;
                getWindow().setAttributes(params);

        return true;
    }

    return super.onKeyDown(keyCode, event);
}

Can any one help me
thank you

A: Finaly i get the solution
@Override
protected void onResume() {
    super.onResume();
    if (PreferenceHelper.getScreenLock(Recognition.this)) {
        wakeLock.acquire();
    }
    WindowManager.LayoutParams params = getWindow().getAttributes();
    params.screenBrightness = 1;
    getWindow().setAttributes(params);

}
@Override
protected void onPause() {
    super.onPause();
    if (PreferenceHelper.getScreenLock(Recognition.this)) {
        wakeLock.release();
    }
    WindowManager.LayoutParams params = getWindow().getAttributes();
    params.screenBrightness = 0;
    getWindow().setAttributes(params);

}

A: public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_HOME) {
    System.out.println("home button");
    DevicePolicyManager mDPM = (DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE);
    mDPM.lockNow();
    return true;
}
return super.onKeyDown(keyCode, event);

}
This will lock your screen on the press of home button.


text:
Q: How to pass argument in on-click function in a polymer dom-repeat here is the code sample:

<template is="dom-repeat" items="{{tableData}}" as="data">

        {{data.id_Mission}}
        {{data.nom}}
        {{data.resume}}

</template>

And I would like to pass an argument to the _test function.
Like this on-click="_test({{data.id_Mission}})".
Is there a way to perform that ?
Have a nice day :)

A: I have a workaround here it is, but i'm still interested if there is a solution like the one I was asking for.

//Build the table
 _buildTable(data)
{
    this.$.spinner.style.display = 'none';
    this.tableHead = Object.keys(data[0]);
    this.tableData = data;
    setTimeout(() => {//After the data is rendered launch a function
        this._test();
    });
}
//Bind event to each element
_test()
{
    var links = this.shadowRoot.querySelectorAll(".link");
    console.log(links);
    links.forEach(link => {
        link.addEventListener('click', function(){
            console.log("Click !", link.innerText);// the innerText contain the data I want
        });
    });
}

        Mission
        Nom
        Résumé

        <template is="dom-repeat" items="{{tableData}}" as="data">

                {{data.id_Mission}}
                {{data.nom}}
                {{data.resume}}

        </template>


text:
Q: Split Map to multiple Maps I need to process a diff between two (huge) Maps. To parallelize the task, I would like to split these 2 Maps by Key hash value and create smaller Maps (by range of hash value).
How would I archieve that in (idiomatic) Scala?

A: Here's a rough sketch to get you started with the Scala syntax:
// create two (slightly different) maps, print them as table side by side
val rnd = new util.Random
val originalMap1 = (0 to 10).map(i => (i, i * i)).toMap
val originalMap2 = (0 to 10).map(i => (i, i * i + rnd.nextInt(2))).toMap
for (i <- 0 to 10) {
  val a = originalMap1(i)
  val b = originalMap2(i)
  val marker = if (a == b) "" else " <-"
  println(s"$i: $a $b $marker")
}

//subdivide into smaller maps
val numSubmaps = 5
val submaps1 = originalMap1.groupBy(_._1.hashCode % numSubmaps)
val submaps2 = originalMap2.groupBy(_._1.hashCode % numSubmaps)

// compare each corresponding pair of maps separately, merge diffs
val diffs = (for (s <- 0 until numSubmaps) yield {
  val m1 = submaps1(s)
  val m2 = submaps2(s)
  for {
    k <- m1.keys
    a = m1(k)
    b = m2(k)
    if a != b
  } yield (k, (a, b))
}).reduce(_ ++ _)

println(diffs.toList.sortBy(_._1))

Input:
0: 0 1  <-
1: 1 2  <-
2: 4 4
3: 9 9
4: 16 16
5: 25 26  <-
6: 36 36
7: 49 49
8: 64 65  <-
9: 81 82  <-
10: 100 101  <-

Output:
List((0,(0,1)), (1,(1,2)), (5,(25,26)), (8,(64,65)), (9,(81,82)), (10,(100,101)))


text:
Q: Cmake link libmapnik c++ I am unable to connect Mapnik via cmake to my application.
I tried to do like this:
cmake_minimum_required(VERSION 3.1)

project(MapnikTest)

set(MAPNIK_LIB "/usr/local/lib/libmapnik.so.3.1.0") dont work

#set(MAPNIK_LIB "/usr/local/lib/libmapnik.so") dont work

set(MAPNIK_INCLUDE_DIR "/usr/local/include/mapnik")  work

#find_package(mapnik REQUIRED) dont work

#find_package(Mapnik REQUIRED) dont work

include_directories(${MAPNIK_INCLUDE_DIR})

add_executable(${PROJECT_NAME} main.cpp)

target_link_libraries(${PROJECT_NAME} PRIVATE ${MAPNIK_LIB})

The thing is, I don't have mapnikConfig.cmake in /usr/local/bin/cmake
Can't connect the library directly. Include he sees.
I edited already LD_LIBRARY_PATH it didn't help either.
/usr/bin/ld: CMakeFiles/MapnikTest.dir/main.cpp.o: in function `main':
main.cpp:(.text+0x3b): undefined reference to `mapnik::Map::Map(int, int, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)'
/usr/bin/ld: main.cpp:(.text+0xb8): undefined reference to `mapnik::load_map(mapnik::Map&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, bool, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
/usr/bin/ld: main.cpp:(.text+0x1b9): undefined reference to `void mapnik::save_to_file<mapnik::image<mapnik::rgba8_t> >(mapnik::image<mapnik::rgba8_t> const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)'
/usr/bin/ld: CMakeFiles/MapnikTest.dir/main.cpp.o: in function `icu_66::UnicodeString::hashCode() const':
main.cpp:(.text._ZNK6icu_6613UnicodeString8hashCodeEv[_ZNK6icu_6613UnicodeString8hashCodeEv]+0x18): undefined reference to `icu_66::UnicodeString::doHashCode() const'
collect2: error: ld returned 1 exit status
make[2]: *** [CMakeFiles/MapnikTest.dir/build.make:104: MapnikTest] Error 1
make[1]: *** [CMakeFiles/Makefile2:95: CMakeFiles/MapnikTest.dir/all] Error 2
make: *** [Makefile:103: all] Error 2

(dont work mean this)

A: Edit
When I inspect github more carefully it turn out that cmake config was introduced recently, after last release. So my answer will become valid for next release of this library.
You can inspect this change to see how import that library.
Original (valid after next release 3.2):
Based on demo form Mapnik repo it should go like this:
cmake_minimum_required(VERSION 3.1)

project(MapnikTest)
find_package(mapnik REQUIRED)

add_executable(${PROJECT_NAME} main.cpp)
target_link_libraries(${PROJECT_NAME} PRIVATE mapnik::agg mapnik::mapnik)

Didn't test it, but should work. I can see library provides proper config.

A: Find where you have mapnikConfig.cmake or mapnik-config.cmake and set mapnik_DIR to it. Like this:
cmake -Dmapnik_DIR="/path/to/config" ..

and it should be
find_package(mapnik REQUIRED)


text:
Q: how to stop Spring AMQP annotated message listener from receiving messages when my Spring AMQP message listener recognizes an error, I want to stop receiving messages from the queue. When I have a ListenerContainer configured as bean, I can call stop() on it.
Can I do something similar, when I have configured my listener with an endpoint annotation? E.g. is it possible to inject the ListenerContainer the container has created for me?
thx,
  tchick

A: Please, find @RabbitListener#id() JavaDocs:
/**
 * The unique identifier of the container managing for this endpoint.
 * <p>If none is specified an auto-generated one is provided.
 * @return the {@code id} for the container managing for this endpoint.
 * @see org.springframework.amqp.rabbit.listener.RabbitListenerEndpointRegistry#getListenerContainer(String)
 */
String id() default "";

So, you have to inject to your target service the RabbitListenerEndpointRegistry and use it to get access to desired ListenerContainer by its id.


text:
Q: Existence of isomorphism mod every power of the maximal ideal This problem is a continuation of Hensel lemma and rational points in complete noetherian local ring.
Let $A$ be a complete noetherian local ring and $\mathfrak{m}$ be its maximal ideal.
Assume $S_1$ and $S_2$ are two finitely generated $A$-algebras (no flatness assumption), and $S_1/\mathfrak{m}^n \cong S_2/\mathfrak{m}^n$ as $A$-algebras for every $n$. If we assume $S_i$ is the inverse limit of $S_i/\mathfrak{m}^n$ respectively, then do we have $S_1 \cong S_2$ as $A$-algebras?
Again the problem is about compatibility. If one try to use the Hom functor, there is a subtlety of representability. The problem can also be stated for finite type schemes.
Moreover, I have one similar question: if $R_1$, $R_2$ are two complete noetherian local rings and $R_1/\mathfrak{m_1}^n \cong R_1/\mathfrak{m_2}^n$, then do we have $R_1 \cong R_2$ as rings?
The similar question for finitely generated modules is true as $Isom$ satisfies Mittag-Leffler condition (an endomorphism of finitely generated module is an isomorphism iff it's surjective, so this can be checked mod $\mathfrak{m}$, and Hom mod ${\mathfrak{m}}^n$ are modules of finite lengths )

A: Here is a lovely argument shown to me by Madhav Nori.
Let $A,B$ be complete local rings, quotients of a power series ring in
finitely many variables over a field $k$. If $A/\mathfrak{M}_A^n\cong
B/\mathfrak{M}_B^n$ for all $n$ then $A\cong B$ where as usual
$\mathfrak{M}$ denotes the maximal ideal.
Proof: Let us denote by $A_n=A/\mathfrak{M}_A^n$ and
similarly $B_n$. Let $G_n=\mathrm{Aut}\, A_n$. Then $G_n$ is an
algebraic group over $k$. Let $I_n=\mathrm{Isom}(A_n,B_n)$, the set of
$k$-algebra isomorphisms, which is naturally a variety over $k$. In our
situation, $G_n\cong I_n$ as algebraic varieties by using any of the
isomorphisms in $I_n$, which is non-empty by assumption. In other
words, if $\phi\in I_n$, then we have a morphism $G_n\to I_n$ given by
$g\mapsto \phi\circ g^{-1}$ which one easily checks is an
isomorphism. (In standard language, $I_n$ is a principal homogeneous
space over $G_n$.)
Basic fact from Algebraic groups: If $f:G\to H$ is a group morphism of
algebraic groups, $f(G)$ is closed.
We have natural restriction maps $r_{m,n}:I_m\to I_n$ for $m>n$. This
induces by using any element of $I_m$ a  group morphism from
$G_m\to G_n$ and hence, we see that $r_{m,n}(I_m)$ is closed in $I_n$. Let
$$K_n=\cap_{m>n} r_{m,n}(I_m).$$
Then $K_n$ is a closed subvariety of $I_n$ and it is non-empty. One
can easily check that $r_{m,n}(K_m)= K_n$. Thus we have a surjective
projective system $\{K_n\}$. Since these are all non-empty, it has an
element in the projective limit. That is, there exists $\phi_n\in K_n$
so that $r_{m,n}(\phi_m)=\phi_n$ for all $m>n$. These $\phi$'s give a
compatible collection of isomorphisms from $A_n\to B_n$ and thus we
get an isomorphism in the projective limit $A\to B$.


text:
Q: How to do select with where clause using JPA CrudRepository Hello I would like create a method to execute the follow query
SELECT * FROM Customer where customer.customerpremium=true;

I tired implement this method but not working.
public interface CustomerRepository extends CrudRepository<Customer, String>{

    Iterable<Customer> findByCustomerPremium(boolean customerpremium);
}

follow my Entity
@Entity
@Table(name = "customer")
public class Customer implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    @Column(name = "customerid")
    private Integer customerid;

    @NotEmpty
    @Column(name = "customername")
    private String customername;

    @NotEmpty
    @Column(name = "customeremail")
    private String customeremail;

    @Column(name = "customerpremium")
    private boolean customerpremium;

    /**gets and sets*/
}

A: your property is in small case customerpremium
try
Iterable<Customer> findByCustomerpremium(boolean customerpremium);

currently this method
Iterable<Customer> findByCustomerPremium(boolean customerpremium);

creating query like this
SELECT * FROM Customer where customer.customer_premium=:customerpremium;

also you can log your sql queries by adding below line in application.properties file
spring.jpa.show-sql=true


text:
Q: how to check if a specific UI element is in focus apple script I've searched a lot for this, but all answers talk about how bringing a whole window (or dialogue.. which is still a window really) into focus via activate etc.
But I couldn't find any way of detecting if a specific UI element was selected, in focus etc.

I'm wrote an apple script that automatically jumps to alfred create custom web search, but the script failed when the features tab wasn't selected by default.. so this is what my code looks like:
tell application "System Events"
    keystroke "," using command down
    delay delay_time
    tell process "Alfred Preferences"
        delay delay_time
        -- hack: to ensure that the the "Default results" button isn't selected
        -- by default, we select another tab first, then select the "features" tab
        click button "Appearance" of toolbar 1 of window 1
        click button "Features" of toolbar 1 of window 1
        delay delay_time
        UI elements of scroll area 1 of window 1
        -- bring the left menu to focus first (see hack above, without hack this would work sometimes only)
        keystroke tab

I'd much rather not do this nasty hack (which causes the app to flicker rapidly between tabs whenever i call the shortcut).. i'd rather make a simple if else statement.. ideas?

A: This definitely works on my system running Alfred 3.  You may need to adjust the delay times but as they are now, this script works for me.
activate application "Alfred Preferences"
delay 1.5
tell application "System Events"
    tell process "Alfred Preferences"
        click button "Features" of toolbar 1 of window "Alfred Preferences" of application process "Alfred Preferences" of application "System Events"
        delay 1
        set selected of row 3 of table 1 of scroll area 1 of window "Alfred Preferences" of application process "Alfred Preferences" of application "System Events" to true
        delay 1
        click button "Add Custom Search" of tab group 1 of window "Alfred Preferences" of application process "Alfred Preferences" of application "System Events"
    end tell
end tell


text:
Q: $X_1,X_2$ distributed $U(0,1)$ and independent, find the distribution of $D=|X_2-X_1|$ I know it shouldn't be this hard but I am having trouble anyway.
I tried using $F_D(t)=\mathbb{P}(|X_2-X_1|\leq t)=\mathbb{P}(-t\leq X_1-X_2\leq t)$ and sketching the unit square $[0,1]^2$ but to no avail, I can't seem to find a formula that fits.

A: If you to a drawing of the problem it will be very easy to find
$$F_D(d)=1-(1-d)^2$$
and derivating you get the density
$$f_D(d)=2(1-d)\cdot \mathbb{1}_{[0;1]}(d)$$

The CDF is the white area, in function of $d \in [0;1]$
To calculate it, it is easier to calculate the purple area $(1-d)^2$ and take the complement to 1

A: What is the pink area in this unit square?

A: Sketch for the solution: setting $Z:=(X,Y)$ you will have that
$$
\begin{align*}
\Pr [|X-Y|\leqslant c]&=\Pr [Z\in A_c]\\&=\int_{\mathbb{R}^2}\mathbf{1}_{A_c}(x,y)f_X(x)f_Y(y)\mathop{}\!d (x,y)\\
&=\int_{[0,1]^2}\mathbf{1}_{A_c}(x,y)\mathop{}\!d (x,y)
\end{align*}
$$
where $A_c:=\{(x,y)\in \mathbb{R}^2:|x-y|\leqslant c\}$ and $f_X(t)=f_Y(t)=\mathbf{1}_{[0,1]}(t)$ are the densities of $X$ and $Y$. Now observe that
$$
\mathbf{1}_{A_c}(x,y)=1 \iff |x-y|\leqslant c \iff x-y\in[-c,c]\iff y\in \mathbb{R}\,\land\, x\in [y-c,y+c]
$$
Therefore $\mathbf{1}_{A_c}(x,y)=\mathbf{1}_{\mathbb{R}}(y)\mathbf{1}_{[y-c,y+c]}(x)$, and so substituting in the last integral we find that
$$
Pr[|X-Y|\leqslant c]=\int_0^{1}\int_0^{1}\mathbf{1}_{[y-c,y+c]}(x)\mathop{}\!d x\mathop{}\!d y
$$
Now the inner integral is just the Lebesgue measure of the set $[0,1]\cap [y-c,y+c]$, this is $1-(y-c)$ when $y-c\in[0,1]$ or $y+c$ when $y+c\in[0,1]$, therefore
$$
Pr[|X-Y|\leqslant c]=\int_0^{1}((1-y+c)\mathbf{1}_{[c,c+1]}(y)+(y+c)\mathbf{1}_{[-c,1-c]}(y))\mathop{}\!d y
$$


text:
Q: postgres inverse of json_each I don't have json text in a field. I have a row with columns "text","format","keyname","..." and I want to export it to json in the format '{"value of keyname column": {"text":"value of text","format":"value of format",... }}'. Is that possible in postgresql?
I have been looking at a postgis2geojson example and learned about the row_to_json function already.
http://www.postgresonline.com/journal/archives/267-Creating-GeoJSON-Feature-Collections-with-JSON-and-PostGIS-functions.html
Furthermore I have been looking at the postgres json documentation: http://www.postgresql.org/docs/9.3/static/functions-json.html
Unfortunately I found no function that covers my need explicitly but json_each does what I want just in the opposite direction. Generally, I think the json functions in postgres are designed on the assumption that only the column names can be used as keys. Am I right? Is there a SQL hack I could use to come around this? Thanks for any help.
EDIT:
select '"'||keyname||'":"'||row_to_json((select r from(Select text, format,
    (select username from my.users where users.id = table.uid) as username,
    machinename ) as r ))||'"'
    from my.table where id = 1;

A: Since version 9.4 postgres has json_object_agg function, which is the inverse of json_each. You can read the documentation here.
If the data look like this:
> select * from example;
 text | format | keyname
------+--------+---------
 foo  | bar    | a
 dead | beef   | b
(2 rows)

Then you can aggregate all of that into an object with keys a and b with the following query:
> select json_object_agg(keyname, json_build_object('text', text, 'format', format)) from example;
                                     json_object_agg
------------------------------------------------------------------------------------------
 { "a" : {"text" : "foo", "format" : "bar"}, "b" : {"text" : "dead", "format" : "beef"} }
(1 row)

A: To keep the API clean I would actually do it a little differently.  You currently have this:
select '"'||keyname||'":"'||row_to_json((select r from(Select text, format,
    (select username from my.users where users.id = table.uid) as username,
    machinename ) as r ))||'"'
    from my.table where id = 1;

You would have this:
WITH full_r AS (select keyname, text, format, username, machinename
                  FROM my.table JOIN my.users ON users.id = table.uid
                  WHERE id = 1),
     small_r AS (select text, format, username, machinename FROM full_r)
SELECT f.keyname, row_to_json(s)
  FROM small_r s CROSS JOIN full_r f;

This assumes only one row returned.  You would want an inner join instead of a cross join if you are working with multiple rows.


text:
Q: Javascript FIle wont display simple code inside html file Do I have to setup a javascript file like an html file so it can display the text i put in the
document.write("hello world!");

I have the <script> </script> inside the html but it still won't display the text i ask for

A: This is working for me.

<script>document.write("helloWorld")</script>

if you want to use javascript you have to put the actual js code into the script tag or link to an external script file.
It is recommended to set up the external file >like your html file< and to link to it inside of an <script> tag at the bottom of the html document. The filename could be App.js and you would have to link to it like this html <script src="./App.js"></script> (if the file is in the same folder). For more Information on this topic you could read this: seperation of concerns(Wikipeda)


text:
Q: How can I speed up maven builds of JavaFX application? My problem can be reproduced by creating a new project in Netbeans 8:
New Project >> Maven >> JavaFX Application
Then adding the org.springframework spring-context dependency.
Build times go up from a few seconds to more than half a minute, most of it due to running javafxpackager.
I can live with slow release builds but how can I speed up my development builds?
This is my pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org    /2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0     http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.mycompany</groupId>
<artifactId>mavenproject1</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>

<name>mavenproject1</name>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <mainClass>com.mycompany.mavenproject1.MainApp</mainClass>
</properties>

<organization>
    <!-- Used as the 'Vendor' for JNLP generation -->
    <name>Your Organisation</name>
</organization>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.6</version>
            <executions>
                <execution>
                    <id>unpack-dependencies</id>
                    <phase>package</phase>
                    <goals>
                        <goal>unpack-dependencies</goal>
                    </goals>
                    <configuration>
                        <excludeScope>system</excludeScope>
                        <excludeGroupIds>junit,org.mockito,org.hamcrest</excludeGroupIds>
                        <outputDirectory>${project.build.directory}/classes</outputDirectory>
                    </configuration>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.2.1</version>
            <executions>
                <execution>
                    <id>unpack-dependencies</id>

                    <phase>package</phase>
                    <goals>
                        <goal>exec</goal>
                    </goals>
                    <configuration>
                        <executable>${java.home}/../bin/javafxpackager</executable>
                        <arguments>
                            <argument>-createjar</argument>
                            <argument>-nocss2bin</argument>
                            <argument>-appclass</argument>
                            <argument>${mainClass}</argument>
                            <argument>-srcdir</argument>
                            <argument>${project.build.directory}/classes</argument>
                            <argument>-outdir</argument>
                            <argument>${project.build.directory}</argument>
                            <argument>-outfile</argument>
                            <argument>${project.build.finalName}.jar</argument>
                        </arguments>
                    </configuration>
                </execution>
                <execution>
                    <id>default-cli</id>
                    <goals>
                        <goal>exec</goal>
                    </goals>
                    <configuration>
                        <executable>${java.home}/bin/java</executable>
                        <commandlineArgs>${runfx.args}</commandlineArgs>
                    </configuration>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>1.7</source>
                <target>1.7</target>
                <compilerArguments>
                    <bootclasspath>${sun.boot.class.path}${path.separator}${java.home}/lib/jfxrt.jar</bootclasspath>
                </compilerArguments>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.16</version>
            <configuration>
                <additionalClasspathElements>
                    <additionalClasspathElement>${java.home}/lib/jfxrt.jar</additionalClasspathElement>
                </additionalClasspathElements>
            </configuration>
        </plugin>
    </plugins>
</build>
<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.0.6.RELEASE</version>
    </dependency>
</dependencies>

Thanks!
Daniel

A: You could define the plugin in a profile that is inactive by default. Then, in order to make the production build, you would have to manually specify the activation of that profile (or activate it in any other standard way).
You pom would be something like (only diffs shown):
<?xml version="1.0" encoding="UTF-8"?>
<project ...>
    ...
    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                ...
                <executions>
                    <!-- take this out of here
                    <execution>
                        <id>unpack-dependencies</id>
                        ...
                    </execution>
                    -->
                    <execution>
                        ...
                    </execution>
                </executions>
            </plugin>
            ...
        </plugins>
    </build>
    <profiles>
        <profile>
            <id>javafxpackager</id>
            <build>
                <plugins>
                    <!-- INSERT THE exec-maven-plugin HERE, ONLY
                         WITH THE unpack-dependencies EXECUTION -->
                </plugins>
            </build>
        </profile>
    </profiles>
</project>

In production run mvn ... -Pjavafxpackager

A: To complete Nikos' answer, this is the configuration of the maven-assembly-plugin which creates the archive for normal builds.
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-assembly-plugin</artifactId>
    <configuration>
        <appendAssemblyId>false</appendAssemblyId>
        <archive>
            <manifest>
                <mainClass>${mainClass}</mainClass>
            </manifest>
        </archive>
        <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
        </descriptorRefs>
    </configuration>
    <executions>
        <execution>
            <id>my-assembly</id>
            <phase>package</phase>
            <goals>
                <goal>assembly</goal>
            </goals>
        </execution>
    </executions>
</plugin>

A: above solutions dont work. The problem has nothing to do with javafxpackager whatsoever. The cause lies in the maven standard configuration. On every project run Maven performs a project clean by default. This deletes the targets/classes/ folder. Thats the same folder where all the unpacked jar files of your dependencies are placed. If those get deleted on every new run then they have to be unpacked over and over again. Anyway, heres how you can prevent the clean from happening:
    <plugin>
  <artifactId>maven-clean-plugin</artifactId>
  <version>2.4.1</version>
  <configuration>
    <skip>true</skip>
  </configuration>
</plugin>

Add this to your POM.xml. Make sure you get the version correct You can check the version of your maven clean plugin in the effective pom (thats parent pom + project POM combined). In netbeans you can watch the readonly effective pom.xml under the effective tab when you've opened the pom.xml file of your project.
please give me a few +1's i want to get 50 points so that i can finally comment on other peoples answers. Thank you!
EDIT:
Also add skip to default-cli to avoid errors
                <execution>
                    <id>default-cli</id>
                    <goals>
                        <goal>exec</goal>
                    </goals>
                    <configuration>
                                <skip>true</skip>
                        <executable>${java.home}/bin/java</executable>
                        <commandlineArgs>${runfx.args}</commandlineArgs>
                    </configuration>
                </execution>

EDIT 2:
For those of you who would like to retain the ability to clean heres another method to prevent the maven plugin from deleting all jar files:
<plugin>
<artifactId>maven-clean-plugin</artifactId>
     <version>2.4.1</version>
<configuration>
    <excludeDefaultDirectories>true</excludeDefaultDirectories>
    <filesets>
        <!-- delete directories that will be generated when you
             start the develpment server/client in eclipse
        -->
        <fileset>
            <directory>target/classes</directory>
            <excludes>
                <exclude>**/*</exclude>
            </excludes>
        </fileset>
    </filesets>
</configuration>

Again, make sure  is correct

A: TL;DR:
To avoid unpacking dependencies, you don't need to modify the default pom.xml at all. Just change what Netbeans calls when you press Run (or Debug). In nbactions.xml change:

*

*runfx.args: Replace -jar "${project.build.directory}/${project.build.finalName}.jar" with -cp %classpath ${mainClass}. This way, the exec goal will not try to execute any jar but rather run your project from the target/classes directory. So no need to build the jar at all.

*goals: replace the "package" goal with "process-classes" (or "test" or any phase you want). We don't need a jar so no need to run the package phase. And no package phase also means no unpacking/repacking etc.

If you ever need the jar file with all the dependencies, just choose "clean and build" in Netbeans or run mvn clean install.
Background:
What happens when you press run in the standard Netbeans JavaFX maven project is:

*

*clean package exec - defined in nbactions.xml, configured in pom.xml:

*

*clean: as usual - deletes the target directory

*package:

*

*first as usual - copies resources and compiles sources to target/classes and packs that all to a jar without dependencies

*maven-dependency-plugin unpacks all the dependency jar files to target/classes

*exec-maven-plugin:unpack-dependencies (the id "unpack-dependencies" is missleading, should be something like "jar-with-dependencies") executes javapackager which builds a jar with dependencies overwriting the first jar

*exec:

*

*executes java with ${runfx.args} as arguments (defined in nbactions.xml) i.e. runs the jar

What happens after the changes above:

*

*clean process-classes exec - defined in nbactions.xml, configured in pom.xml:

*

*clean: as usual - deletes the target directory

*process-classes:

*

*as usual - copies resources and compiles sources to target/classes

*exec:

*

*executes java with ${runfx.args} as arguments (defined in nbactions.xml) i.e. runs the class target/classes/path/to/your/MainClass

Even better:
You may want remove the "clean" goal from nbactions.xml. This way, all the resource files won't be copied each time over and over (although the resource plugin will still keep saying "Copying X resources" - see the comments under https://stackoverflow.com/a/33700970/3519572).
Now, you may also want to only recompile changed classes rather than the whole project by adding useIncrementalCompilation=false (e.g. like <goal>org.codehaus.mojo:exec-maven-plugin:1.2.1:exec -Dmaven.compiler.useIncrementalCompilation=false</goal>). But be sure to read https://stackoverflow.com/a/49700942/3519572!
Therefore, you may also want to add a toolbar button to the "clean" goal to be able to run it manually easily at any time: https://stackoverflow.com/a/26546551/3519572.
BTW:
Finally, you might want to change the NetBeans generated pom.xml anyway. At least my NB 8.2 refers to the deprecated javafxpackager (rename to javapackager). Also the part <bootclasspath>..../lib/jfxrt.jar</bootclasspath> doesn't seem to be necessary with java 8. It actually breaks my build if I run it from the terminal. Removing it seems to fix it and doesn't seem to cause any trouble if started from NB.

A: You can also use parallel maven build feature to speed up.
By default, Maven does not utilize the full power of your hardware. It builds all modules sequentially rather than in parallel. However, often your project setup does not require it to be sequential. Often you can command Maven to analyze your project including the dependency graph and build the project in parallel where possible. You can either specify the exact number of threads to use for building your project or use a portable version of the parameter and specify the number of thread in terms of CPUs available on the machine.
mvn -T 4 install -- will use 4 threads
mvn -T 1C install -- will use 1 thread per available CPU core

See for more details: https://zeroturnaround.com/rebellabs/your-maven-build-is-slow-speed-it-up/


text:
Q: Detecting raised-event at OS-level (OS Appearance) I have what seems to be a common problem. I am running Windows 7 Home Premium on one of the most awesomest computers (when it was bought last year) and certain visual effects just automatically turn themselves off.
My average user experience rating is high, so it doesn't explain why this happens. The only feature that ever gets turned off is the 'Show window contents while dragging' option. And it really annoys me.
There are currently no working solutions to this problem online. Other than to "there must be a conflict with another app installed on your machine."
And yes, I do know what app is causing this conflict. It's my bloody Internet Provider's software - you know... that app that you absolutely MUST have open at all times when you're connected to the net.
So, I had a thought. What if I could subscribe to an event so that my app that runs in the background will detect when this 'show window contents while dragging' option is turned off - and then my app will simply turn it back on again.
When I do this manually, it seems to stay in effect for about an hour or two, then it gets switched off again.
Is it possible to handle these types of events, and re-start certain visual effect features? If so, are there any resources on this?
I have not been able to find anything on this sibject yet.

A: Yes the WM_SETTINGSCHANGE message is sent to all windows when a system setting is changed.  Then you can call SystemParametersInfo with SPI_GETDRAGFULLWINDOWS to determine if the "Show window contents while dragging" is disabled and use SPI_SETDRAGFULLWINDOWS to enable it.
So all that you will need to do is create an application with a form (that can even stay hidden) and override the forms WndProc and handle the WM_SETTINGSCHANGE message and call SystemParametersInfo using p/Invoke.  The p/Invoke definition for SystemParamtersInfo is available at pinvoke.net
Altough what may be easier is change security on the HKCU\Control Panel\Desktop\DragFullWindows registry value so that it can't be changed.


text:
Q: Anti-aliasing filled shapes in libgdx I've been looking everywhere for a way to anti-alias edges of filled shapes drawn with ShapeRenderer (ie. ShapeType.Filled) but can't find anything about this.
Lines works well with Gdx.gl.glEnable(GL10.GL_LINE_SMOOTH) but nothing I've tried works with filled shapes. So, does anyone have any suggestions?

A: maybe this link will help: MULTI SAMPLING ANTI-ALASING IN LIBGDX ON ANDROID
in general you have to enable multisampling to have edges of filled shapes smooth.
http://www.opengl.org/wiki/Multisampling

A: I've found the anti-aliasing support in OpenGL to be lacking (as actual support depends on optional hardware support), especially for the basic polygon primitives.  There are two solutions that I've found to work:
First, you can get reasonable multi-sampling when using textures.  So, maybe render your polygon to a FrameBuffer object, and then copy that to the screen.  There are still a bunch of caveats, see http://www.saschahlusiak.de/2012/10/opengl-antialiasing-in-android-with-transparent-textures/ for more details.
Second, render your filled shape with a shader that anti-aliases, as in this question: Drawing Antialiased circle using Shaders.  If your filled primitive shape is complicated, this can be quite a bit of work.  See https://code.google.com/p/libgdx/wiki/OpenGLShader for how to use a shader with Libgdx.  This option only works with OpenGL ES 2.0, too.

A: Have you tried following hints?
Gdx.gl.glEnable(GL10.GL_LINE_SMOOTH);
Gdx.gl.glEnable(GL10.GL_POINT_SMOOTH);
Gdx.gl.glHint(GL10.GL_POLYGON_SMOOTH_HINT, GL10.GL_NICEST);
Gdx.gl.glHint(GL10.GL_POINT_SMOOTH_HINT, GL10.GL_NICEST);


text:
Q: nohup and std::ignore() not working together One way to wait for a RETURN keypress is to call std::ignore(). However, when I use nohup std::ignore() always returns immediately. Does there exist an alternative way to wait for a keypress, or just return that will work with nohup?

A: When you use nohup to run a command, it connects the standard input of your command to /dev/null so there's no way to wait for any kind of keypress.
When you attempt a read from /dev/null, it automatically responds with EOF.
I guess this could be checked using the following code (untested):
#include <unistd.h>
...
if (isatty(fileno(stdin))) ...

This should work, as the standard guarantees that std::cin is associated with stdin.

A:
Does there exist an alternative way to wait for a keypress

Where from?
The keypress has to come from somewhere. You're expecting to get it from the controlling terminal, and then you deliberately disconnected your process from that terminal.
Yes, there exist alternatives:

*

*don't disconnect from the terminal if you want to get input from there

*get your keypress event from X instead, assuming you have a graphical environment running

*create a new terminal and get your keypress from there. This probably means running an xterm in practise though, so it's not trivial.

or just return that will work with nohup?

std::ignore() already does return, and you're complaining about that. Is waiting for a keypress the only thing that will work for you?

A: i solved the problem with:
std::this_thread::sleep_for(std::chrono::system_clock::duration::max());


text:
Q: How can i create a controlled stand-alone 3D viewer? I'm trying to create a custom 3D viewer that can show up a rigged model created with blender. Particulary, the model will be a mechanical one, so in need to move them with an IK solver: i ll move/rotate a single bone (which will be the motor axes) and all other components must follow it.
I've already done the Blender part (see link below), but now i'm stuck on how to make a stand-alone viewer (ideally a single executable file) that can communicate with another application/process (maybe with TCP socket?) and move the 3d model based on the information sent by it. I'm working on Win10.
Does anyone have any ideas?
(sorry my bad english, I hope explanation was thorough)
https://youtu.be/5rR7BKrGzFg


text:
Q: How to fetch latest entry done in a table for every minute, for every parameter I have records in tables saved like this:
ID | PID   | Param  | Param Value | Date time             |
---|-------|--------|-------------|------------------------
1  | 195   |Param 1 |    12       |2015-11-25 17:41:05.000
2  | 211   |Param 2 |    13       |2015-11-25 17:41:05.000
3  | 195   |Param 1 |    14       |2015-11-25 17:41:35.000
4  | 211   |Param 2 |    15       |2015-11-25 17:41:35.000
5  | 195   |Param 1 |    16       |2015-11-25 17:42:05.000
6  | 211   |Param 2 |    17       |2015-11-25 17:42:05.000
7  | 195   |Param 1 |    16       |2015-11-25 17:42:35.000
8  | 211   |Param 2 |    17       |2015-11-25 17:42:35.000

Data for each param comes multiple times each minute and i want to find data for each param that came latest in every minute that is to say:
Suppose data for param 1 came 3 times between 2015-11-25 17:41:00.000 and 2015-11-25 17:42:00.000 so I want the data that came the third time and this needs to be done for every param.
So my result data-set as per above entries should be like:
ID | PID   | Param | Param Value | Date time             |
-----------------+----------------------------------------
3  | 195   |Param 1 |    14      |2015-11-25 17:41:35.000
4  | 211   |Param 2 |    15      |2015-11-25 17:41:35.000
7  | 195   |Param 1 |    16      |2015-11-25 17:42:35.000
8  | 211   |Param 2 |    17      |2015-11-25 17:42:35.000

I have tried grouping by partitioning and stuff...but it doesn't seem to work. Any help in this regard will be greatly appreciated.
Thanks

A: With the window function and partition by Datepart
Select *
From (
       Select *
             ,RN = Row_Number() over (Partition By PID,Param ,datepart(MI,[Date time]) Order by [Date time] Desc)
       From  YourTable
    ) A
Where RN=1

Returns
ID  PID Param   Param Value Date time               RN
3   195 Param 1 14          2015-11-25 17:41:35.000 1
7   195 Param 1 16          2015-11-25 17:42:35.000 1
4   211 Param 2 15          2015-11-25 17:41:35.000 1
8   211 Param 2 17          2015-11-25 17:42:35.000 1


text:
Q: How can i retrieve a specific data from a json object and add in to an new array I want to make a new array and add some specific keys and values of the json object into the new array. My code adds only the value and not the key. Can someone help me?
CourseGroupCategoriesGroups=[{'GroupId': 11799, 'Name': 'Group 1', 'Description': {'Text': '', 'Html': ''}, 'Enrollments': [264, 265, 266, 50795, 50798]}, {'GroupId': 11928, 'Name': 'Group2', 'Description': {'Text': '', 'Html': ''}, 'Enrollments': [49039, 49040, 49063, 49076, 50720, 50765, 50791]}]
GroupMembership =[]

for record in CourseGroupCategoriesGroups:
    GroupMembership.append(record['Name'])

print(GroupMembership)

A: just add the names you want before the value:
GroupMembership =[]

for record in CourseGroupCategoriesGroups:
    GroupMembership.append({"Name": record['Name']})

A: Here is a solution:
GroupMembership =[]

for record in CourseGroupCategoriesGroups:
    GroupMembership.append({"GroupId": record["GroupId"], "Name": record["Name"]})

You could also use a list comprehension:
GroupMembership = [{"GroupId": record["GroupId"], "Name": record["Name"]} for record in CourseGroupCategoriesGroups]

A: GroupMembership.append({"Name": CourseGroupCategoriesGroups[0]['Name']})


text:
Q: Rounded corners on transparent borders are doubling translucency in Chrome When adding border-radius to an element with a transparent border, Chrome seems to double up opacity on the corners, making them translucent.
Code and example at: http://jsfiddle.net/shodan_uk/LMPMg/
Anybody got any ideas how to get round this?
Cheers,
Terry

A: This is a known bug of Webkit, you can either add a wrapping container to fake the border and apply border-radius, or change the opacity value or the border slightly (this will produce some faint lines on the corner of your element.
See demo here: http://jsfiddle.net/duopixel/hG9W8/
And here is the a similar question to yours:
Weird border opacity behavior in Webkit?

A: Yes I've had a similar issue. i used css3 border image instead to get the same effect as originally intended.


text:
Q: Weak and strong convergence of sequence of linear functionals Is this sequence of linear functionals weakly (strongly) convergent : $$f_n((x_j))=\sum_{k=1}^{n}{\frac{x_k}{k}} , (x_j) \in \ell_2\,?$$

A: Hint: show that for $\{x_n\}\subset\ell^2$, $\{x_n\}$ converges weakly to $0$ if and only if the following two conditions are realized:

*

*the sequence $\{x_n\}$ is bounded in $\ell^2$.

*Denoting $e_k$ the sequence for which all terms are $0$, except the $k$-th which is $1$, we have $\lim_{n\to +\infty}\langle x_n,e_k\rangle =0$ for each $k$.


text:
Q: cordova file plugin applicationDirectory equivalent for windows 8 app I am using Cordova and File plugin to list contents under assets directory in www. On iOS i'm getting the file entry passing cordova.file.applicationDirectory to window.resolveLocalFileSystemURL and everything is working as expected.
var url = cordova.file.applicationDirectory + '/www/assets/';

window.resolveLocalFileSystemURL(
    url,
    onSuccess,
    onFail
);

When I switch to windows app environment cordova.file.applicationDirectory is undefined. I tried using Windows.ApplicationModel.Package.Current.InstalledLocation or Windows.Storage.ApplicationData.current.localFolder with no luck.
What is the correct way to resolve local file system url for windows?


text:
Q: NSURLConnection timeout? I'm using this NSURLConnection with delegates.
nsconnection = [[NSURLConnection alloc] initWithRequest:request
    delegate:self startImmediately:YES];

Problem is the website doesn't respond at all. Nothing, just spins in browser with blank page, no failure. In my delegates, I handle the failure, but when the site doesn't respond the delegates don't get called. Any ideas on how to timeout the connection?

A: Edit: This answer is now obsolete, but at the date of answering was accurate.
I know this thread is old, but I ran into this issue as well. This happened when testing the app outside the internal network where the services lived. The service will eventually timeout, but Apple mandates a period of 240 seconds (4 minutes) before the time out occurs. Check out this thread for more info on the matter.
NSMutableURLRequest not obeying my timeoutInterval

A: You can specify a timeout in your NSURLRequest object.  One way to do this is to construct it via the requestWithURL:cachePolicy:timeoutInterval: method.  (You can pass in the default NSURLRequestUseProtocolCachePolicy cachePolicy parameter if you don't want to worry about that part.)  The timeout is a floating-point value in seconds, as are basically all time intervals in the iPhone SDK.
Also make sure your NSURLConnection's delegate is set and responds to the connection:didFailWithError: method.  A connection always calls either this method or connectionDidFinishLoading: upon connection completion.


text:
Q: Creating class for defining constants in swift Note: I want to achieve similar functionality in swift - Where to store global constants in an iOS application?
I have two classes - MasterViewController and DetailViewController
I want to define an enum (refer below enum) and use its values in both classes:
enum Planet: Int {
    case Mercury = 1, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}

I tried to define it in MasterViewController and use it in DetailViewController like this:
let aPlanet = Planet.Earth

but compiler is complaining :(

"Use of unresolved identifier Planet"

Generally in my objective c code I used to have a global constant file, which I used to import in app-prefix.pch file, which was making it accessible to all files within my project, but in this case I am clueless.

A: If your enum is being defined in a class like this:
class MyClass {
    enum Planet: Int {
        // ...
    }
}

You have to access it through your class:
var aPlanet = MyClass.Planet.Earth

You also want to use the rawValue property. You will need that to access the actual Int value:
var aPlanet = MyClass.Planet.Earth.rawValue

A: In swift you can declare an enum, variable or function outside of any class or function and it will be available in all your classes (globally)(without the need to import a specific file).


text:
Q: is_user_logged_in() isn't working I'm making a login form for my site, and I've this section:
<?php
if (is_user_logged_in()) {
    echo 'Hello, ', $user_login, '. Logout';
} else {
    wp_login_form();
}

And after loggin in, it returns to the page with no indication of logging in.
I suspect is_user_logged_in() isn't working, but I don't know how to debug this problem.
EDIT:
Whenever I do this:
global $current_user;
var_dump($current_user);

I always get:
ect(WP_User)#3 (7) { ["data"]=> NULL ["ID"]=> int(0) ["caps"]=> array(0) { } ["cap_key"]=> NULL ["roles"]=> array(0) { } ["allcaps"]=> array(0) { } ["filter"]=> NULL }

No matter if i've 'logged' in with the above form.

A: There's nothing wrong with the function, it's the fact that you aren't actually being logged in!
You say you're making your own login form? Does this post to the standard wp-login.php, or do you handle the request yourself?
Does the path/domain of the form differ from WordPress? If you inspect your cookies, are any being set?

A: I know it is pretty late, but I am adding my answer to help others. If you use wp_signon() function to login, and verify with is_user_logged_in() thereafter, you need to set the current user with wp_set_current_user() first because wp_signon() does not handle setting the current user as described in the WP codex:
https://developer.wordpress.org/reference/functions/wp_signon/
This is one of the reasons why the function is_user_logged_in() says false when you thought you have logged in a user already.


text:
Q: Access to variables from another target in swift I have some variables in ViewController.swift file which is located in root of the application (default location)
and I want to use them in KeyboardViewController.swift file which is located in custom keyboard target
how can I access those variables?
for being more clear I want to access the variables I have declared in ViewController.swift from a view controller in a target.
the photo will help too
you can see the sample code I have problem with here:
ViewController.swift
import UIKit

public var globalVar = "defaultColor"

class ViewController: UIViewController {

    @IBAction func buttonA(sender: UIButton) {

        globalVar = "ColorA"

    }

    @IBAction func buttonB(sender: UIButton) {

        globalVar = "ColorB"

    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

KeyboardViewController.swift
import UIKit

class KeyboardViewController: UIInputViewController {

    override func updateViewConstraints() {
        super.updateViewConstraints()

        // Add custom view sizing constraints here
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        if (globalVar == "defaultColor" /* The error is here it says use of unresolverd identifier 'globalVar' */) {

        } else if (globalVar == "ColorA") {

        } else if (globalVar == "ColorB") {

        }

    }

}

A: If you need access to a file from within an extension, all you need to do is add the file to your extension target.
However if you are dealing with extensions, be aware that you cannot access the same instances of the class that exists in each. You will have to create a separate instance inside the extension, and use that instance.

A: My problem solved with app group. Thanks Everybody
the solution:
1: Switching on App Groups for both your application and Target by clicking on application > Capabilities
2: Clicking on plus sign and set a name for app group (ex: group.company.appname) note that for both application and target should be same
3: setting NSUserDefaults like this
var defaults = NSUserDefaults(suiteName: "group.company.appname")
defaults?.setObject("Worked!", forKey: "Alarm")
defaults?.synchronize()

4: Reading NSUserDefaults where you want (like in a target) like this
// Check for null pressEffect
if let restoredDefault =  defaults!.stringForKey("Alarm") {
     print(restoredDefault)
} else {
     print("Not Working!")
}


text:
Q: Android terminal--telnet missing commands, receiving this error : KO: unknown command, try 'help' I'm trying to set the coordinates on an emulated device.
XXXX-MacBook-XXXXX XXXX$ telnet localhost 5554
Trying ::1...
telnet: connect to address ::1: Connection refused
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Android Console: Authentication required
Android Console: type 'auth <auth_token>' to authenticate
Android Console: you can find your <auth_token> in
'/Users/XXXXX/.emulator_console_auth_token'
OK

The problem is...
geo fix 77.9888 34.0000
    KO: unknown command, try 'help'

I don't seem to have the geo command
help
Android console command help:

    help|h|?         print a list of commands
    auth             use 'auth <auth_token>' to get extended functionality
    avd              control virtual device execution
    quit|exit        quit control session

try 'help <command>' for command-specific help
OK

In fact, it looks like most of my commands are missing.
Does anyone know why the commands are missing?

A: For amateurs' like me what diego-torres-milano meant :
cat /Users/XXXXX/.emulator_console_auth_token
<copy the above contents - auth_token>
telnet localhost <portnumber> (mostly 5554)
auth auth_token

A: You are not authenticated.
Obtain the content of /Users/XXXXX/.emulator_console_auth_token and after the OK prompt enter
auth <auth_token>


text:
Q: Can you format the style of the DropDownList in yii2? Can you format the style of the DropDownList in yii2 I have the following code that generates a list from a table and I wanted to change the text size and color of the items to choose from.

    <?php
    echo $form->field($model, 'spec')
    ->dropDownList(
        $specialities,
        ['prompt'=>'Any Speciality']
    )->label('');
    ?>

A: should  be the  options

<?php
      echo $form->field($model, 'spec')
      ->dropDownList(
            $specialities,
            ['prompt'=>'Any Speciality',
            'options' => ['style' => 'color: #FA4577; font-size: 18px;'],]
       )->label('');
?>


text:
Q: Getting random second long request time outs when pinging my router I'm connected to my virgin fibre optic router via tp-link powerline adapter with my ethernet cables. When i ping anywhere e.g google.co.uk or riot.de using the command prompt i get regular normal ping (around 38-42 ms) however constantly get request timeouts every 5-10 seconds. This is a huge pain in the ass when playing online games such as League of Legends as my screen will just freeze and not sure where to go from there.
https://gyazo.com/ca584b9015dbd9d182a654644a15a487
There's a gyazo of a recent ping test

A: There are a large number of factors that could be causing this packet loss. Unfortunately because.your connection is quite fast its difficult to tell much from the latencies you are seeing.
The next step is to run MTR (winMTR) which combines ping and traceroute. If run for a fair amount of time it will show where the problem is as well as the extent of it.
I would postulate that  your provider is using QoS/bandwidth pooling and dropping packets to slow down TCP connections and limit utilization.


text:
Q: DbContext issue with connection string login My DbContext has the following implementation
public class BusinessDataContext : IdentityDbContext<User, Role, Guid, UserLogin, UserRole, UserClaim>
{
    public BusinessDataContext() : base(ConnectionStringManager.GetConnectionString())
    {
    }
}

ConnectionStringManager returns a connection string based on which machine I'm working from, since there are several, however as an example...
Data Source=.;Initial Catalog=BusinessDb;User ID=sa;Password=Pa$$word123!;Integrated Security=true;Trusted_Connection=True;MultipleActiveResultSets=true

When I debug this from Visual Studio I don't run into any issues, however when I run under IIS, I get the following error

Cannot open database "BusinessDb" requested by the login. The login
  failed. Login failed for user 'IIS APPPOOL\BusinessDb'.

I don't understand why it's trying to log in as IIS APPPOOL when I've specified 'sa' in the connection string?

A: You need to specify SQL server authentication instead of Windows authentication by setting
 Integrated Security=false

in the connection string.
By setting Integrated Security=true the API tries to use Windows authentication and to log in IIS APPPOOL\BusinessDb which probably has no rights on your SQL server.


text:
Q: Power fit to some experimental data I have to fit some data to a power law
$$ F=\alpha q^{\beta}$$
being $q$ and $F$ the experimental data points. What I usually do is taking logs so that
$$ \ln(F) = \beta \ln(q)+\ln(\alpha)$$
and apply least squares with uncertainties in both variables. How may I approach this in the case that some of the values of $q$ (and eventually $F$) are negative?. If it helps $\beta$ should be compatible with a value of $1$, but I want a general approach.
Edit:
The law to be fitted is Coulomb's law, $F$ is the force between to charged spheres. One of them has fixed charge, the other is a variable we call $q$. The proportionality constant $\alpha$ is related to $\varepsilon_0$ with a known expression in powers of $\beta=\frac{R}{d}$ where $d$ is the distance between the centers of the spheres and $R$ is their radius. So, I want to determine, from experiment, both $\alpha$ and $\beta$ and compare them with $\varepsilon_0$ and $1$.
The actual values are
$$
\begin{array}{|c|c|}
\hline
q / \mathrm{nC} & F / \mathrm{mN} \\ \hline
-26,8 \pm 0.8 & -1.5   \\ \hline
-18.8 \pm 0.5  & -1.1   \\ \hline
-9.9 \pm 0.2  & -0.6   \\ \hline
9.9 \pm 0.2   & 0.5    \\ \hline
18.8 \pm 0.5  & 1.0    \\ \hline
26.8 \pm 0.8   & 1.5    \\ \hline
35 \pm 2    & 2.1     \\ \hline
\end{array}
$$
with the uncertainty in the last decimal place for the forces.

A: Are you sure that it is $q$ taking the negative value and not $\alpha$?
Non-integer powers of negative numbers are complex, so this surely is not what your experiment returned as values for $F$.
If you already know that $\beta$ can only take integer values, you could fit
$$ F_1 = \alpha q^1$$ $$ F_2 = \alpha q^2 $$ and $$F_3 = \alpha q^3$$ and show that $\beta = 1$ is the best fit.
If indeed it is $\alpha$ taking negative values along with $F$, then just fit
$$ -F = -\alpha q^\beta$$
If F only sometimes takes negative values, it might be shifted, i.e.
$$ F = \alpha q^\beta - \gamma$$
Then you can fit $$ F + \gamma = \alpha q^\beta$$
where $\gamma$ is the minimum of $F$.
In your case, you can decide whether the charges are same sign or alternate sign. Write up the observation that alternate signs attract, while same signs repel and fit the absolute value of force over the absolute value of charge, finding a slope of $1/4\pi\epsilon_0$ and a power of 1. Of course, for the absolute values you can use the $\log$ thing, which (edit) apperently is not (/edit) very elegant!

A: Taking the logarithms of negative numbers isn't a viable solution.
When you postulate $ F=\alpha q^{\beta}$ you are implicitly supposing that is F is a real number, q is positive.
Just make a least square fit using the absolute values of $F$, $\alpha$ and $q$:
If $ F=\alpha q^{\beta}$ then $ |F|=|\alpha| |q|^{\beta}$, so $ \ln(|F|) = \beta \ln(|q|)+\ln(|\alpha|)$.
That certainly will work.
Next study the sign: it is evident from data that with negative charge you get negative force. Then you can conclude that $\alpha$ is positive.

A: Being a mathematician, I feel that I should point out a common misconception here. Don't feel too bad, plenty of mathematicians (including myself) have fallen into this trap. Basically, if you want to fit data to power law using least squares methods, then you should NOT fit a straight line in log log space. You should fit a power law using non-linear least squares to the original data in linear space without any kind of transformation.
The basic intuition behind this is this. Least squares method assume that the error distribution is normal meaning that there is one true (unknown) value which you are trying to measure and the measurements you are taking are above/below the true value staying close to the true value so the distribution is gaussian. The problem is that log is not a linear function so when you take log log of the data, numbers bigger than one are pushed together and numbers less than one are spread apart and namely, the error distribution is not normal any more in log log space....meaning that least squares is not guaranteed to converge to the true values any more. In fact it has been proven that fitting in log-log space consistently gives you biased results.
Fitting a straight line in log-log was fashionable back in the day before GHz processors. Now whatever you are using to do the computation, most likely has the ability to do non-linear least squares power law fit to the original data so that is the one you should do. Since power-law is so prevalent in science, there are many packages and techniques for doing them efficiently, correctly, and fast.
I refer you to these published results and a rant here. This is the my question which sparked this discussion.

Addendum:
So by OP's request here is an actual example. The actual function is $y=f(x)=2x^{-4}=ax^b$. I take a bunch of points from $x\in[1,2]$ and $x=10$. Note that $f(10)=0.0002$ and I change this $y$-value to $y=0.00002$ while keeping all others the same and then fitting them using least squares to estimate $a$ and $b$.
Using non-linear least squares fit to the functional form $y=ax^b$ gives us
\begin{eqnarray}
a&=&2\\
b&=&-4\\
r^2&=&0.9999.
\end{eqnarray}
Using linear least squares fit to the functional form $y=mx+n$ in log-log space gives us
\begin{eqnarray}
a &=& exp(n) = 2.46\\
b &=& m = -4.57\\
r^2 &=& 0.9831.
\end{eqnarray}
The $95\%$ bounds for $b$ are $(-4.689, -4.451)$ which doesn't even include the true value for $b$. Basically log pushes numbers bigger than one together and spreads apart numbers less than one. So in linear space changing $y=0.0001$ to $y=0.00001$ is inconsequential. The algorithm doesn't care too much about it. The change in the residual is very tiny. In log-log space the difference is rather huge (an entire order of magnitude) and the point has become an "outlier" from the nice linear trend. The change in residual is now large. Since the algorithm is trying to minimize the sum of the squares, the algorithm can't ignore the deviation and must try to accommodate the outlier point so the line is skewed messing up the slope and the intercept.
Here is the MATLAB code and the graphs. You can easily reproduce this and play with it yourself. Blue are the data points. Black is the power fit in linear space. Red is the fitted line from log-log least squares fitting. The top panel shows all three in linear space and the bottom panel shows all three in log-log space to emphasize the differences. The exponent is off by more than a half between the two methods. But how see how good the second fit it ($r^2=0.98$) and the confidence interval is nowhere near the true value of $b$. The algorithm is very confident that $b\neq-4$.
The same effect will work in reverse with large changes in large numbers. For example, changing a data point from 10000 to 20000 in linear space will cause a huge change but in log-log space the change is not a big deal at all so the algorithm will again give misleading results.
close all
clc
clear all

x = [1:0.01:2 10];
y = 2*x.^(-4);
y(end)
y(end) = 0.00002;

% The power law fit on the original data
ft = fittype( 'power1' );
opts = fitoptions( 'Method', 'NonlinearLeastSquares' );
opts.Display = 'Off';
[fitresult1, gof1] = fit(x',y', ft, opts )

% The linear fit in log-log space
logx = log(x);
logy = log(y);
[fitresult2, gof2] = fit(logx',logy',fittype( 'poly1' ))

% The plots
x1 = min(x):0.01:max(x);
y1 = fitresult1.a*x1.^fitresult1.b;
y2 = exp(fitresult2.p1*log(x1)+fitresult2.p2);
figure
subplot(2,1,1)
plot(x,y,'o',x1,y1,'k',x1,y2,'r')
xlim([min(x),max(x)+1])
subplot(2,1,2)
loglog(x,y,'o',x1,y1,'k',x1,y2,'r')
xlim([min(x),max(x)+1])
legend('Data','Power Fit','Linear Fit')

Second Addendum:

Does non linear least squares manage a set of points with experimental/numerical errors?

I am assuming by manage you mean if NLLSF will give us an unbiased estimate of the parameters. The answer to that is, least squares fitting works if and only if the errors are gaussian. So if the errors are random errors (with the expected value and arithmetic mean being zero) then least squares gives you an unbiased estimate of the true parameter values. If you have any type of systematic error then least squares is not guaranteed to work. We often assume/want-to-think that we only have random error unless there is good evidence to the contrary.

And also does give the uncertainties in both a and b based on those parameters?

Again assuming errors being normally distrubuted, there are standard methods for estimating the error deviation. The mean is already assumed to be zero. We estimate the standard error for each parameter and then we use it to compute the confidence intervals. So yes, if I ONLY have experimental data and I have no idea what the real values of the parameters are, then I can still compute the confidence intervals.

Now an introductory bibliographic reference other than wikipedia would be very helpful.

I don't know of a good stats/regression book I can recommend. I would say just pick your favorite intro to stats book. And there are those papers by Clauset that I linked to both available on Arxiv for free.

TL;DR

*

*Physicist think everything is a power law. It isn't. Even if the data looks like its power law, it probably isn't.

*If you do legitimately have a power law, don't fit a straight line in log-log space. Just use NLLSF to fit a power law on the original data. If there is still any doubt, I can easily make up a numerical example and show you concretely how different the two answers can be.

A: This sort of problem is reasonably straightforward to solve numerically using Gauss-Newton or similar algorithms and your favourite programming language. Matlab even has an entire curve fitting toolbox which does everything very nicely.
These non-linear least squares techniques should work for any (differentiable) function, so have quite a lot of applications.


text:
Q: iOS UIPageControl Replace Status Bar I am wondering how you would replace the status bar or at least place the page control over it?  This would be a temporary placement for a couple seconds each time someone pages then it will disappear.  I have seen it in apps before.

A: I dont think you cant get above the statusbar as it doesn't belong to your root-window.
But can call this to remove the UIStatusBar manually even with animation option.
[[UIApplication sharedApplication] setStatusBarHidden:YES animated:NO];

You can also disable it in your window in InterfaceBuilder. Or you can add the key Status bar is initially hidden = YES in your appname-Info.plist file.
Then you can do with the space what you want.
Maybe you want to remove it and then let it appear again, but be aware that your root-window-size will change due to the 20 pixel you gain from the hidden statusbar.


text:
Q: Data is gone after refresh or closing browser - Laravel Data is becoming null after i edit and refresh several times the page or after closing and opening the browser the data is gone.
I use db in controller
use DB;

here is my view
    {!! Form::open(['action' => ['Admin\SettingsController@index'], 'method' => 'POST']) !!}

            <select name="aircraft_id" class="form-control" id="">
              <option value="0" disabled="true" selected="true"> Select </option>
              @foreach ($aircrafts as $aircraft)
                  <option name="aircraft_id" value="{{ $aircraft->aircraft_id }}">{{ $aircraft->aircraft_registration_number }}</option>
              @endforeach
            </select>

            <br>

            {{Form::hidden('_method', 'PUT')}}
            {{Form::submit('BIND', ['class'=>'btn btn-primary btn-block btn-lg', 'name'=>'submit'])}}

                  {!! Form::close() !!}

my controller
 $airid = $request->input('aircraft_id');   <------ used to call textbox

     $aircraft = DB::table('series')   <----------update my data
      ->update(['aircraft_id' => $airid]);

So after running and updating all this code , I can manage to update my data but again as ive said after refreshing,closing and reopening or any kind of things that may close or refresh the browser, the data is NULL nad Removed
What i just want is to make the data permanent

A: I don't know Laravel but looking at it's documentation regarding database updated it looks like you need a where statement before the update. In some databases when you forget the where, all entries in the table will be updated to the passed value.
Also, in HTML, only the select element has a name attribute. The option element should not have a name.

A:  $airid = $request->input('aircraft_id');   <------ used to call textbox

 $aircraft = DB::table('series')   <----------update my data
  ->update(['aircraft_id' => $airid]);

=> it seems like you're trying to updated all 'aircraft_id' to value passed in $airid. This might be wrong when the column definition is Primary_Key or it's defined as unique. So all you need to do is:
DB::table('series')
        ->where('aircraft_id', $airid)
        ->update(<column_name> => <value>]);

Here  is the column name you would like to update value of.
      is value you would like to set to the desired column you've entered.


text:
Q: Find the unit vector
Let the given vectors be: $\vec a= \vec u+ \vec v$ , $\vec b = 2\vec u + \vec v$ , $|\vec u| = 2$ $,|\vec v| = 4$ and angle between vectors $\vec u$ and $\vec v$ is $120^\circ$.
Express the unit vector $\vec x$ over vectors $\vec u$ and $\vec v$ if $\vec x$ bisects the angle between vectors $\vec a$ and $\vec b$.

I dont know how to find this unit vector. I know that $\cos(\angle(a,b)) = \dfrac{\vec a\vec b}{|\vec a||\vec b|}$. But I don't know what to do with it. I would appreciate any help.


text:
Q: Pull data from AWS RDS to ECS container running a Flask app only when triggered (once daily) I have a dockerized plotly-Dash Flask app pushed to AWS Elastic Container Registry and running on the Elastic Container Service. It communicates fine with my RDS database on the same account.
Currently, data gets pulled from within the Flask app on every refresh of the page, but I would like to be able to trigger the Flask app to pull the data from RDS (once daily at possibly different times day to day, if that makes a difference).
The only way I've found so far is changing the structure so that it is only pulling the data once in the script before the Flask app is started, and then killing the task/restarting a new task every day. This shouldn't be the only way to do this and I'm sure someone here knows a much better way.
My hope would be this:

*

*Python script connects to MySQL db on RDS

*Pulls data to pandas df

*Uses data for Flask app

*I can trigger a new pull of the data without having to kill the task.

A: I think you can create a trigger on your DB table to call a lambda function which can trigger ECS. see the following example: here


text:
Q: JNLP application starts and before loading stops while launching via marathon JavaProfile Webstart Hi my JNLP application strats and then stops after some time. Here is the error
`Dec 03, 2019 10:54:46 AM net.sourceforge.marathon.javadriver.JavaDriverCommandExecutor start

INFO: Executing: [C:\Program Files (x86)\Common Files\Oracle\Java\javapath\javaws.exe,
C:\QThinClient.jnlp][ {JAVA_TOOL_OPTIONS=-DkeepLog=false -Dmarathon.launch.mode=webstart -Dmarathon.mode=playing -Dmarathon.agent=file:/C:/Users/stalin_felix/.m2/repository/com/jaliansystems/marathon-java-agent/5.2.6.0/marathon-java-agent-5.2.6.0.jar -javaagent:"C:\Users\stalin_felix\.m2\repository\com\jaliansystems\marathon-java-agent\5.2.6.0\marathon-java-agent-5.2.6.0.jar"=61197}]

java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at sun.instrument.InstrumentationImpl.loadClassAndStartAgent(Unknown Source)
    at sun.instrument.InstrumentationImpl.loadClassAndCallPremain(Unknown Source)

Caused by: java.awt.AWTError: Error trying to install Assistive Technology:
com.sun.java.accessibility.AccessBridge java.security.AccessControlException: access denied ("java.lang.RuntimePermission" "accessClassInPackage.com.sun.java.accessibility")
    at java.awt.Toolkit.loadAssistiveTechnologies(Unknown Source)
    at java.awt.Toolkit.getDefaultToolkit(Unknown Source)
    at net.sourceforge.marathon.javaagent.JavaElementPropertyAccessor$InternalFrameMonitor.init(JavaElementPropertyAccessor.java:892)
    at net.sourceforge.marathon.javaagent.JavaAgentHook.premain(JavaAgentHook.java:42)
    ... 6 more
FATAL ERROR in native method: processing of -javaagent failed
Picked up JAVA_TOOL_OPTIONS: -DkeepLog=false -Dmarathon.launch.mode=webstart -Dmarathon.mode=playing -Dmarathon.agent=file:/C:/Users/stalin_felix/.m2/repository/com/jaliansystems/marathon-java-agent/5.2.6.0/marathon-java-agent-5.2.6.0.jar -javaagent:"C:\Users\stalin_felix\.m2\repository\com\jaliansystems\marathon-java-agent\5.2.6.0\marathon-java-agent-5.2.6.0.jar"=61197
Exception in thread "main" Dec 03, 2019 10:57:17 AM net.sourceforge.marathon.javadriver.JavaDriverCommandExecutor start
WARNING: Unable to estabilsh connection with the application(timeout): [C:\Program Files (x86)\Common Files\Oracle\Java\javapath\javaws.exe, C:\QThinClient.jnlp][ {JAVA_TOOL_OPTIONS=-DkeepLog=false -Dmarathon.launch.mode=webstart -Dmarathon.mode=playing -Dmarathon.agent=file:/C:/Users/stalin_felix/.m2/repository/com/jaliansystems/marathon-java-agent/5.2.6.0/marathon-java-agent-5.2.6.0.jar -javaagent:"C:\Users\stalin_felix\.m2\repository\com\jaliansystems\marathon-java-agent\5.2.6.0\marathon-java-agent-5.2.6.0.jar"=61197}]
null---------null`

If anyone help solve this issue, please.


text:
Q: How to assert a monkey patch was called in pytest? Consider the following:
class MockResponse:
    status_code = 200

    @staticmethod
    def json():
        return {'key': 'value'}
                                  # where api_session is a fixture
def test_api_session_get(monkeypatch, api_session) -> None:
    def mock_get(*args, **kwargs):
        return MockResponse()

    monkeypatch.setattr(requests.Session, 'get', mock_get)
    response = api_session.get('endpoint/') # My wrapper around requests.Session
    assert response.status_code == 200
    assert response.json() == {'key': 'value'}
    monkeypatch.assert_called_with(
        'endpoint/',
        headers={
            'user-agent': 'blah',
        },
    )

How can I assert that the get I am patching gets called with '/endpoint' and headers? When I run the test now I get the following failure message:
FAILED test/utility/test_api_session.py::test_api_session_get - AttributeError: 'MonkeyPatch' object has no attribute 'assert_called_with'
What am I doing wrong here? Thanks to all those of who reply in advance.

A: You need a Mock object to call assert_called_with - monkeypatch does not provide that out of the box. You can use unittest.mock.patch with side_effect instead to achieve this:
from unittest import mock
import requests

...

@mock.patch('requests.Session.get')
def test_api_session_get(mocked, api_session) -> None:
    def mock_get(*args, **kwargs):
        return MockResponse()

    mocked.side_effect = mock_get
    response = api_session.get('endpoint/')
    ...
    mocked.assert_called_with(
        'endpoint/',
        headers={
            'user-agent': 'blah',
        },
    )

Using side_effect is needed to still get a mock object (mocked in this case, of type MagickMock), instead of just setting your own object in patch, otherwise you won't be able to use the assert_called_... methods.

A: Going to add another response that uses monkeypatch rather than "you can't use monkeypatch"
Since python has closures, here is my poor man's way of doing such things with monkeypatch:
patch_called = False

def _fake_delete(keyname):
    nonlocal patch_called
    patch_called = True
    assert ...

monkeypatch.setattr("mymodule._delete", _fake_delete)
res = client.delete(f"/.../{delmeid}"). # this is a flask client
assert res.status_code == 200
assert patch_called

In your case, since we are doing similar things with patching an HTTP servers method handler, you could do something like (not saying this is pretty):
param_called = None

def _fake_delete(param):
    nonlocal param_called
    patch_called = param
    assert ...

monkeypatch.setattr("mymodule._delete", _fake_delete)
res = client.delete(f"/.../{delmeid}")
assert res.status_code == 200
assert param_called == "whatever this should be"


text:
Q: Parse string to store lead_id as a variable I need to extract the $lead_id here when this is returned to me from an endpoint. What you are looking at here is part of the actual source code of the endpoint I am sending a GET request to
echo "$result: $result_reason - $phone_number|$list_id|$lead_id|$gmt_offset|$user\n";

Here is an example of what is returned to me: SUCCESS: add_lead LEAD HAS BEEN ADDED - 27000000000|6015|81527|2|9000 and I need to store this lead_id, 81527, as a variable on my end


text:
Q: installation of package had non-zero exit status - Linux Server I work with on windows 10 with R. As my project is calculation heavy, i want to use my universities Linux server to do the calculations. The installation of a package (and also its dependencies if tried individually) does not work.
Installing other packages works fine. So i tried to install my package over the console which didn't work, then i accessed R in the console and tried installing it which didn't work. Next i copied my library from my PC in the library which my R accesses on the Linux server. While it works perfectly on my PC, the server tells me it doesn't find my package.
I use the usual install.packages("prodest"), i also tried stuff like install.packages("prodest", dependencies = T), or installing dependencies which it needs directly [like install.packages("haven")].
I would like to install this to then run my script on the server. Some further information:
Warning message on the Server:

    compilation terminated.
/usr/lib64/R/etc/Makeconf:167: recipe for target 'readstat/spss/readstat_zsav_compress.o' failed
make: *** [readstat/spss/readstat_zsav_compress.o] Error 1
ERROR: compilation failed for package 'haven'
* removing '/home/rid52xb/R/x86_64-suse-linux-gnu-library/3.6/haven'
* installing *source* package 'curl' ...
** package 'curl' successfully unpacked and MD5 sums checked
** using staged installation
Package libcurl was not found in the pkg-config search path.
Perhaps you should add the directory containing `libcurl.pc'
to the PKG_CONFIG_PATH environment variable
No package 'libcurl' found
Package libcurl was not found in the pkg-config search path.
Perhaps you should add the directory containing `libcurl.pc'
to the PKG_CONFIG_PATH environment variable
No package 'libcurl' found
Using PKG_CFLAGS=
Using PKG_LIBS=-lcurl
------------------------- ANTICONF ERROR ---------------------------
Configuration failed because libcurl was not found. Try installing:
 * deb: libcurl4-openssl-dev (Debian, Ubuntu, etc)
 * rpm: libcurl-devel (Fedora, CentOS, RHEL)
 * csw: libcurl_dev (Solaris)
If libcurl is already installed, check that 'pkg-config' is in your
PATH and PKG_CONFIG_PATH contains a libcurl.pc file. If pkg-config
is unavailable you can set INCLUDE_DIR and LIB_DIR manually via:
R CMD INSTALL --configure-vars='INCLUDE_DIR=... LIB_DIR=...'
--------------------------------------------------------------------
ERROR: configuration failed for package 'curl'
* removing '/home/rid52xb/R/x86_64-suse-linux-gnu-library/3.6/curl'
ERROR: dependencies 'haven', 'curl' are not available for package 'rio'
* removing '/home/rid52xb/R/x86_64-suse-linux-gnu-library/3.6/rio'
ERROR: dependency 'rio' is not available for package 'car'
* removing '/home/rid52xb/R/x86_64-suse-linux-gnu-library/3.6/car'
ERROR: dependency 'car' is not available for package 'AER'
* removing '/home/rid52xb/R/x86_64-suse-linux-gnu-library/3.6/AER'
ERROR: dependency 'AER' is not available for package 'prodest'
* removing '/home/rid52xb/R/x86_64-suse-linux-gnu-library/3.6/prodest'

The downloaded source packages are in
        '/tmp/RtmpGxZbcG/downloaded_packages'
1: In install.packages("prodest") :
  installation of package 'haven' had non-zero exit status
2: In install.packages("prodest") :
  installation of package 'curl' had non-zero exit status
3: In install.packages("prodest") :
  installation of package 'rio' had non-zero exit status
4: In install.packages("prodest") :
  installation of package 'car' had non-zero exit status
5: In install.packages("prodest") :
  installation of package 'AER' had non-zero exit status
6: In install.packages("prodest") :
  installation of package 'prodest' had non-zero exit status

Session Info on the server:
R version 3.6.0 (2019-04-26)
Platform: x86_64-suse-linux-gnu (64-bit)
Running under: SUSE Linux Enterprise Server 12 SP4

Matrix products: default
BLAS:   /usr/lib64/R/lib/libRblas.so
LAPACK: /usr/lib64/R/lib/libRlapack.so

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C
 [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8
 [7] LC_PAPER=en_US.UTF-8       LC_NAME=C
 [9] LC_ADDRESS=C               LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] data.table_1.12.2

loaded via a namespace (and not attached):
[1] compiler_3.6.0 tools_3.6.0

Session info on my PC:
R version 3.6.1 (2019-07-05)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 17134)

Matrix products: default

locale:
[1] LC_COLLATE=German_Germany.1252  LC_CTYPE=German_Germany.1252    LC_MONETARY=German_Germany.1252
[4] LC_NUMERIC=C                    LC_TIME=German_Germany.1252

attached base packages:
[1] parallel  stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] prodest_1.0.1     Matrix_1.2-17     dplyr_0.8.3       data.table_1.12.2

loaded via a namespace (and not attached):
 [1] zip_2.0.3         Rcpp_1.0.2        cellranger_1.1.0  pillar_1.4.2      compiler_3.6.1
 [6] forcats_0.4.0     tools_3.6.1       zeallot_0.1.0     tibble_2.1.3      lattice_0.20-38
[11] pkgconfig_2.0.2   rlang_0.4.0       openxlsx_4.1.0.1  curl_4.0          DEoptim_2.2-4
[16] haven_2.1.1       rio_0.5.16        AER_1.2-7         vctrs_0.2.0       hms_0.5.0
[21] lmtest_0.9-37     grid_3.6.1        tidyselect_0.2.5  glue_1.3.1        R6_2.4.0
[26] survival_2.44-1.1 readxl_1.3.1      foreign_0.8-71    Rsolnp_1.16       carData_3.0-2
[31] Formula_1.2-3     purrr_0.3.2       car_3.0-3         magrittr_1.5      splines_3.6.1
[36] backports_1.1.4   abind_1.4-5       assertthat_0.2.1  sandwich_2.5-1    truncnorm_1.0-8
[41] crayon_1.3.4      zoo_1.8-6

A: You may need to install (or get your admin to install) libcurl on the SUSE Linux server. On Ubuntu (which your university server does not have) you might do:
sudo apt-get -y install libcurl4-openssl-dev

But on SUSE I read that Yast might be a more typical package management choice.
After getting your system dependencies in shape, you still need to handle the dependencies in R, so consider this (with the warning that it may take a long time):
install.packages( c(tools::package_dependencies(package="prodest", recursive=TRUE)$prodest,
                    "prodest")
                 )

Unfortunately install.packages is not recursive in its searching of a dependency tree, i.e. the dependencies of the dependencies of the dependencies, etc..... That said, the number of dependencies in that particular recursively assembled tree was 77, and it might have been faster to simply install the four or five named packages that were missing.
 install.packages( c( 'haven' 'curl' , 'rio, 'car', 'AER'), dependencies=TRUE)