text:
Q: Sql fetch result from multiple table having same column but no relation Hello all how can get two same name column from two different table as single result in two different column as combine result.
Eg: customer table have column customerid

custmerId
customerName

1
row

2
row

Order Table
it has also column customerid

custmerId
orderName

1
order1

4
order2

5
order3

Expected Output

custmerId
custmerId

1
1

2
4

5

Note: There is no relation between both table

A: it's not possible. it's better to use aliases or group by.
you can use alias, a 'SELECT AS', to seprate column names:
SELECT o.CustomerID as OCustomerID, c.CustomerId as CCustomerID
FROM Customers AS c, Orders AS o;

A: If by result, you mean a simple SELECT query result, you can just indicate the column name in a SELECT clause and separate the table names with a comma in the FROM clause. see example below:
SELECT customerID FROM Customers, Orders;
You can also add a "WHERE" clause at the end if you have conditions the query needs to meet.

A: MySQL does not support FULL JOIN, so
WITH
cte1 AS ( SELECT customerId, ROW_NUMBER() OVER (ORDER BY custmerId) rn
          FROM customer ),
cte2 AS ( SELECT customerId, ROW_NUMBER() OVER (ORDER BY custmerId) rn
          FROM order ),
cte3 AS ( SELECT rn FROM cte1 UNION SELECT rn FROM cte2 )
SELECT cte1.customerId, cte2.customerId
FROM cte3
LEFT JOIN cte1 USING (rn)
LEFT JOIN cte2 USING (rn);

Remember that an outer client software which accesses the output rowset columns by the name (not by the posession) won't print the result correctly. In this case you must assign unique aliases to the output columns. For example,
.. SELECT cte1.customerId AS customer_id, cte2.customerId AS order_id ..


text:
Q: Alternate message when VBA can't open file I have a VBA script that when the user executes it, it opens and writes new data to another file on a Network share drive.  Occasionally the script can't access this file to write new data to it because someone else is simultaneously trying to open it (via read only through a VBA script that they have).
This particular file opening error is not caught in the error handling code and a box comes up and asks the user to End or Debug.  Is there a way to bring up an alternate popup box that says something like "Could not process request.  Please wait a few seconds and try again."

A: yes. put in error handling around the file opening code. like this:
on error goto FileError
    'file opening code
on error goto 0

exit sub
FileError:
    msgbox("Could not process request. Please wait a few seconds and try again")

basically, the OnError tells everything after that statement to do whatever you specify in the event of an error. in this case I've put goto FileError so if an error is encountered anywhere after the onError processing will stop and go to the line marked FileError.
then the OnError goto 0 disables that error handle. that way if other code generates an error it wont be handled by the FileError handle. the other option for onerror is OnError Resume Next which makes the program skip over code that generates an error. so it wont throw the error, and it will just continue processing.
Note the: Exit Sub before the FileError label, that way the code wont go into the FileError label unless it is sent there by an error being generated.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Understanding turbostat debug mode max turbo output Does the output of running turbostat --debug show max turbo per core per socket?
below is an example output. If I have say a 2 socket Server does that mean 2 active cores per Socket can boost to 4GHz (4 cores total) or over both sockets - so only 1 core per socket=2 cores in total?
cpu0: MSR_NHM_TURBO_RATIO_LIMIT: 0x25262727
37 * 100 = 3700 MHz max turbo 4 active cores
38 * 100 = 3800 MHz max turbo 3 active cores
39 * 100 = 3900 MHz max turbo 2 active cores
40 * 100 = 4000 MHz max turbo 1 active cores

I also presume a core here is made up of 2 cpu's I.e a dual socket 20 core machine has 40 cpu's per socket?
Any help is much appreciated - thanks!


text:
Q: How to mock a request in ruby on rails How to mock a request in ruby on rails
I am making a call to multiple external sites via API and facing lot of failures in the response due to net read timeout error and parameters errror , run time errors, etc.
I want to mock the request before making a original call to the API. So that i can avoid more failures in my app.
Can any one help me ?

A: Try using the VCR gem, it records HTTP request for you, the first time you run your tests. For subsequent tests VCR uses the previously recorded HTTP response.
This should solve your timeout errors and allow you to work with external API's more easily.
Checkout these resources for more info:

*

*https://www.relishapp.com/vcr/vcr/docs

*http://natashatherobot.com/vcr-gem-rails-rspec/


text:
Q: dColumns returning Nan with dictionary mapping I have a data frame that looks like below:
         City         State              Country
      Chicago            IL        United States
       Boston
    San Diego            CA        United States
  Los Angeles            CA        United States
San Francisco
   Sacramento
    Vancouver            BC               Canada
      Toronto

I have 3 lists that contain all the missing values:
city_list = ['Boston', 'San Francisco', 'Sacramento', 'Toronto']
state_list = ['MA', 'CA', 'CA', 'ON']
country_list = ['United States', 'United States', 'United States', 'Canada']

And here's my ideal result:
         City         State              Country
      Chicago            IL        United States
       Boston            MA        United States
    San Diego            CA        United States
  Los Angeles            CA        United States
San Francisco            CA        United States
   Sacramento            CA        United States
    Vancouver            BC               Canada
      Toronto            ON               Canada

I used a potential method that's suggested by a helpful person, but I've been scratching my head and couldn't figure out what went wrong. And here's the code:
state_dict = dict(zip(city_list, state_list))
country_dict = dict(zip(city_list, country_list))
df = df.set_index('City')
df['State'] = df['State'].map(state_dict)
df['Country'] = df['Country'].map(country_dict)
df.reset_index()
print(df.City, df.State, df.Country)

But every cell of the State and Country columns return NaN.
         City         State         Country
      Chicago           NaN             NaN
       Boston           NaN             NaN
    San Diego           NaN             NaN
  Los Angeles           NaN             NaN
San Francisco           NaN             NaN
   Sacramento           NaN             NaN
    Vancouver           NaN             NaN
      Toronto           NaN             NaN

What went wrong here? And how would you change the code? Thanks.

A: I think that map should be called on the 'City' rather than 'State' field, like so:
df['State'] = df['City'].map(state_dict)

However, this has the problem that it overwrites any original 'State' values for cities which are not in your dictionary - e.g. 'Chicago'. One solution that gets around this is the following syntactically clumsier (but I believe correct) code:
df['State'] = df.apply(lambda x: state_dict[x['City']] if x['City'] in state_dict else x['State'], axis=1)

And it'll be the same idea for the country field.
I should add that this only works if you do not first set 'City' as index as you have in your example.


text:
Q: Pass value of dropdownlist when click button I have a dropdownlist in my View:
@Html.DropDownListFor(m => m.APtTitleData.apt, (IEnumerable<SelectListItem>)ViewBag.apt, "-Select Apt-", new { id = "SelectedAPt", name= "SelectedAPt" })

and I have a button in the same View
GO

How do I pass the value of the dropdown to my controller (Edit)? I'm trying to get the value to the button, but I'm not sure this is the right way. Any other idea?

A: I would suggest that you use a form where you submit the value from the dropdown to the controller.
Please check out the following code:
@using (Html.BeginForm("APtTitle", "Edit", FormMethod.Post))
{

            AptTitles

                @Html.DropDownListFor(m => m.APtTitleData.apt, (IEnumerable<SelectListItem>)ViewBag.apt, "-Select Apt-", new { id = "SelectedAPt", name= "SelectedAPt" })

                <input type="submit" value="Submit" />

}

And in the controller your code should look similar to the following:
[HttpPost]
public ActionResult Edit(string SelectedAPt)
{
   var aPtValue = SelectedAPt;

    // Do what intended with the value
}

You should now be able to see the value in the controller now.
Try it out and let me know if you run into issues.


text:
Q: ComboBox из XML-файла. Есть Xml-файл с таким содержимым:
<Student Id="0">
<FirstName>Robert</FirstName>
<Last>Jarman</Last>
<Age>21</Age>
<Gender>0</Gender>

<Student Id="1">
<FirstName>Leona</FirstName>
<Last>Menders</Last>
<Age>20</Age>
<Gender>1</Gender>

И так еще много студентов
Задачей является вывести все значения в ComboBox, или любые подходящие поля.
Прочитать смог таким образом: XDocument doc = XDocument.Load(path);
А как их впихнуть в разные поля Combobox?
Спасибо =)

A: Хоть я в XML и не спец, но давайте попробуем так:

*

*Загрузим наш файл в строку: var xmlStr = File.ReadAllText("temp.xml");.

*Загрузим в XElement нашу строку: var str = XElement.Parse(xmlStr);

*Хм, а что же дальше? А дальше давайте создадим небольшой список, который будет в себе иметь всех студентов: var students = str.Elements("Student");

*Отлично, есть студенты, в удобном списке. Давайте пройдемся по ним, хм, циклом, но перед этим создадим необходимый элемент, в который мы будем добавлять наших студентиков, пусть будет ComboBox. В Xaml: <ComboBox x:Name="ComboBox1" />

*Отлично, теперь дело цикла!:

foreach (var student in students)
{
    var id = student.FirstAttribute.Value;
    var FirstName = student.Element("FirstName")?.Value;
    var Last = student.Element("Last")?.Value;
    var Age = student.Element("Age")?.Value;
    var Gender = student.Element("Gender")?.Value == "0" ? "Дядя" : "Тетя";
    ComboBox1.Items.Add($"[{id}] {FirstName} {Last} это {Gender} и за плечами {Age} г. ");
}

p.s. Не форматировался код без цитаты, если кто сможет, уберите ее.

Что мы тут видим? Хм, а нечего сверх сложного, просто у каждого объекта, который найдется для нашего цикла, мы отберем необходимые нам параметры, дальше мы их попросту добавим в наш ComboBox1.

A: Вы делаете как-то слишком вручную. Выучите MVVM на досуге!
Имея класс Student из этого вопроса, проблема решается совсем просто.
<ComboBox ItemsSource="{Binding Students}">
    <ComboBox.ItemTemplate>
        <DataTemplate DataType="{x:Type local:Student}">
            <TextBlock>
                <Run Text="{Binding FirstName, Mode=OneWay}"/>
                <Run Text="{Binding Last, Mode=OneWay}"/>
                <!-- и так далее -->
            </TextBlock>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>


text:
Q: Angular 6 - no manifest was fetched I'm trying to use a Service worker in my app.
I've added @angular/pwa,
registered the service worker:
if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('/ngsw-worker.js', {
        scope: '/'
    }).then((registration) => {
        console.log("Service worker OK!")
    });
}

When i run Google Lighthouse on my local everything work perfect, and the site works in online mode, but whednI upload my app to server I recive an error in Lighthouse:
No manifest was fetched.

Do I use a wrong path?
manifest.json:
"start_url": "/index.html",

A: After adding the @angular/pwa, double check these:
1.In your angular.json file, under assets, add the manifest.json, like below
        "assets": [
          "src/favicon.ico",
          "src/assets",
          "src/manifest.json"
        ],

2.Your manifest.json file should be in the src/ directory, so src/manifest.json
3 Then in your ngsw-config.json file, you should have this:
  "files": [
    "/favicon.ico",
    "/index.html",
    "/manifest.json"
  ],

Do the three steps above, and you're good to go.

A: That error means that your index.html file doesn't tell browsers about the manifest. Add:
<link rel="manifest" href="manifest.json">

A: For me putting the manifest at the top section of the head tag did it.  I was loading scripts embed scripts from Facebook and Twitter, and angular had placed the
at the bottom of head tag.  Moving it above the scripts section somehow fixed it.


text:
Q: Mocking both Model.objects.bulk_create and Model.save() I'm attempting to mock both bulk_create and save for a dry run.
I've created code which in essence does following:
@mock.patch.object(SomeModel.objects, 'bulk_create')
@mock.patch.object(SomeModel, 'save')
def a_dry_run(mocked_bulk_create, mocked_save):

   def print_bulk(obj_list):
       print 'doing bulk_create'
       for obj in obj_list:
          print obj

   def print_save(instance):
       print 'doing save'
       print instance

   mocked_bulk_create.side_effect = print_bulk
   mocked_bulk_create.return_value = True
   mocked_save.side_effect = print_save
   mocked_save.return_value = True

The problem is that when I do bulk_create instead of print_bulk it executes print_save. How do I fix that or is there a cleaner way to do that?

A: The order of argument should be reversed. As you can see at Quick Guide where describe patch the order of mock arguments passed to the function follow patch's decorator from bottom to top.
In you case simply change the patch order or the function signature like
def a_dry_run(mocked_save, mocked_bulk_create):


text:
Q: linear mixed models: (in)appropriate factor level setup? + rank deficient matrix warning I'm trying to run a mixed-effects model to look at the effects of three treatments on weight in two different groups. I have two questions - I'm really sorry if they're stupid ones. I have next to no experience using R; my supervisor said that I should use RStudio and gave me some code (which...he didn't write either, so he can't really help me with it...and nor can anybody else in my lab.), and I'm uncertain about whether it's doing what I need it to be doing. I'd really appreciate some help.
The first question is about the way my factor levels function in the analysis. My groups and factor levels are set up as follows:
GT<- as.factor(data$GT)
AT <- as.factor(data$AT)
FM <- as.factor(data$FM)
batch <- as.factor(data$BOX)

data$GT<-factor(data$GT,levels = c("WT", "m5"))
data$AT<-factor(data$AT,levels = c("no","yes"))
data$FM<-factor(data$FM,levels = c("no","yes"))

Notably, everyone in FM is also in AT.
(i.e. for both WT and M5, there's ATno/FMno, ATyes/FMno, and ATyes/FMyes, but no ATno/FMyes treatments)
This is the code I've been given:
Weight<- data[,53:58]
Weight.new <- organise_data(data = Weight, groups = group.info,
                                new_var_name = 'Time')
Weight.new$Time <- factor(Weight.new$Time,
                              levels = c('Weight_W8','Weight_W9','Weight_W10',
                                'Weight_W11','Weight_W12', 'Weight_W13'))
Weight.new$Time = as.numeric(Weight.new$Time)
Weight.lmm <- lmer(value ~ GT + AT + FM + Time + GT*FM + AT*FM + GT*AT*FM + (1|BOX), na.action=na.omit,
                      data = Weight.new)
summary(Weight.lmm)

Will this mean that results for ATyes include both ATyesFMTno and ATyesFMTyes? If so, given ATyesFMTno and ATyesFMTyes are different treatment groups they should be looked at separately, right? How should I do this?
Second, two of the interactions (AT * FM and GT * AT * FM) are always dropped with the following warning:
fixed-effect model matrix is rank deficient so dropping 2 columns / coefficients

I understand there can be a number of reasons for this, and that it's not necessarily a fatal kind of thing, but here I'm worried that it's because I'm using the model inappropriately, or have incorrectly specified some terms or something. Is this an appropriate way to have structured things? Again, I'm sorry if this is completely obvious, I'm just a bit inexperienced and overwhelmed and there's nobody else I can ask. Any advice would be extremely appreciated.


text:
Q: Facebook post to friends is any way to post request to user friends without dialog , maybe trow api?
function post_request($fbApp, $fbID, $post)
 {
  static $ins;
 if (empty ($ins[$fbApp]))
  {
     Facebook::setConfig ($fbApp);
     $ins[$fbApp] = new Facebook();
  }
 try
  {
  $res = $ins[$fbApp] -> api ('/' . $fbID . '/apprequests', 'POST', $post);
  return true;
  }
 catch (FacebookApiException $e)
  {
  return false;
  }
 }

A: No, not anymore. Could be done long time ago, but since 2010 I think, no.


text:
Q: Sufficient condition for an operator to be orthogonal Lets say I want to prove that an operator $T:V\rightarrow V$ is orthogonal, i.e. for all $u,v \in V: \langle \ f(u) \mid f(v)\ \rangle = \langle \ u \mid v\ \rangle$, Is it sufficient to prove that $\|v\|=\|f(v)\|$ for all $v\in V$?
because I am trying to understand a proof of a theorem that states the following:

$\forall v\in V$ s.t. $v$ is a unit vector $f(v)$ is also a unit vector then $f$ is orthogonal.

In the proof the start with a $v\neq 0$ and they get to $\|v\|=\|f(v)\|$. shouldn't we prove that for all $u,v \in V: \langle \ f(u) \mid f(v)\ \rangle = \langle \ u \mid v\ \rangle$?

A: Yes, it is sufficient to prove that $f$ preserves norms (and by homogeneity, that is equivalent to $f$ mapping unit vectors to unit vectors). This follows from the polarisation identity.
Let $u, v \in V$ arbitrary. If $V$ is a real inner product space, we have
\begin{align}
\langle u \mathop{\vert} v\rangle &= \frac{1}{4}\lVert u+v\rVert^2 - \frac{1}{4}\lVert u - v\rVert^2 \\
&= \frac{1}{4}\lVert f(u+v)\rVert^2 - \frac{1}{4}\lVert f(u-v)\rVert^2 \\
&= \frac{1}{4}\lVert f(u) + f(v)\rVert^2 - \frac{1}{4}\lVert f(u) - f(v)\rVert^2 \\
&= \langle f(u)\mathop{\vert} f(v)\rangle
\end{align}
if $f\colon V \to V$ is a norm-preserving linear map.
If $V$ is a complex inner product space, the polarisation identity is
$$4\langle u\mathop{\vert} v\rangle = \lVert u + v\rVert^2 - \lVert u - v\rVert^2 + i\lVert u + iv\rVert^2 - i\lVert u - iv\rVert^2$$
(assuming the inner product is linear in the first argument and antilinear in the second; in the physicist's convention, the right hand side equals $4\langle v\mathop{\vert} u\rangle$ instead). The rest of the argument is the same as in the real case.


text:
Q: Default desktop theme still boots, after being deleted Ubuntu 20.04 still boots into the default desktop theme, on Budgie and Gnome.
This is after I deleted/moved all the desktop environment themes:
sudo mv /usr/share/themes /usr/share/themes_backup
rm -Rfv $HOME/.themes
rm -Rfv $HOME/.local/share/themes
How is this possible?

NB. Also asked under question here:
https://discourse.ubuntubudgie.org/t/cannot-change-themes-after-hard-reset/5066/9

A:
If by "default theme" you mean "the default theme for GTK applications
and GNOME Shell", then it's expected: the default themes in both cases
is embedded into GTK and GNOME Shell, respectively, as without a
default theme both applications and the shell would be utterly broken.
I guess the actual question is: what is it that you're trying to
achieve.
ebassi, GNOME Team

Answer quoted from https://discourse.gnome.org/t/is-the-default-desktop-theme-backed-up-outside-usr-share-themes/6877


text:
Q: What is the best way to manage authentication for a large number of servers in a datacenter? I'm running a large number of servers (several hundreds) in a local datacenter. Currently most of them are Windows servers of various types, but more and more are Linux.
I would like to know what the best practice is for managing authentication on these servers for system administrators. I can deploy SSH keys to the Linux servers, and the Windows servers are domain members, but is it a better idea to use PAM to authenticate the Linux servers to the AD domain?
If I was running a completely homogeneous Linux environment, how would this answer change? Surely an AD domain wouldn't be reasonable if it were the only Windows machine?

A: I would use a combination of AD and OTP (one time password - vaultssh works great)


text:
Q: Define a random 3-D array x2 of shape (x, y, z) and of numbers between 0 and 1 Note: Set numpy random seed value 100
• Define a random 3-D array x2 of shape (x, y, z) and of numbers between 0 and 1
• Print the value of x2
✓ Sample Case
Sample Input
3 4 2
Sample Output
[[[0.00568851 0.25242635]....

A: It is always great to show what efforts you have been already done to solve this problem, how far you've got.
If the distribution is uniform, I'd use a code like this:
import sys
import numpy
numpy.random.seed(100)

if __name__ == "__main__":
    x, y, z = [int(val) for val in sys.argv[1:4]]
    rnd_mat = numpy.random.uniform(low=0, high=1, size=(x, y, z))
    print(rnd_mat)

A: This was the question I was attempting today & I've made it to the answer
import numpy as np
import random

a = np.random.uniform(0,1,x*y*z)
print(x)
x1 = a.reshape(x,y,z)
x1

This answers your question.

The question is just the second part of this entire question in HackerRank. You can visit the question here.


text:
Q: Can I use where clause instead of AND in given SQL query? If yes, whats the difference in both? Came across this query online some where, explaining inner join with a condition (incentive>3k).Was just wondering if I can use where clause instead of 'AND' in below SQL, if yes, whats will be the output difference in both?
SELECT FIRST_NAME,
       INCENTIVE_AMOUNT
FROM employee a
     INNER JOIN incentives B ON A.EMPLOYEE_ID = B.EMPLOYEE_REF_ID
                                AND INCENTIVE_AMOUNT > 3000;

A: yes, you can try this
Select FIRST_NAME,INCENTIVE_AMOUNT from employee
     inner join incentives B on A.EMPLOYEE_ID=B.EMPLOYEE_REF_ID
where INCENTIVE_AMOUNT >3000

A: I guess you can use it
Select FIRST_NAME,INCENTIVE_AMOUNT from
employee inner join incentives B on
A.EMPLOYEE_ID=B.EMPLOYEE_REF_ID
where INCENTIVE_AMOUNT >3000

A: I don't know about Oracle but, at least for INNER JOIN, MySQL treats the WHERE conditions the same as the join conditions. It checks all of them that can be checked as soon as possible while it computes each row to put in the result set.
These two queries produce the same resultset (and afaik MySQL processes them about the same way):
SELECT FIRST_NAME, INCENTIVE_AMOUNT
FROM employee a
  INNER JOIN incentives B
     ON A.EMPLOYEE_ID = B.EMPLOYEE_REF_ID AND INCENTIVE_AMOUNT > 3000

and
SELECT FIRST_NAME, INCENTIVE_AMOUNT
FROM employee a
  INNER JOIN incentives B
WHERE A.EMPLOYEE_ID = B.EMPLOYEE_REF_ID AND INCENTIVE_AMOUNT > 3000

There is no difference in the output of INNER JOIN but if you move the join conditions in the WHERE clause of a LEFT/RIGHT JOIN you get a different result set.
The query:
SELECT FIRST_NAME, INCENTIVE_AMOUNT
FROM employee a
  LEFT JOIN incentives B
     ON A.EMPLOYEE_ID = B.EMPLOYEE_REF_ID AND INCENTIVE_AMOUNT > 3000

includes in the result set all the rows from table employee, matching with a row full of NULLs the rows that do not have a match (on the join condition) in table b.
But this query:
SELECT FIRST_NAME, INCENTIVE_AMOUNT
FROM employee a
  LEFT JOIN incentives B
WHERE A.EMPLOYEE_ID = B.EMPLOYEE_REF_ID AND INCENTIVE_AMOUNT > 3000

combines all the rows of table a with all rows of table b and then the WHERE clause keeps only the matching rows from the two tables. Its output is identical with the above two INNER JOIN queries.

A: They come to the same thing.
However, it is generally considered good practice to use join clauses only for specifying joins, and keep filter predicates in the where clause, hence:
select first_name, incentive_amount
from   employee e
       join incentives i
            on  i.employee_ref_id = e.employee_id
where  i.incentive_amount > 3000

(Note that the inner and outer keywords are optional and in my view redundant clutter, so I never use them.)
In the case of outer joins (left join, or if you absolutely must, left outer join), the whole idea of separating the filter predicates and placing them in the where clause goes out of the window, because (for example) if there is no incentive row then i.incentive_amount will be null and so any predicate whatsoever will exclude the row. Some say this is why ANSI join syntax is rubbish and the distinction between join and filter predicates is artificial and pointless, while others see it as a quirk of an otherwise helpful syntax.
select first_name, incentive_amount
from   employee e
       left join incentives i
            on  i.employee_ref_id = e.employee_id
            and i.incentive_amount > 3000

You could still follow the convention for inner joins in the same query, e.g:
select first_name, incentive_amount
from   employee e
       join departments d
            on d.department_id = e.department_id
       left join incentives i
            on  i.employee_ref_id = e.employee_id
            and i.incentive_amount > 3000
where  d.name = 'Philology'

Just to add, I agree with Jonathan Lewis that a and b are terrible aliases for employee and incentives. (By the way, why not employees or incentive?) In my version I have used the surely more readable e and i.


text:
Q: Is it possible to activate ionic app on call I am not sure it is possible in ionic or not. What i want to do is create an app that can record user calls. so app must be activate when user make or get a call.
can anyone tell me if it is possible, how to do this?

A: Beware this won't be an easy task but "never give up, never surrender". You'll want to use a variation of techniques first off this isn't an Ionic thing as much as it is a PhoneGap thing - ionic runs on phonegap.
Your workflow will look something like this:

*

*User opens your app sees a list of contacts
(the formatted names of contacts are different for android & ios so be prepared to test for this.
http://ngcordova.com/docs/plugins/contacts/)

*Contacts are displayed in ion-list user select one and phone's dialer launches (use href=tel:xxxxx)
From there you're going to want to trigger the audio capture plugin's API
https://github.com/apache/cordova-plugin-media-capture
To add the plugin to your project:
cordova plugin add cordova-plugin-media-capture

While it doesn't directly say it can record in call conversations it should still work.
It can definitely be done the storage space is also of concern, you'll have to set something in place to tell the user how many seconds/minutes they have the capacity to store.
That should get you started there will certainly be unforeseen nuances.
Good luck.

A: We can record calls with cordova-media-plugin plugin in android.
First install the media Plugin by executing the following command
cordova plugin add cordova-plugin-media
Then goto the Plugin folder and traverse into the following file "plugins\cordova-plugin-media\src\android\AudioPlayer.java" . Here in the startRecording function we have line
this.recorder.setAudioSource(MediaRecorder.AudioSource.MIC); line number is 154
Change it to this.recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
We can replace MIC with any audio source in the following link. for example VOICE_COMMUNICATION,VOICE_DOWNLINK,VOICE_RECOGNITION etc
https://developer.android.com/reference/android/media/MediaRecorder.AudioSource.html


text:
Q: Application crashes when increase the images I want to load the memory of the android device. I have tried using drawable images but the app crashes as number of images increases. So I was thinking to make an app with following scenario:-
How can I make an android application whose wallpapers keep on changing after a fixed interval. Say I have 10 images and want each one to be displayed in the background of the android application after a gap of say 10 seconds. I would like to achieve this using a service, so that it keeps on working even if the application is minimized.
Since I am new to android please be thorough and show patience with me.

A: I suggest you to use View Flipper to slide images and Also have a look at startFlipping() and setFlipInterval() methods in ViewFlipper class
For more check this
and for View flipper see this

A: This temporary solution not good solution
In manifest file -> Use android:largeHeap="true" in your application tag
It will increase the allocation for memory size for your application.
< application
    android:name=".MyApplication"
    android:largeHeap="true"
.................................
/>

Official document -
http://developer.android.com/guide/topics/manifest/application-element.html#largeHeap


text:
Q: Relative paths not set at debugging, Why? I retrieve the values using simple C++ code to check the assigned values of XML Loader and load the XML scenario file by setting relative path like this.
"loader.LoadXMLScenarioFile("relative path");"
But when debugging loader doesn't load the value if we are not setting up the absolute path.
But its successfully write the values to text file and it's works correctly.
Why it is happen?

A: Since you are using VS2008 you should double check your debug settings. Especially the path settings for the debugger.
Look at Properties->Configuration Properties->Debugging. Is the working directory really what you expect for your relative path? By default it is set $(ProjectDir) which is not the directory where your executable is.


text:
Q: How can I forward my selected items to another page in Flutter I have some datas and I can see in the homepage.
I want to see also in the another page, how can i do this?
I have card for example, and It has some datas like fav_numbers, name, last_name etc. and I want to pass these informations to another page. Then, I can see these cards (only selected) in the another page. How can i do this?
I want to pass like this:
ElevatedButton(
onPressed: () {
AutoRouter.of(context).push(
PeopleRoute(
name: games[index]["name"],
surname: games[index]["surname"],
luckyNumber: games[index]["luckyNumber"]),
 );
 },
child: Icon(CupertinoIcons.add),
 ),

and I can use these informations in people page like widget.name or widget.surname . But I need to a list right? Because I do not want to show just 1 card, I want to show when user click PLUS(+) button, then I want to show cards which are selected.
If you show simply, I can continue with using other state management ways...

A: Just I needed to create items in another widget, which I wanted.


text:
Q: What's the equivalent of CloseableService in Quarkus / RestEasy I am migrating a REST-Service from Jersey to Quarkus/RestEasy. Jersey can inject different Context objects into the Resource classes, among them is a CloseableService that you can use to robustly handle Closeable resources, no matter what goes wrong with the request (Runtime Exceptions, Aborted Connections, etc.).
The signature of a resource method looks roughly like this:
    @Path("/datasets/{dataset}")
    @Consumes("application/json")
    @Produces("application/json")
    @GET
    public Stream<TSRecord> getDatasetDataJson(
            @PathParam("dataset") final String dsName,
            @QueryParam("parameter") final Parameter parameter,
            @Context final CloseableService closer
    ) throws NoSuchDatasetException {
        final Stream<TSRecord> stream = database.stream(dsName, parameter);
        closer.add(stream::close);
        return stream;
    }

What is the equivalent of a CloseableService in Quarkus/RestEasy?


text:
Q: How to get a link to go to a specific div on another page Say I have a link that says:
Services
When I click on that link I want to obviously go to the services page, but what I am trying to figure out is how can I get that link to take me to a specific section on that page.
The thing is, the page I want to show a specific section, it does not show unless I hit a tab. Here is what my services page looks like. You will see if you click a tab a specific section will show up.
https://jsfiddle.net/esayoaqg/1/
If I clicked on a link referring to Service 1, I want the link to go to the services page and show the div #service1.
How can I do this?
Service 1
Service 2
Service 3

$(function(){

    //get the section name from hash
    var sectionName = window.location.hash.slice(1);

    //then show the section
    $('#service-display-box').show();
    //$('#' + sectionName ).show();
    $('#service' + sectionName).show().siblings().hide();
})

A: you could use hash sign #:
Services

//services.html

...

UPDATED:
if you need to auto show a section after page loaded, you could do something like:
$(function(){

    //get the section name from hash
    var sectionName = window.location.hash.slice(1);

    //then show the section
    $('#' + sectionName ).show();
})

A: You can use
blah blah

show this content

and then use a show content based on scroll or window location..
Most likely will need javascript of the sorts to get it how you want.

A: You can use an anchor, but it will not set the hidden element to visible.
You'll need to add some javascript to display it.
Based on the example in your fiddle, it would be as follows:
var index = location.hash.indexOf('#service');
if(index > -1) {
    var serviceId = parseInt(location.hash.substring(index));
    if(serviceId) {
        $('#service-display-box').show();
        $('#service' + serviceId).show().siblings().hide();
    }
}


text:
Q: Richfaces 3 on Payara 5: Request prolog cannot be read I'm attempting to move an existing Richfaces 3.3.4 / JSF 1.2 application off Glassfish 3 (for a number of reasons) onto Payara 5.192.  The application runs fine with a couple exceptions, the primary problem being rich:fileUpload doesn't work.
I added multipart-config to web.xml, but that didn't resolve the problem:
    <context-param>
        <param-name>javax.faces.DISABLE_FACELET_JSF_VIEWHANDLER</param-name>
        <param-value>true</param-value>
    </context-param>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
        <multipart-config>
            <max-file-size>33554432</max-file-size>
            <max-request-size>335544320</max-request-size>
        </multipart-config>
    </servlet>

Here is the error:
org.ajax4jsf.exception.FileUploadException: IO Error parsing multipart request
    at org.ajax4jsf.request.MultipartRequest.parseRequest(MultipartRequest.java:388)
    at org.richfaces.component.FileUploadPhaselistener.beforePhase(FileUploadPhaselistener.java:63)
    at com.sun.faces.lifecycle.Phase.handleBeforePhase(Phase.java:201)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:74)
    at com.sun.faces.lifecycle.RestoreViewPhase.doPhase(RestoreViewPhase.java:109)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:177)
    at javax.faces.webapp.FacesServlet.executeLifecyle(FacesServlet.java:707)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:451)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1628)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:339)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:209)
    at org.ajax4jsf.webapp.BaseXMLFilter.doXmlFilter(BaseXMLFilter.java:206)
    at org.ajax4jsf.webapp.BaseFilter.handleRequest(BaseFilter.java:290)
    at org.ajax4jsf.webapp.BaseFilter.processUploadsAndHandleRequest(BaseFilter.java:367)
    at org.ajax4jsf.webapp.BaseFilter.doFilter(BaseFilter.java:515)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:251)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:209)
    at org.apache.catalina.core.ApplicationDispatcher.doInvoke(ApplicationDispatcher.java:822)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:688)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:527)
    at org.apache.catalina.core.ApplicationDispatcher.doDispatch(ApplicationDispatcher.java:496)
    at org.apache.catalina.core.ApplicationDispatcher.dispatch(ApplicationDispatcher.java:378)
    at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:507)
    at org.apache.catalina.core.StandardHostValve.dispatchToErrorPage(StandardHostValve.java:701)
    at org.apache.catalina.core.StandardHostValve.status(StandardHostValve.java:385)
    at org.apache.catalina.core.StandardHostValve.throwable(StandardHostValve.java:319)
    at org.apache.catalina.core.StandardHostValve.postInvoke(StandardHostValve.java:217)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:373)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:238)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:520)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:217)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:182)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:156)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:218)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:95)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:260)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:177)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:109)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:88)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:53)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:524)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:89)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:94)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:33)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:114)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:569)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:549)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.io.IOException: Request prolog cannot be read
    at org.ajax4jsf.request.MultipartRequest.readProlog(MultipartRequest.java:333)
    at org.ajax4jsf.request.MultipartRequest.initialize(MultipartRequest.java:369)
    at org.ajax4jsf.request.MultipartRequest.parseRequest(MultipartRequest.java:379)
    ... 47 more¡ëôwÍ$


text:
Q: Laravel 5.2 new query results get back to old when click on pagination I've applied search form in my app's index page. Results gets updated when I search for something. But when I click on the pagination, it gets me back to old results. So, I guess I've to update the pagination or clear cache or something and how to do it?
In routes.php
Route::get('/', 'BookmarkController@index');
Route::post('/', 'BookmarkController@search');

In BookmarkController.php
public function index(Request $request) {
    $tags_list = Tag::orderBy('tag', 'asc')->get();
    $bookmarks = Bookmark::orderBy('created_at', 'desc')->where('public', '1')->paginate(3);
    $bookmarks_all = Bookmark::orderBy('created_at','desc')->where('public', '1')->get();

    return view('welcome')
        ->with('bookmark', $bookmarks)
        ->with('tags_list', $tags_list)
        ->with('bookmarks_all', $bookmarks_all)
    ;
}

public function search(Request $request) {
    $search_value = $_POST['search'];
    $tags_list = Tag::orderBy('tag', 'asc')->get();
    $bookmarks = Bookmark::orderBy('created_at', 'desc')
        ->where('public', '1')
        ->where('title', 'rlike', $search_value)
        ->orwhere('description', 'rlike', $search_value)
        ->orwhere('contents', 'rlike', $search_value)
        ->orwhere('tags', 'rlike', $search_value)
        ->paginate(3)
    ;

    $bookmarks_all = Bookmark::orderBy('created_at', 'desc')->where('public', '1')->get();

    return view('welcome')
        ->with('bookmark', $bookmarks)
        ->with('tags_list', $tags_list)
        ->with('bookmarks_all', $bookmarks_all)
        ->render()
    ;
}

In welcome.blade.php
    @if (count($bookmark) > 0)

            @foreach ($bookmark as $bookmark_single)

                                thumbnail}}" />

                                    {{ $bookmark_single->title }}

                                    {{ str_limit($bookmark_single->description, $limit = 50, $end = ' [...]') }}

<?php   $tags = $bookmark_single->tags;
                                    $tag_list = explode(',', $tags); ?>
                                    @foreach ($tag_list as $tag)
                                        {{$tag}}
                                    @endforeach

-  bookmarker }}">{{ $bookmark_single->bookmarker }}

                                url }}">Visit the link

                            <button type="button" class="btn btn-success btn-circle btn-lg btn-read-more"></button>

                            {{ print $bookmark_single->contents }}

            @endforeach

                {{!!$bookmark->render()!!}}

        @endif

Search form HTML in welcome.blade.php
<form id="demo-2" action="/" class="search-form col-sm-4" method="post">
    {{ csrf_field() }}

        <input id="search" class="form-control" placeholder="Search" name="search" value="" type="text">

            <button class="btn btn-primary" id="search-btn" type="submit"></button>

</form>

A: When you click on a pagination link you initiate a get request to the same page and end up on your first route that uses BookmarkController@index
One possible solution here is to change search route to get instead of post like:
Route::post('/search', 'BookmarkController@search');

and make sure your pagination applies to this new route like /search?page=2
If you want to keep the search login in the index method you need to make sure non of search filters apply if it's blank
public function index(Request $request) {
    $tags_list = Tag::orderBy('tag', 'asc')->get();
    $bookmarks_all = Bookmark::orderBy('created_at','desc')->where('public', '1')->get();

    $search_value = $request->input('search', '');

    $bookmarks = Bookmark::where(function($query) use ($search_value) {
        if (!empty($search_value)) {
            $query->where('title', 'rlike', $search_value)
            ->orwhere('description', 'rlike', $search_value)
            ->orwhere('contents', 'rlike', $search_value)
            ->orwhere('tags', 'rlike', $search_value)
        }
    })->where('public', '1')->orderBy('created_at', 'desc')->paginate(3);

    return view('welcome')
        ->with('bookmark', $bookmarks)
        ->with('tags_list', $tags_list)
        ->with('bookmarks_all', $bookmarks_all)
    ;
}

And change your search form method to get


text:
Q: Using whenever gem to schedule a cron job I'm testing whenever to figure out how to use it and am running into trouble even after reading the Github documentation.
I simply want to update the attributes of my model like this (config/schedule.rb)
set :output "/log/today.log"
every 10.seconds do
  runner "Example.update_all(sample: Time.now)"
end

I am neither seeing a log file nor seeing the model attributes updated.
Is there anything I am not doing correctly?

A: First you need to add your cron job in the cron tab.
If you do not want to add because you are just testing it, you can try the code given below(which i did for my rails application).
cd /home/your_home/your_project && script/your_script -e <environment> "method_call"
In your case:
environment = development
method_call = Example.update_all(sample: Time.now)
It might help you.


text:
Q: git pull error when trying to deploy to AWS EC2 I am trying to commit some new lines of code from my repository to Aws. I have everything synced on Github. Trying to do a pull from my repository to the EC2 instance.
I ssh in to my EC2, no issues here, but when I do "git pull" (and enter in my github username and password) i get a prompt saying:
"You are not currently on a branch. Please specify which branch you want to merge with. See git-pull(1) for details. git pull <remote> <branch>".

Update:
I tried a 'git checkout master' before the 'git pull' but it messed up by EC2, the site is down with these errors - 'Pull is not possible because you have unmerged files. Please, fix them up in the work tree, and then use 'git add/rm <file>' as appropriate to mark resolution, or use 'git commit -a '
Appreciate your help!

A: Try git checkout -b <your_branch>, it seems that your local Git isn't working in any branch right now.


text:
Q: How do I change icon size in folders? Is it possible, and how do I change icon size in my folders in Ubuntu 14.04?  This was part of the folder menu in 12.04, but is missing in 14.04.

A: You can also use these keyboard shortcuts to zoom in and out.

*

*Ctrl + + to increase the size (zoom in)

*Ctrl + - to decrease the size (zoom out)

*Ctrl + 0 to revert to normal size

A: Try this : Hold Ctrl key and scroll.
Hope this work for you.


text:
Q: How to disable external javascript execution / site requests in phantomjs I am trying to run some tests on a website looking for issues.
For the record, I am using phantomjs with the ghostdriver in selenium from C#
Everything is working fine, but I would like to speed things up. Checking on the headers in fiddler, a lot of time is spent on external calls to external sites (facebook / twitter) for the social plugins all sites seem to think is a good idea these days :-\
I am not required to test these functions, so am trying to disable external site calls, which should speed my tests up some what.
Is there a way in phantom to get the effect that noscript / ghostery gives in firefox?

A: To filter invalid requests, you could use the onResourceRequested callback : this allow you to abort unwanted urls.
Here is a basic example for stackoverflow.
var system = require('system');
var page = require('webpage').create();
var domain = 'stackoverflow.com'
var url = 'http://www.stackoverflow.com';

page.onResourceRequested = function (requestData, networkRequest) {
    if (requestData.url.indexOf('.js')===-1 && requestData.url.indexOf(domain) === -1) {
        networkRequest.abort();
        console.log('aborted :'+ requestData.url)
    }
};

page.onResourceReceived = function (response) {
    console.log('Response (#' + response.url + ', stage "' + response.stage + '"): ');
};

if (system.args.length !== 1) {
    console.log("Usage: phantomjs filter.js url");
} else {
    page.open(url, function (status) {
        if (status = 'succeed') {
            console.log("status", status);
            phantom.exit(0);
        }
    });
}

Note that it's not recommended to abort js files, as this can cause a javascript error on you page.
Another way to speed up your test is to disable images using argument --load-images=false


text:
Q: How do I send an email via mime-mail-ses which has a proper "from" name? The SES data type has the sesFrom field. Everywhere on the Internet I see that I should write something like "\"My Name\" <mymail@gmail.com>" in order to display My Name in the "from" field. But when I put this into the sesFrom field I get
Not sent due to SESException {seStatus = Status {statusCode = 400, statusMessage = "Bad Request"}, seCode = "InvalidParameterValue", seMessage = "Missing '<'", seRequestId = "acf8bb7d-0440-11e8-94c8-45570c829243"}

I checked sources and all seems to be fine there. How do I set the sesFrom field, so a name is displayed?

A: OK, got it. Instead of writing "\"My Name\" <mymail@gmail.com>" :: Address and relying on OverloadedStrings one should write
Address (Just "Ny Name") "mymail@gmail.com"

I'd say the library should parse "\"My Name\" <mymail@gmail.com>" into that address, but whatever.


text:
Q: Recurrence General formulas In this post I will share general formulas for recurrences I have worked out, just for fun.
And you are more than welcome to share yours.
I will also include a table for a quick check.

A: *

*

$$u_{n} = au_{n-1} + b$$
$$\Downarrow$$
i: $$u_n = u_0a^n + \frac {b(a^n-1)} {a-1} $$
or ii: $$u_n = u_0a^n + Σ_{m=1}^{n} ba^m$$

Proof:
Introduce another recurrence $v$, define $v_n = u_n + \frac b {a-1}$
$\therefore u_n = v_n - \frac b {a-1}$
$v_n = u_n + \frac b {a-1} = (au_{n-1} + b) + \frac b {a-1} = au_{n-1} + \frac {ab}{a-1} = a(u_{n-1} + \frac b {a-1}) = av_{n-1}$
$\therefore v_n = av_{n-1}$ (definition of $v$ in terms of $v$)
$v_n = a^rv_{n-r} = a^nv_0$ (general formula for $v$)
$\because u_n = v_n - \frac b {a-1}$ (definition of $v$ in terms of $u$)
$\therefore u_n = a^nv_0 - \frac b {a-1} = a^n(u_0 + \frac b {a-1}) - \frac b{a-1}$ (substitute $v$ s with $u$ s)
$u_n = a^nu_0 + \frac {a^nb} {a-1} - \frac b {a-1} = a^nu_0 + \frac {a^nb-b} {a-1} = a^nu_0 + \frac {b(a^n-1)} {a-1}$
$\therefore$
$$u_n = a^nu_0 + \frac {b(a^n-1)} {a-1}$$
Notice that the second term is the formula for a geometric series (Kadry, 2014) $ba^{n-1}$
Therefore the expression above equals to:
$$u_n = u_0a^n + Σ^n_{m=1} ba^m$$

Reference:
Seifedine Kadry,
Mathematical Formulas for Industrial and Mechanical Engineering,
Elsevier,
2014,
Pages 65-111,
ISBN 9780124201316,
https://doi.org/10.1016/B978-0-12-420131-6.00005-1.
(https://www.sciencedirect.com/science/article/pii/B9780124201316000051)


text:
Q: using "AND" and "OR" in an SQL query I am trying to optimize a query. There are three different lookups in the table, which i think, are not required.
This is the original query, which i want to optimize.
SELECT DISTINCT(productid) FROM q_products
      WHERE visibility=1 and status=0 AND productid IN (productidList)
        UNION ALL
      SELECT DISTINCT(q_products.productid) FROM q_products,q_product_apply_access
        WHERE q_products.productid=q_product_apply_access.productid
        AND q_product_apply_access.partnerid='partnerid'
        AND q_product_apply_access.apply_status=0
        AND q_products.visibility=3 AND q_products.status=0
        AND q_products.productid IN (productidList)
        UNION ALL
      SELECT DISTINCT(q_products.productid) FROM q_products,q_product_aff_access
        WHERE q_products.productid=q_product_aff_access.productid
        AND q_product_aff_access.accid='accountid'
        AND q_products.visibility=2 AND q_products.status=0
        AND q_products.productid IN (productidList)

Let me walk you all through this query,
1) I am selecting distinct productid from q_products which have visibility=1 and status=0 and which are also in productidList
2) I am now selecting distinct productid from q_products and checking if same productid is present in another table q_product_apply_access, if so, then checking if q_product_apply_access.partnerid is same as given to us and also if q_product_apply_access.apply_status is 0 and then again, checking if those productids are in productidList.
3) It does similar things and at the end checks again if productids are in productidList.
My idea to optimize was is to do the following way ->
1) select all productids from q_products which are in my productidList.
2) check if those productids are in tables q_product_apply_access and q_product_aff_access and if yes, then their subsequent conditions are fulfilled.
3) when all this is done, i check which of those have q_products.visibility IN (1,2,3) and q_products.status=0.
I think in that way i can minimize lookups in the table and my query would be queried in minimal subset of productidList which may contain only upto 20-30 rows.
Here is my code for that , but I am not getting the correct answer. Can anyone tell me how I can do it? or How I should apply nested loops here?
SELECT DISTINCT(productid)
        FROM q_products as oc,
        q_product_apply_access  as ocaa,
        q_product_aff_access as ocfa
        WHERE productid IN (productidList)
          AND (
            (oc.productid=ocaa.productid
            AND ocaa.affiliateid='partnerid'
            AND ocaa.apply_status=0)
            OR
            (oc.productid=ocfa.productid
            AND ocfa.accid='accountid')
            )
          and status=0
          AND visibility IN (1,2,3)

A: The title of your question:

using "AND" and "OR" in an SQL query

Might be more accurately defined as:

Will using "AND" and/or "OR" statements help this query run faster?

And, the short answer is, NO.-- the optimizations will probably need to be done elsewhere.
So, the long answer:
After looking at this for a while, the requirements 'baked into' the original query prevent logical JOINs from speeding anything up. Your best bet to get this to run faster is to utilize indexes on the tables being referenced. My original answer was using inner-selects, but didn't meet the requirements. By requirements, I mean the necessity of returning a list of unique productids from the productid table meeting three different and distinct criteria.
That said, I would re-write the original query into something more readable, using JOIN statements and aliases for readability (note the absence of DISTINCT -- the UNION ensures unique records out of all 3 result sets):
SELECT p.productid
FROM q_products p
WHERE visibility = 1
  AND status = 0
  AND productid IN (productIdList)

UNION

SELECT p.productid
FROM q_products p
JOIN q_product_apply_access paa ON paa.productid = p.productid
WHERE paa.partnerid = 'partnerid'
  AND paa.apply_status = 0
  AND p.visibility = 3
  AND p.status = 0
  AND p.productid IN (productidList)

UNION

SELECT p.productid
FROM q_products p
JOIN q_product_aff_access paf ON paf.productid = p.productid
WHERE paf.accid = 'accountid'
  AND p.visibility = 2
  AND p.status = 0
  AND p.productid IN (productidList)

Original Answer
So, the problem you're having is a bit difficult as it's hard to wrap my head around the original query in the first place. That said, I threw together a possible solution using inner-selects as joins to the q_products table. I haven't tested it, so let me know how it turns out:
SELECT
*
FROM
    q_products p
    JOIN (
        SELECT productid FROM q_product_apply_access paa
        WHERE paa.productid = p.productid
          AND paa.partnerid = 'partnerid'
          AND paa.apply_status = 0
          AND p.visibility = 3
    ) paa ON paa.productid = p.productid
    JOIN (
        SELECT productid FROM q_product_aff_access paf
        WHERE paf.productid = p.productid
          AND paf.accid = 'accountid'
          AND p.visibility = 2
    ) paf ON paf.productid = p.productid
WHERE
    p.status = 0
    AND p.productId IN ( productIdList )

A: INDEX(visibility, status, productid)

with your original UNION ALL
Please provide SHOW CREATE TABLE; that may prompt other techniques.
(Edit)
After the fact, you can do
ALTER TABLE q_products ADD INDEX(visibility, status, productid);

It will take some time, depending on the size of the table.
An INDEX is usually much smaller than the table, itself.
Indexes are your first line of defense against slow queries.  (Rewriting is the second.)
How big is q_products?

A: Your original query, slightly reformatted, is:
SELECT DISTINCT(q_products.productid)
  FROM q_products
 WHERE q_products.visibility = 1
   AND q_products.status = 0
   AND q_products.productid IN (productidList)
UNION  ALL
SELECT DISTINCT(q_products.productid)
  FROM q_products, q_product_apply_access
 WHERE q_products.productid = q_product_apply_access.productid
   AND q_product_apply_access.partnerid = 'partnerid'
   AND q_product_apply_access.apply_status = 0
   AND q_products.visibility = 3
   AND q_products.status = 0
   AND q_products.productid IN (productidList)
UNION  ALL
SELECT DISTINCT(q_products.productid)
  FROM q_products, q_product_aff_access
 WHERE q_products.productid = q_product_aff_access.productid
   AND q_product_aff_access.accid = 'accountid'
   AND q_products.visibility = 2
   AND q_products.status = 0
   AND q_products.productid IN (productidList)

You've not told us whether there are any other values for visibility other than 1, 2, 3 so we have to assume there can be other values (but note the comments below this answer).
We can see that there are some common sub-expressions restricting rows from q_products (status = 0 and productid IN (productidList), where it isn't clear what productidList really is, but we can assume it works OK.
It would be really useful if MySQL had support for CTEs (common table expressions, aka WITH clauses):
WITH pv AS
     (SELECT productid, visibility
        FROM q_products
       WHERE status = 0
         AND visibility IN (1, 2, 3) -- or visibility >= 1 and visibility <= 3
         AND productid IN (productidList)
     )
SELECT pv.productid
  FROM pv
 WHERE pv.visibility = 1
UNION  ALL
SELECT DISTINCT(pv.productid)
  FROM pv
  JOIN q_product_apply_access AS a
    ON pv.productid = a.productid
 WHERE pv.visibility = 3
   AND a.apply_status = 0
   AND a.partnerid = 'partnerid'
UNION  ALL
SELECT DISTINCT(pv.productid)
  FROM pv
  JOIN q_product_aff_access AS f
    ON pv.productiond = f.productid
 WHERE pv.visibility = 2
   AND f.accid = 'accountid'

Since MySQL doesn't yet support CTEs, you probably have to write the CTE out verbatim 3 times and hope that the optimizer spots what you're doing.  Or, since all of the alternatives are about to filter more precisely on visibility, you include that term in a modified form of the CTE (and avoid selecting visibility explicitly) and write it out three times — like this:
SELECT pv.productid
  FROM (SELECT productid
          FROM q_products
         WHERE status = 0
           AND visibility = 1
           AND productid IN (productidList)
       ) AS pv
UNION  ALL
SELECT DISTINCT(pv.productid)
  FROM (SELECT productid
          FROM q_products
         WHERE status = 0
           AND visibility = 3
           AND productid IN (productidList)
       ) AS pv
  JOIN q_product_apply_access AS a
    ON pv.productid = a.productid
 WHERE a.apply_status = 0
   AND a.partnerid = 'partnerid'
UNION  ALL
SELECT DISTINCT(pv.productid)
  FROM (SELECT productid
          FROM q_products
         WHERE status = 0
           AND visibility = 2
           AND productid IN (productidList)
       ) AS pv
  JOIN q_product_aff_access AS f
    ON pv.productiond = f.productid
 WHERE f.accid = 'accountid'

This should produce the same result.  It is hard to be sure that it will be faster.  It may depend on whether there are suitable indexes on the status and visibility columns of q_products.  The first term of the UNION could be written more simply, but this presentation is uniform with the other two alternatives, which tends to make these things clearer (to the human reading the query, and possibly to the query optimizer too).
As always, studying the actual query plan may help you improve things.


text:
Q: javascript await function in script returns Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules I have an async function on a .js file. for example :
async function LoadProducts() {
return new Promise(resolve => {
    PageMethods.set_path('/xxx/xxxx.aspx');
    PageMethods.GetToken(OnSuccess, OnError);

    function OnSuccess(Token) {
        var settings = {
            "url": "xxx",
            "method": "POST",
            "timeout": 0,
            "headers": {
                "Token": Token,
                "Content-Type": "application/json; charset=UTF-8"
            },
            "data": JSON.stringify({
                "xxx": xxx
            }),
        };

        $.ajax(settings).done(function (response) {
            $("#divProducts").append(Ret);
            resolve('');
        });
    }

    function OnError(Error) {
        resolve('error');
    }
});

}
I want to call this function from html, in order to Load some products this way :
<div id="divProducts">
</div>
<script>
    await LoadProducts();
</script>

I get error : Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules.
I need to Load this part of the page before other scripts (of html template) run, that's why i use this way.
Any Ideas?
Thanks!

A: finally, i had to write in html this way :
<script type="module">
    await LoadProducts();
</script>


text:
Q: How can I dynamically set router options in a Meteor application using the iron router package? I would like to set a route option label to that of the current url, e.g.
Router.route('/:_url', {
  label: '_url',
  action: function () {
    this.render('home');
  }
});

This is my helper:
if (Meteor.isClient) {
  Template.home.helpers({
    getLabel: function() {
      return Router.current().route.options.label;
    }
  });
}

This is my template:
<template name="home">
  hi
  {{getLabel}}
</template>

When I visit locolhost:3000/alexander I should see hi alexander however I see hi _url
How can I get the _url variable to correctly resolve so I see hi alexander ?

A: Router.route("/:name", {
  name: "home",
  template: "home",
  data: function(){
    // this will create a new key myName on the route object for this route
    // and set the value to the name that the user entered in the path
    this.route.options.myName = this.params.name;
    return {
      label: this.params.name
    };
  }
});

// All routes are stored in the Router.routes array
// Loop through it to find the only one with a myName key and return the value

for (var i = 0; i < Router.routes.length; i++){
  if (Router.routes[i].options.myName){
    console.log(Router.routes[i].options.myName);
  }
}

A: You can set the data context of your route to include the URL parameter like this :
JS
Router.route("/:name", {
  name: "home",
  template: "home",
  data: function(){
    return {
      label: this.params.name
    };
  }
});

HTML
<template name="home">

Hi {{label}}

</template>


text:
Q: Android Viewholder package com.jakewalther.x;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.List;

public class adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
Context context;
List<users> users;
public adapter(List<users> getDataAdapter, Context context){
    super();
    this.users = getDataAdapter;
    this.context = context;
}

public adapter(List<users> usersList, LoadXOrgasm context) {
}

@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview, parent, false);
    ViewHolder viewHolder = new ViewHolder(view);
    return viewHolder;
}

@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
    users getDataAdapter1 =  users.get(position);
    holder.UserName.setText(getDataAdapter1.getName());
}

@Override
public int getItemCount() {
    return users.size();
}

class ViewHolder extends RecyclerView.ViewHolder {
    public TextView UserName;
    public ViewHolder(View itemView) {
        super(itemView);
        UserName = (TextView) itemView.findViewById(R.id.TextViewCard) ;
    }
}

I am trying to make an adapter for a recycler view. Getting a compile error cannot find UserName at the line
holder.UserName.setText(getDataAdapter1.getName());

I have tried everything I can't figure out why the code won't run.

A: Your problem is You are extending ViewHolder of RecylerView, not your custom ViewHolder.in onBindViewMethod() you have to check that holder instance will be of Your custom Viewholder instance.
 if(holder intanceOf ViewHolder ){ //here ViewHolder is your custom holder class

            ((ViewHolder ) holder).UserName((getDataAdapter1.getName());

        }

A: replace your onBindViewHolder with this,
 @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        ViewHolder viewHolder = (ViewHolder)holder;
        users getDataAdapter1 =  users.get(position);
        viewHolder.UserName.setText(getDataAdapter1.getName());
    }


text:
Q: Android Instrumentation - How to detect external activity call I am using Robotium for testing android applications and am interested in how to detect a situation when an external application activity (e.g. browser, camera, facebook) is being launched by tested app. There are several questions asking how to handle such situation, but all I need is to detect it, for example just log time when it's occurred. Is this possible using Robotium or simple Instrumentation?
BTW, I can't use the solution when system apps are being replaced by fake analogues, I can't even know what application (and when) will be launched, because the tests are random. (Yes, I know, it's a bad approach, but this is a project restriction).

A: See my answer here. The main idea is to detect current top Activity, which is Activity of external application. You can create Service, which will monitor top activities.

A: Anther way is to check when your activity looses focus. When it looses focus that means that the other external Activity has focus instead.
http://developer.android.com/reference/android/app/Activity.html#hasWindowFocus()
You can use Solo.waitForCondition() in conjunction with hasWindowFocus.


text:
Q: Pascals identity when k=n Pascal's identity states that $\binom{n}{k}$ = $\binom{n-1}{k-1}$ + $\binom{n}{k+1}$
However, if we let k = n then according to the identity we have that $\binom{n-1}{n-1}$ + $\binom{n}{n+1}$ which is then undefined if I am correct. So must n>k for the identity to be defined?


text:
Q: Does the phrase "apace with" mean "to keep pace with"? Merriam Webster says the below:

Definition of apace with : going or advancing at the same rate as (something)
E.g. The company has been struggling to keep pace/apace with the latest developments

But I've not seen this definition in other dictionaries like Oxford Advanced's Learners Dictionary. Can someone kindly share if this is accurate?

A: This usage has been commonplace for nearly two centuries, at least regionally. The early uses seem to be in the form of keep apace. Stay apace being a less common version that appeared about 80 years later.
The following were gleaned from Elephind.

1851 - The Cornwall Chronicle (That's Cornwall California, in the off-chance there are others)
Nor is the tone of
moral feeling, in or out of cities, of a low,
vicious, or evil character ; but as the diffi
culties of subsistence accumulate, and want
and famine approaches — as come it will to
many — outrages will doubtless increase,
and keep apace with tbe poverty and misery
under which many thousands, I fear, are
doomed to perish during the present wintry
season of that country.

There were a few slightly earlier references from the American Midwest or Southwest, but the digitized text wasn't available.

... , where the national open championship opens it*, tumultuous three-day stand tQday. There are 6,709 yards of velvety greensward to be done in 7? -strokes by the player who would stay apace with par—approximately 100 yards more than at either Olympia fields or Winged Foot, where the last two opens have been held—but there is considerable more to the course .
Page 11 [Newspaper Page] — Indianapolis Times — 10 July 1930
Publication Title: Indianapolis Times
Source: Indiana Digital Historic Newspaper Program (Indiana State Library)
Country/State of Publication: Indiana, United States

Speed Enables Press To Stay Apace Of War
The Kent Stater, Volume XVII, Number 71, 18 February 1942

This one is interesting since it is oriented towards the idea of speed, but is used as a comparison to a benchmark.

https://texashistory.unt.edu/ark:/67531/metapth283646/m1/1/zoom/?q=%22stay%20apace%22&resolution=2&lat=2703.1249999999995&lon=661.5
However, Rotan enjoys a good water supply at this time with a 16 mile gravity flow pipe line from wells. It has been necessary to keep digging wells to stay apace of demand.
April 20 1949.

The context here is a comparison to demand, and that doesn't carry any semantic sense of speed at all.
I leaned heavily on the stay apace version because I think it more clearly restricts the usage to the abreast with or consistent with sense. All the early examples appear to be American.
Personally, I have only ever used apace in this comparative sense. I had thought the earlier sense was obsolete.
After several hours of poking around, I did find one recent example where I'm reasonably confident that the writer meant quickly.

The JCPOA puts a temporary lid on Iran's uranium-enrichment and plutonium programs, but other nuclear developments – testing of more advanced centrifuges, stockpiling of uranium, and enhancing nuclear manufacturing infrastructure – continue apace. Developments on Tehran's missile program therefore cannot be dealt with in isolation from its nuclear efforts.
https://www.fdd.org/analysis/2017/02/08/irans-missile-tests-reveal-weaknesses-of-un-security-council-resolution/
Olli Heinonen
Foundation for Defense of Democracies

So I sampled other uses of apace in this context (JCPOA, P5+1) but only found the comparative use I am accustomed to. But the negotiations were largely an American thing, and the commentary above was from someone born in Finland.

A: It seems that MW is ahead of the game but only if you believe the dictum "When enough people are wrong, they are right."
A Google search for  To keep apace of and to keep apace with shows relatively frequent collocations. Apace (adverb) seems to be a substitute for the original noun "pace."
From Google:
keep apace of

M&S digital lab brings nimble start up approach https://www.marketingweek.com › ms-digital-lab-bring...
Marks & Spencer has created its own in-house "digital lab" division to keep apace of developments that will make sure its business remains relevant to the ...
Forthcoming Events - Cinema Theatre Associationhttps://cinema-theatre.org.uk › visits-events › forthcomi...
Keeping apace of developments in the field of high-tech film exhibition, we are privileged to have a presentation about the latest IMAX installation at ...
Iron and Steelworks of the World - ProQuesthttps://search.proquest.com › openview
by T Smith · 2002 — An attempt has also been made to try and keep apace of developments in the USA with eight of the present 28 companies in Chapter 1 1 bankruptcy protection ...
PSS Across the UK | Port Skills and Safetyhttps://www.portskillsandsafety.co.uk › news › pss-acro...
24 Nov 2020 — ... automation of port operations and how PSS must stay apace of developments in this field in order to provide a well-rounded service.

to keep apace with

Who to follow on Twitter to keep apace with PropTechhttps://www.lendinvest.com › blog › whos-proptech-twi...
2 Sept 2016 — Who to follow on Twitter to keep apace with PropTech. London PropTech is having its moment. If you're as keen as us to know what is going on ...
Quality childcare matters - Care Inspectorate Waleshttps://www.careinspectorate.wales › quality-childcare-...
24 Aug 2015 — To do this we will continue to improve on our inspection methods and keep apace with modern practice to have a greater impact on improving ...
Stars of film criticism show how to keep apace with ... - Swissinfohttps://www.swissinfo.ch › eng › stars-of-film-criticism-...
12 Aug 2022 — Stars of film criticism show how to keep apace with the changes in the industry. Debate with critic Laura Mulvey at Locfarno75 ...
Apace Synonyms & Antonymshttps://www.synonyms.com › synonym › apace
... upbeat about credit demand, but we'll have to see how the capitalization of banks evolves and whether it can keep apace with this appetite for credit.
SuperGroup to open new fulfilment centre to keep apace with ...https://www.retail-week.com › 5048235.article
SuperGroup to open new Burton-on-Trent fulfilment centre to keep apace with growing sales. By Nicola Harrison15 April 2013. No comments.


text:
Q: the maximum of several right continuous stepfunctions are also right continuous I want to proof that in general the maximum (or minimum) of several right continuous step functions are also right continuous. For example, consider $g_1$, $g_2$ and $g_3$ defined as follows:
$  g_1 (x)  \left\{
\begin{array}{ll}
      0 & 0 \le x < 0.5 \\
       0.5 & 0.5 \le x < 1 \\
     1 & x \ge 1 \\
 \end{array}
\right. $;
$  g_2 (x)  \left\{
\begin{array}{ll}
      0 & 0 \le x < 0.25 \\
       0.25 & 0.25 \le x < 1 \\
     1 & x \ge 1 \\
 \end{array}
\right. $ and
$  g_3 (x)  \left\{
\begin{array}{ll}
      0 & 0 \le x < 0.6 \\
       0.6 & 0.6 \le x < 1 \\
     1 & x \ge 1.
 \end{array}
\right. $
Define $f(x)=max\{g_1(x), g_2(x), g_3(x) \}$, $\forall x \in [0, \infty].$
How to approach a general proof. Thanks!!

A: Let $g_1,\ldots, g_n\colon I\to \Bbb R$ be right continuous step functions and $f\colon \Bbb R^n\to\Bbb R$ an arbitrary function. Then $F(x):=f(g_1(x),\ldots, g_n(x))$ defines a right continuous step function $F\colon I\to \Bbb R$.
We need to show that for all $x\in I$, there exists $\epsilon>0$ such that $F$ is constant on $[x,x+\epsilon)$.
So let $x\in I$ be given. For each $i$, we know that there exists $\epsilon_i>0$ such that $g_i|_{[x,x+\epsilon_i)}$ is constant. Let $\epsilon=\min\{\epsilon_1,\ldots,\epsilon_n\}$. Then all $g_i$ are constant on $[x,x+\epsilon)$, henec so is $F$.

A: The $\max$ function is continuous, hence if $f_1,f_2$ and $f_3$ are right-continuous we have
\begin{align}
\lim_{x\to c^+}\max\{f_1(x),f_2(x),f_3(x)\}
&=\max\{\lim_{x\to c^+}f_1(x),\lim_{x\to c^+}f_2(x),\lim_{x\to c^+}f_3(x)\}\\
&=\max\{f_1(c),f_2(c),f_3(c)\}
\end{align}
which implies that $g(x)=\max\{f_1(x),f_2(x),f_3(x)\}$ is itself right-continuous.


text:
Q: MyObjectBox is not generated in kotlin (objectbox library) I am trying to use Object Library.
I read the official documentation and follow the instructions. But still, it not working.
The problem is when I try to initialize boxStore object I don't find MyObjectBox class.
val boxStore = MyObjectBox.builder().androidContext(this).build()

Here is my app module.
build.gradle (app module)
apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'

apply plugin: 'io.objectbox'

android {
    compileSdkVersion 26
    defaultConfig {
        ....
    }
    buildTypes {
        release {
           ....
        }
    }

    sourceSets {
        main.java.srcDirs += 'src/main/java'
    }
}

kapt {
    generateStubs = true

    arguments {
        arg("objectbox.debug", true)
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"

    ... other dependencies

    //object box
    implementation "io.objectbox:objectbox-android:$objectboxVersion"
    // some useful Kotlin extension functions
    implementation "io.objectbox:objectbox-kotlin:$objectboxVersion"
    kapt "io.objectbox:objectbox-processor:$objectboxVersion"

}

And Here is my project module:
build.gradle (project)
buildscript {
ext.kotlin_version = '1.2.10'
//all version
ext.support_version = '26.1.0'
ext.objectboxVersion = '1.3.3'

repositories {
    google()
    jcenter()
    maven { url "http://objectbox.net/beta-repo/" }
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.0.1'
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files

    //object box
    classpath "io.objectbox:objectbox-gradle-plugin:$objectboxVersion"
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven { url 'https://maven.google.com' }
        maven { url "http://objectbox.net/beta-repo/" }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

I am searching for the possible solution in several projects. I also follow the official demo app. But still, it not working for me?
Can anyone help me to fix this?

A: I think I finally found the solution: the important part is that you have to write the objectbox-gradle-plugin, above the kotlin-gradle-plugin in your project-level gradle file, the code looks like this :
classpath 'com.android.tools.build:gradle:3.2.1'
classpath "io.objectbox:objectbox-gradle-plugin:$objectboxVersion"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

After that, add the following lines under the other apply plugin:... in app-level gradle
apply plugin: 'kotlin-kapt'
apply plugin: 'io.objectbox'

Most Importantly, you have to make at least one @Entity class and rebuild the project, and MyObjectBox will appear.

A: Your setup looks good. Note that you do not need to add the objectbox-android, objectbox-kotlin or objectbox-processor dependencies. The plugin will do it for you.
Do you have at least one @Entity class defined? For example:
@Entity
public class User {
    @Id
    private long id;

    private String name;
}

Then Build > Make project. The annotation processor should pick up the entity and generate your MyObjectBox class.

A: I meet with the same question. My config is same with you.
Finally I found the reason.
@Entity
data class Person @JvmOverloads constructor(@Id var id:Long,
                                            var name:String,
                                            var age:Int,
                                            var high:Int)

Like this. You must define one bean first. Thus MyObjectBox will generate.

A: Had also issues here. Had 3 entities, but the MyObjectBox class was not generated. I had to use the advanced kapt setting for Kotlin, which solved the problem:
kapt {
    arguments {
        arg("objectbox.modelPath", "$projectDir/schemas/objectbox.json")
    }
}

Source: https://docs.objectbox.io/advanced/advanced-setup


text:
Q: Pepper cancel running animation Currently developping on a Pepper robot (Android dev), I'm trying to use some "basic" animations (from QiSQK lib).
For instance, when calling a WS, I'm starting a "think" animation using animation/animate. Then, when the WS call ends, I try to use another animation ("showing the tablet").
I saw that Pepper can't animate twice if the previous animation isn't finished/cancelled.
So, I used requestCancellation(), but it didn't stop the animation.
I also used cancel(mayInterruptIfRunning), didn't stop either.
So, I can't chain 2 animations without waiting the previous animation to stop (my WS call = 3-4s max).
Any idea ?
Example :
private var animate: Future<Animate>? = null

fun animate(animRes: Int) {
        animate?.requestCancellation()

        AnimationBuilder
                .with(qiContext)
                .withResources(animRes)
                .buildAsync()
                .thenConsume { futureAnimation ->
                    animate = AnimateBuilder
                            .with(qiContext)
                            .withAnimation(futureAnimation?.value)
                            .buildAsync()
                    animate?.andThenConsume {
                       it.async().run()
                    }
                }
}

Thx,
Bastien.

A: Finally found out my issue.
Actually, I was storing the animate reference when creating the object like this :
animate = AnimateBuilder
                  .with(qiContext)
                  .withAnimation(futureAnimation?.value)
                  .buildAsync()

So, I printed my objects (like every Future's used in my callbacks), then I found that after using it.async().run() from my animate andThenConsume callback, which returns the running animation reference, is different from the one I created before (was thinking reusing same old ref).
So, instead, here my new (working) code :
fun animate(animRes: Int) {
        //Cancelling possible running animation to display a new one
        animate?.requestCancellation()

        AnimationBuilder
                .with(qiContext)
                .withResources(animRes)
                .buildAsync()
                .thenConsume { futureAnimation ->
                    AnimateBuilder
                            .with(qiContext)
                            .withAnimation(futureAnimation?.value)
                            .buildAsync()
                            .andThenConsume {
                                animate = it.async().run() as Future<Animate>
                            }
                }
}


text:
Q: why does this particular program print me five? Please help me with this one guys! why are there arguments given to a method that is void??
public class C {
    public static void main(String[] argv) {
        int k = 1;
        int[] x = {0, 1, 2, 3};
        int[] y = x;
        lurig(x, y, k);
        System.out.println(x[0] + k + y[0]);
    }

    public static void lurig(int[] p, int[] q, int r) {
        p[0] = 1;
        q[0] = 2;
        r = 3;
    }
}

A: Your x and y array actually refer to the same location in memory. This means that after calling lurig(x, y, k) both x[0] and y[0] are 2.
If you want x and y to refer to seperate memory locations, you need to do it like this
int[] x = {0, 1, 2, 3};
int[] y = new int[4];
System.arraycopy(x, 0, y, 0, x.length);

A: x[0] is 0 k is 1 y[0] is 0
-> lurig() changes x[0] to 1 and y[0] to 2 but since y has the same reference as x it also changes x[0] to 2 k is a primitive type so it remains as 1 (completely unaffected)
-> 2 + 1 + 2 gives 5
5 is NOT returned it's being written out to the console. You don't have a return statement you have a System.out out stands for output.


text:
Q: How can we add / update a image path with own code without using ->addImageToMediaGallery() , on magento Can we update a own defined product image path to database, I am adding products with own custom code.I want to add image database without help of
->addImageToMediaGallery()

Is it doable?? without using this line i want to add direct path // external url to database
->setMediaGallery (array('images'=>array (), 'values'=>array ())) //media gallery initialization
->addImageToMediaGallery('xxx/my.jpg', array('image','thumbnail','small_image'), false, false)

A: Magento is a system which is having events and to handle those events there are observers. So my suggestion to you would be a strict no until you know which events will be triggered by  function addImageToMediaGllery() . You can do this if you know exactly which events will be triggered and you handle those events  accordingly.


text:
Q: Environment variables in Ubuntu Tomcat, Apache and Java I have a java web app running in Windows enviroment and I want to move it to Ubuntu system.
In windows I use an environment variable to store the main path:
MAIN_PATH=C:\test

This variable is used in many configuration files and  also by application, for example:

*

*Apache and Tomcat configuration file

*Application logging configuration (log4j)

*Java application itself by System.getEnv(...)

examples:
tomcat config
 <Host name="localhost"  appBase="${MAIN_PATH}/webapps" unpackWARs="true" autoDeploy="true">

apache virtualhost
<VirtualHost *:80>
    DocumentRoot "${MAIN_PATH}/www"
    ServerName testmain
    <Directory "${MAIN_PATH}/www">
...

I can not find some way to set it in ubuntu, I tried this places:
/etc/enviroment
/etc/profile

export MAIN_PATH=/opt/test in /etc/init.d/tomcat7.sh
All this solution didn't work or works just in one of my requirements (only in server configuration but not in application or vice versa).
Is nothing like windows global environment variable to use for all this cases?

A: Did you check ubuntu/linux documentation? It's fairly simple.
Refer to: https://help.ubuntu.com/community/EnvironmentVariables
This worked perfectly for me.

*

*$ nano /etc/environment (or whatever file editor you want to use)

*add 'export MAIN_PATH=/opt/test' to the file and save

*$ source /etc/environment

*$ echo $MAIN_PATH

*Output: /opt/test

A: I would recommend you keep the environment variables separate for each layer of your application. For example it might seem like putting everything in one place makes sense, but I don't feel it's good design to share a configuration directory for Apache and Tomcat. Both have standard locations for config files (e.g., $CATALINA_HOME/conf).
I wouldn't think you're using log4j on Apache so why put it in a custom directory that's shared with Apache. Put it in a conf folder inside your webapp, or in the previously mentioned top level conf directory. Maybe you'll have more than one webapp on Tomcat -- in that case it makes even more sense to have logging config files within the particular webapp directory.
It's also cleaner to have the environment variables contained within the process. They don't gum up the global environment variables. For example when you start Tomcat, the setenv.sh script runs and sets all the enviroment variables just for the java process that's running Tomcat.


text:
Q: ExecJS: keeping the context between two calls I'm currently trying to use ExecJS to run Handlebars for one of the product I work on (note: I know the handlebars.rb gem which is really cool and I used it for some times but there is issues to get it installed on Windows, so I try another homemade solution).
One of the problem I'm having is that the Javascript context is not kept between each "call" to ExecJS.
Here the code where I instantiate the @js attribute:
class Context
  attr_reader :js, :partials, :helpers

  def initialize
    src = File.open(::Handlebars::Source.bundled_path, 'r').read
    @js = ExecJS.compile(src)
  end
end

And here's a test showing the issue:
let(:ctx) { Hiptest::Handlebars::Context.new }

it "does not keep context properly (or I'm using the tool wrong" do
  ctx.js.eval('my_variable = 42')
  expect(ctx.js.eval('my_variable')).to eq(42)
end

And now when I run it:
rspec spec/handlebars_spec.rb:10                                                                   1 ↵
I, [2015-02-21T16:57:30.485774 #35939]  INFO -- : Not reporting to Code Climate because ENV['CODECLIMATE_REPO_TOKEN'] is not set.
Run options: include {:locations=>{"./spec/handlebars_spec.rb"=>[10]}}
F

Failures:

  1) Hiptest::Handlebars Context does not keep context properly (or I'm using the tool wrong
     Failure/Error: expect(ctx.js.eval('my_variable')).to eq(42)
     ExecJS::ProgramError:
       ReferenceError: Can't find variable: my_variable

Note: I got the same issue with "exec" instead of "eval".
That is a silly example. What I really want to do it to run "Handlebars.registerPartial" and later on "Handlebars.compile". But when trying to use the partials in the template it fails because the one registered previously is lost.
Note that I've found a workaround but I find it pretty ugly :/
  def register_partial(name, content)
    @partials[name] = content
  end

  def call(*args)
    @context.js.call([
      "(function (partials, helpers, tmpl, args) {",
      "  Object.keys(partials).forEach(function (key) {",
      "    Handlebars.registerPartial(key, partials[key]);",
      "  })",
      "  return Handlebars.compile(tmpl).apply(null, args);",
      "})"].join("\n"), @partials, @template, args)
  end

Any idea on how to fix the issue ?

A: Only the context you create when you call ExecJS.compile is preserved between evals.  Anything you want preserved needs to be part of the initial compile.


text:
Q: Time formatting in watchOS Complication I want to display a timer as part of a complication. The timer should only display minutes and hours. For this purpose I have created a CLKRelativeDateTextProvider and passed the corresponding units as an array to the initializer. So my current attempt looks like the following:
func currentTimelineEntry(for complication: CLKComplication) async -> CLKComplicationTimelineEntry? {
    let relativeProvider = CLKRelativeDateTextProvider(date: Date(), style: .timer, units: [.hour, .minute])
    let template = CLKComplicationTemplateGraphicCornerStackText(
        innerTextProvider: relativeProvider,
        outerTextProvider: CLKSimpleTextProvider(text: "Test")
    )

    return CLKComplicationTimelineEntry(date: Date(), complicationTemplate: template)
}

Unfortunately this doesn't work right, because seconds are displayed alongside minutes and hours.
So for example the following screenshot was taken at the moment where the timer displayed 29 seconds.

Do you have any idea how I could achieve a format like H:mm to display only the hour and minute at every point in time (29 seconds should be displayed as 0:00). I don't understand why the passed units are being ignored.
Thanks for your help :-)...
PS: I'm also open to other approaches like working with SwiftUI to get the time properly displayed but all my attempts in this direction haven't been successful so far.


text:
Q: fancybox: higher than viewport? I am using a fancybox to show some inline content on a listview. My problem is, that when the inline content is higher than the viewport, fancybox creates scrollbars inside the lightbox - but this is not the desiered effect. Instead i would like the lightbox/fancybox to addapt to the inline content, so that the scrollbar will be in the browser itself and not the lightbox.
Any ideas?

A: from api
autoScale  =    true  =>    If true, FancyBox is scaled to fit in viewport
look on the api document for more option
http://fancybox.net/api


text:
Q: Django with Postgres and advanced constraints I have the following model:
class AppHistory(models.Model):
    campaign = models.ForeignKey('campaigns.Campaign')
    context_tenant = models.ForeignKey('campaigns.FacebookContextTenant')
    start_date = models.DateField()
    end_date = models.DateField(blank=True, null=True)

The backend is a Postgres database. For the above model I need the following constraints to be checked before a dataset is inserted:

*

*A row can only be inserted if it does not overlap in the date (start_date - end_date) with an existing one with the same campaign and context_tenant

*A row can only be inserted if there's none with the same campaign and context_tenant where end_date is NULL

I know there's the option to do this in Django by performing a validation.
But I'd like to make sure that even manual insertion into the database are verified.
So currently I came up with two options, database constraints and triggers. I'm not too familiar with postgres, so I'm uncertain how extensive the constraints are. Is it possible to do the above restrictions with constraints only or should I use triggers (or even something else)?

A: I solved the problem by using constraints, such as
EXCLUDE USING gist (campaign WITH =, daterange(start_date, end_date) WITH &&)

A: you can use trigger in postgresql and RAISE EXCEPTION when data is invalid to roll back transaction
when you create your trigger you can use a custom migration to create trigger on database.
with migration.RunPython

A: You should override  save() method in your model
def save(self, *args, **kwargs):

    <add your conditions here>

    return super(AppHistory, self).save(*args,**kwargs)

For your first condition where you want to check uniqueness you should use,
class Meta:
    unique_together = ("campaign", "context_tenant", "start_date")


text:
Q: branch.io deep link with video-url in metadata not playing in whatsapp I'm using branch.io to deep-link to our flutter app. We have a sharable link to a post that has the video. I need to show the video from the link metadata when shared on WhatsApp, just like we see youtube's video - playable in-app.
I did tried the $og_video, $og_video_type, $og_video_height and $og_video_width tags but the link not previewing the video.
I checked youtube's metatags also, but it's no help.