text:
Q: Sub component template not rendered I created a brand new project with jhipster using angular, internationalization and maven.
The project compiles and runs without any problem.
Than I created a new angular component with:
ng generate component my-new-component
I included that component into src/main/webapp/app/layouts/main/main.component.html
<jhi-page-ribbon></jhi-page-ribbon>

<router-outlet name="navbar"></router-outlet>

    <router-outlet></router-outlet>
    <router-outlet name="popup"></router-outlet>

<jhi-footer></jhi-footer>
<jhi-my-new-component></jhi-my-new-component>

and also into src/main/webapp/app/home/home.component.html

Welcome, Java Hipster!

      <jhi-my-new-component></jhi-my-new-component>

This is your homepage

The component into main.component.html is correctly rendered.
But on the second case, home.component.html, the component tag is rendered, but component's template is not rendered.
Any suggestion will be really appreciated.
Some info:

Using JHipster version installed locally in current project's node_modules
  4.14.1
our global Angular CLI version (1.7.3) is greater than your local
  version (1.6.6). The local Angular CLI version is used.


text:
Q: Using pandas apply function on multilevel DataFrame Suppose this is my multilevel DataFrame:
States = pd.DataFrame({'Alaska' : [1, 2, 3, 4], 'Arizona': [5, 6, 7, 8]},
                      index=pd.MultiIndex(levels=[['A', 'B'], ['x','y']],
                      labels=[[1,1,0,0],[1,0,1,0]])).T

I'm trying to derive new variables from this DataFrame.
def scoring_algorithm(x):
    return x[('A', 'x')] + 100
States.apply(scoring_algorithm)

But this throws an error
KeyError: (('A', 'x'), 'occurred at index (B, y)')
I assume from the error that my column selector ('A', 'x') is not satisfactory, but I can't find any resources for how to use this for an apply function.
Note: I need the apply function or something similar because the final scoring algorithm requires several columns as inputs to the apply function.
Thanks in advance for any guidance!

A: You're currently applying to the index.
df.apply(fxn)

is equivalent to:
df.apply(fxn, axis='index')

You need to apply to the columns.
df.apply(fxn, axis='columns')

So for you:
States.apply(scoring_algorithm, axis='columns')

and I get:
Alaska     104
Arizona    108
dtype: int64

redpajama_set_name: RedPajamaStackExchange


text:
Q: publish 5 words from model title django I have a model :
  class publish(models.Model):
    publish_time=models.DateTimeField(auto_now_add=True)
    owner=models.ForeignKey(User, on_delete=models.CASCADE)
    Publish_Your_Story=models.TextField()

    def __str__(self):
      return '{}'.format(self.Publish_Your_Story)

I have views.py :
class Index(ListView):
    model=publish

Template:

Articles

{% for article in object_list %}

{{ article }}

 {% empty %}

No articles yet.

  {% endfor %}

Now i want to publish only 10 words from Publish_Your_Story row from models as article in Template . Kindly help .


text:
Q: Which is the most memory effective way to implements an iteration statement? I know that there are ways to know the cost of cycle or an iteration statement, but I want to know 2 things:
1st.
Which of these two listing is more cost effective? (or if there are a better approach, I'm all ears):
UPDATE: The question then goes: Wich of the 2 of them will do proper use of the memory/GC?
Keep in mind that, the "values" of reqObj and resObj are not going to be necessary for the next loop.
for (TransactionLog transactionLog : transactionLogList) {
 RequestObj reqObj = new RequestObj();
 ResponseObj resObj;
 try {

  //do things with these 2 babes and the transactionLog

 } catch (WhateverException ex) {
  log.error("Error in XYZ while doing whatever", ex);
  //execute code without throwing anything up
 } finally {
  reqObj = null;
  resObj = null;
 }
}

or
RequestObj reqObj = new RequestObj();
ResponseObj resObj;
for (TransactionLog transactionLog : transactionLogList) {
 try {
  //do things with these 2 babes and the transactionLog

 } catch (WhateverException ex) {
  log.error("Error in XYZ while doing whatever", ex);
  //execute code without throwing anything up
 } finally {
  //do something
 }
}

and 2nd.
Where I can find a good place/book/site to learn this "algorithms best practice" and the function O(letter) to calculate the interation's statement cost?
PD: Sorry for my English... he's not very good looking. xD

A: Local objects is clearer, less error prone, and such objects get handled well by the garbage collector. For reusable objects like a StringBuilder you could clear in every cycle instead of doing new StringBuilder I was surprised it holds too (said someone).
Just as setting to null is a beginner's signature.

A: If RequestObj and ResponseObj are AutoCloseable (or you implement them as such), then you should consider using the try-with-resources block available with Java 7. It takes care of any cleanup that they require, or that you want, without the extra finally (or an additional catch in the finally, for that matter; those exceptions are suppressed).
try( RequestObj reqObj = new RequestObj(); ResponseObj resObj = ... ) {
  // Do stuff

} catch (WhateverException ex) {
  log.error("Error in XYZ while doing whatever", ex);
  // execute code without throwing anything up
}

// No finally block required

You shouldn't worry about the GC/Memory issues as much as that seems to be premature optimization in your case. It's better to keep your code clean and readable.
For more information: http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html


text:
Q: how to calculate integrate about Heaviside everyone,here I have a question about how to calculate
 $$\int e^t H(t) dt$$
where $H(t)$ is Heaviside step function
thank you for your answering!!

A: $$
\int f(t) H(t), dt = \int_0^{+\infty} f(t)
$$

A: Hint: The Heaviside function is defined as
\begin{aligned}
\text{H}(t) & = 0, \quad t<0,\\
\text{H}(t) & = 1, \quad t\geq0.
\end{aligned}
That means your integrand will be zero for all $t<0$, and $e^{t}$ for $t\geq1$. Can you figure out the rest?
Note: If you use the half-maximum convention though, you will find it to be:
\begin{aligned}
\text{H}(t) & = 0, \quad t<0,\\
\text{H}(t) & = \frac{1}{2}, \quad t=0,\\
\text{H}(t) & = 1, \quad t>0.
\end{aligned}
If so, you will have the integrand is $\frac{1}{2}e^{t}$ in $t=0$, and the rest is similar to the above.

A: The derivative that you need is zero in the negatives and an exponential in the positives. Hence take a constant in the negatives and an exponential in the positives.
$$H(-x)+e^xH(x)$$ will be continuous. No solution can be differentiable at $x=0$.

A: In fact the result is just trivially
$\int e^tH(t)~dt=e^tH(t)+C$


text:
Q: Conditionally create resources with terraform I'm trying to write a module to deploy Sensu on AWS, the plan was to use elasticache for Redis but now I'm facing an edge case. Some of our VPCs have tenancy set to dedicated and we can't use elasticache there(http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/AmazonVPC.EC.html), I thought I could work around this by conditionally using elasticache or deploying a redis cluster in a ASG. I've written the code and used:
count = "${replace(replace(var.vpc_instance_tenancy,"/.*dedicated.*/","0"),"/(.*default.*|^$)/","1")}"

to decide if I should create the elasticahe cluster or the ASG, the problem is that I need to pass a hostname or IP address to the Sensu servers and api nodes so that they can connect to Redis, was planning to use:
redis_host = "${coalesce(aws_elasticache_cluster.redis_cluster.cache_nodes.0.address,aws_elb.redis_lb.dns_name)}"

but this always fails because one of the resources never gets created and I can't reference it in the coalesce function. Any ideas?

A: I managed to get this working, looks like we can reference inexistent resources if we use the splat variable format, like this:
redis_host = "${element(concat(aws_elasticache_cluster.redis_cluster.*.cache_nodes.0.address, aws_elb.redis_lb.*.dns_name), 0)}"
redis_port = "${element(concat(aws_elasticache_cluster.redis_cluster.*.cache_nodes.0.port, list(var.redis_port)), 0)}"

so the nonexistent resource will return an empty list and the other one will return a single element list, I concat them both together and get the first element.


text:
Q: Google Cloud ML using Rest API Can any one help me how to access google cloud ml service using Rest API in python. I have tried it using postman but it gives 404 in response everytime.I have some project  on google cloud I just want to use all the apis available on https://cloud.google.com/ml-engine/reference/rest/

A: You can find examples from Datalab:
Training service:
https://github.com/googledatalab/pydatalab/blob/master/google/datalab/ml/_job.py#L61
Prediction service:
https://github.com/googledatalab/pydatalab/blob/master/google/datalab/ml/_cloud_models.py#L225
Alternatively, instead of calling CloudML service endpoints directly, you can try Datalab's ml toolbox itself which supports structured data and image classification. You can view the notebooks first without setting up datalab:
https://github.com/googledatalab/notebooks/tree/master/samples/ML%20Toolbox
To set up Datalab and actually run these notebooks, see https://cloud.google.com/datalab/docs/quickstarts.


text:
Q: Generate a shadow/outline uniformly around an element without the blur effect I have an element (let's say icon) with an irregular shape.
I want some kind of outline around it that conforms the shape in a certain color. The color of this outline must be uniformly around the shape, i.e. have the same distance from it everywhere and no color gradient.
What I found was using the css option filter: drop-shadow()
See: https://jsfiddle.net/m8w94qsz/3/
However, the generated shadow either has a blur effect (first example) or is not placed uniformly around the element (second example).
Is there any way to achieve the desired result with CSS?

A: You may use filter: url() with an svg filter like so:

svg{position:absolute; left:-10em;}
.my-icon {
  content: url('https://img.icons8.com/officel/344/arrow.png');
  filter: url('#outline');
}
<svg width="0" height="0">
<filter id="outline">
<feMorphology in="SourceAlpha" result="expanded"
operator="dilate" radius="3"/>
<feFlood flood-color="red" result="red" />
<feComposite in ="red" in2="expanded" operator="in" />
<feComposite in="SourceGraphic"/>
</filter>
</svg>

A: An interesting and useful answer @enxaneta inspired this answer
The examples below use a more complex set of filters.
But with this combination of filters, it becomes possible to adjust the thickness of the stroke, the presence or absence of a gap between the figure and the stroke.

*

*Icon stroke in red without a gap

Note the value of the radius attribute
      <feMorphology id="fm1" operator="dilate" in="SourceAlpha"
                    radius="5" result="e1" >
      </feMorphology>
          <feMorphology id="fm2" operator="dilate" in="SourceAlpha"
                        radius="0.01" result="e2" >
            </feMorphology>

svg{position:absolute; left:-10em;}
.my-icon {
  content: url('https://img.icons8.com/officel/344/arrow.png');
  filter: url('#groupborder');
}
<svg width="0" height="0">
<defs>
    <filter id="groupborder" filterUnits="userSpaceOnUse"
            x="-1%" y="-1%" width="360" height="360">
      <feMorphology id="fm1" operator="dilate" in="SourceAlpha"
                    radius="5" result="e1" >
      </feMorphology>
    <feMorphology id="fm2" operator="dilate" in="SourceAlpha"
      radius="0.01" result="e2" >
   </feMorphology>
      <feComposite in="e1" in2="e2" operator="xor"
                   result="outline"/>
      <feColorMatrix type="matrix" in="outline"
                     values="0 0 0 1 0
                             0 0 0 0 0
                             0 0 0 0 0
                             0 0 0 1 0" result="outline2"/>
      <feComposite in="outline2" in2="SourceGraphic"
                   operator="over" result="output"/>
    </filter>
  </defs>
</svg>

*

*Changing the stroke thickness is achieved by changing the attribute
ralius =" 10 "
<feMorphology id="fm1" operator="dilate" in="SourceAlpha"
                    radius="10" result="e1" >

svg{position:absolute; left:-10em;}
.my-icon {
  content: url('https://img.icons8.com/officel/344/arrow.png');
  filter: url('#groupborder');
}
<svg width="0" height="0">
<defs>
    <filter id="groupborder" filterUnits="userSpaceOnUse"
            x="-1%" y="-1%" width="360" height="360">
      <feMorphology id="fm1" operator="dilate" in="SourceAlpha"
                    radius="10" result="e1" >
      </feMorphology>
    <feMorphology id="fm2" operator="dilate" in="SourceAlpha"
      radius="0.01" result="e2" >
   </feMorphology>
      <feComposite in="e1" in2="e2" operator="xor"
                   result="outline"/>
      <feColorMatrix type="matrix" in="outline"
                     values="0 0 0 1 0
                             0 0 0 0 0
                             0 0 0 0 0
                             0 0 0 1 0" result="outline2"/>
      <feComposite in="outline2" in2="SourceGraphic"
                   operator="over" result="output"/>
    </filter>
  </defs>
</svg>

*

*Stroke Icons with gap

svg{position:absolute; left:-10em;}
.my-icon {
  content: url('https://img.icons8.com/officel/344/arrow.png');
  filter: url('#groupborder');
}
<svg width="0" height="0">
<defs>
    <filter id="groupborder" filterUnits="userSpaceOnUse"
            x="-1%" y="-1%" width="360" height="360">
      <feMorphology id="fm1" operator="dilate" in="SourceAlpha"
                    radius="8" result="e1" >
      </feMorphology>
    <feMorphology id="fm2" operator="dilate" in="SourceAlpha"
      radius="4" result="e2" >
   </feMorphology>
      <feComposite in="e1" in2="e2" operator="xor"
                   result="outline"/>
      <feColorMatrix type="matrix" in="outline"
                     values="0 0 0 0.2 0
                             0 0 0 0.2 0
                             0 0 0 0.2 0
                             0 0 0 1 0" result="outline2"/>
      <feComposite in="outline2" in2="SourceGraphic"
                   operator="over" result="output"/>
    </filter>
  </defs>
</svg>

Example animation
To draw attention to the icon, you can animate the stroke.
<feMorphology operator="dilate" in="SourceAlpha"
                    radius="2" result="e2" >
        <animate attributeName="radius" values="6;4;2;2;4;6" dur="1s" calcMode="discrete" repeatCount="indefinite" />
      </feMorphology>

svg{position:absolute; left:-10em;}
.my-icon {
  content: url('https://img.icons8.com/officel/344/arrow.png');
  filter: url('#groupborder');
}
<svg width="0" height="0">
<defs>
    <filter id="groupborder" filterUnits="userSpaceOnUse"
            x="-20%" y="-20%" width="420" height="420">
      <feMorphology operator="erode" in="SourceAlpha"
                    radius="2" result="e1" >
   <animate attributeName="radius" values="2;4;6;6;4;2" dur="1s" calcMode="discrete" repeatCount="indefinite" />
      </feMorphology>
      <feMorphology operator="dilate" in="SourceAlpha"
                    radius="2" result="e2" >
  <animate attributeName="radius" values="6;4;2;2;4;6" dur="1s" calcMode="discrete" repeatCount="indefinite" />
      </feMorphology>
      <feComposite in="e1" in2="e2" operator="xor"
                   result="outline"/>
      <feColorMatrix type="matrix" in="outline"
                     values="0 0 0 0 0
                             0 0 0 0.2 0
                             0 0 0 0.2 0
                             0 0 0 1 0" result="outline2"/>
      <feComposite in="outline2" in2="SourceGraphic"
                   operator="over" result="output"/>
    </filter>
  </defs>
</svg>


text:
Q: Rails slow responce I have a rails app. But in my logs I have some strange output, especially string
Completed 200 OK in 113ms (Views: 45.0ms | ActiveRecord: 2.9ms | Sphinx: 0.0ms)

45ms(views) + 3ms(AR) = 48ms but not 113
My app should be 2x faster. What is the problem?
Here is full log for a single request

A: Nowhere it is said that your 113ms should be the sum of whatever is inside the parenthesis. The time took by rails to handle the request is not there, nor is the time took by the logic in your action.


text:
Q: "Unexpected address space" compilation error while using shared memory in PTX I have written a trivial kernel in which I declare my shared memory array as
extern __shared__ float As[100];

In my kernel launch I specify the number_of_bytes of shared memory. I get the error "Unexpected address space" while compiling the kernel(to PTX). I am using fairly new version of LLVM from svn(3.3 in progress). Any ideas what I am doing wrong here ? the problem seems to be with extern keyword, but then how else am I gonna specify it?(Shared memory).
Should I use a different LLVM build?
Config CUDA 5.0 , Nvidia Tesla C1060

A: Well, it runs out that extern keyword is not really required in this case as per Gert-Jan from Nvidia forum. I am not sure what his id is on SO.
His reply --
"If you know how many elements your shared memory array has (e.g. 100 elements), you should not use the extern keyword, and you don't have to specify the number of bytes of shared memory in the kernel launch (the compiler can figure it out by himself). Only if you don't know how many elements you will need, you have to specify this in the kernel launch, and in your kernel you have to write "extern shared float *As"."
Hope this help other users.

A: I am not sure if CUDA-C/C++ supports this but perhaps try to set the address space attribute as a work-around:
__attribute__((address_space(3)))
extern __shared__ float As[100];

That should force llvm to put it in shared address space....
Good luck!


text:
Q: Enemy respawning in Kingdoms of Amalur: Reckoning How does respawning work in KoA? It appears to be almost immediate in the "overworld", but what about in dungeons? Do bosses ever respawn?

A: Bosses don't respawn. From what I can tell it appears that it takes about 1 to 2 amalur days for a full respawn.  Some dungeons have special monsters and don't respond for some reason.  Overworld seems to be about 1 day and dungeons seem to take a bit longer.  You can literally fast travel from one location to a far away location and back and see all of the enemies back in most areas.  Remember, as you progress through the game you will find some enemies don't respawn.  That is probably because they are quest monsters.  Power leveling is best reserved for a reckoning event with a exp potion added.  When doing reckoning mode try to kill as many enemies as you can and then perform a fateshift on an orange enemy with a exp potion already stacked as the exp bonus from the button mashing will apply to all kills while in reckoning mode and then the exp bonus potion will stack as well.  When you're fast traveling somewhat regularly, the respawn rates can become quite a nuisance.

A: I believe the respawn rate differs from dungeon to dungeon. I don't think the bosses respawn, though.


text:
Q: Setting torch.nn.linear() diagonal elements zero I am trying to build a model with a layer of torch.nn.linear with same input size and output size, so the layer would be square matrix. In this model, I want the diagonal elements of this matrix fixed to zero. Which means, during training, I don't want the diagonal elements to be changed from zero. I could only think of adding some kind of step that change diag elements to zero for each training epoch, but I am not sure if this is valid or efficient way. Is there a definite way of making this kind of layer which can ensure that the diagonal elements don't change?
Sorry if my question is weird.

A: You can always implement your own layers. Note that all custom layers should be implemented as classes derived from nn.Module. For example:
class LinearWithZeroDiagonal(nn.Module):
  def __init__(self, num_features, bias):
    super(LinearWithZeroDiagonal, self).__init__()
    self.base_linear_layer = nn.Linear(num_features, num_features, bias)

  def forward(self, x):
    # first, make sure the diagonal is zero
    with torch.no_grad():
      self.base_linear_layer.weight.fill_diagonal_(0.)
    return self.base_linear_layer(x)


text: Q: How to present the abstract method in the child classes in a class Diagram I am doing a class diagram and I have one abstract class and two child classes which inherit from the parent one. The abstract class has also 2 abstract methods.My question is,should I add the abstract methods in the child classes in my class diagram ? Since its a abstract method I know that they have to be implemented in the inherited classes. This is my diagram :


text:
Q: Android build failed: Unable to find facebook-core:5.11.1 In the recent update of the facebook SDK, i got this issue while syncing the gradle file in android project (react native).
error Failed to install the app. Make sure you have the Android development environment set up: https://facebook.github.io/react-native/docs/getting-started.html#android-development-environment. Run CLI with --verbose flag for more details. Error: Command failed: ./gradlew app:installDebug -PreactNativeDevServerPort=8081

FAILURE: Build failed with an exception.

facebook-core:5.11.1 failed to resolve.

A: To make it work, you have to add following line to android/gradle.properties:

facebookSdkVersion=5.11.0

to use the old SDK Version.
Solution by andrewzey

A: Changing the versions to "5.0,5.11.0" fixed the issue for me.

A: Goto -> Gradle Scripts -> Build.gradle (Module:app) -> change your facebook dependency version from [5,6) to 5.11.0 and sync check this

A: Changing following line
implementation 'com.facebook.android:facebook-login:[5,6)' to implementation 'com.facebook.android:facebook-login:5.11.0' build.gradle (Module: app) file
and sync
worked for me

A: In my Case by changing the dependency to hardcoded worked.
I have use facebook sdk for login so,
implementation "com.facebook.android:facebook-login:5.11.0"

A: EMP fixbug: node_modules/react-native-fbsdk/android/build.gradle
change from:
def DEFAULT_FACEBOOK_SDK_VERSION = "[5.0,6.0["

to:
def DEFAULT_FACEBOOK_SDK_VERSION = "[5.0,5.11.0["


text:
Q: What is the difference between PubSub.Subscriptions() and Topic.getSubscriptions() in Google PubSub? I've created a program that handles PubSub messaging using the Google PubSub NodeJS SDK.
While developing this I noticed that the NodeJS Library and docs show two ways of retrieving active subscriptions in Google PubSub:

*

*PubSub.subscriptions('SubscriptionName') docs

*PubSub.topic('TopicName).getSubscriptions() docs
I understand that the 2nd option might only list subscriptions related to a topic, but I'm more interested in the workings behind the scene.
In my first attempt I used the 2nd option to retrieve my subscriptions and that worked while running the application, but I ran into timeouts when trying to mock the call in my unit tests and I couldn't fix it. I switched to the 1st approach which doesn't use a Promise and just returns a plain Subscription object, this did work in my unit tests just fine
Are there downsides to not using the promise based call as it might not yield the most up to date results? If not, is there a reason why there are two options and one is promise based and the other is not?

A: These two APIs do very different things. The first one creates a Subscription object in the client that can be used for receiving messages. It does not retrieve any state from the Cloud Pub/Sub service. Therefore, there is no asynchronous work to do and it need not return a promise. The second one actually goes to the Cloud Pub/Sub service, retrieves the list of subscriptions for the topic, and creates a Subscription object for each one.
If you know the name of the subscription for which you want to receive messages and can be reasonably confident that it exists, then use PubSub.subscriptions('SubscriptionName'). If you try to start receiving messages on this subscription by calling subscription.on('message', messageHandler); and it doesn't exist, then an error is emitted.
If you don't know the name of the subscription and instead need to fetch the list and choose the subscription from which to receive messages from the list of all subscriptions for the topic, then use the PubSub.topic('TopicName).getSubscriptions() call.
For further help with why mocking the getSubscriptions() call didn't work, would probably need to see the code you were using to mock it.


text:
Q: Retail system with local database objectbox and data sync to cloud I wanna develop a Retail system with offline and online options and want to know if the following features can be achieved by objectbox.

*

*Can I sync the changes on table schemas from cloud to mobile clients. For example, Suppose I have added new columns on the customer table in the cloud then is there a way to sync those new columns to mobile clients.

*What is the data size limit on the objectbox as a local database in mobile client.

*Does data sync works when the mobile app is running or does it works in the background on the mobile client so the data from the cloud syncs automatically even app is not running?

*Will it be time consuming to write my own connector at the cloud to sync data between mysql.

It would really helpful to decide on objectbox. A big thank you in advance.


text:
Q: Pydantic input model for partial updates I am using Pydantic to validate data inputs in a server. Pydantic models:

*

*User: for common fields

*UserIn: user input data to create new account

*UserInDB: to hash password and include extra fields like created_at

*UserOut: to output created/updated user data

Now how can I utilize the model UserIn for user account partial updates? so that None fields are excluded. Or do I have to rewrite it again and make every field optional?
class User(BaseModel):

    name_first :          str = Field(...)
    name_last :           Optional[str] = None
    mobile :              int = Field(..., description="It has to be 8 digits and starts with either 9 or 7", example="99009900")

    email :               Optional[EmailStr] = None

    gender:               Literal['m', 'f'] = Field(..., example="m")
    birth_date:           datetime.date
    preferred_language :  Literal['ar', 'en'] = Field(..., example="ar")
    newsletter :          bool = Field(...)

    @validator('mobile')
    def number_has_to_start_with_9_or_7(cls, v):
        if str(v)[:1] !="9" and str(v)[:1] !="7":
            raise ValueError('Mobile number must start with 9 or 7')
        if len(str(v)) !=8:
            raise ValueError('Mobile number must be 8 digits')
        return v

class UserIn(User):
    password: str = Field(...)

class UserInDB(UserIn):
    mobile_otp:           int = Field(...)
    bitrole:              int = Field(...)
    created_at:           datetime.datetime
    updated_at:           datetime.datetime

class UserOut(User):
    id:                   int
    mobile_otp:           int
    bitrole:              int
    mobile_confirmed :    bool
    email_confirmed :     bool
    disabled :            bool
    created_at:           datetime.datetime
    updated_at:           datetime.datetime

    class Config:
        orm_mode = True

A: Unfortunately this is a problem that has been already faced by quite a lot of people (me included).
There is no simple way of handling it out of the box and as far as I know.
Here are some solutions proposed to bypass the problem, although not completely, on github
https://github.com/samuelcolvin/pydantic/issues/990#issuecomment-645961530
MY SOLUTION
I use pydantic with fastapi and partial updates of resources are quite common. Due to the limitation of pydantic I ask the user to resubmit all the values, filling correctly the pydantic model and then update all the fields that can be updated.
It's not ideal, I know, but it seems to work
UPDATE
I've found another possible solution. Basically, retrieve the old data, update it, and write the updated data (much better than my solution).
See fastapi docs https://fastapi.tiangolo.com/tutorial/body-updates/#partial-updates-with-patch


text:
Q: How to convert serde_json::Value into concrete type implementing Deserialize trait? I am writing a websocket server which deserializes incoming frames into a serde_json::Value and then passes this value to (potentially many) callbacks. I would like the callbacks to convert the serde_json::Value to a new type (e.g. MyType in the example below) without an encode/decode pass. It seems to me that the serde machinery should have enough information to do this (with the possibility of an error if the contained fields and types do not match). In the example below, the function to_my_type() stands in for this callback function. Is is the encode/decode that I want to bypass from this function.
I could of course pass the raw encoded data to each callback, but then each callback will have to do the decoding separately. I want to keep the function signature of the callbacks taking an argument of type serde_json::Value so that different callbacks can get different types but that I can register them all with a common function signature.
#![feature(proc_macro)]

#[macro_use]
extern crate serde_derive;
extern crate serde_json;

#[derive(Serialize, Deserialize)]
struct MyType {
    a: bool,
}

fn as_json(a: &MyType) -> serde_json::Value {
    let buf = serde_json::to_vec(a).unwrap();
    serde_json::from_slice::<serde_json::Value>(&buf).unwrap()
}

fn to_my_type(value: serde_json::Value) -> MyType {
    // How to convert a serde_json::Value into MyType without encode/decode pass?
    let buf = serde_json::to_vec(&value).unwrap();
    serde_json::from_slice::<MyType>(&buf).unwrap()
}

fn main() {
    let store = MyType{a: true};
    let raw_json = as_json(&store);
    let _store2 = to_my_type(raw_json);
}

A: You can use the serde_json::from_value function to convert a Value to any type that implements Deserialize:
fn to_my_type(value: serde_json::Value) -> MyType {
    serde_json::from_value(value).unwrap()
}


text:
Q: Сервер Django не работает
Подскажите пожалуйста в чем ошибка? не могу сервер запустить.
python manage.py runserver (doesn't work)

A: Вы не установили через pip coursheders. Или удалите его из SETTINGS или установите через pip


text:
Q: getting error while adding controller in the mvc Iam getting error while adding controller as
        "Unable to retrieve meta data for MvcCustomer.ViewModels.ViewOrderData.Unable to load  the specialfied metadata resource".
Here is my viewmodel
          namespace MvcCustomer.ViewModels
          {
           public class ViewOrderData
           {
            public IEnumerable<CustomerInfo> customerinfo { get; set; }
            public IEnumerable<CustomerOrderData> customerorderdata { get; set; }
           }
         }

Trying to add the controller with MvcCustomer Class and DBContext but it is unabl to creating the controller.


text:
Q: Error while creating numpy array len = 5
results = np.empty(len)
for i in range(len):
    results[i] = ([999, 'sss'])

I would like to predefine the length of a list, which is 5 and then fill in some values which contains both numerical and string variables... However, whatever I use
for i in range(len):
    results[i] = ([[999], ['sss']])

or
for i in range(len):
    results[i] = [[999], ['sss']]

I got error message as
ValueError                                Traceback (most recent call last)
<ipython-input-114-4cfd5264742d> in <module>()
      2 results = np.empty(len)
      3 for i in range(len):
----> 4     results[i] = ([999, 'sss'])

ValueError: setting an array element with a sequence.

How should i do?

A: you could use the dtype 'object' for your results array:
length = 5
results = np.empty(length, dtype='object')
for i in range(length):
    results[i] = ([999, 'sss'])

>>> results
array([list([999, 'sss']), list([999, 'sss']), list([999, 'sss']),
       list([999, 'sss']), list([999, 'sss'])], dtype=object)

If what you're putting into your results array is always of length 2, better to specify the appropriate shape when you make your np.empty:
length = 5
results = np.empty((length,2), dtype='object')
for i in range(length):
    results[i] = ([999, 'sss'])

>>> results
array([[999, 'sss'],
       [999, 'sss'],
       [999, 'sss'],
       [999, 'sss'],
       [999, 'sss']], dtype=object)

Note, try not to use len as a variable, as it is already a built-in function in python (I replaced it with length in my examples above)

A: Unless you really have a need for a numpy array with mixed dtype, I'd recommend making a list of lists:
In [96]: alist = []
In [97]: for i in range(5):
    ...:     alist.append([999, 'sss'])
    ...:
In [98]: alist
Out[98]: [[999, 'sss'], [999, 'sss'], [999, 'sss'], [999, 'sss'], [999, 'sss']]

Or if you make a list of tuples, you can go on an make a structured array - 1d with 2 fields of the desired dtype:
In [99]: alist = []
In [100]: for i in range(5):
     ...:     alist.append((999, 'sss'))
     ...:
     ...:
In [101]: alist
Out[101]: [(999, 'sss'), (999, 'sss'), (999, 'sss'), (999, 'sss'), (999, 'sss')]
In [102]: np.array(alist, dtype='int,U3')
Out[102]:
array([(999, 'sss'), (999, 'sss'), (999, 'sss'), (999, 'sss'),
       (999, 'sss')], dtype=[('f0', '<i8'), ('f1', '<U3')])

When trying to mix integers and strings you need to pay attention to the intended use.

Note what happens when you create an 'empty' array:
In [103]: arr = np.empty(4)
In [104]: arr
Out[104]: array([0.e+000, 0.e+000, 0.e+000, 5.e-324])
In [105]: arr.dtype
Out[105]: dtype('float64')

It creates an array of the desired size, but with a default dtype, float.  The initial values are garbage - though displayed as floats.
That means that the only thing you can put in arr[0] is a float.
In [106]: arr[0]=999       # converted to float
In [107]: arr[1]='sss'
...
ValueError: could not convert string to float: 'sss'
In [108]: arr
Out[108]: array([9.99e+002, 0.00e+000, 0.00e+000, 4.94e-324])

And it won't accept a list or tuple either, a sequence.  It has to be something that can be converted to a float.
Specifying an object dtype does let you put anything in elements, because the elements actually hold pointers - just like a list.
In [110]: arr = np.empty(4,dtype=object)
In [111]: arr
Out[111]: array([None, None, None, None], dtype=object)
In [112]: arr[0]=1
In [113]: arr[1]=.999
In [114]: arr[2]='sss'
In [115]: arr[3]=[999,'sss']
In [116]: arr
Out[116]: array([1, 0.999, 'sss', list([999, 'sss'])], dtype=object)

Such an array is either a glorified list, or a debased one, depending on your needs.


text:
Q: Could not see Windows Experience Subscores I could see my Windows Experience Score.  But when I click the Rating.  Windows 7 doesn't display the subscores.
Any idea what's wrong ?
Thanks
Michael

A: The following conditions might prevent Windows from updating the Windows Experience Index:
•Running on battery power. Windows automatically tries to conserve power when running on a battery alone. So if your computer is running on battery power, a performance assessment won't reflect its true capabilities. Plug your computer in, and then re-run the assessment.
•Not enough free disk space. The Windows Experience Index assessment tool creates a test file on your hard disk. If there's not enough free disk space to create the test file, the assessment can't be completed. You can use the Disk Cleanup tool to free up disk space. For more information, see Delete files using Disk Cleanup.
•The assessment is already running. If the Windows Experience Index assessment tool is already running, your scores can't be updated.
•The display driver is older. If your computer is using an older version of the display driver, your scores might not be updated. For more information, see Update drivers: recommended links
•No multimedia support. If your computer doesn't have multimedia support, your scores can't be updated.
Source


text:
Q: Once image is clicked it will "pop out" compared to other images? I have three images, and each image has a value with it, so the first img=1, second img=2, third img=3.
What I can't figure out is how to select one, make the others look transparent and use the value of the image selected?
Is there a way to do it through html5, css3?
Below is an example similar to what I want it to look like when I click (in the example it is based on hover):
http://jsbin.com/umacat/4/edit
Thanks in advance!

A: This is my strategy:

*

*Store the toggle state, say, clickToggle, as a data object in each element.

*Update the clickToggle value when you click on — this value is also checked and allowed to determine the mode of action

*Perform the necessary actions after evaluating the value of clickToggle. Instead of using :hover, we will toggle a class to be added/removed.

Here is the updated CSS:
.box.toggled {
   box-shadow: 0 2px 8px #334;
   background:#ccd;
   -webkit-transform: scale(1.1);
   transform: scale(1.1);
   opacity:1;
}

Here is the code I have, and demonstrated to be working, too:
$(function(){
  $('.box').on('click', function(e) {
    // Prevent default function
    e.preventDefault();

    // Check state
    if(!$(this).data('clickToggle') || $(this).data('clickToggle') === 0) {

      // Update state, add class
      $(this)
      .data('clickToggle', 1)
      .addClass('toggled');

      // Force siblings to revert to original state
      $(this)
      .siblings()
        .data('clickToggle', 0)
        .removeClass('toggled');

    } else if($(this).data('clickToggle') === 1) {

      // Update state, remove class
      $(this)
      .data('clickToggle', 0)
      .removeClass('toggled');
    }
  });
});


text:
Q: How to sync/update a database connection from MS Access to SQL Server Problem:
I need to get data sets from CSV files into SQL Server Express (SSMS v17.6) as efficiently as possible. The data sets update daily into the same CSV files on my local hard drive. Currently using MS Access 2010 (v14.0) as a middleman to aggregate the CSV files into linked tables.
Using the solutions below, the data transfers perfectly into SQL Server and does exactly what I want. But I cannot figure out how to refresh/update/sync the data at the end of each day with the newly added CSV data without having to re-import the entire data set each time.
Solutions:
Upsizing Wizard in MS Access - This works best in transferring all the tables perfectly to SQL Server databases. I cannot figure out how to update the tables though without deleting and repeating the same steps each day. None of the solutions or links that I have tried have panned out.
SQL Server Import/Export Wizard - This works fine also in getting the data over to SSMS one time. But I also cannot figure out how to update/sync this data with the new tables. Another issue is that choosing Microsoft Access as the data source through this method requires a .mdb file. The latest MS Access file formats are .accdb files so I have to save the database in an older .mdb version in order to export it to SQL Server.
Constraints:
I have no loyalty towards MS Access. I really am just looking for the most efficient way to get these CSV files consistently into a format where I can perform SQL queries on them. From all I have read, MS Access seems like the best way to do that.
I also have limited coding knowledge so more advanced VBA/C++ solutions will probably go over my head.
TLDR:
Trying to get several different daily updating local CSV files into a program where I can run SQL queries on them without having to do a full delete and re-import each day. Currently using MS Access 2010 to SQL Server Express (SSMS v17.6) which fulfills my needs, but does not update daily with the new data without re-importing everything.
Thank you!

A: You can use a staging table strategy to solve this problem.
When it's time to perform the daily update, import all of the data into one or more staging tables. Execute SQL statement to insert rows that exist in the imported data but not in the base data into the base data; similarly, delete rows from the base data that don't exist in the imported data; similarly, update base data rows that have changed values in the imported data.
Use your data dependencies to determine in which order tables should be modified.
I would run all deletes first, then inserts, and finally all updates.
This should be a fun challenge!
EDIT
You said:

I need to get data sets from CSV files into SQL Server Express (SSMS
  v17.6) as efficiently as possible.

The most efficient way to put data into SQL Server tables is using SQL Bulk Copy.  This can be implemented from the command line, an SSIS job, or through ADO.Net via any .Net language.
You state:

But I cannot figure out how to refresh/update/sync the data at the end
  of each day with the newly added CSV data without having to re-import
  the entire data set each time.

It seems you have two choices:

*

*Toss the old data and replace it with the new data

*Modify the old data so that it comes into alignment with the new data

In order to do number 1 above, you'd simply replace all the existing data with the new data, which you've already said you don't want to do, or at least you don't think you can do this efficiently.  In order to do number 2 above, you have to compare the old data with the new data. In order to compare two sets of data, both sets of data have to be accessible wherever the comparison is to take place. So, you could perform the comparison in SQL Server, but the new data will need to be loaded into the database for comparison purposes.  You can then purge the staging table after the process completes.

A: In thinking further about your issue, it seems the underlying issue is:

I really am just looking for the most efficient way to get these CSV
  files consistently into a format where I can perform SQL queries on
  them.

There exist applications built specifically to allow you to query this type of data.
You may want to have a look at Log Parser Lizard or Splunk.  These are great tools for querying and digging into data hidden inside flat data files.

A: An Append Query is able to incrementally add additional new records to an existing table.  However the question is whether your starting point data set (CSV) is just new records or whether that data set includes records already in the table.
This is a classic dilemma that needs to be managed in the Append Query set up.
If the CSV includes prior records - then you have to establish the 'new records' data sub set inside the CSV and append just those.  For instance if you have a sequencing field then you can use a > logic from the existing table max.  If that is not there then one would need to do a NOT compare of the table data with the csv data to identify which csv records are not already in the table.
You state you seek something 'more efficient' - but in truth there is nothing more efficient than a wholesale delete of all records and write of all records.  Most of the time one can't do that - but if you can I would just stick with it.


text:
Q: Random notification  I am pretty new with android app development. I have a requirment in which I have to generate random reminder notification during the time set.
I dont know where to start from, what i need to look into for fullfiling the requriment - android services i guess but before going that route , i want to check with experts.

A: If you need something done in the background on a regular basis, then yes, it has to be a service. Also there is another way of doing it (pointed out by Pixie) which would be using Alarm Manager to launch your task at a scheduled time.


text:
Q: Remote Filtering Based on JSON Attributes in Geomesa HBase I'm trying to run a query that filters based on json attributes against a Geomesa HBase cluster with remote filtering enabled (hbase.remote.filtering = true). However, the query is failing due to an IllegalArgumentException with error message Property '$.featurePayload.properties.user' does not exist in feature type. Is there a way to enable remote filtering based on json attributes with Geomsa and HBase?
Note: I was able to run this query successfully when hbase.remote.filtering was set to false and the filtering was done on the client side where the application connects to a GeoTools DataStore to get the features by query. My main confusion is what is different on the remote filtering that is throwing the exception and if there is anyway to get json attribute filtering remotely working.
This is an example query I am trying to run:
\"$.featurePayload.properties.user\" = 'someUser'

This is the table schema:
INFO  Describing attributes of feature 'OSMNodes'
geometry           | Point     (Spatio-temporally indexed)
ingestionTimestamp | Timestamp (Spatio-temporally indexed)
nextTimestamp      | Timestamp
serializerVersion  | String
featurePayload     | String

Example feature in the table:
id,*geometry:Point:srid=4326,ingestionTimestamp:Timestamp,nextTimestamp:Timestamp,serializerVersion:String,featurePayload:String
1789928211#3165330648,POINT (-0.1844331 27.2077326),2019-12-23T03:00:00.000Z,9999-12-30T23:59:59.000Z,geojson,"{""geometry"":{""type"":""Point"",""coordinates"":[-0.1844331,27.2077326]},""id"":""3165330648"",""properties"":{""tags"":{},""changesetId"":123456,""version"":1,""uid"":1111111,""user"":""someUser"",""featureSource"":""OSM"",""sourceTimestamp"":""2014-11-03 19:40:40"",""ingestionTimestamp"":""2019-12-23 03:00:00""}}"

Stack trace:
1. Caused by: java.lang.IllegalArgumentException: Property '$.featurePayload.properties.user' does not exist in feature type
2.  at org.locationtech.geomesa.filter.factory.FastFilterFactory$$anonfun$1.apply(FastFilterFactory.scala:263)
3.  at org.locationtech.geomesa.filter.factory.FastFilterFactory$$anonfun$1.apply(FastFilterFactory.scala:263)
4.  at scala.Option.getOrElse(Option.scala:121)
5.  at org.locationtech.geomesa.filter.factory.FastFilterFactory.property(FastFilterFactory.scala:262)
6.  at org.locationtech.geomesa.filter.visitor.QueryPlanFilterVisitor.visit(QueryPlanFilterVisitor.scala:139)
7.  at org.geotools.filter.AttributeExpressionImpl.accept(AttributeExpressionImpl.java:347)
8.  at org.geotools.filter.visitor.DuplicatingFilterVisitor.visit(DuplicatingFilterVisitor.java:118)
9.  at org.locationtech.geomesa.filter.visitor.QueryPlanFilterVisitor.visit(QueryPlanFilterVisitor.scala:318)
10.     at org.locationtech.geomesa.filter.visitor.QueryPlanFilterVisitor.org$locationtech$geomesa$filter$visitor$QueryPlanFilterVisitor$$bind(QueryPlanFilterVisitor.scala:351)
11.     at org.locationtech.geomesa.filter.visitor.QueryPlanFilterVisitor.visit(QueryPlanFilterVisitor.scala:150)
12.     at org.geotools.filter.IsEqualsToImpl.accept(IsEqualsToImpl.java:149)
13.     at org.locationtech.geomesa.filter.visitor.QueryPlanFilterVisitor.visit(QueryPlanFilterVisitor.scala:81)
14.     at org.geotools.filter.AndImpl.accept(AndImpl.java:45)
15.     at org.locationtech.geomesa.filter.factory.FastFilterFactory$.optimize(FastFilterFactory.scala:412)
16.     at org.locationtech.geomesa.filter.factory.FastFilterFactory$.toFilter(FastFilterFactory.scala:401)
17.     at org.locationtech.geomesa.index.iterators.IteratorCache$$anonfun$filter$2.apply(IteratorCache.scala:82)
18.     at org.locationtech.geomesa.index.iterators.IteratorCache$$anonfun$filter$2.apply(IteratorCache.scala:82)
19.     at org.locationtech.geomesa.utils.cache.ThreadLocalCache.getOrElseUpdate(ThreadLocalCache.scala:68)
20.     at org.locationtech.geomesa.index.iterators.IteratorCache$.filter(IteratorCache.scala:82)
21.     at org.locationtech.geomesa.hbase.filters.CqlTransformFilter$.deserialize(CqlTransformFilter.scala:286)
22.     ... 19 more


text:
Q: Download.file with method curl downloads 0 bytes When I use the download.file function with method curl I get a downloaded file with 0 bytes.
for example:
download.file('https://github.com/rstudio/rmarkdown/archive/refs/heads/main.zip', destfile='library', method='curl')

Produces the following output:
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
character(0)

How can I get this fixed?
Note:
method='wget' works but that is because my Mac has wget, however my windows laptop only has curl as an option, and this does not work. I specifically want to fix the curl method.


text:
Q: Error resolving template "pages", template might not exist or might not be accessible by any of the configured Template Resolvers I did a project using Spring with Thymeleaf and Tiles with the following structure :

I have configured my Spring-Servlet :
<bean id="templateResolver"
                class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
                <property name="prefix" value="/WEB-INF/templates/" />
                <property name="suffix" value=".html" />
                <property name="characterEncoding" value="UTF-8" />
                <property name="templateMode" value="HTML5" />
        </bean>

        <bean id="tilesConfigurer"
                class="org.thymeleaf.extras.tiles2.spring4.web.configurer.ThymeleafTilesConfigurer">
                <property name="definitions">
                        <list>
                                <value>/WEB-INF/tiles-defs.xml</value>
                        </list>
                </property>
        </bean>
        <bean id="tilesViewResolver" class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
                <property name="viewClass"
                        value="org.thymeleaf.extras.tiles2.spring4.web.view.ThymeleafTilesView" />
                <property name="templateEngine" ref="templateEngine" />
                <property name="characterEncoding" value="UTF-8" />
        </bean>
        <bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
                <property name="templateResolver" ref="templateResolver" />
                <property name="additionalDialects">
                        <set>
                                <bean class="org.thymeleaf.extras.tiles2.dialect.TilesDialect" />
                        </set>
                </property>
        </bean>

my Tiles Definition is :
<tiles-definitions>
    <definition name="layout" template="layout">
        <put-attribute name="header"   value="header" />
        <put-attribute name="menu"   value="menu" />
        <put-attribute name="footer" value="footer" />
        <put-attribute name="body" />

    </definition>

    <definition name="usersView" extends="layout">
        <put-attribute name="body"   value="pages :: users" />
    </definition>
 </tiles-definitions>

will this give me the following error :
Error resolving template "pages", template might not exist or might not be accessible by any of the configured Template Resolvers

but when i move the users.html page to the templates folder and make my tiles def as
<definition name="usersView" extends="layout">
        <put-attribute name="body"   value="users" />
    </definition>

its working fine .
So the Question is can Thymeleaf accept My Folder Structure? if Yes ,How?

A: Yes it can be by using the viewNames property
just change your Spring-Servlet.xml to
<bean id="templateResolver"
                class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
                <property name="prefix" value="/WEB-INF/" />
                <property name="suffix" value=".html" />
                <property name="characterEncoding" value="UTF-8" />
                <property name="templateMode" value="HTML5" />

        </bean>

        <bean id="tilesConfigurer"
                class="org.thymeleaf.extras.tiles2.spring4.web.configurer.ThymeleafTilesConfigurer">
                <property name="definitions">
                        <list>
                                <value>/WEB-INF/tiles-defs.xml</value>
                        </list>
                </property>
        </bean>
        <bean id="tilesViewResolver" class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
                <property name="viewClass"
                        value="org.thymeleaf.extras.tiles2.spring4.web.view.ThymeleafTilesView" />
                <property name="templateEngine" ref="templateEngine" />
                <property name="characterEncoding" value="UTF-8" />
                <property name="order" value="1" />
                <property name="viewNames" value="templates/*,pages/*" />
        </bean>
        <bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
                <property name="templateResolver" ref="templateResolver" />
                <property name="additionalDialects">
                        <set>
                                <bean class="org.thymeleaf.extras.tiles2.dialect.TilesDialect" />
                        </set>
                </property>
        </bean>

and your tiles definition to
<tiles-definitions>
    <definition name="layout" template="templates/layout">
        <put-attribute name="header"   value="templates/header" />
        <put-attribute name="menu"   value="templates/menu" />
        <put-attribute name="footer" value="templates/footer" />
        <put-attribute name="body" />
    </definition>

    <definition name="pages/usersView" extends="layout">
        <put-attribute name="body"   value="pages/users" />
    </definition>
 </tiles-definitions>

Explanation :
we have defined the root folder in the prefix at the Resolver
<property name="prefix" value="/WEB-INF/" />

and extended it by
 <property name="viewNames" value="templates/*,pages/*" />

to the needed folders and any new view folder you create should goes in this property also redirect or forward too

A: And also make sure that the query written in Repo layer might be not correct. If so please check your query (using CriteriaBuilder, CriteriaQuery, Predicate) once is it satisfying the condition.
Here in my case I tried to getting a value from data base where the condition is not satisfied.


text:
Q: Selection sort using max I am trying to implement a custom version of selection sort, by selecting the maximum of the unsorted part and placing it at the end of the output (sorted) list.
I have a problem with the list recursive build. How can I start building the output list from the right?
sel_sort2([], []).
sel_sort2(L, R) :-
    max_list(L, M),
    delete1(M, L, L1),
    append(R, [M], R),
    sel_sort2(L1, R).

A: You don't need to use append (which as pointed in the first comment is fishy). Instead you can write the second clause like:
sel_sort2(L, [E|T]) :-
    min(L, E),
    del(L, E, L1),
    sel_sort2(L1, T).

Where min takes the minimum element from the input list, and this element is on the first position in the result list, L1 is all elements from L without the first occurrence of a given element.


text:
Q: Where to set window property in XAML I found some code for an attached property that will let me escape close a window called as a dialog here on SO.
But I can't figure out where to set the property.
This might be complicated by the fact that this is a RibbonWindow and not a normal Window but I don't think so.
The attached property will be ab:WindowService.EscapeClosesWindow="True". Where in the xaml should it go??
Cheers,
Berryl
ERROR
Unable to cast object of type
'Microsoft.Expression.Platform.WPF.InstanceBuilders.WindowInstance' to type
'Microsoft.Windows.Controls.Ribbon.RibbonWindow'.
at  AttachedBehaviors.WindowService.OnEscapeClosesWindowChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)

The gist of the attached property is
    private static void OnEscapeClosesWindowChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
        var target = (Window) d;
        if (target != null)
            target.PreviewKeyDown += Window_PreviewKeyDown;
    }

    /// <summary>Handle the PreviewKeyDown event on the window</summary>
    private static void Window_PreviewKeyDown(object sender, KeyEventArgs e) {
        var target = (Window) sender;

        // If this is the escape key, close the window
        if (e.Key == Key.Escape)
            target.Close();
    }

window xaml
<r:RibbonWindow x:Class="SCA.Presentation.Wpf.Views.TimeSheet.WeeklyTimeSheetView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local ="clr-namespace:SCA.Presentation.Wpf.Views.TimeSheet"
xmlns:ab="clr-namespace:SCA.Presentation.Wpf.AttachedBehaviors;assembly=Smack.Core.Presentation.Wpf"
xmlns:r="clr-namespace:Microsoft.Windows.Controls.Ribbon;assembly=RibbonControlsLibrary"
   Background="{DynamicResource WaveWindowBackground}"
   FontFamily="Arial" FontSize="12"
   Width="900" Height="600"
   ResizeMode="CanResizeWithGrip"
   WindowStartupLocation="CenterScreen"
             ab:WindowService.EscapeClosesWindow="True" <=== ERROR

    >

<r:RibbonWindow.Resources>
    <ResourceDictionary Source="TimesheetResources.xaml" />
</r:RibbonWindow.Resources>

A: I created a sample application to recreate that error you mentioned. And I failed to reproduce that error. It easily compiled in my app.
Can you check with a sample application and try to find any differences?
Recreation:
public static class WindowService
{
    public static readonly DependencyProperty EscapeClosesWindowProperty = DependencyProperty.RegisterAttached(
       "EscapeClosesWindow",
       typeof(bool),
       typeof(WindowService),
       new FrameworkPropertyMetadata(false, new PropertyChangedCallback(OnEscapeClosesWindowChanged)));

    public static bool GetEscapeClosesWindow(DependencyObject d)
    {
        return (bool)d.GetValue(EscapeClosesWindowProperty);
    }

    public static void SetEscapeClosesWindow(DependencyObject d, bool value)
    {
        d.SetValue(EscapeClosesWindowProperty, value);
    }

    private static void OnEscapeClosesWindowChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        Window target = (Window)d;
        if (target != null)
        {
            target.PreviewKeyDown += new System.Windows.Input.KeyEventHandler(Window_PreviewKeyDown);
        }
    }

    private static void Window_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        Window target = (Window)sender;

        if (e.Key == Key.Escape)
            target.Close();
    }
}

XAML:
<ribbon:RibbonWindow x:Class="WpfApplication1.RibbonWindow1"
                     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                     xmlns:ribbon="clr-namespace:Microsoft.Windows.Controls.Ribbon;assembly=RibbonControlsLibrary"
                     xmlns:local="clr-namespace:WpfApplication1"
                     local:WindowService.EscapeClosesWindow="True"
                     Title="RibbonWindow1"
                     x:Name="Window"
                     Width="640"
                     Height="480">
    <Grid x:Name="LayoutRoot">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <ribbon:Ribbon x:Name="Ribbon">
            <ribbon:RibbonTab x:Name="HomeTab"
                              Header="Home">
                <ribbon:RibbonGroup x:Name="Group1"
                                    Header="Group1"></ribbon:RibbonGroup>
            </ribbon:RibbonTab>
        </ribbon:Ribbon>
    </Grid>
</ribbon:RibbonWindow>


text:
Q: Sharing data between controllers in Ember I'm new to Ember and I'm pulling my hair out over this.
The app I'm working on has a set of "alerts" that will be dynamically updated. I have the alerts template/controller/module all working fine. The alerts controller has a method for displaying the number of alerts that have not been dismissed. This works fine within the alerts template.
However, when I access that same method from another controller, it always returns 0.
Here's a pastebin with the controllers, templates and model
Thanks for any help!
UPDATE:
I discovered that if I actually load the alerts view, and then go back to the home view, the alerts controller starts returning the correct value. So apparently there is an issue with the fixture data not being ready when the menu controller accesses that method. I haven't yet been able to figure out why.

A: Try something like this:
App.HomeRoute = Ember.Route.extend({
    renderTemplate: function(controller, model) {
        this._super(controller, model);
        this.render('menu', {
            into: 'home',
            outlet: 'alertsMenuItem',
            controller: 'alerts'
        });
    }
});

with Ember.Route.render you can specify the controller to use for a template.
Note that if you want to access your AlertsModel from routes other than alerts, you should set up your model in the AlertsController instead. Something like this works for me with Ember 1.10, but might be slightly different for earlier version:
App.AlertsController = Ember.ArrayController.extend({
    init: function() {
        var self = this;
        this.store.find('alert').then(function(model) {
            self.set('model', model);
        });
    },
    sortProperties: ['createdAt:desc'],
    sortedModel: Ember.computed.sort("model", "sortProperties"),
    remaining: function() {
            console.log(this.filterBy('isCompleted', false).get('length'));
            return this.filterBy('isCompleted', false).get('length');
    }.property('@each.isCompleted')
});


text:
Q: How can I know from which Google account (Email id) user purchased a product in my app? Suppose a user has 3 accounts and one of them is in the app purchase account.
Then when this user purchases a product from my app, how can I know from which account the in app purchase happened?
Can I get the email id?

A: No this is impossible. Google does not give this information. You can know from where is user, user device model, or something like this, but not who is user!


text:
Q: Should I use scrum for big projects? I've been working as a programmer on a project designed for generic software for gas stations (to be redistributed for many customers) for 18 months. The project is big. Today we have around 150 tables. We haven't used a specifc approuch, it was not well managed.
The person table has today around 70 columns, but 15 months ago it had around 30 columns. These new fields emerged in order to integrate with other modules such as sales, financial and accounting. Also many fields were created then deleted.
As a result, we had many refactoring and rework. The project never gets ready because there are always new requirements emerging.
Here's my doubt: if we had used a usual approach of specification, we would had interviews, a requirements document, activity, sequence and class diagrams, so we would know since the begin that the "person" table would need 70 fields, then we had avoided a lot of refactoring.
Could scrum help in this project? I have a feeling that in this case scrum would end up in a lot of refactoring as well.
I'm only a programmer, not a project manager. I'm wondering how it should have been done: with scrum or with big design up front.
Edit
Just to complement the end of this story.
Eight months later I asked this question, after put the project in production in some "test costumers" the project officialy failed. The product owner decided to abandon the project. It got hard to fix problems and a lot of perfomance problems occured.

A: If you can't manage requirements and don't have people capable of implementing requirements properly, SCRUM isn't going to help you (much), and that seems to be the real problem you're facing.
SCRUM can help you better deal with changing requirements than more static project management systems, but it's not the holy grail that will magically make everything work. In fact, unless your people are on board, willing and capable of working with SCRUM, and so is the rest of the organisation, it may end up making things worse.

If you've a table that's grown so much to fit in stuff to link with other systems, I postulate your database design is seriously flawed for example. No amount of SCRUM is going to improve your database design without you including people who are good at database design in your team and not being afraid of those design changes and the changes they will cause to the rest of your system.

A: Please note that when I wrote this answer, I didn't realise that the system was not in production yet.
They way you describe your product, I don't think that your immediate problem is that of managing requirements, nor your development process. It is that of your system architecture.
You have managed to create a monolith - and a rather large one at that. 150 tables is a lot for one system*. In particular, you mention that you have 40 new fields during the last 15 months just for integrating to external systems. I would seriously consider splitting your system into several autonomous services, probably starting with services for integrating to external systems - but later identifying separate business areas implemented in you monolith, and then perhaps split those concerns into separate services.
If you manage to split this monolith into separate maintainable code bases, you can also split your developers into smaller teams with well-defined responsibilities in specific areas of your business, and you can have a lot of smaller agile teams maintaining their own code base, instead of all hacking in the same code base.
As to why you have arrived at such an architecture, the root cause for your problem, there can be many answers. Maybe it's rooted in you development process, maybe all your developers are only experienced with transactional consistent software, or maybe it's a consequence of how your organization is structured (you are the victim of Conway's Law). I think there's a good chance it is a combination of the latter two.
I don't think that implementing scrum, or being better at managing requirements will help solve your immediate problem, nor the root cause. Adjusting the architecture for the complexity of you system will, and addressing the root cause for why you have build such a system will.
* Some will probably argue that they can maintain a system with 150 tables - or they have maintained much larger systems, but I do believe that most developers will consider this a large number of tables for one system.

A: It looks like you have churned your way in an uncontrolled development process to create a never-ending development system. This occurs in agile systems too.
The root problem is a lack of requirements, and while your solution might seem to be to use an agile methodology to fix this (as agile is designed around changing requirements) it would not solve the problem.
Even agile methods require a fairly firm starting point. They respond well to changing requirements, but they are just as useless as any other methodology if you start with no requirements. You still have to have a plan that you're heading towards before you start. Agile helps when that goal drifts, it does not help you define that goal.
Now its true that a fixed up-front design is too rigid if you do not know exactly what you are building.
So, I think you're going to have to move from your current 'chaos' methodology to something more organised and will have to implement a fair amount of design and planning. You can try to do this in one go with a heavy methodology, or you can be more flexible with an agile one. What you cannot do is expect any methodology to fix your lack of initial planning.
Incidentally, Kanban sounds more appropriate for your needs. Scrum works best with small teams and projects. Kanban can work with larger projects but it also works with a throughput of work approach, so design changes are continual and not chunked into sprints. I think you'd have more success with that.

A: 18 months, 150 tables and still not in production? Sounds much like a death march for me. The only way you can fix this, if there is any chance to save this now, is to narrow the scope of your project dramatically - at least for your first production release. What you need is proper release planning, small, reachable goals and getting the system to the end user as soon as possible.
And when you have your first release in production, with only a tenth of the requirements implemented, you will have to extend it step-by-step by the next block of requirements, which will cause "refactoring". You will also get feedback, which means bugfixing and changed requirements, which will cause refactoring, too.
Now to you question - will Scrum help? Maybe, maybe not. Scrum is a tool to support iterative development and changing requirements, and focussing on the important things first. Other "Agile" methods do this too, and a not-so-formalized process might handle that also. But as long as you try to bring a monster like this in one "big bang" into production, it does not matter if you use "agile" or "upfront" development, both will fail.
So before thinking about Scrum, first rethink your goals and your release strategy, and then check if Scrum is the right tool for that, not vice versa.


text:
Q: Kafka Compacted Topic Related Questions Kafka noob here! I have two questions:
1) Consider few Kafka consumers running on different Kubernetes pods as part of the same Kafka consumer group. The topics being consumed by these pods are compacted topics. Now, let's say one of the pods goes down and comes up in a while. Now my question is, will the consumer in question, receive all messages from that compacted Kafka topic ? Or, will it receive only the topics which arrived after it had come back from failure?
2) I understand that Kafka consumers receive topics from partitions starting from a "committed offset" . How will it work in case of "compacted topics", as Kafka will send events with the latest offset only

A: Consumers works the same way for compacted topics as non-compacted ones. During compaction if there are offsets with the same keys then only the latest key stays but the compacted offsets are never deleted it stays pointing to the latest key
Eg. if offsets 10,11,12 have the same keys , then only the 12th offset key would be retained after compaction and any consumer fetching offset 10,11 or 12 , it would fetch the same result i.e. key-value stored at offset 12 ( as key-value for 10,11 are deleted)
Coming to your questions -
1.Consumer can fetch from the desired offset , only thing is that if some offsets are compacted ,you will get the latest value for the compacted offsets
2.As explained consumers will continue to fetch from the last committed offset and if the offsets to be fetched has compacted you might get duplicate messages
Refer to the compaction logic in detail in the below kafka link
https://kafka.apache.org/documentation.html#design_compactionbasics


text:
Q: Correct JSON structure I need to return a leaderboard data in pages via JSON, which is the correct structure, is it this
{
 pages: [
         {
          [
           {user: John,
            rating:11},
           {user: Bob,
            rating: 20},
           {user: Andy,
            rating: 30},
            ...
          ]
         },
         {
          [
           {user: Sally,
            rating: 110},
           {user: Peter,
            rating: 115},
           {user: Jim,
            rating: 350},
            ...
          ]
         },
         ...
        ]
}

Or is this (correct JSON)
{
    "pages": [
        [
            {
                "user": "John",
                "rating": 11
            },
            {
                "user": "Bob",
                "rating": 20
            },
            {
                "user": "Andy",
                "rating": 30
            }
        ],
        [
            {
                "user": "Sally",
                "rating": 110
            },
            {
                "user": "Peter",
                "rating": 115
            },
            {
                "user": "Jim",
                "rating": 350
            }
        ]
    ]
}

UPDATE:
Thanks for all the prompt answers, and yes I did construct the JSON by hand which is obviously not a good idea as some of you have pointed out. The 2nd option is the proper JSON and I have updated it with the correct JSON structure for anyone else that might be reading this in the future.

A: The latter is correct, but you need to enclose all your strings with double quotes. You also used a period instead of a comma after the first closing square bracket.
You may wish to use JSONLint to validate your JSON.

A: Your first example doesn't make much sense: pages is an array whose elements are objects but there are no key-value pairs. Your second example makes more sense: pages is an array where which element is in turn another array containing a list of objects.
Note that neither of your examples is valid JSON. As explained in the previous paragraph, your first example has objects with no key-value pairs. Furthermore, in both examples the strings aren't quoted. In JSON, every string must be quoted, be it a key or a value.

A: You might want to check out this JSON validator :) http://www.jsonlint.com/

A: For starters, the first option is not valid JSON. The array:
{
 pages: [
         {
          [ <== HERE

...would require a name.  E.g.
{
 pages: [
         {
           "SomeName": [

Also, assuming John, Bob, Andy etc, are strings, then they should be:
[
           {user: "John",
            rating:11},
           {user: "Bob",
            rating: 20},
           {user: "Andy",
            rating: 30},
            ...
]

Some would also argue that your dictionary member names should be enquoted.


text:
Q: Load single image by map API and draw overlays I have an image which  I want to make it zoomable and dragable in browser, and draw some overlays like lines and markers on it.
So I wonder if I can use the map api like Google map or openlayers to load the image. Then I can use the draw feature provided by the API to add overlays.
Since the image size is not fixed ,some of them are almost 100M. So I may have to generate tiles first, but the image have no coordinates, so I do not know if it is possible.
Any suggestions?

A: Yes, it is definitely possible.
QGis has a QTiles plugin, which uses gdal2tiles under the hood, AFAIK.
Then you can use leaflet/openlayers to read your tiles from the created directory structure.


text:
Q: media(String str) allow no space in the str private static final String MEDIA_URL =
    "file:///d:/dt_32bars_120tribal.wav";
    //"file:///d:/Linkin Park - Numb.mp3";
 Media media = new Media(MEDIA_URL);
 MediaPlayer mediaPlayer = new MediaPlayer(media);

When I use the file:///d:/dt_32bars_120tribal.wav; the program can work. But when I use the second one: file:///d:/Linkin Park - Numb.mp3; it cannot work.
After I rename the MP3 as LinkinPark-Numb.mp3(remove all space), then I use file:///d:/LinkinPark-Numb.mp3; it can work now.
Does this mean that the Media() cannot allow space in the file name? but as we all know that sometimes the name of mp3 files contain several space. How can I deal with it?

A: You could use File.toURI() to generate a properly escaped URI string:
new java.io.File("abc def.mp3").toURI().toString();
;; => "file:/.../abc%20def.mp3"

See the Media(String) documentation:
The supplied URI must conform to RFC-2396 as required by java.net.URI.

Spaces, e.g., have to be escaped as %20.


text:
Q: darkening the body does not work, what is the problem? I am trying to darken the rest of the html file when opening a modal, to open the modal you must press show and by doing this through the 'modalState' function the darken class will be added to the body. In this case add a red color as a test. The problem is that while the class is added nothing happens. What is the problem? What is the correct way to do it?

    <!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link rel="stylesheet" href="src/style.css" >

    <title>Cristian Orellana M.</title>

C

Sobre Mi

Sobre Mi

Habilidades

Porfolio

Contacto

Blog

                <input type="radio" id="theme-dark" name="theme" checked /> Dark

                <input type="radio" id="theme-light" name="theme" />
                Light

              <button class="btn-contact">testing</button>

Sobre Mi

Mi nombre es Cristian Orellana Muñoz ¡Mucho gusto!. Soy un desarrollador de software en busca de nuevas oportunidades laborales, principalmente orientadas al desarrollo de aplicaciones web.

Me gusta mucho aprender nuevas tecnologías para el desarrollo de software por lo que constantemente me encuentro haciendo cursos de este rubro.

Si me quieres contratar debes de saber que soy una persona responsable y que valoro mucho el trabajo en equipo, considero importante el llevarse bien con quienes se trabaja y ayudar a quien lo necesite.

Hobbies: Esta es una lista de cosas que me gusta hacer

- Leer (Libros, Manga y Comics)

- Ver series y películas

- Hacer ejercicio (porque me mantiene saludable y en forma)

- Y jugar a video juegos (Me encanta jugar con mis amigos ;D )

Porfolio

Estos son algunos de los proyectos en los que he trabajado. En algunos projyectos trabaje en solitario y en otros trabaje con personas geniales.

Puedes pasar el mouse por una de las imagenes para ver más detalles.

Show

Show

Show

Show

Show

Show

Bruno Fritsch

                  <svg class="fill-current text-gray-500" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 18 18">
                    <path d="M14.53 4.53l-1.06-1.06L9 7.94 4.53 3.47 3.47 4.53 7.94 9l-4.47 4.47 1.06 1.06L9 10.06l4.47 4.47 1.06-1.06L10.06 9z"></path>
                  </svg>

Empresa del rubro automotriz. Su sistema permite crear documentos de compra y venta, inventario, contratos, contabilidad y callcenter (Esta es la web de acceso público la del sistema de los empelados no puedo agregarla ).

Puedes visitar el sitio en https://www.brunofritsch.cl/

                  #PHP
                  #JAVASCRIPT
                  #BOOTSTRAP
                  #POSTGRESQL
                  #WEBSERVICES

javascript
let theme_dark = document.getElementById('theme-dark');
let theme_light = document.getElementById('theme-light');

theme_dark.addEventListener('click', function() {
    console.log("pasa por theme dark")
    document.documentElement.classList.add('dark');
});

theme_light.addEventListener('click', function() {
    console.log("pasa por theme light")
    document.documentElement.classList.remove('dark')
});

const card_close = document.getElementById('card_close')
const card_panel = document.getElementById('card_panel')
const body = document.querySelector('body')
const main_body = document.getElementById('main_body')
const main_menu = document.getElementById('main_menu')
const test_div = document.getElementById('test_div')

function modalState() {
    if(card_panel.classList.contains('hidden')) {
        // Show modal
        card_panel.classList.remove('hidden')
        card_panel.classList.add('block')
        console.log(body)
        body.classList.add('darken')
        // Start animation open
        card_panel.classList.add('card_open')
    } else {
        // Delete modal
        card_panel.classList.add('hidden')
        card_panel.classList.remove('block')
        body.classList.remove('darken')
        // Show button

        // Remove animation open
        card_panel.classList.remove('card_open')
    }
}

function ModalShow(){
    const modal = document.getElementById("staticBackdrop")

    if(modal.classList.contains('hidden')) {
        // Show modal
        modal.classList.remove('hidden')
        modal.classList.add('block')

    } else {
        // Delete modal
        modal.classList.add('hidden')
        modal.classList.remove('block')
    }

}

/*
card_open.addEventListener('click', modalState)
card_close.addEventListener('click', modalState)
*/
function ShowTextView(id){
    console.log("pasa por function")
    console.log(id)
    const new_id = id.split("_")
    document.getElementById("show_text_"+new_id[1]).classList.remove("opacity-0");
    document.getElementById("img_proyect_"+new_id[1]).classList.remove("opacity-50");
}

function HideTextView(id){
    console.log("pasa por function")
    console.log(id)
    const new_id = id.split("_")
    document.getElementById("show_text_"+new_id[1]).classList.add("opacity-0");
    document.getElementById("img_proyect_"+new_id[1]).classList.add("opacity-50");
}

A: Reviewing this link I understood how to achieve the desired effect. https://www.w3schools.com/howto/howto_css_modals.asp
Adapting it to my code it looks like this:

On the JS side, the style must be applied to the modal, not to the body (the id of the modal is card_panel)
function modalState() {
  if(card_panel.classList.contains('hidden')) {
    // Show modal
    card_panel.classList.remove('hidden')
    card_panel.classList.add('block')
    console.log(body)
    card_panel.classList.add('darken')
    // Start animation open
    card_panel.classList.add('card_open')
  } else {
    // Delete modal
    card_panel.classList.add('hidden')
    card_panel.classList.remove('block')
    card_panel.classList.remove('darken')

    // Show button
    // Remove animation open
    card_panel.classList.remove('card_open')
  }
 }


text:
Q: Swift - Multiple Files Error: Cannot convert return expression of type '()' to return type 'Bool' I understand to provide code for the error but this error Cannot convert return expression of type '()' to return type 'Bool' is for multiple files, even files that have no code just a class view controller declaration. Picture is provided of all the files affected. I am not sure how to debug this since clicking on the error does not provide the line of the error, only brings up the file. For some files when clicking on the error and bring up the file the error will disappear for that file then reappear.

A: Try to find some place when you use "guard else { return }"
Maybe in some filter function.
Comment that place and try to build again.
If its build correctly then fix the "guard else" code.
I had same problem, and its helps me.

A:  func filterContent(searchText:String) {

    self.filteredUsers = self.usersArray.filter { user in

        let username = user!["businessName"] as? String

        return(username?.lowercased().contains(searchText.lowercased()))!
    }
    tableView.reloadData()

}

This code is where my errors had been coming from. This code was used in multiple files to sort users. This will throw this unfindable error in your code.

A: I don't know the circumstances of your case. In my case it was a map function on a publisher that didn't return a Bool and was assigned to a variable.
Original failing line was
publisher.map({ result in

Changed with
publisher.map({ result -> Bool in

A: Same here. It's weird, it's definitely a bug in Xcode. in my case problem was from this line:
var mainUrls: [String] = opts.map { if let u = $0.value ?? "" { return u } else { return } }

There should show error for return nothing in map closure, but instead in 24 files was showing:
Cannot convert return expression of type '()' to return type 'String'

A: I had the same problem, below is an example of how I got the error. context here is an NSManagedObjectContext. The problem here is the return without the Bool.
func a() -> Bool {
    return context.performAndWait {
        if (false) {
            return false
        }
        return
    }
}

For me the file with the error was one of the listed files and when building in the console it was the first file in the list och failed files.
Hopefully this will be helpful in some way in the search for your error.


text:
Q: where public schema is defined in postgres I did search, but couldn't get clear clue. There is 'public' schema in postgres. But where is the schema defined? I only see it when I create a new db. More I want to know is where it is defined and how to change it.
Thanks in advance.
Yang

A: The public schema is created in the template0 and template1 databases by the initdb command when the database cluster is initialised.
When you create a new database the template1 database is copied (cloned) to create the new database unless you specify a different template. All the contents of the template database are copied, so the new database starts out with a public schema.
You can customise the template1 database - or make new databases to use as templates, specifying them with the TEMPLATE option to the CREATE DATABASE command.
See the documentation on template databases.
If you want custom templates I'd recommend making a new DB as a template and customising it how you want. It's perfectly reasonable to DROP the public schema.

A: As you guessed; It is created when you create the db.
There is nothing else special about it other than it is the default schema you get after createdb and is the default search_path. You are free to DROP it, create another one named 'public' or operate completely without one named 'public'.
Just make sure you have something useful in your search_path or you might end up having to type fully-qualified names all day.


text:
Q: In Chrome, do iframes consume resources in the same way as tabs? I need to cycle automatically through several webpages using Chrome. There are Chrome extensions which will cycle tabs like this, but I wonder if iframes and setInterval could work too.
I want to keep each page open once I've loaded it, i.e. I would need to make many iframes and show/hide them, rather than reload on each change by setting the src on a single iframe.
Bearing in mind that the end result needs to be run for long periods of time, are there significant advantages or disadvantages to using multiple iframes instead of tabs?


text:
Q: UploadedFile - NullPointerException I am trying to fileupload component of Primefaces 3.0 based on the example given in the demo. I have also added commons-fileupload-1.2.2.jar and commons-io-2.0.1.jar along with primefaces-3.1.jar file.
I run the uploader I get a java.lang.NullPointerException could anyone please help me with this problem, I have searched the internet extensively and cannot find a solution that works.
I am using NetBeans 7.2.1 and GlassFish to deploy.
My Codes :
XHTML :
<h:form id="frm" enctype="multipart/form-data">

                    <h:form id="img" enctype="multipart/form-data">

        <h:panelGrid columns="2">
           <h:outputText value="Nom Projet :"/>
           <h:inputText id="Nom" value="#{ajoutprjt.nomProjet}" />
           <h:outputText value="Ref Projet :"></h:outputText><h:inputText value="#{ajoutprjt.idProjet}" />
           <h:outputText value="Date de Début :"></h:outputText><h:inputText value="#{ajoutprjt.dateDeb}" />
           <h:outputText value="Date de Fin :"></h:outputText><h:inputText value="#{ajoutprjt.dateFin}" />
           <h:outputText value="Chef  :"></h:outputText>
           <h:selectOneMenu value="#{ajoutprjt.idChef}">
               <f:selectItem itemValue="#{null}" itemLabel="-- select one --" />
               <f:selectItems value="#{ajoutprjt.tdata}" var="cmd"
                                             itemValue="#{cmd.id}" itemLabel="#{cmd.id} #{cmd.nom} #{cmd.prenom}" />
           </h:selectOneMenu>
           Documents :

           <h:outputText></h:outputText>

       </h:panelGrid>

                    </h:form>

        </h:form>[/code]

my  Bean :
package beans;

import com.persistence.Compte;
import com.persistence.Projets;
import com.persistence.geoUtil;
import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.primefaces.model.UploadedFile;
/**
 *
 * @author  SA
 */
@ManagedBean
@RequestScoped
public class ajoutprjt implements Serializable{

     private String idpro;
     private String IdProjet;
     private String NomProjet;
     private String DateDeb;
     private String DateFin;
     private String nomimg;
     private UploadedFile file;
     private String IdChef;
     private DataModel<Compte> tdata ;

       public ajoutprjt(){

                        }
      // getters et Setters

    ...

    public UploadedFile getFile() {
        System.out.println("Je suis sous GetFile: " );
        return file;
    }

    public void setFile(UploadedFile file) {
        System.out.println("je Suis Sous SetFile : ");
        this.file = file;
    }

  public void ajoutP(){
    //  String p=Integer.toString(puis);
     System.out.println("Ajout Projet de ref : " +IdProjet);
     System.out.println("Ajout Projet de Idchef est  : " +IdChef);
     System.out.println("file a ajouter e  : " +this.getFile().getSize());
     if(IdProjet.equals("")==false && NomProjet.equals("")==false  && DateDeb.equals("")==false && DateFin.equals("")==false && IdChef.equals("")==false){

           try{
        Session se=geoUtil.getSessionFactory().getCurrentSession();
        Transaction tr=se.beginTransaction();
        Query q = se.createQuery("SELECT p from Projets p where IdProjet = :rf");
           q.setParameter("rf", IdProjet);
           List<Object[]> list = (List<Object[]>) q.list();
           if(list.size() == 0){

         Projets p =new Projets();

         p.setNomProjet(NomProjet);
         p.setIdProjet(IdProjet);
         p.setDateDeb(DateDeb);
         p.setDateFin(DateFin);
         p.setIdChef(IdChef);
         // UploadedFile file = event.getFile();
          if(this.getFile()!= null) {
                 String fileName = file.getFileName();
                 byte[] fileBytes = file.getContents();
                 p.setNomimg(fileName);
                 p.setImg(fileBytes);}
             else{
                      p.setNomimg("Pas de fichier");
                      String s = "a";
                      byte[] a = s.getBytes();
                      p.setImg(a);
                         }
            se.persist(p);
            tr.commit();

         context.addMessage(null,new FacesMessage(FacesMessage.SEVERITY_INFO,"Projet ajouté avec succes","Compte chef ajouté avec succes"));
     this.setNomProjet("");
         this.setIdProjet("");
         this.setDateDeb("");
         this.setDateFin("");
         this.setIdChef("");

           }else{
               context.addMessage(null,new FacesMessage(FacesMessage.SEVERITY_ERROR,"Attention:Projet déjas existe","Attention"));
           }
           }
           catch(Exception e1){
               e1.printStackTrace();
       context.addMessage(null,new FacesMessage(FacesMessage.SEVERITY_ERROR,"Attention:Erreur d'insertion","Attention"));
           }
          }
       else{
         context.addMessage(null,new FacesMessage(FacesMessage.SEVERITY_WARN,"Attention Tous les champs doivent etre  remplis!!","Attention"));
       }

   }
}

This is my web.xml file :
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>Development</param-value>
    </context-param>
    <context-param>
        <param-name>primefaces.THEME</param-name>
        <param-value>aristo</param-value>
    </context-param>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
        <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>faces/auth.xhtml</welcome-file>
    </welcome-file-list>
    <resource-ref>
        <description>Base de données pour app Ontologie
Projet master Pro</description>
        <res-ref-name>jdbc/gcn</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
        <res-sharing-scope>Shareable</res-sharing-scope>
    </resource-ref>
        <filter>
         <filter-name>PrimeFaces FileUpload Filter</filter-name>
        <filter-class>
                org.primefaces.webapp.filter.FileUploadFilter
         </filter-class>
        </filter>
        <filter-mapping>
            <filter-name>PrimeFaces FileUpload Filter</filter-name>
             <servlet-name>Faces Servlet</servlet-name>
                 <dispatcher>FORWARD</dispatcher>
        </filter-mapping>
</web-app>

Any help would be greatly appreciated.
Here is the stack trace:
javax.faces.el.EvaluationException: java.lang.NullPointerException
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    at javax.faces.component.UICommand.broadcast(UICommand.java:315)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
    at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
    at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
    at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
    at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
    at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
    at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
    at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
    at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
    at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
    at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.NullPointerException
    at beans.ajoutprjt.ajoutP(ajoutprjt.java:176)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at com.sun.el.parser.AstValue.invoke(AstValue.java:254)
    at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:302)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
    ... 32 more

A: I don't understand how you can use this method "ajoutP" on "actionListener" like follow "actionListener="#{ajoutprjt.ajoutP}" so that you have a parameter in the method "ajoutP(FileUploadEvent event)". that generate the following Error  «javax.el.MethodNotFoundException»

A: You seem to have a lot of stuff on that page. Here is how I would approach debugging this:

*

*Download all the dependencies if you have not already done so (if you did then double check your work).
here is the link/source for dependencies

*

*Use this example from PrimeFace website to just create a separate fileuploadController and view page just like what they have at this link

*Try to make the above step working first, once you have that working then start adding those elements slowly to your existing current JSF page and controller and change to accommodate your requirements (start from scratch though and not with what you have already modified and posted on this page).
Just one thing I noticed:

*

*I see you have nested enctype="multipart/form-data" this maybe one of the contributing factors of being null is you have too many of these in one page and your controller is only getting one of them but this is just a educated observation which you may want to debug and look into before going through all the trouble/steps I listed out for you above.

A: In xhtml page Use actionListener instead of action as like

And change the ManagedBean ajoutP() method as
public void ajoutP(FileUploadEvent event){

        OutputStream out=null;
        InputStream fileContent=null;
        try{
            UploadedFile uploadedFile= event.getFile();
            out= new FileOutputStream(new
                           File("D:/")+uploadedFile.getFileName());
            fileContent= uploadedFile.getInputstream();
            int read=0;
            final byte[] bytes= new byte[1024];
            while((read= fileContent.read(bytes))!=-1){
               out.write(bytes,0,read);
            }
        }
        catch(FileNotFoundException fnfe){

        }
        catch(IOException ioex){

        }
}