text:
Q: this page say the value inputted by user in the textbox section I want the value the user inputted in the textbox section show up in the window.alert

<input class="textbox" type="text" placeholder="Username" name="" value="">

var name = document.getElementById ("textbox")
function myFunction() {alert("Welcome back!", name);}

This page say: Welcome back! "Username"

A: You have some mistake:
document.getElementById("textbox") only return DOM object.
You did not map function to any event, i assigned to blur event, you can choose other event.
You can change to this demo:

function myFunction(e) {
var name = document.getElementById("textbox").value;
  alert("Welcome back! " + name);
}
<input type="text" id="textbox" onblur= "myFunction()" />

A: The value property is what you need
var name = document.getElementById("textbox").value

function myFunction() {
  alert("Welcome back!", name)
}

myFunction()

A: You need to get the value of the text box:
var name = document.getElementById("textbox").value;


text:
Q: Infinispan: storing large objects > RAM size? Is it possible to use Infinispan for objects that are larger than the VM's total avilable RAM by supplying it with a store?
Update
I found this link which seems to indicate streaming support starting with infinispan 9: http://infinispan.org/docs/stable/user_guide/user_guide.html#hot_rod_protocol_2_6

A: Infinispan is not designed for storing single huge object (or object graph), the expected data model are key-value pairs where each pair has kilobytes, or few MBs at most. The total number of such pairs is not limited, though.

A: There is a Jira for this (https://issues.jboss.org/browse/ISPN-78) but it hasn't received attention in a long long time.

redpajama_set_name: RedPajamaStackExchange


text:
Q: In what cases HTTP referer will be truncated I'm trying to understand the behavior of HTTP referer header. I noticed that sometimes the referer is full (full URL, including path and query string) but mostly it includes the domain only.
For example 'https://www.google.com/' instead of 'https://www.google.com/search?q=http+referer+truncated&oq=http+referer+truncated&aqs=chrome..69i57.6485j0j1&sourceid=chrome&ie=UTF-8#q=http+referer+is+not+full'
Are there any rules as to when the refere and is full and when it's truncated?

A: Updated details as of Nov 2020...
Many browsers have started to default to a stricter referrer policy (strict-origin-when-cross-origin) when making a cross-domain request instead of the old default (no-referrer-when-downgrade). This will most often result in truncated urls, but occasionally means that the referrer will not be set at all (no-referrer).
Here is an excerpt from a good article about this:
https://plausible.io/blog/referrer-policy

Chrome is using strict-origin-when-cross-origin from version 85. Strict-origin-when-cross-origin is where the full path is sent if on the same domain but only sends the domain itself if going to another domain. Previously it used no-referrer-when-downgrade.

Firefox is using no-referrer-when-downgrade by default. It always passes the full path unless the request is sent from HTTPS to HTTP. Firefox is using strict-origin-when-cross-origin in the Private Browsing tabs and for known trackers.

Edge is using no-referrer-when-downgrade. Same as Firefox.

Safari is using strict-origin-when-cross-origin. Same as Chrome.

Brave is using no-referrer where the referrer header is completely removed. It never shares the full URL even for same-origin requests and you cannot even see the domain name for cross-origin requests.

A: HTTP referrer headers are created by browsers according to desired criteria using Referrer Policy even though there is a general standard used by majority of the browsers there are some differences about how the browsers handles the servers instructions, mainly mobile web browsers are the ones which does not cooperate nicely with WWWC recommendations on this matter.
So why is there need for different HTTP referrer headers? To understand this we need to look at what are these headers are used for first. Main purpose in its simplest form is "carrying information from the originating page to the new page".
Everywhere we see the word "information" in the web there is a information security concept attached to it and HTTP header is no different. Depending on what kind of information headers carry, server can specify the type of referrer policy needs to be used. Here is the list of referrer policies from W3
enum ReferrerPolicy {
  "",
  "no-referrer",
  "no-referrer-when-downgrade",
  "same-origin",
  "origin",
  "strict-origin",
  "origin-when-cross-origin",
  "strict-origin-when-cross-origin",
  "unsafe-url"
};
Detailed information about each of these are available in the Referrer policy link i included above.
To give an example;
Using google searching for "Yellow Pages". in this case
origin:https://www.google.ie
referer:https://www.google.ie/
Referrer Policy:origin
generated URL:https://www.google.ie/gen_204?atyp=i&ct=&cad=udla=3&ei=x65kGDkdyKGHDkF0KeoBg&e=12&zx=1494785478502
link to the first result is
https://www.google.ie/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwiA26TfiHSGDFHKFAKHQXoCWUQFggoMBB&url=https%3A%2F%2Fwww.goldenpages.ie%2F&usg=AFQjCNGTG-tsBSFHgMkXw_GuvOcLEOD2hg
While the actual URL is https://www.goldenpages.ie/
When we actually click the link referrer changes to
Referer:https://www.goldenpages.ie/ and the referrer policy is
Referrer Policy:no-referrer-when-downgrade
This means if we click another link from the current page we won't see all the additional parameters similar to the ones we saw in the URL from google search results page.
To prove this is the case; click any link from the current page and watch the referrer header changing according to the the policy type (Which can be found in the associated js file if you use developer tools and inspect the network activity)
When i click the "List your business" link referrer stay as
https://www.goldenpages.ie/list-your-business/
and no other parameters are passed
So just to tidy up this messy explanation; What URL gets generated is dependent on what rules are set regarding to Referrer policy may that be a simple base rule with no parameters or a very long URL with loads of information relating to the user and origin of the navigation.
Note: URLs wont work i have jumbled some letters.

A: There is both the Referrer-Policy header AND the referrer meta tag.
<meta name="referrer" content="none">

They seem to do exactly the same job (as described in @Ulug's answer). If both are present I don't know how the browser decides which to choose, I just deleted the HTML one to solve my problem.


text:
Q: how to efficiently make airflow dag definitions database-driven Background
I have some dags that pull data from an 3rd-party api.
The accounts we need to pull can change over time.  To determine which accounts to pull, depending on the process we may need to query a database or make an HTTP request.
Before airflow, we would just get the account list at the start of the python script.  Then we would iterate through the account list and pull each account to file or whatever it was we needed to do.
But now, using airflow, it makes sense to define tasks at the account level and let airflow handle retry functionality and date range and parallel execution etc.
Thus my dag might look something like this:

Problem
Since each account is a task, the account list needs to be accessed with every dag parse.  But since dag files are parsed frequently, you don't necessarily want to query the database or wait for a REST call with every dag parse from every machine all day long.  This could be resource intensive, and could cost money.
Question
Is there a good way to cache this type of config information in a local file, ideally with a specified time-to-live?
Thoughts
I have thought about a couple different approaches:

*

*write to csv or pickle file and use mtime to expire.

*

*the concern with this is that i might get collisions if two processes try to expire the file at the same time. i don't know how likely this is or what the consequences would be but probably nothing terrible.

*create a common sqlite DB for all such processes.  should be auto created first time a variable is accessed.  each config variable gets a row in table.  use last_modified_datetime column to tell when to expire.

*

*requires more elaborate code & dependencies.

*use airflow variables

*

*nice thing about this would be that it uses existing DB, so would be no $ per query and reasonable network lag, but it still requires network round trip.

*has benefit of being identical across all nodes in a multi-node setup.

*determining when to expire would probably be problematic so would probably create config manager dag to update the config variables periodically.

*but then this would add complexity to deployment and devolpment process -- the variables need to be populated in order to define the DAGs properly -- all developers would need to manage this locally too, as opposed to a more create-on-read cacheing approach.

*Subdags?

*

*never used them, but I have a suspicion they could be used here.  But the community seems to discourage their use anyway...

Have you dealt with this problem?  Did you arrive at a good solution?  None of these seems very good.

A: Airflow default DAG parsing interval is pretty forgiving: 5 minutes. But even that is quite a lot for most people, so it's quite reasonable to increase that if your deployment isn't too close to the due times for the new DAGs.
In general, I'd say it's not that bad to make a REST request at every DAG parse heartbeat. Also, nowadays the scheduling process is decoupled from the parsing process, so that won't affect how fast your tasks are scheduled. Airflow caches the DAG definition for you.
If you think you still have reasons to put your own cache on top of that, my suggestion is to cache at the definitions server, not on the Airflow side. For example, using cache headers on the REST endpoint and handling cache invalidation yourself when you need it. But that could be some premature optimization, so my advice is to start without it and implement it only if you measure convincing evidence that you need it.
EDIT: regarding Webserver and Worker
It's true that the Webserver will trigger DAG Parses as well, not sure about how frequent. Probably following the guicorn workers refresh interval (which is 30 seconds by default). Workers will do it also by default at the start of every task, but that can be saved if you activate pickling DAGs. Not sure if that's a good idea though, I've heard this is something destined to be deprecated.
One other thing you can try to do is to cache that in the Airflow process itself, memoizing the function that makes the expensive request. Python has a built-in functools for that (lru_cache) and together with pickling it might be enough and very very much easier than the other options.

A: I have the same exact scenario.
Have API call for multiple accounts. Initially created a python script to iterate the list.
When I started using Airflow thought about what you are planning to do. Tried 2 of the alternatives you listed. After some experimentation decided to handle retry logic within python with simple try-except blocks if HTTP calls fail. Reasons are

*

*One script to maintain

*Less Airflow objects

*Restartability is easier with one script in place.
(restarting failed job in Airflow is not a breeze (no pun intended))

At the end it's up to you, that was my experience.


text:
Q: Vitali set of outer-measure exactly $1$. I know that for any $\varepsilon\in (0,1]$ we can find a non-measurable subset (w.r.t Lebesgue measure) of $[0,1]$ so that its outer-measure equals exactly $\varepsilon$. It is done basicly with the traditional Vitali construction inside the interval $[0,\varepsilon]$ and noticing that such a set carries zero inner-mass, and thus its complement in $[0,\varepsilon]$ (being non-measurable as well) must carry the full outer-mass of $[0,\varepsilon]$.
However, this resulting non-measurable set is a complement of the traditional Vitali constructed set. My question asks if the Vitali construction itself can yield a non-measurable set with outer-measure of exactly $1$ (or any before-hand decided number from $(0,1]$). Some modifications can be done inside the construction of course, but in particular I would like to stay away from taking complements. Maybe someone knows how this could be done?
Any references and input is appreciated. Thanks in advance.

A: $\newcommand{\c}{\mathfrak{c}}$
Let $\c$ denote the cardinal of the continuum and wellorder the Borel subsets of $[0,1]$ as $(B_\alpha)_{\alpha < \c}$.  We build by transfinite recursion a sequence $(x_\alpha)_{\alpha < \c}$ of elements of $[0,1]$ such that:
(a) $x_\alpha$ is Vitali inequivalent to $x_\beta$ for all $\beta < \alpha$, and
(b) $x_\alpha \in [0,1] \setminus B_\alpha$ if $[0,1] \setminus B_\alpha$ is uncountable.
Note that this process can't get stuck, since if the complement of $B_\alpha$ is uncountable then it has cardinality $\c$, and thus it meets an unused Vitali equivalence class (since at most $|\alpha| < \c$ have been used so far).  Then by setting $X = \{x_\alpha : \alpha < c\}$ we obtain a set such that whenever $B$ is a Borel set with $X \subseteq B$, then $B$ has countable complement (and in particular has measure $1$).  So $X$ has outer measure $1$ as desired.


text:
Q: Windows, Ec2ServerCreate - Cannot set JSON attributes when running knife from Rails application I am able to launch new instance at AWS from Ruby on Rails application  (Chef::Knife::Ec2ServerCreate.new()). Works fine till I try to set JSON attributes. When I set them from command line and invoke knife.bat, it works.
Looking at ec2_server_create shows that command line option --json-attributes is mapped to symbol :json_attributes. I tried to set it using following code:
Chef::Config[:knife][:json_attributes] = "{'NodeName' : 'Node001'}"

and I get error:TypeError (no implicit conversion of Symbol into Integer):
As soon as I comment this single line, instance is created, registered with chef server and recipe is running.
Any suggestion how to set json attributes of first chef-client run?
PS
Sample code shows constant value for attribute, but actual value would be dynamically created.
Error message and code line where error occurs:
/chef/knife/core/bootstrap_context.rb:188:in `[]=': no implicit conversion of Symbol into Integer (TypeError)

Looking into source you can find:
def first_boot
  (@config[:first_boot_attributes] || {}).tap do |attributes|
    if @config[:policy_name] && @config[:policy_group]
       attributes[:policy_name] = @config[:policy_name]
       attributes[:policy_group] = @config[:policy_group]
    else
      attributes[:run_list] = @run_list #THIS LINE CAUSES EXCEPTION
    end
    attributes.merge!(:tags => @config[:tags]) if @config[:tags] && !@config[:tags].empty?
   end
end

I set run list.

A: The issue is that json_attributes needs to be a hash, not a string. It isn't the @run_list that is failing, it is "{'NodeName' : 'Node001'}"[:run_list] which when you see in on place is probably a bit clearer.


text:
Q: Arduino and MP3 Shield not working simultaneously with information received from Pieszo sensor The program I am writing essentially enables a person to run/step with a Pieszo sensor attached to the bottom of their shoe and a corresponding track with the same bpm will play through a small speaker that is attached to the MP3shield on the Arduino. This is a prototype for a bigger concept.
Below is what I have so far:
// libraries
#include <SPI.h>
#include <SdFat.h>
#include <SdFatUtil.h>
#include <SFEMP3Shield.h>
#include <SimpleTimer.h>

int knockSensor = 0;
int MINIMUM = 520;
int MAXIMUM = 530;
int counter = 0;
int comparativeBPM;

SdFat sd;

SFEMP3Shield MP3player;

SimpleTimer timer;

String trackLibrary[30] = {track001.mp3, track002.mp3, track003.mp3, track004.mp3, track005.mp3, track006.mp3, track007.mp3, track008.mp3, track009.mp3, track010.mp3, track011.mp3, track012.mp3, track013.mp3, track014.mp3, track015.mp3, track016.mp3, track017.mp3, track018.mp3, track019.mp3, track020.mp3, track021.mp3, track022.mp3, track023.mp3, track024.mp3, track25.mp3, track026.mp3, track027.mp3, track028.mp3, track029.mp3, track030.mp3};
//bpms increases by 1 starting with 151 in the track library above so 151-180

void setup() {
  Serial.begin(9600);
  timer.setInterval(1000, ticker);

  if(!sd.begin(9, SPI_HALF_SPEED)) sd.initErrorHalt();
  if (!sd.chdir("/")) sd.errorHalt("sd.chdir");

  MP3player.begin();
  MP3player.setVolume(10,10);
}

void loop() {
  timer.run();
  if (analogRead(knockSensor) >= MINIMUM && analogRead(knockSensor) <= MAXIMUM) { //if knock is between maximum and minimum threshold
    Serial.println("Step detected"); //print when step detected
    counter = knockSensor++; //increment counter every time step detected
    Serial.println(counter); //print counter value to test
  }
  if (timer == 60000) {
    comparativeBPM = (counter/60)*3; // divide counter by 60s to get BPM and multply by 3 to get average bpm
      if (comparativeBPM >= 151) {
        MP3player.playTrack(track001.mp3);
      }
      if (comparativeBPM == 152) {
        MP3player.playTrack(track002.mp3);
      }
      if (comparativeBPM == 153) {
        MP3player.playTrack(track003.mp3);
      }
      if (comparativeBPM == 154) {
        MP3player.playTrack(track004.mp3);
      }
      if (comparativeBPM == 155) {
        MP3player.playTrack(track005.mp3);
      }
      if (comparativeBPM == 156) {
        MP3player.playTrack(track006.mp3);
      }
      if (comparativeBPM == 157) {
        MP3player.playTrack(track007.mp3);
      }
      if (comparativeBPM == 158) {
        MP3player.playTrack(track008.mp3);
      }
      if (comparativeBPM == 159) {
        MP3player.playTrack(track009.mp3);
      }
      if (comparativeBPM == 160) {
        MP3player.playTrack(track010.mp3);
      }
      if (comparativeBPM == 161) {
        MP3player.playTrack(track011.mp3);
      }
      if (comparativeBPM == 162) {
        MP3player.playTrack(track012.mp3);
      }
      if (comparativeBPM == 163) {
        MP3player.playTrack(track013.mp3);
      }
      if (comparativeBPM == 164) {
        MP3player.playTrack(track014.mp3);
      }
      if (comparativeBPM == 165) {
        MP3player.playTrack(track015.mp3);
      }
      if (comparativeBPM == 166) {
        MP3player.playTrack(track016.mp3);
      }
      if (comparativeBPM == 167) {
        MP3player.playTrack(track017.mp3);
      }
      if (comparativeBPM == 168) {
        MP3player.playTrack(track018.mp3);
      }
      if (comparativeBPM == 169) {
        MP3player.playTrack(track019.mp3);
      }
      if (comparativeBPM == 170) {
        MP3player.playTrack(track020.mp3);
      }
      if (comparativeBPM == 171) {
        MP3player.playTrack(track021.mp3);
      }
      if (comparativeBPM == 172) {
        MP3player.playTrack(track022.mp3);
      }
      if (comparativeBPM == 173) {
        MP3player.playTrack(track023.mp3);
      }
      if (comparativeBPM == 174) {
        MP3player.playTrack(track024.mp3);
      }
      if (comparativeBPM == 175) {
        MP3player.playTrack(track025.mp3);
      }
      if (comparativeBPM == 176) {
        MP3player.playTrack(track026.mp3);
      }
      if (comparativeBPM == 177) {
        MP3player.playTrack(track027.mp3);
      }
      if (comparativeBPM == 178) {
        MP3player.playTrack(track028.mp3);
      }
      if (comparativeBPM == 179) {
        MP3player.playTrack(track029.mp3);
      }
      if (comparativeBPM == 180) {
        MP3player.playTrack(track030.mp3);
      }
    }
    timer.restartTimer(timer);
  }
}

void ticker() {
  Serial.print("Time (s): ");
  Serial.println(millis()/1000);
}

If anyone has any idea how this works, any assistance would be much appreciated. The MP3 shield I am using is a SparkfunMP3 shield and comes with it's own reference libraries here https://learn.sparkfun.com/tutorials/mp3-player-shield-hookup
It makes sense that this should work but I don't know enough about the documentation to figure out why this isn't working! Please help


text:
Q: Slicing multiple dimensions in a ndarray How to slice ndarray by multiple dimensions in one line? Check the last line in the following snippet. This seems so basic yet it gives a surprise... but why?
import numpy as np

# create 4 x 3 array
x = np.random.rand(4, 3)

# create row and column filters
rows = np.array([True, False, True, False])
cols = np.array([True, False, True])

print(x[rows, :].shape == (2, 3))  # True ... OK
print(x[:, cols].shape == (4, 2))  # True ... OK
print(x[rows][:, cols].shape == (2, 2))  # True ... OK
print(x[rows, cols].shape == (2, 2))  # False ... WHY???

A: Since rows and cols are boolean arrays, when you do:
x[rows, cols]

it is like:
x[np.where(rows)[0], np.where(cols)[0]]

which is:
x[[0, 2], [0, 2]]

taking the values at positions (0, 0) and (2, 2). On the other hand, doing:
x[rows][:, cols]

works like:
x[[0, 2]][:, [0, 2]]

returning a shape (2, 2) in this example.


text:
Q: How should I combine St monad and State monad (or equivalent)? I am building code to gain understanding, in fact a Solitaire solver.
I have a simple brute force implementation which uses the State monad, really just to prove I can use it (it only keeps a count of each move evaluated).
But now I want to use Unboxed Mutable arrays to record the visited boards and thereby shortcut evaluation of paths when I reach a board position which was already visited via another path.
It seems that the ST monad doesn't allow me to thread implicit state, but that I must use ST (or IO), in order to get access to the Mutable array.  So it seems I must combine two Monads - State to thread the state (which will actually include a Mutable array), and another (ST) to gain the Mutable array functions.

*

*Is this right?

*And if so, is there a better alternative than the (canonical?) combination of Data.Array.ST/Control.Monad.ST/Control.Monad.ST and mtl?

*If I do go this route, does it matter which order I stack ST and State?

*Should I consider rolling my own single Monad based on either or both ST or State in order to avoid using monad transformers?

A: I'm not 100% sure that the ST monad is the way to improve performance for a search task like this. But assuming it is... You can "thread state" by just putting the state that you want to keep into an STRef. You can do this without needing to mix multiple monads together, which should make things much simpler for you.
You definitely need either the ST or IO monad if you want mutable state. (Or the STM monad, but that's only used for thread synchronisation, which you don't need here.)
The order in which monads are stacked can matter - but in this case, it doesn't. If you had something like the List monad and the Error monad, then depending on the stacking order, an error either fails just one possibility in the list, or all possibilities in the list. For your case, there aren't any effects which change depending on stack order.
...which is fortunate, since there isn't a transformer for turning things into ST. So ST has to be the inner monad.
Having said all that, again, I don't think you actually need a monad stack here. I would think a simple STRef will do.

A: When using ST, any arrays or references you have are not really state in the State monad sense of the word: they are never modified! You can think of them as a pointer; the pointer is constant, though the things it points at may change. So you can just pass your arrays or references or whatever in to your ST actions as function arguments. The StateT machinery would be appropriate if you expected the ST action to need to return a different array than the one it was passed -- i.e. not just modify the existing array but create a fresh one. Since this is generally not the case, StateT is not appropriate.
If you really want to have a monad transformer stack, you could put your arrays and references into the environment of a ReaderT monad. But this is probably not necessary.


text:
Q: How/where to load data which a certain class needs injected into it To make code more testable I have learned to inject an objects dependencies into it and I realized I was not doing that in my Config and Router classes.
The Config object loads up the application configuration settings from a php file and the Router loads up custom routes from a php file.
I want to inject the configuration settings into the Config object when it is instantiated and inject the custom routes into the Router object when it is instantiated.
These objects are created in a small dependency injection container so would the code for loading the data go in there? Or does it make sense to have some sort of loader class which can load data from php files and encapsulate any logic/error checking?


text:
Q: Keep style of  while dragging I have a table where I use JqueryUI and when I make a drag of a row the style of this disappear, that's normal cause when you make a drag of the row, this pass to be outside of table.
The element created while dragging is a
and have the class .placeholder-style I want to keep the padding of the fields in the row created while drag.
How can I do this?

$("#tabs").tabs();

$("#tbodyproject").sortable({
  items: "> tr",
  appendTo: "parent",
  helper: "clone",
  placeholder: "placeholder-style",
  start: function(event, ui) {

    var cantidad_real = $('.table thead tr th:visible').length;
    var cantidad_actual = $(this).find('.placeholder-style td').length;

    if (cantidad_actual > cantidad_real) {
      var cantidad_a_ocultar = (cantidad_actual - cantidad_real);

      for (var i = 0; i <= cantidad_a_ocultar; i++) {
        $(this).find('.placeholder-style td:nth-child(' + i + ')').addClass('hidden-td');
      }
    }

    ui.helper.css('display', 'table');

  },
  stop: function(event, ui) {
    ui.item.css('display', '')
  },
  update: function(event, ui) {
    let newOrder = $(this).sortable('toArray');
    $.ajax({
        type: "POST",
        url: '/admin/projects/updateOrder',
        data: {
          ids: newOrder
        }
      })
      .done(function(msg) {
        location.reload();
      });
  }
}).disableSelection();
img {
  width: 100px;
}

.hidden-td {
  display: none !important;
}

.table {
  background-color: green;
  border: 0;
}

.trdrag {
  background-color: yellow;
}

.thcenter {
  background-color: grey !important;
}

.ui-sortable-helper {
  left: 0px!important;
}

.idrow {
  width: 5%;
}

.tdvisible {
  width: 5%;
}

.tdslug {
  width: 10%;
}

.tdimg {
  width: 15%;
}

.tdorder {
  width: 20%;
}

.tdacciones {
  width: 40%;
}

@media (max-width: 500px) {
  .ocultarid {
    display: none;
  }
  .tdslug {
    width: 15%;
  }
}

@media (max-width: 350px) {
  .ocultarvisible {
    display: none;
  }
  .accionesvisible {
    display: none;
  }
  .ordenvisible {
    display: none;
  }
}

<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />

            ID
            Visible
            Nombre
            Header
            Home
            Orden
            Acciones

1

            Testing
            Testing2

              Yes

Slug

Order 1

              <form method="POST" action="{{route('admin.projects.destroy',$project->id)}}" onsubmit="return ConfirmarBorrar()">
                Edit
                <input type="submit" value="Delete" class="btn btn-danger btn-sm" id="margindata">
                <input type="hidden" name="_token" value="Token 1">Delete
              </form>

2

            Testing

              Yes

Slug

Order 1

              <form method="POST" action="{{route('admin.projects.destroy',$project->id)}}" onsubmit="return ConfirmarBorrar()">
                Edit
                <input type="submit" value="Delete" class="btn btn-danger btn-sm" id="margindata">
                <input type="hidden" name="_token" value="Token 1">Delete
              </form>

3

            Testing

              Yes

Slug

Order 1

              <form method="POST" action="{{route('admin.projects.destroy',$project->id)}}" onsubmit="return ConfirmarBorrar()">
                Edit
                <input type="submit" value="Delete" class="btn btn-danger btn-sm" id="margindata">
                <input type="hidden" name="_token" value="Token 1">Delete
              </form>

1

            Testing

              Yes

Slug

Order 1

              <form method="POST" action="{{route('admin.projects.destroy',$project->id)}}" onsubmit="return ConfirmarBorrar()">
                Edit
                <input type="submit" value="Delete" class="btn btn-danger btn-sm" id="margindata">
                <input type="hidden" name="_token" value="Token 1">Delete
              </form>

4

            Testing

              Yes

Slug

Order 1

              <form method="POST" action="{{route('admin.projects.destroy',$project->id)}}" onsubmit="return ConfirmarBorrar()">
                Edit
                <input type="submit" value="Delete" class="btn btn-danger btn-sm" id="margindata">
                <input type="hidden" name="_token" value="Token 1">Delete
              </form>

5

              Yes

Slug

Order 2

              <form method="POST" action="{{route('admin.projects.destroy',$project->id)}}" onsubmit="return ConfirmarBorrar()">

                Edit
                <input type="submit" value="Delete" class="btn btn-danger btn-sm" id="margindata">
                <input type="hidden" name="_token" value="Token 2">Delete
              </form>

https://jsfiddle.net/3g3bt80e/9/

A: Try defineing the td / tr tags the css to a certain height & width this may resolve ur problem.


text:
Q: Animated images on homescreen I have a client that wants me to make an app that creates animated backgrounds behind the app icons on Homescreen. I said that it's not possible but I just want to be sure that I'm not totally wrong...
It should work on both Android and iOS.
Am I wrong?


text:
Q: Different image size on Safari iOS Mobile I have a problem with my website on iOS mobile devices - the image height isn't at is should be (look at the images).
Here is the website if you want to look
The image has these attributes:
height: auto;
max-height: 1000px;
width: 100%;
max-width: 100%

behavior on normal broswer
[behavior on safari ios][3]


text:
Q: Show Input Error Using Custom directives Without Using NgMessages I Have input and I use a custom directive to display the input error with use of ng-messages. And I want to use attribute for showing the error, not ng-message.
Here is my Code
    <md-input-container class="md-block" flex-gt-sm>
        Enter Your Message
     <input required md-no-asterisk ng-model="newEmployee.message" type="text" id="name" name="name" formValidate>

Message is Invalid

 </md-input-container>

Directive :
    app.directive('formValidate', function() {
return {
    restrict: 'A',
    require: 'ngModel',
    template: '
Name is required
',
    link: function(scope, element, attr, ctrl) {
        function formValidate(ngModelValue) {
            if ([A - z].test(ngModelValue)) {
                ctrl.$setValidity('formValidate', false)
            } else {
                ctrl.$setValidity('formValidate', true),

            }
        return ngModelValue;
        }
        ctrl.$parsers.push(formValidate);
    }
};
});

A: Make use of angular-form. Go through this doc https://docs.angularjs.org/guide/forms
Without ng-messages

    First Name

        <input class="form-control" name="firstname" id="firstname" ng-model="vm.firstname" type="text" ng-change = "vm.resetValidationErrors('firstname')" required/>

First name is required.

{{ vm.form.firstname.errorMessage }}


text:
Q: Notification in Contact update when Contact is merged When contact is merged and assume winning contact is updated, is there a SFDC standard event that will tell us that "winning contact is updated as part of merge process NOT regular UI record update"? If not, what are the different ways that I can know in Update Contact Trigger that contact is updates as part of merge process?

A: To reliably detect merge events, you'll need to implement an after delete trigger. Records in the after delete trigger will have a special field called MasterRecordId populated, which allows you to determine that they've been deleted due to a merge into the record whose Id is provided. This applies to all objects that support merges.
See Triggers and Merge Statements for details on the order of operations that are performed during a merge. Update triggers are fired as they normally would be, but that doesn't provide you any information about the merge as such.
The way the documentation is written and your experience with static variables makes me think the merge is executed in two ordered transactions: first the Delete event is completely executed, then the Update event is executed in a separate transaction with no access to the merge details.
The only other option, if you don't want to do your processing in after delete, would be to write merge details to a custom object that you can later process asynchronously in a Queueable rather than a before/after update trigger


text:
Q: How to run a senario 1000 time using Protractor Scenario: Create 500/1000 Chat for a module Collaboration.
For Creating 50 Chat it is taking 5 mins now, I want to create 500 chat in minimum time, I used multithreading concept in protractor because this is an angular Application. And i as of now I m not able to create more than 40 chats.
Problem: Maximum is it allowing 5 browsers at a time.
and the major issue is for even 2 browsers are not working well. it is losing the focus in a browser.
Any suggestion in protractor or any other way to do it.

A:
Please note that selenium is best used for web browser automation and
is not design to create large amounts of data and/or to perform same
steps simultaneously.

So if you wanted to create data in a minimum amount of time. The best way to do this is to use Performance Testing Software like jmeter, HP LoadRunner. That way, you can utilize a large number of users performing these steps to be able to create your data. And the limit of the number of threads is dependent on your load generator - machine's specifications.


text:
Q: Sorting of 2 different sets of values of single row of a table I have the below table,
A             B            C
--------   ----------     -----------
Akhil      Kerala         0008 – 0030
Athul      Kerala         15
Basil      Delhi          0031 – 0059
Rahul      Chennai        32
Kishore    New York       0060 – 0090
Anoop      Mumbai         45

I have to sort the entries according to the column C, the sorted order of the column should be like,
15
32
45
0008 – 0030
0031 – 0059
0060 – 0090
Kindly advice. Thanks in advance.

A: Oracle SQL:
select t.*,
  to_number(decode(instr(c,' '),5,null,c)) atr1,
  decode(instr(c,' '),5,c,null) atr2
from TEST_TAB t
order by atr1, atr2

If the table has many rows and the query will be frequently executed then you should add this index:
create index sort_idx on TEST_TAB (
  to_number(decode(instr(c,' '),5,null,c)),
  decode(instr(c,' '),5,c,null)
);

If you use e.g. MSSQL database then replace DECODE with CASE statement and INSTR with CHARINDEX.


text:
Q: Transpiling  language into a custom one Our company has a legacy assembly-like language with some terrible design choices. I'm pretty sure the language is not going to change, since way too many legacy things might change their behavior which would be obviously unintended.
I'd like to use/find any language which has at least C-like syntax ( or something similar, just make it not exotic, like LISP or so :) )
Only basic elements are needed, for example:

*

*functions

*local variables

*basic operators (bitwise, basic math)

*Comments

*

*NO global variables exists

No OOP or anything special is necessary.
I don't want to actually run that piece of code, I just want to use a decent syntax, which during a "compilation" is converted into that ugly assembly-like (asm would be at least organized, but it's worse) language.
What can you recommend me to start looking at? If not necessary I wouldn't like to write my own parser for this. I'm good at C++, but any language is okay if it better suits my needs.

A: Watch out that you are now introducing another layer of testing into the mix: testing and debugging compilers can take a lot of effort. It's also another layer of software to maintain, and after you've moved on...
And if integrating with existing software, be prepared for non-standard register use etc.
Possible approaches:

*

*Look into using an existing macro processor to improve the assembly programming experience. e.g. m4 (GNU, Unix)

*Use a simple DSL written in Ruby (which happens to be good for writing domain specific languages) to generate things like configuration tables, etc.

*Write your own macro processor which will recognize some simple macro directives and expand these with templates. Don't try and be too clever - I don't know your target hardware, but you might not have significant stack space (or, for that matter, a stack). etc. This might rule out nested control structures, local variables, etc.

I assume that the target is some proprietary hardware, so use of the assembler is unavoidable.
If it isn't proprietary hardware, check first that there isn't a C compiler, FORTH interpreter, or (if ancient) a BCPL compiler already available. It's highly likely the manufacturer didn't just have an assembler in their SDK.

A: You probably don't want to use something like LLVM for your use case. It is an extremely flexible IR, which means you will end up having to implement a bunch of stuff you don't really need, just to get it to work. If you had to be able to run any arbitrary existing C program on your assembly language, then it would be worth it.
Parsers aren't really that hard to write. Mostly you have to get past all the computer science jargon. Do a search for recursive descent parsers for the easiest method to understand (in my opinion).  The next easiest method is probably to find a parser combinator library for your language. After that, using a parser generator like bison.
The tricky part is taking the Abstract Syntax Tree your parser produces and outputting your target code. Parser tutorials usually have you make an interpreter because it's easier. Once you've gone through those, then made an interpreter for your custom language, you will have the background knowledge to have a better idea of what the next step is.


text:
Q: Laravel deleted event on mass delete for logging I'm trying to use spatie activity log for a model which is working fine for creating and updating events, but not for deleted events.
after some googling, i got the following
When executing a mass delete statement via Eloquent, the deleting and deleted model events will not be dispatched for the deleted models. This is because the models are never actually retrieved when executing the delete statement.

is there any workaround to mass delete the selected items while dispatching the events so ActivityLog can pick it up ? other than doing it manually by looping through the selected items and deleting them or loop through them and adding log activity for each manuly.
// Delete all selected units that are not in the parentsIds array
    Unit::whereIn('id',$this->selected)->whereNotIn('id',$this->parentsIds)->delete();

and this is the model
// Activity Logging
protected static $recordEvents = ['deleted', 'updated', 'created'];
use LogsActivity;
public function getActivitylogOptions(): LogOptions
{
    return LogOptions::defaults()
    ->logOnly(['name', 'type','Parent.name']);
    // Chain fluent methods for configuration options
}

A: You could retrieve the Model Instance
$unitsToDelete = Unit::whereIn('id',$this->selected)->whereNotIn('id',$this->parentsIds)

Then with a loop call delete method for each record
foreach($unitsToDelete as $unit) {Unit::find($unit->id)->delete()}
Not better and elegant way, but a workaround that solve the problem


text:
Q: How to find the mean and Std of a 3 channel image from numpy import asarray
from PIL import Image

image = Image.open('../input/chest-xray-pneumonia/chest_xray/train/NORMAL/IM-0115-0001.jpeg')
pixels = asarray(image)

pixels = pixels.astype('float32')
means = pixels.mean(axis=(0,1), dtype='float64')
stds = pixels.std(axis=(0,1), dtype='float64')
print('Means: %s, Stds: %s' % (means, stds))
pixels = (pixels - means) / stds
means = pixels.mean(axis=(0,1), dtype='float64')
stds = pixels.std(axis=(0,1), dtype='float64')
print('Means: %s, Stds: %s' % (means, stds))'''

output>> Means: 128.90747832983968, Stds: 62.30103035552067
         Means: 1.2235509834827096e-07, Stds: 1.0000000181304383

The problem is while putting 3 channel image ,only got two values each

A: Separate the image channels into r,g,b using OpenCV,
Then use numpy mean and std function to calculate the mean and standard deviations for each channel.
Example for separating the image into rgb channels.
import cv2
import numpy as np

img = cv2.imread("image.jpg")
b = img[:,:,0]
g = img[:,:,1]
r = img[:,:,2]

A: You can pass tuple of axis you want results for in dim para of torch.mean and torch.std.
pixels = torch.rand(3, 50, 50)          # if shape of `pixels` like [channels, height, width]

pixels.mean((1,2))                      # torch.mean(pixels, dim=(1,2))
tensor([0.4948, 0.4910, 0.4921])

pixels.std((1,2))                       # torch.std(pixels, dim=(1,2))
tensor([0.2891, 0.2896, 0.2880])


text:
Q: Appropriate distance measure between two finite state Markov chain models? I am empirically creating Markov chains similar to this question. I end up with several finite state Markov chain models with the same nodes but varying transition probabilities. I want to calculate a pairwise distance between those models. What are appropriate distance measures to compare two Markov chains?
In my case the state space are user actions in a computer system and the transition probabilities are the observed transition frequencies between different actions.

A: As the problem comes down to compare two probability vectors, I guess you could use for instance the Kullback–Leibler divergence or, if you need a symmetrical measure, the Jensen–Shannon divergence.
Hope this help


text:
Q: Getting Class Property Values from Linq Expression In Html Helper MVC3 I have an HTML helper that I need to pass an Object to.  This Object is a class that has some Properties on it that I would need to access in the helper.  The actual base class of this object is a generic type so I decided that I would use a Linq expression and pass it the object.
Here is the method signature:
public static MvcHtmlString PartyDetailsField<TModel, TProperty>(this HtmlHelper<TModel> helper, string controlLabelText, Expression<Func<TModel, TProperty>> expression, IEnumerable<IDetailsConfiguration> configuation, string width = "")

Here is how I use the control:
@Html.PartyDetailsField("Identifiers", m => m.Person, Model.IdentifierConfiguration, "186px")

I need the instance information from m.Person.  How can I get the object instance and access the properties of the class instance from the expression?  Is there a better way of doing this?

A: suggest reading this post http://blogs.msdn.com/b/csharpfaq/archive/2010/03/11/how-can-i-get-objects-and-property-values-from-expression-trees.aspx


text:
Q: How can I create a dependent pick list on a visual flow page? I have 2 pick-list fields on an object, that are dependent to each other.
How can I create such connection on a visual-flow screen?

A: By following these steps you can show your Controlling and dependent piclist on Visual flow.

*

*Controlling picklist will be in Screen 1 and Dependent picklist will
be in child screens of Screen1,

*Based on the selected value in controlling picklist, go the
corresponding screen ( by putting decision box in between)

*We can remove 'Required' Line from Dropdown, edit the screen > double
click on right side drop down, on left you can find an option to
change

Let me know if this solves the problem!


text:
Q: How to trim extra spaces after the last character in PHP using anyscript Can u guys help me with a code that eliminates white spaces form the front as well as the back when inserting into my sql back of characters
For Eg: lets say that the word "   hello   ". Now i want to remove all these space when i enter my data in MySQL so when it gets inserted there are no more spaces either in the front or back of the word.

A: You can use trim():
$string = '    aaa ';
$string = trim($string);
var_dump($string);
string(3) "aaa"

This function returns a string with whitespace stripped from the beginning and end of str.

A: The PHP Trim Function does exactly that.

A: Use PHP's trim function.

trim — Strip whitespace (or other characters) from the beginning and end of a string

$string = "   hello   ";
echo trim($string); // "hello"

There is also ltrim and rtrim for trimming only the beginning/end of a string.

You also tagged JavaScript so I'll provide a JS resource as well:
Faster JavaScript Trim has many implementations of trim in JS.
String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, "");
};

"   hello   ".trim();  // "hello"

A: With Php you can use an inbuilt function trim here is an example :-
<?php
    $my_var = '   hello world  ';
    echo $my_var . "\n";  //  hello world
    $trimmed = trim($my_var);
    echo $trimmed ;       //hello world

?>

you can check it Here. The official reference of PHP for the same  PHP Reference TRIM

A: Use PHP's trim() function:
$trimmed = trim($text);

If you want to do this with JavaScript as well, you can use .trim():
> '   asd   '.trim()
"asd"

A: Try the trim() function PHP Manual - Trim
$str = ' Hello World ';
echo trim($str);

// will result in "helloworld"

A: You want to use the trim function such as:
$myString = ' The string to trim ';
$myString = trim($myString);

echo $myString;

The output of this is: 'The string to trim'
Notice the removal of the spaces...


text:
Q: Perl not closing TCP sockets if clients are no longer connected? The purpose of the application is to listen for a specific UDP multicast and then to forward the data to any TCP clients connected to the server. The code works fine, but I have a problem with the sockets not closing after the TCP clients disconnects. A socketsniffer utility shows the the sockets remain open and all the UDP data continues to be forwarded to the clients. The problem I believe is with the "if ($write->connected())" block as it always return true, even if the TCP client is no longer connected. I use standard Windows Telnet to connect to the server and to see the data. When I close telnet, the TCP socket is suppose to close on the server.
Any reason why connected() show the connections as active even if they are not? Also, what alternative should I use then?
Code:
    #!/usr/bin/perl

use IO::Socket::Multicast;
use IO::Socket;
use IO::Select;

my $tcp_port = "4550";
my $tcp_socket = IO::Socket::INET->new(
                                       Listen    => SOMAXCONN,
                                       LocalAddr => '0.0.0.0',
                                       LocalPort => $tcp_port,
                                       Proto     => 'tcp',
                                       ReuseAddr => 1,
                                      );
use Socket qw(IPPROTO_TCP TCP_NODELAY);
setsockopt( $tcp_socket, IPPROTO_TCP, TCP_NODELAY, 1);

use constant GROUP => '239.2.0.81';
use constant PORT  => '6550';
my $udp_socket= IO::Socket::Multicast->new(Proto=>'udp',LocalPort=>PORT);
$udp_socket->mcast_add(GROUP) || die "Couldn't set group: $!\n";

my $read_select  = IO::Select->new();
my $write_select = IO::Select->new();

$read_select->add($tcp_socket);
$read_select->add($udp_socket);

## Loop forever, reading data from the UDP socket and writing it to the
## TCP socket(s).
while (1) {

    ## No timeout specified (see docs for IO::Select).  This will block until a TCP
    ## client connects or we have data.
    my @read = $read_select->can_read();

    foreach my $read (@read) {

        if ($read == $tcp_socket) {

            ## Handle connect from TCP client.  Note that UDP connections are
            ## stateless (no accept necessary)...
            my $new_tcp = $read->accept();
            $write_select->add($new_tcp);

        }
        elsif ($read == $udp_socket) {

            ## Handle data received from UDP socket...
            my $recv_buffer;

            $udp_socket->recv($recv_buffer, 1024, undef);

            ## Write the data read from UDP out to the TCP client(s).  Again, no
            ## timeout.  This will block until a TCP socket is writable.
            my @write = $write_select->can_write();

            foreach my $write (@write) {

                ## Make sure the socket is still connected before writing.
        if ($write->connected()) {
                     $write->send($recv_buffer);
                   }
                else {
                    $write_select->remove($write);
                    close $write;

                }

            }

        }

    }

}

A: I don't know anything about perl, or perl sockets for that matter, but I can't think of a socket API that provides a way to know if a socket is connected. In fact, I'm pretty sure TCP doesn't actually have a way of knowing immediately like this. This suggests to me that connected() is not telling you what you think it is telling you. (I have no idea, but I'll bet it is telling you whether you've called connect/accept or not)
Usually sockets tell you they've become disconnected by reading or writing zero bytes - you might want to check the return value of write to see if it ever returns zero

A: Thanks for the feedback. I have found a solution that seems to work well for me(Thanks Stewart). It was as simple as checking the return value:
$resultsend = $write->send($recv_buffer);
if (!$resultsend) {
                $write_select->remove($write);
                close $write;
}

TCP sockets are closed now after a client disconnects.

A: The IO::Socket connected method just tells you whether the socket is in a connected state, i.e., whether you called "connect" on it after you created it. As Stewart said, there is no general way to tell if the other end of a TCP socket dropped off, and whether you are "still connected".

A: Off the top of my head, try:
ReuseAddr => 0
I'm more than certain the IO::Socket's magic is what's causing your issues.


text:
Q: Consequences of Singletons So I just delved into the Singleton classes and yes, I find them quite helpful. I use my singletons mostly for data storage for multiple targets (views, tables etc.). That being said, I can already see myself going to implement a lot of singletons in my project.
But can a lot of singletons have a negative impact? From what I've read about singletons is that you create one instance for each of them in a proces. Other class instances get released (assuming they get released properly) from memory, then should singletons be released too?
So to narrow it down to one question: Is it harmful to have a lot of singletons?

A: Singletons don't scale.  No matter what you think should be a singleton, when your system gets bigger, it turns out you needed more than one.
If you NEVER need more than one, a singleton is fine.  However, as systems scale, you typically need more than one of anything within its own context.
Singletons are merely another way to say "global".  It's not bad, but generally, it's not a good idea for systems that evolve and grow in complexity.

A: From GOF Book:

The Singleton pattern has several benefits:

*

*Controlled access to sole instance. Because the Singleton class encapsulates its sole instance, it can have strict control over how
  and when clients access it.

*Reduced name space. The Singleton pattern is an improvement over global variables. It avoids polluting the name space with global
  variables that store sole instances.

*Permits refinement of operations and representation. The Singleton class may be subclassed, and it's easy to configure an application
  with an instance of this extended class. You can configure the
  application with an instance of the class you need at run-time.

*Permits a variable number of instances. The pattern makes it easy to change your mind and allow more than one instance of the Singleton
  class. Moreover, you can use the same approach to control the number
  of instances that the application uses. Only the operation that grants
  access to the Singleton instance needs to change.

*More flexible than class operations. Another way to package a singleton's functionality is to useThe Singleton class can be
  subclassed. class operations (that is, static member functions in C++
  or class methods in Smalltalk). But both of these language techniques
  make it hard to change a design to allow more than one instance
  ofclass. Moreover, static member functions in C++ are never virtual,
  so subclasses can't override them polymorphically.


text:
Q: Should I bring temporary variable declarations out of loops in C and C++? Here is what I mean, suppose I have code like:
for (int i = 0; i < 1000; i++) {
    char* ptr = something;
    /*
    ... use ptr here
    */
}

It seems that char* ptr gets allocated every time in the loop, making it ineffective?
Is it more effective to write this?
char* ptr = something;
for (int i = 0; i < 1000; i++) {
    /*
    ... use ptr here
    */
}

Please comment on this interesting problem. Thank you!
Thanks, Boda Cydo.

A: I'm of the school that thinks it's better to limit the scope of variable names as much as possible; if ptr isn't meant to be referenced outside of the loop, then it should not be declared outside of the loop.
However, if something turns out to be an expensive operation AND it's invariant (i.e., it doesn't depend on i) AND it's preventing your code from meeting a hard performance requirement, then yes, you should move the declaration outside of the loop.
This is unspeakably ugly, but you can do something like this:
do
{
  char *ptr = something;
  for (int i = 0; i < 1000; i++)
  {
    /* use ptr here */
  }
} while (0);

You're still limiting the scope of ptr, but you're no longer assigning it on every loop iteration.

A: It can make a performance difference, but many optimizing compilers undertake this optimization for you, if appropriate.  This is called "loop-invariant code motion".

A: The way that code gets translated really depends on your compiler and the optimizations it performs. The compiler might perform a "dumb" translation and allocate every loop, or it might place the allocation outside the loop for you in it's optimization phase. To be safe, I would place the declaration outside the loop. As with anything, you could test out both and see how long each loop takes to see if there is a difference.

A: You have to profile and see for yourself. Check out this question (and the accepted answer) of mine as a reference. As jalf says, it's just a rule of thumb to expect it to be optimized away (and it's probably correct for POD types) but you'll need to back it up with profiling.

A: As a matter of personal convention in 'C' programs, I like to put variable declarations at the top of the function, top of the file or in a common .h file.  If I start to bury declarations within the code it could potentially be confusing and easy to lose track of variable scope, resulting in unwanted consequences.

A: For built-in types such as the char* in your example, there isn't much difference.  The second form is usable after the loop exits, and only evaluates the initializer once.  But as John says, most compilers will precalculate the initialization anyway.
There's an obvious difference if ptr gets re-assigned inside the loop (and if you don't reassign it, you should make it char* const ptr), in that the value will be kept from the previous iteration instead of reset.
Finally, non-POD types would have their constructor and destructor run for every loop iteration.


text:
Q: $V\cap \Sigma$ homeomorphic to a disc
Let $X:U\subset\mathbb{R}^3\to\mathbb{R}^3$ a complete vector field of class $\mathscr{C}^k$($k\geqslant 1$), $p$ a regular point for $X$,$\varphi(t,p)$ a solution curve that goes through $p$ and $\Sigma$ a local cross -section of $X$ that passes through $p$. Assume that $\varphi(T,p)\in\Sigma$ for a $T>0$.
Show there exists a neighborhood $V$ of $p$ and a diffeomorphism  over $\pi$ such that for every $\Sigma_0=V\cap\Sigma$ is homeomorphic to a disc  and contains p, and $\pi(x)\in \Sigma$ is the first return of point x to the section $\Sigma$.

I think I could use the Flow box theorem so that it would give a diffeormphism let's say $\psi:V\to(-\epsilon,\epsilon)\times B$. However I am not sure and I do not know how to formalize that proof.
I am stuck at this problem as I do not have any idea on how to solve it.
Question:
How should I solve the problem?
Thanks in advance!


text:
Q: Openapi generator: how to import generated pom.xml Suppose I have a project, where I generate the Api, Model and pom.xml from an openapi spec with openapi-generator plugin in the pom.xml. Handily this plugin generates the pom.xml with all the necessary dependencies.

Question: how do I import the generated pom into my parent pom? (without installing my generated pom into a local repository?).
I have seen solutions such as copying those dependencies into the parent pom, which feels hacky.
There seems to be a similar question on stackoverflow. But the answer is not very clear...
I have tried importing the generated pom.xml via dependency management, but maven complains, that it cannot find the generated pom in the local repo.
Parent pom.xml:
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>${project.groupId}</groupId>
                <artifactId>generated_pom</artifactId>
                <type>pom</type>
                <version>1.0.6</version>
                <scope>import</scope>
            </dependency>

        </dependencies>
    </dependencyManagement>

Also: I know about the multi module approach, which requires me to setup a super pom.xml with packaging pom. This end up in three poms: generated, parent and super pom.xml. I would like to avoid that.
My Current pom.xml
    <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>org.acme</groupId>
    <artifactId>app</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>app</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>17</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jersey</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.openapitools</groupId>
                <artifactId>openapi-generator-maven-plugin</artifactId>
                <!-- RELEASE_VERSION -->
                <version>5.4.0</version>

                <!-- /RELEASE_VERSION -->
                <executions>
                    <execution>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                        <configuration>
                            <inputSpec>${project.basedir}/src/main/resources/api/petstore.json</inputSpec>
                            <generatorName>java</generatorName>
                            <configOptions>
                                <sourceFolder>src/java/main</sourceFolder>
                                <dateLibrary>java8</dateLibrary>
                                <library>resteasy</library>
                                <groupId>${project.groupId}</groupId>
                                <artifactId>petstore</artifactId>
                            </configOptions>
                            <output>${project.build.directory}/generated-sources</output>
                            <generateApis>true</generateApis>
                            <generateModels>true</generateModels>
                            <generateSupportingFiles>true</generateSupportingFiles>
                            <generateApiTests>false</generateApiTests>
                            <generateModelTests>false</generateModelTests>
                            <generateApiDocumentation>false</generateApiDocumentation>
                            <modelPackage>${project.groupId}.petstore.dto</modelPackage>
                            <apiPackage>${project.groupId}.petstore.api</apiPackage>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>


text:
Q: Extract the 0th frame of every second on a live video I have a command to extract the zero-th frame of every second. I got the command from here.
ffmpeg -i input.ts -vf "select=between(mod(n\, 25)\, 0\, 0), setpts=N/24/TB" output-%04d.png

But when I run the above command on live feed, it is extracting more than 100000 frames. The above command is not working on a live recording. Can anyone suggest or help me to extract the very first frame on a live recording? Thanks in advance.
P.S: For my testing I am running the above command on a tcr video.

A: Use
ffmpeg -i input.ts -vf "select='if(eq(n\,0),1,floor(t)-floor(prev_selected_t))'" -vsync 0 output-%04d.png

This will output the first frame of each second, if it exists.


text:
Q: Handling an adding new item event in Sitefinity dynamic module I'm working with Sitefinity CMS. I've created new dynamic module with Module Builder (for example Products). I would like to do some actions when I add new item to content Products. Is it possible to handle that event?
I will be very grateful to someone who will help with suggestions.

A: the most recent release of sitefinity contains some event hooks to which you can subscribe to do exactly this.
I'm still exploring this topic and some new docs should be out soon but in the meantime you want to be looking at the Telerik.Sitefinity.Services.EventHub.Subscribe(handler) where T is the type of event you want to subscribe to (Inheriting from IEvent), and handler is your event handler containing the code you wish to execute.
like I said more info is coming soon, but hopefully this will point you in the right direction in the meantime!
hope this is helpful!


text:
Q: Django: How do I pass a for variable into a querystring? I'm attempting to fix some pagination issues in a Django app. Using the Previous and Next buttons work fine, since I'm using existing variables like previous_page_number, but I'm unsure how to get the Page 1, Page 2, Page N buttons to work. Here's the Previous Page code, which works just fine:
{% if table.page and table.paginator.num_pages > 1 %}
    {% block pagination %}

        {% block pagination.previous %}
        {% if table.page.has_previous %}
            Previous
        {% else %}
            Previous
        {% endif %}
        {% endblock pagination.previous %}

And here's my current Pagination Range code, which doesn't. Specifically, the else segment is what I'm unable to get working.
{% block pagination.range %}
{% if table.page.has_previous or table.page.has_next %}

    {% for p in table.page|table_page_range:table.paginator %}
        {% if table.page.number == p %}

            {{ table.page.number }}

        {% else %}

            {{ p }}

       {% endif %}
   {% endfor %}

{% endif %}
{% endblock pagination.range %}

Currently, the pagination doesn't work, and the URL that gets passed ends at page= instead of page=p, whatever p is at the time. I'm uncertain how to pass p in as a readable variable, to cause it to appear in the URL. I've tried using the same format as other parts of the code not in the querystring.
{% else %}

    {{ p }}

{% endif %}

This causes an error that prevents the page loading at all, as Django can't reconcile the {{ part.

A: Display

and you can get from the views.py like that;
page = request.GET.get("page", ""),

if it is page is none you can give them default value like this
page = request.GET.get("page", "1")


text:
Q: How to validate if first array doesn't have value from second array by radio buttons with YUP I select first radio button to render first array of radio buttons with colors, select one of the colors, then I select second radio to render second array of radio buttons with colors. If my selected color from first array doesn't include of second array, how to show error?
CodeSandbox: https://codesandbox.io/s/focused-microservice-l4q3re?file=/src/App.tsx

import React, { useState } from "react";

import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";

export default function App() {
  const schema = yup.object().shape({
    choose: yup.string().typeError("select first or second").required(),
    color: yup
      .string()
      .typeError("selected color doesn't include of this array")
      .required("select color")
  });

  const {
    register,
    formState: { errors },

    handleSubmit
  } = useForm({
    resolver: yupResolver(schema)
  });

  const onSubmit = (data: any) => {
    console.log(data);
  };

  const onError = (error: any) => {
    console.log(error);
  };

  let colors = [
    ["black", "white", "pink"],
    ["black", "red", "blue"]
  ];
  const [select, setSelect] = useState<number>();

  return (
    <form onSubmit={handleSubmit(onSubmit, onError)}>

        <input
          type="radio"
          onClick={() => setSelect(0)}
          value={"first"}
          {...register("choose")}
        />
        first

        <input
          type="radio"
          onClick={() => setSelect(1)}
          value={"second"}
          {...register("choose")}
        />
        second

 {errors && errors.choose?.message}

        {select != null &&
          colors[select].map((color: any, i: number) => (

              <input
                type="radio"
                value={color}
                {...register("color")}
              />
              {color}

          ))}
        {select != null &&
 {errors && errors.color?.message}
}

      <button type="submit">Add</button>
    </form>
  );
}

A: The final code for App.tsx
Paste this in App.tsx in your given sandbox to see the result.
import React, { useState } from "react";

import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";

export default function App() {
  const schema = yup.object().shape({
    choose: yup.string().typeError("select first or second").required(),
    color: yup
      .string()
      .typeError("selected color doesn't include of this array")
      .required("select color")
  });

  const {
    register,
    formState: { errors },

    handleSubmit
  } = useForm({
    resolver: yupResolver(schema)
  });

  const onSubmit = (data: any) => {
    console.log(data);
  };

  const onError = (error: any) => {
    console.log(error);
  };

  let colors = [
    ["black", "white", "pink"],
    ["black", "red", "blue"]
  ];
  const [select, setSelect] = useState<number>();
  const [validationState, setValidationState] = useState<boolean>();

  const onClickChildRadio = (value: string) => {
    const secondArray:string[] = colors[1];
    const isExistInSecondArray = secondArray.includes(value);
    setValidationState(isExistInSecondArray);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit, onError)}>

        <input
          type="radio"
          onClick={() => setSelect(0)}
          value={"first"}
          {...register("choose")}
        />
        first

        <input
          type="radio"
          onClick={() => setSelect(1)}
          value={"second"}
          {...register("choose")}
        />
        second

 {errors && errors.choose?.message}

        {select != null &&
          colors[select].map((color: any, i: number) => (

              <input
                onClick={(e) => onClickChildRadio(e.target.value)}
                type="radio"
                value={color}
                {...register("color")}
              />
              {color}

          ))}
        {select != null &&
 {errors && errors.color?.message}
}

      <button type="submit">Add</button>

        Validate :
        {validationState
          ? "Value exist in second array"
          : "Value doesn't exist in second array"}

    </form>
  );
}


text:
Q: Counting with aggregate functions SQL I have a database with a table that holds all codes and a second table that holds codes that apply to data that can't be turned into primary key(hence a huge problem with it). Sometimes the codes are held in such a way "E1/D2/E3" in the comments section so multiple codes can appear in one comment
What I need is to get a list of codes of certain level and then use it with a LIKE statement to find a count of how many times each code exists in this particular database for example.
Count how many times each code exists in the codes column of the comments table. I've figured to get a list of Codes of this level and then I'm stuck with it. Please help
Code Table:
+----+-----------+-----+
|Code|Description|Level|
+----+-----------+-----+
|A1  |desc       |1    |
+----+-----------+-----+
|A2  |desc       |1    |
+----+-----------+-----+
|A3  |desc       |1    |
+----+-----------+-----+
|A4  |desc       |1    |
+----+-----------+-----+
|A1.1|desc       |2    |
+----+-----------+-----+
|A2.1|desc       |2    |
+----+-----------+-----+
|A3.1|desc       |2    |
+----+-----------+-----+
|A4.1|desc       |2    |
+----+-----------+-----+

Comments Table:
+-------------+----------+-------------+
|Comment      |Codes     |Location     |
+-------------+----------+-------------+
|Hello there  |A1/A1.1/A2|Somewhere    |
+-------------+----------+-------------+
|How are you  |A4/A7/B1.1|Long time ago|
+-------------+----------+-------------+
|My name is...|B1/B2/B3  |Somewhere    |
+-------------+----------+-------------+

Now what I need is to count the amount of times each code from level 1 occured in the comments section for each tuple.

A: If you mean how often each code appears in the codes column of the comments table:
select co.code, count(*)
from comments c join
     codes co
     on find_in_set(co.code, replace(c.codes, '/', ',')) > 0 and
        co.level = 1
group by co.code;

EDIT:
You can also express this using like:
select co.code, count(*)
from comments c join
     codes co
     on concat('/', c.codes, '/') like concat('%/', co.code, '/%')
        co.level = 1
group by co.code;

Note that appending of delimiters at the beginning and end to ensure full matches.


text:
Q: can't delete a row from post_meta table I have checkbox in my post and I want to delete a database row when checkbox is not checked but when I press update button nothing happend and the row wasn't deleted.
here is my codes
if (isset($_POST['save-author-to-book'])) {
        $key = 'save-author-to-book';
        $values_to_save = array();
        $new_values = $_POST["save-author-to-book"];
        $existing_values = get_post_meta( $post_id, $key, true ) ;

        if(!empty($new_values)){
            foreach($new_values as $new_value ){
            $values_to_save[] = $new_value ;

            }
         update_post_meta( $post_id, $key, $values_to_save );
        }

    }
    else{

        delete_post_meta( $post_id, $key, $meta_value='');
        // break;

    }

any idea would be appreciated.

A: This is because the value of meta key is inside the if clause and is not set for the else.
try
else {
        $key = 'save-author-to-book';
        delete_post_meta( $post_id, $key, $meta_value='');
        // break;

    }


text:
Q: Read content inside json file php I have a webservice that return me this JSON file:
{"success":true,"msg":"[{\"inCarico\":\"1\",\"a\":\"2007-01-12 00:00:00\",\"b\":\"\",\"cd\":\"\",\"ef\":\"\",\"IdL\":\"0\",\"IdM\":\"0\"}]"}

Now I am using this code to decode json and get the msg content, but I want to decode every voice (carico, a, b, IdL...) in the "msg" voice.
$url = 'http://......';
$obj = json_decode(file_get_contents($url), true);
echo $obj['msg'];

How can I do this?

A: You have to use json decode two time.
$json = '{"success":true,"msg":"[{\\"inCarico\\":\\"1\\",\\"a\\":\\"2007-01-12 00:00:00\\",\\"b\\":\\"\\",\\"cd\\":\\"\\",\\"ef\\":\\"\\",\\"IdL\\":\\"0\\",\\"IdM\\":\\"0\\"}]"}';
$result = json_decode ($json, true);

$arr = json_decode ($result['msg'], true);
print_r($arr);

Result:
Array
(
    [0] => Array
        (
            [inCarico] => 1
            [a] => 2007-01-12 00:00:00
            [b] =>
            [cd] =>
            [ef] =>
            [IdL] => 0
            [IdM] => 0
        )

)

Please notify me what can i do for you now?


text:
Q: problem installin vala 0.15.0 Gobobject not found /gir/bug651773: FAIL
error: Package `GLib-2.0' not found in specified Vala API directories or GObject-Introspection GIR directories
error: Package `GObject-2.0' not found in specified Vala API directories or GObject-Introspection GIR directories
Generation failed: 2 error(s), 0 warning(s)
1 of 145 tests failed
make[4]: *** [check-TESTS] Error 1
make[4]: Leaving directory `/home/suman/Downloads/vala-0.15.0/tests'
make[3]: *** [check-am] Error 2
make[3]: Leaving directory `/home/suman/Downloads/vala-0.15.0/tests'
make[2]: *** [check] Error 2
make[2]: Leaving directory `/home/suman/Downloads/vala-0.15.0/tests'
make[1]: *** [check-recursive] Error 1
make[1]: Leaving directory `/home/suman/Downloads/vala-0.15.0'
make: *** [check] Error 2

A: 0.15.0 isn't just old, it's an unstable development release.  There is no reason for anyone to be using it.  0.22.0 is out, and there aren't any dependencies on newer software which should cause problems (IIRC our only real dependency is on glib >= 2.18 and I don't think that is any different than vala-0.15), so you should probably be using it.
If, for some reason, you need an older version of Vala then you should use a stable release.  If you can't build it post a complete log.  Also, running the unit tests aren't a requirement for installation.  If the problem only manifests itself when trying to run the unit tests, don't run them.  Nobody is going to bother backporting fixes to 0.15 or 0.16, so there isn't really much of a point.


text:
Q: Animated semicircles in logo with SVG I would like to make this graphic in SVG. I can use <animate> tags and I can manipulate the SVG document with javascript. I would prefer to do it all in SVG if possible.

A: Here's a simpler example:
<svg height="200" width="200" viewBox="0 0 144 144">
    <circle cx="72" cy="72" r="49" stroke-width="6" stroke="#F68524" fill="none"/>
    <circle cx="72" cy="72" r="49"
        stroke-width="6" stroke="#838588" fill="none">
        <animate attributeName="stroke-dasharray" values="154 0;0 154" dur="1s" repeatCount="indefinite"/>
    </circle>
</svg>

The proper values to use for the stroke-dasharray are based on the circle's circumference, 2 * π * r, and we want half of that so divide it by 2. In the example that computes to roughly 154.
See jsfiddle.
Update:
Pretty close, but not quite the same, as noted. Here's a version that also animates the colors:
<svg height="200" width="200" viewBox="0 0 144 144">
    <circle cx="72" cy="72" r="49" stroke-width="6" stroke="#F68524" fill="none">
        <animate attributeName="stroke" values="#838588;#F68524"
                 dur="2s" calcMode="discrete" repeatCount="indefinite"/>
    </circle>
    <circle cx="72" cy="72" r="49"
        stroke-width="6" stroke="#838588" fill="none">
        <animate attributeName="stroke-dasharray" values="154 0;0 154"
                 dur="1s" repeatCount="indefinite"/>
        <animate attributeName="stroke" values="#F68524;#838588"
                 dur="2s" calcMode="discrete" repeatCount="indefinite"/>
    </circle>
</svg>

See jsfiddle.

A: This is just an idea for a starting point. You can then apply masks to hide and show parts of the graphic.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
    <circle cx="200" cy="200" r="100" fill="gray"/>
    <rect x="100" y="200" height="101" width="201" fill="white">
        <animateTransform attributeName="transform"
            attributeType="XML"
            type="rotate"
            from="0 200 200"
            to="360 200 200"
            dur="5s"
            repeatCount="indefinite"/>
    </rect>
    <circle cx="200" cy="200" r="90" fill="white"/>
</svg>

A: Huge thanks to @helderdarocha to pointing me in the right direction.
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     width="144px" height="144px" viewBox="0 0 144 144" enable-background="new 0 0 144 144">

    <defs>
        <clipPath id="rotation-top" clip-path="url(#top-half)">
            <rect x="0" y="72" height="72" width="144">
                <animateTransform attributeName="transform"
                    attributeType="XML"
                    type="rotate"
                    from="360 72 72"
                    to="0 72 72"
                    dur="3s"
                    repeatCount="indefinite">
                </animateTransform>
            </rect>
        </clipPath>
        <clipPath id="rotation-bottom" clip-path="url(#bottom-half)">
            <rect x="0" y="0" height="72" width="144">
                <animateTransform attributeName="transform"
                    attributeType="XML"
                    type="rotate"
                    from="360 72 72"
                    to="0 72 72"
                    dur="3s"
                    repeatCount="indefinite">
                </animateTransform>
            </rect>
        </clipPath>
        <clipPath id="top-half">
            <rect x="0" y="0" height="72" width="144">
            </rect>
        </clipPath>
        <clipPath id="bottom-half">
            <rect x="0" y="72" height="72" width="144">
            </rect>
        </clipPath>
    </defs>

    <!-- background white -->
    <circle opacity="0.56" fill="#FFFFFF" cx="72" cy="72" r="72"/>

    <!-- back gray color -->
    <circle cx="72" cy="72" r="49" stroke-width="6" stroke="#838588" fill-opacity="0.0"/>

    <!-- foreground orange color -->
    <circle
        cx="72" cy="72" r="49"
        stroke-width="6" stroke="#F68524" fill-opacity="0.0"
        clip-path="url(#rotation-bottom)"
    />

    <circle
        cx="72" cy="72" r="49"
        stroke-width="6" stroke="#F68524" fill-opacity="0.0"
        clip-path="url(#rotation-top)"
    />

</svg>

A: For cross-browser animation it is better to use Javascript. (IE doesn't support SMIL). setInterval is quite robust in all browsers.
For instance, to continously rotate an element, you would use:
function basicRotate()
{
    var FPS=100  //----frames per second---
    var angle = 0//---starting value---
    function frame()
    {
        angle++
        myElement.setAttribute("transform","rotate("+angle+" "+centetX+" "+centerY+")")
        if (angle == 360)
        angle=0
    }
    //---start interval timer---
    var iT = setInterval(frame, 1000/FPS ) //---draw every 10ms ---
}


text:
Q: C++ : Connecting a member of a class to its definition I'm new to C++, I have more experience in OCaml and Python. I want to learn C++ by making a program playing "Morpion Solitaire". My beginnings are a bit difficult.
In the following code :
typedef enum {NORTH, NORTHEAST, EAST, SOUTHEAST} direction;

char deltax[4] = { 0, 1, 1, 1};
char deltay[4] = { 1, 1, 0, -1};

class Coords {
 private:
  char x,y;

 public:
  Coords(char xx,char yy){
    x = xx;
    y = yy;
  };

  char get_x() const { return x;}

  char get_y() const { return y;}
};

class Line {
 private:
  Coords orig;
  direction dir;
  Coords newcross;

 public:
  Line(char x1, char y1, direction d, char x2, char y2) {
    orig = Coords(x1,y1);
    dir = d;
    newcross = Coords(x2,y2);
  };

  Coords nthpoint(char n) {
    char x,y;

    x = orig.get_x() + n*deltax[dir];
    y = orig.get_y() + n*deltay[dir];

    return Coords(x,y);
  };
};

the compiler tells me this :
nico@gaston:~/Travail/Cplusplus/morpion++$ g++ -c morpion.cc
morpion.cc: In constructor 'Line::Line(char, char, direction, char, char)':
morpion.cc:29:57: error: no matching function for call to 'Coords::Coords()'
   Line(char x1, char y1, direction d, char x2, char y2) {
                                                         ^
morpion.cc:29:57: note: candidates are:
morpion.cc:11:3: note: Coords::Coords(char, char)
   Coords(char xx,char yy){
   ^
morpion.cc:11:3: note:   candidate expects 2 arguments, 0 provided
morpion.cc:6:7: note: Coords::Coords(const Coords&)

I don't understand the message. I have given a 2 argument constructor for class Coords, but the compiler keeps telling me that orig = Coords(x1,y1) calls the constructor with 0 arguments.
What did I miss ?
Remark : I initially put the declarations of Coords and Line in different files, and thought I did not use the proper #include, but putting everything in one single file didn't solve the problem...

A: Line(char x1, char y1, direction d, char x2, char y2)
  : orig(x1,y1), dir(d), newcross(x2, y2) {}

Coords doesn't have a default constructor. Your original code attempts to first default-construct orig, then assign a new value to it. But for lack of that default constructor, the first step fails.

A: The problem you are having is that all class members and basses must be constructed before entering the constructor body.  Because of that what your constructor actually looks like after having the implicit constructions added by the compiler is
Line(char x1, char y1, direction d, char x2, char y2): orig(), dir(), newcross() {
    orig = Coords(x1,y1); // this is assignment not construction
    dir = d; // this is assignment not construction
    newcross = Coords(x2,y2); // this is assignment not construction
};

This is not a problem for dir since it can be implicitly constructed but Coords is not so orig() and newcross() fails.
To fix this you need to use the member initialization list and have a constructor like
Line(char x1, char y1, direction d, char x2, char y2) : orig(x1, y1), newcross(x2, y2), dir(d) {}

A: TL;DR: the fix:
Line(char x1, char y1, direction d, char x2, char y2) :
    orig(x1, y1), newcross(x2, y2), dir(d)
{
};

The constructor of class Line is to call constructors of all members of this class, and does this prior to the execution of constructor body. That is, the member orig should be constructed before line
orig = Coords(x1,y1);

execution. By default, the default constructor is called, but in your case the class Coords has no default constructor. When we write orig(x1, y1), we override the default, and the constructor Coords(x1, y1) is called to construct orig.


text:
Q: row level comparison of two tables Hi I have a two tables like this.
source table
orig1 orig2 orig3 xref1 xref2 xref3
1      1     1     2     2     2
1      1     1     3     3     3
23    23    23     12   12    12

target table:
orig1 orig2 orig3 xref1 xref2 xref3  version
1      1     1     1     1      1       0

I need output as follows
1) I need to match (source(orig1 orig2 orig3) == target(orig1 orig2 orig3)),
if its macthing we need to append from source to target table by increment the version by 1
if its not matching, just append version as '0'
expected output is:
orig1 orig2 orig3 xref1 xref2 xref3  version
1      1     1     1     1      1       0
1      1     1     2     2      2       1
1      1     1     3     3      3       2
23    23    23     12   12     12       0

I tried with data frame level. But it is not working as expected. Any help would be appreciated.
I tried the following way.
val source = spark.sql("select xref1,xref2,xref3,orig1,orig2,orig3 from default.source")
val target = spark.sql("select xref1,xref2,xref3,orig1,orig2,orig3 from default.target")
val target10 = spark.sql("select xref1,xref2,xref3,orig1,orig2,orig3,version from default.target")
val diff=( source.select("xref1","xref2","xref3","orig1","orig2","orig3") == target.select("xref1","xref2","xref3","orig1","orig2","orig3"))
if  ( diff == false ){
  val diff1 = source.select("orig1","orig2","orig3").except(target.select("orig1","orig2","orig3"))
  if (  diff1.count > 0 ) {
   val ver = target10.groupBy("orig1","orig2","orig3").max("version")
   val common = source.select("orig1","orig2","orig3").intersect(target.select("orig1","orig2","orig3"))
   val result = common.join(ver, common("orig1") === ver("orig1") && common("orig2") === ver("orig2") && common("orig3") === ver("orig3"), "inner").select(ver("orig1"),ver("orig2"),ver("orig3"),(ver("max(version)") + 1
) as "version")
    val result1 = result.join(source, result("orig1") === source("orig1") && result("orig2") === source("orig2") && result("orig3") === source("orig3"), "inner").select(source("orig1"),source("orig2"),source("orig3"),result("version"),source("xref1"),source("xref2"),source("xref3"))
  val result2=source.select("orig1","orig2","orig3").except(target.select("orig1","orig2","orig3")).withColumn("version",lit(0))
  val execpettarget=result2.select($"orig1".alias("DIV"),$"orig2".alias("SEC"),$"orig3".alias("UN"),$"version".alias("VER"))
  val result23 = execpettarget.join(source, execpettarget("DIV") === source("orig1") && execpettarget("SEC") === source("orig2") && execpettarget("UN") === source("orig3"), "inner").select(source("orig1"),source("orig2"),source("orig3"),execpettarget("VER"),source("orig1"),source("orig2"),   source("orig3"))
   val final_result = result1.union(result23)
   final_result.show()
}else{
println("else")
val ver1 = target10.groupBy("orig1","orig2","orig3").max("version")
val common1 = source.select("orig1","orig2","orig3").intersect(target.select("orig1","orig2","orig3"))
val result11 = common1.join(ver1, common1("orig1") === ver1("orig1") && common1("orig2") === ver1("orig2") && common1("orig3") === ver1("orig3"), "inner").select(ver1("orig1"),ver1("orig2"),ver1("orig3"),(ver1("max(version)") + 1) as "version")
val result3 = result11.join(source, result11("orig1") === source("orig1") && result11("orig2") === source("orig2") && result11("orig3") === source("orig3"), "inner").select(source("orig1"),source("orig2"),source("orig3"),result11("version"),source("xref1"),source("xref2"),source("xref3"))
result3.show()
}}

But in the final join the source has 2 duplicate rows. So when joining source with target I am getting multiple rows.

A: I didn't try to decipher your code, but based on source, target & expected result I would thing this could be a solution:
val w = Window.partitionBy('orig1,'orig2,'orig3).orderBy('version.desc)

val joined = source
  .withColumn("version", lit(null).cast(IntegerType))
  .union(target)
  .withColumn("version", row_number().over(w) + coalesce(max('version).over(w),lit(0)) - lit(1))

joined.show()

My idea was that a join doesn't make sense, because you want to end up with # records from source + # records from target: => union
After this union you want to process each group of similar keys (orig1, orig2, orig3) => Window
You care about the highest version number in the group, otherwise pick 0: => max & coalesce
You want to use this max as offet for a ranking of the rest of the window: => row_number
Based on the example this code will output:
+-----+-----+-----+-----+-----+-----+-------+
|orig1|orig2|orig3|xref1|xref2|xref3|version|
+-----+-----+-----+-----+-----+-----+-------+
|   23|   23|   23|   12|   12|   12|      0|
|    1|    1|    1|    1|    1|    1|      0|
|    1|    1|    1|    2|    2|    2|      1|
|    1|    1|    1|    3|    3|    3|      2|
+-----+-----+-----+-----+-----+-----+-------+


text:
Q: Creating an autokey cipher function Can someone help me with putting what I can say in words into code.
I want to create autokey encrypt and decrypt functions (just wanting help encrypting and then can figure out decrypting). Everything is in Z 26.
The function would begin like:
autokeyEncrypt(x_, key_) :=

x is plaintext (e.g. rendezvous) and k is the key (e.g. 8), I first would need to convert the plaintext into a sequence of integers. I have a function to do this already that is used like:
stringToNumbers[x]

this would give
{17, 4, 13, 3, 4, 25, 21, 14, 20, 18}

Call this list xlist. The keystream then would be
{8, 17, 4, 13, 3, 4, 25, 21, 14, 20}

That is, the key argument prepended to xlist. Now form xlist[[i]] + keystrean[[i]] , reducing mod 26, and the resulting ciphertext (as numbers then letters) would be:
{25, 21, 17, 15, 7, 3, 20, 9, 8, 12}
ZVRQHDUJIM

I am familiar with java and wondering if there is a way to accomplish something with the structure similiar to
autokeyEncrypt(x, key) {
   x = stringToNumbers(x)
   create list with just the key in it
   loop to take numbers from x and fill list (until reaches specific length)
   etc

A: Here is an implementation that reads almost like a literal translation of the problem statement:
stringToNumbers[x_] := ToCharacterCode @ ToUpperCase @ x - 65

autokeyEncrypt[x_String, key_Integer] :=
  Module[{xlist, keystream}
  , xlist = stringToNumbers[x]
  ; keystream = Most @ Prepend[xlist, key]
  ; FromCharacterCode[Mod[xlist + keystream, 26] + 65]
  ]

autokeyEncrypt["rendezvous", 8]
(* "ZVRQHDUJIM" *)


text:
Q: choosing which main() to use in the Makefile In a C project, I have a main() function in several files. When I compile I thus have an error "multiple declarations of main". Is it possible to choose in the Makefile which one of those main() functions should be used to compile ? (the other ones would then be ignored...)

A: You could hide them using the pre-processor:
In file1.c:
#if defined FILE1_MAIN
int main(void)
{
  printf("Running main() in file1.c");
  return 0;
}
#endif

This can be repeated as necessary in any number of C files.
Then have logic in the Makefile that passes the proper -D option to the compiler, i.e. -DFILE1_MAIN to include the main() from file1, -DFILE2_MAIN to get file2.c's, and so on.
This technique can also be useful when implementing e.g. library modules, to include an optional main() for testing in a single C file.

A: You could simply write a target for each main(), where you would ignore all but one file which contains main().

A: You only may have one main() function in your source. You'll have either to rename all of the other instances, or to exclude those source files that include other instances of main() from the build.


text:
Q: how to get all the data from row of parse.com databrowser in android? I have a class on parse.com named "MQOD" ,it is having several coloumns,I want to get DeviceId List and check it with my device it,And If that array contais my deviceId,I want to get all data from that row.My table in parse.com is as below,

I have tried as below,Which gives me size of array,But I dont know how to check in that array for my deviceId,and get that row's data.
code
ParseQuery<ParseObject> query = ParseQuery.getQuery("MQOD");
        query.whereExists("DeviceId");
        query.findInBackground(new FindCallback<ParseObject>() {
            public void done(List<ParseObject> ClientList, ParseException e) {
                if (e == null) {
                    Log.d("DeviceId", "Retrieved " + ClientList.size()
                            + " DeviceId");
                    System.out
                            .println("::::::::::::::::::MY arrayList:::::::::::::from Parsde.::::::::::::::::"
                                    + ClientList.toString());
                    Log.d("Installation date", "Retrieved "
                            + ClientList.get(1).get("InstalationDate")
                            + " DeviceId");
                } else {
                    Log.d("score", "Error: " + e.getMessage());
                }
            }
        });

A: I have got answer,I have changed my code as below,And I solved my Problem
code
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("MQOD");
        // query.orderByDescending("createdAt");
        query.whereEqualTo("DeviceId", android_id);
        // query.toString();
        System.out.println("::::::::::::::::::QUERY:::::::::::::::" + query);
        try {
            ob = query.find();
        } catch (ParseException e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        if (ob.size() > 0) {
            // IS INSTALLED ON DEVICE..!!!
            for (ParseObject mediObject : ob) {
                Const.DeviceId = mediObject.get("DeviceId").toString();
                Const.InstDate = mediObject.get("InstallationDate").toString();
                Const.UpDate = mediObject.get("NextSubscription").toString();

            }
}catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }