text:
Q: SyntaxError on import with matplotlib This code is giving me a SyntaxError. Not sure what is wrong.
import numpy as np
from matplotlib.pyplot as plt

x = np.linspace(0., 10, 0.1)
y = np.sin(x)
plt.plot(x, y);
plt.show();

This is the error message:
  File "<ipython-input-4-b3d93c2fbfde>", line 2
    from matplotlib.pyplot as plt
                            ^
SyntaxError: invalid syntax

A: Your second line should be:
import matplotlib.pyplot as plt

In addition, note that you don't need a semi-colon terminator in Python.
Also, the np.linspace call that you use is wrong - it'll just give you an empty array.  Try the following instead:
x = np.linspace(0, 10, num=101)


text:
Q: Vue.js app works in development but not mounting template in production with Rails 5.2.0 / Webpacker - blank screen with no errors in console I'm using Rails 5.2.0 and Webpacker gem to deploy a Vue application.
The show.html.erb file is very simple:

<MyComponent></MyComponent>

And then in my entry pack, packs/my_vue_app.js:
import TurbolinksAdapter from 'vue-turbolinks';
import Vue from 'vue/dist/vue.esm'
Vue.use(TurbolinksAdapter);
import MyComponent from '../components/my_app/index.vue'

document.addEventListener('turbolinks:load', () => {

  var element = $('[data-behavior="vue-app"]');

  if(!element) { return };

  console.log('Initializing Vue');

  const app = new Vue({
    el: element[0],
    data: {

    },
    components: { MyComponent }
  })
})

In development, everything works absolutely fine. The app is mounted and functional.
But in production, after the page load and JS runs,
 is removed from the paging, leaving only  in it's place.
In the console, there are absolutely no errors. I can confirm using DevTools that the pack js file is loaded, and it was parsed, since the console.log is printed in the console.
Heck, the proof that Vue is working is that the entire
 where it was mounted was removed from DOM after JS parsing.
The weirdest thing of all is that I could get the app to mount ONCE, by attaching a debugger on the console.log line and turning it off while the debugger paused execution. Even tough I saw the app mounting that time, I could not get it to mount later on, even fiddling with the debugger again ... it's really, really weird.
These are the versions of package.json:

"vue": "^2.5.16",
"vue-loader": "14.2.2",
"vue-template-compiler": "^2.5.16",

The Rails app is brand new, with no config other than the default.
Webpacker gem is 3.5.3 and Rails is 5.2.0.
After spending a really long time on this, I only found this github issue: https://github.com/rails/webpacker/issues/1520
EDIT: I'm providing a link to the real, production app where this bug is happening: https://planilha.tramitacaointeligente.com.br/planilhas/ED2sUXz32-R9CJKdkmtf8Q
You'll see it's not mounting. Here's the same page in development:

A: I eventually managed to solve it by changing how the Vue app loading was defined.
Try import Vue from 'vue' (instead of from 'vue/dist/vue.esm') and then:
const app = new Vue({
    el: domElement,
    render: h => h(RootComponent)
  })

The comments that appear in the hello_vue.js scaffold from the Webpacker gem tell you that you can choose between using the DOM as your template OR load the component with a render function; they both do work in development, but only the latter (loading the component with a render function, using vue instead of vue/dist/vue.esm and render: h => h(RootComponent) worked for me in production.
This has been, by far, the longest, most frustrating debugging session of my life, since there are absolutely no errors in console, you just stare into a blank screen, and Vue is running since it removes the DOM element it was mounted to from the DOM.
Source of solution: https://stackoverflow.com/a/48651338/1290457 and here's the github issue (currently open) on Webpacker gem https://github.com/rails/webpacker/issues/1520
I still don't know how to use DOM as template with Vue in production tough.

A: I had similar problem in Rails 5.2 + webpack Vue. All was good in development, but not working in production. After hours of investigating I found the reason. It was in this recommendation from  webpaker gem docs.
Adding this
Rails.application.config.content_security_policy do |policy|
  if Rails.env.development?
    policy.script_src :self, :https, :unsafe_eval
  else
    policy.script_src :self, :https
  end
end

brokes production. Removing else part - fixing the situation.
Chrome silently ignoring this. Firefox shows warnings.

redpajama_set_name: RedPajamaStackExchange


text:
Q: HashMap not modifiying object contents I have a hashmap in which i am putting a reference to an object.
     DateTest test100 = new DateTest("ABC",100);
     dateTestMap.put(96, test100);

I am passing this reference variable to a method where i am assigning it a different object and after returning i am pointing the existing reference to the new object as follows:
    test100 = datePassingTest(test100);

    private DateTest datePassingTest(DateTest test100)
    {
        DateTest newTest = new DateTest("XYZ", 69);
        test100 = newTest;
        return test100;
    }

Well, test100 does get modified to point to the new object but the value stored in map isn't getting updated. Is there something i am missing ?
Thanks,
Adithya

A: That is because test100 is not holding the reference of the object which was created using this new DateTest("ABC",100);. It now points to the object created by this new DateTest("XYZ", 69);.
If you had done something like test100.setSomething(150), then the change would have been reflected in the map. In this case, it won't as the test100 now refers a completely different object.

A: When you do
test100 = newTest

The only thing that is done is that test100 now references the same object as newTest. The object referenced by the original value of test100 is still present but only in the hashmap.
To do what you want, you should try
test100.setTime(newTest.getTime());

A: DateTest test100 = new DateTest("ABC",100);
dateTestMap.put(96, test100);

Here a copy of reference (of test100) goes and sits into the dateTestMap which points to DateTest("ABC",100). Now a HashMap dateTestMap contains a new reference which points to the same object DateTest("ABC",100)
So it can be depicted something like this

Now when you do
test100 = datePassingTest(test100);

The outer test100 will point to new DateTest("XYZ", 69), but the copy reference present in dateTestMap still points to same DateTest("ABC",100) object.

Java is pass by value - which essentially means passing the copy of reference

A: Thats because, you're putting the object inside the map and then modifying the object. Thus, the map would still hold the old object
 DateTest test100 = new DateTest("ABC",100);
 dateTestMap.put(96, test100);           // entry/object added to map

 test100 = datePassingTest(test100);     // object updated

 dateTestMap.put(96, test100);           // map gets new object

// now the map contains the updated object but not the older one.

A: You are not modifying the object. You are just assigning.
Clear explanation in Language Specification JLS#4.301,

If two variables contain references to the same object, the state of the object can be modified using one variable's reference to the object, and then the altered state can be observed through the reference in the other variable.


text:
Q: Render each of multiple objects in array with Express in Node.js I have multiple objects in array of locals in my routes and would like to render each at the time.
Example
// routes.js

const routes = {
  path: '/posts/:id',
  view: 'posts',
  locals: [
    {
      id: 'how-to-write-short',
      title: 'How to write short',
      description: 'The art of painting a thousand pictures with just a few words',
      date: '23 Mar 2018',
      issue: '1'
    },
    {
      id: 'the-glamour-of-grammar',
      title: 'The glamour of grammar',
      description: 'A guide to the magic and mystery of practical English',
      date: '01 April 2018',
      issue: '2'
    }
  ]
}

Right now, this renders the last objects in array when I visit either link http://localhost:3000/posts/how-to-write-short or http://localhost:3000/posts/the-glamour-of-grammar.
// server.js

const express = require('express')
const routes = require('./routes')

const app = express()

app.set('views', 'src/pages')
app.set('view engine', 'js')
app.engine('js', require('./engine'))

app.get(routes.path, function(req, res) {
    res.render(routes.view, routes.locals)
})

app.listen(3000)

What's a better to render each e.g routes.locals[0], routes.locals[1], and ...?

A: The optimal way is search the post id and pass it to the render:
app.get(routes.path, (req, res) => {
  const id = req.params.id;
  const post = routes.locals.find(p => p.id === id);
  if (post) {
    res.render(routes.view, post);
  } else {
    res.render(routes.post_not_found_view);
  }
});

A: You could do the following:
In your code
app.get(routes.path, function(req, res) {
    res.render(routes.view, routes.locals)
})

take from req the id and pass it to the res.render. Then you should select only the local that you are interested in and this should do the trick.
app.get(routes.path, function(req, res) {
    const id = req.params.id;
    const local = routes.locals.filter(local => local.id === id)
    res.render(routes.view, local)
})

Hope this will help you.


text:
Q: Iterative Control Flow in Subshelled Script I have a shell script(A) that is being called by another script(B).
In this script(A) I am creating some directories and moving some files as preparatory work for the rest of the script to work fine. Script(A) is called upon by script(B) in an iterative manner, I only want the creating of directories and moving of files to occur only once i.e during the very first loop.
What can I do to execute a part of my script only once?

A: There are several ways to pass this information from the calling script to the called script. One is to use a parameter (./script --init vs. ./script) or a parameter value (./script --init=0 vs. ./script --init=1). I guess the most simple method is to use an environment variable:
script B:
init=0
while whatever; do INIT=$((init++)) ./script_A; done

script A:
[...]
if [ 0 -eq "$INIT" ]; then
  : make preparations
fi
[...]

If script A shall be able to run without being called from script B then the missing variable must be handled (before the if statement, of course):
: ${INIT:=1}

A: You need some relatively unique quality of the environment upon which to rely. This is not easy to come by - especially if you are calling a separate script iteratively in a loop and expect it to behave differently for each occurrence (why not portions of the same script in that case?).
Anyway, the common thing to do is to use a lockfile - or something like it - for these kinds of things. In order to do this though, you do need that unique bit of environment. Consider the following:
sh -c 'echo "$PPID" "$$"
       for i in 1 2 3 4 5
       do sh -c "echo \"\$PPID\""
       done'

OUTPUT
25711 28929
28929
28929
28929
28929
28929

If you can rely on the caller providing its pid to you in the environment variable $PPID it may be just what you need. For example:
#!/bin/sh
#script a
LOCKDIR=${TMPDIR:-/tmp}/${0##*/}.$PPID

init() { mkdir "$LOCKDIR" || exit
#        do other initialization tasks
}

loop() { : do the iterable tasks here; }

[ -d "$LOCKDIR" ] || init
loop

...and...
#!/bin/sh
#script b
a='/path/to/script/a'
for stuff in $things
do "$a" "$stuff"
done
rm -rf "${TMPDIR:-/tmp}/${a##*/}.$$"

Seriously, though, I haven't encountered many situations at all in which doing this kind of thing is a good idea - if I am calling another shell-script iteratively and I must rely upon its environment then I would probably . source the script's contents into the current shell and run it that way. I would do this, that is, if I was very sure the script I was running was securely written.

A: I have created a trigger text file, I am using the number of line count as the trigger for my if statement, then inside the if statement I am editing the text file to add more lines in it. That way the if statement will only be triggered once through whatever iterations. It is solved by a very simple code.
touch Trigger.txt
n=$(wc -l > Trigger.txt
fi


text:
Q: "We found an issue in the following area(s): Title" in google play console I can't understand how to fix the app rejected problems, after rename the app Name then also it shows the same problem.
can anyone help me out of this problem.

A: Maybe due to Misleading text your app is rejected
reference to google play policy


text:
Q: MQTT - Mosquitto Bridge not sending messages I've got a pretty basic two node mosquitto setup.  One of the machines is behind a firewall not accepting incoming connections, but I can send information out.  I've not implemented SSL or an ACL yet.  Trying to keep this verry simple right now.  Anyway, the machine behind the firewall is getting messages from some Pi's then sending it to the local broker.  Another local application is connecting to that machine over websockets.  I need to have these messages published to another broker outside the firewall.
I'm seeing the firewalled broker connecting to the external one, but I am unable to see any messages.  Further more, I need to have the devices behind the firewall continue to receive messages from the local broker.
The following is my bridge config
connection bridge
address hostname-to-external-mqtt
topic both 0 #
bridge_attempt_unsubscribe false
local_clientid local
remote_clientid remote
start_type automatic
try_private false
cleansession true

The following is the verbose output from my the firewalled machine that needs to duplicate the messages on the remote machine
mosquitto -c ./mosquitto.conf -v
1441942973: mosquitto version 1.4.2 (build date 2015-07-02 21:31:17-0400) starting
1441942973: Config loaded from ./mosquitto.conf.
1441942973: Opening ipv4 listen socket on port 1883.
1441942973: Opening ipv6 listen socket on port 1883.
1441942973: Opening websockets listen socket on port 9001.
1441942973: Bridge local doing local SUBSCRIBE on topic NODE-1/
1441942973: Connecting bridge bridge (remotehost:1883)
1441942973: Bridge remote sending CONNECT
1441942973: Received CONNACK on connection local.
1441942973: Bridge local sending SUBSCRIBE (Mid: 2, Topic: NODE-1/, QoS: 0)
1441942973: Received PUBACK from local (Mid: 1)
1441942973: Received SUBACK from local
1441942974: New connection from 192.168.1.18 on port 1883.
1441942974: New client connected from 192.168.1.18 as paho/AE8E0FF0F7A0180A22 (c1, k60).
1441942974: Sending CONNACK to paho/AE8E0FF0F7A0180A22 (0, 0)
1441942974: New connection from 192.168.1.3 on port 1883.
1441942974: New client connected from 192.168.1.3 as paho/9EE5A8894DD7E6EDC3 (c1, k60).
1441942974: Sending CONNACK to paho/9EE5A8894DD7E6EDC3 (0, 0)

And the following is the the verbose output from the remote machine
1441943193: New connection from firewalled-ip on port 1883.
1441943193: New client connected from firewalled-ip as local (c1, k60).
1441943193: Sending CONNACK to local (0, 0)
1441943193: Received PUBLISH from local (d0, q1, r1, m1, '$SYS/broker/connection/local/state', ... (1 bytes))
1441943193: Sending PUBACK to local (Mid: 1)
1441943194: Received SUBSCRIBE from local
1441943194:     NODE-1/ (QoS 0)
1441943194: local 0 NODE-1/
1441943194: Sending SUBACK to local

Can anyone help point me in the right direction please?

A: It doesn't look like the config you posted and the logs match.
Config states:
topic both 0 #

Yet the log shows:
1441943194: Received SUBSCRIBE from local
1441943194:     NODE-1/ (QoS 0)

It should be subscribing to # instead of NODE-1/.
Could you check that you are using the config that you think?


text:
Q: factorization in python this code is working fine. say for 1980 it gives the result 2 ^ 2 *3 ^ 2 *5 ^ 1 *7 ^ 0 *11 ^ 1 *(an extra asterisk remains at the end. i can remove it. and that has nothing to with my problem.
the code is:
prime=[2,3,5]
f=7
def next_prime(f):
    j=0
    while j==0:
        for x in prime:
            if f%x==0:
                f+=2
                break
        else:
            j=1
    return f;
def factorization(n):
    list=[2,3,5]
    power=[]
    x=0
    while x<len(list):
        j=0
        while n%list[x]==0:
            j+=1
            n=n/list[x]
        power.append(j)
        x+=1
    if n!=1:
        while n!=1:
            g=next_prime(f)
            j=0
            while n%g==0:
                j+=1
                n=n/g
            else:
                power.append(j)
                prime.append(g)
    x=0
    while x<len(power):
        print(prime[x],"^",power[x],"*",end="")
        x+=1

factorization(1980)

then if i want to remove the term 7 ^ 0 from the result therefore all the primes which have the power zero, i made change in line 31 (if j!=0: instead of else:). and then the code's not working. it's working for numbers like 13860 where no prime has the power zero not in numbers like 1980. i can't find the problem!
the changed code is:
prime=[2,3,5]
f=7
def next_prime(f):
    j=0
    while j==0:
        for x in prime:
            if f%x==0:
                f+=2
                break
        else:
            j=1
    return f;
def factorization(n):
    list=[2,3,5]
    power=[]
    x=0
    while x<len(list):
        j=0
        while n%list[x]==0:
            j+=1
            n=n/list[x]
        power.append(j)
        x+=1
    if n!=1:
        while n!=1:
            g=next_prime(f)
            j=0
            while n%g==0:
                j+=1
                n=n/g
            if j!=0:
                power.append(j)
                prime.append(g)
    x=0
    while x<len(power):
        print(prime[x],"^",power[x],"*",end="")
        x+=1

factorization(1980)

A: I haven't analyzed your logic, but you're using else clause wrongly. while .. else makes sense only if you call a break inside your while. In your first code sample, the else branch is always executed.
As example, even the following code will run else branch:
while False:
    print 'while'
else:
    print 'else'

A: If you are only interested in getting the prime factors of a number you can try:
def primefactors(x):
    factorlist=[]
    loop=2
    while loop<=x:
        if x%loop==0:
            x/=loop
            factorlist.append(loop)
        else:
            loop+=1
    return factorlist

For example:
primefactors(1980)
[2, 2, 3, 3, 5, 11]
primefactors(13860)
[2, 2, 3, 3, 5, 7, 11]

A: To add onto imsc's answer,
There is actually an algorithm that uses loop =6 and loop +=6 then tries loop+1 and loop-1 that runs a little better. 2 & 3 must be tried manually first though.


text:
Q: How do I remove Admin from my shipping label? My company has set up the USPS shipping module and we have started printing shipping labels through Magento 2.
Our only problem is that each time we print a shipping label, the name on the label says Admin. I have searched all over the backend, gone through every tab and can't find where this data is coming from.
Could somebody help me figure out how to remove this from our shipping labels?
(Bonus points if you know how to disable signature confirmation because it seems to be automatically applying to each USPS order)

Thank you for your time.

A: Finally found the answer just in case anyone ever gets stuck with this issue.
The Admin Account name was actually coming from my Magento Admin Panel account name. I wish I would have not given it such a generic name or else I may have solved this issue sooner.
Anyway, the solution is as simple as logging into the backend Admin panel, going to
System -> All Users -> Add New User
 Whatever name you input into first and last name for that user will be displayed on the postage when printing it out using USPS or any extension for USPS.


text:
Q: Writing to InfluxDB fails due to timestamp problem I want to write a data point to my influxdb via bash shell but the timestamp seems to cause problems.
root@server:UP [~]# curl -i -XPOST 'http://localhost:8086/write?db=tbr' --data-binary 'codenarc maxPriority2Violations=917 maxPriority3Violations=3336 1593122400000000000'
HTTP/1.1 400 Bad Request
Content-Type: application/json
Request-Id: 03666c3f-b7b5-11ea-8659-02420a0a1b02
X-Influxdb-Build: OSS
X-Influxdb-Error: unable to parse 'codenarc maxPriority2Violations=917 maxPriority3Violations=3336 1593122400000000000': bad timestamp
X-Influxdb-Version: 1.7.10
X-Request-Id: 03666c3f-b7b5-11ea-8659-02420a0a1b02
Date: Fri, 26 Jun 2020 13:57:46 GMT
Content-Length: 129

{"error":"unable to parse 'codenarc maxPriority2Violations=917 maxPriority3Violations=3336 1593122400000000000': bad timestamp"}

This is how I created the timestamp in the first place
def date = LocalDateTime.of(2020, Month.JUNE, 26, 0, 0, 0)
def ms = date.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()
TimeUnit.NANOSECONDS.convert(ms, TimeUnit.MILLISECONDS)

So the timestamp is supposed to be in ns and I ensured that. Why is influxdb giving me that error message? What's wrong with that timestamp?
Thanks!

A: It's not a timestamp issue. You have missed comma between the data that you are passing. Kindly comma separate all of them except the timestamp field. Modified your curl request, try now.
curl -i -XPOST 'http://localhost:8086/write?db=tbr' --data-binary 'codenarc, maxPriority2Violations=917, maxPriority3Violations=3336 1593122400000000000'

One more example:
curl -i -XPOST 'http://localhost:8086/write?db=mydb' --data-binary 'cpu_load_short,host=server02,region=us-west value=0.55 1422568543702900257'


text:
Q: RecyclerView row flashes/blinks when item inserted Any time I insert an item into my Room database, my recycler view flashes the row containing the newly inserted view holder (the rest of the list does not flash). I am using LiveData to keep my list automatically updated by calling submitList(list) in onChanged() of the observed ViewModel method. My adapter extends ListAdapter and I am using DiffUtil to track changes in the list. That being said, I don't call notifyItemInserted(position) directly as DiffUtil should do this for me. There are 2 instances where an item gets inserted (1) a completely new item gets inserted at the end of the list (2) a deleted item gets reinserted into the list. Both cases the item will insert itself then flash. I have read numerous posts where people suggest disabling animations on the recycler view but this is not an option for me as I rely on animations elsewhere in my code. Any other suggestions would be appreciated. I'm trying to keep the posted code brief but I can post more if it would be helpful.
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

@Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    initComponents();
    initRecyclerView();
    setListeners();
    setListObserver();
    createItemTouchHelper();
  }

  private void setListObserver() {
    viewModel.getAllItems().observe(this, new Observer<List<ListItem>>() {
      @Override
      public void onChanged(List<ListItem> newList) {
        adapterMain.submitList(newList);
      }
    });
  }

...

// Inserts a new ListItem when MainActivity's EditText is used
  public void onClick(View v) {
    if (v.getId() == R.id.img_add_item_main) {
        String itemName = String.valueOf(edtAddItem.getText());
        if (!itemName.trim().equals("")) { // Insert new list item only if the EditText is not empty
          ListItem item = new ListItem();
          item.setItemName(itemName);
          viewModel.insert(item);
        }

...

// SnackBar to allow a user to undo a delete operation
  public void showUndoSnackBar(ListItem deletedItem) {
    Snackbar undoSnackBar = Snackbar.make(constraintLayout, "Undo deleted Item",
        Snackbar.LENGTH_LONG).setAction("UNDO", new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        // Restore deleted item to its original position in the list if UNDO is clicked
        viewModel.insert(deletedItem);
      }
    });
    undoSnackBar.show();
  }

RecyclerAdapterMain.java
public class RecyclerAdapterMain extends ListAdapter<ListItem, RecyclerAdapterMain.ListItemHolder> {

  public RecyclerAdapterMain() {
    super(DIFF_CALLBACK);
  }

    private static final DiffUtil.ItemCallback<ListItem> DIFF_CALLBACK = new DiffUtil.ItemCallback<ListItem>() {
    @Override
    public boolean areItemsTheSame(@NonNull ListItem oldItem, @NonNull ListItem newItem) {
      return oldItem.getId() == newItem.getId();
    }

    @Override
    public boolean areContentsTheSame(@NonNull ListItem oldItem, @NonNull ListItem newItem) {
      return oldItem.equals(newItem);
    }

@Override
  public ListItemHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.recycler_item_layout_main, parent, false);
    return new ListItemHolder(itemView);
  }

 @Override
  public void onBindViewHolder(@NonNull ListItemHolder holder, int position) {

    ListItem item = getItem(position);

    holder.txtItemName.setText(item.getItemName());
    holder.checkBox.setChecked(item.getIsChecked());

    if(item.getIsChecked()) {
      holder.txtItemName.setTextColor(Color.LTGRAY);
    } else {
      holder.txtItemName.setTextColor(Color.BLACK);
    }
  }

...

ListItem.java (POJO)
@Entity(tableName = "list_item_table")
public class ListItem {

  @PrimaryKey(autoGenerate = true)
  private long id;

  private String itemName;
  private boolean isChecked;

  public long getId() {
    return id;
  }

  public void setId(long id) {
    this.id = id;
  }

  ... other getters and setters

  public boolean equals(@Nullable ListItem listItem) {
    return this.itemName.equals(listItem.getItemName()) && this.isChecked == listItem.getIsChecked();
  }
}

A: I determined that the DefaultItemAnimator class (which is the animator for RecyclerView at the time of this writing) has a method called animateAdd(final RecyclerView.ViewHolder holder) that sets the holder's alpha to 0 then animates it to 1 over time. I verified that this was the cause of the blinking by changing the default setting to 1. I solved the problem by a using a combination of the accepted answer from this StackOverflow post and the documentation for DefaultItemAnimator.
First, I created a new animator class that extends DefaultItemAnimator in order to override the animateAdd() method. Under the section for animateAdd(), the documentation states, "Called when an item is added to the RecyclerView. Implementors can choose whether and how to animate that change, but must always call dispatchAddFinished(RecyclerView.ViewHolder) when done, either immediately (if no animation will occur) or after the animation actually finishes." I called dispatchAddFinished() immediately to avoid the add animation. Instead of disabling animations altogether, all animations are present except for the problematic one.
MyRecyclerViewAnimator.java
public class MyRecyclerViewAnimator extends DefaultItemAnimator {

  @Override
  public boolean animateAdd(RecyclerView.ViewHolder holder) {
    dispatchAddFinished(holder); // this is what bypasses the animation
    return true;
  }

/* this is the default implementation of animateAdd() in DefaultItemAnimator
@Override
    public boolean animateAdd(final RecyclerView.ViewHolder holder) {
        resetAnimation(holder);
        holder.itemView.setAlpha(0); // this is what caused the flashing/blinking
        mPendingAdditions.add(holder);
        return true;
    }
*/
}

MainActivity.java
...

  recyclerMain.setItemAnimator(new MyRecyclerViewAnimator()); // set the default animator to your extended class

...


text:
Q: nextjs dynamically set response header I'm trying to create a blog for my website. Because I want to be able to dynamically add blogs without rebuilding I had to choose between incremental static generation and server-side rendering. Because a blog page won't change often, I decided to go for ISG. Of course, not every blog ID is a valid page. Therefor I want to set a status code, but I can't find out how without using server-side rendering

A: I found the answer. Turns out I can return notFound: true from the getStaticProps to get a 404


text:
Q: css rotate doesn't work correclty i have one problem with css rotation.
I created this demo from codepen.io
In this demo you can see blue div the lower right corner of the page. When you click this div then the links will opening with rotate animation. But the rotate is not working correclty. I have tryed transform-origin but doesn't worked.
What i am missing in here ? Anyone can help me in this regard ?
CSS
.menu {
  float:left;
  width:0px;
  height:0px;
  border-radius:45px;
  opacity:0;
  text-align:center;line-height:45px;
-webkit-transform:rotate(0deg);
-moz-transform:rotate(0deg);
-o-transform:rotate(0deg);
}
.menu img {
    width: 25px;
    height: 25px;
    margin-top: 9px;
}
.activeMenu {
    width:45px;
    height:45px;
  display:block;
  opacity:1;
  transform-origin:50% 50%;
  -webkit-transform-origin: 50% 50%;
  -webkit-transform:rotate(360deg);
-moz-transform:rotate(360deg);
-o-transform:rotate(360deg);
-webkit-animation:  2s infinite linear;
-moz-animation:  2s infinite linear;
-o-animation:  2s infinite linear;
-ms-animation:  2s infinite linear;
animation:  2s infinite linear;
}

.activeMenu:nth-child(1){
  -webkit-transition-delay: 1s;
 -webkit-transition: all .1s ease .15s;
    -moz-transition: all .1s ease .15s;
    -o-transition: all .1s ease .15s;
    -ms-transition: all .1s ease .15s;
    transition: all .1s ease .15s;
}
.activeMenu:nth-child(2){
  -webkit-transition-delay: 2s;
 -webkit-transition: all .3s ease .30s;
    -moz-transition: all .3s ease .30s;
    -o-transition: all .3s ease .30s;
    -ms-transition: all .3s ease .30s;
    transition: all .3s ease .30s;
}
.activeMenu:nth-child(3){
  -webkit-transition-delay: 3s;
  -webkit-transition: all .5s ease .45s;
    -moz-transition: all .5s ease .45s;
    -o-transition: all .5s ease .45s;
    -ms-transition: all .5s ease .45s;
    transition: all .5s ease .45s;
}
.activeMenu:nth-child(4){
  -webkit-transition-delay: 4s;
 -webkit-transition: all .7s ease .60s;
    -moz-transition: all .7s ease .60s;
    -o-transition: all .7s ease .60s;
    -ms-transition: all .7s ease .60s;
    transition: all .7s ease .60s;
}

HTML

A: I've modified your css a little. Here is the complete document I've tested.
I've also added comments where I made some changes. Got them icons spinning like you wanted to.
<!DOCTYPE html>


text:
Q: Is the Med-Bay Upgrade useful in something? According to the Normandy SR-2 Upgrades on the Mass effect Wiki, the Med-Bay Upgrade only do this :

Using this unit will immediately and completely heal your scars. Further scarring will not occur regardless of the actions you take.

Apart form the cosmetic improvement, nonexistent is you choose the paragon path, is there any reason to throw 50,000 Platinum into the research of this upgrade?

A: It makes no difference to the ending, and does really appear to be a purely cosmetic upgrade.
You can save all your crew members without it, unlike some of the other upgrades.


text:
Q: Proving that the equation $8x^4-8x+7=0$ has no real roots I have to prove that the equation $8x^4-8x+7=0$ has no real roots.
My work:
i) for $x\leq 0,$ expression $8x^4-8x+7>0$,
ii) for $x\geq 1,$ expression $8x(x^3-1)+7>0$,
iii) for $0<x<1$?  I can't go further. Could someone help me with this?

A: Note that
$$8x^4-8x+7=8(x^2-1/2)^2+8(x-1/2)^2+3> 3>0.$$

A: For iii)
We have
$$\begin{align}8x^4-8x+7&=7x^4+x^4-7x-x+7\\&=7x^4-x(1-x^3)+7(1-x)\\&=7x^4-x(1-x)(1+x+x^2)+7(1-x)\\&=7x^4+(1-x)(7-x-x^2-x^3)\end{align}$$
You should be able to prove that this is positive.

A: If
$f(x)
=8x^4-8x+7
$,
$f(0) = 7$
and
$f(1) = 1$.
Also
$\begin{array}\\
f(x)
&=8x^4-8x+7\\
&=8x(x^3-1)+7\\
&=8x(x-1)(x^2+x+1)+7\\
&=-8x(1-x)(x^2+x+1)+7\\
\end{array}
$
For $0 < x < 1$,
$(x-\frac12)^2 \le \frac14$
since
$-\frac12 \le x-\frac12 \le \frac12$
for $0 \le x \le 1$
and
$0 \le x(1-x) \le \frac14$
since
$\begin{array}\\
x(1-x)
&=x-x^2\\
&=-(x^2-x)\\
&=-(x^2-x+\frac14-\frac14)\\
&=-((x-\frac12)^2-\frac14)\\
&=\frac14-(x-\frac12)^2\\
\end{array}
$
Therefore,
since
$1 \le 1+x+x^2 \le 3$,
$0
\le 8x(1-x)(1+x+x^2)
\le 8(\frac14)(3)
=6
$,
so
$f(x) \ge 1$
for $0 \le x \le 1$.

A: With calculus: set $f(x)=8x^4-8x+7$, so
$$
f'(x)=8(4x^3-1)
$$
which only vanishes at $x=4^{-1/3}$. So this is the unique point of minimum.
What's $f(4^{-1/3})$?


text:
Q: How to prove that this series converges uniformly? I have a series
$$
-\frac{\pi}{12} + \sum_{k=1}^\infty \frac{\left(3k\pi^2-16\right)\sin{\frac{k\pi}{2}} + 8\pi\cos{\frac{k\pi}{2}}}{\pi^2k^3}\cos{kt}
$$
And I have to use Weierstass test to prove that the series converges uniformly. The problem is that the sines and cosines are really making it hard to simplify the absolute value of the above and compare it to a known convergent series. Could you help me with that?

A: The series converges absolutely and uniformly, independently of $t$. We can bound the numerator above by $3k\pi^2 + 16 + 8\pi$, which is in general less than $C k$ for a constant $C$ and entirely independent of $t$.
Then the sum looks like
$$ \sum_k \frac{C}{k^2},$$
which converges absolutely. This gives absolute and uniform convergence by the Weierstrass M test.


text:
Q: How high will a party balloon filled with helium go? How high can a party balloon filled with helium go before bursting?  If you filled 2 balloons to different amounts and tied them together, would they go higher?
I'm asking because I'm considering buying a 200g weather balloon to take a phone into the upper stratosphere, but I suddenly wondered if a bunch of cheaper party balloons and string would do the trick.

A: There's a lot more than just physics to this answer.
First - you may not be aware of the fact that the "helium" you buy in a party store is a helium/air mixture that contains enough helium to lift a party balloon - but it doesn't have a lot of "lift" beyond that.
Second - you are in essence asking about the pressure at high altitudes; a balloon that has little elasticity (like a proper high altitude balloon) but a lot of "give" will expand in volume as the surrounding pressure drops, according to $\frac{PV}{T}=\rm{const}$. The pressure of the atmosphere follows a roughly exponential shape, with the value being about 0.1 atm at an altitude of 20 km (which is "somewhere in the stratosphere", depending on your definition).
Now there are two problems. The first is that your party balloons can only be partially filled at 1 atm if you don't want them to burst at 0.1 atm; this means you need a lot more balloons to get the same lift, and that means a lot of additional surface area / mass (including the strings holding the balloons together).
The second problem is the elasticity of the balloon. As the balloon fills, there is some internal pressure that builds up. This will compress the gas inside, making it denser and less buoyant. For a meteorological balloon, this effect is small
This is the reason proper high altitude balloons are slack - they can increase in size as they go higher. Having a single large surface rather than lots of smaller surfaces also significantly reduces the total mass of balloon you would need.
Finally - when toy balloons burst, they end up in the environment, and they kill wildlife. Please don't contribute further to that very real problem.


text:
Q: Is there a way to change/customize images on AddThis script/widget? So we're using the script from this site to share stuff on our site.
However, we like to change the icons/buttons that it uses as a default. Is there a way to change them?

A: Yes, you can change your toolbox and use the icons you want.
Check the "Custom Images" section of this page.

A: See:
http://support.addthis.com/customer/portal/questions/1521845-why-do-my-icons-change-randomly-

These are different for each individual based on their past sharing history and what services are most popular in our service...

Instead of using addthis_button_preferred_1, addthis_button_preferred_2, ... its better to use the following which clearly states what service each image maps to:

      <img src="<URL>/email-share.png" width="80" border="0" alt="Share" />

      <img src="<URL>/fb-share.png" width="80" border="0" alt="Share" />

      <img src="<URL>/googleplus-share.png" width="80" border="0" alt="Share" />

      <img src="<URL>/linkedin-share.png" width="80" border="0" alt="Share" />

      <img src="<URL>/twitter-share.png" width="80" border="0" alt="Share" />

      <img src="<URL>/addthis-share.png" width="80" border="0" alt="Share" />

Replace the URL part according to your needs.


text:
Q: DLL Injection on two processes I am trying to build a dll (in order to inject in a process) and am having some issues with it.
Let me explain :
When I inject my dll in my target, Everything works perfectly. Once I add another target (the same executable) while the first one is still running, there will be some conflicts.
To be fair, I think there is "only" one conflict. Here is the code.
DWORD WINAPI MainThread(LPVOID param)
{
    // Same behaviour with GetKeyState
    while (!GetAsyncKeyState(VK_F9)) // While F9 is not pressed, do nothing
        Sleep(5);
    fprintf(stdout, "Clicked !"); // Print Clicked when F9 is pressed
    while(true); // Just to stop.
    return false;
}

BOOL APIENTRY DllMain(HMODULE hModule,DWORD  ul_reason_for_call,LPVOID lpReserved)
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH: // Gets ran when injected
        AllocConsole(); // Enable the console
        freopen_s((FILE**)stdout, "CONOUT$", "w", stdout);
        freopen_s((FILE**)stdin, "CONIN$", "r", stdin);
        CreateThread(0, 0, MainThread, hModule, 0, 0); // Creates our thread
        break;
    }
    return TRUE;
}

This sample will do the following :
I start Target.exe, I inject Inject.dll into it, I press F9, "Clicked" appears. Expected.
Now, I start Target.exe, I inject Indect.dll, I don't press F9. Instead, I start another Target.exe, I inject Inject.dll into it, and now, if I press F9, Clicked will be printed on both consoles. Unexpected.
Why ?
I read on https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getasynckeystate the following

Although the least significant bit of the return value indicates whether the key has been pressed since the last query, due to the pre-emptive multitasking nature of Windows, another application can call GetAsyncKeyState and receive the "recently pressed" bit instead of your application. The behavior of the least significant bit of the return value is retained strictly for compatibility with 16-bit My Windows applications (which are non-preemptive) and should not be relied upon.

Target.exe and Inject.dll are both 32 bits, so I guess I do not need to be bothered by that quote, so I am really clueless on what is causing it.
Note that I also tested with getchar, but since it is console-related, I can not use it, even if it does not print on the second console.

A: Well, as I stated in my last comment

Tried with SetWindowsHook, same behaviour. Came up with a window rename + name comparison. Works perfectly ! Thanks for your help

I used rename + name comparison. Others issues came out, so I had to rethink my way of achieving it. Here is the final version :
bool isSameProcess(HWND window, DWORD pid)
{
    DWORD activePId;
    DWORD activeThreadId = GetWindowThreadProcessId(window, &activePId);
    return activePId == pid;
}

Explaination :
window is the active window, pid our own process id.
we will check if our pid is equal to active window's process id. If it is, we return true, else, false.
So this way, you can use it like that :
if ((GetAsyncKeyState(VK_F9) & 0x8000))
{
    window = GetForegroundWindow();
    if(isSameProcess(window, pid))
    {/* Whatever you want to do */}
}


text:
Q: What practices will help me write an efficient query against a large partitioned table? Table Properties:

*

*Row Count: 276,027,782

*Number of Partitions: 68
I'm looking to create a report off of one large table. I have a view which holds customer info. To return data of interest for 1 Client/Customer, it takes about 2 minutes. I have about 2200 Clients that I need to return data for. I'm joining on indexes and as far as I can tell I'm hitting the latest partition. As I'm returning data from 1/2017 onward. I'm looking for solutions or ideas that would speed up the code below:
select distinct
 vc.ClientID
,left(datestamp, 6) Month
,count(*) over (partition by left(datestamp, 6)) Cnt
,avg(delta) over (partition by left(datestamp, 6)) Perf
,percentile_cont (0.5) within group (order by delta) over (partition by left(datestamp, 6)) Median
,percentile_cont (0.90) within group (order by delta) over (partition by left(datestamp, 6)) Perc90
,percentile_cont (0.95) within group (order by delta) over (partition by left(datestamp, 6)) Perc95
,percentile_cont (0.99) within group (order by delta) over (partition by left(datestamp, 6)) Perc99
from schema.Monitor pm
    join Reporting.dbo.vwClient vc
        on pm.Institution_ID = vc.ClientID
            and vc.ActiveFlag = 1
            and vc.TestFlag = 0
            and vc.AccountType = 'Customer'

WHERE pm.LogInfo like ('StringFilter') -- no int or id value to filter on

--and pm.IID = @clientID -- filter for 1 customer
ORDER BY
 left(datestamp, 6) desc

A: Partitions do not really matter if you have proper indices. So, the practice is to learn your tools.
Partitions are not more effective than an index - they are there for managing data, i.e. fast delete (swapp out a partition in a millisecond instead of spending hours deleting 12 billion rows in it).
So, the question is: How do I make this query faster - without partition.
Start by deleting the distinct. Go on by actually givine a query plan and - with 2200 clients, please tell us about the server cluster you use to handle the load.


text:
Q: SQL select rows where col1 and col2 are same combination with different col3 values I am kind of not an expert in SQL.
I have a table :
C1   || C2  || C3
    --------------------------
    abc   || 123   || ADD
    abc   || 123   || MERGE
    xyz   || 456   || ADD
    xyz   || 456   || UPDATE
I need to get the rows which have same C1 and C2  and C3 as ADD and MERGE
What is the SQL for that?

A: If you want to find C1 and C2 which has only ADD and UPDATE in C3 then use this
select C1, C2
from yourtable
Group by C1, C2
Having count(case when C3 in ('ADD','MERGE') then 1 end) = count(*)

If you want to find C1 and C2 has both ADD and UPDATE in C3 then use this
select C1, C2
from yourtable
Group by C1, C2
Having count(case when C3 = 'ADD' then 1 end) > 0
   AND count(case when C3 = 'UPDATE' then 1 end) > 0

A: To find C1,C2 where C3 ADD and MERGE without grouping
SELECT C1,C2
FROM
table1 t1
join table1 t2 on t1.C1= t2.C1 and t1.C2=t2.C2 and t2.C3='MERGE'
WHERE
t1.C3='ADD'


text:
Q: How to return two array of objects from one function I have a enum on front end side like this
const listCodes = {
    makePay: 'makePay',
    billPay: 'billPay',
    yesPay: 'yesPay'
}

Now, I am getting the following response from server
const response = [{'entitle': ['makePay', 'yesPay'], 'nonEntitle': ['billPay']}]
const entitled  =  getList(response[0]?.entitle)
const nonentitle = getList(response[0]?.nonEntitle)

Now, I am trying to get these data
const getList = (list) => Object.keys(listCodes).filter((makePayList) => list?.includes(makePayList))

Here I am calling this two times. Is there any way through which we can return both from one method it self ?
Thanks

A: Sure, a function can return an object/array, which encapsulates the multiple return values you want to get. The receiver can use a destructuring assignment to immediately extract those different parts into different variables.
For instance:

const listCodes = {
    makePay: 'makePay',
    billPay: 'billPay',
    yesPay: 'yesPay'
};

const filterLists = obj =>
    ["entitle", "nonEntitle"].map(key =>
        obj[key].filter(code => code in listCodes)
    );

const response = [{'entitle': ['makePay', 'yesPay'], 'nonEntitle': ['billPay']}]
const [entitled, nonEntitle] = filterLists(response[0]);

console.log(entitled);
console.log(nonEntitle);

A: Here is the simplest way of doing it:

const listCodes = {
  makePay: 'makePay',
  billPay: 'billPay',
  yesPay: 'yesPay'
};

const response = [{'entitle': ['makePay', 'yesPay'], 'nonEntitle': ['billPay']}]

const {entitle, nonEntitle} = response && response[0] ? response[0] : {}

console.log(entitle);
console.log(nonEntitle);

It is a little unclear what you are asking in the last part of your question. But from what it looks like I have mentioned the simplified code for what you seem to be trying to achieve. You don't even need an additional function.


text:
Q: How to eliminate the warnings: mockbuild does not exist I was building a package from SRPM on Fedora:
$ rpmbuild --rebuild *.src.rpm

...
warning: user mockbuild does not exist - using root
warning: group mockbuild does not exist - using root
warning: user mockbuild does not exist - using root
warning: group mockbuild does not exist - using root
...

The package was built but there were many such mockbuild does not exist warnings. There doesn't seem to be such an account on my system, even though I have package mock installed. Are there any other packages I'm missing? Is this a fault on the package or my system? How to eliminate these warnings?

A: You don't, and they don't do anything anyways. They are an artifact of the package having been built in the Fedora buildsystem.

A: Installing mock is the way to go, if you are interested in making the same package as Fedora's (as opposed to just creating an rpm).  When installing that, the package creates a mock user which happens to partially fix the problem. According to the Fedora wiki page Using Mock to test package builds, you should add yourself to the mock group:

Add your user name to the mock group
sudo usermod -a -G mock myusername

Doing that fixed the warnings which I got in a rebuild of Fedora's ncurses source-packages.  Depending on the version of mock (and the packages built using it), there may be a mockbuild account referenced in the source-rpms:

commit c33ccca2d36250e9d9fb7dec85fa72c311d43adb
Author: Miroslav Suchý
Date:   Thu Nov 13 14:59:00 2014 +0100
run --shell as root with --new-chroot

Until now --new-chroot run --shell as 'mockbuild' user. This is
regression from --old-chroot, where it was run as root user.

Further reading:

*

*build rpm packages such as Redhat/Fedora:

On 11/13/2010 18:15, Christopher Stolzenberg wrote:

yum install mock
useradd mockbuild
usermod -G mock mockbuild

Unless you want to ``su'' to a dedicated mockbuild account every time
you want to build you should add your usual account to the mock group
instead.

mock rebuild -r epel-6-x86_64 /home/mockbuild/kernel 2.6.32-71.7.1.el6.src.rpm

Mock typically grabs packages from CentOS, so until CentOS 6 is out
you're going to have to build using RHEL 6.

*

*Building RPMS:

The Fedora project's page says to add your user to mock. You can skip this, but to avoid errors later (when installing srpms), add a mockbuild user. The mockbuild user doesn't need a password.
sudo useradd mockbuild


text:
Q: What does "(?x::" mean in a Boost regex replacement, where "x" is a number? This is a Perl-style Regular Expression found in one of the snippet files in the Ruby package of Sublime Text 2:
/(?:\A|_)([A-Za-z0-9]+)(?:\.rb)?/(?2::\u$1)/g

I know it converts a file name like "some_class.rb" into "SomeClass", but I can't figure out what this part does: (?2::. Sublime Text 2 uses boost for its Regular Expressions, so I checked the documentation for Boost-Extended Format String Syntax, and I found that boost supports conditionals in the format string (f.inst. (?2(foo):(bar))) but you'll never need two colons for that. Additionally, ?2 would point to the second sub-expression, but the expression above only ever matches one sub-expression. For those reasons, I don't think this is a conditional expression.
Thanks for any enlightening answers.

A: First of all, the (?2::\u$1) on the replacement side of ///g is not Perl. It's Boost's own extension

*

*see [Search and Replace Format String Syntax > Boost-Extended Format String Syntax] as mentioned by OP.

Referring to said document, it is saith,

The character '?' begins a conditional expression, the general form is:
?Ntrue-expression:false-expression
where N is decimal digit.
If sub-expression N was matched, then true-expression is evaluated and sent to output, otherwise false-expression is evaluated and sent to output.

Based on this, let's analyze the mysterious (?2::\u$1)

*

*?2 is always false, because there is no 2nd capturing group.

*the first : is a "special character" in true-expression which means empty string

*

*if we assume that true-expression cannot be left empty, the first : is not interpreted as the separator between the true- and false-expression (for the gory/juicy details, please read Appendix D).

*in fact, we can put whatever we want as true-expression (as long as there is no : somewhere in the middle) since ?2 never evaluates to true.

*\u$1 is the false-expression.

Putting two and two together, I'm going to go out on a limb and say
/(?:\A|_)([A-Za-z0-9]+)(?:\.rb)?/(?2::\u$1)/g

is but an obfuscated way of doing this:
/(?:\A|_)([A-Za-z0-9]+)(?:\.rb)?/\u$1/g

Appendix D: Experimentation with snippet in Sublime Text 2
So I defined a Sublime Text 2 snippet with this content
<snippet>
    <content><![CDATA[
snakecase: ${1:hello_world}
camelcase: ${1/(?:\A|_)([A-Za-z0-9]+)(?:\.rb)?/(?2::\u$1)/g}
]]></content>
    <tabTrigger>convert</tabTrigger>
</snippet>

and played around with different expressions for the right side of substitution.
Given the input hello_world

*

*if right side is (?2::\u$1), returns HelloWorld

*if right side is (?2:\u$1), returns HW

*if right side is (?2:$1), returns nothing

*if right side is (?2:::\u$1), returns :Hello:World

*if right side is (?1:\u$1), returns HelloWorld

*if right side is (?1::\u$1), returns HW

*if right side is (?1::$1), returns nothing

*if right side is (?1:::\u$1) returns HW

*if right side is (?1:::$1) returns nothing

*if right side is \u$1, returns HelloWorld
Some tentative conclusions based on this (assuming that cases 2, 6, 8 are anomalies†)

*

*if only a single colon (:) follows the digit, it is ignored (i.e. it is not interpreted as the separator between true- and false-expression).

*if 2 colons (::) follow the digit, the true-expression is an empty string (2nd : is the separator)

*if 3 colons (:::) follow the digit, the true-expression is an empty string, and the false-expression starts with a literal colon (2nd : is the separator)

*comparing cases 1 and 10, my conclusion on the equivalence of (?2::\u$1) and \u$1 still stands.

† I said anomalies because \u$1 behaves so differently compared to $1 (everything except the first character of captured substring disappears)

A: Maybe there's a colon in the replacement string, like :\u$1 is the replacement string.


text:
Q: nHibernate complex Query I have a problem querying using nHibernate.
I have the following entities:
public class CostAmount
{
    public virtual int Id {get;set;}
    public virtual Year Year{get; set;}
    public virtual Month Month{get; set;}
}

public class Year
{
    public virtual int Id {get;set;}
    public virtual string Code {get;set;}
}

public class Month
{
    public virtual int Id {get;set;}
    public virtual string Code {get;set;}
}

I want to query using some sql like the following:
select * from CostAmount ca
inner join Year y on ca.YearID = y.ID
inner join Month m on ca.MonthID = m.ID
where y.Code *100+m.Code between 9107 and 9207

Can any one help me please.

A: As I've written, NHibernate QueryOver has poor syntax for math operations... Now, if we consider Code to be an int (because I normally don't multiply strings by 100):
// Aliases
CostAmount costAmount = null;
Year year = null;
Month month = null;

// Projections for the math operations

// y.Code * 100
var proj1 = Projections.SqlFunction(
    new VarArgsSQLFunction("(", "*", ")"),
    NHibernateUtil.Int32,
    Projections.Property(() => year.Code),
    Projections.Constant(100)
);

// proj1 + m.Code
var proj2 = Projections.SqlFunction(
    new VarArgsSQLFunction("(", "+", ")"),
    NHibernateUtil.Int32,
    proj1,
    Projections.Property(() => month.Code)
);

// The query

var query = Session.QueryOver(() => costAmount)
                   .JoinAlias(() => costAmount.Year, () => year)
                   .JoinAlias(() => costAmount.Month, () => month)
                   .Where(Restrictions.Between(proj2, 9107, 9207));

var res = query.List();

The trick for math operations was taken from https://stackoverflow.com/a/10756598/613130

A: Maybe you can check this question Fluent Nhibernate inner join
Or maybe from this explanation can guide you to find the right answer.
http://ayende.com/blog/4023/nhibernate-queries-examples


text:
Q: Kotlin lets-plot: minimal example I would like to write a completely minimal example of lets-plot, which just saves png and doesn't use any frontend. For this, I created a "helloworld" Kotlin project in IntelliJ IDEA. Then I added Maven dependency org.jetbrains.lets-plot:lets-plot-common:2.1.0. Now if I try to import jetbrains.letsPlot.letsPlot, I get the error "Unresolved reference: letsPlot". Thus, the question is how to write the most minimal lets-plot example, without using any frontend and Gradle.

A: The right dependencies are org.jetbrains.lets-plot:lets-plot-kotlin-jvm:3.0.2 (for API) and org.jetbrains.lets-plot:lets-plot-image-export:2.1.0 (to be able to export to raster). Now it works, and the resulting image in lets-plot-images directory.
The code:
import jetbrains.letsPlot.export.ggsave
import jetbrains.letsPlot.geom.geomPoint
import jetbrains.letsPlot.letsPlot

fun main() {
    val xs = listOf(0,  0.5, 1, 2)
    val ys = listOf(0, 0.25, 1, 4)
    val data = mapOf<String, Any>("x" to xs, "y" to ys)

    val fig = letsPlot(data) + geomPoint(
        color = "dark-green",
        size = 4.0
    ) { x = "x"; y = "y" }

    ggsave(fig, "plot.png")
}

The resulting image:


text:
Q: Aggregate list based on size I have a list of let's say size 10, I want to aggregate using max size 6.
In this case it should work like this: first six messages are aggregated into one message and then right away (without any timeout) the next 4 messages are aggregated into second message.
How can I achieve this in spring integration? I tried using releaseStrategy but I can only define in it the max size, and then the messages that are left (4 messages in my case) are waiting in the aggregator for more messages (so the max size condition is met). I don't want to wait for aggregator timeout cause I know that my list's size is 10, so there is nothing to wait for after the 4th message, it should create the second aggregated message right away.

A: Use a custom ReleaseStrategy; something like...
public class MyReleaseStrategy implements ReleaseStrategy {

    private final Map<Object, AtomicInteger>() map = new HashMap<>();

    public boolean canRelease(MessageGroup group) {
        AtomicInteger count = map.get(group.getGroupId());
        if (count == null) {
            count = new AtomicInteger();
            map.put(int);
        }
        int n = count.incrementAndGet();
        boolean canRelease = n == 6 || n == 10;
        if (n == 10) {
            map.remove(group.getGroupId());
        }
        return canRelease;
    }
}


text:
Q: Cobertura coverage failing I am running into issues similar to [https://stackoverflow.com/questions/25432810/error-when-trying-to-use-org-codehaus-mojocobertura-maven-plugin2-6].
LOGS:
Execution default-cli of goal org.codehaus.mojo:cobertura-maven-plugin:2.6:instrument failed: Plugin org.codehaus.mojo:cobertura-maven-plugin:2.6 or one of its dependencies could not be resolved: Could not find artifact com.sun:tools:jar:0 at specified path /usr/local/Cellar/openjdk/15.0.2/libexec/openjdk.jdk/Contents/Home/../lib/tools.jar
RESEARCH:
When I do java --version, I get:
java 11.0.6 2020-01-14 LTS
Upon searching SO, I found that since I am on the JDK 11, the tools.jar has been removed [https://stackoverflow.com/a/60549167/13241701]. When I run the jacoco, the test cases run. But
ISSUE: I want to report the cobertura coverage report only.
Can I get some help?

A: I would recommend using latest version of the plugin which is 2.7 and has built in fixes for java 11.
If you cannot use latest plugin for some reason, here are some of the things you can try
Use 'mvn dependency:tree' to find where that jar is being called and exclude it like so
<dependency>
    <groupId>org.apache.struts</groupId>
    <artifactId>struts2-core</artifactId>
    <version>${struts2.version}</version>
    <exclusions>
        <exclusion>
            <artifactId>tools</artifactId>
            <groupId>com.sun</groupId>
        </exclusion>
    </exclusions>
</dependency>

Or you can just reference it in your mvn like
<dependency>
   <groupId>com.sun</groupId>
   <artifactId>tools</artifactId>
   <version>1.6</version>
   <scope>system</scope>
   <systemPath>C:\Program Files\Java\jdk1.11.6\lib\tools.jar</systemPath>
 </dependency>

where system path is link to your lib
Another way is to provide jdk vm as a run arg
-vm "C:\Program Files\Java\jdk1.11.6\bin"


text:
Q: How to extract text of paragraph from html using Jsoup? import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class JavaApplication14 {

public static void main(String[] args)  {
    try {
        Document doc = Jsoup.connect("tanmoy_mahathir.makes.org/thimble/146").get();
         String html= "" + "
Parsed HTML into a doc."
                 + "
";
  Elements paragraphs = doc.select("p");
  for(Element p : paragraphs)
    System.out.println(p.text());
    } catch (IOException ex) {
        Logger.getLogger(JavaApplication14.class.getName()).log(Level.SEVERE, null, ex);
    }
}

}
can anyone help me with jsoup code how can i parse just portion including paragraph so that just print
Hello ,World!
Nothing is impossible

A: For this small bit of html you just need to do
String html= "" + "
Parsed HTML into a doc."+
                    +"
";
Document doc = Jsoup.parse(html);
Elements paragraphs = doc.select("p");
for(Element p : paragraphs)
  System.out.println(p.text());

As I see your link contains pretty much the same html you could then also replace the definition of doc with
Document doc = Jsoup.connect("https://tanmoy_mahathir.makes.org/thimble/146").get();

UPDATE
Here is the full code that compiles and runs fine for me.
import java.io.IOException;
import java.util.logging.*;
import org.jsoup.*;
import org.jsoup.nodes.*;
import org.jsoup.select.*;

public class JavaApplication14 {

  public static void main(String[] args)  {
    try {
      String url = "https://tanmoy_mahathir.makes.org/thimble/146";
      Document doc = Jsoup.connect(url).get();
      Elements paragraphs = doc.select("p");
      for(Element p : paragraphs)
        System.out.println(p.text());
    }
    catch (IOException ex) {
      Logger.getLogger(JavaApplication14.class.getName())
            .log(Level.SEVERE, null, ex);
    }
  }
}

A: You may start by trying this....
String url = "url of the html page";
Document page = Jsoup.parse(url);

Elements elements = page.select("div[class=class_name] p");

A: *

*Element firstPara = d.select("div.post-content p").first() ;2

*System.out.println(firstPara);

you can select tag with it's class and then can go more specific like getting first paragraph


text:
Q: iOS 12.2 Flash SMS (class 0) with sender and warning We found that since iOS 12.2 if one send Flash SMS (class 0),

Uppers side contains our company's name (we send SMS a lot);
Second looks like iOS warning about SMS sender. How can we manipulate with it? Hide second warning?

A: I'm not sure if this would work can you wrap the code like a strand of DNA to hide it and put it back together after you are past what ever you are trying to get by in other words put send in one code with the other in parts and assemble it after just a thought


text:
Q: How do I make Excel tab through merged cells in a protected sheet? I am having a problem with how tab selection in an Excel sheet behaves on merged cells when the sheet is protected versus when it is unprotected.
I have a merged cell that is two rows high.  When the sheet is unprotected, the user is able to select either cell immediately to the left of the merged cells, hit tab once to enter the merged cell, and hit tab again to continue onto whatever row they started on.

My issue is that when I protect the sheet, that behavior changes.  If the user selects the cell in the lower row and hits tab, their selection skips the merged cell entirely.

I want the sheet to behave like it does when it is unprotected, even if I protect it.  What is causing the change in selection behavior, and what can I do to preserve the unprotected sheet behavior in a protected sheet?
I only see this behavior with hitting the tab key- the right and left arrow keys behave normally.

A: Sadly this will not solve your problem either, but if it helps I avoid using merged cells altogether by removing vertical borders to give the appearance of merged and to "center across selection" to give the appearance in the horizontal.
I am aware this is just a work around, but hopefully it helps.


text:
Q: tcpdump is not capturing packets Can anybody tell me what kind of error I have in this? It isn't reading any packets when I run it.
nohup sudo tcpdump -i any host 10.0.1.107 and port 5060 and port 6060 -G 010 -W 015 -w capture_%Y-%m-%d_%H:%M:%S.pcap -z gzip </dev/null >nohup.out 2>&1 &
Thanks

A: The error is here:
and port 5060 and port 6060

If port is 5060, port cannot be 6060, and viceversa, so the condition you entered will always be false. You probable want to use or instead.

A: port 5060 and port 6060 is true only if one of the ports in the packet is 5060 and the other port is 6060, so it won't capture all packets to or from port 5060 or all packets to or from port 6060.
If you want all packets from or to port 5060 or from or to port 6060, you want port 5060 or port 6060, i.e. host 10.0.1.107 and (port 5060 or port 6060), in quotes.


text:
Q: Still working in flex3, now want to move to flex4, have some queries, Help Needed? I am flex developer, and from last few months, i am continuously working on projects, so i was not getting enough time to migrate to flex4
I am well comfortable in flex3, as i m doing the whole flex projects designing by myself, normally i prefer graphical skinning. i am using adobe flash for this.
But now i want to move to flex4 environment, but facing the same problem, how do i do skinning for the buttons and other components?
Do Flex4 allow same old graphical skinning?
i did googled for this , but couldn't extract n e thing useful?
and also please tell help me with some gud links, so that i will be able to start my new project development in flex4 now,
I did studied flex4 tutorials on adobe etc, but they support some sort of making some skinnig classes, and do everything thru coding, i guess thats real hard?
i feel like, making up, over, down and disabled skin of a button in flash, and then importing them to flex, that was much easier.
Can n e eone also tell me, why there are few halo components still there in flex4, whose spark replacements are not avaialble?
is flex4.5 version includes all spark components which were halo in flex3
Well, lots of questions this time :)
Thanks everyone in advance

A: Flex4 has improved skinning and states.
It is easy to auto generate skin classes.
Specify a skinClass:
<s:Button skinClass="ExampleSkin" />

You can [command/control]+[space-bar] inside the skinClass property and choose "Create skin..." option from the context menu to generate an appropriate skin class.
Properties may be set by state, for example:
<!-- states -->
<s:states>
    <s:State name="up" />
    <s:State name="over" />
    <s:State name="down" />
    <s:State name="disabled" />
</s:states>

        <s:GradientEntry color="0x000000"
                         color.down="0xFFFFFF"

For the Spark Button GradientEntry above, color is black except for the down state which is white.
Auto generated skin class for a Button would be:
<?xml version="1.0" encoding="utf-8"?>

<!--

    ADOBE SYSTEMS INCORPORATED
    Copyright 2008 Adobe Systems Incorporated
    All Rights Reserved.

    NOTICE: Adobe permits you to use, modify, and distribute this file
    in accordance with the terms of the license agreement accompanying it.

-->

<!--- The default skin class for the Spark Button component.

       @see spark.components.Button

      @langversion 3.0
      @playerversion Flash 10
      @playerversion AIR 1.5
      @productversion Flex 4
-->
<s:SparkButtonSkin xmlns:fx="http://ns.adobe.com/mxml/2009"
             xmlns:s="library://ns.adobe.com/flex/spark"
             xmlns:fb="http://ns.adobe.com/flashbuilder/2009"
             minWidth="21" minHeight="21"
             alpha.disabled="0.5">

    <fx:Metadata>
        <![CDATA[
        /**
         * @copy spark.skins.spark.ApplicationSkin#hostComponent
         */
        [HostComponent("spark.components.Button")]
        ]]>
    </fx:Metadata>

    <fx:Script fb:purpose="styling">
        <![CDATA[
            import spark.components.Group;
            /* Define the skin elements that should not be colorized.
            For button, the graphics are colorized but the label is not. */
            static private const exclusions:Array = ["labelDisplay"];

            /**
             * @private
             */
            override public function get colorizeExclusions():Array {return exclusions;}

            /**
             * @private
             */
            override protected function initializationComplete():void
            {
                useChromeColor = true;
                super.initializationComplete();
            }

            /**
             *  @private
             */
            override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number) : void
            {
                var cr:Number = getStyle("cornerRadius");

                if (cornerRadius != cr)
                {
                    cornerRadius = cr;
                    shadow.radiusX = cornerRadius;
                    fill.radiusX = cornerRadius;
                    lowlight.radiusX = cornerRadius;
                    highlight.radiusX = cornerRadius;
                    border.radiusX = cornerRadius;
                }

                if (highlightStroke) highlightStroke.radiusX = cornerRadius;
                if (hldownstroke1) hldownstroke1.radiusX = cornerRadius;
                if (hldownstroke2) hldownstroke2.radiusX = cornerRadius;

                super.updateDisplayList(unscaledWidth, unscaledHeight);
            }

            private var cornerRadius:Number = 2;

        ]]>
    </fx:Script>

    <!-- states -->
    <s:states>
        <s:State name="up" />
        <s:State name="over" />
        <s:State name="down" />
        <s:State name="disabled" />
    </s:states>

    <!-- layer 1: shadow -->
    <!--- @private -->
    <s:Rect id="shadow" left="-1" right="-1" top="-1" bottom="-1" radiusX="2">
        <s:fill>
            <s:LinearGradient rotation="90">
                <s:GradientEntry color="0x000000"
                                 color.down="0xFFFFFF"
                                 alpha="0.01"
                                 alpha.down="0" />
                <s:GradientEntry color="0x000000"
                                 color.down="0xFFFFFF"
                                 alpha="0.07"
                                 alpha.down="0.5" />
            </s:LinearGradient>
        </s:fill>
    </s:Rect>

    <!-- layer 2: fill -->
    <!--- @private -->
    <s:Rect id="fill" left="1" right="1" top="1" bottom="1" radiusX="2">
        <s:fill>
            <s:LinearGradient rotation="90">
                <s:GradientEntry color="0xFFFFFF"
                                 color.over="0xBBBDBD"
                                 color.down="0xAAAAAA"
                                 alpha="0.85" />
                <s:GradientEntry color="0xD8D8D8"
                                 color.over="0x9FA0A1"
                                 color.down="0x929496"
                                 alpha="0.85" />
            </s:LinearGradient>
        </s:fill>
    </s:Rect>

    <!-- layer 3: fill lowlight -->
    <!--- @private -->
    <s:Rect id="lowlight" left="1" right="1" top="1" bottom="1" radiusX="2">
        <s:fill>
            <s:LinearGradient rotation="270">
                <s:GradientEntry color="0x000000" ratio="0.0" alpha="0.0627" />
                <s:GradientEntry color="0x000000" ratio="0.48" alpha="0.0099" />
                <s:GradientEntry color="0x000000" ratio="0.48001" alpha="0" />
            </s:LinearGradient>
        </s:fill>
    </s:Rect>

    <!-- layer 4: fill highlight -->
    <!--- @private -->
    <s:Rect id="highlight" left="1" right="1" top="1" bottom="1" radiusX="2">
        <s:fill>
            <s:LinearGradient rotation="90">
                <s:GradientEntry color="0xFFFFFF"
                                 ratio="0.0"
                                 alpha="0.33"
                                 alpha.over="0.22"
                                 alpha.down="0.12"/>
                <s:GradientEntry color="0xFFFFFF"
                                 ratio="0.48"
                                 alpha="0.33"
                                 alpha.over="0.22"
                                 alpha.down="0.12" />
                <s:GradientEntry color="0xFFFFFF"
                                 ratio="0.48001"
                                 alpha="0" />
            </s:LinearGradient>
        </s:fill>
    </s:Rect>

    <!-- layer 5: highlight stroke (all states except down) -->
    <!--- @private -->
    <s:Rect id="highlightStroke" left="1" right="1" top="1" bottom="1" radiusX="2" excludeFrom="down">
        <s:stroke>
            <s:LinearGradientStroke rotation="90" weight="1">
                <s:GradientEntry color="0xFFFFFF" alpha.over="0.22" />
                <s:GradientEntry color="0xD8D8D8" alpha.over="0.22" />
            </s:LinearGradientStroke>
        </s:stroke>
    </s:Rect>

    <!-- layer 6: highlight stroke (down state only) -->
    <!--- @private -->
    <s:Rect id="hldownstroke1" left="1" right="1" top="1" bottom="1" radiusX="2" includeIn="down">
        <s:stroke>
            <s:LinearGradientStroke rotation="90" weight="1">
                <s:GradientEntry color="0x000000" alpha="0.25" ratio="0.0" />
                <s:GradientEntry color="0x000000" alpha="0.25" ratio="0.001" />
                <s:GradientEntry color="0x000000" alpha="0.07" ratio="0.0011" />
                <s:GradientEntry color="0x000000" alpha="0.07" ratio="0.965" />
                <s:GradientEntry color="0x000000" alpha="0.00" ratio="0.9651" />
            </s:LinearGradientStroke>
        </s:stroke>
    </s:Rect>
    <!--- @private -->
    <s:Rect id="hldownstroke2" left="2" right="2" top="2" bottom="2" radiusX="2" includeIn="down">
        <s:stroke>
            <s:LinearGradientStroke rotation="90" weight="1">
                <s:GradientEntry color="0x000000" alpha="0.09" ratio="0.0" />
                <s:GradientEntry color="0x000000" alpha="0.00" ratio="0.0001" />
            </s:LinearGradientStroke>
        </s:stroke>
    </s:Rect>

    <!-- layer 7: border - put on top of the fill so it doesn't disappear when scale is less than 1 -->
    <!--- @private -->
    <s:Rect id="border" left="0" right="0" top="0" bottom="0" width="69" height="20" radiusX="2">
        <s:stroke>
            <s:LinearGradientStroke rotation="90" weight="1">
                <s:GradientEntry color="0x000000"
                                 alpha="0.5625"
                                 alpha.down="0.6375" />
                <s:GradientEntry color="0x000000"
                                 alpha="0.75"
                                 alpha.down="0.85" />
            </s:LinearGradientStroke>
        </s:stroke>
    </s:Rect>

    <!-- layer 8: text -->
    <!--- @copy spark.components.supportClasses.ButtonBase#labelDisplay  -->
    <s:Label id="labelDisplay"
             textAlign="center"
             maxDisplayedLines="1"
             horizontalCenter="0" verticalCenter="1" verticalAlign="middle"
             left="10" right="10" top="2" bottom="2">
    </s:Label>

</s:SparkButtonSkin>

Flash Catalyst provides design authoring, or Flash Professional has the Flex Component Kit.
You could create a skin that loads embedded Flash library symbols by state.
MX architecture is generally deprecated by Spark.  Use Spark components if available.


text:
Q: How to supress a Shiny observeEvent firing in a lapply I am looking for a little assistance on an overly sensitive R Shiny reactiveValues object please.  Thanks in advance.
I am aiming to develop a simple form that returns 3 Shiny fluidrows via calls on renderUI in an lapply. Each row has two buttons and a value which starts at 0. The value should increment or decrease by 1 by respectively clicking the "plus" or "minus" buttons.
When either button is clicked though the observeEvent keeps firing, as can be seen with the call to print the updated value. I placed an isolate up front but that negates the front-end value from updating.
library(shiny)
library(dplyr)

ui <- fluidPage(
  uiOutput('oupt_q11')
)

server <- function(input, output, session) {

  tbl_vals <- reactiveValues(
    pos_1    = 0
    , pos_2  = 0
    , pos_3  = 0
  )

  output$oupt_q11 <- renderUI({

    lapply(seq_along(1:3), function(x){

      # tbl_vals_x <- isolate(as.character(tbl_vals[[paste0('pos_', x)]]))
      tbl_vals_x <- as.character(tbl_vals[[paste0('pos_', x)]])

      hold_rtrn <- fluidRow(
        column(12,
               style = 'background-color: #b8c2d1'
               , column(3, actionButton(paste0('btn_less_', x), label = ' - '))
               , column(3, tbl_vals_x)
               , column(3, actionButton(paste0('btn_more_', x), label = ' + '))
        ))

      observeEvent(input[[paste0('btn_less_', x)]], {

        pass_value <- as.numeric(tbl_vals[[paste0('pos_', x)]])
        tbl_vals[[paste0('pos_', x)]] <- pass_value - 1
        print(tbl_vals[[paste0('pos_', x)]])

      })

      observeEvent(input[[paste0('btn_more_', x)]], {

        pass_value <- as.numeric(tbl_vals[[paste0('pos_', x)]])
        tbl_vals[[paste0('pos_', x)]] <- pass_value + 1
        print(tbl_vals[[paste0('pos_', x)]])

      })
      return(hold_rtrn)
    })
  })

}

shinyApp(ui, server)

A: Just put the observeEvent() outside the renderUI.  It works.  Try this.
library(shiny)
library(dplyr)

ui <- fluidPage(
  uiOutput('oupt_q11')
)

server <- function(input, output, session) {

  tbl_vals <- reactiveValues(
    pos_1    = 0
    , pos_2  = 0
    , pos_3  = 0
  )

  output$oupt_q11 <- renderUI({
    hold_rtrn <- list()

    lapply(seq_along(1:3), function(x){
      #tbl_vals_x <- as.character(tbl_vals[[paste0('pos_', x)]])

      hold_rtrn[[x]] <<- fluidRow(
        column(12,
               style = 'background-color: #b8c2d1'
               , column(3, actionButton(paste0('btn_less_', x), label = ' - '))
               , column(3, as.character(tbl_vals[[paste0('pos_', x)]]))
               , column(3, actionButton(paste0('btn_more_', x), label = ' + '))
        ))

    })
    hold_rtrn
  })

  lapply(1:3, function(x) {
    observeEvent(input[[paste0('btn_less_', x)]], {
      pass_value <- as.numeric(tbl_vals[[paste0('pos_', x)]])
      tbl_vals[[paste0('pos_', x)]] <- pass_value - 1
      print(tbl_vals[[paste0('pos_', x)]])

    })

    observeEvent(input[[paste0('btn_more_', x)]], {
      pass_value <- as.numeric(tbl_vals[[paste0('pos_', x)]])
      tbl_vals[[paste0('pos_', x)]] <- pass_value + 1
      print(tbl_vals[[paste0('pos_', x)]])

    })
  })

}

shinyApp(ui, server)


text:
Q: cannot save tensorrflow keras quantum model using save/pickle how to save tensorflow quantum model? I am getting the following when i am trying to save keras model with quantum circuits.
I didnt find any support for the same.
tensorflow:Layer add_circuit_2 was passed non-serializable keyword arguments
tensorflow:Layer add_circuit_2 was passed non-serializable keyword arguments
tensorflow:Layer add_circuit_2 was passed non-serializable keyword arguments
    WARNING:tensorflow:Layer add_circuit_2 was passed non-serializable keyword arguments: {'prepend':
    cirq.Circuit([
    cirq.Moment(operations=[
    cirq.H.on(cirq.GridQubit(0, 0)),
    cirq.H.on(cirq.GridQubit(0, 1)),
    cirq.H.on(cirq.GridQubit(0, 2)),
    cirq.H.on(cirq.GridQubit(0, 3)),
    cirq.H.on(cirq.GridQubit(1, 0)),
    cirq.H.on(cirq.GridQubit(1, 1)),
    cirq.H.on(cirq.GridQubit(1, 2)),
    cirq.H.on(cirq.GridQubit(1, 3)),
    cirq.H.on(cirq.GridQubit(2, 0)),
    cirq.H.on(cirq.GridQubit(2, 1)),
    cirq.H.on(cirq.GridQubit(2, 2)),
    cirq.H.on(cirq.GridQubit(2, 3)),
    cirq.H.on(cirq.GridQubit(3, 0)),
    cirq.H.on(cirq.GridQubit(3, 1)),
    cirq.H.on(cirq.GridQubit(3, 2)),
    cirq.H.on(cirq.GridQubit(3, 3)),
]),
cirq.Moment(operations=[
    cirq.CZ.on(cirq.GridQubit(0, 0), cirq.GridQubit(0, 1)),
]),
cirq.Moment(operations=[
    cirq.CZ.on(cirq.GridQubit(0, 1), cirq.GridQubit(0, 2)),
]),
cirq.Moment(operations=[
    cirq.CZ.on(cirq.GridQubit(0, 2), cirq.GridQubit(0, 3)),
]),
cirq.Moment(operations=[
    cirq.CZ.on(cirq.GridQubit(0, 3), cirq.GridQubit(1, 0)),
]),
cirq.Moment(operations=[
    cirq.CZ.on(cirq.GridQubit(1, 0), cirq.GridQubit(1, 1)),
]),
cirq.Moment(operations=[
    cirq.CZ.on(cirq.GridQubit(1, 1), cirq.GridQubit(1, 2)),
]),
cirq.Moment(operations=[
    cirq.CZ.on(cirq.GridQubit(1, 2), cirq.GridQubit(1, 3)),
]),
cirq.Moment(operations=[
    cirq.CZ.on(cirq.GridQubit(1, 3), cirq.GridQubit(2, 0)),
]),
cirq.Moment(operations=[
    cirq.CZ.on(cirq.GridQubit(2, 0), cirq.GridQubit(2, 1)),
]),
cirq.Moment(operations=[
    cirq.CZ.on(cirq.GridQubit(2, 1), cirq.GridQubit(2, 2)),
]),
cirq.Moment(operations=[
    cirq.CZ.on(cirq.GridQubit(2, 2), cirq.GridQubit(2, 3)),
]),
cirq.Moment(operations=[
    cirq.CZ.on(cirq.GridQubit(2, 3), cirq.GridQubit(3, 0)),
]),
cirq.Moment(operations=[
    cirq.CZ.on(cirq.GridQubit(3, 0), cirq.GridQubit(3, 1)),
]),
cirq.Moment(operations=[
    cirq.CZ.on(cirq.GridQubit(3, 1), cirq.GridQubit(3, 2)),
]),
cirq.Moment(operations=[
    cirq.CZ.on(cirq.GridQubit(3, 2), cirq.GridQubit(3, 3)),
]),
cirq.Moment(operations=[
    cirq.CZ.on(cirq.GridQubit(3, 3), cirq.GridQubit(0, 0)),
]),])}.
They will not be included in the serialized model (and thus will be missing at deserialization time).
---------------------------------------------------------------------------
NotImplementedError                       Traceback (most recent call last)
<ipython-input-91-a74ee5c9d34d> in <module>()
----> 1 qcnn_model.save('qcnn_model.h5')

8 frames
/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/keras/engine/base_layer.py in
get_config(self)
497     # or that `get_config` has been overridden:
498     if len(extra_args) > 1 and hasattr(self.get_config, '_is_default'):
--> 499       raise NotImplementedError('Layers with arguments in `__init__` must '
500                                 'override `get_config`.')
501     return config

NotImplementedError: Layers with arguments in `__init__` must override `get_config`.

A: TensorFlow Quantum does not yet implement get_config and load_config. We had some difficulty with saving certain Cirq objects, we are working on it.
For now if you want to save models that contain quantum layers you can use the
model = tf.keras.Model(...)
model.save_weights("some_path")
...
model.load_weights("some_path")

function instead.


text:
Q: $(\kappa,\lambda)$-extenders and well-foundedness (Note that I'm considering extenders within the full context of $\mathsf{ZFC}$ rather than various fragments.)
For $E$ a $(\kappa,\lambda)$-extender, the well-foundedness of the limit ultrapower $\mathrm{ult}(V,E)$ is equivalent to countable completeness:

for every sequence $\langle a_n, X_n:n\in\omega\rangle$ with $X_n\in E_{a_n}$, there is a function $g:\bigcup_{n<\omega}a_n\rightarrow\kappa$ such that $g\mathord{"}a_n\in X_n$ for each $n<\omega$.

I'm able to show the supposedly harder direction that well-foundedness implies countable completeness (analogous to the proof for ultrafilters). But for some reason, I'm having trouble showing that countable completeness implies well-foundedness.
My initial idea was just to take a $\in^{\mathrm{ult}(V,E)}$-decreasing sequence $\langle[b_n,f_n]:n\in\omega\rangle$, and work with $a_n=\bigcup_{i\le n}b_n$ and just define $X_n$ by
$$t\in X_n\quad\text{iff}\quad\bigwedge_{i<n}f_{i+1}(t)\in f_{i}(t)\text{.}$$
From here we get a $g$ as above so that one consequence is $f_{n+1}(g\mathord{"}a_n)\in f_n(g\mathord{"}a_n)$.  But this doesn't quite give what we want, which is that $f_{n+1}(g\mathord{"}a_{n+1})\in f_n(g\mathord{"}a_n)$ (and then consider $\langle f_n(g\mathord{"}a_n):n\in\omega\rangle$, contradicting the well-foundedness of $V$).  So how are we supposed to relate $f_{n+1}(g\mathord{"}a_n)$ and $f_{n+1}(g\mathord{"}a_{n+1})$?
Perhaps I'm having tunnel-vision with this, but this is supposed to be the easier direction, given by a straightforward argument.  Is there something I'm missing?

A: Okay, so if we assume that $g$ is order preserving, this isn't that difficult. I'm still not sure how to prove the result without this additional assumption, but some resources do have $g$ as order preserving.
Now when removing the dummy variables (or introducing them), I'll write the relevant function as $\mathrm{proj}_{a,b}$, defined by $\mathrm{proj}_{a,b}(a)=b$ and $\mathrm{proj}_{a,b}(\{\xi_0,\cdots,\xi_{|a|}\})=\{\xi_{i_0},\cdots,\xi_{i_m}\}$ when $\xi_0<\cdots<\xi_{|a|}$.
From here, as in the question, take $a_n=\bigcup_{i\le n}b_n$ and $t\in X_n$ iff (writing the transformed versions this time for clarity)
$$ \bigwedge_{i<n} f_{i+1}^{b_{i+1},a_n}(t)\in f_i^{b_i,a_n}(t)\text{.}$$
Thus $X_n\in E_{a_n}$ by Łoś's theorem, and so we get an order preserving $g$ where $g\mathord{"}s_n\in X_n$.  Because $g$ is order preserving, removing the dummy variables yields that for $i\le n$, $\mathrm{proj}_{a_n,b_i}(g\mathord{"}a_n)=g\mathord{"}b_i$.  In particular, $f^{a_n,b_i}_{i}(g\mathord{"}a_n)=f_i(\mathrm{proj}_{a_n,b_i}(g\mathord{"}a_n))=f_i(g\mathord{"}b_i)$.  And from here we can finally conclude that $\langle f_i(g\mathord{"}b_i):i\in\omega\rangle$ is a $\in$-decreasing sequence, contradicting well-foundedness.


text:
Q: Manipulate MS Excel tables Based on foreign Keys similar to SQL Inner-Join We are in the process of converting a SQL Server process to Postgres.  In the interim, we want to use MS Excel to manually update the tables and load to Postgres. The SQL Server process does an inner-join on two tables to match the foreign keys and initialize certain columns based on those fields.
Is there a way to simulate this process in MS Excel? I have researched some Excel functions such as VLOOKUP and INDEX MATCH but they fall a little short on getting the job done.
The SQL query is as follows:
UPDATE table1
SET OrderCount = 0,
    Cost = 0.
FROM table1.
INNER JOIN table2 ON table2.OrderId = table1.orderID
WHERE table2.shippingChoice = 1

A: If Table2 is distinct, then I think the following would work. But you'll want to check and confirm.
In picture below, I'm adding Column D and E as new columns.
Cell D3 formula:
=IF(VLOOKUP($A3,$G$3:$H$9,2) = 1,0,B3)

Drag is across and down, and you're done. If the shipping choice is 1, then use 0's, otherwise use the values.


text:
Q: How do you find the sine of the angle between two vectors? I do not know what the sine of the angle between two vectors is. I think it may be the vector created by connecting the tips of the two vectors but I am not sure.
How do you find the sine of the angle between two vectors?

A: In general for $\mathbf{a},\mathbf{b}\in\mathbb{R}^3$, we have
$$\|\mathbf{a}\times \mathbf{b}\|=\|\mathbf{a}\|\|\mathbf{b}\|\sin\theta,$$
where $\theta$ is the angle between $\mathbf{a}$ and $\mathbf{b}$.

A: Let $\theta$ be the angle between the two vectors. Now you can use,
$$\cos\theta={\vec v\cdot\vec w\over |\vec v||\vec w|}$$ and
$$\sin\theta=\sqrt{1-\cos^2\theta}.$$

A: Translate your two vectors so that their tails are at the origin.  Then draw a line through each of those two vectors.  The smaller of the two angles is the called the "angle between the two vectors".
Hint on how to find it:  The angle $\theta$ between two vectors $\vec u$ and $\vec v$ is given by the formula $$\theta = \arccos\left(\frac {\vec u\cdot\vec v}{|\vec u||\vec v|}\right)$$
Or -- here's a slightly harder way (because it involves calculating a cross product).  You know that $|\vec u\times \vec v| = |\vec u||\vec v|\sin(\theta)$, so find the cross product and all of the norms and then plug in.


text:
Q: Litmus test for checking if address range is in process address space? I am wondering if there is any simple/neat way in C to detect if a given memory range (A, A+len) falls under the process address space?
EDIT:
My use case is more for reverse engineering and locating some strings (or fixed sized structs) in memory. So even a hacky test will work right for me to narrow down my search.

A: On Linux, read /proc/$pid/maps. It contains a textual description of the memory ranges mapped by a process, e.g.
00400000-0040b000 r-xp 00000000 08:00 35402                              /bin/cat
0060a000-0060b000 r--p 0000a000 08:00 35402                              /bin/cat
0060b000-0060c000 rw-p 0000b000 08:00 35402                              /bin/cat
006ab000-006cc000 rw-p 00000000 00:00 0                                  [heap]
7f9a73235000-7f9a734fe000 r--p 00000000 08:00 949                        /usr/lib/locale/locale-archive
7f9a734fe000-7f9a736b8000 r-xp 00000000 08:00 18124                      /lib/x86_64-linux-gnu/libc-2.19.so
7f9a736b8000-7f9a738b8000 ---p 001ba000 08:00 18124                      /lib/x86_64-linux-gnu/libc-2.19.so
7f9a738b8000-7f9a738bc000 r--p 001ba000 08:00 18124                      /lib/x86_64-linux-gnu/libc-2.19.so
7f9a738bc000-7f9a738be000 rw-p 001be000 08:00 18124                      /lib/x86_64-linux-gnu/libc-2.19.so
7f9a738be000-7f9a738c3000 rw-p 00000000 00:00 0
7f9a738c3000-7f9a738e6000 r-xp 00000000 08:00 17952                      /lib/x86_64-linux-gnu/ld-2.19.so
7f9a73ad9000-7f9a73adc000 rw-p 00000000 00:00 0
7f9a73ae3000-7f9a73ae5000 rw-p 00000000 00:00 0
7f9a73ae5000-7f9a73ae6000 r--p 00022000 08:00 17952                      /lib/x86_64-linux-gnu/ld-2.19.so
7f9a73ae6000-7f9a73ae7000 rw-p 00023000 08:00 17952                      /lib/x86_64-linux-gnu/ld-2.19.so
7f9a73ae7000-7f9a73ae8000 rw-p 00000000 00:00 0
7ffde1b80000-7ffde1ba1000 rw-p 00000000 00:00 0                          [stack]
7ffde1bd5000-7ffde1bd7000 r--p 00000000 00:00 0                          [vvar]
7ffde1bd7000-7ffde1bd9000 r-xp 00000000 00:00 0                          [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]

There's a lot of information here, but what matters to you is the first two columns. The first one is an address range, and the second one is the access privileges it's mapped with.
Note that this has a distinct advantage over any approach based around triggering segfaults: it can be read from another process, and doesn't require any code to be added to the target process.


text:
Q: Antivirus for Ubuntu 18.04 with real-time protection I'm running Ubuntu 18.04, is there any antivirus that can protect me from virus when I'm installing packages from Ubuntu repository or install python packages with pip or conda? I know that there are third party tools for ClamAV, however I don't know which one to choose.

A: There are few antivirus software for Ubuntu but they are old such as clamav and comodo but you can check out Sophos.


text:
Q: Webhook Custom .NET I see a few tutorials on one of the newer features of .NET '15, called WebHooks. But mainly they are for GitHub and Dropbox. Does anyone know of any resources for making a WebHook that listens to a custom third party? I'm trying to set one up in the project and the configuration is proving difficult.
I've installed the Micrsooft ASP.NET Custom package, but when I run the route that I published to on Azure and specify "https://blahblah.azurewebsites.net/api/webhooks/incoming/custom"
I get
"Could not find a valid configuration for WebHook receiver 'custom' and instance ''. The setting must be set to a value between 32 and 128 characters long."
So it seems like the resource is there, how do I set up a receiver? is that the name of the controller?

A: I added
<add key="MS_WebHookReceiverSecret_Slack" value="VALUE_FROM_SLACK" />

and then things were rosey

A:
You have to add below in web.config under <appSettings>
<add key="MS_WebHookReceiverSecret_Custom" value="12345678901234567890123456789012" />


text:
Q: Draw abline through points from a loop I am trying to draw a line through points on a plot. Each plot is a chromosome. The x-axis is the sampleID and the y-axis is the correlation between one sample and sample 17. All Im trying to do is draw a linear trend line between the points. However when I use abline as below I get the errorbelow and Im not sure how to correct it. I've moved the abline to the correct bit of the code but no resolution>

 #Get the data as display it
 df <- read.delim("~/Desktop/SequencingScripts/Plots/blabla.txt", header=TRUE)
 df[,order(names(df))]
 ind = unique(as.character(df$chr))
 for(jj in ind){
  indic = which(df$chr == jj)
  plot(i, corrie, xlim=c(0,22), ylim=c(0.7,1), pch=19, type="s", xlab="sample", ylab="r",     main=jj)
  for(i in 3:16) {
corrie = (cor(df[,i][indic], df[,15][indic]))
points(i,corrie)
 }
abline(lm(corrie ~ i))
}

Error in int_abline(a = a, b = b, h = h, v = v, untf = untf, ...) :
  'a' and 'b' must be finite

Example data:
 chr         column3     column4      column5  etc..
 chr9      14.44324324  11.66666667 14.13333333
 chr9      22.93333333  7.20000000  9.13333333
 chr9      15.60000000  5.86666667  5.73333333
 chr10     3.06666667   8.46666667  1.80000000
 chr12     10.333333        12.133333   7.000000
 chr18    4.60000000    5.66666667  8.40000000
 chr9      16.33333333  13.20000000 19.86666667
 chr9      3.66666667   10.73333333 17.73333333
 chr9      15.06666667  11.80000000 14.200000
chr2      7.800000      10.933333   7.066667

A: This is a blind attempt at solving your problem as you didn't give any example data. My recommendation would be that you format the data that you want to plot before your start plotting.
In your example you want to calculate the correlations using the for-loop over i. So you can just do this within this loop and save all the correlations in a data.frame. When you have gathered all the data that go into the plot, you can draw these by calling plot and abline on the new data.frame.
This you can repeat for all chromosomes (the loop over jj). You can add a line that saves the plot to separate in that loop.
for(jj in ind){
  indic <- which(df$chr == jj)

  plot.df <- data.frame()
  for(i in 3:16) {
    corrie <- (cor(df[,i][indic], df[,15][indic]))
    plot.df <- rbind(plot.df, c(i, corrie))
  }
  colnames(plot.df) <- c("sample", "cor")

  plot(cor ~ sample, data=plot.df, xlim=c(0,22), ylim=c(0.7,1), pch=19,
       type="p", xlab="sample", ylab="r", main=jj)
  abline(lm(cor ~ sample, data=plot.df))
}


text:
Q: How to control the source of AWS network load balancer? 2 questions on NLB in AWS

*

*I have a requirement to use NLB in front of the EC2 which runs MYSQL. This EC2 is in private network. I just want to allow NLB to be accessed by some particular internet IP. If it's ALB, I can use security group to do this. However, without security group in NLB, how can I achieve this?

*In this setup, I connect to NLB from my PC and reach to that MYSQL EC2. To make it success, I find that I have to allow 0.0.0.0/0 in the incoming rule of the EC2 security group instead of just putting my PC IP. I thought my PC IP should be brought to EC2 directly through NLB. Is it not true? I dont want to allow 0.0.0.0/0 in EC2 security group. Is there any better way?
Thanks!

A: The security group evaluations are performed by the instances security groups for the Network Load Balancer. You would need to add the IP addresses you would like to communicate with the NLB to your instances, as long as your instance is in a private subnet this will prevent any client directly interacting with the host.

Network Load Balancers do not have associated security groups. Therefore, the security groups for your targets must use IP addresses to allow traffic from the load balancer.

More information is available in the Register targets with your target group documentation.

A: The only way to block the traffic in your case is to have the IPs to which you want to allow access in the EC2 SG.
However you need to account for the fact that there is a difference on the IP address from which the request will come from and thus will be evaluated from the EC2 SG based on how you have configured the target group of the NLB and more specifically on whether you have set up the target type to be instance or ip, as there is a difference in the NLB behaviour.

*

*If the target type is set to instance, the NLB will pass the traffic to your instance as is, and the EC2 SG will see your locap PC public IP address, and if there is a rule to allow it you will be able to connect

*If the target type is set to ip, the NLB is doing an NAT, and the EC2 SG will actually see the private IP of the NLB as a source IP for the incoming traffic.

Take a look at the Source IP Preservation in the NLB Target Group documentation.
There is a similar discussion in this question.


text:
Q: Very slow scripts (with weird errors) after a recovery of a previous version of a spreadsheet
I was having problems with a spreadsheet, and I decided to go back to a previous version...
However, I noticed that after this restoration, the spreadsheet SCRIPTS were SUPER SLOW (often shutting down by timeout) and presenting errors that I've never seen! (like the ones I posted above). It's like the script is having a hard time finding the spreadsheet...
Does anyone know how I can resolve this? I've tried everything!
Look at this simple script, which starts quickly, but on the first line it takes 2 MINUTES to perform!!! (Full script after screenshot)

Script:
    function atualizarDisparos() {
Logger.log("step1")
  var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('DB');
Logger.log("step2")

  var startRow = 27; // Lembrar de tirar o cabeçalho
  var quantidadeDeViveiros = 16;
  var lastRow = startRow + quantidadeDeViveiros; // figure out what the last row is

  Logger.log("step4")

  var startColumn = 2; // Lembrar de tirar as bordas
  var lastColumn = ss.getLastColumn(); // figure out what the last column is
  var numColumns = lastColumn-startColumn+1; // subtrair um pelo outro

  var dataRange = ss.getRange(startRow, startColumn, quantidadeDeViveiros, numColumns)
  var data = dataRange.getValues();

  var povoamento ="";
  var bioensaio ="";
  var despesca ="";
  var povoadoHoje ="";
  var atualizar = 0;

  var biomassaDespesca = 2000;
  var tamanhoDespesca = 18;
  var tempoBioensaio = 3;
  var diasParaVenda = 15;

Logger.log("step4")

  for (var linhaAtual = 0; linhaAtual <= quantidadeDeViveiros-1; linhaAtual++) {
    var row = data[linhaAtual];
    Logger.log("step5")
    if (row[7] == 0 || row[35] < diasParaVenda) { //==== POVOAMENTO
      var povoamento = povoamento + "V" + row[0] + " (" + row[12] + "kg de " + row[14] + "g) || "
      var atualizar = 1;
    }

    if (row[7] != 0 && row[9] == "" && row[11] <= 3) { //=== BIOENSAIO
      var dataPovoamento = new Date(row[5]);
      var dataBioensaio = dataPovoamento.setDate(dataPovoamento.getDate()+tempoBioensaio-1);
      var dataBioensaio = new Date(dataBioensaio);
      var dataHoje = new Date();
      Logger.log(dataBioensaio)
      Logger.log(dataHoje)

      if (dataHoje >= dataBioensaio) {
        var dataBioensaio = Utilities.formatDate(dataBioensaio, Session.getScriptTimeZone(), 'dd/MM/yy');
        var bioensaio = bioensaio + "V" + row[0] + " (Tirar Bioensaio: " + dataBioensaio + ") || "
      }
      var atualizar = 1;
    }

      if (row[7] != 0 && row[8] == 0) { //=== POVOADO HOJE
      var dataPovoamento = new Date(row[5]);
      var dataPovoamento = new Date(dataPovoamento);
      var dataPovoamento = Utilities.formatDate(dataPovoamento, Session.getScriptTimeZone(), 'dd/MM/yy');
      var povoadoHoje = povoadoHoje + "V" + row[0] + " (Povoado dia: " + dataPovoamento + ") || "

      var atualizar = 1;
    }

    if (row[14] >= 8 && row[35] < diasParaVenda) { //=== DESPESCA
      var despesca = despesca + "V" + row[0] + " (" + row[12] + "kg de " + row[14] + "g) || "
      var atualizar = 1
    }
  }

  if(atualizar == 1) {
    var ssPC = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('PC');
    ssPC.getRange('k107').setValue(povoamento);
    ssPC.getRange('k108').setValue(bioensaio);
    ssPC.getRange('k109').setValue(despesca);
    ssPC.getRange('k123').setValue(povoadoHoje);
  }
}


text:
Q: Compilation Error using Custom Sort inside Class I am trying to use custom sort inside a class,
such as sort(arr,arr+n,cust);
inside a class function.
Custom sort looks like this:
bool cust (int a, int b) {
  return pos[a]<pos[b];
}

Where pos is an array inside class.
But it does not compile, and gives compilation error

"invalid use of non-static member function"
  how to get rid of compilation error.

my code -> https://pastebin.com/W1zw0A5s
I have tried writing:
static bool cust (int a, int b) {
     /* same code */
}

which hasn't helped.

A: According to the pastebin link, this function is a member function in your class. You need to bind the this pointer to it in order to use it:
sort(sa,sa+n, [this](int a, int b){ return this->sufCmp(a,b); } );