text:
Q: App freezing upon button click Here is all code within the project from the youtube tutorial which I have followed.
(main section)
ProjectActivity:
package justinehume.Project;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class ProjectActivity extends Activity{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button tut1 = (Button) findViewById(R.id.tutorial1);
        tut1.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {

            startActivity(new Intent("android.intent.action.TUTORIALONE"));

            }
        });

    }
    protected void onPause(){
        super.onPause();
    }
}

main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    android:orientation="vertical">

    <Button android:id="@+id/tutorial1" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:text="Button" />

</LinearLayout>

ProjectManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="justinehume.Project"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".ProjectActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
               <activity
            android:label="@string/app_name"
            android:name=".Tutorialone" >
            <intent-filter >
                <action android:name="android.intent.action.TUTORIALONE" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Tutorialone.java
package justinehume.Project;

import android.app.Activity;
import android.os.Bundle;

public class Tutorialone extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tutorial1);
    }

}

Every time I click the button when the app is running in the SDK, the app crashes and it is force closed. Any ideas?
Thank you!
Logcat
> 04-11 16:19:54.799: D/AndroidRuntime(344): Shutting down VM 04-11
> 16:19:54.809: W/dalvikvm(344): threadid=1: thread exiting with
> uncaught exception (group=0x4001d800) 04-11 16:19:54.819:
> E/AndroidRuntime(344): FATAL EXCEPTION: main 04-11 16:19:54.819:
> E/AndroidRuntime(344): android.content.ActivityNotFoundException: No
> Activity found to handle Intent {
> act=android.intent.action.TUTORIALONE } 04-11 16:19:54.819:
> E/AndroidRuntime(344):    at
> android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1408)
> 04-11 16:19:54.819: E/AndroidRuntime(344):    at
> android.app.Instrumentation.execStartActivity(Instrumentation.java:1378)
> 04-11 16:19:54.819: E/AndroidRuntime(344):    at
> android.app.Activity.startActivityForResult(Activity.java:2817) 04-11
> 16:19:54.819: E/AndroidRuntime(344):  at
> android.app.Activity.startActivity(Activity.java:2923) 04-11
> 16:19:54.819: E/AndroidRuntime(344):  at
> justinehume.Project.ProjectActivity$1.onClick(ProjectActivity.java:23)
> 04-11 16:19:54.819: E/AndroidRuntime(344):    at
> android.view.View.performClick(View.java:2408) 04-11 16:19:54.819:
> E/AndroidRuntime(344):    at
> android.view.View$PerformClick.run(View.java:8816) 04-11 16:19:54.819:
> E/AndroidRuntime(344):    at
> android.os.Handler.handleCallback(Handler.java:587) 04-11
> 16:19:54.819: E/AndroidRuntime(344):  at
> android.os.Handler.dispatchMessage(Handler.java:92) 04-11
> 16:19:54.819: E/AndroidRuntime(344):  at
> android.os.Looper.loop(Looper.java:123) 04-11 16:19:54.819:
> E/AndroidRuntime(344):    at
> android.app.ActivityThread.main(ActivityThread.java:4627) 04-11
> 16:19:54.819: E/AndroidRuntime(344):  at
> java.lang.reflect.Method.invokeNative(Native Method) 04-11
> 16:19:54.819: E/AndroidRuntime(344):  at
> java.lang.reflect.Method.invoke(Method.java:521) 04-11 16:19:54.819:
> E/AndroidRuntime(344):    at
> com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
> 04-11 16:19:54.819: E/AndroidRuntime(344):    at
> com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 04-11
> 16:19:54.819: E/AndroidRuntime(344):  at
> dalvik.system.NativeStart.main(Native Method)

A: Tutorialone's intent filter should have category "android.intent.category.DEFAULT" instead of "android.intent.category.LAUNCHER"

A: Okay, upon your request since this is a basic application, I am posting the complete code.
ProjectActivity.java
package justinehume.Project;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class ProjectActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button tut1 = (Button) findViewById(R.id.tutorial1);
        tut1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Jean-Philippe Roy's correction
                startActivity(new Intent(ProjectActivity.this, Tutorialone.class));
            }
        });

    }
}

Tutorialone.java
package justinehume.Project;

import android.app.Activity;
import android.os.Bundle;

public class Tutorialone extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
         // TODO Auto-generated method stub
         super.onCreate(savedInstanceState);
         setContentView(R.layout.tutorial1);
    }
}

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="justinehume.Project"
     android:versionCode="1"
     android:versionName="1.0" >

<uses-sdk android:minSdkVersion="8" />

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <activity
        android:name=".ProjectActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:label="@string/app_name" android:name=".Tutorialone"/>

</application>

</manifest>

Note: I have tested this on an emulator and it doesn't crash. I would recommend that you read/view more tutorials to have a better understanding. Good Luck!


text:
Q: Calling SOAP Web Service from Java What is the best way to call a soap based web service and map the results to a Java objects?  The only thing I have is a wsdl url.

A: The best way is to use wsdl2java, you just supply the wsdl and it generates the client.
Wsdl2java eclipse plugin

A: Take a look at JAX-WS and its reference implementation.
Given a WSDL, it can generate all the client artifacts for you using a tool called wsimport
Once you have the client packaged in a jar file, you can call the web service from a Java client.

A: if you have wsdl then why are so late , dear create web service client import the wsdl into it , and the code will be created and Create object of servicelocator and then use service .

redpajama_set_name: RedPajamaStackExchange


text:
Q: Use MathJax inside Android Studio WebView? Ok so I'm trying to use a WebView with a local html file that uses the MathJax library, but when I run it it doesn't use the library. I tired webView.setJavaScriptEnabled() and I made sure it works as an html document on its own not in a WebView.
Here's my code:
package com.example.mathcompetitions;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    WebView webView;

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

        webView = findViewById(R.id.webView);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        webView.loadUrl("file:///android_asset/index.html");

    }

}

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>Math Concepts</title>
    <style>
        @font-face{
            font-family:Cambria;
            src:url('file:///android_asset/cambria.ttc')
        }
        body {
            font-family: 'Cambria';
            font-size: 32px;
            font-weight: normal;
            text-align: center;
            background-color: #222;
            color: #eee
        }
    </style>
    <script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"> </script>
</head>
<body>
<p id="p">
    When \(a \ne 0\), there are two solutions to \(ax^2 + bx + c = 0\) and they are
    \[x = {-b \pm \sqrt{b^2-4ac} \over 2a}.\]
</p>
</body>
</html>

A: Switching to a different API should do the trick. While working on this I was on 29, but switching to 30 fixed it. And as mentioned in the comments <uses-permission android:name="android.permission.INTERNET" /> in the manifest


text:
Q: A continuous crawl set in powershell does not seem to be crawling content A week ago I created a continuous crawl in SharePoint by using this script:
GET Search Service Application
$ssa = Get-SPEnterpriseSearchServiceApplication

#Get the Crawl Content Source
$cs = Get-SPEnterpriseSearchCrawlContentSource -SearchApplication $ssa -Identity "Local SharePoint sites"

#Enable Continuous Crawls
Set-SPEnterpriseSearchCrawlContentSource -Identity $cs -EnableContinuousCrawls $True

#Set the crawl interval to 10 minutes
$ssa.SetProperty("ContinuousCrawlInterval", 10)
$ssa.Update()

After running the script I could see that the crawl was working.  Recently updated content appeared in searches.  However, after a few days, I noticed that items added after enabling continuous crawls were not appearing in search results.
I ran this script to give me some information on the status:
$ssa = Get-SPEnterpriseSearchServiceApplication

Get-SPEnterpriseSearchCrawlContentSource -Identity 'Local SharePoint Sites' -SearchApplication $ssa | Format-List -Property *

...and received this back:
CrawlState               : Idle
CrawlCompleted           : 5/17/2018 3:53:48 PM
CrawlStarted             : 5/17/2018 3:06:28 PM
SharePointCrawlBehavior  : CrawlVirtualServers
EnableContinuousCrawls   : True
FollowDirectories        : False
Type                     : SharePoint
DeleteCount              : 299
ErrorCount               : 15508
LevelHighErrorCount      : 0
SuccessCount             : 35373
WarningCount             : 1138
Parent                   : {Local SharePoint sites}
StartAddresses           : {https://<servername>/}
Id                       : 1
Tag                      :
Name                     : Local SharePoint sites
FullCrawlSchedule        :
IncrementalCrawlSchedule : Microsoft.Office.Server.Search.Administration.DailySchedule
CrawlStatus              : Idle
ContinuousCrawlStatus    : Crawling
CrawlPriority            : Normal
RefreshCrawls            : Enabled

Because I'm not receiving search results from content I've added since the crawl has been created, and since the value of CrawlCompleted is a week old, I feel that the Continuous Crawl are not truly active as I thought they were.
Can anyone suggest how I might be able to truly enable continuous crawls through PowerShell?
Any suggestions would be appreciated.
Thanks in advance.
M.

A: Your screen capture shows a very large number of errors. These are usually caused from the crawler not having the proper permissions. Check the Crawl Logs to find the cause of the errors.
Have you identified a pattern for what's not getting indexed? A certain site, library, document type, etc.?


text:
Q: Chrome browser is not using 'Open Sans' font defined in my web page instead it is using default for a website I have included font link in my every .html file of website
and defined in CSS to use :
font-family: 'Open Sans', sans-serif;
And it is working fine on firefox but in chrome, it is not picking up this font even after mentioning explicitly in my .html page.
In Chrome, we have to change font type from settings manually. So I am looking a way to force Chrome to use the font type which is mention in my website rater using its own.
Please provide me any code line and explanation to achieve this.
Here is my code :

<!DOCTYPE html>

    <title></title>

    <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,500,600,700" rel="stylesheet">

This is Simple text to identify if font-family Open Sans is shown by chrome or not. This is Simple text to identify if font-family Open Sans is shown by chrome or not. This is Simple text to identify if font-family Open Sans is shown by chrome or not. This is Simple text to identify if font-family Open Sans is shown by chrome or not. This is Simple text to identify if font-family Open Sans is shown by chrome or not. This is Simple text to identify if font-family Open Sans is shown by chrome or not.

you can also see this on Click this link on chrome to see this live

A: welcome on Stackoverflow.
If you look the href of the stylesheet you included the Muli font, ..?family=Muli in order to use the Open Sans you should include the it, replace it with ?family=Open+Sans

A: Your link reference is bad i think, i have a different thing when selecting the font:
<link href="https://fonts.googleapis.com/css?family=Open+Sans&display=swap" rel="stylesheet">

A: I have thought, The real cause is a chrome security add-on Pri*** Ba****, which I disabled and now I can see Open Sans on the live web also.


text:
Q: how to add middleware in nextjs server I am trying to add a middleware in nextjs server like the below node express server uploadFile.single("")
app.post("/upload-excel", uploadFile.single('file'), async (req, res) => {

Here is the nextjs server code, where I need to add the uploadFile.single('file')
export default function handler(req: any, res: NextApiResponse<Data>) {
  });
}

A: Create a _middleware file and handle based on your specific routes :
export function middleware(request: NextRequest) {
  const myCase =
    request.nextUrl.pathname.startsWith('/upload-excel');

  if (myCase) {
    //handle here
  }

}


text:
Q: Pyton Envio de infomacion del sistema unix por correo Estoy tratando de generar un script en python3 que al ejecutar me envie a mi correo personal una serie de información de mi sistema en la nube con centos7, en concreto la salida de un comando sobre varios servicios: Apache, Mysql, pptp... pero me encuentro con un problema.El objetivo es tener mas o menos controlado mi servidor web y los servicios que dependen del. Este es código y problema:
#!/usr/bin/python
import smtplib
import subprocess
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

ApacheStatus = subprocess.call(['systemctl','status','httpd'])
MysqlStatus = subprocess.call(['systemctl','status','mysqld'])
PptpdStatus = subprocess.call(['systemctl', 'status', 'pptpd'])

# create message object instance
msg = MIMEMultipart()

hasta aquí bien,ahora guardo la información genera por el comando en varias variables: ApacheStatus, MysqlStatus, PptpdStatus y se las paso al contenido del mensaje que quiero enviar. Asi:
message = ApacheStatus

password = "xxxxxxxxxxxxx"
msg['From'] = "silicom33@gmail.com"
msg['To'] = "adasdasd21312@gmail.com"
msg['Subject'] = "Prueba-Python"

msg.attach(MIMEText(message, 'plain'))
server = smtplib.SMTP('smtp.gmail.com: 587')
server.starttls()

server.login(msg['From'], password)

server.sendmail(msg['From'], msg['To'], msg.as_string())

server.quit()

print
"Email enviado correctamente %s:" % (msg['To'])

Al ejecutarlo me genera el siguiente error  no llega a enviar nada
Traceback (most recent call last):
  File "StatusServerCorreo.py", line 24, in <module>
    msg.attach(MIMEText(message, 'plain'))
  File "/usr/lib64/python3.6/email/mime/text.py", line 34, in __init__
    _text.encode('us-ascii')
AttributeError: 'int' object has no attribute 'encode'

De lo contrario si formateo la variable message como string, asi:
message = ApacheStatus

me envia un correo con el siguiente cuerpo:
0

Ni más ni menos. En que me equivoco? Estoy formateando mal la salida del comando del sistema (centos7)?
Gracias y estamos en contacto

A: De acuerdo a otras respuestas, podrías obtener algo más que el ID del estado del proceso así:
import subprocess
service = "httpd"

p =  subprocess.Popen(["systemctl", "is-active",  service], stdout=subprocess.PIPE)
(output, err) = p.communicate()
output = output.decode('utf-8')

print(output)


text:
Q: unrecognized option: --diagnostics-file in Mallet I am using LDA in mallet to explore my data. I do not have training and test data. I just use it for clustering my data.
I would like to use a number of useful diagnostic measures provided by Mallet. but when I use this query:
bin\mallet train-topics --input doc500.mallet --num-topics 40 --num-top-words  50 --optimize-interval 10 --output-state doc500topic40-state.gz --output-topic-keys doc500topic40-keys.txt --output-doc-topics  doc500topic40-composition.txt --topic-word-weights-file  doc500topic40-word-weights.txt --diagnostics-file doc500topic40_diagnostics.xml

then I get this Error:
Exception in thread "main" java.lang.IllegalArgumentException:
Unrecognized option 16: --diagnostics-file

A: The diagnostics file option is relatively new. Make sure that you are using version 2.0.8.


text:
Q: Writing a string-concat: How to convert character array to pointer I am learning C and I have written the following strcat function:
char * stringcat(const char* s1, const char* s2) {

    int length_of_strings = strlen(s1) + strlen(s2);
    char s3[length_of_strings + 1]; // add one for \0 at the end

    int idx = 0;

    for(int i=0; (s3[idx]=s1[i]) != 0; idx++, i++);
    for(int i=0; (s3[idx]=s2[i]) != 0; idx++, i++);
    s3[idx+1] = '\0';

    // s3 is a character array;
    // how to get a pointer to a character array?
    char * s = s3;

    return s;

}

That part that looks odd to me is where I have to "re-assign" the character array to a pointer, otherwise C complains that my return is a memory address. I also tried "casting" the return value to (char *) s3, but that didn't work either.
What is the most common way to do this "conversion"? Is this a common pattern in C programs?

A: The problem isn't converting from array to pointer; that happens all the time implicitly, and it's no big deal. Your problem is you've just returned a pointer to invalid memory. The array you allocated in the function disappears when the function returns, and dereferencing a pointer to that array is undefined behavior (returning the pointer isn't technically illegal, but any good compiler warns you, because a pointer that is never dereferenced is usually pretty useless).
If you want to return a new array with the concatenated string, you must use dynamically allocated memory, e.g. from malloc/calloc; making the array static would also work (it would now be persistent global memory), but it would make your function both non-reentrant and non-threadsafe, so it's usually frowned on.
Your little trick of assigning to a pointer and returning the pointer may have fooled the compiler into thinking you weren't doing anything illegal, but it did nothing to make your code safer.

A: You might be used to languages with more dynamic memory handling, but your function here won't work because C strings are just a block of local memory which disappears when you return. That means that whatever you write to char s3[] will disappear after the return (the details vary and the memory can sometimes stick around long enough for you to think it worked even when it didn't).
Normally you'd want to allocate the memory before calling the function, and pass it in as a parameter, as in:
void stringcat(const char * first, const char * second, char * dest, const size_t dest_len)

Called like this:
char title[] = "Mr. ";
char last[] = "Jones";
char addressname[sizeof(title) + sizeof(last)];

stringcat(title, last, addressname, sizeof(addressname));

The other way to do it is to allocate the memory in the function using malloc(), and return that, but you have to remember to free it in the code when you're done with it.

A: There are many ways to handle this situation, but returning a pointer to stack-allocated memory inside the function isn't one of them (the behavior is undefined; consider this memory untouchable once the function returns).
One approach is to allocate heap memory using malloc inside the function, build the result string, then return the pointer to the newly allocated memory with the understanding that the caller is responsible for freeing the memory.
Here's an example of this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *stringcat(const char* s1, const char* s2) {
    int i = 0;
    int s1_len = strlen(s1);
    int s2_len = strlen(s2);
    char *result = malloc(s1_len + s2_len + 1);
    result[s1_len+s2_len] = '\0';

    for (int j = 0; j < s1_len; j++) {
        result[i++] = s1[j];
    }

    for (int j = 0; j < s2_len; j++) {
        result[i++] = s2[j];
    }

    return result;
}

int main(void) {
    char *cat = stringcat("hello ", "world");
    printf("%s\n", cat); // => hello world
    free(cat);
    return 0;
}

Another approach is for the caller to handle all of the memory management, which is similar to how strcat behaves:
/* Append SRC on the end of DEST.  */
char *
STRCAT (char *dest, const char *src)
{
  strcpy (dest + strlen (dest), src);
  return dest;
}

man says:

The strcat() function appends the src string to the dest string, overwriting the terminating null byte ('\0') at the end of dest, and then adds a terminating null byte. The strings may not overlap, and the dest string must have enough space for the result. If dest is not large enough, program behavior is unpredictable; buffer overruns are a favorite avenue for attacking secure programs.


text:
Q: how to extract missing datetime interval in python I have a date dataframe where date contains 15 min of interval. I want to find the missing datetime interval. id should be copied from previous line but value should be nan
'''

 date value id
   2021-12-02 07:00:00  12456677    693214
   2021-01-02 07:30:00  12456677  693214
   2021-01-02 07:45:00  12456677  693214
   2021-01-02 08:00:00  12456677 693214
   2021-01-02 08:15:00  12456665  693215
   2021-01-02 08:45:00  12456665  693215
   2021-01-03 09:00:00  12456666 693217
   2021-01-03 10:30:00  12456666   693217

expacted output is

date value id

   2021-01-02 08:30:00  NAN  693215
   2021-01-02 09:15:00 NAN    693217
   2021-01-03 09:30:00 NAN    693217
   2021-01-03 09:45:00 NAN    693217
   2021-01-03 10:00:00  NAN   693217

I am trying

df['Datetime'] = pd.to_datetime(df['date'])
df[ df['Datetime'].diff() > pd.Timedelta('15min') ]

but it is just giving a time after which date is missing. not the missing date and time.it showed me this output

date value id

   2021-01-02 08:15:00  12456665  693215
   2021-01-03 09:00:00  12456666 693217
   2021-01-03 10:30:00  12456666   693217

can some one please guide me how can I extract missing date and time?
Thanks in advance

A: Use Series.asfreq per groups for get missing intervals:
#create DatetimeIndex
df['date'] = pd.to_datetime(df['date'])
df = df.set_index('date')

#add 15 Minutes index per days and per id
df1 = (df.groupby([pd.Grouper(freq='D'), 'id'])['value']
         .apply(lambda x: x.asfreq('15min'))
         .reset_index(level=0, drop=True)
         .reset_index())
print (df1)
        id                date       value
0   693214 2021-01-02 07:30:00  12456677.0
1   693214 2021-01-02 07:45:00  12456677.0
2   693214 2021-01-02 08:00:00  12456677.0
3   693215 2021-01-02 08:15:00  12456665.0
4   693215 2021-01-02 08:30:00         NaN
5   693215 2021-01-02 08:45:00  12456665.0
6   693217 2021-01-03 09:00:00  12456666.0
7   693217 2021-01-03 09:15:00         NaN
8   693217 2021-01-03 09:30:00         NaN
9   693217 2021-01-03 09:45:00         NaN
10  693217 2021-01-03 10:00:00         NaN
11  693217 2021-01-03 10:15:00         NaN
12  693217 2021-01-03 10:30:00  12456666.0
13  693214 2021-12-02 07:00:00  12456677.0

Test missing values in boolean indexing:
df2 = df1[df1['value'].isna()]
print (df2)
        id                date  value
4   693215 2021-01-02 08:30:00    NaN
7   693217 2021-01-03 09:15:00    NaN
8   693217 2021-01-03 09:30:00    NaN
9   693217 2021-01-03 09:45:00    NaN
10  693217 2021-01-03 10:00:00    NaN
11  693217 2021-01-03 10:15:00    NaN


text:
Q: Getting a list of BuildFire plugin users from the Widget side I am developing a plugin that allows the user the post content that I am storing in an object in publicData. To identify the user that posted the data, I am storing the _id that is returned from buildfire.auth.getCurrentUser() in that publicData object along with the content of the post.
Is there a way I can access a list of the users of my plugin, then iterate through that to find the user with the corresponding _id? A list of the users of my plugin must exist somewhere, I just do not know how to/if I can access it.
Any help on this would be greatly appreciated!

A: I would recommend caching the user object's nonsensitive data. Remember, you have a bit more access to the logged-in user over fetching another user profile using the user id. https://github.com/BuildFire/sdk/wiki/How-to-use-Auth#buildfireauth-getuserprofileoptionscallback
Since the user profile picture URL is really an API, you don't have to worry about the user changing it since it will always return the latest. The other property I recommend you cache is the Display name (not the first name and last name) since that rarely changes as well. This way your performance wont suffer and you can do a lazy fetch for a distinct list of user ids an update them as needed. KNowing most wont need an UI updates since nothing changed


text:
Q: How to find the number of sequences of zeros and ones without "111" I have a problem:
I have a N (N <= 40). N is a length of sequence of zeroz and ones. How to find the number of sequences of zeros and ones in which there are no three "1" together?
Example:
N = 3, answer = 7
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0

A: Here's a solution using a recursive function :
(PHP code here, but it's really simple)
$seq = '';

function tree ($node, $flag, $seq)
{
if ($flag == 3) { return 0; }

if ($node == 0) { echo $seq, ' '; return 0;}

$seq1 = $seq.'1';
$seq2 = $seq.'0';

tree($node-1, $flag+1, $seq1);
tree($node-1, 0, $seq2);

}

tree(8, 0, $seq);

I use a tree to go through all the possible sequences, and a flag to check how many 1 in a row.
If there is two 1 in a row, then the flag reaches 3, and the function is stopped for this branch.
If we reach a leaf of the tree (ie. $node = 0), then the sequence is displayed, and the function ends.
Else, the function explores the two sub-trees starting from the current node.
void tree ( int node, int flag, std::string seq)
{
    std::string seq1 = seq;
    std::string seq2 = seq;

    if(flag ==3) { return; }
    if(node ==0) { printf("%s\n",seq.c_str()); return;}

    seq1 += '1';
    seq2 += '0';

    tree(node-1, flag+1, seq1);
    tree(node-1, 0, seq2);

}

A: You can write a grammar for the (non-empty) strings of this language. It's designed so that each string appears exactly once.
S := 0 | 1 | 11 | 10 | 110 | 0S | 10S | 110S

Let a_i be the total number of strings of length i in S.
First, look at the number of strings of length 1 on both sides of the grammar rule. There's a_1 in S by definition which deals with the left-hand-side.
a_1 = 2

For a_2, on the right-hand-side we immediately get two strings of length 2 (11 and 10), plus another two from the 0S rule (00 and 01). This gives us:
a_2 = 2 + a_1 = 4

Similarly, for a_3, we get:
a_3 = 1 + a_2 + a_1 = 7

(So far so good, we've got the right solution 7 for the case where the strings are length three).
For i > 3, consider the number of strings of length i on both sides.
a_i = a_{i-1} + a_{i-2} + a_{i-3}

Now we've got a recurrence we can use. A quick check for a_4...
a_4 = a_1 + a_2 + a_3 = 2 + 4 + 7 = 13.

There's 16 strings of length 4 and three containing 111: 1110, 0111, 1111. So 13 looks right!
Here's some code in Python for the general case, using this recurrence.
def strings_without_111(n):
    if n == 0: return 1
    a = [2, 4, 7]
    for _ in xrange(n - 1):
        a = [a[1], a[2], a[0] + a[1] + a[2]]
    return a[0]

A: This is a dp problem. I will explain the solution in a way so that it is easy to modify it to count the number of sequences having no sequence a0a1a2 in them(where ai is arbitrary binary value).
I will use 4 helper variables each counting the sequence up to a given length that are valid and end with 00, 01, 10, and 11 respectively. Name those c00, c01, c10, c11. It is pretty obvious that for length N = 2, those numbers are all 1:
int c00 = 1;
int c01 = 1;
int c10 = 1;
int c11 = 1;

Now assuming we have counted the sequences up to a given length k we count the sequences in the four groups for length k + 1 in the following manner:
int new_c00 = c10 + c00;
int new_c01 = c10 + c00;
int new_c10 = c01 + c11;
int new_c11 = c01;

The logic above is pretty simple - if we append a 0 to either a sequence of length k ending at 0 0 or ending at 1 0 we end up with a new sequence of length k + 1 and ending with 0 0 and so on for the other equations above.
Note that c11 is not added to the number of sequences ending with 1 1 and with length k + 1. That is because if we append 1 to a sequence ending with 1 1 we will end up with an invalid sequence( ending at 1 1 1).
Here is a complete solution for your case:
int c00 = 1;
int c01 = 1;
int c10 = 1;
int c11 = 1;
for (int i = 0; i < n - 2; ++i) {
  int new_c00 = c10 + c00;
  int new_c01 = c10 + c00;
  int new_c10 = c01 + c11;
  int new_c11 = c01;
  c00 = new_c00;
  c01 = new_c01;
  c10 = new_c10;
  c11 = new_c11;
}
// total valid sequences of length n
int result = c00 + c01 + c10 + c11;
cout << result << endl;

Also you will have to take special care for the case when N < 2, because the above solution does not handle that correctly.

A: To find a number of all possible sequences for N bits are easy. It is 2^N.
To find all sequences contains 111 a bit harder.
Assume N=3 then Count = 1
111

Assume N=4 then Count = 3
0111
1110
1111

Assume N=5 then Count = 8
11100
11101
11110
11111
01110
01111
00111
10111

If you write simple simulation program it yields 1 3 8 20 47 107 ...
Subtract 2^n - count(n) = 2 4 7 13 24 44 81 149...
Google it and it gives OEIS sequence, known as tribonacci numbers. Solved by simple recurrent equation:
a(n) = a(n - 1) + a(n - 2) + a(n - 3)


text:
Q: Derived class specific functions, inside an overridden virtual function, being called by a base class pointer I understand the principle of why you can only call base class functions when assigning a derived class to a base class pointer. From my understanding of virtual tables the reason why is because only base class virtual function pointers are put into the virtual table so only they can be called but if the base class pointer points to a derived class, when the derived class constructor is called the base class virtual function is replaced with the override in the virtual table.
However my point is: are there going to be problems if you have a non virtual member function in the derived class that is used in a derived class override of a virtual base class member function.
My theory is there shouldn't because its a question of function access not jumps within the function, by assigning the pointer to new DerivedClass, you are assigning space for all the derived class, so access to the virtual overridden function is allowed using the pointer to the virtual function kept in the v-table. All actions from there onward are as if you were just in a derived class object so it can jump to whatever function it wants.
Is this correct? Or is there an issue with the jump in the function using the base class pointer as a jump reference (like an array: *pointer + 2 for function), is that how member functions are called?
If this is (not my intention but still) no issue, could it be theoretically possible to have a virtual function that takes, say an int argument. Then a switch statement inside the derived class override of the virtual function that, depending on int passed in, calls specific derived class functions thereby working around the 'only call base class defined virtual functions' problem?
eg. (skeleton with no constructors etc. and separation of declaration/definition)
class A
{
   protected:
          virtual void AFunc() ;

} ;

class B : public A
{
   public:
          virtual void AFunc() { BSpecificFunc() ;} // doable?
   /* if thats the case why not:
          virtual void Sfunv(int temp)
           {
              switch(temp)
                   {
                     case 1 : BSpecificFunca() ; break;
                     case 2:  BSpecificFuncb() ; break;
                     etc.
                    }
            }
       */
   private:
          void BSpecificFunc() ;
          void BSpecificFunca() ;
          void BSpecificFuncb() ;
          void BSpecificFuncc() ;

} ;

int main()
{
   A *pBaseClass = new B;

   pBaseClass->AFunc(); //Will there be any issues doing this?

}

currently at design stage which is why I have kept this nice and theoretical.

A: If you call pBaseClass->AFunc() and pBaseClass is actually a B then B::AFunc() is what gets called. If pBaseClass is actually an A then A::AFunc() is what gets called. That's the whole point of polymorphism.
What B::AFunc() does is up to B, there's no reason it can't call other functions or use data within B that don't exist in A.

A: There shouldn't be an issue - the call to the non-virtual function is already resolved. Think of it this way: B::AFunc() is compiled to something like call BSpecificFunc. That can be done at compile time.
The only challenge is to get to B::AFunc(), and for that we have the virtual table. But once we're there - there are no issues, the object pointer actually points to a B object (which is valid for BSpecificFunc, and the function call to BSpecificFunction is already resolved.


text:
Q: How to return appropriate nested attribute value in a form (edit action)? I have following structure:
class Project < ActiveRecord::Base
  has_many :costs, :dependent => :destroy
  accepts_nested_attributes_for :costs, :allow_destroy => true
end

class Cost < ActiveRecord::Base
  belongs_to :project
end

Suppose there are two attributes in Cost model: cost_plan (used in new action) and cost_fact (properly used in edit). I'm tying to do something like this when editing form:
<!-- _cost_fields.erb -->

<div title="<%= value of :cost_plan %>">
  <%= f.label :cost_fact %>
  <%= f.text_field :cost_fact %>
</div>

I can return value of :cost_plan using hidden_field, but how to return it as title text?

A: Just get the object of the form helper back and retrieves it's associated objects directly:
<%= f.object.attribute %>
<%= f.object.costs.first.attribute %>


text:
Q: Inno-Setup destination folder Does anyone know how to use Inno-Setup to put a file into specified folder?
I would like to put a .xlam file into: %appdata%\Microsoft\Addins
I can't make it put anything into this folder.

A: You can also do something like this with ISPP:
[ISPP]
#define DataDir "{userappdata}\Microsoft\addins"

[Files]
Source: "C:\source\myapp\output\test.xlam"; DestDir: "{#DataDir}"; Flags: overwritereadonly ignoreversion uninsremovereadonly; Attribs: readonly

But note that it is not always a good idea to use the {userappdata} folder. I have had instances where the installer is elevated and the data files end up in the administrators user area. Thus, I install these kind of files to the {commonappdata} folder and then when my application starts, it looks to see if it needs to copy any files from {commonappdata} to {userappdata}.

A: You'll want to look at the {userappdata} and {commonappdata} constants to get the %appdata% portion of the path.
You can't use the wizard, you'll need to add the entry manually.  It'll look something like:
Source: "C:\source\myapp\output\test.xlam"; DestDir: "{userappdata}\Microsoft\addins"; Flags: ignoreversion


text:
Q: Facebook Graph API - Object Insights for any Photo returns 0 for all Metrics Using the Facebook Graph API I am able to retrieve data for a photo post - I can see the object likes and object comments which return data. So I know I have the correct ID for the photo.
However when I try to use object insights all the values returned are 0, which I know is not true via the insights dashboard on my account: https://www.facebook.com/{page name}/insights/
The query I am running is:
https://graph.facebook.com/v2.3/{page id}_{post id}/insights

Which I am doing via the API tool: https://developers.facebook.com/tools/explorer
If I try a status or a link, they return values.
Does anybody have any ideas?

A: Ok so I figured this out finally...
If you query all posts /{page_id}/posts and find the post you are after, at the very top is the following:
{
      "id": "112665855555813_473845879437807",
      "from": {
        "category":

And that is the id that you need to use and not use the object id
"type": "photo",
"status_type": "added_photos",
"object_id": "473462762809452",

Which is what I was doing. This is a different number and is the one you will get if you view the post on facebook - its the id of the photo and not the actual post.


text:
Q: Powershell - Efficient Way to Return Line Numbers from Logs I have an extremely large log file (max 1GB) which is appended to throughout the day. There are various strings within this log which I would like to search for (that I can already achieve using Select-String) however I am scanning the whole file on every sweep which is inefficient and a tad unnecessary.
Ideally I want to scan only the last 5 minutes of the log for these strings on each sweep. Unfortunately not every row of the log file contains a timestamp. I initially thought of doing a wildcard select-string for the last 5 mins timestamps combined with the strings of interest will miss some occurrences. My only other idea at the moment is to determine the line numbers of interest, $FromLineNumber (5 mins before current system time) and $ToLineNumber (the very last line number of log file) and then only Select-String between those two line number ranges.
As an example, to search between line 50 and the final line of the log. I am able to return the line number of $FromLineNumber but I'm struggling with grabbing $ToLineNumber for final row of log.
Q. How do I return only the line number of the final row of a log file?
So far I have tried returning this with Get-Content $path -tail -1 (object type linenumber) however this always returns blank values even with various switches and variations. I can only return line numbers via the Select-String cmdlet however I do not have a specific string to use that relates to the final row of the log. Am I misusing this cmdlet per its original design and if so...is there any other alternative  to return the last line number?
Continued...Once I have determined the line number range to search between would I isolate those rows using a Get-Content loop between
$FromLineNumber and $ToLineNumber first to filter down to this smaller selection and then pipe this into a Select-String or is there a more efficient way to achieve this? I suspect that looping through thousands of lines would be demanding on resources so I'm keen to know if there is a better way.

A: Here is the answer to the first question
From https://blogs.technet.microsoft.com/heyscriptingguy/2011/10/09/use-a-powershell-cmdlet-to-count-files-words-and-lines/

If I want to know how many lines are contained in the file, I use the Measure->Object cmdlet with the line switch. This command is shown here:

Get-Content C:\fso\a.txt | Measure-Object –Line


text:
Q: Unary operator '--' cannot be applied to an operand of type '@lvalue Int?' (aka '@lvalue Optional') I just updated my app's code to the latest version of Swift and I have this function:
func setupGraphDisplay() {

        //Use 7 days for graph - can use any number,
        //but labels and sample data are set up for 7 days
        //let noOfDays:Int = 7

        //1 - replace last day with today's actual data
        graphView.graphPoints[graphView.graphPoints.count-1] = counterView.counter

        //2 - indicate that the graph needs to be redrawn
        graphView.setNeedsDisplay()

        maxLabel.text = "\((graphView.graphPoints).max()!)"
        print((graphView.graphPoints).max()!)

        //3 - calculate average from graphPoints
        let average = graphView.graphPoints.reduce(0, +)
            / graphView.graphPoints.count
        averageWaterDrunk.text = "\(average)"

        //set up labels
        //day of week labels are set up in storyboard with tags
        //today is last day of the array need to go backwards

        //4 - get today's day number
        //let dateFormatter = NSDateFormatter()
        let calendar = Calendar.current
        let componentOptions:NSCalendar.Unit = .weekday
        let components = (calendar as NSCalendar).components(componentOptions,
            from: Date())
        var weekday = components.weekday

        let days = ["S", "S", "M", "T", "W", "T", "F"]

        //5 - set up the day name labels with correct day
        for i in (1...days.count).reversed() {
            if let labelView = graphView.viewWithTag(i) as? UILabel {
                if weekday == 7 {
                    weekday = 0
                }
                labelView.text = days[(weekday--)!]
                if weekday! < 0 {
                    weekday = days.count - 1
                }
            }
        }
    }

However I am getting an error message at the following line:
labelView.text = days[(weekday--)!]

Where Xcode is giving me the following error:
Unary operator '--' cannot be applied to an operand of type '@lvalue Int?' (aka '@lvalue Optional<Int>')

I tried searching online for answers but I still couldn't find anything that would help me fix this error.
I was also curious what the error message exactly means by type @lvalue Int (aka '@lvalue Optional<Int>')? I have never seen this data type before and don't know how to solve the problem accordingly.
Thanks in advance.

A: Answer is very simple. ++ and -- was removed from Swift 3. But += and -= remained
About Optional<Int> this is longer version for Int? definition. In Swift Optional defined as
public enum Optional<Wrapped> : ExpressibleByNilLiteral


text:
Q: Disable a gem's Railtie initializer Is there a way to disable a railtie that is loaded by a gem by default ?
The developers of the gem did not make it modular and once putting the gem in the Gemfile, the require will automatically load the railties this way:
require 'some_gem'

module SomeGem
  module RailtieMixin
    extend ActiveSupport::Concern

    included do
      rake_tasks do
        require 'some_gem/rake_tasks'
      end

      initializer 'some_gem.configuration' do
        config.after_initialize do
          ...
        end
      end

      initializer 'some_gem.controller_methods' do
        ...
      end
    end
  end
end

I'd like to have some control, and ideally disable only the 'some_gem.controller_methods', is it possible to do this ? without monkeypatching ? without patching the gem ?

A: This is probably not a good idea but if you must do that
you can do something like the following to find the initializer instance and filter out the initializer that you don't want before the initializer is run.
module MyModule
  class Railtie < Rails::Railtie
    config.before_configuration do
      Rails.application.initializers.find { |a| a.name == 'some_gem.configuration'}.context_class.instance.initializers.reject! { |a| a.name == 'some_gem.configuration'}
    end
  end
end

A: This doesn't exactly answer your question, but you can always use
gem 'whenever', :require => false

in your Gemfile. This way, the gem won't be loaded and the initialization code won't run until you call
require 'whenever'

See: Bundler: What does :require => false in a Gemfile mean?


text:
Q: Exposing SOAP backend as a REST API WSO2 api manager 4.1.0 using the generate API's implementation is throwing error 500 during the creation I am trying to expose a soap backend as rest using wso2 apim and during so I followed the steps :
step1
step2
the error that is shown in the log in the following :
log error
and here is the link to the wsdl file I used :
https://blackboard.mynaseej.net/webapps/bb-data-integration-lis-final-BBLEARN/services/PersonManagementServiceSyncService.wsdl
PS : the WSDL file is valid and it's already been used in my company for previous integrations.


text:
Q: Mechanics Question I do not understand A particle starts from rest and moves in a straight line with constant acceleration. In a
certain 4 seconds of its motion it travels 12 m and in the next 5 seconds it travels 30m.
The acceleration of the particle is?
The velocity of the particle at the start of the timing is?
The distance it had travelled before timing started was?
Apparently, the velocity of the particle at the start of the timing is not 0 m/s

A: Use $s=ut+\frac{1}{2}at^2$.We are told that $u=0$.
Let the timing start at time $t$ and at distance $s$.
$s=\frac{1}{2}at^2$
$s+12=\frac{1}{2}a(t+4)^2$
$s+42=\frac{1}{2}a(t+9)^2$
Solving these gives $a=\frac{2}{3}$, $t=\frac{5}{2}$ and $s=\frac{25}{12}$.
For the velocity, use $v^2=u^2+2as$.

A: Let's observe picture bellow.We can write next equations:
$x=\frac{1}{2}at_x^{2}$ ; $v_A=at_x$; $v_B=v_A+at_1$; $s_1=v_At_1+\frac{1}{2}at_1^{2}$; $s_2=v_Bt_2+\frac{1}{2}at_2^{2}$
$s_1=4at_x+8a \Rightarrow 12=4at_x+8a \Rightarrow at_x=3-2a$
$s_2=(at_x+4a)5+\frac{25}{2}a \Rightarrow 6=at_x+4a+\frac{5}{2}a \Rightarrow 12=2at_x+13a$ , Since that :
$12=2(3-2a)+13a \Rightarrow a=\frac{2}{3}\frac{m}{s^2} \Rightarrow t_x=\frac{5}{2}sec$, $ v_A=at_x \Rightarrow v_A=\frac{5}{3} \frac{m}{s}$ and $x=\frac{1}{2}at_x^{2} \Rightarrow x=\frac{25}{12} m$


text:
Q: rename (or move) folders, subfolders and files on specific path I have a function (.bat) to search and rename (or move) any folder with a specific name folder (call "data"), with all its contents intact, on a specific path (path:\ Is the specific route like c:\ or h:)
I need to simplify it and make it work.
call:test "TEST1"
call:test "TEST2"

:: funcion test
@echo off
pause
goto:eof
:test
 set test=%1
 CD /D path:\
 if exist "%test%" (goto make) else (goto end)
 :make
 MOVE /Y "%test%" data
 FOR /F %%x IN ("%test%") DO REN "%%x" data
 FOR /F "tokens=*" %%G IN ('DIR /B /AD /S "%test%"') DO MOVE /Y "%%G" data
 :end
 echo OK
 goto:eof

The TEST1 and TEST2 folders contain many files and subfolders. The problem is that i use three commands to do this work and not 100% works.
 MOVE /Y "%test%" data
 FOR /F %%x IN ("%test%") DO REN "%%x" data
 FOR /F "tokens=*" %%G IN ('DIR /B /AD /S "%test%"') DO MOVE /Y "%%G"

I need to rename the folders TEST1 and TEST2, wherever they are within the path (may be in the root or in subfolders. Both should be renamed (merged) as "data").
Example: The TEST1 and TEST2 folders have content (files and subfolders). The ".bat" search into the path to find TEST1 and when it finds renamed TEST1 with "data". Keep looking and find TEST2 and rename as "data" too without asking.
But, in the case of both folders (TEST1 and TEST2) are within the same location, both should be merged (one overrides the other). The important thing is to do it without asking.
But "MOVE /Y" does not overwrite folders (only files). I think the solution could be that instead of overwriting, rename the file or folder duplicate to avoid this failure command
Note: Previously i used Robocopy with "move" option...
SET MoveDirSource=path:\"%test%"
SET MoveDirDestination=path:\data
MKDIR "%MoveDirDestination%"
FOR %%i IN ("%MoveDirSource%\*") DO MOVE /Y "%%i" "%MoveDirDestination%\%%~nxi"
FOR /D %%i IN ("%MoveDirSource%\*") DO ROBOCOPY /MOVE /E /W:5 "%%i" "%MoveDirDestination%\%%~nxi"

But it is not viable, because robocopy, first, copy from source to destination and then removed at source. And if TEST1 or TEST2 folders have 2 or 6 GB of information, this process can take hours.
Thanks a lot

A: I would use

ROBOCOPY "%Test%" Data /MOVE /E

Robocopy is installed by default in windows and does all what you want in one pass.


text:
Q: Drupal localhost redirecting to www.localhost.com I am working on a drupal site which I checked out (svn) to my localhost.
Now the problem is that when I go to:

http://www.site.com

it all works fine, but when I go to:

http://localhost/work/site

I get redirected to

http://www.localhost.com/work/site

I have ran the install.php script and all works great. It reinstalls everything but when I go to the main site the redirect occurs.
I removed the .htaccess file, didn't do anything.
I am using windows 7 ultimate 64 (also tried on winxp pro 32) apache 2.2, php 5.2.13
Anyone know anyway to fix this?
Thanks

A: Have you checked your window's hosts file? Not sure about where it lives in Windows 7, but in XP it lives here:
C:\WINDOWS\system32\drivers\etc\hosts

Make sure there is an entry like this:
127.0.0.1       localhost

As a double-check, you may want to flush your PCs DNS cache. Go into the command line and type:
ipconfig /flushdns

A: The redirect is caused by Firefox not being able to get a good connection with the local server and then trying to "fix" the address.  You can disable the behavior in Firefox as follows:

*

*Type about:config in the address bar
and hit return.

*Find browser.fixup.alternate.enabled.

*Double click the "true" value. The line will become bold, and the
value will change to "false" from here
However that will not solve your underlying problem (local server isn't responding right), it will just get rid of really annoying behavior. There are several possible causes of this failure, the host file problem MatW suggested is a common cause.
In my case Drupal seems to be crashing Apache during certain page loads, which is hard to diagnose/fix when your browser keeps redirecting itself away from the page you need to refresh.

A: From the drupal sites/default/settings.php file:
/**
 * Base URL (optional).
 *
 * If you are experiencing issues with different site domains,
 * uncomment the Base URL statement below (remove the leading hash sign)
 * and fill in the absolute URL to your Drupal installation.
 *
 * You might also want to force users to use a given domain.
 * See the .htaccess file for more information.
 *
 * Examples:
 *   $base_url = 'http://www.example.com';
 *   $base_url = 'http://www.example.com:8888';
 *   $base_url = 'http://www.example.com/drupal';
 *   $base_url = 'https://www.example.com:8888/drupal';
 *
 * It is not allowed to have a trailing slash; Drupal will add it
 * for you.
 */
# $base_url = 'http://www.example.com';  // NO trailing slash!

Try setting $base_url = 'http://localhost/work/site';

A: I finally found the reason behind this huge problem.
It was the css and js optimization that was messing everything up.
I set those two to off and then copied the database to the localhost version of the site and all worked out great!!!


text:
Q: Can files be recovered from an encrypted linux disk, if it gets formatted to ntfs? I sent in my laptop to gateway for a LCD repair, with instructions not to format the hard drive. They saw that I had ubuntu installed and formatted it, installing windows 7. My hard drive was encrypted at the filesystem level. If possible, how do I go about restoring my files?

A: If you made a copy of the LUKS header, you can try restoring the header, unlocking the partition with the same key, and then using traditional filesystem recovery techniques.
Otherwise, nope.


text:
Q: How to broadcast Webcam Image stream to multiple devices using Opencv and Flask? I have the following code. It works well when trying to connect with one device to the server. When two devices connect, only one works the other freezes and gives the following error.
The goal is to broadcast a video stream to multiple devices. Also, is there a way to improve the FPS transmitted and reduce latency with Flask?
CODE
Camera.py
import cv2

class VideoCamera(object):
    def __init__(self):
        # Using OpenCV to capture from device 0. If you have trouble capturing
        # from a webcam, comment the line below out and use a video file
        # instead.
        self.video = cv2.VideoCapture(0)
        # If you decide to use video.mp4, you must have this file in the folder
        # as the main.py.
        # self.video = cv2.VideoCapture('video.mp4')

    def __del__(self):
        self.video.release()

    def get_frame(self):
        success, image = self.video.read()
        # We are using Motion JPEG, but OpenCV defaults to capture raw images,
        # so we must encode it into JPEG in order to correctly display the
        # video stream.
        ret, jpeg = cv2.imencode('.jpg', image)
        return jpeg.tobytes()

Main.py
import os

install_opencv = os.system("pip install flask opencv-python")
print("Install OPENCV-PYTHON: ", install_opencv)

from flask import Flask, render_template, Response
from camera import VideoCamera

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

def gen(camera):
    while True:
        frame = camera.get_frame()
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')

@app.route('/video_feed')
def video_feed():
    return Response(gen(VideoCamera()),
                    mimetype='multipart/x-mixed-replace; boundary=frame')

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)

ERROR
Traceback (most recent call last):
cv2.error: OpenCV(3.4.3) C:\projects\opencv-python\opencv\modules\imgcodecs\src\grfmt_base.cpp:145: error: (-10:Unknown error code -10) Raw image encoder error: Empty JPEG image (DNL not supported) in function 'cv::BaseImageEncoder::throwOnEror'
127.0.0.1 - - [01/Nov/2018 16:16:21] "GET /video_feed HTTP/1.1" 200

A: I also did this way and could not access through and two devices.
There is a project at github https://github.com/miguelgrinberg/flask-video-streaming or you can see a better explanation on the developer's site https://blog.miguelgrinberg.com/post/flask-video-streaming-revisited #commentform
With this code I was able to access from multiple devices, but only allows a camera to be displayed. I am working so that it is possible to view 2 or more cameras, as if it were a DVR.


text:
Q: How can I make my layout load time more efficient? I currently have a layout with 4 tabs, the first tab has the home screen of the app, loads 4 imageviews for the icons of other activities.  The second tab loads a webview (very basic one) as does the third tab.  The final tab loads a map.  The app loads very slow, takes about 11 seconds, and when I debug in Eclipse almost the entire time is spent on setContentView, but I can't figure out what in my layout is taking so long to load.
Here is my layout code:
<?xml version="1.0" encoding="utf-8"?>

<TabHost
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tabhost" android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        >
        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            >
            <RelativeLayout
                android:id="@+id/tab1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/background"
                >
                <ImageView
                    android:id="@+id/HomeButtonEvents"
                    android:src="@drawable/eventsicon"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentBottom="true"
                    android:layout_alignParentLeft="true"
                    android:paddingBottom="95dp"
                    android:clickable="true"
                    />
                <ImageView
                    android:id="@+id/CancelledClasses"
                    android:src="@drawable/cancelledicon"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentBottom="true"
                    android:layout_alignParentRight="true"
                    />
                <ImageView
                    android:id="@+id/CourseSchedule"
                    android:src="@drawable/coursesicon"
                    android:layout_width="141dp"
                    android:layout_height="139dp"
                    android:layout_alignParentTop="true"
                    android:layout_alignParentLeft="true"
                    />
                <ImageView
                    android:id="@+id/POTD"
                    android:src="@drawable/potdicon"
                    android:layout_width="294dp"
                    android:layout_height="247dp"
                    android:paddingTop="45dp"
                    android:paddingRight="1dp"
                    android:layout_alignParentTop="true"
                    android:layout_alignParentRight="true"
                    android:layout_toRightOf="@id/CourseSchedule"
                    />
<!--            <ImageView -->
<!--                android:id="@+id/potdview"-->
<!--                android:layout_width="wrap_content"-->
<!--                android:layout_height="wrap_content"-->
<!--                android:paddingTop="0dp" -->
<!--                android:paddingRight="1dp"-->
<!--                android:paddingBottom="150dp" -->
<!--                android:layout_alignParentTop="true"-->
<!--                android:layout_alignParentRight="true" -->
<!--                android:layout_toRightOf="@id/CourseSchedule" -->
<!--                /> -->
            </RelativeLayout>

            <WebView
                android:id="@+id/tab2"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                />

        </FrameLayout>

        <TabWidget
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="0"
            />

    </LinearLayout>

</TabHost>

Any ideas/suggestions?

A: My suggestions would be to split the 4 tabs into separate activities unless you absolutely had to have them as tabs.  If you wish to have them as tabs, then perhaps load the tab content dynamically when the tab is focused.

A: It looks to me like you have too many Layout objects. I believe you should be able to do everything with just a TabHost and the RelativeLayout.


text:
Q: TensorFlow: Initializing variables multiple times I am a bit confused by how the following code segment runs.
import tensorflow as tf

x = tf.Variable(0)
init_op = tf.initialize_all_variables()
modify_op = x.assign(5)

with tf.Session() as sess:
    sess.run(init_op)
    print(sess.run(x))
    x += 3
    print(sess.run(x))
    sess.run(init_op) # Trying to initialize x once again to 0
    print(sess.run(x)) # Gives out 3, which leaves me confused.
    print(sess.run(modify_op))
    print(sess.run(x)) # Gives out 8, even more confusing

This is the output:
0
3
3
5
8
Is it that the line x += 3 is not part of the default graph? Or something else is going on? Some help will be appreciated, thanks!

A: Your x variable is being changed by
x += 3

but not in a way you might expect. The tensorflow library code over-rides +, so that you are effectively swapping the contents x for a new TF tensor (the old one will still be in the graph, just x now points to a new one). Write it out like this:
x = tf.Variable(0) + 3

and it is clearer what is going on. Also, insert some print statements . . .
x = tf.Variable(0)
print(x)
# <tensorflow.python.ops.variables.Variable object at 0x1018f5d68>

x += 3
print(x)
# Tensor("add:0", shape=(), dtype=int32)

If the contents of x are important to you, then avoid re-assigning to x if you want to track/display x using the variable name later. Alternatively, you can always name the tensor and fetch it direct from the graph if you don't have a convenient Python variable pointing at it. What's important is getting used to the separation between TF variables and Python variables.
Actually seeing the TF variable being assigned and re-set as you are trying to do, needs to use a TF assignment operator:
import tensorflow as tf

x = tf.Variable( 0 )

with tf.Session() as session:
    session.run( tf.initialize_all_variables() )
    print( x.eval() )

    session.run( x.assign( x + 3 ) )
    print( x.eval() )

    session.run( tf.initialize_all_variables() )
    print( x.eval() )

This outputs:
0
3
0

as you were expecting.


text:
Q: Nutch selenium firefox issue: Unable to connect to host 127.0.0.1 on port 7055 after 45000 ms I'm trying to set up a headless crawler using Nutch Selenium and Firefox.
I do have xvfb running and a display set. If I use the conf/nutch-site.xml with changes only to use protocol-selenium and if the seed list has more than 1 url, the fetch errors out saying either one of the following error:
org.openqa.selenium.firefox.NotConnectedException: Unable to connect to host 127.0.0.1 on port 7055 after 45000 ms.

java.lang.RuntimeException: org.openqa.selenium.WebDriverException: Failed to connect to binary FirefoxBinary(/usr/bin/firefox) on port 7055

java.lang.RuntimeException: org.openqa.selenium.remote.UnreachableBrowserException: Error communicating with the remote browser. It may have died.

firefox selenium nutch GLib-CRITICAL **: g_slice_set_config: assertion `sys_page_size == 0' failed

If however there is only 1 url in the seed list, the fetcher is successful.
Now, if I change in conf/nutch-site.xml - fetcher.threads.per.queue to 1, and there are multiple urls in the seed list, the fetcher runs for a couple of them, but fails with any of the above errors for some.
The behaviour seems to be random, though I'm pretty sure there is something I'm not seeing right.
I'm on Amazon AMI Linux, Nutch 1.13, which has Selenium 2.48.2 and Firefox 31.4.0
Tried with FF (40.0.0, 35.0 but still same situation)
I was able to see the questions asked all over, but did not find a reliable answer. I'd appreciate any help or suggestion.
Thanks!


text:
Q: EntityManagerFactory must not be null after migrate to hibernate 5.2.6 in spring boot I using Hibernate in my Spring boot App after migrate from Hibernate 5.0.11 to 5.2.6.Final .i get EntityManagerFactory must not be null exception
this is my codes
My Hibernate Configuration
@Configuration
@EnableTransactionManagement
public class DatabaseConfiguration {

    @Bean
    public HibernateJpaSessionFactoryBean sessionFactory() {
        return new HibernateJpaSessionFactoryBean();
    }

    @Bean
    public HibernateTransactionManager transactionManager(@Autowired SessionFactory sessionFactory) {
        HibernateTransactionManager transactionManager = new HibernateTransactionManager();
        transactionManager.setSessionFactory(sessionFactory);
        return transactionManager;
    }

}

My Repository Class
@Repository
public class GenericRepository{

    @Autowired
    private SessionFactory sessionFactory;

}

Exception is this
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalStateException: EntityManagerFactory must not be null
    at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:175)
    at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.getObjectFromFactoryBean(FactoryBeanRegistrySupport.java:127)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getObjectForBeanInstance(AbstractBeanFactory.java:1634)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:254)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:220)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveNamedBean(DefaultListableBeanFactory.java:1018)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:345)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:340)
    at org.springframework.orm.jpa.EntityManagerFactoryUtils.findEntityManagerFactory(EntityManagerFactoryUtils.java:143)
    at org.springframework.orm.jpa.EntityManagerFactoryAccessor.setBeanFactory(EntityManagerFactoryAccessor.java:137)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeAwareMethods(AbstractAutowireCapableBeanFactory.java:1647)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1615)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
    ... 50 common frames omitted
Caused by: java.lang.IllegalStateException: **EntityManagerFactory must not be null**
    at org.springframework.util.Assert.state(Assert.java:392)
    at org.springframework.orm.jpa.vendor.HibernateJpaSessionFactoryBean.getObject(HibernateJpaSessionFactoryBean.java:46)
    at org.springframework.orm.jpa.vendor.HibernateJpaSessionFactoryBean.getObject(HibernateJpaSessionFactoryBean.java:41)
    at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:168)
    ... 71 common frames omitted

A: I changed my configuration to this  for create sessionfactory
    @Inject
    public DataSource dataSource;

    @Inject
    public JpaProperties prop;

    @Bean("sessionFactory")
    @Primary
    public LocalSessionFactoryBean getSessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setPackagesToScan(new String[] { "org.roshan" });
        sessionFactory.setAnnotatedPackages(new String[] { "org.roshan" });
        sessionFactory.setHibernateProperties(getHibernateProperties());
        return sessionFactory;
    }

    private  Properties getHibernateProperties() {
        Properties p = new Properties();
        p.putAll(prop.getProperties());
        p.put(AvailableSettings.HBM2DDL_AUTO, prop.getHibernate().getDdlAuto());
        return p;
    }

A: Just remove @Autowired from transactionManager bean configuration, it should be like this:
 @Bean
    public HibernateJpaSessionFactoryBean sessionFactory() {
        return new HibernateJpaSessionFactoryBean();
    }

    @Bean
    public HibernateTransactionManager transactionManager() {
        HibernateTransactionManager transactionManager = new HibernateTransactionManager();
        transactionManager.setSessionFactory(sessionFactory());
        return transactionManager;
    }


text:
Q: What are the arclengths of the curves described by the intersection of two cylinders (different sizes): A) tangential cylinders B) angled cylinders I'm assuming a numerical integration is required to determine the arclengths, and if someone knows the integrals that describes the arclength, that would be appreciated.
With the help of stack exchange, I was able to calculate a similar problem: the arclength of a curve of two orthogonal intersecting cylinders (a steinmetz curve) by using the trapezoidal method for integration:  https://scicomp.stackexchange.com/questions/36913/calculate-the-arc-length-of-a-steinmetz-curve-numerically/36914?noredirect=1#comment72347_36914
Here are two pictures describing the two cases I'm interested in:
Angled Cylinder
Tangential cylinders


text:
Q: how to remain the form open when x button(in the upper right most) is clicked? I'm having a problem with my form in VB.net. I want to remain my form open when I clicked no in the decision box.
this is my code:
Private Sub Form1_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
        If (MsgBox("Do you want to quit now?", MsgBoxStyle.YesNo).ToString = "Yes") Then
            Dim login As New login
            login.Show()
        Else
            'remain my form
        End If
    End Sub

Please help me. thankyou.

A: You should set the Cancel property of the e parameter to True.
e.Cancel = True

For more info, check the Form.FormClosing (or Form.Closing) event.


text:
Q: Ionic 3 - Dropdown Select I am trying to recreate the below in Ionic 3 (see link for GIF).
I have no idea what I am doing.
I have tried to use the ionic select options but it is not giving me the desired effect.
Can someone please help me with this?
Dropdown Select:

More Info:
Currently I am at this point:
Current Progress
As you can see, very far off.
My code is:
<ion-grid>
    <ion-row>
        <ion-col col-3>
            <ion-item>
                <ion-label stacked>Filter</ion-label>
                <ion-select interface="popover">
                    <ion-option value="10">10</ion-option>
                    <ion-option value="20">20</ion-option>
                </ion-select>
            </ion-item>
        </ion-col>
        <ion-col col-3>
            <ion-item>
                <ion-label>Due Date</ion-label>
                <ion-select interface="popover">
                    <ion-option value="10">10</ion-option>
                    <ion-option value="20">20</ion-option>
                </ion-select>
            </ion-item>
        </ion-col>
        <ion-col col-3>
            <ion-item>
                <ion-label>Descending</ion-label>
                <ion-select interface="popover">
                    <ion-option value="10">10</ion-option>
                    <ion-option value="20">20</ion-option>
                </ion-select>
            </ion-item>
        </ion-col>
    </ion-row>
</ion-grid>

A: Below is the html code from drop down..it is not exactly as you want...but i hope u'll get some idea :
Declare variable in .ts file :
selectedLeave : string = '';
add below code in html file :
<ion-item class="item-leave-height">
    <ion-label>SELECT LEAVE</ion-label>
    <ion-select [(ngModel)]="selectedLeave">
        <ion-option value="CASUAL LEAVE">Casual Leave</ion-option>
        <ion-option value="COMP OFF">Comp Off</ion-option>
        <ion-option value="EARNED LEAVE">Earned Leave</ion-option>
        <ion-option value="SICK LEAVE">Sick Leave</ion-option>
    </ion-select>
</ion-item>

A: I suggest using the Popover Controller.
Generate a new Page with your ion-selectand call it like this:
 presentPopover(myEvent) {
    let popover = this.popoverCtrl.create("YourPopoverPage");
    popover.present({
      ev: myEvent
    });
  }

This should be in your html with the Selects:
<div (click)="presentPopover($event)" style="display:flex; float:right;">
          <ion-label style="text-align:right;">Klick</ion-label>
          <ion-icon name="md-arrow-dropdown" id="icon_lang"></ion-icon>
    </div>

A: Even though you are using ionic doesn't mean you can't use the normal html select component.

<select name="carlist" form="carform">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>

A: <ion-list>
  <ion-item>
     <ion-label>Color</ion-label>
            <ion-select>
                <ion-option  value="1">1</ion-option>
                <ion-option  value="1">2</ion-option>
                <ion-option  value="1">3</ion-option>
                <ion-option  value="1">4</ion-option>
            </ion-select>
    </ion-item>
</ion-list>


text:
Q: ACF repeater subfield for meta query This is my meta query.. (var_dump mode)
array(2) {
    ["relation"]=> string(3) "AND"
    [0]=> array(2) {
        ["relation"]=> string(2) "OR"
        [0]=> array(3) {
            ["key"]=> string(17) "status_$_bedrooms"
            ["value"]=> string(1) "1"
            ["compare"]=> string(1) "="
        }
    }
}

I set more nested meta queries in case that other fields has any value..
This is a case of a repeater subfield I added the following filter but with no luck.. I don't know if has to do with my query's structure
function my_posts_where( $where ) {
    $where = str_replace("meta_key = 'status_$", "meta_key LIKE 'status_%", $where);
    return $where;
}

add_filter('posts_where', 'my_posts_where');

Any advice? Thanks!

A: I solved the problem..
the value is string.. I had to convert it to integer with intval() to compare number with number


text:
Q: Getting Web Element Using VBA I can't seem to return the web element using this function. Any help would be appreciated.
Function scrape2(id As String)

Set objhttp1 = New WinHttp.WinHttpRequest
Dim doc1 As MSHTML.HTMLDocument
objhttp1.Open "GET", "https://www.axie.tech/axie-pricing/" & id, True
objhttp1.send

Set doc1 = New MSHTML.HTMLDocument
doc1.body.innerHTML = objhttp1.responseText

Set Result = doc1.FindElementByClass("axie-pricing_decodedGenesCapsule__m9R-C")

scrape2 = doc1.Text

End Function

Function Input: 373595
Expected Result:
D
R1
R2
Telescope
Telescope
Sleepless
Sakura
Pink Cheek
Curly
Anemone
Sponge
Blue Moon
Piranha
Piranha
Lam
Lagging
Scaly Spear
Teal Shell
Koi
Nimo
Snake Jar

A: doc1 is an MSHTML.HTMLDocument instance which does not have a FindElementByClass method. Nor a .text property of any nodes within the DOM. The method you are referencing is one from Selenium Type class where you have an instance of WebDriver.
Then there a variety of other issues. What you see on the page is dynamically rendered, and the data you want comes from XHR POST requests using graphql queries that return JSON. You would need to formulate those requests and use a JSON parser, such as in my example below, on the results.
Also, use Option Explicit, declare all your variables, use meaningful names and make the request synchronous by passing False in the .Open  line.
parts is a collection of dictionaries you need to For Each over, then For Each Key, where Key is variant, over the .Keys of each dictionary.
Select the items you want. The key abilities returns a collection, so needs to be handled differently if used.
TODO:

*

*R1 and R2 you need to use the parent ids and extract from requests for those ids info. The code below is for the child id and returns column D of your desired results.

*data requests a lot more info that it seems you need so you could remove a lot of the parameters within it.

JSON library:
I use JsonConverter.bas. Download raw code from here and add to standard module called JsonConverter . Remove the top Attribute .... line from the copied code and Option Explicit if already specified.
You then need to go:
VBE > Tools > References > Add references to:
Microsoft Scripting Runtime
Microsoft HTML Object Library
Microsoft WinHTTP Services, version 5.1 Library (or your version).

In VBA for JSON the [] denotes a collection and the {} represents a dictionary.

VBA:
Option Explicit

Public Sub PrintGetAxieDetail()

    Dim response As Object

    Set response = GetAxieGeneDetail("5016162")

    Debug.Print JsonConverter.ConvertToJson(response)

End Sub

Public Function GetAxieGeneDetail(ByVal id As String) As Object

    Dim http As WinHttp.WinHttpRequest
    Dim doc1 As MSHTML.HTMLDocument
    Dim data As String

    Set http = New WinHttp.WinHttpRequest
    Set doc1 = New MSHTML.HTMLDocument

    With http

        .Open "POST", "https://axieinfinity.com/graphql-server-v2/graphql", False

        .setRequestHeader "content-type", "application/json"
        .setRequestHeader "user-agent", "Mozilla/5.0"
        .setRequestHeader "referer", "https://www.axie.tech/"
        .setRequestHeader "accept-language", "en-GB,en-US;q=0.9,en;q=0.8"

        data = "{""operationName"":""GetAxieDetail"",""variables"":{""axieId"":""" & id & """},""query"":""query GetAxieDetail($axieId: ID!)" & _
                "{\n  axie(axieId: $axieId) {\n    ...AxieDetail\n    __typename\n  }\n}\n\nfragment AxieDetail on Axie {\n  id\n  image" & _
                "\n  class\n  chain\n  name\n  genes\n  owner\n  birthDate\n  bodyShape\n  class\n  sireId\n  sireClass\n  matronId\n  matronClass" & _
                "\n  stage\n  title\n  breedCount\n  level\n  figure {\n    atlas\n    model\n    image\n    __typename\n  }" & _
                "\n  parts {\n    ...AxiePart\n    __typename\n  }\n  stats {\n    ...AxieStats\n    __typename\n  }" & _
                "\n  auction {\n    ...AxieAuction\n    __typename\n  }\n  ownerProfile {\n    name\n    __typename\n  }" & _
                "\n  battleInfo {\n    ...AxieBattleInfo\n    __typename\n  }" & _
                "\n  children {\n    id\n    name\n    class\n    image\n    title\n    stage\n    __typename\n  }\n  __typename" & _
                "\n}\n\nfragment AxieBattleInfo on AxieBattleInfo {\n  banned\n  banUntil\n  level\n  __typename" & _
                "\n}\n\nfragment AxiePart on AxiePart {\n  id\n  name\n  class\n  type\n  specialGenes\n  stage\n  abilities" & _
                "{\n    ...AxieCardAbility\n    __typename\n  }\n  __typename\n}\n\nfragment AxieCardAbility on AxieCardAbility" & _
                "{\n  id\n  name\n  attack\n  defense\n  energy\n  description\n  backgroundUrl\n  effectIconUrl\n  __typename\n}" & _
                "\n\nfragment AxieStats on AxieStats {\n  hp\n  speed\n  skill\n  morale\n  __typename\n}\n\nfragment AxieAuction on Auction" & _
                "{\n  startingPrice\n  endingPrice\n  startingTimestamp\n  endingTimestamp\n  duration\n  timeLeft\n  currentPrice" & _
                "\n  currentPriceUSD\n  suggestedPrice\n  seller\n  listingIndex\n  state\n  __typename\n}\n""}"

        .send data

        Dim axieDetail As Object, geneResults As Object

        Set axieDetail = JsonConverter.ParseJson(.responseText)
        Set geneResults = axieDetail("data")("axie")("parts") 'this returns a collection to For Each over
        Set GetAxieGeneDetail = geneResults

    End With

End Function

Sample of JSON:


text:
Q: Autofilter data in two columns I have data in two columns. One column is states and the other is for dates.
I want to filter on one state and three months.
When I apply this code all of the data dissapears. It seems as though everything in both of these filters deselect.
months is an ArrayList.
Sheets("The Data (2)").Select
ActiveSheet.Range("$A:$T").AutoFilter Field:=6, Criteria1:=stateName, Operator:=xlFilterValues
Set months = getMonths(Year, Quarter)
ActiveSheet.Range("$A:$T").AutoFilter Field:=17, Criteria1:=Array(months.Item(0), months.Item(1), months.Item(2)), Operator:=xlFilterValues
Range("$A$1:$T$1").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Windows("State Rate Planning Template.xlsm").Activate
Sheets(3).Select
Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Range("A1").Select

A: Does this meet your needs. There was a little guess work within the question so if not, feel free to clarify below.
Sub untested()
Dim wb As Workbook: Set wb = Workbook(ThisWorkbook.Name)
Dim ws As Worksheet: Set ws = wb.Worksheets("The data (2)")
Dim months As Integer

Set months = getMonths(Year, Quarter)

With ws
  .Range("$A:$T").AutoFilter Field:=6, Criteria1:=stateName, Operator:=xlFilterValues
  .Range("$A:$T").AutoFilter Field:=17, Criteria1:=Array(months.Item(0), months.Item(1), months.Item(2)), Operator:=xlFilterValues
  .Range(Selection, Selection.End(xlDown)).Copy Destination:=Workbooks("State Rate Planning Template.xlsm").Worksheets(3).Range("A1")
End With

Workbooks("State Rate Planning Template.xlsm").Worksheets(3).Range("A1").Select

End Sub


text:
Q: How to convert LPCTSTR to char * No matter what i do i just can't get it to work.
ALL i want to do is take a LPCTSTR and a char* and concatenate them into a char*
myfunction(LPCTSTR pass, LPCTSTR fail, LPCTSTR done, char* table,char* db_file, int s_time){
    char query2[200];
    strcpy(query2,"SELECT value FROM ");
    strcat(query2,table);
    strcat(query2," WHERE value = '");
    strcat(query2,(char*)pass);
    strcat(query2,"' OR value = '");
    strcat(query2,(char*)fail);
    strcat(query2,"'");
}

For the love of all that is holy why is this so hard.
ALSO NO, i can not just USE a string, cstring, stringstream or any other intermediate container. For some reason every time i try to use these i get a memory allocation error.


text:
Q: Implement 2FA both server and client on my website I'm working on a website using PHP, jQuery, CSS, Bootstrap (standard suite) and i'd like to implement standard Google 2FA.
Now, I know how 2FA usually works - client gets secret code, he enters that into his mobile app and every X seconds he gets correct key to authenticate on the server. In my case, beside usual server-side "entered code checking", I would also like to implement, on my website, "client part" of the system as well!
I short, i want my website to show correct "XXX XXX" number that my website would accept. I know it's counter-intuitive but i need to have on my website both 2FA "entered code checker" and also to show correct number that would be accepted by my server.
Is that possible? I found some examples how to implement server-side part of the story (this url) but how can my webpage pull correct code from Google using provided secret?
EDIT: Is Google 2FA safe to be used as Random Number Generator? My idea is to use such system as "user-verifiable RNG"


text:
Q: React js tsx parsing error: Missing semicolon I have the following script (see below), when I try to run it I get the following errors:

src/translatorLanguage.tsx
  Line 114:35:  Parsing error: Missing semicolon.

  112 |
  113 |       try {
> 114 |         length = /^\d+/.exec(json)![0]
      |                                   ^
  115 |
  116 |         json = JSON.parse(
  117 |           json.slice(length.length, parseInt(length, 10) + length.length),

This happens locally, when I try on my pc.
On codesandbox, this error doesn't give it.
Link: codesandbox
App.tsx
import React, { useEffect, useCallback } from "react";
import { doubleTranslate } from "./translatorLanguage";

export default function App() {
  const fetchData = useCallback(async () => {
    const translations = await doubleTranslate("Hi, my name is");
    console.log(translations);
  }, []);

  useEffect(() => {
    fetchData();
  }, []);

  return (

Hi!

  );
}

translatorLanguage.tsx
async function translate(
  text: string,
  opts?: {from?: string | boolean; to?: string | boolean; tld?: string},
) {
  try {
    var result = {
      text: '',
      pronunciation: '',
      from: {
        language: {
          didYouMean: false,
          iso: '',
        },
        text: {
          autoCorrected: false,
          value: '',
          didYouMean: false,
        },
      },
      raw: '',
    }

    opts = opts || {}
    // var e = undefined as {message: string; code: number} | undefined
    // var languages = new translatorLanguage()
    // ;[opts.from, opts.to].forEach(function (lang) {
    //   if (lang && !languages.isSupported(lang)) {
    //     e = {
    //       message: "The language '" + lang + "' is not supported",
    //       code: 400,
    //     }
    //   }
    // })
    // if (e) {
    //   return undefined
    // }
    const extract = (key: string, res: string) => {
      var re = new RegExp(`"${key}":".*?"`)
      var result = re.exec(res)
      if (result !== null) {
        return result[0].replace(`"${key}":"`, '').slice(0, -1)
      }
      return ''
    }

    const objToQueryString = (obj: any) => {
      const keyValuePairs = []
      for (const key in obj) {
        keyValuePairs.push(key + '=' + obj[key])
      }
      return keyValuePairs.join('&')
    }

    opts.from = opts.from || 'auto'
    opts.to = opts.to || 'en'
    opts.tld = opts.tld || 'com'

    // opts.from = languages.getCode(opts.from.toString())
    // opts.to = languages.getCode(opts.to.toString())

    var url = 'https://translate.google.' + opts.tld
    var response = await fetch(url)
    var txt = await response.text()

    var data = {
      rpcids: 'MkEWBc',
      'f.sid': extract('FdrFJe', txt),
      bl: extract('cfb2h', txt),
      hl: 'en-US',
      'soc-app': 1,
      'soc-platform': 1,
      'soc-device': 1,
      _reqid: Math.floor(1000 + Math.random() * 9000),
      rt: 'c',
    }

    console.log("body", opts)

    url =
      url +
      '/_/TranslateWebserverUi/data/batchexecute?' +
      objToQueryString(data)
    var body =
      'f.req=' +
      encodeURIComponent(
        JSON.stringify([
          [
            [
              'MkEWBc',
              JSON.stringify([[text, opts.from, opts.to, true], [null]]),
              null,
              'generic',
            ],
          ],
        ]),
      ) +
      '&'
    var res = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
      },
      body: body,
    })
    if (res) {
      console.log("--", res)
      var ttx = await res.text()
      var json = ttx.slice(6)
      var length = ''

      try {
        length = /^\d+/.exec(json)![0]

        json = JSON.parse(
          json.slice(length.length, parseInt(length, 10) + length.length),
        )

        json = JSON.parse(json[0][2])

        result.raw = json
      } catch (e) {
        return result
      }
      if (json[1][0][0][5] === undefined) {
        // translation not found, could be a hyperlink?
        result.text = json[1][0][0][0]
      } else {
        ;(json[1][0][0][5] as any).forEach(function (obj: any) {
          if (obj[0]) {
            result.text += obj[0]
          }
        })
      }
      result.pronunciation = json[1][0][0][1]

      // From language
      if (json[0] && json[0][1] && json[0][1][1]) {
        result.from.language.didYouMean = true
        result.from.language.iso = json[0][1][1][0]
      } else if (json[1][3] === 'auto') {
        result.from.language.iso = json[2]
      } else {
        result.from.language.iso = json[1][3]
      }

      // Did you mean & autocorrect
      if (json[0] && json[0][1] && json[0][1][0]) {
        var str = json[0][1][0][0][1]

        str = str.replace(/()?/g, '[')
        str = str.replace(/(<\/i>)?<\/b>/g, ']')

        result.from.text.value = str

        // @ts-ignore
        if (json[0][1][0][2] === 1) {
          result.from.text.autoCorrected = true
        } else {
          result.from.text.didYouMean = true
        }
      }

      return result
    }
  } catch (error) {
    console.log(error)
  }

  return undefined
}

export async function doubleTranslate(str: string) {
  const results = await Promise.all([
    translate(str, {to: 'en', from: 'it'}),
    translate(str, {to: 'it', from: 'en'}),
  ])

  return {
    en: results[0]?.text,
    it: results[1]?.text,
  }
}


text:
Q: Documenting Pythons @property "attributes" with docstrings I gather that docstrings are more of a personal preference than anything, but I wanted to get the opinion of some people smarter than I ...
Is this a legitimate way to document the get/set nature pythons @property descriptor attributes?
class Handle(rgm.RigModule):
    '''
    Handle nodes are intended to be keyable transforms, made viewable by shape nodes connected as children

    @Properties:

        parent:
            Transform: Returns Transform instance if parent exists, otherwise None
        parent.setter:
            (str): Sets parent transform. (Accepts string name of transform, or any instance of the Transform class)

        shape:
            str: returns string representation of current shape
        shape.setter:
            (str): sets current shape using string representation provided.  If string key does not exist in library, shape will be set to None

        shapeDraw:
            dict: returns dictionary of shape data
        shapeDraw.setter:
            (dict): sets current shapes using data

        shapeColor:
            int: returns integer representation of current shape color
        shapeColor.setter:
            (int): sets current shape color using integer provided.

        shapeColor:
            int: returns integer representation of current shape color
        shapeColor.setter:
            (int): sets current shape color using integer provided.

        shapeTranslate:
            list: returns a 3list of the shape nodes relative offset translation
        shapeTranslate.setter:
            (list): sets relative offset translation of the shape nodes

        shapeRotate:
            list: returns a 3list of the shape nodes relative offset rotation
        shapeRotate.setter:
            (list): sets relative offset rotation of the shape nodes

        shapeScale:
            list: returns a 3list of the shape nodes relative offset scale
        shapeScale.setter:
            (list): sets relative offset scale of the shape nodes

        shapeMatrix:
            list: returns a 8list of the shape nodes relative offset matrix
        shapeMatrix.setter:
            (list): sets relative offset matrix of the shape nodes

A: Docstring format depend on what IDE or automatic document generation tools you are using. I can give an example for PyCharm IDE because I use it always in my work.
If you are using PyCharm the docstring is a powerful way to enhance IDE analyzer results. You can read a lot about how write "right" docstring for this IDE here. Below some examples:
class Character(object):
    pass

class Item(object):

    def __init__(self, owner=None):
        """
        :type owner: Character or None
        """
        self.__owner = owner

    @property
    def owner(self):
        """:rtype: Animal"""
        return self.__owner

    @owner.setter
    def owner(self, value):
        """:type value: Character"""
        self.__owner = value

class ArmorItem(Item):
    def __init__(self, defence, owner=None):
        """
        :type defence: int
        :type owner: Character or None
        """
        super(ArmorItem, self).__init__(owner)
        self.__defence = defence

    @property
    def defence(self):
        """:rtype: int"""
        return self.__defence

class Shield(ArmorItem):

    def block(self, damage):
        """
        :param int damage: The damage that can hero get
        :rtype: bool
        """
        if self.defence > damage:
            return True
        return False

class Helm(ArmorItem):

    def save(self, damage):
        """
        :param int damage: The damage that can hero get
        :rtype: bool
        """
        if self.defence > damage:
            return True
        return False

class Sword(Item):

    def __init__(self, damage, owner=None):
        """
        :type damage: int
        :type owner: Character or None
        """
        super(Sword, self).__init__(owner)
        self.__damage = damage

class Hero(Character):

    def __init__(self, name, weapon, armors):
        """
        :param str name: Hero name
        :param weapon weapon: Hero weapon
        :param list of ArmorItem armors: The armor item that have hero
        """
        super(Hero, self).__init__()

        self.__name = name
        self.__weapon = weapon

        self.__armors = armors
        for armor in self.__armors:
            armor.owner = self

    @property
    def name(self):
        """:rtype: str"""
        return self.__name

    @property
    def weapon(self):
        """:rtype: Sword"""
        return self.__weapon

    @property
    def armors(self):
        """:rtype: list of ArmorItem"""
        return self.__armors

def main():
    """
    Here method documentation can be placed.
    There is a test function to show analyzer facilities when a good docstring specified.

    Of course where I wrote "error" it mean that not Python exception will be thrown.
    In this place analyzer (e.g. PyCharm) show that it's something wrong.
    """
    weapon_bad1 = Sword(34.2)  # Error because damage is not int
    weapon_bad2 = Sword(20, weapon_bad1)  # Error because owner is not appropriate class

    weapon = Sword(10)  # Ok
    helm = Helm(20)  # Ok
    shield = Shield(30)  # Ok

    # Specify that all_items it not list but it list of Item (any)
    all_items = [weapon, helm, shield]
    """:type: list of Item"""

    hero_bad = Hero("bad", weapon, all_items)  # Again error here because all_items is not ArmorItem list
    hero_good = Hero("good", weapon, [helm, shield])

    # "Cast type" to notify analyzer that we get not ArmorItem but we get concrete ArmorItem
    some_armor = hero_good.armors[0]
    """:type: Helm"""

    some_armor.save(10)  # Ok, Helm class has save method
    some_armor.block(10)  # Error, Helm class has not block method

if __name__ == "__main__":
    main()

And what you can see in IDE if right docstrings specified in each methods:

Note PyCharm IDE analyzer can help very much when docstrings specified (extended list of docstring format you can find in link at the answer beginning).


text:
Q: Fit rectangle of given aspect ratio around a set of points Given a set of points in 2D space, how would I find a smallest (rotated) rectangle of a given aspect ratio that encloses the points?
I found several questions about fitting arbitrary rectangles (by looking at the angle of the edges of the convex hull), but that approach does not seem to carry over easily.


text:
Q: Twig: How can I manually escape inside a custom function? I wrote my own Twig function that outputs HTML, so I have is_safe set to html so that Twig knows not to escape the output my function.
However, my function takes arguments. One of the arguments is placed in the output directly. I want to escape this before outputting it. So it seems I just need to be able to manually escape the option value before outputting it.
I can't find how to do this. Anyone know?

A: The trick is to store the twig enviroment which in turn is passed to twig_escape_filter
class TournExtension extends \Twig_Extension
{
    protected $env;

    public function initRuntime(\Twig_Environment $env)
    {
        parent::initRuntime($env);
        $this->env = $env;
    }
    protected function escape($string)
    {
        return twig_escape_filter($this->env,$string);
    }