text:
Q: Android wakeLock issue I have foreground service.
Manifest contains this permissions:
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />

In Splash activity i request this permisssion once:
Intent intent = new Intent();
        String packageName = context.getPackageName();
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        if (!pm.isIgnoringBatteryOptimizations(packageName)) {
            intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
            intent.setData(Uri.parse("package:" + packageName));
        }
        context.startActivity(intent);

In onCreate service method i calling createAlarm method:
private void createAlarm() {
    wakeupIntent = PendingIntent.getBroadcast(getBaseContext(), 0, new Intent("com.android.internal.location.ALARM_WAKEUP"), 0);
    powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getPackageName() + ":TrackService");
    wakeLock.acquire();

    dozeHandler = new Handler();
    Runnable heartbeat = new Runnable() {
        @Override
        public void run() {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
                try {
                    if (powerManager != null && powerManager.isDeviceIdleMode()) {
                        try {
                            Log.d("MainService", "In IDLE MODE");
                            wakeupIntent.send();
                        } catch (SecurityException | PendingIntent.CanceledException e) {
                            Log.d("MainService", "Heartbeat location manager keep-alive failed", e);
                        }
                    } else if (!powerManager.isDeviceIdleMode()) {
                        Log.d("MainService", "Device alive");
                    }
                } finally {
                    if (dozeHandler != null)
                        dozeHandler.postDelayed(this, 5000);
                }
        }
    };
    heartbeat.run();

    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(this, MyWakefulReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
    if (Build.VERSION.SDK_INT >= 23) {
        alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, 30000, pendingIntent);
    } else {
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, 30000, pendingIntent);
    }
}

And after all initializations calling setWakeLock:
@SuppressLint("WakelockTimeout")
public void setWakeMode(Context context, int mode) {
    boolean wasHeld = false;
    if (wakeLock != null) {
        if (wakeLock.isHeld()) {
            wasHeld = true;
            wakeLock.release();
        }
        wakeLock = null;
    }
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(mode | PowerManager.ON_AFTER_RELEASE, MainService.class.getName());
    wakeLock.setReferenceCounted(false);
    if (wasHeld) {
        wakeLock.acquire();
    }
}

I am confused in these functions and as a result I do not get awakening, please help me.

A: boolean wasHeld = false;
if (wakeLock != null) {
    if (wakeLock.isHeld()) {
        wasHeld = true;
        wakeLock.release();
    }
    wakeLock = null;
}

You are only setting 'wasHeld' to true if 'wakeLock.isHeld()'. You are only calling acquire if 'wasHeld' is true:
if (wasHeld) {
    wakeLock.acquire();
}

Take out the 'if (wasHeld)...' and just call acquire no matter what, I'm guessing wasHeld is always false, so acquire never gets called.
If it still doesn't work, as per AndroidStudio documentation you can just:
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
        "MyApp::MyWakelockTag");
wakeLock.acquire();

and call
wakeLock.release();

when finished.


text:
Q: Formatting dates in org mode How do I format dates in emacs org-mode?
For example, in the following table, I would like the dates to appear as "Aug 29", or "Wed, Aug 29" rather than "<2012-08-29 Wed>"
#+ATTR_HTML: border="2" rules="all" frame="border" align="center" cellpadding="6"
|------+------------------+---------+-------|
| Week | Date             | Speaker | Title |
|------+------------------+---------+-------|
|    / | <>               | <>      | <>    |
|    0 | <2012-08-29 Wed> |         |       |
|    2 | <2012-09-05 Wed> |         |       |
|    3 | <2012-09-12 Wed> |         |       |
|    1 | <2012-09-19 Wed> |         |       |
|    4 | <2012-09-26 Wed> |         |       |
|    5 | <2012-10-03 Wed> |         |       |
|    6 | <2012-10-10 Wed> |         |       |
|    7 | <2012-10-17 Wed> |         |       |
|    8 | <2012-10-24 Wed> |         |       |
|    9 | <2012-10-31 Wed> |         |       |
|   10 | <2013-03-07 Thu> |         |       |
|------+------------------+---------+-------|
#+TBLFM: @3$1 = 0::$1 = @-1$1 + 1 ::@3$2 = <Aug 29, 2012>::$2 = @-1$2 + 7

A: Custom date format should help. It will show timestamps with your own custom formatting.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to format postgreSQL queries in a python script for better readability? I have another question that is related to a project I am working on for school. I have created a PostgreSQL database, with 5 tables and a bunch of rows. I have created a script that allows a user to search for information in the database using a menu, as well as adding and removing content from one of the tables.
When displaying a table in PostgreSQL CLI itself, it looks pretty clean, however, whenever displaying even a simple table with no user input, it looks really messy. While this is an optional component for the project, I would prefer to have something that looks a little cleaner.
I have tried a variety of potential solutions that I have seen online, even a few from stack overflow, but none of them work. Whenever I try to use any of the methods I have seen and somewhat understand, I always get the error:
TypeError: 'int' object is not subscriptable
I added a bunch of print statements in my code, to try and figure out why it refuses to typecast. It is being dumb. Knowing me it is probably a simple typo that I can't see. Not even sure if this solution will work, just one of the examples I saw online.
try:
        connection = psycopg2.connect(database='Blockbuster36', user='dbadmin')
        cursor = connection.cursor()
except psycopg2.DatabaseError:
        print("No connection to database.")
        sys.exit(1)

cursor.execute("select * from Customer;")
tuple = cursor.fetchone()
List_Tuple = list(tuple)

print("Customer_ID | First_Name | Last_Name | Postal_Code | Phone_Num | Member_Date")
print(List_Tuple)
print()
for item in List_Tuple:
        print(item[0]," "*(11-len(str(item[0]))),"|")
        print(item)
        print(type(item))
        print()
        num = str(item[0])
        print(num)
        print(type(num))
        print(str(item[0]))
        print(type(str(item[0])))

cursor.close()
connection.close()

I uploaded the difference between the output I get through a basic python script and in the PostgreSQL CLI. I have blocked out names in the tables for privacy reasons. https://temporysite.weebly.com/
It doesn't have to look exactly like PostgreSQL, but anything that looks better than the current mess would be great.

A: Use string formatting to do that. You can also set it to pad right or left.
As far as the dates use datetime.strftime.
The following would set the padding to 10 places:
print("{:10}|{:10}".format(item[0], item[1]))


text:
Q: Ошибка при передаче client session aiohttp Пытаюсь передать сессию между функциями в python, но происходит ошибка:
Exception has occurred: RuntimeError
Session is closed
  File "C:\Users\Maxim\Desktop\connserv.py", line 31, in edit_db
    async with client.get(url=url, params=params) as resp:
  File "C:\Users\Maxim\Desktop\connserv.py", line 43, in <module>
    asyncio.run(edit_db())

Код который я использую:
from aiohttp import ClientSession, client
import asyncio

async def send_request():
    url = ''
    params = {
        'email': "",
        "pass": "",
        "authorization": "true"
    }

    async with ClientSession() as client:
        async with client.post(url, params=params) as resp:
            return client

async def edit_db():
    client = await send_request()

    url = ''
    params = {
        "ID": "248098",
        "data[name]": "Statistics [ Global Timezones Bot ]",
        "data[text]": f"""reefe""",
        "action": "edit_record",
        "data[category_ID]": "82627"
    }

    async with client.post(url=url, params=params) as resp:
        print(resp.text)

if __name__ == "__main__":
    asyncio.run(edit_db())

A: После
return client

контекст менеджер with закрывается.
client = ClientSession()
....
return client


text:
Q: Which primes $p$ in $Z$ remain primes in $Z[\sqrt{-1}]$? Which primes $p$ in $Z$ remain primes in $Z[\sqrt{-1}]$? I don't just want to know which ones, I want to know how I find them.

A: Since $2=(1+i)(1-i)$, let's consider the odd primes.
Suppose that $p=(a+bi)(a-bi)=a^2+b^2$. Since $p$ is odd and the only quadratic residues $\bmod{\,4}$ are $0$ and $1$, we must have that $p\equiv1\pmod{4}$. Thus, any $p\equiv3\pmod{4}$ is also prime in the Gaussian integers.
In fact, it is true that if $p\equiv1\pmod{4}$ then $p=a^2+b^2$ for some $a$ and $b$. Thus, if $p\equiv1\pmod{4}$, it is not a prime in the Gaussian integers.

Here is an excerpt from a paper I wrote a while ago that proves the last claim.

Claim: if $p$ is a rational prime, then either $p$ is a Gaussian prime or $p$ is the product of two conjugate Gaussian primes.

Proof: Since no rational prime other than $p$ can divide $p$, if $p$ is not a Gaussian prime, then the Gaussian prime factors of $p$ must appear in conjugate pairs.  If there were $k$ conjugate pairs, each pair could be multiplied together to yield $k$ rational integers whose product is $p$.  Thus, $k$ must be $1$.  Therefore, if $p$ is not a Gaussian prime, $p$ is the product of a conjugate pair of Gaussian primes.
QED

Lemma: Suppose $p$ is a rational prime, then $p$ is a Gaussian prime if and only if $p\equiv3\pmod4$.

Proof: Suppose $p$ is not a Gaussian prime, then $p = (u+iv)(u-iv) = u^2 + v^2$ for some Gaussian prime $u+iv$.  Thus, as the sum of two squares, $p\not\equiv3\pmod4$.

Suppose $p\not\equiv3\pmod4$.  Then either $p = 2$ or $p\equiv1\pmod4$.  If $p=2$, then $p=(1+i)(1-i)$, and $p$ is not a Gaussian prime.  If $p\equiv1\pmod4$, then $(p-1)/4$ is an integer.  The equation $x^{(p-1)/2} + 1 = 0$  has $(p-1)/2$ solutions in $\mathbb{Z}_p$.  For any such solution, $x$, if $m=x^{(p-1)/4}$, then $m^2+1\equiv0\pmod p$. That is, $p\,|\,(m+i)(m-i)$, but $p$ divides neither $m+i$ nor $m-i$.  Therefore, $p$ is not a Gaussian prime.
QED

A concern has been raised regarding the claim that factors appear in conjugate pairs.

Suppose that $(a+bi)(c+di)=k\in\mathbb{Z}$, where $\gcd(a,b)=1$ and $b\ne0$. Since $ad+bc=0$, we have
$$
c+di=-\frac db(a-bi)
$$
and therefore,
$$
\begin{align}
bk
&=-d(a+bi)(a-bi)\\
&=-d(a^2+b^2)
\end{align}
$$
Since $\gcd(a,b)=1$, $\gcd(a^2+b^2,b)=1$. Therefore, $(a+bi)(a-bi)=a^2+b^2\,|\,k$.

A: $1.$ The prime $2$ can be expressed as $(1+i)(1-i)$.
$2.$ Primes of the form $4k+3$ don't split, and so remain prime. To see this, suppose to the contrary that such a prime $q$ can be expressed as $(a+bi)(c+di)$, where neither $a+bi$ nor $c+di$ is a unit. Then taking norms we find that $a^2+b^2=q$. This cannot happen.
For if $a^2+b^2=q$, then $a^2\equiv -b^2 \pmod{q}$. Multiplying by the inverse of $b$, we get that $-1$ is a quadratic residue of $q$. But it isn't.
$3.$ For primes $p$ of the form $4k+1$, one can use Fermat's result that every prime of the form $4k+1$ can be expressed as the sum $a^2+b^2$ of two squares. That gives the splitting $p=(a+bi)(a-bi)$.
Or else (better) use the standard fact that if $p$ is of the form $4k+1$, then $-1$ is a quadratic residue of $p$.  It follows that there are integers $x$ and $k$ such that $x^2+1=pk$. Note that $x^2+1=(x+1)(x-i)$.
If $p$ is a Gaussian prime, then since $p$ divides $x^2+1$, it must divide $x+i$ or $x-i$. But it is clear that $p$ divides neither, so $p$ cannot be a Gaussian prime.

A: Show the following:

*

*A rational prime $p$ factors nontrivially if and only if $p=\pi\bar{\pi}$ for some $\pi\in{\bf Z}[i]$. Hint: suppose you have a factorization, notice that $p$ is invariant under conjugation, pair off the factors.

*$p=\pi\bar{\pi}$ for some $\pi\in{\bf Z}[i]$ if and only if $p=a^2+b^2$ for some integers $a,b\in{\bf Z}$.

Consider Fermat's theorem on sums of two squares (and the case $p=2$ separately).


text:
Q: Insert into hive partitioned table SemanticException First I create a hive partitioned table:
hive> create table partition_table
    > (sid int ,sname string ,age int)
    > partitioned by (sex string)
    > row format delimited fields terminated by',';
OK
Time taken: 1.232 seconds

The table desc is given below:
 hive> desc partition_table;
    OK
    sid                     int
    sname                   string
    age                     int
    sex                     string

# Partition Information
# col_name              data_type               comment

sex                     string
Time taken: 0.34 seconds, Fetched: 9 row(s)

and then I insert some data into this table but it doesn't work.
hive> insert into table partition_table partition(sex='M')select sno ,sname ,age from student1 where sex ='M';
FAILED: SemanticException [Error 10006]: Line 1:44 Partition not found ''M''

To avoid this I wrote the following command and then executed my insert command, even then I get the same error repeatedly.
set exec.dynamic.partition=true;
set exec.dynamic.partition.mode=nonstrict;

A: add the partition before loading:
ALTER TABLE partition_table ADD PARTITION( sex= 'M' );
insert into table partition_table partition(sex='M') select sno ,sname ,age from student1 where sex ='M';

or try dynamic partitioning:
set hive.exec.dynamic.partition=true;
INSERT OVERWRITE TABLE partition_table PARTITION (sex)
SELECT sid, sname, age, sex
FROM student1;


text:
Q: Print RDLC report from server in C# I'm creating a RDLC report and printing it from ASP.Net. When i try this in local machine it works fine. But when deploying in the server the printer settings are not valid.
//Code
 if (m_streams == null || m_streams.Count == 0)
            throw new Exception("Error: no stream to print.");

        PrintDocument printDoc = new PrintDocument();

       // printDoc.PrinterSettings.PrinterName = "HP LaserJet 3055 PCL5";

        if (!printDoc.PrinterSettings.IsValid)
        {
            throw new Exception("Error: cannot find the default printer.");
        }
        else
        {
            printDoc.PrintPage += new PrintPageEventHandler(PrintPage);
            m_currentPageIndex = 0;
            printDoc.Print();
        }

From the above code it throws me an exception "cannot find default printer". Tried to add the printer name which exists in the client machine but still didn't work.
I need to print the report in the client machine.
Don't know where to change. Any help?

A: I belive that you are doing something you arent' supposed to do.
If you have a ASP.NET Website, that has a RDLC report in the site. If I, access that report, I would like to print in my machine, not in the server. Are you sure, that you want to make the server to print the report? Shouldn't the client/browser to issue the print command?
If your server is in a datacenter, and I'm at my home, where should the printing be done? Unless you want to print in the server (Mail Merge stickers, for example).

A: As far as I know it is not possible to access the client's printer settings. What you are doing is access the servers printer, which, if I am right, is not installed.
You can print accesing browser/ javascript functionality by calling window.print() in javascript,because the browser is running client-side and has access to the printers. But accessing the clients system resources directly would be a huge security flaw.
Maybe there is an obscure workaround/hack, but it would be a bad solution


text:
Q: Gitlab schedule jobs with `rules` are not running and can't be triggered I would like to run one or multiple jobs within a scheduled context and therefore used the specific rule to declare it like this.
Problem is that the pipeline will neither be triggered by my schedule configuration nor when i manually trigger it via the scheduling pipeline UI. I just don't see any triggered scheduled pipeline at all.
Gitlab Version: 12.9.2
gitlab-ci.yml (partially):
workflow:
rules:
    -   if: $CI_COMMIT_TAG
    -   if: $CI_COMMIT_BRANCH

non-scheduled-job:
...
rules:
    -   if: '$CI_PIPELINE_SOURCE != "schedule"'

scheduled-job:
...
rules:
    -   if: '$CI_PIPELINE_SOURCE == "schedule"'
        when: always
    -   if: '$CI_PIPELINE_SOURCE != "schedule"'
        when: never

I know that the second rule for the scheduling-job is not needed but even without this the pipeline is not properly running.

A: Unfortunately, as for Workflows logic, Gitlab is very twiggy.
If you use Workflow section and Rules conditions for your jobs, you have to obviously declare 'Scheduled' type of pipeline in the Workflow section to enable it in your configuration:
workflow:
    rules:
      - if: '$CI_PIPELINE_SOURCE == "schedule"'
      ...

Or you may enable all types of pipelines in your configuration just adding at the end of workflow:rules
workflow:
  rules:
    ...
    - when: always

In other way, use may use except/only notation for scheduled jobs and it will work, but only if your workflow conditions met:
only:
  - schedules

This approach may appear merging conflicts if you use include option.
Because merging lets you extend and override dictionary mappings, but you cannot add or modify items to an included array. Thus you have to obviously declare all previously added workflow:rules array items in the last included YAML or use anchors.
See issue for details.

A: You can use only.
E.g.
scheduled-job:
  only:
    - schedules

https://docs.gitlab.com/ee/ci/pipelines/schedules.html
But, when reusing the snippet in other jobs,
do not use rules togetther with only / except.


text:
Q: What is the best way to display the data on jQuery that will look like console with scroll bar I had to make this text adventure game for school project. I would like to make my game display the text in div box, using jQuery, that feels like you were typing in a terminal console with the scrolling bar when the text append.
Which one is the best for me using

*

*append()

*insertBefore/After()

*text()

*addClass()

*appendTo()

*clone()


text:
Q: Week() function in sql script I am using sql server 2005. I just want to know is there something we can get the week number for the particular month. Example Date = '2008-10-16' Is there something we can have SELECT WEEK(Date). Or any better suggestion.

A: SELECT DATEPART( week, '2008-10-16')

A: You can do it this way:
SET @weeksinmonth=datediff(week, @date, @lastdate) + 1

That is a copy-and-paste out of one of my stored procedures.

A: select (datepart(dd,'2008-10-08')-1) / 7 + 1


text:
Q: How to assign a word to execute a particular command I am very new to bash, I don't even know if what I want is possible.  Sorry in advance if unknowingly I am asking for too much and  it isn't possible.
I execute many different bash scripts for testing and learning process too frequently after doing small edits.
It's really annoying to type the whole command over and over again every minute, it wastes lot of my time.
For example,
currently to execute the script I always enter
su -c sh /sdcard/downloads/script1.sh

Is there anyway I can assign this whole command to be initiated by just entering a single word?  I would like to just type e.g.
script1

This should actually execute
su -c sh /sdcard/downloads/script1.sh

(or any defined command for that instance).
In short, there would be many pairs of a single word and it's corresponding command so that it will save my time.
And this thing should be permanent.
Even if I close the terminal and reopen it and enter my assigned word, it should run the corresponding defined command.
I hope there's a way to do it.

A: Create alias in your ~/.bashrc file:
alias script1='su -c sh /sdcard/downloads/script1.sh'

The alias will then be available in the next shell session that your start.

A:
alias script1="su -c /sdcard/downloads/script1.sh && su -c
  /sdcard/downloads/script2.sh'. Does this seem correct ?

Not really. That is probably not the road to take. It is just not practical. It works for this alias and these two scripts at their present location, but you don't want to create aliases for every script you call. You mention "many different scripts for learning".
You have to organize your tab completion, command history, PATH, aliases, functions, scripts, bash login (.bashrc). It does not take much, but it has to be coordinated.
nb: the alias command itself is tab-completable. And readline function shell-expand-line can expand the alias before you execute. That means you can scri<tab><M-C-e> and you get the whole line, so you can edit before you hit enter. Just to show what is possible.
To repeat special commands you rather use command history. To execute normal scripts you use shell functionality like alias, PATH, functions and other scripts.


text:
Q: How can I setup nightly backups via the command line? I'm running Ubuntu Server and I'm looking for an efficient way of performing nightly backups of particular directories using cron.  However, since the computer isn't always on, I'd like it to just run when the computer is on and to keep the last 5 backups.  Would I need to use a bash script of some kind to achieve this?

A: You can use tar and rsync for a combination of full & incremental backups and there is a tutorial here that sets it up to do nightly / weekly backups using cron.

A: rsync is an amazing backup tool that has inspired a lot of backup utilities, from easy bash scripts as referenced above to GUI applications that handle the grunt work for you. For workstations/toys, my favorite backup utility has got to be deja-dup, just for the straightforwardness and the simplified UI that i can comfortably recommend to my parents (the UI standard by which all applications must be judged :P ).
For headless systems, I'd go with rdiff-backup or duplicity, the app that powers deja-dup's backend.
References

*

*http://www.nongnu.org/rdiff-backup/

*http://live.gnome.org/DejaDup

*http://duplicity.nongnu.org/


text:
Q: A post is not rendering properly I don't have the knowledge to use the correct terminology, but the post I earned 2cool4skool on a site I have not visited is greyed out on the "home" and "questions" pages with what looks like some sort of error symbol on the status-bydesign tag.

When I open it, the tags are normal.
It does have a pending edit, but not sure if it's related.
Galaxy XCover Pro, Android version 12, in both "full site" and "mobile" views and using Google Chrome app version 107.0.5304.91.

A: That's what an ignored tag looks like when you choose "Gray out questions in your ignored tags" when editing your ignored tags list.
I've gone ahead and ignored the bug tag and had a look at this post from the /questions page. Here's how it looks:

That little eye with a cross through it indicates that it's one of your ignored tags.
If you'd rather completely hide such questions, you can choose the  "Hide questions in your ignored tags" option when editing your ignored tags:


text:
Q: How to type event on scroll handler react typescript? I have a page with lazy loading. There is a scroll listener inside it. I need to type event in the scrollHandler function.
const scrollHandler = (e: any) => {
        let scrollHeight = e.target.documentElement.scrollHeight;
        let scrollTop = e.target.documentElement.scrollTop;
        let innerHeight = window.innerHeight;
        if (scrollHeight - (scrollTop + innerHeight) < 100) {
            dispatch(setStatus(Status.LOADING));
        }
    };

    useEffect(() => {
        document.addEventListener('scroll', scrollHandler);
        return function () {
            document.removeEventListener('scroll', scrollHandler);
        }
    });

I tried Event type. It returns me this error:

TS2339: Property 'documentElement' does not exist on type 'EventTarget'.

A: You have to convince TypeScript that the element you're referring to is indeed a Document element. You can do that this way:
const target = e.target;
if (!(target instanceof Document)) return;

For the lines that come later, TS would know that target is a Document element and should have a property named documentElement.


text:
Q: Javascript Facebook API: Caching User Data Is there a way I can cache user info on the clients system? For example, if I had a list of all of the users friends..via fql...is there a way to save that somewhere so that I don't have to request it on every use of the app?
I apologize if I've used incorrect terminology I'm an amateur programmer.

A: yes, you can use one of the new HTML5 features

*

*http://ajaxian.com/archives/webkit-does-html5-client-side-database-storage

*http://html5demos.com/storage
You can also check to see if the broswer doesn't have that available, and use a server-side caching mechanism to your advantage such as memcached or application variables.

A: Aside of HTML5 local storage (as suggested by DCMS in other answer) there is also SQLite support in WebKit browsers and userData in older versions of Internet Explorer.
You can use something like jStorage (it have support for jQuery, Prototye and MooTools) to support client-side storage in most browsers.


text:
Q: How to create a 4 node cluster in Google cloud to run an HPC application I think i read every document Google cloud has but not finding an answer. Everything seems to be targeted for web services.
I want to create a cluster of 4 identical nodes in google cloud engine and run an MPI pingpong or an MPI application. I'm very new to cloud computing
Ideally if i can use a "gold" instance that i can set up with the tools i need and use it to create the cluster.
Any help is appreciated it.
Thanks

A: There are a number of compute options on Google Cloud. It sounds like you might be looking at App Engine, which is Google's platform-as-a-service offering. As you indicated, it is definitely geared towards creating web applications. Instead you should consider either Compute Engine or Kubernetes Engine (also known as Container Engine). Compute Engine allows you to create virtual machines, which will absolutely let you install whatever software you choose. You can select from a number of different operating systems for your virtual machine, including Debian, CentOS, Ubuntu, Red Hat, SUSE and Windows. You can create your first virtual machine, install your software and configure the virtual machine the way you'd like, take a snapshot of it, and then generate additional virtual machines from the snapshot.
If your environment lends itself to being run in a container, you might want to consider Kubernetes Engine. Kubernetes Engine allows you to create Docker-style containers, which are more lightweight and boot faster than traditional VM's. If you want your application to be able to launch additional nodes and scale up rapidly, Kubernetes Engine would definitely be worth investigating.
Google's Cloud website (https://cloud.google.com) has a ton of information on both of these options. If you'd like more structured learning, I highly recommend Linux Academy (https://linuxacademy.com). They have an excellent Introduction to Google Cloud Platform course, and they offer a seven day free trial.

There are two ways to create duplicate VM's: Instance groups or Snapshots. Given what you're trying to accomplish, I think snapshots will be your best bet.
Once your VM has all your software installed and configured, you need to take a snapshot of it. You can take snapshots with the VM running, but I think it's cleaner to shut the VM down first.
To create the snapshot, go to https://console.cloud.google.com. Make sure you are in the same project as your original VM. You can check what project you're in by looking to the right of the words "Google Cloud Platform" up in the blue bar at the top of your browser screen. It's a dropdown menu, so if you are not in the correct project you can change to it. Then, to the left of the words "Google Cloud Platform" click the hamburger menu (the three horizontal lines). Scroll up and down until you find "Compute Engine". Hover your mouse cursor over it and another menu should pop out to the right. Click "Snapshots". Assuming you haven't created any other snapshots, there should be a blue "Create snapshot" button in the center of the screen. Click it. You can name it whatever you'd like, just as long as you use only lower case letters, numbers and hyphens. Click on the "Source disk" dropdown, and you should see the name of the VM you already created. Select it. You can leave everything else at the default and click the blue "Create" button. Once the snapshot has been created, a green check will appear to the left of the snapshot name.
Now you can create the rest of your VM's. On the left menu, click "VM instances". You should see the VM you already created. In the menu above the list of VM's, click the "CREATE INSTANCE" button. You're going to build this VM pretty much the same way you built the first, but with one difference. In the section titled "Boot disk", click the "Change" button. A list should pop up with all of the different operating systems that Google Cloud offers. At the top of the list are the options "OS images", "Application images", "Custom images", "Snapshots", and "Existing disks". Click "Snapshots". You should see the snapshot you created. Click it so that it is selected. Feel free to change the size of the disk if necessary, and then click the blue "Select" button. Change any other settings that may be appropriate for your VM, and then click the blue "Create" button. It will be created using your snapshot as a source, so it should be virtually identical to your original VM. Continue creating additional VMs using your snapshot as the source until you have created the amount you require.


text:
Q: ASP.NET Get Current Page Object Trying to get the current page object from a custom class and the only code I can find is:
Dim page As UI.Page = TryCast(HttpContext.Current.CurrentHandler, UI.Page)

However the result is Nothing (also tried HttpContext.Current.Handler). Is there another reference someone can suggest for me to look at or does someone shed some light on why my code is returning Nothing.
NB: If I use CType instead the exception it returns is:
    Unable to cast object of type 'System.Web.WebPages.WebPageHttpHandler' to type 'System.Web.UI.Page'

A: Try this code
Dim page As Page = TryCast(HttpContext.Current.Handler, Page)
If page IsNot Nothing Then
    ' Use page instance.
End If


text:
Q: Is it possible to a molecule go through spaces between a solid material without breaking it? Imagine the following system:
We have a 3-dimensional box that is completely closed and have no connection to the environment outside of it. The walls of this box are made by some material $R$. Inside of that box, we only have a bunch of molecules of some random element $A$.
Assume that the state of $R$ is solid and $A$ is Gas.
If we increase the temperature of the molecules of the element $A$, we're going to increase the pressure on the walls, and probably with some high temperature, we are going to break the material $R$.
My question is:
Is there a chance of any molecule $A$ make a path through the spaces between the molecules of $R$ without breaking it?
If so, for what $A$ (GAS) and $R$ (SOLID) is that possible?
Thanks!

A: It is permeation, the ability to permeate

In physics and engineering, permeation (also called imbuing) is the penetration of a permeate (such as a liquid, gas, or vapor) through a solid. It is directly related to the concentration gradient of the permeate, a material's intrinsic permeability, and the materials' mass diffusivity. Permeation is modeled by equations such as Fick's laws of diffusion, and can be measured using tools such as a minipermeameter.

If you have a specific material you have to search for it specifically. An example is here.


text:
Q: specify armeabi-v7a, but jni continue to build x86_64 I am doing jni by using the third lib, where jni lib: libLivenessDetectorJni.so depend on liblivenessdetector.so(a third lib only in armeabi-v7a).
I specify abi build only under armeabi-v7a in gradle:
externalNativeBuild {
            cmake {
            cppFlags "-std=c++11 -frtti -fexceptions"
            abiFilters "armeabi-v7a"
            }
        }

But after building armeabi-v7a(success), it continues to build x86_64(fail), why?
> Task :common-silent:externalNativeBuildDebug
Build LivenessDetectorJni armeabi-v7a
[1/2] Building CXX object CMakeFiles/LivenessDetectorJni.dir/LivenessDetectorJni.cpp.o
[2/2] Linking CXX shared library /home/jnitest/common-silent/build/intermediates/cmake/debug/obj/armeabi-v7a/libLivenessDetectorJni.so

> Task :common-silent:mergeDebugJniLibFolders
> Task :common-silent:transformNativeLibsWithMergeJniLibsForDebug
> Task :common-silent:transformNativeLibsWithStripDebugSymbolForDebug
> Task :common-silent:transformNativeLibsWithIntermediateJniLibsForDebug

> Task :app:externalNativeBuildDebug FAILED
Build LivenessDetectorJni x86_64
ninja: error: '/home/jnitest/common-silent/src/main/jniLibs/x86_64/liblivenessdetector.so', needed by '/homejnitest/app/build/intermediates/cmake/debug/obj/x86_64/libLivenessDetectorJni.so', missing and no known rule to make it

FAILURE: Build failed with an exception.
Who can help me config it? Thanks.
BTW, after I remove all the abiFilters and save the build log, I found that jni is compiled 2 times. Why?
cat log | grep LivenessDetectorJni --color
Build LivenessDetectorJni x86_64
[1/2] Building CXX object CMakeFiles/LivenessDetectorJni.dir/LivenessDetectorJni.cpp.o
[2/2] Linking CXX shared library /home/jnitest/common-silent/build/intermediates/cmake/debug/obj/x86_64/libLivenessDetectorJni.so
Build LivenessDetectorJni x86
[1/2] Building CXX object CMakeFiles/LivenessDetectorJni.dir/LivenessDetectorJni.cpp.o
[2/2] Linking CXX shared library /home/jnitest/common-silent/build/intermediates/cmake/debug/obj/x86/libLivenessDetectorJni.so
Build LivenessDetectorJni arm64-v8a
[1/2] Building CXX object CMakeFiles/LivenessDetectorJni.dir/LivenessDetectorJni.cpp.o
[2/2] Linking CXX shared library /home/jnitest/common-silent/build/intermediates/cmake/debug/obj/arm64-v8a/libLivenessDetectorJni.so
Build LivenessDetectorJni armeabi-v7a
[1/2] Building CXX object CMakeFiles/LivenessDetectorJni.dir/LivenessDetectorJni.cpp.o
[2/2] Linking CXX shared library /home/jnitest/common-silent/build/intermediates/cmake/debug/obj/armeabi-v7a/libLivenessDetectorJni.so
Build LivenessDetectorJni x86_64
[1/2] Building CXX object CMakeFiles/LivenessDetectorJni.dir/LivenessDetectorJni.cpp.o
[2/2] Linking CXX shared library /home/jnitest/app/build/intermediates/cmake/debug/obj/x86_64/libLivenessDetectorJni.so
Build LivenessDetectorJni x86
[1/2] Building CXX object CMakeFiles/LivenessDetectorJni.dir/LivenessDetectorJni.cpp.o
[2/2] Linking CXX shared library /home/jnitest/app/build/intermediates/cmake/debug/obj/x86/libLivenessDetectorJni.so
Build LivenessDetectorJni arm64-v8a
[1/2] Building CXX object CMakeFiles/LivenessDetectorJni.dir/LivenessDetectorJni.cpp.o
[2/2] Linking CXX shared library /home/jnitest/app/build/intermediates/cmake/debug/obj/arm64-v8a/libLivenessDetectorJni.so
Build LivenessDetectorJni armeabi-v7a
[1/2] Building CXX object CMakeFiles/LivenessDetectorJni.dir/LivenessDetectorJni.cpp.o
[2/2] Linking CXX shared library /home/jnitest/app/build/intermediates/cmake/debug/obj/armeabi-v7a/libLivenessDetectorJni.so

If I use abiFilters, then the log is changed as:
cat log | grep LivenessDetectorJni --color
Build LivenessDetectorJni armeabi-v7a
[1/2] Building CXX object CMakeFiles/LivenessDetectorJni.dir/LivenessDetectorJni.cpp.o
[2/2] Linking CXX shared library /home/jnitest/common-silent/build/intermediates/cmake/debug/obj/armeabi-v7a/libLivenessDetectorJni.so
Build LivenessDetectorJni x86_64
[1/2] Building CXX object CMakeFiles/LivenessDetectorJni.dir/LivenessDetectorJni.cpp.o
[2/2] Linking CXX shared library /home/jnitest/app/build/intermediates/cmake/debug/obj/x86_64/libLivenessDetectorJni.so
Build LivenessDetectorJni x86
[1/2] Building CXX object CMakeFiles/LivenessDetectorJni.dir/LivenessDetectorJni.cpp.o
[2/2] Linking CXX shared library /home/jnitest/app/build/intermediates/cmake/debug/obj/x86/libLivenessDetectorJni.so
Build LivenessDetectorJni arm64-v8a
[1/2] Building CXX object CMakeFiles/LivenessDetectorJni.dir/LivenessDetectorJni.cpp.o
[2/2] Linking CXX shared library /home/jnitest/app/build/intermediates/cmake/debug/obj/arm64-v8a/libLivenessDetectorJni.so
Build LivenessDetectorJni armeabi-v7a
[1/2] Building CXX object CMakeFiles/LivenessDetectorJni.dir/LivenessDetectorJni.cpp.o
[2/2] Linking CXX shared library /home/jnitest/app/build/intermediates/cmake/debug/obj/armeabi-v7a/libLivenessDetectorJni.so

A: abiFilter is part of 'ndk'block.
android {
  ...
  defaultConfig {
    ...
    externalNativeBuild {
      //cmake {...}
      ndkBuild {
         abiFilters 'armeabi-v7a'
      }
    }

  }

See details here.
https://developer.android.com/studio/projects/gradle-external-native-builds#specify-abi

A: Because I link c++ in the android project 2 times, the project builds 2 times.


text:
Q: Why I'm getting 0 results when fuzziness is more than 2? I'm using elastic search 7.6.2
I have index with the following mapping:
        "mappings": {
            "properties": {
                "content": {"type": "text"},
            }
        }

with 3 documents:

*

*michael jordan and scottie pippen - NBA is a professional basketball league in North America.

*michael jordan and scottie pippen - National Basketball Association

*michael jordan and scottie pippen

I'm running the following simple query:
  "query":{
              "bool":{
                 "must":[
                    {
                       "span_near":{
                          "clauses":[
                             {
                                "span_multi":{
                                   "match":{
                                      "fuzzy":{
                                         "content":{
                                            "value":"hael",
                                            "fuzziness":4
                                         }
                                      }
                                   }
                                }
                             },
                          ],
                          "slop":1,
                          "in_order": "true"
                       }
                    }
                 ]
              }
           }
    }

And I'm getting 0 results.

*

*Why I'm not getting results ? (The value hael has 3 missing letters, and the fuzziness is 4) ?

*What is the meaning of slop (at the end of the query) ? (It seems that it doesn't do nothing)


text:
Q: Visual C++: Runtime Library of Release Mode as 'Multi-threaded Debug DLL' Here I asked that I get LNK2001 error when I build my Visual C++ code through 'Release Mode', even though all my configuration settings between 'Release' and 'Debug' modes are the same (at least the ones I changed have been changed via 'all configurations').
I could solve the problem by changing Release mode: Configuration Properties -> C/C++ -> Code Generation -> Runtime Library from 'Multi-threaded DLL (/MD)' to 'Multi-threaded Debug DLL (/MDd)'. What does this tell me? Is what I did something odd (to take runtime library of Release from Debug)? Or does this imply that my 'Release' configurations are wrong?

A: I suggest you could refer to the Linker Tools Error LNK2001

If you link to the release mode libraries when building a debug
  version of an application. Similarly, if you use options /MTd or /MDd
  or define _DEBUG and then link to the release libraries, you should
  expect many potential unresolved externals, among other problems.
  Linking a release mode build with the debug libraries also causes
  similar problems. To fix this issue, make sure you use the debug
  libraries in your debug builds, and retail libraries in your retail
  builds.

As far as I'm concerned, you are linking the Debug DLL in release mode. You should make sure you use the debug libraries in your debug builds, and retail libraries in your retail builds.


text:
Q: Google Sheets equivalent for Excel's AGGREGAT formula I am using Google Sheets and I need to implement following excel formula into my sheet.
https://docs.google.com/spreadsheets/d/1XzAYEezt2gNt_tdbxyZT-p6XwjNdhvUbt_9rBoABlhI/edit?usp=sharing
 =IFERROR(INDEX(Formularantworten!B:B;AGGREGAT(15;6;ROW(Formularantworten!$B$2:$B$100)/(Formularantworten!$B$2:$B$100<>"")/(Formularantworten!$H$2:$H$100<>"");ROW(A1)));"")

A: Well if you want to match two columns and index a third column, finding the first match, you can do what you used to do in Excel before  Aggregate came along:
=index(C:C,match(1,(A:A<>"")*(B:B<>""),0))

or
=index(C:C,min(if((A:A<>"")*(B:B<>""),row(A:A))))

But in Google sheets you have more options and are more likely to use something like
=query(A:C,"select C where A is not null and B is not null limit 1")


text:
Q: Redirect do JSF web no mobile não esta funcionando! Estou desenvolvendo um projeto estudantil com JSF 2.2, Primefaces 5.0 e wildfly 8, e me deparei com o seguinte problema:
Minha Aplicação funciona normalmente quando eu acesso de um dispositivo desktop, porem quando eu tento acessar de um dispositivo Mobile, vou na tela de login e quando faço o procedimento de "logar", sou redirecionado para mesma pagina de login não conseguindo acessar a aplicação.
O Log não apresenta erros, usei log4j para acompanhar os procedimentos e tudo acontece como deveria acontecer, porem na hora de efetuar o redirect a aplicação não se comporta como deve.
Estou fazendo o redirectda seguinte forma:
return "/autenticate/escolhaperfil.xhtml?faces-redirect=true";
Se alguém puder me ajudar agradeço.


text:
Q: How can I make
* elements flow left-to-right instead of top-to-bottom? Here are my
 elements. I want them to appear left-to-right instead of top-to-bottom.

test

test

test

test

test

How can I do this?
EDIT:how to control spacing between each li element and its bachground color and spacing between a element and border of li element?

A: There's a few ways.
One way is display:inline as the other posts mention
Another way is float:left;
edit:  more detail!  try this out in a page

using display: inline;

inline

inline blah bla

i am not so neat on

inline

wrapping and I probably

inline

need a bit of work and tweaking

inline

the "line-height" css property

inline

to make me wrap better

inline

also notice how i tend to break a line up into .. two.  see?  make your browser narrow.

inline

using float:left;

floated left

i tend to behave

floated left

better for wrapping

floated left

when the list

floated left

reaches the edge of the page

floated left

A: Try:

test

test

test

test

test

The styles should really be in an external style sheet, I just put them on the page for simplicity.

A: You could use the float attribute:
.nav ul li{float:left;}

A: i think you are looking for
li {
  display:inline;
}

A: Just to let you know, that IE does a "step-down" thing when you float list items to the left, and I think that IE is the only browser to do that, all the others keep going straight. To have the list items goes straight across, use "display: inline" in your css instead of "float: left", this should work in all browsers this way. For more in dept explanation, check out this quick tutorial

A: .nav li  { display: inline }

For further details and inspiration, have a look at Listamatic. They've got tons of excellent tutorials with step-by-step explanations and everything about margin, padding, and browser compatibility issues.

A: To answer the question after the edit:
li {
    float: left;
    display: block;
    padding: 4px 12px;   /* example spacing */
    margin: 0px 4px;     /* example margin */
}

Edit: You might want to apply the padding and the display:block to the  element so that you can click on the padding as well:
li {
    float: left;
    margin: 0px 4px;     /* example margin */
}
li a {
    display: block;
    padding: 4px 12px;   /* example spacing */
}

A: You could use display: inline, like this:
li{
    display: inline;
}

Or, if you have more lists, you could assign a class to that specific list:

Test

And then style it like:
.horizontal{
    display: inline;
}


text:
Q: How to Store Google oAuth Credential in Database using gclient-java library? I am using glcient-java library to handle Google oAuth Flow.As recommended in docs, i have two classes extending AbstractAuthorizationCodeServlet and AbstractAuthorizationCodeCallbackServlet respectively. The flow is going smooth. I am now trying to persist/store the Credential Object i receive in onSuccess method to the database.
The situation is , the users(identified by a uniqueID) have the option to connect one or multiple google accounts.
What i want is everytime a new Google Account is connected via oAuth Flow and from onSuccess Method, i should be able to add a row in database where uniqueID,GoogleAccountEmailID,AccessToken,RefreshToken are stored in the table.
Here are my important methods of Implementation:
@Override
protected AuthorizationCodeFlow initializeFlow() throws ServletException,
        IOException {
    return
            new GoogleAuthorizationCodeFlow.Builder(
                    new NetHttpTransport(), JacksonFactory.getDefaultInstance(),Constants.GOOGLE_CLIENT_ID, Constants.GOOGLE_CLIENT_SECRET,Constants.SCOPES)
            .setAccessType("offline")
            .setApprovalPrompt("force")
            .build();
}

@Override
protected void onSuccess(HttpServletRequest req, HttpServletResponse resp,
        Credential credential) throws ServletException, IOException {

    // Creates a new Gmail API client.
    System.out.print("Successfully Authenticated");
    System.out.println("Access Token"+credential.getAccessToken());
    System.out.println("Ref Token"+credential.getRefreshToken());
    System.out.println("");

    /*Here i want to store the accessToken,RefreshToken,uniqueID,credentialEmailID*/

}

Also, How should i be implementing my getUserID() method to give me emailID extracted from oauth Token response or from Credential Object.
Please help.


text:
Q: PHP Azure OAuth JWT App Roles I've created an application in an Azure AD from a manifest with several appRoles inside of it, and I can assign users to these roles. After a user completes the single sign on, returns to my application and I then request a JSON Web Token from their login. The problem is, there are no assigned roles listed in the token I get back from Azure, as it would suggest there's supposed to be here.
Is there a configuration option I'm missing or is there an alternate way to find out their assigned role through the Azure Graph API?

Update:
After specifying the resource as the App ID URI when requesting the authorisation URL I've managed to get a little further.
I'm now getting back the following error (in the return URL):
"The signed in user '<user email>' is not assigned to a role for the application '<app client id>'."

The user has definitely been assigned a role in the Azure AD control panel for the app, and the app client id in the error message matches the app's client id exactly.

Application config:

User assigned a role:

Error message after logging in and returning to app:

A: @Phlip,Could you please try to set your application permission using PowerShell?
#1.down load Azure AD powershell and login in using your user in AD
$msolcred=get-credential
connect-msolservice -credential $msolcred

#2. get principal Id
$ClientIdWebApp = '5b597c35-**-**-ad05-***'
$webApp = Get-MsolServicePrincipal –AppPrincipalId $ClientIdWebApp

# 3. use Add-MsolRoleMember to add it to "Company Administrator" role).
Add-MsolRoleMember -RoleName "Company Administrator" -RoleMemberType ServicePrincipal -RoleMemberObjectId $webApp.ObjectId

For more information, please refer to this page:
https://msdn.microsoft.com/en-us/library/azure/dn919663.aspx
and Use this methods to add member into role:
Add-MsolRoleMember -RoleName "Company Administrator" -RoleMemberEmailAddress "user@contoso.com"

Any updates or results, please let me know.

A: Probably not the answer people want to hear if they're coming across this thread looking for a solution to the issue, but we switched from using OAuth to SAML and we now successfully get app roles in the SAML response.
I can only assume the OAuth implementation of app roles on Azure AD is completely broken because we changed nothing except switching to SAML.

A: The below C# code can query the assigned users your application have using AppRoleAssignedTo attribute. I am not family with php, but I believe it has the similar method. The ActiveDirectoryClient class comes from the Active Directory Graph Client Library.
var Serprincipal = activeDirectoryClient.ServicePrincipals.Where(IServicePrincipal => IServicePrincipal.AppId.Equals("app client id")).ExecuteAsync().Result.CurrentPage.ToList();
            var sp = Serprincipal.FirstOrDefault();
            var userAssignments = (sp as IServicePrincipalFetcher).AppRoleAssignedTo.ExecuteAsync().Result.CurrentPage.ToList();
           foreach (IAppRoleAssignment assignedUser in userAssignments)
            {
               Console.WriteLine("UserId: {0}  Name: {1} ObjectType: {2} ", assignedUser.PrincipalId, assignedUser.PrincipalDisplayName, assignedUser.ObjectType);
           }


text:
Q: Inconsistency between OpenGL and CUDA maximum number of threads My GPU is NVIDIA GeForce GT440, whose compute capability version is 2.x. NVIDIA's official CUDA_C_Programming_Guide points out

Limit 1. Maximum number of threads per block = 1024
  Limit 2. Maximum number of resident threads per multiprocessor = 1536

However, two of the OpenGL computer shader implementation limits are

Limit 3. GL_MAX_COMPUTE_WORK_GROUP_INVOCATIONS = 1536

My questions are
1. Why Limit 1 is not equal to Limit 2 and Limit 3?
2. Should the real threads/block (invocations/workgroup) be 1024 or 1536?

A:
Why Limit 1 is not equal to Limit 2 and Limit 3?

Because it isn't the same thing. Blocks are a logical construct in CUDA and are limited to a maximum of 1024 threads. But a multiprocessor can run multiple blocks concurrently (up to 8 in the case of your hardware). So a SM can have up to 1536 concurrent threads in your hardware, but not all of those threads can come from a single block.

Should the real threads/block be 1024 or 1536?

1024 for all the reasons outlined above. You can see a complete summary of the capabilities of all supported hardware here.


text:
Q: what is the advantage of initializing variables in the constructor of a Java class in Android? two examples of android classes are shown below,  they are utility classes that do not extend Activity.
what is the advantage of using example 1, and why is it better than example 2?
example 1
public class SKR {

String[] code;
String[] sub_code;

public SKR(){

    code = new String[87];
    sub_code = new String[87];

    }

}

example 2
public class SKR {

String[] code = new String[87];
String[] sub_code = new String[87];

    public SKR(){

   }

}

A: It's better to the second in my opinion so the compiler can precompile the code.
But there is no real difference in the code.


text:
Q: How to add style polyfill for Angular I faced a problem, where our team developed an application on Angular 12 + we use Sass, and then our customer told us to add support for older browsers. The problem is we used style called gap which is poorly supported for example in Safari, so basically we decided to use polyfill for styles. We found flex-gap-polyfill. The problem is I don't know how to add it to the main bundle. It uses construction like
const flexGapPolyfill = require('flex-gap-polyfill');

flexGapPolyfill.process(YOUR_CSS /*, processOptions, pluginOptions */);

so it should probably be handled by polyfill.ts but how to do it stays a mystery


text:
Q: Getting weird output for dynamic allocation of the 2d array. How can I resolve the issue? I want to create a dynamic 2d array and want to perform the operation on it. However, when I print the matrix, the first column shows different numbers, and don't know where is it coming from?
I tried to make the change from array[i][j] to *(*(array+i)+j), and still I am getting the same result.
int main ()
{
  int sum=0,diagsum=0;
  int rowSize,colSize;
  std::cout << "Input Row size of the matrix" << '\n';
  std::cin >> rowSize;
  std::cout << "Input Column size of the matrix" << '\n';
  std::cin >> colSize;

  int** arrayA = new int*[rowSize];   //declaring array dynamically.

  for(int m=0;m<rowSize;++m)
  {
    arrayA[m] = new int[colSize];
  }

  //Creating matrix A of size rowSize x colSize with random of first 30
  for(int i = 0;i<rowSize;++i)
  {
    for(int j = 1;j<=colSize;++j)
    {
      arrayA[i][j]=rand() % 30;
    }
  }

  std::cout << "Matrix A is of size"<< rowSize << " X " << colSize << '\n';

  //printing Matrix A
  for(int i = 0;i<rowSize;++i)
  {
    for(int j = 0;j<=colSize;++j)
    {
      std::cout << arrayA[i][j] << "\t";
    }
    std::cout << '\n';
  }

  //sum of element of the matrix
  for(int i = 0;i<rowSize;i++)
  {
    for(int j=0;j<colSize;j++)
    {
      sum = sum + arrayA[i][j];
    }
    std::cout << '\n';
  }

  // sum of elet of diagonal of matirx
  for(int i = 0;i<rowSize;i++)
  {
      diagsum = diagsum + arrayA[i][i];
  }

  std::cout << "sum of the element of matrix is"<< sum << '\n';

  std::cout << "Diagonal sum is" << diagsum <<'\n';

//deleting mem for the array.
  for(int m=0;m<1000;m++)
  {
    delete[] arrayA[m];
  }

  delete[] arrayA;

  return 0;
}

Actual result:
Input Row size of the matrix
5
Input Column size of the matrix
5
Matrix A is of size5 X 5
9140960 11      17      4       10      29
9140960 4       18      18      22      14
9140960 5       5       1       27      1
9140960 11      25      2       27      6
9115176 21      24      2       3       22

sum of the element of matrix is45679273
Diagonal sum is9140974

===================================
Expected result:
Input Row size of the matrix
5
Input Column size of the matrix
5
Matrix A is of size5 X 5
11      17      4       10      29
4       18      18      22      14
5       5       1       27      1
11      25      2       27      6
21      24      2       3       22

A: Where you have for(int j = 1;j<=colSize;++j) it should be for(int j = 0; j < colSize;++j). Everywhere you have <= colSize should be < colSize. Where you have m<1000, should be m < rowSize, e.g.
#include <iostream>

int main (void)
{
    int sum=0,diagsum=0;
    int rowSize,colSize;
    std::cout << "Input Row size of the matrix" << '\n';
    std::cin >> rowSize;
    std::cout << "Input Column size of the matrix" << '\n';
    std::cin >> colSize;

    int** arrayA = new int*[rowSize];   //declaring array dynamically.

    for(int m=0;m<rowSize;++m)
    {
        arrayA[m] = new int[colSize];
    }

    //Creating matrix A of size rowSize x colSize with random of first 30
    for(int i = 0; i < rowSize; ++i)
    {
        for(int j = 0; j < colSize; ++j)
        {
            arrayA[i][j]=rand() % 30;
        }
    }

    std::cout << "Matrix A is of size"<< rowSize << " X " << colSize << '\n';

    //printing Matrix A
    for(int i = 0;i < rowSize; ++i)
    {
        for(int j = 0; j < colSize; ++j)
        {
            std::cout << arrayA[i][j] << "\t";
        }
        std::cout << '\n';
    }

    //sum of element of the matrix
    for(int i = 0; i < rowSize; i++)
    {
        for(int j = 0; j < colSize; j++)
        {
            sum = sum + arrayA[i][j];
        }
        std::cout << '\n';
    }

    // sum of elet of diagonal of matirx
    for(int i = 0; i < rowSize; i++)
    {
        diagsum = diagsum + arrayA[i][i];
    }

    std::cout << "sum of the element of matrix is"<< sum << '\n';

    std::cout << "Diagonal sum is" << diagsum <<'\n';

    //deleting mem for the array.
    for(int m = 0; m < rowSize; m++)
    {
        delete[] arrayA[m];
    }

    delete[] arrayA;

    return 0;
}

(note: if you space your loop declartions a bit more, the errors will be easier to spot. Also be consistent with either ++j or j++)
(also note: you can collect sum and diagsum in a single loop, just by checking if (i == j) diagsum += arrayA[i][j];)
You should also validate your user input, e.g.
    if (!(std::cin >> rowSize)) {
        std::cerr << "error: invalid rowSize\n";
        return 1;
    }

Otherwise, you are one slip of the keyboard away from undefined behavior.
Example Use/Output
$ ./bin/array_dyn_rand
Input Row size of the matrix
5
Input Column size of the matrix
5
Matrix A is of size5 X 5
13      16      27      25      23
25      16      12      9       1
2       7       20      19      23
16      0       6       22      16
11      8       27      9       2

sum of the element of matrix is355
Diagonal sum is73

You should remove std::cout << '\n'; from your loop computing the sum it is completely unnecessary.
Since you are using rand() from C stdlib.h, you must seed the random number generator by calling srand() before your 1st call to rand(), generally initialized with the seconds since epoch with, e.g.
#include <ctime>
...
    srand (time(NULL));     /* seed the random number generator */

(note: C++ provides it own Pseudo-random number generation routines)
Simply cleaning up your code a bit for readability and combining the sum and diagsum calculations in a single loop, you could do:
#include <iostream>
#include <ctime>

int main (void)
{
    int sum=0,
        diagsum=0,
        rowSize,
        colSize;

    std::cout << "Input Row size of the matrix: ";
    if (!(std::cin >> rowSize)) {       /* validate EVERY user-input */
        std::cerr << "error: invalid rowSize\n";
        return 1;
    }
    std::cout << "Input Col size of the matrix: ";
    if (!(std::cin >> colSize)) {
        std::cerr << "error: invalid colSize\n";
        return 1;
    }

    srand (time(NULL));     /* seed the random number generator */

    int **arrayA = new int* [rowSize];  /* allocate rowSize pointers */

    for(int m = 0;m < rowSize; m++)     /* allocate colSize ints per-row */
        arrayA[m] = new int[colSize];

    /* Populate rowSize rows x colSize columns with random 0 - 29 */
    for (int i = 0; i < rowSize; i++)
        for (int j = 0; j < colSize; j++)
            arrayA[i][j]=rand() % 30;

    std::cout << "\nMatrix A is of size " << rowSize << " x " << colSize
                << "\n\n";

    // printing Matrix A
    for (int i = 0; i < rowSize; i++) {
        for (int j = 0; j < colSize; j++)
            std::cout << arrayA[i][j] << "\t";
        std::cout << '\n';
    }

    // sum of elements and diagonal of the matrix
    for (int i = 0; i < rowSize; i++) {
        for(int j = 0; j < colSize; j++) {
            if (i == j)
                diagsum += arrayA[i][j];
            sum = sum + arrayA[i][j];
        }
    }

    std::cout << "\nsum of the element of matrix is: "<< sum << '\n'
                << "Diagonal sum is: " << diagsum <<'\n';

    // deleting mem for the array.
    for (int m = 0; m < rowSize; m++)
        delete[] arrayA[m];             /* delete storage for rows */
    delete[] arrayA;                    /* delete pointers */

    return 0;
}

Revised Use/Output
$ ./bin/array_dyn_rand
Input Row size of the matrix: 5
Input Col size of the matrix: 5

Matrix A is of size 5 x 5

24      8       16      5       15
15      13      24      24      11
16      26      11      12      26
20      9       22      9       22
19      3       3       13      0

sum of the element of matrix is: 366
Diagonal sum is: 57

Let me know if you have further questions.


text:
Q: In this Rails app view loop, how can I include CSS button styling? I want the "complete" below to have a fake button styling, basically a border and a colored interior.
What would be the best way to do this? I tried to suffix class: 'btn btn-mini' but that doesn't work (for obvious reasons, as it's not really a button).
- @tasks.each do |task|
  %tr
    %td= task.content
    - if @dayhash[task.day_id] == "today"
      - if task.start != nil && task.stop.nil?
        %td underway
      - elsif task.start !=nil and task.stop !=nil
        %td complete

A:   - elsif task.start !=nil and task.stop !=nil
    %td
      .btn.btn-mini Complete


text:
Q: Ajax.BeginForm inside Html.BeginForm I have a view that is used for editing stuff, say Orders.  Orders have line items that can be added arbitrarily.  So a main view and nested partialviews.
Each partial should have an ajax form for tweaking quantities of each line item or whatever.
Thus:
Html.BeginForm()
{%>
    Ship to: blah blah blah
    <%
    Ajax.BeginForm("EditLineItem", "Order", new { OrderLineItemID = Model.ObjectID }, itemAjaxOptions))
    {
        Item qty blah blah blah

        <--! (ajax form's submit button, etc.)-->
    }
    %>
    <--! (ajax form's submit button, etc.)-->
<%
}

I have a controller that looks like this:
[ActionName("Edit")]
[AcceptVerbs(HttpVerbs.Post)]
[ValidateAntiForgeryToken]
public ActionResult Edit(int orderID)
{
    blah, blah
}

[ActionName("EditLineItem")]
[AcceptVerbs(HttpVerbs.Post)]
[ValidateAntiForgeryToken]
public ActionResult EditLineItem(Guid orderLineItemID)
{
    blah, blah
}

My trouble is that when I submit the Ajax form, I get the Edit method instead of the EditLineItem methods.  Both routes are mapped.  Is there some gotcha like "you can't submit an Ajax form inside of an Html form" that I don't know about?

A: AFAIA the AjaxForm is still renders as a form tag, so you'd be nesting forms, which as you've found is a no no.
I reckon Francisco is on the right lines (tho I'd suggest implementing a post rather than a get as you are updating something).
Kind regards,
TP

A: I tried the exact same thing a while ago. No matter what I did, it wouldn't do the AJAX submit. So I think the answer is: yes, you can't put a submit button for an AJAX form inside a regular html form.
But, why would you have partial submits merged with full submits?
The easiest workaround to this imo would be to use JSON requests with jQuery.
for instance, updating a quantity span text when you change a dropdownlist (id=Order):
<script type="text/javascript">
    $(document).ready(function() {
        $('select#Order').change(function() {
            $.getJSON('/Orders/UpdateQty/' + this.value, {},
              function(data) {
                  $('#qty').html(data);
              });
        });
    });

</script>

And the code in the "Orders" controller:
public class OrdersController : Controller
{
    public ActionResult UpdateQty(int id)
    {
        return Json(yourLibrary.getQuantities(id));
    }
}

This Link might help.
Regards
Edit:
So.. the link no longer exists. But thanks to the internet wayback machine, we have this copy :)


text:
Q: PostgreSQL: data retrieval from a private (authentication-based) RESTful web API using a foreign data wrapper In some cases, one want to feed or populate some PostgreSQL database tables using data fetched from the web, e.g. through a RESTful API (serving JSON features).
I've recently discovered foreign data wrappers and I'm not yet 100% used to them, but they seem to be a very interesting option to replace some custom Python scripts that retrieve data from the web, process it and use a Python data wrapper (i.e. psycopg2, or others) to populate some of my PostgreSQL database tables with that data.
After some research, I've successfully used the ogr_fdw (see also here) for fetching data from an OGC API features endpoint as well as the http extension for retrieving JSON data from a standard public API. Both those APIs are public, so they don't need any type of authentication.
I'm now naturally wondering if it's possible to build a view or populate a PostgreSQL table using a foreign data wrapper which retrieves data from a private RESTful API, i.e. which has an authentication procedure?
If yes, what kind of extension should I use and how? I couldn't find a tutorial or any detailed information at the moment.
The authentications I want to succeed with are the web based ones, i.e.: HTTP Basic Auth, API keys or OAuth2.


text:
Q: Laravel: Form select not working with style / class when setting the default option I am using Laravel 5 with Bootstrap.
When I use below, the class and/or style works fine:
{!! Form::select('mylist', [''=>'-- select --'], array('id' => 'mylist'), array('class' => 'myclass', 'style' => 'width:116px)) !!}

However, when I set $mylist as the default option for my select form (in my edit record page), the style / class is not working:
{!! Form::select('mylist', [''=>'-- select --'] + $mylist, $row->myfile, array('id' => 'mylist'), array('class' => 'myclass', 'style' => 'width:116px)) !!}

Please kindly advise me to achieve this.
Thanks,
Naren

A: I think this is the correct format you should use
{!! Form::select('mylist', $mylist, $row->myfile, array('placeholder' => 'Select','class' => 'myclass', 'style' => 'width:116px')) !!}


text:
Q: R - Calculate sum within date range using zoo Suppose I have a data frame with ten years of daily temperature data (in degree C) like this:
mydf <- data.frame(Date = seq(as.Date("2001/1/1"), as.Date("2010/12/31"), by = "day"), Temp = runif(3652, 0, 40))

I am trying to calculate growing degree days for plants. This is how it works: within a date range, I need to integrate the difference between the daily temperature and a base temperature, let's say 10 degrees C. To make it harder, the date range goes across years. For example, I need to calculate the growing days between november 1st and march 31st for all years in the time series. In terms of an "algorithm", the logic would be something like this:
t_base <- 10

for (each day between nov 1st and mar 31st) {
  sum (Temp - t_base)
}

How to do this using the zoo package?

A: Note that "yearmon" class variables are of the form year + frac where the frac is 0 for Jan, 1/12 for Feb, 2/12 for Mar, etc.  Below ym is a "yearmon" vector corresponding to the Date except that we have added two months.  ym is then split into year y (the season-end year) and month m (where month is 0 for the first month of the season, 1 for the second month, ..., 4 for the 5th and last month in season and higher numbers for months not in season) .  in.seas is TRUE for those data points in Nov, Dec, Jan, Feb or Mar (which corresponds to m <= 4).  Finally use ave to calculate the cumulative sum among dates having the same season-end year or aggregate to calculate the sum.
library(zoo)

z <- read.zoo(mydf)
ym <- as.numeric(as.yearmon(index(z)) + 2/12)
y <- floor(ym) # year of date's season end or this year if not in season
m <- round(12 * (ym - y))  # month Nov = 0, Dec = 1, Jan = 2, Feb = 3, Mar = 4, ...
in.seas <- m <= 4
Cum <- ave(z[in.seas], y[in.seas], FUN = function(x) cumsum(x - t_base))

or to just get the sum of each season:
Sum <- aggregate(z[in.seas], y[in.seas], function(x) sum(x - t_base))

Note that fortify.zoo(x) will convert zoo object x back to a data frame should that be necessary.


text:
Q: Multiple Table Joins Help (SQL Server) I have a school assignment and I've almost completed it but the last few questions have me stumped. We are using the AdventureWorks database - https://imgur.com/a/i1N4j.
The troublesome question is as follows:
"List the American states/counties with the number of different phone number types for states/counties that have 500 or more of each phone number type.  Order by the count of each phone type desc"
I've never had to deal with this many tables before and it's got me stumped. Am I meant to join 7 or 8 tables together in order to link the Person.PhoneNumberType and Person.StateProvince tables together? How do I go about joining that many tables?
A nudge in the right direction is all I'm after.
Thank you


text:
Q: Python ctypes TypeError for defined function I have a known function type definition of wintypes.HANDLE, wintypes.LPVOID with a return value of wintypes.DWORD.
Using ctypes I've defined the type and function and tried to make the call with a handle and lpvoid reference:
ftype = CFUNCTYPE(wintypes.HANDLE, wintypes.LPVOID, wintypes.DWORD)
function = ftype(address)

base = wintypes.LPVOID(0x0)
ptr = function(GetCurrentProcess(), byref(base))

However, when executing I receive an error:
ctypes.ArgumentError: argument 2: <class 'TypeError'>: wrong type
Can someone please help me identify the problem?
What type should I be passing, if not the defined lpvoid?

A: Here's a minimal example.  I created a DLL with the function signature described and extracted the address to demo the Python code.
#include <windows.h>
#include <stdio.h>

#ifdef _WIN32
#   define API __declspec(dllexport)
#else
#   define API
#endif

API DWORD function(HANDLE h, LPVOID pv) {
    printf("h=%p pv=%p\n", h, pv);
    return 1;
}

from ctypes import *
from ctypes import wintypes

dll = CDLL('./test')
address = addressof(dll.function)

# return value is the FIRST parameter to CFUNCTYPE
ftype = CFUNCTYPE(wintypes.DWORD, wintypes.HANDLE, wintypes.LPVOID)

# ftype(address) doesn't expect an unwrapped C address, but a Python function,
# so I used from_address() instead.
function = ftype.from_address(address)

ret = function(0x123,None) # None can be used for a null pointer
print(ret)

Output:
h=0000000000000123 pv=0000000000000000
1


text:
Q: Can I copy debug.keystore from one PC to another? Can I copy the debug.keystore in My home directory to another PC's home directory? Does it have to be Linux on Linux, and Windows and Windows? Can I copy Linux keystores to Windows, and vice-versa?

A: Yes.
I've created a keystore for a project and share it with my team. Everyone is able to build with the same key.
I've created it in Linux and it was used in Linux and in Windows. We didn't try the other way round, but it should work.


text:
Q: Отправка 2х форм одним ajax скриптом Подскажите, пожалуйста, как правильно написать аякс скрипт так, чтобы при отправке второй формы не перезагружалась страница. Необходимо чтобы оставалось именно 2 формы.
Что происходит в коде:
При отправке первой формы add_review через ajax, в success отправляю вторую форму $('.rating').submit();, но страница в таком случае перезагружается. Возможно ли дописать скрипт так, чтобы вторая форма отправлялась но страница не перезагружалась.
Конструкция:
<form class="rating" method="POST" action="updates/add_review_stars.php" enctype="multipart/form-data">
    <input type="hidden" class="uk-input" value="<?echo $product_id;?>" name="product_id" id="product_id">

    <input type="radio" name="stars" value="1" />
    ★

    <input type="radio" name="stars" value="2" />
    ★
    ★

    <input type="radio" name="stars" value="3" />
    ★
    ★
    ★

    <input type="radio" name="stars" value="4" />
    ★
    ★
    ★
    ★

    <input type="radio" name="stars" value="5" />
    ★
    ★
    ★
    ★
    ★

    </form>

    <form id ="add_review" enctype="multipart/form-data">
    <input type="hidden" class="uk-input" value="<?echo $product_id;?>" name="product_id" id="product_id">
    <input type="hidden" class="uk-input" value="0" name="approved" id="approved">

    Имя
    <input type="text" class="uk-input" name="name" id="name" required>
    Отзыв
    <textarea class="uk-textarea" name="review" id="review" required></textarea>

    <input type="submit" name="submit" value="Добавить отзыв" data-dismiss="modal" class="uk-button uk-button-default">

    </form>

A: Можно например так написать, я добавил очистку форм в конце, ну и сделать кнопки не активными было бы хорошо, чтобы случайно дважды не отправилось если первый запрос не успел отработать то такое может произойти теоретически.
Как вариант еще можно сделать функцию с аяксом, которую и вызывать для этих двух форм (с разными аргументами) ну и в начале функции дизейблить кнопку отправки, пока не придет ответ или не произойдет ошибка отправки.

$("#add_review").submit(function(send){
    send.preventDefault();
    $.ajax({
        url: 'http://httpstat.us/200',
        type: 'POST',
        data: new FormData(this),
        contentType: false,
        cache: false,
        processData:false,
        success: function(html){
            //$("#addresult_review").html(html);
            sendRating()
        }
    });
    });

    function sendRating(){
      var postData = $('.rating').serialize(); // данные
      $.ajax({
          url: 'http://httpstat.us/200',
          type: 'POST',
          data: postData,
          contentType: false,
          cache: false,
          processData:false,
          success: function(html){
             console.log('Отправлено')
             // чистим формы
             $("#add_review").trigger("reset");
             $('.rating').trigger("reset");
          }
      });
    }

<form class="rating" method="POST" enctype="multipart/form-data">
<input type="hidden" class="uk-input" value="<?echo $product_id;?>" name="product_id" id="product_id">

<input type="radio" name="stars" value="1" />
★

<input type="radio" name="stars" value="2" />
★
★

<input type="radio" name="stars" value="3" />
★
★
★

<input type="radio" name="stars" value="4" />
★
★
★
★

<input type="radio" name="stars" value="5" />
★
★
★
★
★

</form>

<form id ="add_review" enctype="multipart/form-data">
<input type="hidden" class="uk-input" value="<?echo $product_id;?>" name="product_id" id="product_id">
<input type="hidden" class="uk-input" value="0" name="approved" id="approved">

Имя
<input type="text" class="uk-input" name="name" id="name" required>
Отзыв
<textarea class="uk-textarea" name="review" id="review" required></textarea>

<input type="submit" name="submit" value="Добавить отзыв" data-dismiss="modal" class="uk-button uk-button-default">

</form>


text:
Q: Storyboard prepareForSegue I have a question regarding storyboard segues.  Platform is iOS 6.1.  Target device is iPhone. IDE is Xcode 4.5.2.  What I have are 2 TableViewControllers, both of which have a segue (segOne & segTwo) to the same ViewController.  The desired outcome is that when a user navigates to this ViewController, they will return to the originating TableViewController.  To do this I need some way to pass the id of the originating segue (or TableViewController) to the destination ViewController.  In the past I accomplished this by setting up the 'back' button in the NavigationItem which always worked fine.  Now, however I want to code the back buttons as separate controls.
I understand that to accomplish this I need to set up the 'prepareForSegue' method in the source TableViewControllers which I have done.  Where I am having a problem is writing the code in the destinationViewControllers to programmatically identify which of the two segues is the source segue, segOne or segTwo?  Both segues are identified as 'segOne' and 'segTwo' in Storyboard Seque.  Both are style 'push' segues and both are destination 'current' segues.  Each of the TableViewController implementation files are identical except for the segue ids.  Here's my code:
header file:
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender;

implementation file:
-(void)prepareForSegue:(UIStoryboardSegue*)segue sender:(id)sender
{
  if([[segue identifier] isEqualToString:@"segOne"])
  {
      NSLog (@"TableViewController1: segue.identifier %@", segue.identifier);
      NSLog (@"TableViewController1: self %@", self);
      NSLog (@"TableViewController1: sender %@", (id)sender);
  }
}

The output is exactly what I would expect.  Here it is forTableViewController1:
TableViewController1: segue.identifier segOne
TableViewController1: self <TableViewController1: 0x928eb70>
TableViewController1: sender <UITableViewCell: 0x927a3e0; frame = (0 22; 768 44); text = '  1. birth month and year...'; autoresize = W; layer = <CALayer: 0x928d380>>

So, what I need is the code for the ViewController that identifies which of the two segues, segOne or segTwo is the originating segue.  I do understand that any code needs to go in the viewDidAppear method of the destination ViewController.  Once I have this it will be a simple matter to code the IBAction in the ViewController to navigate to the originating TableViewController. Any code examples on how to do this would be appreciated.  thx...

A: When you push a view controller using a Navigation view controller, it will be pushed on the top of a stack with view controllers.
So all you have to do get back to the previous view controller is to pop the one that got pushed.
Put this in your IBAction method:
[self.navigationController popViewControllerAnimated:YES];

Now, if you really want to know what segue that was used, you can just pass the segue identifier to the destination controller, and put it in a property like this:

-(void)prepareForSegue:(UIStoryboardSegue*)segue sender:(id)sender
{
    if([[segue identifier] isEqualToString:@"segOne"])
    {
        MyOtherViewController *other = (MyOtherViewController *)segue.destinationViewController;
        other.theSegueIUsed = @"segOne";
    }
}

You also need to add the property to the other view controllers header file:
@property (strong, nonatomic)NSString *theSegueIUsed;


text:
Q: Select2 Js not working with Laravel Livewire I am using livewire in my laravel project. Where I am using a button to generate a new tab. Like this.

Normally when I refresh the page I will found the search portion.

But after adding a new tab the search portion will be vanised. Here I am using select2 js for this search portion.
The Component code is

            <form wire:submit.prevent="allocationGenerate">

Product Allocations

                        Showroom name
                        <select class="form-control" style="width: 100%;" wire:model.defer="showroom_id"
                                required>
                            <option value="" selected>Select Showroom</option>
                            @foreach($showrooms as $showroom)
                                <option value="{{ $showroom->id }}">{{ $showroom->name }}</option>
                            @endforeach
                        </select>

                            Products Stock

                                    Product
                                    Quantity

                                @foreach ($orderProducts as $index => $orderProduct)

                                                <select name="orderProducts[{{$index}}][product_id]"
                                                        wire:model="orderProducts.{{$index}}.product_id"
                                                        class="form-control item" style="width: 100%">
                                                    <option value="">-- Choose product --</option>
                                                    @foreach ($allProducts as $product)
                                                        <option value="{{ $product->id }}">
                                                            {{ $product->name }} - {{ $product->attribute->name }} - {{ $product->sku }} - {{ $product->barcode }}
                                                        </option>
                                                    @endforeach
                                                </select>

                                            <input type="number"
                                                   name="orderProducts[{{$index}}][quantity]"
                                                   class="form-control"
                                                   wire:model="orderProducts.{{$index}}.quantity" />

                                            <button class="btn btn-danger">Delete</button>

                                @endforeach

                                    <button class="btn btn-sm btn-secondary"
                                            wire:click.prevent="addProduct">+ Add Another Product</button>

                    <button type="submit" class="btn btn-primary">Save Allocation</button>

            </form>

under push js i used that script

So how can I solve these issues? I am not good at jquery. Please help me to solve this issue.


text:
Q: GNU Assembly scan and print float I am new to Assembly and have been trying to write a program to read a float, store it and then print it, the problem is when I print it with %f flag it prints 0.0 although the scan flag is also %f and the type is .float
.section .data        # memory variables
format: .asciz "%f"    # string terminated by 0 that will be used for scanf parameter
n: .float 0.0             # the variable n which we will get from user using scanf and will be printed by printf

.section .text        # instructions
.globl _main          # make _main accessible from external
_main:                # the label indicating the start of the program
   pushl $n           # push to stack the second parameter to scanf (the address of the integer variable n) the char "l" in pushl means 32-bits address
   pushl $format       # push to stack the first parameter to scanf
   call _scanf        # call scanf, it will use the two parameters on the top of the stack in the reverse order
   add $8, %esp       # pop the above two parameters from the stack (the esp register keeps track of the stack top, 8=2*4 bytes popped as param was 4 bytes)

   pushl n
   pushl $format
   call _printf
   add $8, %esp
   ret

Can someone tell me what is the problem here? Thanks!


text:
Q: Why does the FileUpload control get bound to the current list item in a custom list EditForm? I've written a custom edit form for a list which means I lose certain out of the box capabilities such as Attachments as it was part of the out of the box form. The way I have implemented the form is by writing a custom visual web part using ASP.NET and C# code behind and then during deployment I hide the existing edit web part in the EditForm.aspx page and then add my web part to it.
The way I have developed the form is with a proper separation of concerns where my form really doesn't know anything about SharePoint and it just passes a data object to a datamanager object that then writes the data to SharePoint.
The problem comes in with the attachments form that I wrote. What I found is that SPContext.Current.ListItem.Attachments immediately contains the file in the FileUpload control upon post back. I did not have to write any code for this to happen - just trigger a postback while a file is selected in the control.
In most cases I can just ignore the fact that this happens and everything works fine because I never actually update that instance of the list item. But in some edge cases such as uploading a file where an attachment with the same name already exists, the form blows up without even touching my code.
I also found that there is an AttachmentsControl in the SPContext.Current.FormContext.FieldControlCollection and removing this in every Page_Init event of the UserControl doesn't help the issue at all.
The reason I want my form within the context of the list item is so that all of the out of the box tool bars / ribbon / context menus / etc. still properly link to the form. I could redirect from the edit form to an out of context page with my web part on it, but this seems hackish and unnecessary (not to mention just bad coding).
Does anyone have any insight on why this behavior is happening and how I can work around it? It seems like very bad design for any list form to automatically hijack a control for its own use like this. I feel like SharePoint should have its own control and just leave the ASP.NET control alone but that seems to not be the case.

A: On a standard list form if an attachment with the same name was added multiple times. If the item will be stored the form throws an exception, that one of the attachments was added multiple time and prevent from adding the item.
In your case you override this exception, which causes that no attachments are available when you try to store the list item. To avoid this behavior you need to manually check if a attachment was added multiple times otherwise you will always fail.
You need to remove the default NewForm web part instead of hiding it. Then the exception won't be raised and you are able to get the attachments.

A: If you attach an event handler to the itemAdding event does it fire on the error conditions?  You might be able to use that to run some custom code to either handle the event, or possibly just suppress the system system error message and provide your own nicer one.


text:
Q: How can I improve VS 2013 markup editor performance? The performance of the markup editor in VS 2013 is horrible. Each time I press a key I have to wait a little bit to see the results.
Is there any way to improve the performance, to make it work faster, maybe disable intellisense or code analysis for markup?
How do You handle this issue, because I can't work right now.
Thanks for any hints.

A: Ok, in this case the problem was with the balance power consumption laptop setting which changed after system reinstallation. After switching to high performance reaction speed in vs is acceptable, but still maybe You have any hints on improveing it even more ?


text:
Q: ggplot is not graphing a vertical line I am trying to plot a graph in ggplot2 where the x-axis represents month-day combinations, the dots represent y-values for two different groups.
When graphing my original data set using this code,
ggplot(graphing.df, aes(MONTHDAY, y.var, color = GROUP)) +
          geom_point() +
          ylab(paste0(""))+
          scale_x_discrete(breaks = function(x) x[seq(1, length(x), by = 15)])+
        theme(legend.text = element_blank(),
              legend.title = element_blank()) +
          geom_vline(xintercept = which(graphing.df$MONTHDAY == "12-27")[1], col='red', lwd=2)

I get this graph where the vertical line is not showing.

When I tried to create a reproducible example using the following code...
df <- data.frame(MONTHDAY = c("01-01", "01-01", "01-02", "01-02", "01-03", "01-03"),
                                TYPE = rep(c("A", "B"), 3),
                                VALUE = sample(1:10, 6, replace = TRUE))

      verticle_line <- "01-02"

      ggplot(df, aes(MONTHDAY, VALUE, color = TYPE)) +
          geom_point() +
          #geom_vline(xintercept = which(df$MONTHDAY == verticle_line)[1], col='red', lwd=2)+
          geom_vline(xintercept = which(df$MONTHDAY == verticle_line), col='blue', lwd=2)

The vertical line is showing, but now its showing in the wrong place

In my original data set I have two values for each month-day combination (representing each of the two groups).  The month-day combination column is a character vector, it is not a factor and does not have levels.

A: Here is a way. It subsets the data keeping only the rows of interest and plots the vertical line defined by MONTHDAY.
library(ggplot2)

verticle_line <- "01-02"

ggplot(df, aes(MONTHDAY, VALUE, color = TYPE)) +
  geom_point() +
  geom_vline(data = subset(df, MONTHDAY == verticle_line),
             mapping = aes(xintercept = MONTHDAY), color = 'blue', size = 2)

Data
I will repost the data creation code, this time setting the RNG seed in order to make the example reproducible.
set.seed(2020)
df <- data.frame(MONTHDAY = c("01-01", "01-01", "01-02", "01-02", "01-03", "01-03"),
                                TYPE = rep(c("A", "B"), 3),
                                VALUE = sample(1:10, 6, replace = TRUE))

A: The reason your line is not showing up where you expect is because you are setting the value of xintercept= via the output of the which() function.  which() returns the index value where the condition is true.  So in the case of your reproducible example, you get the following:
> which(df$MONTHDAY == verticle_line)
[1] 3 4

It returns a vector indicating that in df$MONTHDAY, indexes 3 and 4 in that vector are true.  So your code below:
geom_vline(xintercept = which(df$MONTHDAY == verticle_line)...

Reduces down to this:
geom_vline(xintercept = c(3,4)...

Your MONTHDAY axis is not formatted as a date, but treated as a discrete axis of character vectors.  In this case xintercept=c(3,4) applied to a discrete axis draws two vertical lines at x intercepts equivalent to the 3rd and 4th discrete position on that axis:  in other words, "01-03" and... some unknown 4th position that is not observable within the axis limits.
How do you fix this?  Just take out which():
ggplot(df, aes(MONTHDAY, VALUE, color = TYPE)) +
  geom_point() +
  geom_vline(xintercept = verticle_line, col='blue', lwd=2)

A: We can get the corresponding values of 'MONTHDAY' after subsetting
ggplot(df, aes(MONTHDAY, VALUE, color = TYPE)) +
      geom_point() +
      geom_vline(xintercept = df$MONTHDAY[df$MONTHDAY == verticle_line],
                        col='blue', lwd=2)


text:
Q: JS Drop Down Menu to appear over Image Rotator hoping someone can help me out with this. I'm trying to get the drop down menu to appear over the javascript image slider on this page...
http://www.spektroskopy.com/SNSv2/index.php
I seem to remember coming across this issue ages back but for the life of me i can't seem to find a solution, i even had a play around with z-index.. but with no luck.

A: it's a CSS issue, in navigation.css line 52 you will find .dropmenu li ul, .dropmenu li > div add there z-index:2


text:
Q: Error Jaspersoft Studio Error preparing statement for executing the report query When I try the Preview Report, return this error
net.sf.jasperreports.engine.JRException: net.sf.jasperreports.engine.JRException: Error preparing statement for executing the report query :

SELECT `accounts`.`name` AS `accounts_name` FROM `accounts` WHERE `accounts`.`id` NOT IN (SELECT `tasks`.`parent_id` FROM  `tasks` WHERE `tasks`.`date_modified` > DATE_SUB(now(), INTERVAL 3 OR 6 MONTH))

    at com.jaspersoft.studio.editor.preview.view.control.ReportControler.fillReport(ReportControler.java:467)
    at com.jaspersoft.studio.editor.preview.view.control.ReportControler.access$18(ReportControler.java:442)
    at com.jaspersoft.studio.editor.preview.view.control.ReportControler$4.run(ReportControler.java:334)
    at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54)
Caused by: net.sf.jasperreports.engine.JRException: Error preparing statement for executing the report query :

SELECT `accounts`.`name` AS `accounts_name` FROM `accounts` WHERE `accounts`.`id` NOT IN (SELECT `tasks`.`parent_id` FROM  `tasks` WHERE `tasks`.`date_modified` > DATE_SUB(now(), INTERVAL 3 OR 6 MONTH))

    at net.sf.jasperreports.engine.query.JRJdbcQueryExecuter.createStatement(JRJdbcQueryExecuter.java:377)
    at net.sf.jasperreports.engine.query.JRJdbcQueryExecuter.createDatasource(JRJdbcQueryExecuter.java:196)
    at net.sf.jasperreports.engine.fill.JRFillDataset.createQueryDatasource(JRFillDataset.java:1119)
    at net.sf.jasperreports.engine.fill.JRFillDataset.initDatasource(JRFillDataset.java:691)
    at net.sf.jasperreports.engine.fill.BaseReportFiller.setParameters(BaseReportFiller.java:434)
    at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:508)
    at net.sf.jasperreports.engine.fill.BaseFillHandle$ReportFill.run(BaseFillHandle.java:120)
    at java.lang.Thread.run(Thread.java:695)
Caused by: java.sql.SQLSyntaxErrorException: palabra desconocida:
    at org.hsqldb.jdbc.Util.sqlException(Unknown Source)
    at org.hsqldb.jdbc.Util.sqlException(Unknown Source)
    at org.hsqldb.jdbc.JDBCPreparedStatement.<init>(Unknown Source)
    at org.hsqldb.jdbc.JDBCConnection.prepareStatement(Unknown Source)
    at net.sf.jasperreports.engine.query.JRJdbcQueryExecuter.createStatement(JRJdbcQueryExecuter.java:267)
    ... 7 more
Caused by: org.hsqldb.HsqlException: palabra desconocida:
    at org.hsqldb.error.Error.error(Unknown Source)
    at org.hsqldb.error.Error.error(Unknown Source)
    at org.hsqldb.ParserBase.read(Unknown Source)
    at org.hsqldb.ParserBase.readThis(Unknown Source)
    at org.hsqldb.ParserDQL.XreadSelect(Unknown Source)
    at org.hsqldb.ParserDQL.XreadQuerySpecification(Unknown Source)
    at org.hsqldb.ParserDQL.XreadSimpleTable(Unknown Source)
    at org.hsqldb.ParserDQL.XreadQueryPrimary(Unknown Source)
    at org.hsqldb.ParserDQL.XreadQueryTerm(Unknown Source)
    at org.hsqldb.ParserDQL.XreadQueryExpressionBody(Unknown Source)
    at org.hsqldb.ParserDQL.XreadQueryExpression(Unknown Source)
    at org.hsqldb.ParserDQL.compileCursorSpecification(Unknown Source)
    at org.hsqldb.ParserCommand.compilePart(Unknown Source)
    at org.hsqldb.ParserCommand.compileStatement(Unknown Source)
    at org.hsqldb.Session.compileStatement(Unknown Source)
    at org.hsqldb.StatementManager.compile(Unknown Source)
    at org.hsqldb.Session.execute(Unknown Source)
    ... 10 more

What's happen?
The Test database connection it's ok (I use org.hsqldb.jdbcDriver), the database is in Mysql(If I try the Mysql driver, error communication failure), the version the Jasper is the 6.0.0.
The code is
<?xml version="1.0" encoding="UTF-8"?>

<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="CompanyReport" language="groovy" pageWidth="595" pageHeight="842" columnWidth="535" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="a5bf3d64-d6b6-48c5-9c1e-412341420f11">
    <property name="ireport.zoom" value="1.0"/>
    <property name="ireport.x" value="0"/>
    <property name="ireport.y" value="84"/>
    <property name="com.jaspersoft.studio.data.defaultdataadapter" value="Canal4"/>
    <queryString language="SQL">
        <![CDATA[SELECT `accounts`.`name` AS `accounts_name` FROM `accounts` WHERE `accounts`.`id` NOT IN (SELECT `tasks`.`parent_id` FROM  `tasks` WHERE `tasks`.`date_modified` > DATE_SUB(now(), INTERVAL 3 OR 6 MONTH))]]>
    </queryString>
    <field name="accounts_name" class="java.lang.String"/>
    <background>
        <band/>
    </background>
    <title>
        <band/>
    </title>
    <pageHeader>
        <band height="79">
            <staticText>
                <reportElement mode="Opaque" x="0" y="1" width="441" height="75" forecolor="#FFFFFF" backcolor="#000099" uuid="26217d12-c674-43a7-bc1a-bf78deeaec88"/>
                <textElement verticalAlignment="Middle">

                </textElement>
                <text><![CDATA[Informe detallado de empresa]]></text>
            </staticText>
            <line>
                <reportElement x="0" y="76" width="555" height="1" forecolor="#666666" uuid="fdffb19d-6028-475b-950b-e79e2b1f99c8"/>
            </line>
        </band>
    </pageHeader>
    <columnHeader>
        <band/>
    </columnHeader>
    <detail>
        <band height="381">
            <rectangle>
                <reportElement x="1" y="4" width="554" height="24" forecolor="#CCFFFF" backcolor="#CCFFFF" uuid="0f212168-15c3-4f56-986f-459e65788377"/>
            </rectangle>
            <line>
                <reportElement positionType="FixRelativeToBottom" x="0" y="258" width="555" height="1" uuid="7ad8233c-4bbe-4ccf-b271-4346d742f303"/>
            </line>
            <textField isStretchWithOverflow="true">
                <reportElement x="80" y="7" width="284" height="20" uuid="1e5b0494-848f-48c2-8e3f-71859e5d6049"/>
                <textElement>

                </textElement>
                <textFieldExpression><![CDATA[$F{accounts_name}]]></textFieldExpression>
            </textField>
            <staticText>
                <reportElement mode="Opaque" x="0" y="6" width="70" height="21" forecolor="#006699" backcolor="#E6E6E6" uuid="95550a5a-8e1c-403d-8be1-cec0f685ec04"/>
                <textElement textAlignment="Right">

                </textElement>
                <text><![CDATA[Empresa :]]></text>
            </staticText>
        </band>
    </detail>
    <columnFooter>
        <band/>
    </columnFooter>
    <pageFooter>
        <band height="23">
            <textField>
                <reportElement mode="Opaque" x="0" y="8" width="515" height="13" backcolor="#E6E6E6" uuid="6b37b78b-a8fe-497c-8266-7029bfa327e6"/>
                <textElement textAlignment="Right"/>
                <textFieldExpression><![CDATA["Page "+$V{PAGE_NUMBER}+" of"]]></textFieldExpression>
            </textField>
            <textField evaluationTime="Report">
                <reportElement mode="Opaque" x="515" y="8" width="40" height="13" backcolor="#E6E6E6" uuid="95b2ed71-fa56-43af-bc36-44f93a377437"/>
                <textFieldExpression><![CDATA[" " + $V{PAGE_NUMBER}]]></textFieldExpression>
            </textField>
            <textField pattern="EEEEE dd MMMMM yyyy">
                <reportElement x="0" y="4" width="100" height="13" uuid="19ca911f-a36f-4549-b58f-866a11508e95"/>
                <textFieldExpression><![CDATA[new java.util.Date()]]></textFieldExpression>
            </textField>
            <line>
                <reportElement x="0" y="2" width="556" height="1" uuid="626fba8b-3b52-4e3a-a726-266aebe08c93"/>
            </line>
        </band>
    </pageFooter>

        <band/>

</jasperReport>

A: The solution was comment the line in skip-networking the configure file of mysql, my.cnf

A: I'm not sure if is the same case but I was deling with the same error for hours just to notice that I was closing the connection before sending it to the report