text:
Q: How can one search TableDefs for linked tables? Looping through a set of TableDefs, how can one determine if each TableDef represents a linked table, as opposed to a local table?

A: Based on http://p2p.wrox.com/access-vba/37117-finding-linked-tables.html (the linked code resulted in an infinite loop, so I modified it):
Dim tdf As DAO.TableDef
With CurrentDb
    For Each tdf In .TableDefs
        If tdf.Attributes And dbAttachedODBC Or tdf.Attributes And dbAttachedTable Then
            ' We found a linked table! Now, show its location.
            Debug.Print tdf.Connect
        End If
    Next
End With

Taken directly from http://p2p.wrox.com/access-vba/37117-finding-linked-tables.html, the ADO counterpart (unverified code):
Sub ListAllTables(cnn As ADODB.Connection)

   Dim cat As ADOX.Catalog
   Dim tbl As ADOX.Table

   Set cat = New ADOX.Catalog
   cat.ActiveConnection = cnn

   cat.Tables.Refresh
   For Each tbl In cat.Tables
      Select Case tbl.Type
         Case "ACCESS TABLE"
            Debug.Print tbl.Name & " - Access table"
         Case "SYSTEM TABLE"
            Debug.Print tbl.Name & " - System table"
         Case "TABLE"
            Debug.Print tbl.Name & " - Native table"
         Case "LINK"
            Debug.Print tbl.Name & " - Linked table"
         Case "PASS-THROUGH"
            Debug.Print tbl.Name & " - ODBC DSN Linked table"
        End Select
    Next tbl

    Set tbl = Nothing
    Set cat = Nothing

End Sub

A: For a linked table, the TableDef.Connect property contains the connection information.  But for a native table, the .Connect property is an empty string.
So you can tell which are which by examining Len() of .Connect
Dim tdf As DAO.TableDef
With CurrentDb
    For Each tdf In .TableDefs
        If Len(tdf.Connect) > 0 Then
            Debug.Print tdf.Name, tdf.Connect
        End If
    Next
End With

That approach is simpler for me to remember than tdf.Attributes And dbAttachedODBC Or tdf.Attributes And dbAttachedTable, or the ADOX approach.  It is also much more concise than the ADOX approach.


text:
Q: Load data from database with gui c# and use SqlDataReader.ExecuteReader() twice I am very new to C# and coding, so I hope you will be patient with me. :)
I'm using Visual Studio 2013 and I built my  database connection and it worked. I will post my code tomorrow, but here my first example:
sSQL = "select person_id from person where person_email_adress = "+ email;
cmd.CommandText = sSQL
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();

while(dr.Read()){
   person_id = dr.GetString(0)
}

This worked fine, but my problem is in the second SQL command:
sSQL = "select article from purchase where person_id = "+ person_id;
cmd.CommandText = sSQL
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();

while(dr.Read()){
   // random stuff
}

My problem is, that my second SqlDataReader returns no rows, but if I run the same query in SQLDeveloper with the same person_id, I have more then 10 hits.
I know that the dr.Read() is empty, because I make the following thing:
if(!dr.HasRow) {
    MessageBox.text("This query is empty");
} else {
    MessageBox.text("This query got some hit");
}

I want to go in the while, and read the lines, but I always get the problem, that dr is empty.
I also checked if the SQL output is right with a MessageBox and it was right.
What now?
I hope you understand my bad English and if you have any question I am at your service. :)
Thanks and regards,
Xplosio

A: First I would debug line-by-line to make sure that person_id has the value you expect.
Second, I would change both queries to use parameters:
sSQL = "select article from purchase where person_id = :person_id";
cmd.CommandText = sSQL
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new OracleParameter("person_id", person_id))
OracleDataReader dr = cmd.ExecuteReader();

while(dr.Read()){

   // random stuff

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How did so many certificates in my Mac system, why I can't delete them? I've been experiencing a "ERR_BAD_SSL_CLIENT_AUTH_CERT" when visiting https://angular.io
I haven't solved this problem yet. But how does so many certificates in my Mac and I can't delete them? It is the 1st time I see this part of Mac OS.  How do I delete them?


text:
Q: LdapRepository configuration no match We're trying to set up an LdapRepository from Spring Ldap and struggling with retrieving a user list. The Ldap server is an ActiveDirectory.
We can log in via ActiveDirectoryLdapAuthenticationProvider using the same credentials.
Spring Properties:
spring.ldap.base=cn=Users,dc=company,dc=local
spring.ldap.password=secret
spring.ldap.username=useradmin
spring.ldap.urls=ldap://172.16.36.60:389

When reading out the inetOrgPerson retrieved from logging in, it says:
    dn="CN=useradmin,CN=Users,DC=company,DC=local"
So I think the base is correct.
No, when trying to .findAll() from the repository, nothing is found. Our model class currently looks like this.
@Entry(base="cn=Users,dc=company,dc=local",objectClasses = {"inetOrgPerson","top"})
public final class CompanyUser implements Serializable {

@Id private Name dn;
@Attribute(name="username") private String userName;
@Attribute(name="mail") private String email;
...
}

When leaving out the base on @Entry annotation, the repository will return count=0. With the base attribute on the annotation, query throws:
javax.naming.NameNotFoundException: [LDAP: error code 32 - 0000208D: NameErr: DSID-03100241, problem 2001 (NO_OBJECT), data 0, best match of:
'CN=Users,DC=company,DC=local'
]

A: Not adding base on the entity class is correct, if base is already fully defined in the properties.
The reason the server returned no results, could be fixed by removing "inetOrgPerson" object class from the @Entry, for now.


text:
Q: conditional build based on branch for multi stage pipeline using different templates under stages How to trigger by branch to use specific template under "stages"?
trigger:
 branches

   include:

     - ci

     - prod

stages:

*

*template: ci.yml
condition: and(eq(['build.sourceBranch'], 'ci'))

*template: prod.yml
condition: and(eq(['build.sourceBranch'], 'prod'))
Tried above condition but didn't work. I was getting "unexpected value condition". Any help is appreciated
***** Tried one of the solution as by passing condition as parameter to the template:
stages:

*

*template: ci.yml
parameters:
condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/ci'))

*template: prod.yml
parameters:
condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/prod'))
Getting "unexpected parameter condition"
Pipeline structure:
master.yml (contains runtime parameters)
stages:
template: ci.yml
parameters:
condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/ci'))
template: prod.yml
parameters:
condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/prod'))
ci.yml
stages:

*

*stage: BuildApp

*stage: BuildWeb

*stage: DeployLocal
prod.yml
stages:

*

*stage: BuildApp

*stage: BuildWeb

*stage: DeployProd

A:
How to trigger by branch to use specific template under "stages"?

To resolve this issue, we could add the condition on the job level, like:
stages:
- stage: Test1
  jobs:
  - job: ci
    displayName: ci
    pool:
      name: MyPrivateAgent
    condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/ci'))
    steps:
        - template: ci.yml

  - job: prod
    displayName: prod
    pool:
      name: MyPrivateAgent
    condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/prod'))
    steps:
        - template: prod.yml

Check the document Specify conditions for some more details.
On the other hand, we could also set the condition as parameter to the template yml, like:
- template: ci.yml
  parameters:
    doTheThing: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/ci'))

The template yml file:
# template.yml
parameters:
  doTheThing: 'false'
steps:
- script: echo This always happens!
  displayName: Always
- script: echo Sometimes this happens!
  condition: ${{ parameters.doTheThing }}
  displayName: Only if true

You could check the thread YAML - Support conditions for templates for some more details.
Hope this helps.


text:
Q: Passing values to input through g:each iteration Say if i have this data from my controller that i want to pass it to my GSP
def test = [value: ['TEST1', 'TEST2', 'TEST3']]

And in my GSP, i have the following
<g:set var="counter" value="${0}"/>
<g:set var="count" value="${count}"/>
<g:while test="${counter < count}">
    <g:set var="counter" value="${counter+1}"/>
    <g:each var='obj' in='${test}' status='i'>
        <g:textField id='justATest1' name='justATest' value='obj.value'>
        <g:textField id='justATest2' name='justATest' value='obj.value'>
        <g:textField id='justATest3' name='justATest' value='obj.value'>
    </g:each>
</g:while>

And i want it so that justATest1 will get TEST1,  justATest2 will get TEST2 and  justATest3 will get TEST3.
How can i achieve that?

A: Assuming your model contains the following
def myAction() {
    [value: ['TEST1', 'TEST2', 'TEST3']]
}

This should do it
<g:each status="i" in="${value}" var="item">
    <g:textField id="justATest${i}" name='justATest' value="${item}">
</g:each>

A: Ok seems i managed to iterate object in GSP
<g:each var='obj' in='${test}'>
    <g:each var='subObj' in='${obj.value}'>

${subObj}

    </g:each>
</g:each>

But kind of not elegant enough.
I can do it too with this, as what Donal put in his answer
<g:each var='obj' in='${test.value}'>

${obj}

</g:each>

But it would be hard i think if i want to iterate each item inside test object separately and uniquely.
Anyone please feel free to fix my approach.


text:
Q: Knockout JS Checkbox List not binding I have an issue where my checkbox list is not binding when loading data from the server.
So I have a table where you select a client when I click the edit button a bootstrap modal window popup with all the information fields such as first name, last name etc.
Now a couple of these fields are checkbox lists. Everything is being populated with the correct data except these two fields. Below is the current code of one of the lists.

        Referral Source

                <input type="checkbox" data-bind="
                    checkedValue: id,
                    checked: $root.currentClient.ReferralSourceIDs
                " />

This code should bind the data from the currentClient which is in the viewmodel.
self.currentClient = ko.observable();

On the edit button being clicked the currentClient is filled with the correct data.
editClient = function (editingClient) {

    self.currentClient(editingClient);
}

The data we receive from the database fills up the ReferralSource class.
function ReferralSource(id, source) {
    this.id = ko.observable(id);
    this.source = ko.observable(source);

    return this;
}
clientsLoad = function () {
    $.ajax({
        contentType: 'application/json',
        type: "GET",
        url: baseUrl + 'api/Client/LoadAll',
        dataType: 'json',
        context: this,
        success: function (data, textStatus, jqXHR) {
            self.clients($.map(data, function (item) {
                var referralSources = new Array();
                for (var i = 0; i < item.ReferralSourceIDs.length; i++) {
                    referralSources.push(
                        new ReferralSource(
                            item.ReferralSourceIDs[i].ReferralSourceID,
                            item.ReferralSourceIDs[i].Source
                        )
                    );
                }
                return new Client(
                    item.FirstName,
                    item.LastName, /* etc */
                    referralSources
                );
            }));
        }
    });
}

So with all that being said the load data is working fine the edit on select is being populated with the correct data but the only issue is that the check boxes are not being selected on bind. Can anyone see something I am missing or am I doing something wrong. If you need more info please ask, I will be trying to get this to work in the meantime.
EDIT: So I found a way to get it working and it has to deal with this part of the code.
<input type="checkbox" data-bind="checkedValue: id, checked: $root.currentClient.ReferralSourceIDs" />

It does not like $root.currentClient.ReferralSourceIDs. I removed this out of the class and put it into the view model and it started to work. So it looks like this now $root.referralSources. I have no idea why but it works that way. So if anyone has any other solutions please let me know for now I will stick with this.


text:
Q: Essential range and integral means I am looking at the notion of essential range, which is defined for a function $f:(X,\mu)\rightarrow \mathbb{C}$ as the set $R_f$ of points $z\in\mathbb{C}$ satisfying
$$\forall\epsilon>0, \mu(\{x\in X:|z-f(x)|<\epsilon\})>0.$$
I consider the case where $f\in L^{\infty}(\mu)$. In this case, let's consider the set $A_f$ of complex numbers of the form
$$\frac{1}{\mu(E)}\int_E f\ d\mu,$$
where $E$ is a measurable set satisfying $0<\mu(E)<\infty$.
I conjecture that

$A_f$ is included in the convex hull of $R_f$.

I have first proved that $\mu(X-f^{-1}(R_f))=0$, so that each element of $A_f$ is actually a ''mean'' over a set $E\cap f^{-1}(R_f)$, comprised of elements mapped into $R_f$. This convinces me that $A_f$ is included into the convex hull of $R_f$, but I can't manage to prove it. Is there a simple or elegant way to come to the result?
NB: I also proved that $R_f$ is compact with supremum $\|f\|_{\infty}$, may it be useful...

A: Let's prove that there exists $\alpha\in R_f$ such that $\alpha\geq A_f$.
Suppose that this does not happen. Let $b=\|f\|_{\infty}$, then $A_f\leq b$. Consider the closed interval $[A_f,b]$. For any $z$ in it, there exists $\varepsilon_z>0$ such that the set $$\{x\in X\big| |z-f(x)|<\varepsilon_z\}=f^{-1}\left(B(z,\varepsilon_z)\right)$$ has measure zero, since any $z\in[A_f,b]$ is not in $R_f$. Then the balls $B(z,\varepsilon_z)$ form an open cover of $[A_f,b]$, which is compact, therefore there exist finitely many $z_1,\dots z_n\in[A_f,b]$ such that the balls $B(z_i,\varepsilon_{z_i})$ cover $[A_f,b]$. Therefore, $$[A_f,b]\subseteq\bigcup_{i=1}^nB(z_i,\varepsilon_{z_i})\Rightarrow f^{-1}\left([A_f,b]\right)\subseteq\bigcup_{i=1}^nf^{-1}\left(B(z_i,\varepsilon_{z_i})\right),$$ from which you see that $f^{-1}\left([A_f,b]\right)$ has measure zero. Therefore, $f(x)<A_f$ almost everywhere, so $$0=A_f-\frac{1}{\mu(E)}\int_Ef\,d\mu=\frac{1}{\mu(E)}\int_E(A_f-f)\,d\mu,$$ and since $A_f-f>0$ almost everywhere, you get a contradiction. So, there exists $z\geq A_f$ such that $z\in R_f$.
If $z=A_f$, you are done. If not, then $z>A_f$, and you can show similarly that there exists $w\leq A_f$ such that $w\in R_f$. If $w=A_f$, you are done; if not, then $w<A_f$ and $A_f$ is a convex combination of $z$ and $w$, so $A_f$ is in the convex hull of $R_f$.


text:
Q: What do %@ and %ld mean in Objective-C? NSString *expectedURL = [NSString stringWithFormat:@"https://%@:%ld/%@"];
What do the %@ and %ld mean?

A: %@ format specifier used for printing and formatting Objective-c Objects.
%ld used for Unsigned 64-bit integer .i.e. NSInteger.

A: They are format specifiers.  Basically, insertion points for the rest of the parameters to stringWithFormat.
https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html


text:
Q: Checking a string against an array of phone numbers in a broadcast receiver I have an activity for adding / modifying an array, and I have another activity that shows this array as a list.
I am trying to have a third activity that checks an incoming calls phone number against a number in the array and rejects it if the number is in the array. Everything is working fine, except for retrieving the array in my IncomingCallReceiver class.
Here's my array
_pxlist = new ArrayList<Product>();
        SharedPreferences prefs = getPreferences(MODE_PRIVATE);
        String[] array = prefs.getString("numbers", "").split("&");
        for (int i = 0; (i+1)<array.length; i += 2) {
            Number n = new Number();
            n.name = array[i];
            n.number = array[i+1];
            _pxlist.add(n);
        }

and in the IncomingCallReceiver activity
if ((phoneNumber == pxArray)) {
//Reject Call
}

How can I import this array into a Broadcast receiver and then check against it?

A:
How can I import this array into a Broadcast receiver and then check
  against it?

You can achieve this by adding your _pxlist as a static field of your Activity, assume it's name is ArrayActivity, then you can use it in your IncomingCallReceiver like this:
if(ArrayActivity._pxlist != null && ArrayActivity._pxlist.size() > 0){
    // do the checking work.
}


text:
Q: Compose navigation lose state after pop screen (initial composition) I am using compose navigation with single activity and no fragments.
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MobileComposePlaygroundTheme {
                Surface(color = MaterialTheme.colors.background) {
                    val navController = rememberNavController()
                    NavHost(navController, startDestination = "main") {
                        composable("main") { MainScreen(navController) }
                        composable("helloScreen") { HelloScreen() }
                    }
                }
            }
        }
    }
}

@Composable
private fun MainScreen(navController: NavHostController) {
    val count = remember {
        Log.d("TAG", "inner remember, that is, initialized")
        mutableStateOf(0)
    }

    LaunchedEffect("fixedKey") {
        Log.d("TAG", "inner LaunchedEffect, that is, initialized")
    }

    Column {
        Spacer(modifier = Modifier.height(16.dp))
        Button(
            onClick = {
                count.value++
                Log.d("TAG", "count: ${count.value}")
            },
            modifier = Modifier.padding(8.dp)
        ) {
            Text(text = "Increase Count ${count.value}")
        }
        Button(
            onClick = { navController.navigate("helloScreen") },
            modifier = Modifier.padding(8.dp)
        ) {
            Text(text = "Go To HelloScreen")
        }
    }
}

@Composable
fun HelloScreen() {
    Log.d("TAG", "HelloScreen")
    Text("Hello Screen")
}

MainScreen -> HelloScreen -> back button -> MainScreen

After pop HelloScreen by back button, MainScreen restart composition from scratch. That is, not recomposition but initial composition. So remember and LaunchedEffect is recalculated.
I got rememberSaveable for maintaining states on this popping upper screen case. However how can I prevent re-execute LaunchedEffect? In addition, docs saying rememberSavable makes value to survive on configuration change but this is not the exact case.
I expected that LowerScreen is just hidden when UpperScreen is pushed, and LowerScreen reveal again when UpperScreen is popped, like old Android's onPause(), onResume(), etc.
In Compose, is this not recommended?
ps.
Lifecycle of Composable is not tied with ViewModel but with Activity
It needs more care about initialization of ViewModel
Why Compose team design like this?
Can you recommend good architecture sample code?


text:
Q: Отслеживание памяти по всем объектам при отладке Есть цикл, где каждая итерация независима от другой. При каждой итерации один и тот же массив инициализируется новыми данными. В итоге на 5 итерации кончается память и на моменте добавления в массив нового элемента выскакивает OutOfMemory.
Я прописал в конфиг
<runtime>
<gcAllowVeryLargeObjects enabled="true" />
</runtime>

Но всё равно. Уже в конце итерации я приравниваю ко всем массивам null и вызываю сборщик мусора
GC.Collect(GC.MaxGeneration);

Но ничего не помогает. Как можно отследить, куда девается память? Потому что на следующей итерации нам вообще ненужна память, которая выделялась на предыдущей. Но, если смотреть через Диспетчер задач, то там после каждой итерации память выделяется всё больше и больше, не чистится. Можете подсказать пожалуйста, где что посмотреть или сделать?


text:
Q: how to do port forwarding from local host to docker container I am using ec2-instance. installed docker and running rundeck in a container.
How can i expose 4440 port to local ec2 ip address ?
i.e,  htttp://ec-2ip:4440 should show me rundeck dashboard.

A: You can do something like this.
docker run -it -p 4440:4440 rundeck
-p does the job here. You are publishing the container port on the host. The mapping is -p host_port:container_port
Refer this articles for more options.
https://docs.docker.com/engine/userguide/networking/default_network/binding/
https://github.com/wsargent/docker-cheat-sheet#exposing-ports


text:
Q: setResult does not work when BACK button pressed I am trying to setResult after the BACK button was pressed. I call in onDestroy
Intent data = new Intent();
setResult(RESULT_OK, data)

But when it comes to
onActivityResult(int requestCode, int resultCode, Intent data)

the resultCode is 0 (RESULT_CANCELED) and data is 'null'.
So, how can I pass result from activity terminated by BACK button?

A: Activity result must be set before finish() is called. Clicking BACK actually calls finish() on your activity, so you can use the following snippet:
@Override
public void finish() {
    Intent data = new Intent();
    setResult(RESULT_OK, data);

    super.finish();
}

If you call NavUtils.navigateUpFromSameTask(); in onOptionsItemSelected(), finish() is called, but you will get the wrong result code. So you have to call finish() not navigateUpFromSameTask in onOptionsItemSelected().
wrong requestCode in onActivityResult

A: You should override onOptionsItemSelected like this:
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
        final Intent mIntent = new Intent();
        mIntent.putExtra("param", "value");
        setResult(RESULT_OK, mIntent);
        finish();
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

A: If you want to set some custom RESULT_CODE in onBackPressed event then you need to first set the result and then call the super.onBackPressed() and you will receive the same RESULT_CODE in the caller activity's onActivityResult method
    @Override
    public void onBackPressed()
    {
         setResult(SOME_INTEGER);
         super.onBackPressed();
    }

A: Refer onActivityResult(int, int, Intent) doc
Solution is to check the resultCode for value Activity.RESULT_CENCELED. If yes, then it means that either BACK was pressed or the activity crashed. Hope it works for you guys, works for me :).

A: You need to overide the onBackPressed() method and set the result before the call to superclass, i.e
@Override
public void onBackPressed() {
    Bundle bundle = new Bundle();
    bundle.putString(FIELD_A, mA.getText().toString());

    Intent mIntent = new Intent();
    mIntent.putExtras(bundle);
    setResult(RESULT_OK, mIntent);
    super.onBackPressed();
}

A: I refactored my code. Initially I prepared some data and set it as activity result in onDestroy (this did not work). Now I set activity data each time the data to be returned is updated, and have nothing in onDestroy.

A: onDestroy is too late in the chain — instead override onPause and check isFinishing() to check if your activity is at the end of its lifecycle.

A: Try overriding onBackPressed (from android level 5 up), or override onKeyDown() and catch KeyEvent.BUTTON_BACK (see Android Activity Results)
This does the trick for me.

A: Don't rely on any logic executed in onPause of one activity when you return to the initial one. According to the docs:

Implementations of this method (onPause) must be very quick because
  the next activity will not be resumed until this method returns

See http://goo.gl/8S2Y for details.
The safest way is to set result after each result altering operation is complete (as you mention in your answer)

A: i paste the answer may be will be helpful to other people:
when a set launcheMode with  android:launchMode="singleTask"
i also cant get the result,
the doc says:
     /*
Note that this method should only be used with Intent protocols
 * that are defined to return a result.  In other protocols (such as
 * {@link Intent#ACTION_MAIN} or {@link Intent#ACTION_VIEW}), you may
 * not get the result when you expect.  For example, if the activity you
 * are launching uses the singleTask launch mode, it will not run in your
 * task and thus you will immediately receive a cancel result.
 */

and:
     /*
As a special case, if you call startActivityForResult() with a requestCode
 * >= 0 during the initial onCreate(Bundle savedInstanceState)/onResume() of your
 * activity, then your window will not be displayed until a result is
 * returned back from the started activity.  This is to avoid visible
 * flickering when redirecting to another activity.
 */


text:
Q: How to populate a List in android (not ListView) I am getting list of third party applications though this code.
    ApplicationInfo ai;
    final PackageManager pm = main.getPackageManager();

    List<ApplicationInfo> packages1 = null;
    int index = 0;

    List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);

    for (ApplicationInfo appInfo : packages)
    {
        if ((appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)
        {
            // IS A SYSTEM APP
        }

        else
        {
            packages1.add(index, appInfo);
            index++;
        }
    }

But I get an exception , when I comment this line :
    packages1.add(index, appInfo);

Then the code executes correctly , but it gives exception due to this line. Here is my logcat:
07-01 05:19:32.058: W/dalvikvm(5558): threadid=8: thread exiting with uncaught exception (group=0x4001d7d0)
07-01 05:19:32.065: E/AndroidRuntime(5558): FATAL EXCEPTION: AsyncTask #1
07-01 05:19:32.065: E/AndroidRuntime(5558): java.lang.RuntimeException: An error occured while executing doInBackground()
07-01 05:19:32.065: E/AndroidRuntime(5558):     at android.os.AsyncTask$3.done(AsyncTask.java:200)
07-01 05:19:32.065: E/AndroidRuntime(5558):     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
07-01 05:19:32.065: E/AndroidRuntime(5558):     at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
07-01 05:19:32.065: E/AndroidRuntime(5558):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
07-01 05:19:32.065: E/AndroidRuntime(5558):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
07-01 05:19:32.065: E/AndroidRuntime(5558):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
07-01 05:19:32.065: E/AndroidRuntime(5558):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
07-01 05:19:32.065: E/AndroidRuntime(5558):     at java.lang.Thread.run(Thread.java:1096)
07-01 05:19:32.065: E/AndroidRuntime(5558): Caused by: java.lang.NullPointerException
07-01 05:19:32.065: E/AndroidRuntime(5558):     at com.example.first.Fetch_Software.doInBackground(Fetch_Software.java:46)
07-01 05:19:32.065: E/AndroidRuntime(5558):     at com.example.first.Fetch_Software.doInBackground(Fetch_Software.java:1)
07-01 05:19:32.065: E/AndroidRuntime(5558):     at android.os.AsyncTask$2.call(AsyncTask.java:185)
07-01 05:19:32.065: E/AndroidRuntime(5558):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
07-01 05:19:32.065: E/AndroidRuntime(5558):     ... 4 more
07-01 05:19:36.894: E/WindowManager(5558): Activity com.example.first.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@47faa8f8 that was originally added here
07-01 05:19:36.894: E/WindowManager(5558): android.view.WindowLeaked: Activity com.example.first.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@47faa8f8 that was originally added here
07-01 05:19:36.894: E/WindowManager(5558):  at android.view.ViewRoot.<init>(ViewRoot.java:247)
07-01 05:19:36.894: E/WindowManager(5558):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:171)
07-01 05:19:36.894: E/WindowManager(5558):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:114)
07-01 05:19:36.894: E/WindowManager(5558):  at android.view.Window$LocalWindowManager.addView(Window.java:424)
07-01 05:19:36.894: E/WindowManager(5558):  at android.app.Dialog.show(Dialog.java:241)
07-01 05:19:36.894: E/WindowManager(5558):  at com.example.first.MainActivity.onClick(MainActivity.java:114)
07-01 05:19:36.894: E/WindowManager(5558):  at java.lang.reflect.Method.invokeNative(Native Method)
07-01 05:19:36.894: E/WindowManager(5558):  at java.lang.reflect.Method.invoke(Method.java:521)
07-01 05:19:36.894: E/WindowManager(5558):  at android.view.View$1.onClick(View.java:2067)
07-01 05:19:36.894: E/WindowManager(5558):  at android.view.View.performClick(View.java:2408)
07-01 05:19:36.894: E/WindowManager(5558):  at android.view.View$PerformClick.run(View.java:8818)
07-01 05:19:36.894: E/WindowManager(5558):  at android.os.Handler.handleCallback(Handler.java:587)
07-01 05:19:36.894: E/WindowManager(5558):  at android.os.Handler.dispatchMessage(Handler.java:92)
07-01 05:19:36.894: E/WindowManager(5558):  at android.os.Looper.loop(Looper.java:123)
07-01 05:19:36.894: E/WindowManager(5558):  at android.app.ActivityThread.main(ActivityThread.java:4627)
07-01 05:19:36.894: E/WindowManager(5558):  at java.lang.reflect.Method.invokeNative(Native Method)
07-01 05:19:36.894: E/WindowManager(5558):  at java.lang.reflect.Method.invoke(Method.java:521)
07-01 05:19:36.894: E/WindowManager(5558):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:871)
07-01 05:19:36.894: E/WindowManager(5558):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
07-01 05:19:36.894: E/WindowManager(5558):  at dalvik.system.NativeStart.main(Native Method)

A: I think you missed the declaration line.
It should be:
List<ApplicationInfo> packages1 = null;
packages1 = new ArrayList<ApplicationInfo>();

A: First you do this:
List<ApplicationInfo> packages1 = null;

Then you do this:
packages1.add(index, appInfo);

Which translates to:
null.add(index, appInfo);

Which finally becomes:
07-01 05:19:32.065: E/AndroidRuntime(5558): Caused by: java.lang.NullPointerException
07-01 05:19:32.065: E/AndroidRuntime(5558):     at com.example.first.Fetch_Software.doInBackground(Fetch_Software.java:46)

in your logs.

A: Null pointer occurred when you forget to initialization data type, here you forgot to initialize your List.
Just initialization your list like below:
List<ApplicationInfo> packages1 = new List<ApplicationInfo>();

A: package1 hasn't been initialized, try following:
package1 = new ArrayList<ApplicationInfo>();


text:
Q: How should I manage large DataTables? For reasons that don't make a lot of sense (Read: Not my decision) I need to keep a large number of rows, about ~90,000, in a DataTable and I do not have the option of using a database.
I need to be able to search the DataTable efficiently to find rows that match some basic criteria. For example, I might be looking at a row that has the value 2 in two specific columns.
What is the best way to do this?
Edit: Please take a look at https://chat.stackoverflow.com/transcript/message/62648#62648 for more details; after I work on this I will try and summarize the extra details from the chat here as well as provide my solution.

A: You could easily use DataTable.Select()

A: The solution I ended up using for this painfully awkward and inconvenient situation was to use DataTable.Select(), populate a new DataTable and then use the same operation to select the rows I needed from the refined DataTable.
I think that this solution is clumsy, but then again the constraints on the problem were somewhat unrealistic seeing as I was on a tight schedule as well.


text:
Q: Why minimal actions of a Abelian group is not proximal unless the action be tivial? Let $G$ be a discrete abelian group which acts minimally on a compact (for comfort, compact and metrizable) space $X$ by homeomorphisms. If the action is proximal in addition then $X$ must be a singleton. Why?

*

*By minimality, I mean orbit of every $x\in X$ is dense in $X$.

*By proximally, I mean for every $x, y\in X$ there is a sequence $\{g_n\}_n$ such that $\lim_n g_{n}.x=\lim_n g_{n}.y=z\in X$

A: OK. It doesn't as hard as I supposed. Indeed it is an elementary problem.
Let $g\in G$ and $x\in X$. $(x, g.x)$ is proximal so there is a net $\{h_i\}$ in $G$ such that $\lim_{i}h_i.x=\lim_{i}h_{i}.(g.x)=z\in X$. Also $G$ is abelian so $\lim_{i}h_{i}.(g.x)=\lim_{i}g.(h_{i}.x)=g.\lim_{i}h_{i}.x$. Thus we must $z=gz$ for all $g\in G$ i.e., the action has a fixed point wherease the action is minimal therefore $X$ is a singleton.


text:
Q: full image with rectangle with text inside of it Trying to put on my image a red rectangle with white text in it.
Same as its shown here

So far, I can put the text in the top left corner but I still miss the full-width rectangle with the text inside it.
Where do I put the rectangle
from PIL import Image, ImageDraw, ImageFont
base = Image.open('C:\\Users\\t3cho\\Desktop\\DSC15178.jpg').convert('RGBA')
width, height = base.size
txt = Image.new('RGBA', base.size, (255,255,255,0))
fnt = ImageFont.truetype('arial.ttf', 80)
d = ImageDraw.Draw(txt)
d.text((0,0), "10% OFF FOR THIS ITEM", font=fnt, fill=(255,0,0,128))
out = Image.alpha_composite(base, txt)
out.show()

A: from PIL import Image, ImageFont, ImageDraw, ImageEnhance
from io import BytesIO

source_img = Image.open("C:\\Users\\t3cho\\Desktop\\DSC15178.jpg").convert("RGBA")
font = ImageFont.truetype(font=BytesIO(open("C:\\Windows\\Fonts\\COOPBL.TTF", "rb").read()),size=65)  #ImageFont.truetype("cooper black",65)
text = "This is my text centered"

# get text size
text_size = font.getsize(text)
# set button size + 10px margins
button_size =  (source_img.size[0], 100)  # (text_size[0]+20, text_size[1]+20)
# create image with correct size and black background
button_img = Image.new('RGBA', button_size, "red")
positionx = (float(source_img.size[0]) - float(text_size[0])) / float(2)
# put text on button with 10px margins
button_draw = ImageDraw.Draw(button_img)
button_draw.text((positionx, 10), text, font=font)
# put button on source image in position (0, 0)
source_img.paste(button_img, (0, 0))
# save in new file
im = source_img.convert("RGB")
im.save("C:\\Users\\t3cho\\Desktop\\DSC15178-out.jpg")


text:
Q: Difference between Next JS and Puppeteer JS I watched Google's conference on SEO and they suggested to use Dynamic Rendering for JS built applications (React, Vue, etc). One of the tools to achieve this is with Puppeteer JS.
I need to create an app that relies heavily on SEO so Server Side Rendering (SSR) is extremely important.
I know that Next JS by default accomplishes SSR, but can I do the same with Puppeteer + Create React App? What is the difference between Next JS and Puppeteer in terms of SSR and Dynamic Rendering, and which one is better for SSR?

A: Headless Chrome enables "isomorphic JS" between server and client. It's a great option if your library doesn't work on the server (Node). Example for it is lit-html which it's core feature doesn't work outside the browser.
The difference is huge in terms of features.
Next.js offers some nice features that Pupeteer doesn't.

*

*Hot reloading client & server

*Automatic code splitting

*Built-in CSS support, CSS-in-JS

*Fetching data and component lifecycle

*and more.

Some feature of Pupeteer:

*

*Generate screenshots and PDFs of pages.

*Crawl a SPA and generate pre-rendered content (i.e. "SSR").

*Automate form submission, UI testing, keyboard input, etc.

*Create an up-to-date, automated testing environment. Run your tests directly in the latest version of Chrome using the latest JavaScript and browser features.

*Capture a timeline trace of your site to help diagnose performance issues.

*and SSR apparently...

So you can see the major difference these two tools have.
Next.js is opinionated but aims to do SSR with react and builds on that concept;
Take into account that SSR with Puperteer in relatively new whereas community adoption of next.js is already mature with nice set of examples with different tech stacks.

A: In short,
Next.js is a node framework. You use it to write code, i.e. build your application.
Pupetteer can be considered a tool. It comes bundles with Chromium which is practically a browsers equivalent to a testing environment. You writes tests via pupetteer to run scenarios in chromium.
I've provided an over-simplified explanation for those who want it. Shmotam gave a brilliant answer if you want depth.

A: Difference Between Nextjs and Puppeteer JS is very very simple.
Next Js :- It is React Framework for server side rendering those help in SEO, Optimized for Discovery , Lightning Fast Delivery.so ,very simple word is SSR. For Link https://nextjs.org/#features
Puppeteer JS it is Developed by Google and this is used for End to End testing of your application like selenium.
Both are completely Different and purpose are also different.

A: nextjs is the powerful framework that supports ssr (server side rendering) and seo friendly Google search engine.
The react of interpretation is that the component is called after each state change. but nextjs load component and call getInitalProps first time, so view page source you can see data loaded

A: Puppeteer is used to make bots which works at backend.
NextJs is used to build Full Stack Website. And may be it will soon be available for React Native to make mobile apps.


text:
Q: Prove $\forall a, b, c \in \mathbb{Z} (\exists c \in \mathbb{Z} ((a + b)c = a^2 - b^2))$ This is from the book Concrete Mathematics by Norman L. Biggs.
$$
\forall a, b, c \in \mathbb{Z} (\exists c \in \mathbb{Z} ((a + b)c = a^2 - b^2))
$$
From right hand side:
$$
a ^2 - b^2 = a^2 + ab - ab - b^2 = a(a + b) - b(a + b) \\
= (a - b) (a + b)
$$
Comparing both sides, $c$ must be $a - b$, which is also an integer (Axiom I1 indirectly applied, $a, b \in \mathbb{Z} \to (a + b) \in \mathbb{Z}$ and $a - b = a + (-b)$. Although I think the axiom identifiers I1 through I7 are not standard).
$$\therefore \forall a, b, c \in \mathbb{Z} (\exists c \in \mathbb{Z} ((a + b)c = a^2 - b^2)) \text{ is true. }$$


text:
Q: Adding "this" to the parents stack for "each" in jQuery This question is a bit of a two-parter. First, the title question. Here's what I've got:
// Report all of the parents
$(this).parents().each(function(i){

    // Collect the parts in a var
    var $crumb = '';

    // Get the tag name of the parent
    $crumb += ""+this.tagName+"";

    // And finally, report it
    $breadcrumbs.prepend($crumb);

});

Unfortunately, this doesn't include the actual element itself, only the parents. Is there any way of saying something like "this and parents"?
Now, the second question. If I were unable to add to the stack, how would I separate the guts of that function into another function, while retaining the "this" ability of it? Would it be something like:
// Function to report the findings
function crumble(e){

    // Collect the parts in a var
    var $crumb = '';

    // Get the tag name of the parent
    $crumb += ""+this.tagName+"";

    // And finally, report it
    $breadcrumbs.prepend($crumb);

};
$(this).parents().each(crumble());

Thanks in advance for your time!

A: For the first question, you can use the .andSelf method:
$(this).parents().andSelf().each(function () {
  // ..
});

You have to note something, the $crumb variable is locally-scoped, so it will initialize in every iteration of you each loop.
For your second question, yes, you can define a function that does the job of the each callback, you just have to pass a reference to it, and not invoke it (remove the parens):
$(this).parents().each(crumble);


text:
Q: Queries return incorrect values with multi-level single table inheritance using Mongoid In my project I have the following class hierarchy, using Mongoid with STI:
class User
  include Mongoid::Document
end

class SpecificUser < User
end

class MoreSpecificUser < SpecificUser
end

Mongoid gives me the correct result when I query User.count and MoreSpecificUser.count, but returns 0
when I try SpecificUser.count. Only after I query MoreSpecificUser.count it returns the correct value
for SpecificUser.count. Is there a way to make the queries in SpecificUser return the correct values
without querying its subclasses before?
Note: It was working with MongoMapper before, it only broke after I migrated to Mongoid.
My mongoid.yml:
development:
  clients:
    default:
      database: dev_project
      hosts:
        - 127.0.0.1:27017
      options:
        preload_models: true
        max_pool_size: 16
  options:
    raise_not_found_error: false

I'm using Mongoid 5, MongoDB 2.6, Ruby 2.2.2 and Rails 4.2.4.

A: Seems like adding config.mongoid.preload_models = true in application.rb solves it.
http://docs.mongodb.org/ecosystem/tutorial/ruby-mongoid-tutorial/#model-preloading


text:
Q: model definitions for tautology, contradiction, and connectives quantify too much, no? Occasionally I come across a definition based on what will happen in all models, for example, that a contradiction is a statement that is false in all models, that a tautology is a statement that is true in all models, that sentence A implies sentence B if in all models in which A is true, B is also true, and similar for "and" and "or". But these definitions cannot be formalized as is, because they quantify over "all models", an impossibility. How does one get around this? Does one quantify over all models of first-order theories inside a second-order theory?

A: You would need to specify your meta-system, before you can formalize a meta-theoretic statement. Conventionally logicians use some conservative extension of ZFC as their meta-system. Within ZFC one can consider any first-order language and collection of sentences (encoded in some way) over it, and ask whether there is a model, which is defined as a tuple consisting of a set for the domain and interpretations for each predicate or function or constant symbol of the language.
However, this definition does not give a set of all models, because no such set can exist (unless you love contradictions). But "$M$ is a model of $X$" can be expressed by a first-order sentence over ZFC. So what you can do is to define a new abbreviation $IsModelOf$, namely a binary predicate symbol such that, for every (sets) $M,X$, we have $IsModelOf(M,X)$ iff $M$ is a model of $X$.
Quantifying over all models is then possible, since restricted quantification over elements satisfying a predicate can be easily expressed using unrestricted quantification. What cannot be done is to use the collection of all models as a single object in the set-theoretic universe. You are right that if you use second order ZFC you can natively have the collection of all (set) models of a set of sentences. One commonly used essentially second-order set theory is MK (Morse-Kelley), which has two sorts, one for sets and one for collections of sets called classes.


text:
Q: How to sample points on a triangle surface in 3D? To take random uniform points inside a triangle Triangle Point Picking method is used. But this is for 2D points, how can I take random points from a triangle that is defined by 3 arbitrary 3D points?
In other words, let's say I have 3 points in 3D space, and these points define a plane, how can I take random points on the plane such that my points are uniformly sampled inside the triangle that is defined by these 3 points?
Thanks in advance..

A: The same exact algorithm should work in $3D$ too:
$$\vec{x} = \vec{v_1} + a (\vec{v_2} -\vec{v_1}) + b (\vec{v_3} -\vec{v_1})$$
Where $a,b$ are uniformly distributed in $[0,1]$ and the $\vec{v}$'s are the triangle vertices in $3D$.

A: As mentioned in the comments, this formulation is not guaranteed to give you points on the triangle. The correct formulation is as follow:
$P = (1 - \sqrt{a})v1 + (\sqrt{a} (1 - b))v2 + (b \sqrt{a})v3$
where $a, b \sim U[0, 1]$.


text:
Q: Fill in missing values in Pandas Dataframe wrong Suppose 'df' is dataframe object, 'ca' is one of the variables.
>>> df.ca.value_counts()
0.0    176
1.0     65
2.0     38
3.0     20
?        4
Name: ca, dtype: int64

As you can see, I have four missing values. I want to fill in them. Using below code:
>>> df.loc[df.ca == '?', 'ca'] = 0.0
0.0    176
1.0     65
2.0     38
3.0     20
0.0      4
Name: ca, dtype: int64

Why I got 5 unique values? I want to merge fifth row into first row, i.e.
0.0   176 + 4 = 180
1.0     65
2.0     38
3.0     20

How can I fix it?

A: Because '?' was one of your values, I know that df.ca is either dtype object or string.  When you replace('?', 0.) you now have both string '0.0' and float 0.0.  After you convert all to float, you shouldn't have a problem.
df.ca.replace('?', 0.).astype(float).value_counts()

0.0    180
1.0     65
2.0     38
3.0     20
dtype: int64

A: The following pretty much works too:
In [193]: df = pd.DataFrame({'ca': [0.0]*176 + [1.0]*65 + [2.0]*38 + [3.0]*20 + ['?']*4})

In [194]: df.ca.value_counts()
Out[194]:
0.0    176
1.0     65
2.0     38
3.0     20
?        4
Name: ca, dtype: int64

In [195]: df.loc[df.ca == '?', 'ca'] = 0.0

In [196]: df.ca.value_counts()
Out[196]:
0.0    180
1.0     65
2.0     38
3.0     20
Name: ca, dtype: int64


text:
Q: Creating line from points using PostGIS? I have a PostGIS table with position data of numerous vehicles and want to create lines from these points.
Data can be selected by vehicle id and ordered by timestamp but how to create lines from the result?
What I basically need is one line segment from point 1 to point 2, finalize the line and then again from point 2 to point 3. Of course all that under consideration of the vehicle id.
The latter one is needed because I want to calculate the cruise direction and speed of the vehicle from one point to the next.

A: It can be done in a few ways, using self-joins or correlated subqueries but using window functions is probably the easiest way.
The function lead() returns a value that's ahead in the given partition and our partition is (PARTITION BY <vehicle_id> ORDER BY <timestamp>)
This query gives us the vehicle number, the position of that point in partition (which is equal to the position of line starting with it) and the two geometries that will make the line. Of course it returns NULL geom2 for last point so we need to check for that in the outer query.
SELECT mmsi, num, ST_MAKELINE(geom,geom2) FROM (
  SELECT mmsi, row_number() OVER w AS num, geom, lead(geom) OVER w AS geom2
  FROM ais_data WINDOW w AS (PARTITION BY mmsi ORDER BY bs_ts) ) as q
WHERE geom2 IS NOT NULL;


text:
Q: Can numpy functions replace this for loop to gain speed? I have many of these matrix arrays, in which I want to replace the 0 entries with the closes non zero entry with the lowest index. This can be done easily using a for loop:
import numpy as np

input_array = np.array([ 0.01561,  0.01561,  0.02039,  0.02039,  0.02776,  0.02776,
  0.03997,  0.,          0.03997,  0.06243,   0.,          0.,       0.0624662,
  0.11105,  0.,          0.,          0.,          0.11105,  0.24986,
  0.,          0.,          0.,          0.,          0.,          0.,
  0.24986])

for i in range(0,len(input_array)) :
   if input_array[i] == 0 :
      input_array[i] = input_array[i-1]

Would anyone suggest me if it is worth the effort?

A: Applying the numpy solution in:
Most efficient way to forward-fill NaN values in numpy array
def foo2(arr):
    idx=np.where(arr==0,0,np.arange(len(arr)))
    idx=np.maximum.accumulate(idx)
    return arr[idx]

def foo1(arr):
    arr = arr.copy()
    for i in range(len(arr)):
        if arr[i]==0:
            arr[i] = arr[i-1]
    return arr

For your test array, arr, the speed improvement is modest:
In [67]: timeit foo1(arr)
100000 loops, best of 3: 18.1 µs per loop
In [68]: timeit foo2(arr)
The slowest run took 1387.12 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 11.4 µs per loop

But with a larger one, the loop increases with size, the array version barely changes:
In [69]: arr1=np.concatenate((arr,arr,arr,arr,arr,arr,arr))
In [70]: timeit foo1(arr1)
10000 loops, best of 3: 116 µs per loop
In [71]: timeit foo2(arr1)
The slowest run took 4.16 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 14.6 µs per loop

The details of the idx construction:
In [72]: idx=np.arange(len(arr))
In [73]: idx[arr==0]=0
In [74]: idx
Out[74]:
array([ 0,  1,  2,  3,  4,  5,  6,  0,  8,  9,  0,  0, 12, 13,  0,  0,  0, 17, 18,  0,  0,  0,  0,  0,  0, 25])
In [75]: idx=np.maximum.accumulate(idx)
In [76]: idx
Out[76]:
array([ 0,  1,  2,  3,  4,  5,  6,  6,  8,  9,  9,  9, 12, 13, 13, 13, 13, 17, 18, 18, 18, 18, 18, 18, 18, 25], dtype=int32)


text:
Q: Removing course and relationship I'm trying to remove courses/sections/lessons with soft delete
I have on tables:
$table->softDeletes();

And in models:
use Illuminate\Database\Eloquent\SoftDeletes;

use HasFactory, SoftDeletes;

protected $dates = ['deleted_at'];

Destroy function:
  public function courseDestroy(Course $course)
    {
        foreach($course->sections as $section){
            foreach($section->lessons as $lesson){
              $lesson->delete();
            }
            $section->delete();
          }
          $course->delete();
        return redirect('/all-courses');
    }

Route:
 Route::delete('/course/remove/{id}', [CourseManagementController::class, 'courseDestroy'])->name('course.destroy');

And blade:
<form action="/course/remove/{{$course->id}}" method="POST">
            @csrf
            @method('DELETE')
            <button type="submit" class="btn btn-danger">Delete</button>
          </form>

But it don't working it's only redirecting me back...

A: I had problem with
 Route::delete('/course/remove/{id}', [CourseManagementController::class, 'courseDestroy'])->name('course.destroy');

I changed {id} with {course} and it's now working : )


text:
Q: The intersection of algebraic curves Let $L$ be the complex line ${ax+by+c=0}$ in $\mathbb{C}^{2}$,and let $C$ be the algebraic curve ${{f(x,y)=0}}$, where $f$ is an irreducible polynomial of degree $d$. Prove that $C\bigcap L$ contains at most $d$ points unless $C=L$.

A: Assume that $a\neq 0.$ For any point $(x,y)\in C\cap L$ we will have $x=-\dfrac{by+c}{a}$ and so $g(y)=f(-\frac{by+c}{a},y)=0.$ But $g(y)$ is a degree $d$ polynomial in one variable over $\Bbb C,$ so ...


text:
Q: Angular error: [$injector:unpr] Unknown provider: lineChartProvider <- lineChart <- MainController Not Sure why but my controller wont recognize the service. I have checked enerything what am I missing here. I have included the services file in HTML. It recognizes other services but not just this one
(function() {
  'use strict';

  angular
    .module('pollyvotes')
    .service('lineChart', lineChart);

    /** @ngInject */
    function lineChart($scope, $http){
      var promise = null;
      return function(){
        if (promise){
          return promise
        } else {
          promise = $http.jsonp('')
          .success(function(data){
            $scope.predictions = data;
         })
          .error( function(data){
            $scope.data = "Request failed";
          })

          return promise;
        }

      }

Controller
(function() {
  'use strict';

  angular
    .module('pollyvotes')
    .controller('MainController', MainController);

  /** @ngInject */
  function MainController($scope, $timeout, lineChart) {

    $scope.photos = [   {id: 'chart-1', name: 'something here',src: "assets/images/300x600.png", href: "https://www.google.de/?gws_rd=ssl", discription: "say something about the chart here"},
                        {id: 'chart-2', name: 'another picture', src: "assets/images/300x600.png", href: "https://www.google.de/?gws_rd=ssl", discription: "say something about the chart here"},
                        {id: 'chart-3', name: 'another picture', src: "assets/images/300x600.png", href: "https://www.google.de/?gws_rd=ssl", discription: "say something about the chart here"},
                        {id: 'chart-4', name: 'another picture', src: "assets/images/300x600.png", href: "https://www.google.de/?gws_rd=ssl", discription: "say something about the chart here"}
                    ];

  }

})();

and declaring module
(function() {
  'use strict';

  angular
    .module('pollyvotes', ['ngAnimate', 'ngCookies', 'ngTouch', 'ngSanitize',
                           'ngMessages', 'ngAria', 'ngResource', 'ui.router',
                           'ui.bootstrap',  'akoenig.deckgrid', 'smoothScroll',
                           'ngToast', 'picardy.fontawesome']);

})();

A: You are injecting $scope to your service.
That's what the documentation says about this error:
https://docs.angularjs.org/error/$injector/unpr

Attempting to inject a scope object into anything that's not a controller or
      a directive, for example a service, will also throw an
      Unknown provider:     $scopeProvider <- $scope error.

There is a good answer how to avoid this here:
Injecting $scope into an angular service function()


text:
Q: Applications of Descent? The technique of faithfully flat descent, and, in the case of vector spaces, Galois descent has been used quite a bit in Algebraic Geometry. However, the question of whether, say, a given $k$-vector space $V$ arises from some $L$-vector space $W$ seems like it could be asked in a wide variety of settings. I'm wondering, in particular, if anyone has seen descent in modular representation theory.

A: The question is a little too vague to have a really satisfactory answer, but obviously descent
is omnipresent in (modular) representation theory.
For example, the basic result that two representations of a group $G$ on some $k$-vector spaces are isomorphic iff they become isomorphic on some extension $L$ of $k$ is an instance of faithfully flat descent.
Or to take a less trivial example, let $R$ be a d.v.r with residual field $k$ algebraically closed (or just separably closed, or finite, or...) and of field of fraction $K$. Let $\rho$ be a representation of a group $G$ on some extension $L$ of $K$, whose characteristic polynomials of element of $g$ are in $R[x]$. (In characteristic zero, you can replace
that condition by "character takes values in $R$").
A natural question in this context is if you can "descend" $\rho$ to a representation over $R$. For example, the answer is yes when there exists a representation of $G$  over $k$
which is absolutely irreducible and whose characteristic polynomial agree with the reduction of those of $\rho$. The proof uses a lot of faithfully flat
descent via the theory of Azumaya algebras.
Edit: to answer Martin's comment, I precise how the faithful flatness plays a role in the first example.
Lemma: Let $G$ be a group. Let $k$ be a commutative noetherian ring, $k'$ a flat $k$-algebra. Let $M$, $N$, be  $k[G]$-module, finitely generated as $k$-modules. let $M'=M \otimes_k k'$ and $N'=N\otimes_k k'$.
Then $Hom_{k[G]}(M,N) \otimes_k k' = Hom_{k'[G]}(M',N')$. Moreover if $k'$ is a faithfully flat $k$-algebra, $Hom_{k[G]}(M,N)$ is non-zero if and only if $Hom_{k'[G]}(M',N')$ is non-zero.
Pf: Let $g_1,\dots,g_n$ be a finite family of elements of $g$ generating the image of $k[G]$ in $End_{k}(N)$.
Let $t_i$ be the linear endomorphism of $H:=Hom_{k}(M,N)$ given by $\phi \mapsto \phi g_i - g_i \phi$. Consider the map $H \rightarrow H^n$ given by the $t_i$. The kernel of this map
is $Hom_{k[G]}(M,N)$. the kernel of the same map tensorized by $k'$ is $Hom_{k'[G]}(M',N')$.
Hence the first result by flatness. The second is clear by faithful flatness.
So for example, if $k$, $k'$ are field, $M$, $N$ simple $k[G]$-modules, one retrieve
the classical assertion that $M \simeq N$ off $M' \simeq N'$. But I hope I have shown that
the essence of this assertion is faithfully flat descent.

A: Descent does appear in modular representation theory (of finite groups) in a slightly surprising form. Indeed, descent techniques allow us to discuss extension from $Stab(kH)$ to $Stab(kG)$, where $H$ is a subgroup of $G$, of index prime to the characteristic of the field $k$, and where $Stab(-)$ denotes the stable category of modules modulo projectives.
To understand how an extension problem turns out to be a descent problem, one should start by the following "monadicity" observation: There exists a commutative separable ring object (i.e. monoid) $A$ in the symmetric monoidal category $C:=Stab(kG)$ such that the category $A-Mod_C$ of $A$-modules in that category $C$ is equivalent to the stable category $Stab(kH)$, and this in such a way that restriction from $G$ to $H$ coincides with extension-of-scalars with respect to $A$.
So restriction to a subgroup is in fact a extension-of-scalars!
The condition that the index of $H$ in $G$ is prime to the characteristic exactly expresses the faithfulness of the ring object $A$. (Flatness is sort of built-in when you deal with tensor triangulated categories.) Hence extension from $H$ to $G$ is really faithful(ly-flat) descent!
One can then reason rather geometrically, pretty much as with (finite) etale extensions. There is even a Grothendieck topology and a stack hiding in the bushes... This is all explained in the preprint
"Stacks of group representations"
available on my publication page.

A: Probably not quite what you're looking for, but it certainly involves modular representation theory, and it's really neat! A baby version of descent is used in a proof of Quillen's stratification theorem.
Suppose we have a compact Lie group, $G$, and a smooth $G$-manifold $X$ (if you'd like to feel modular, take $G$ to be finite and $X$ to be a point). We'd like to show that the map $H_G^*X \rightarrow \lim H_G^*A$ is an F-isomorphism, where cohomology has coefficients in some fixed prime, the limit is taken over a certain category involving components of fixed point subspaces and the elementary abelian subgroups of $G$, and an "F-isomorphism" is a map of rings such that all elements of the kernel are nilpotent and every element, $s$, in the codomain satisfies $s^{p^n} \in \text{image}$ for some $n$. (This implies, in particular, that the Krull dimensions of each ring are the same.) In the case of the point, the right hand side is the limit over elementary abelian subgroups of $G$.
Here's one of the ways that Quillen does this. First he constructs a space $\mathcal{F}$ as follows: Choose a faithful unitary representation of $G$, say on $U(n)$, and let $\mathcal{F} = U(n)/S$ where $S$ is the subgroup of the maximal torus consisting of elements of order $p$ (i.e. matrices with $p$-roots of unity on the diagonal and zeros elsewhere). This space has all sorts of nice properties as a $G$-manifold (in particular, all of the isotropy groups are elementary abelian subgroups.)
Now, Quillen proves the theorem for the $G$-manifold $X \times \mathcal{F}$ (notice that even if all you cared about was when $X$ is a point, you'd still need the general statement of the theorem) and then uses a fun argument using a baby version of faithfully flat descent to deduce the theorem for $X$!
I won't give the argument here, but basically he uses the sequence $X \times \mathcal{F} \times \mathcal{F} \Rightarrow X \times \mathcal{F} \rightarrow X$ (I don't know how to make a double arrow here...) and shows that applying H^* gives an equalizer sequence (this is the "descent" part), and applying the functor appearing on the right hand side of the theorem also gives an exact sequence. Then one does a 3-lemma esque argument to conclude the result. It's really neat! For a much more detailed and entertaining account, see
http://www.math.washington.edu/~mitchell/Quillen/qnew.pdf


text:
Q: how to call an external api using rest client or rest template? How to call an external API using rest client or rest template?
@Override
 public LoginResponse login(LoginDetails loginDetails) throws PrepaidException {
  logger.info("Entering:: LoginServiceImpl:: login method");

try {
  LoginResponse loginResponse = null;
  LoginRequest loginRequst = new LoginRequest();
  loginRequst.setUserName(loginDetails.getUserName());
  loginRequst.setChatakPass(loginDetails.getChatakPass());
  loginRequst.setLoginSessionId(loginDetails.getLoginSessionId());
  loginRequst.setAuditSection(loginDetails.getAuditSection());
  loginRequst.setAuditEvent(loginDetails.getAuditEvent());
  loginRequst.setIp(loginDetails.getIp());
  loginRequst.setBrowserName(loginDetails.getBrowserName());
  loginRequst.setUser(loginDetails.getUser());
  loginRequst.setAuditPortalType(loginDetails.getAuditPortalType());
  ClientResponse response = JsonUtil.postRequest(loginRequst, "/adminUserManagementServices/adminUserService/login");
  ObjectMapper mapper = new ObjectMapper();
  if(response.getStatus() != 200)
    throw new PrepaidException(Properties.getProperty("prepaid.admin.genera  l.error.message"));
  String output = response.getEntity(String.class);
  loginResponse = mapper.readValue(output, LoginResponse.class);
  logger.info("Exiting:: LoginServiceImpl:: login method");
  return loginResponse;
}
catch(PrepaidException e) {
    logger.error("ERROR:: LoginServiceImpl:: login method", e);
  throw new PrepaidException(e.getMessage());
}
catch(Exception e) {
    logger.error("ERROR:: LoginServiceImpl:: login method", e);
  throw new PrepaidException(Properties.getProperty("prepaid.admin.general.error.message"));
   }
  }
 }

This is the sample code , this method is in different service , my issue is I have to call the same kind of thing from other service


text:
Q: How to set $scope.property only when corresponding value is defined/resolved Inside my controller I have this piece of code:
$scope.property = localStorageService.get('property');

To clarify, localStorageService is an angular module which helps deal with setting and getting Local Storage variables.
The problem is localStorageService.get('property') will only be set after a certain period of time because of an asynchronous $http call handled by a factory class. At the time when I do the assignment, localStorageService.get('property') is undefined, but will eventually be resolved by the xhr call.
App.factory('fact', ['$http', 'localStorageService', function($http, localStorageService){
    return {
        fetchProperty: function() {
            $http.get('/property')
                .success(function(data, status, headers, config){
                    localStorageService.set('property', data);
                })
        }
    }
}]);

How do I set $scope.property when and only when localStorageService.get('property') has already been set?
edit
I am using the browser's Local Storage because the retrieved property is meant to persist throughout the application until the user logs out, in which case, it is removed from the browser.

A: As suggested in the comments, return the promise. You can even chain the then calls like this
return $http.get('/property').then(function(data) {
    localStorageService.set('property', data);
    return data;
});

Then, in your controller...
fact.fetchProperty().then(function(property) {
    $scope.property = property;
});

A: Have you tried using the bind function of local storage service.
Something like

App.factory('fact', ['$scope', '$http', 'localStorageService', function($scope, $http, localStorageService){
    return {
        fetchProperty: function() {
            $http.get('/property')
                .success(function(data, status, headers, config){
                    localStorageService.set('property', data);
                    localStorageService.bind($scope, 'property');
                })
        }
    }
}]);

Then you shouldn't need to set the value in your controller.


text:
Q: Rethrow custom exceptions in several methods C++11 I have a use case where I have to catch various exception that can be thrown and pass an equivalent exception from my library
example:
def subscribe() {
    try {
       .....
       .....
    catch (A e) { throw new MY_A(e);}
    catch (B e) { throw new MY_B(e);}
    catch (C e) { throw new MY_C(e);}
    catch(...) { throw default(e)}
}

I wanted to do this for several methods - subscribe, unsubscribe, stop, start etc., Is there any easy way of doing this ?
Had it been in python, I would have simply written a decorator and achieved this. What will be the easy way to do this in C++11 ?

A: Yes, you can use std::current_exception() to get a handle on the current exception in a catch(...) block. Combining that with the fact that default arguments are evaluated at the point of a function call, we can do the following:
void common_exception_handler(std::exception_ptr eptr = std::current_exception()) {
    try {
        if (eptr) {
            std::rethrow_exception(eptr);
        }
    }
    catch (A const &e) {throw MY_A(e);}
    catch (B const &e) {throw MY_B(e);}
    catch (C const &e) {throw MY_C(e);}
}

void subscribe() {
    try {
        ...
    }
    catch (...) {common_exception_handler();}
}


text:
Q: API gateway for appengine micro-services? Im moving a monolithic App "Rest Mobile Backend" written in Java into a micro-services App
This App is currently hosted in AppEngine in GCP as a single service and hence will be broken down into 8-10 services in App Engine.
Now Im still in the design phase, and my concern is simply that for some client's calls I need to call multi services sequentially or in parallel, how to provide such thing?
I've heard about API Gateway term but Im not sure if GCP have such thing ready to use?
I have heard about NginX but it needs to be installed in a VM and hence handling its scaling up/down and security by myself and I dont want that since my team is pretty small. I need to leverage the Power of scaling up/down of the App Engine in all my system so  my team just need to write code and upload it and nothing more to work about.

A: There is this new API Gateway product in GCP (released September 2020).
It's described as:

Fully managed gateway for serverless workloads

This seem to match your requirements.
The product is currently in beta, and it has some limitations (it does not currently support OpenAPI v3).
The requirements specified in the comments (which you might want to add to your question) are not fulfilled by the GCP's API Gateway, since that gateway is only for securing and monitoring the API itself.
You'll have to develop some logic behind it. As suggested in some comments, a good idea would be:
GCP API Gateway -> Cloud Run service to fan out requests in parallel -> All microservices


text:
Q: Entity Framework 4 and SQL Server 2008 Multiple Possible Foreign Keys I am trying to come up with a database design that would work with Entity Framework 4 Code First.  Actually, I have no experience yet of EF4 Code First but as I understand it, if I write the code, it will create the database and tables.
The issue is this. There are various types of auctions, they all have some common fields and some specific ones. In the code I envisage having a base abstract class called Auction and subclasses like LowestUniqueBidAuction and EnglishForwardAuction etc.
Nothing surprising there. The problem is that I imagine the database structure to mimic this. I imagine an Auction table and a LowestUniqueBidAuction table and a EnglishForwardAuction table. In the Auction table I imagine a foreign key into one of these two tables for each row depending on the type of auction that that row is. I also imagine another column in the Auction table with the name of the derived auction table (such as EnglishForwardAuction).
The problem is that whenever I've ever created a foreign key I've had to specify the name of the foreign table into which the key points (which makes sense). In this case, however, there is one of many tables that the key could point. So there are many issues here. Firstly, I could simply not use a foreign key and just use an ordinary field, but then the database will not be able to maintain data consistency for me. The second issue is how will EF Code First handle this?  In other words, how will it know that if I ask for all EnglishForwardAuction rows from the Auction table that it should look at the column with the table name and then join on the EnglishForwardAuction table to get the extra fields?
Has anyone ever faced similar issues?
Thanks,
Sachin

A: This problem is solvable in Entity Framework in a number of ways - read up on how EF handles inheritance and what strategies are available.
There are basically three strategies how to handle this:
(1) Table per Hierarchy
You have only one single table, that represents all possible sub classes. Of course, this means, several rows (that only exist in a given subclass) must be nullable, since they don't show up / don't exist in super classes or other subclasses.
(2) Table per Type
Each subclass gets its own table, and by default, the sub-types table shares the PK with the base classes' table - e.g. PK = 1 in Auction will also be PK = 1 in EnglishForwardAuction. So your subclass tables reference the base table - not the other way around.
(3) Table per Concrete Type
Each concrete subclass (your separate auction types) gets its own table, but that table contains everything - all the columns, from that specific type, but also its base type.
Read more here:

*

*Inheritance in the Entity Framework

*Inheritance and Associations with Entity Framework Part 1

*Entity Framework Modeling: Table Per Hierarchy Inheritance

*Entity Framework Modeling: Table Per Type Inheritance
Searching for Entity Framework Inheritance and/or one of these strategies will reveal a lot more hits, too - that topic is very well covered and discussed on the interwebs! :-)


text:
Q: Run echo and type without new line I'm looking for a way to run echo and type in one line on DOS batch.
echo [No.1]
type No1.log
echo [No.2]
type No2.log

this script will output like below
[No.1]
No1.log No1.log No1.log No1.log
[No.2]
No2.log No2.log No2.log No2.log

But this is not good for legibility. I want to print like below
[No.1] No1.log No1.log No1.log No1.log
[No.2] No2.log No2.log No2.log No2.log

A: Have you tried reading the content of the log, then concatenating it?
For example, using this to read the log:
set /p log1=<No1.log

Then echo the line:
echo [No.1] %log1%


text:
Q: subprocess.CalledProcessError - Airflow I have created a custom view in airflow 1.10.12.
when I try to open the page, I get the following error in web.
Traceback (most recent call last):
  File "/home/deploy/airflow_env/lib/python3.7/site-packages/flask/app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/deploy/airflow_env/lib/python3.7/site-packages/flask/app.py", line 1952, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/deploy/airflow_env/lib/python3.7/site-packages/flask/app.py", line 1821, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/home/deploy/airflow_env/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/home/deploy/airflow_env/lib/python3.7/site-packages/flask/app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/deploy/airflow_env/lib/python3.7/site-packages/flask/app.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/deploy/airflow_env/lib/python3.7/site-packages/flask_admin/base.py", line 69, in inner
    return self._run_view(f, *args, **kwargs)
  File "/home/deploy/airflow_env/lib/python3.7/site-packages/flask_admin/base.py", line 368, in _run_view
    return fn(self, *args, **kwargs)
  File "/home/deploy/airflow/plugins/views/backfill_view.py", line 14, in base
    dags=self._get_dag_names()
  File "/home/deploy/airflow/plugins/views/backfill_view.py", line 66, in _get_dag_names
    'airflow list_dags', shell=True
  File "/usr/lib/python3.7/subprocess.py", line 411, in check_output
    **kwargs).stdout
  File "/usr/lib/python3.7/subprocess.py", line 512, in run
    output=stdout, stderr=stderr)
subprocess.CalledProcessError: Command 'airflow list_dags' returned non-zero exit status 120.

this is the code piece from backfill_view.py line 66
dags_raw = subprocess.check_output(
    'airflow list_dags', shell=True
).split()

I'm able to run airflow list_dags directly from the server.
I couldn't find the right solution. I'd appreciate it if anyone could help with this.
Apache Airflow [1.10.12]
Platform: [Linux, x86_64]
Python Version: [3.7.3]


text:
Q: CMake: "cl.exe not able to compile a simple test program" I want to build DCMTK in Visual Studio 2010.
I followed the advice here enter link description here, as the image shows.

And I still get the same error. Any ideas?

A: Run the following script before running cmake.
>vcvars32  (to set some system vars, C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin\vcvars32.bat)

A: A similar problem has been reported here
The solution is:
First, check if you have .NET 4.5 on your system. If you do, that is very likely causing the problem. Try either upgrading to VS2010 SP1 or downgrade .NET to 4.0
CAUSES:
This error appear because you have installed Visual C++ 2012 after you have actually installed Visual C++ 2010 in your system; another cause is because .net Framework 4.5 replace .net Framework 4.0; .net Framework corrupted files;
HOW TO SOLVE:
Uninstall .NET Framework 4.5 from your system; then download .NET Framework 4.0 and install it; this should fix your problem;


text:
Q: How do I put all the dates from a table in a new column as I use 'select' in MySQL? I have a a SQL query
SELECT
 student.`firstname` AS student_firstname,
 student.`lastname` AS student_lastname,
 DATE_FORMAT(attendance.`date`, '%M %d, %Y') AS attendance_date,
 class.`subcode` AS class_subcode,
 student.`idno` AS student_idno
FROM
 `student` student INNER JOIN `attendance` attendance ON student.`idno` = attendance.`sidno`
 INNER JOIN `class` class ON attendance.`classid` = class.`id`
WHERE
 class.iidno = 930
GROUP BY student.idno
HAVING SUM(attendance.remark='absent') > 3
ORDER BY
 class.subcode,
 student.lastname,
 attendance.date
ASC

This query displays all the students that has 3 or more absences but in the attendance.date field it only displays one date. I want to display all the attendance.date that has attendance.remark='absent'
This is a sample display from the query above
student_firstname   student_lastname   attendance_date   class_subcode   student_idno
Student 1 fs        Student 1 ls       February 01, 2016 IT421           0000001
Student 2 fs        Student 2 ls       February 01, 2016 IT421           0000002
Student 3 fs        Student 3 ls       February 01, 2016 IT421           0000003

as you can see it only contains 1 date even though that student has more than 3 absences. I need a display like this
student_firstname   student_lastname   attendance_date   class_subcode   student_idno
Student 1 fs        Student 1 ls       February 01, 2016 IT421           0000001
Student 1 fs        Student 1 ls       February 02, 2016 IT421           0000001
Student 1 fs        Student 1 ls       February 03, 2016 IT421           0000001
Student 2 fs        Student 2 ls       February 01, 2016 IT421           0000002
Student 3 fs        Student 3 ls       February 01, 2016 IT421           0000003
Student 3 fs        Student 3 ls       February 02, 2016 IT421           0000003

or maybe like this
student_firstname   student_lastname   attendance_date   class_subcode   student_idno
Student 1 fs        Student 1 ls       Feb 01, Feb 02    IT421           0000001
Student 2 fs        Student 2 ls       Feb 01            IT421           0000002
Student 3 fs        Student 3 ls       Feb 01, Feb 02    IT421           0000003

Is this possible?

A: Try the following to match your 2nd expected result.
SELECT
 student.`firstname` AS student_firstname,
 student.`lastname` AS student_lastname,
 GROUP_CONCAT(DATE_FORMAT(attendance.`date`, '%b %d') SEPARATOR ', ') AS attendance_date,
 class.`subcode` AS class_subcode,
 student.`idno` AS student_idno
FROM
 `student` student INNER JOIN `attendance` attendance ON student.`idno` = attendance.`sidno`
 INNER JOIN `class` class ON attendance.`classid` = class.`id`
WHERE
 class.iidno = 930
GROUP BY student.idno
HAVING SUM(attendance.remark='absent') > 3
ORDER BY
 class.subcode,
 student.lastname,
 attendance.date
ASC


text:
Q: AsciiDoc -> Docbook not showing images I am having some trouble with an AsciiDoc document. It uses an image, but the image is only shown in the HTML version, but not in the PDF version.
I have this short document:
Test book
=========
Robert Larsen
:doctype: book

Test chapter
------------
image:test_image.jpg[Test image]

This looks fine in HTML. But when I convert first to Docbook and then to PDF (using db2pdf), then only the alternative text is shown.
The Docbook version is:

<book lang="en">
<bookinfo>
    <title>Test book</title>
    <author>
        <firstname>Robert</firstname>
        <surname>Larsen</surname>
    </author>
    <authorinitials>RL</authorinitials>
</bookinfo>
<chapter id="_test_chapter">
<title>Test chapter</title>
<simpara><inlinemediaobject>
  <imageobject>
  <imagedata fileref="test_image.jpg"/>
  </imageobject>
  <textobject><phrase>Test image</phrase></textobject>
</inlinemediaobject></simpara>
</chapter>
</book>

I have tried other image formats as well, so that is not it.
I use Ubuntu 12.10
Any ideas?

A: I can't explain why the image is missing (perphaps there is something wrong with the processing of inlinemediaobject). In any case, db2pdf is part of an old toolchain (based on DSSSL stylesheets) that is hardly maintained anymore.
It will work if you use the more modern DocBook-XSL stylesheets together with FOP. See this Ubuntu documentation: https://help.ubuntu.com/community/DocBook#DocBook_to_PDF.


text:
Q: Can't access website admin panel , https to http migration misconfiguration Website Backend: codeigniter php
So I was trying to change http to https to my website, My college has a SSL certificate in our college domain in which http was working fine, I added these 3 line to my main .htaccess file
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{SERVER_NAME}/$1 [R,L]

So basically what is doing is redirecting to https whenever a request is made to http, Since I haven't configured my https properly, It is showing

This page cant be reached

When I was trying change back my .htaccess file I couldnt even open admin panel because the admin panel is in the same domain , so it is again showing the error.
Anyone help me please
Thanks in advance

A: RewriteEngine On
RewriteCond %{HTTP_HOST} ^domainname\.com [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://domainname.com/$1 [R=301,L]

try this way


text:
Q: Smart cast an Arrow-kt Option I am trying to smart cast an Option from any Any variable so that I can determine if the Option is empty however the IDE is indicating that Option<*> could not be smart cast because it is declared in a different module.
fun hasEmptyValue(column: Pair<String, Any>): Boolean = when {
    column.second is Option<*> -> column.second.isEmpty()
    else -> false
}

A: The following causes smartcast to work for me:
fun hasEmptyValue(column: Pair<String, Any>): Boolean {
    val second = column.second
    return when (second) {
        is Option<*> -> second.isEmpty() //Smart cast to arrow.core.Option<*>
        else -> false
    }
}

The explanation for why a smart cast across modules is not allowed is on the Jetbrains issue tracker here:

A smart cast is only valid when multiple accesses of the same property are guaranteed to return the same value. If the property being accessed is defined in a different module from the access location, the module containing the property can be recompiled separately from the module where it's accessed, breaking the key requirement of the smart cast. Therefore, cross-module smart casts are not allowed.

A: David Rawson shows how to fix it, but doesn't explain why your code doesn't work.
The reason is that column.second could in principle return different values for two calls; even though Pair#second is a val, it could have a custom getter method.
If Pair was in the same module, the compiler could check this, but for other modules it doesn't.


text:
Q: Windows Java command line to know the memory settings I'm looking for a windows command line that would tell me at how much the memory settings have been set to start an application.
What is the default for Windows 7 JRE 1.6 if I do "java -jar my.jar" ?
thanks

A: If you're using Sun's JVM, -XX:+PrintFlagsFinal will print out all JVM settings:
java -XX:+PrintFlagsFinal ...

The maximum heap size is shown as MaxHeapSize:
uintx MaxHeapSize                              := 1073741824      {product}

The value is in bytes, so in the above example it's 1GB.

A: You can use jinfo (which is part of the JDK) to show the environment with which the JVM was started. If any non-standard settings were specified, it will also show them:

Attaching to process ID 2520, please wait...
Debugger attached successfully.
Client compiler detected.
JVM version is 23.3-b01

Java System Properties:

java.runtime.name = Java(TM) SE Runtime Environment
java.vm.version = 23.3-b01
...
java.vm.specification.name = Java Virtual Machine Specification
java.runtime.version = 1.7.0_07-b10
java.awt.graphicsenv = sun.awt.Win32GraphicsEnvironment
os.arch = x86

java.vm.specification.vendor = Oracle Corporation
...
java.specification.name = Java Platform API Specification
java.class.version = 51.0
sun.management.compiler = HotSpot Client Compiler
user.timezone = Europe/Berlin
java.awt.printerjob = sun.awt.windows.WPrinterJob
java.vm.info = mixed mode, sharing
java.version = 1.7.0_07

...

VM Flags:

-Xmx512m


text:
Q: Creating a new variable using dplyr in R using lists So let's say we have three lists.
list_A <- c("PA","MA","MD")
list_B <- c("NJ","NY","OK")
list_C <- c("AZ","MT","LA")

I have a dataframe like this
ID        presenter          state
1         Donatello   c("AZ","NY")
2          Leonardo             NJ
3            Rafael   c("LA","MT")
4     Michaelangelo    c("PA,"LA")

I want to use the tidyverse to create three new vars which count how many times state contains an element of their list for each row.
ID        presenter          state     A   B   C
1         Donatello   c("AZ","NY")     0   1   1
2          Leonardo             NJ     0   1   0
3            Rafael   c("LA","MT")     0   0   2
4     Michaelangelo   c("PA","LA")     1   0   1

Unrelated but related, but out of curiousity, is it possible to unlist() the state but make more rows with the old info, so manipulating df1...
ID        presenter          state
1         Donatello             AZ
1         Donatello             NY
2          Leonardo             NJ
3            Rafael             LA
3            Rafael             MT
4     Michaelangelo             PA
4     Michaelangelo             LA

A: You can use double sapply :
list_data <- list(list_A, list_B, list_C)
cbind(df1, data.frame(sapply(list_data, function(x)
           sapply(df1$state, function(y) sum(y %in% x)))))

#     ID presenter     state        X1    X2    X3
#  <int> <chr>         <list>    <int> <int> <int>
#1     1 Donatello     <chr [2]>     0     1     1
#2     2 Leonardo      <chr [1]>     0     1     0
#3     3 Rafael        <chr [2]>     0     0     2
#4     4 Michaelangelo <chr [2]>     1     0     1

A: How about this regarding your first question:
library(dplyr)
library(tidyr)
library(tibble)

list_A <- c("PA","MA","MD")
list_B <- c("NJ","NY","OK")
list_C <- c("AZ","MT","LA")

data <- tibble(
  ID = c(1, 2, 3, 4),
  presenter = c("Donatello", "Leonardo", "Rafael", "Michaelangelo"),
  state = list(c("AZ", "NJ"), c("NJ"), c("LA", "MT"), c("PA", "LA"))
)

data <- data %>%
  rowwise() %>%
  mutate(A = sum(list_A %in% state),
         B = sum(list_B %in% state),
         C = sum(list_C %in% state))

With this output:
> data
Source: local data frame [4 x 6]
Groups: <by row>

# A tibble: 4 x 6
     ID presenter     state         A     B     C
  <dbl> <chr>         <list>    <int> <int> <int>
1     1 Donatello     <chr [2]>     0     1     1
2     2 Leonardo      <chr [1]>     0     1     0
3     3 Rafael        <chr [2]>     0     0     2
4     4 Michaelangelo <chr [2]>     1     0     1

UPDATE
As for your second question: the tidyr unnest function will do this.
> data %>%
+   unnest(state)
# A tibble: 7 x 3
     ID presenter     state
  <dbl> <chr>         <chr>
1     1 Donatello     AZ
2     1 Donatello     NJ
3     2 Leonardo      NJ
4     3 Rafael        LA
5     3 Rafael        MT
6     4 Michaelangelo PA
7     4 Michaelangelo LA

UDPATE2
To count multiple occurrences in the state column you will need an extra loop. This may do it (but suggest you test it):
data <- data %>%
  rowwise() %>%
  mutate(A = sum(unlist(lapply(list_A, function(x) sum(x == state)))),
         B = sum(unlist(lapply(list_B, function(x) sum(x == state)))),
         C = sum(unlist(lapply(list_C, function(x) sum(x == state)))))

For this data:
data <- tibble(
  ID = c(1, 2, 3, 4),
  presenter = c("Donatello", "Leonardo", "Rafael", "Michaelangelo"),
  state = list(c("AZ", "NJ"), c("NJ"), c("LA", "MT", "MT", "MT"), c("PA", "PA", "LA"))
)

we would expect extra counts for the third (3x "MT") and fourth (2x "PA") rows for respectively column C and A:
> data
Source: local data frame [4 x 6]
Groups: <by row>

# A tibble: 4 x 6
     ID presenter     state         A     B     C
  <dbl> <chr>         <list>    <int> <int> <int>
1     1 Donatello     <chr [2]>     0     1     1
2     2 Leonardo      <chr [1]>     0     1     0
3     3 Rafael        <chr [4]>     0     0     4
4     4 Michaelangelo <chr [3]>     2     0     1


text:
Q: ressource a routing file in xml In routing.yml I can ressource other routing configs with:
leaphly_cart:
type: rest
resource: '@AppXXXBundle/Resources/config/rest.xml'
prefix:   /api/v1/

And rest.xml file :
<?xml version="1.0" encoding="UTF-8" ?>

  <routes xmlns="http://symfony.com/schema/routing"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://symfony.com/schema/routing http://symfony.com/schema/routing/routing-1.0.xsd">

      <import id="carts" type="rest" resource="leaphly_cart.cart.limited.controller" name-prefix="api_1_" />
      <import id="cartItems" type="rest" resource="leaphly_cart.cart_item.limited.controller" name-prefix="api_1_" parent="carts" />
      <import id="carts_full" type="rest" resource="leaphly_cart.cart.full.controller" name-prefix="api_1_full_" prefix="/full" />
      <import id="cartItems_full" type="rest" resource="leaphly_cart.cart_item.full.controller" name-prefix="api_1_full_" parent="carts_full" prefix="/full" />
      <import id="cartTransitions" type="rest" resource="Leaphly\CartBundle\Controller\CartTransitionsController" name-prefix="api_1_" parent="carts" />

  </routes>

But this doesn't work...and show error :
InvalidArgumentException: [ERROR 1845] Element '{http://symfony.com/schema/routing}routes': No matching global declaration available for the validation root. (in /var/www/app.com/web/ - line 5, column 0)

What's wrong in this ?

A: The XML validation fails because there are attributes present that symfony's standard routing xsd does not include/allow ( i.e. the name-prefix attribute).
Add FOSRestBundle/Resources/config/schema/routing/rest_routing-1.0.xsd to your xml file and the validation won't fail.


text:
Q: Unable to extract url links in python I'm trying to print the place names (cults, bankhead) in the following link
https://www.saa.gov.uk/search.php?SEARCHED=1&ST=&SEARCH_TERM=aberdeen%2C+Aberdeen+City&ASSESSOR_ID=&SEARCH_TABLE=valuation_roll_cpsplit&x=0&y=0&PAGE=0&DISPLAY_COUNT=10&TYPE_FLAG=CP&ORDER_BY=PROPERTY_ADDRESS&H_ORDER_BY=SET+DESC&ORIGINAL_SEARCH_TERM=aberdeen&DRILL_SEARCH_TERM=ABERDEEN%2C+Aberdeen+City&DD_UNITARY_AUTHORITY=Aberdeen+City&DD_TOWN=ABERDEEN#results
I've written the following code but when I run it, it thinks for a while generates a blank output and cmd prompts me to enter again.
I've tried 2 different print statments at end, i've put a # in front of the first
Any ideas, thanks & Regards
import requests
from bs4 import BeautifulSoup
import csv

# connection header
header={'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Encoding':'gzip, deflate, sdch, br',
'Accept-Language':'en-US,en;q=0.8,fr;q=0.6',
'Connection':'keep-alive',
'Cookie':'mdtp=y4Ts2Vvql5V9MMZNjqB9T+7S/vkQKPqjHHMIq5jk0J1l5l131dU0YXsq7Rr15GDyghKHrS/qcD2vdsMCVtzKByJEDZFI+roS6tN9FN5IS70q8PkCCBjgFPDZjlR1A3H9FJ/zCWXMNJbaXqF8MgqE+nhR3/lji+eK4mm/GP9b8oxlVdupo9KN9SKanxu/JFEyNXutjyN+BsxRztNem1Z+ExSQCojyxflI/tc70+bXAu3/ppdP7fIXixfEOAWezmOh3ywchn9DV7Af8wH45t8u4+Y=; mdtpdi=mdtpdi#f523cd04-e09e-48bc-9977-73f974d50cea#1484041095424_zXDAuNhEkKdpRUsfXt+/1g==; seen_cookie_message=yes; _ga=GA1.4.666959744.1484041122; _gat=1',
'Host':'https://www.saa.gov.uk/',
'Referer':'https://www.saa.gov.uk/',
'Upgrade-Insecure-Requests':'1',
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.51 Safari/537.36'
}

session = requests.session()

user_agent = {'User-Agent': 'Mozilla/5.0'}
url = 'https://www.saa.gov.uk/search.php?SEARCHED=1&ST=&SEARCH_TERM=aberdeen%2C+Aberdeen+City&ASSESSOR_ID=&SEARCH_TABLE=valuation_roll_cpsplit&x=0&y=0&PAGE=0&DISPLAY_COUNT=10&TYPE_FLAG=CP&ORDER_BY=PROPERTY_ADDRESS&H_ORDER_BY=SET+DESC&ORIGINAL_SEARCH_TERM=aberdeen&DRILL_SEARCH_TERM=ABERDEEN%2C+Aberdeen+City&DD_UNITARY_AUTHORITY=Aberdeen+City&DD_TOWN=ABERDEEN#results'

response = session.get(url, headers=header)

soup = BeautifulSoup(response.content,"lxml")

for link in soup.findAll('a'):
    #print link.get('href')
    print link.find('a')['href']

A: There's no hard limit on this web page, so a simple requests.get would do the scraping job, as for BeautifulSoup part, the place names and links you are looking for are in td tags with no extra attribute, so CSS selector would be more fit for parsing.
So in this case:
import requests
from bs4 import BeautifulSoup as soup

url = 'https://www.saa.gov.uk/search.php?SEARCHED=1&ST=&SEARCH_TERM=aberdeen%2C+Aberdeen+City&ASSESSOR_ID=&SEARCH_TABLE=valuation_roll_cpsplit&x=0&y=0&PAGE=0&DISPLAY_COUNT=10&TYPE_FLAG=CP&ORDER_BY=PROPERTY_ADDRESS&H_ORDER_BY=SET+DESC&ORIGINAL_SEARCH_TERM=aberdeen&DRILL_SEARCH_TERM=ABERDEEN%2C+Aberdeen+City&DD_UNITARY_AUTHORITY=Aberdeen+City&DD_TOWN=ABERDEEN#results'
baseurl = 'https://www.saa.gov.uk'

response = requests.get(url)
html = soup(response.text, 'lxml')

for link in html.select('td a'):
    print link.text, baseurl + link['href']

And results:
...
...
BOYD ORR CLOSE https://www.saa.gov.uk/search.php?SEARCHED=1&ST=&SEARCH_TERM=aberdeen%2C+ABERDEEN%2C+Aberdeen+City&ASSESSOR_ID=&SEARCH_TABLE=valuation_roll_cpsplit&x=0&y=0&PAGE=0&DISPLAY_COUNT=10&TYPE_FLAG=CP&ORDER_BY=PROPERTY_ADDRESS&H_ORDER_BY=SET+DESC&ORIGINAL_SEARCH_TERM=aberdeen&DRILL_SEARCH_TERM=BOYD+ORR+CLOSE%2C+ABERDEEN%2C+Aberdeen+City&DD_UNITARY_AUTHORITY=Aberdeen+City&DD_TOWN=ABERDEEN&DD_STREET=BOYD+ORR+CLOSE#results
DON TERRACE https://www.saa.gov.uk/search.php?SEARCHED=1&ST=&SEARCH_TERM=aberdeen%2C+ABERDEEN%2C+Aberdeen+City&ASSESSOR_ID=&SEARCH_TABLE=valuation_roll_cpsplit&x=0&y=0&PAGE=0&DISPLAY_COUNT=10&TYPE_FLAG=CP&ORDER_BY=PROPERTY_ADDRESS&H_ORDER_BY=SET+DESC&ORIGINAL_SEARCH_TERM=aberdeen&DRILL_SEARCH_TERM=DON+TERRACE%2C+ABERDEEN%2C+Aberdeen+City&DD_UNITARY_AUTHORITY=Aberdeen+City&DD_TOWN=ABERDEEN&DD_STREET=DON+TERRACE#results
BYRON CRESCENT https://www.saa.gov.uk/search.php?SEARCHED=1&ST=&SEARCH_TERM=aberdeen%2C+ABERDEEN%2C+Aberdeen+City&ASSESSOR_ID=&SEARCH_TABLE=valuation_roll_cpsplit&x=0&y=0&PAGE=0&DISPLAY_COUNT=10&TYPE_FLAG=CP&ORDER_BY=PROPERTY_ADDRESS&H_ORDER_BY=SET+DESC&ORIGINAL_SEARCH_TERM=aberdeen&DRILL_SEARCH_TERM=BYRON+CRESCENT%2C+ABERDEEN%2C+Aberdeen+City&DD_UNITARY_AUTHORITY=Aberdeen+City&DD_TOWN=ABERDEEN&DD_STREET=BYRON+CRESCENT#results
MARINE TERRACE https://www.saa.gov.uk/search.php?SEARCHED=1&ST=&SEARCH_TERM=aberdeen%2C+ABERDEEN%2C+Aberdeen+City&ASSESSOR_ID=&SEARCH_TABLE=valuation_roll_cpsplit&x=0&y=0&PAGE=0&DISPLAY_COUNT=10&TYPE_FLAG=CP&ORDER_BY=PROPERTY_ADDRESS&H_ORDER_BY=SET+DESC&ORIGINAL_SEARCH_TERM=aberdeen&DRILL_SEARCH_TERM=MARINE+TERRACE%2C+ABERDEEN%2C+Aberdeen+City&DD_UNITARY_AUTHORITY=Aberdeen+City&DD_TOWN=ABERDEEN&DD_STREET=MARINE+TERRACE#results
...
...

Edit:
If you only need to find all links in first table, all you need to do is to locate the first table first with first_table = html.find('table'), then search for links in this table.
html = soup(response.text, 'lxml')

first_table = html.find('table')

for link in first_table.select('td a'):
    print link.text, baseurl + link['href']


text:
Q: Asymptotic behaviour of fourier transform of exponential of a polynomial Consider the family of functions $f_n=e^{-x^{2n}}$, where $x$ is a real number. I am interested in the fourier transform $\hat{f_n}(t)=\int_{-\infty}^{\infty}f_n(x)e^{2\pi itx}dx$. While the exact expression for $\hat{f}_n$ would be difficult to obtain, except when $n=1$, are there results that provide the asymptotic behaviour of $\hat{f}_n(t)$, for any fixed $n$ (say $n=2$), but as $t\rightarrow \infty$? In particular, does $\hat{f_n}(t)$ decay as $e^{-t^{\alpha(n)}}$, for some $\alpha(n)>0$?

A: This can be solved by steepest descent analysis of the integral.
To set things us, it's convenient to first change variables. Exchange $t$ for a new parameter $\lambda$, defined by
$$
\lambda = \left(\frac{\pi t}{n}\right)^\frac{2n}{2n-1} \to \infty.
$$
Then change variables in the integral to $z$, defined by
$$
x = \lambda^\frac{1}{2n} z.
$$
The Fourier integral then becomes
$$
\lambda^\frac{1}{2n} \int_{-\infty}^\infty  e^{\lambda s(z)} \, dz, \qquad s(z)= 2i n z-z^{2n}.
$$
The saddle-points are the stationary points $s'(z)=0$ of $s$, lying on the unit circle at points
$$
z = \exp\left(\frac{2k-\frac{3}{2}}{2n-1} i \pi\right),\qquad k=1,2,\ldots,2n-1.
$$
Now to work out which of these saddle-point is relevant, a diagram is worth $10^3$ words:

This plot shows (for $n=3$) the real part of $s(z)$, with saddle-points marked in black. Blue colours indicate regions where the real part is more negative. The red curves are contours of constant imaginary part of $s(z)$: the paths of steepest descent follow such curves. With this picture, you can convince yourself that the contour along the real axis should be deformed to pass through all the saddle-points in the upper half-plane, namely $k=1,2,\ldots,n$.
Next, we should see which saddle-point is most important, giving the largest real part of $s(z)$. On the saddle-points, we have $z^{2n-1}=i$, so $s(z)=(2n-1)iz$: the largest real part of $s(z)$ comes from the smallest imaginary part of $z$, which is $k=1$ and $k=n$.
Finally, we expand $s(z)$ to quadratic order at each of these two saddle-points, and do the Gaussian integral to get the leading order asymptotics. For $n>1$, we get
$$
\int_{-\infty}^\infty e^{\lambda s(z)} dz \sim 2\sqrt{\frac{\pi }{\lambda  n (2 n-1)}} \Re\left[\exp \left(-i \frac{\pi}{2}\frac{(n-1)}{2n-1}+\lambda  e^{\frac{i n \pi }{2 n-1}} (2 n-1)\right)\right].
$$
This is twice the real part of the $k=1$ saddle (with the $k=n$ saddle giving the complex conjugate). For $n=1$, the result is less by a factor of two, because there's a unique saddle (and we get the exact result).
The original Fourier transform therefore decays like $\exp\left(-(2n-1)\sin\left(\frac{\pi}{2(2n-1)}\right)\lambda\right)$, times a rapid oscillation. In terms of the original variable $t$, this is $\exp\left(-\# t^\frac{2n}{2n-1}\right)$.


text:
Q: placing a loader next to a button im trying to add a loader next to a button, I'm using bootstrap spinner
this is my code :

    <form>

Fibonacci Calculator

            The Fibonacci Of
            <input class="userInput" type="number" id="number" name="amount" min="0" max="50">
            <button type="button" class="btn btn-primary" id="isBtn">Is</button>

    </form>

I tried display:flex on the form tag, also tried to add class and add margins didn't work.
This is the best result I manage to get:


text:
Q: Why does a motor draw more current stopped or under load? I have a small motor connected to DC source, and use the ampere meter to survey the current through the motor. While the motor is rotating, I hold the motor by hand so that it stop. I see the current through the motor increases. Could you help me explain this problem?

A: When you are forcing the motor to stop by holding the motor by hand, you are actually applying a good amount of load which the motor is trying to overcome by trying to generate more power. Thus it draws more current.


text:
Q: How to get unique nested array items in Nunjucks (11ty) and loop over it? I have data from headless CMS of the following type:
type Assortiment = {
  list: Array<Item>
  // ...
}

type Item = {
  brands: Array<Brand>
  // ...
}

type Brand = {
  logo: string,
  title: string,
}

As you can see, there is a list of assortiment entries each with it's own brands list. I need to loop over all unique brands and show them on page using nunjucks.
I tried writing a custom filter for that but couldn't get it working in nunjucks loop. JS would be like that:
eleventyConfig.addFilter('uniqueBrands', (assortiment) => {
  const brands = assortiment.list.flatMap(item => item.brands)
  const map = new Map(brands.map(b => [b.logo, b.title]))

  return [...map.entries()]
})

How I want to use it:

  {% for logo, title in (assortiment.list | uniqueBrands) %}

  {% endfor %}

My tech stack is 11ty + Nunjucks + Netlify CMS.
It seems like I'm trying to misuse nunjucks filter, if so how can it be done otherwise?

Got it working, final solution:
// filters
cfg.addFilter('flatMap', (list, key) => list.flatMap((x) => x[key]))

cfg.addFilter('unique', (list, key) => {
  const map = new Map(list.map((x) => [x[key], x]))

  return [...map.values()]
})

// render

  {% for brand in (assortiment.list | flatMap('brands') | unique('logo')) %}

  {% endfor %}

A: Not sure what you are missing, your code looks fine. You apply a filter in Nunjucks using the pipe operator:

  {% for logo, title in (assortiment | uniqueBrands) %}

  {% endfor %}

It seems like I'm trying to misuse nunjucks filter, if so how can it be done otherwise?

It would probably be easier to create a collection with your unique brands. Your JS code could stay almost the same, but you'd need to get the list of brands using the collection API.