text:
Q: Displaying NSImage beyond limits of view I'm rather new to AppKit programming and OS X programming in general so forgive me if this is a n00b question.  I would like to make a windowless app which does nothing but take an image and animate it across the user's screen.  If I bound myself to the window limits of my app this is easy to accomplish.  How to I animate things if I want to go beyond my window/view limits?

A: You can't literally draw outside your window, but you can make your window borderless, transparent, and cover the whole screen or screens.


text:
Q: What language C++, Python, or Java is most supported in Precise Pangolin for game development? I've studied game programming and design in Windows using DirectX, and a bit using Python and PyGame.
I would like to start developing some games for Ubuntu. Now I would like to build a game called Hnefatafl which is mathematically complex but graphically fairly simple (2D board game). However, I'll need to create some simpler ones building up to it.
Anyway, which of the three languages C++, Python, or Java is most supported under Ubuntu for this type of programming operation?  Also, which libraries should I be studying using for such endeavors - OpenGL, the venerable Allegro, or others I'm not aware of yet?

A: Python and C++ are the Ubuntu "default" languages, both are more used than java for native development. There is not even one java program in the default install.
Now, choosing between this two is harder. You already have experience with python and pygame, so this is a great choice to get a quick start. You will be productive as soon as possible and your game will be cross-platform. But C++ is way faster than python. If you're game is really into heavy math with complex data structures the performance gain could well worth the extra effort.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Order statistics $P(X_{i_1}Let $X_1,X_2,...,X_n$ be i.i.d. continuous random variables such that the transformation theorem conditions are satisfied. Prove that $P(X_{i_1}<X_{i_2}<...<X_{i_n})=\frac{1}{n!}$ for all permutations $(i_1,i_2,...,i_n)$ of $(1,2,...,n)$
I understand that there are $n!$ permutations of $(1,2,...,n)$ and each permutation is equally likely to occur so the possibility is $\frac{1}{n!}$.But why do we need transformation theorem?

A: Since $X_{1}, \ldots X_{n}$ are continuous their cdf $F$ is also continuous. Since $F$ is monotonic increasing,
\begin{align*}
  P(X_{i_1} < X_{i_2} < \ldots  < X_{i_n}) = P(F^{-1}(X_{i_1}) < F^{-1}(X_{i_2}) < \ldots  < F^{-1}(X_{i_n}))
\end{align*}
Observe that, for every $j$, $F^{-1}(X_{i_j}) \sim \text{Uniform}(0,1)$.
Hence, your problem boils down to proving that, if $U_{1}, \ldots U_{n}$ are i.i.d. random variables with $U_{i} \sim \text{Uniform}(0,1)$, then $P(U_{i_1} < U_{i_2} < \ldots  < U_{i_n}) = (n!)^{-1}$.
Observe that $\{u \in R^{n}: u_{i_1} < u_{i_2} < \ldots < u_{i_n}\}$ all have the same volume. Hence, since there are n! disjoint sets corresponding to each permutation, the result follows.


text:
Q: Unity & Rider - References go AWOL after Git Commit I'm setting up a Unity project, create source files, open them in Rider: All looks good!
I commit it all to Git, come back into Rider and all references (System, System.Core, UnityEditor, UnityEngine, etc.) go missing. Does anyone know why this happens and how to fix it?
I remember back in the old days in VS we added references from the Unity DLLs manually. Does this still need to be done? I'm asking because I think this should not happen anymore.
EDIT: Deleting the broken references and re-adding them from the DLL files doesn't help. They still show the warning icon on them afterwards. Any solutions to this issue?

A: Switch the Unity - Preferences - Rider - TargetFrameworkVersion checkbox.
Same issue https://github.com/JetBrains/resharper-unity/issues/164


text:
Q: HIVE-SQL_SERVER: HadoopExecutionException: Not enough columns in this line I have a hive table with the following structure and data:
Table structure:
CREATE EXTERNAL TABLE IF NOT EXISTS  db_crprcdtl.shcar_dtls
  ID  string,
  CSK string,
  BRND string,
  MKTCP string,
  AMTCMP string,
  AMTSP string,
  RLBRND string,
ROW FORMAT DELIMITED
FIELDS TERMINATED BY '\t'
LINES TERMINATED BY '\n'
STORED AS TEXTFILE
LOCATION '/on/hadoop/dir/'

-------------------------------------------------------------------------------
ID  |     CSK |          BRND |          MKTCP |            AMTCMP
-------------------------------------------------------------------------------
782    flatn,grpl,mrtn  hnd,mrc,nsn    34555,56566,66455     38900,59484,71450
1231   jikl,bngr        su,mrc,frd     56566,32333,45000     59872,35673,48933
123    unsrvl           tyt,frd,vlv    25000,34789,33443     29892,38922,36781

Trying to push this data into the SQL Server. But while doing so, getting the following error message:
SQL Error [107090] [S0001]: HdfsBridge::recordReaderFillBuffer - Unexpected error encountered filling record reader buffer: HadoopExecutionException: Not enough columns in this line.

What I tried:

There's an online article where the author has documented similar kind of issues. I tried to implement one of them Looked in Excel and found two columns that had carriage returns but this also doesn't come handy.
Any suggestion/help would be really appreciated. Thanks

A: If I'm able to understand your issue, then it seems that your , separated data is getting divided into various columns rather one column on the SQL-SERVER, something like:
------------------------------
ID  |CSK |BRND |MKTCP |AMTCMP
------------------------------
782    flatn grpl mrtn  hnd mrc nsn  345   56566 66455   38900 59484 71450
1231   jikl bngr        su  mrc frd  56566 32333 45000   59872 35673 48933
123    unsrvl           tyt frd vlv  25000 34789 33443   29892 38922 36781

So, if you look on Hive there are only 5 columns. While on SQL-SERVER the same. This I presume as you haven't shared the schema. But if that's the case, then you see that there are more than 5 values are being passed. While the schema definition is only of 5 columns.
So the error is populating.
Refer this Document by MS and try to create a FILE_FORMAT with FIELD_TERMINATOR ='\t',
like:
CREATE EXTERNAL FILE FORMAT <name>
WITH (
   FORMAT_TYPE = DELIMITEDTEXT,
   FORMAT_OPTIONS (
        FIELD_TERMINATOR ='\t',
        | STRING_DELIMITER = string_delimiter
        | First_Row = integer -- ONLY AVAILABLE SQL DW
        | DATE_FORMAT = datetime_format
        | USE_TYPE_DEFAULT = { TRUE | FALSE }
        | Encoding = {'UTF8' | 'UTF16'} )
  );

Hope that helps to resolve to your issue :)


text:
Q: Is there a package for polar plot in android studio, given data set of (r,theta)? From what I found most of the package return a piechart not a polar.
I have a list of data containing the radius and the angle (r,theta) and want to plot it in an android app
Does anyone know a package for this application?
Some image to make it clearer what I'm asking.
polar plot

radiation pattern

Thank you very much for your help in advance.


text:
Q: sort array with multi properties (descending date, name) Could you please help correct the below code?

var arr =

    [
      { created: '2020-09-28', title: 'title13' },
      { created: '2020-09-30', title: 'title12' },
      { created: '2020-09-29', title: 'title8' },
      { created: '2020-09-29', title: 'title7' },
      { created: '2020-09-28', title: 'title6' },
      { created: '2020-09-30', title: 'title1' },
      { created: '2020-09-30', title: 'title13' },
      { created: '2020-09-30', title: 'title2' },
    ];

function sortByValue(arr){
     var sortedArray = [];
     for(var i in arr)
     {
        sortedArray.push([arr[i], arr[i].created, arr[i].title]);
     }
     var sortedArraydata= [];
     sortedArraydata = sortedArray.sort();

     var finalarray=[];
     for (var i in sortedArraydata)
     {
        finalarray.push(sortedArraydata[i][0]);
     }
     return finalarray;
   }
sortByValue(arr);

The expectation is to sort by descending date and name properties. Here is what I am trying to achieve.
Output:
[
  { created: '2020-09-30', title: 'title1' },
  { created: '2020-09-30', title: 'title2' },
  { created: '2020-09-30', title: 'title12' },
  { created: '2020-09-30', title: 'title13' },
  { created: '2020-09-29', title: 'title7' },
  { created: '2020-09-29', title: 'title8' },
  { created: '2020-09-28', title: 'title6' },
  { created: '2020-09-28', title: 'title13' },
];

A: I'd use Array.prototype.sort() :-)

let arr = [
  { created: '2020-09-28', title: 'title13' },
  { created: '2020-09-30', title: 'title12' },
  { created: '2020-09-29', title: 'title8' },
  { created: '2020-09-29', title: 'title7' },
  { created: '2020-09-28', title: 'title6' },
  { created: '2020-09-30', title: 'title1' },
  { created: '2020-09-30', title: 'title13' },
  { created: '2020-09-30', title: 'title2' },
]

let sorted = arr.sort((a, b) =>

  // sort by created desc
  (new Date(b.created) - new Date(a.created))

  // if 0 (a tie), sort by title asc
  || a.title.localeCompare(b.title)
)

console.log(sorted)


text:
Q: Add directory containing pre compiled module in CMakeLists I am modifying a CMakeLists.txt file for a fortran code. I need to add a directory that contains a precompiled module.
How can I do that in CMakeLists.txt ?

A: There is a target property called Fortran_MODULE_DIRECTORY
For good measure, I also add the module directory as an include directory. gfortran looks for .mod files in the include directories.
set_target_properties( Target PROPERTIES Fortran_MODULE_DIRECTORY "dir" )
target_include_directories(Target PUBLIC "dir" )

Edit
Reading through your question again, I see that the module you are interested in is already compiled. Fortran_MODULE_DIRECTORY specifies where to PUT .mod files, and adds that directory as a place to look for them. target_include_directories statement just specifies where to look for them.  I am most familiar with using gfortran, which has this in it's man page:
  -Idir
       These affect interpretation of the "INCLUDE" directive (as well as of the "#include" directive of the
       cpp preprocessor).

       Also note that the general behavior of -I and "INCLUDE" is pretty much the same as of -I with
       "#include" in the cpp preprocessor, with regard to looking for header.gcc files and other such things.

       This path is also used to search for .mod files when previously compiled modules are required by a
       "USE" statement.

   -Jdir
       This option specifies where to put .mod files for compiled modules.  It is also added to the list of
       directories to searched by an "USE" statement.

       The default is the current directory.

This is what CMake will do for you and your compiler; you shouldn't need to specify these flags explicitly. In your case, just the includes should be sufficient, since the module has already been compiled.
However, if you find it's not working with your compiler, you may have to specify them manually by setting the variable CMAKE_Fortran_FLAGS.
Hope this helps.


text:
Q: Using dagger-injected objects in attachBaseContext I need to access my SharedPreferences instance in the attachBaseContext of my activity (so I can set the locale there), but the injected SharedPreferences instance is not available there as the injection is happening in the onCreate method, which is running after the attachBaseContext call. I am using dagger2 for dependency injection.
Any idea how I can avoid creating a new SharedPreferences instance?
EDIT:
Ok, so I think the problem is that I am trying to use dagger too much, I think in this case it is simply not suitable. In the attachBaseContext of each activity I have to update the locale, and I extracted this updating logic to a LocaleManager which needs access to the SharedPreferences instance and the Context that I get in attachBaseContext. The SharedPreferences instance is already in the AppModule, but I still cannot @Inject it to the activities before the attachBaseContext call, as the activity`s injections happen after attachBaseContext.

A: You can inject like this:
    @EntryPoint
    @InstallIn(SingletonComponent::class)
    interface PreferencesProvider {

        fun getPreferences(): Preferences
    }

    abstract class BaseActivity ... {
        private lateinit var preferences: Preferences

        override fun attachBaseContext(newBase: Context) {
           initPreferences(newBase)
           super.attachBaseContext(ContextLocaleWrapper.wrap(newBase,preferences.getLanguage()))
        }

        private fun initPreferences(context: Context) {
            preferences = EntryPointAccessors.fromApplication(
                context.applicationContext,
                PreferencesProvider::class.java
            ).getPreferences()
        }
    }

A: As long as you can access your Component you could add a provision method
@Singleton
@Component(modules = [AppModule::class])
interface AppComponent {

    fun inject(myActivity: MyActivity)

    fun sharedPreferences(): SharedPreferences

    ...
}

and then access your SharedPreferences directly via the Component:
class MyActivity : AppCompatActivity() {

    override fun attachBaseContext(newBase: Context) {
        val sharedPreferences = component.sharedPreferences()
        ...
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        component.inject(this)
    }

}


text:
Q: Thymeleaf - Accessing Nested Object Properties Rookie question here, I have an <input> that I'd like to display a User's nested property using Thymeleaf

*

*Each User has a Department

*Every Department has a name

I attempt to access it like by sending a List of User objects to my form
<select id="user">
    <option value="" th:text="-Select-"></option>
    <option
        th:each="user: ${users}"
        th:value="${user.id}"
        th:text="${user.name}"
        th:attr="data-department=${user.department.name}">
    </option>
</select>

Thymeleaf can locate the nested department object (returns [object, Object]), but when trying to access the department name  a SpringExpressionLanguage Exception when trying to access the name of the department.
org.springframework.expression.spel.SpelEvaluationException: EL1007E:(pos 0): Property or field 'name' cannot be found on null

I'm still going through the documentation, but haven't found how to access this yet which is probably extremely simple. Any ideas?

A: Obviously, one of users has no department, hence departemnt is null. Thymeleaf can't get value of property of null. That's why you get error. Try to check that department is not null before output:
<select id="user">
        <option value="" th:text="-Select-"></option>
        <option
            th:each="user: ${users}"
            th:value="${user.id}"
            th:text="${user.name}"
            th:attr="data-department=${user.department!=null}?${user.department.name}:'not specified'">
        </option>
    </select>


text:
Q: Is there maximum number of images that can be cached? I have 700 frames/images of 352x288 size 9kbs on my server.  I want to render them like a video clip on a browser. I am using JQueryAjax to get these images and return an array of 's to be loaded one after another via a timer. I have found when i try to cache all 700 images I get an unspecified server error.  I have reduced the cache to 250 images which work. My question is whether there is a limit to a cache of this type and is it dependent upon browser, image size?
I ask this because to get round my 250 max problem I was going to update the cache dynamically as soon as the image has been displayed.  But this could fall down if it is dependent on things like PC/client browser limitations.
thanks.
my existing code:
HTML

hello andy

Javascript:


text:
Q: Unitialized Class Calling Function, No exception. What is going on here? Is this normal behavior; this never happened to me before. I assume it would cause an exception but why doesn't it here? Take a look.

CWindowsApplication::MsgProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    static CWindowApplication* pApp = NULL;

    if (message == WM_NCCREATE)
    {
    //// retrieve Window instance from window creation data and associate
    //pApp = reinterpret_cast(((LPCREATESTRUCT)lParam)->lpCreateParams);
    //::SetWindowLong(hWnd, GWL_USERDATA, reinterpret_cast(pApp));

    //pApp = reinterpret_cast(::GetWindowLong(hWnd, GWL_USERDATA));
    }

    pApp->WndProc(hWnd, message, wParam, lParam); // pApp = NULL, but it still works? I expected a exception of some sort.
}

But, when I change the class to something else I get the exception I was expecting.
What is going on here? Never in my 10+ years as an enthusiastic programmer have I ever came across something like this.

A: As long as WndProc is not virtual, the pointer technically doesn't need to be dereferenced at all in order to make the call.  That's not to say it won't crash and burn when you try to use this (including calling any virtual function with an implicit this) inside WndProc, but non-virtual calls go by the type of the pointer, and don't need to touch the vtable (or any other instance member).

A: All you're doing is invoking undefined behaviour. That means that it can appear to work, it can crash, or whatever the compiler feels like making it do.


text:
Q: Can't set hazelcast ManagedContext when using Jet.bootstrappedInstance() I want to run hazelcast-jet embedded in my spring application (ie cluster is in process / NOT remote). I also want my jet jobs to be able to access spring beans from the ApplicationContext (see jet/spring docs). I don't want to have to configure the classpath on each jet job, I want to use the JVM's bootstrap classpath.
I think I need to use Jet.bootstrappedInstance() to get a JetInstance but this does NOT allow me to set the ManagedContext on the underlying HazelcastInstance. The docs from Jet.bootstrappedInstance() detail the way in which I want to interact with Jet

When you submit a job to a Jet instance that runs locally in your JVM, it will have all the dependency classes available

I've tried this:
@Bean
public ManagedContext managedContext() {
   return new SpringManagedContext();
}
@Bean
public JetInstance jet(ManagetContext managedContext, List<Pipeline> pipelines) {
   JetInstance jet = Jet.bootstrappedInstance();
   jet.getHazelcastInstance().getConfig().setManagedContext(managedContext);
   ...
   return jet;
}

But I get the following exception
Caused by: java.lang.UnsupportedOperationException: Unsupported operation
    at com.hazelcast.internal.dynamicconfig.DynamicConfigurationAwareConfig.setManagedContext(DynamicConfigurationAwareConfig.java:981)

Please note that the normal way of calling setManagedContext(...) is like this
   JetConfig config = new JetConfig();
   config.configureHazelcast(hz -> hz.setManagedContext(managedContext));
   JetInstance jet = Jet.newJetInstance(config);

I can't find a way of combining Jet.bootstrappedInstance() with Config.setManagedContext(ManagedContext)
As a workaround, I've copied code from JetBootstrap.createStandaloneInstance() (a private method) and added hzConfig.setManagedContext(managedContext)
  JetConfig config = ConfigProvider.locateAndGetJetConfig();
  Config hzConfig = config.getHazelcastConfig();

  // turn off all discovery to make sure node doesn't join any existing cluster
  hzConfig.setProperty("hazelcast.wait.seconds.before.join", "0");
  hzConfig.getAdvancedNetworkConfig().setEnabled(false);
  hzConfig.setManagedContext(managedContext);

  JoinConfig join = hzConfig.getNetworkConfig().getJoin();
  join.getAutoDetectionConfig().setEnabled(false);
  join.getMulticastConfig().setEnabled(false);
  join.getTcpIpConfig().setEnabled(false);
  join.getAwsConfig().setEnabled(false);
  join.getGcpConfig().setEnabled(false);
  join.getAzureConfig().setEnabled(false);
  join.getKubernetesConfig().setEnabled(false);
  join.getEurekaConfig().setEnabled(false);
  join.setDiscoveryConfig(new DiscoveryConfig());
  JetInstance jet = Jet.newJetInstance(config);

A:
I want to run hazelcast-jet embedded in my spring application (I don't want to submit jobs to a remote jet cluster)

In this case using bootstrapInstance() doesn't make sense. It was designed to work with the bin/jet submit command where it creates a client instance according to the config/hazelcast-client.yaml or standalone instance for testing from your IDE.
For using Jet embedded you can use the annotation based configuration or alternatively you can use Hazelcast Jet Spring Boot Starter.


text:
Q: How can I convert scala.xml.Elem to something compatible with the javax.xml APIs? I have a Scala representation of some XML (i.e. a scala.xml.Elem), and I'd like to use it with some of the standard Java XML APIs (specifically SchemaFactory).  It looks like converting my Elem to a javax.xml.transform.Source is what I need to do, but I'm not sure.  I can see various ways to effectively write out my Elem and read it into something compatible with Java, but I'm wondering if there's a more elegant (and hopefully more efficient) approach?
Scala code:
import java.io.StringReader
import javax.xml.transform.stream.StreamSource
import javax.xml.validation.{Schema, SchemaFactory}
import javax.xml.XMLConstants

val schemaXml = <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
                  <xsd:element name="foo"/>
                </xsd:schema>
val schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

// not possible, but what I want:
// val schema = schemaFactory.newSchema(schemaXml)

// what I'm actually doing at present (ugly)
val schema = schemaFactory.newSchema(new StreamSource(new StringReader(schemaXml.toString)))

A: What you want is possible - you just have to gently tell the Scala compiler how to go from scala.xml.Elem to javax.xml.transform.stream.StreamSource by declaring an implicit method.
import java.io.StringReader
import javax.xml.transform.stream.StreamSource
import javax.xml.validation.{Schema, SchemaFactory}
import javax.xml.XMLConstants
import scala.xml.Elem

val schemaXml = <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
                  <xsd:element name="foo"/>
                </xsd:schema>
val schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

implicit def toStreamSource(x:Elem) = new StreamSource(new StringReader(x.toString))

// Very possible, possibly still not any good:
val schema = schemaFactory.newSchema(schemaXml)

It isn't any more efficient, but it sure is prettier once you get the implicit method definition out of the way.


text:
Q: Need to get the last part of a URL where path doesn't exist I have the URL of www.domain.com/profile/user123 (where user123 will vary for each user profile viewed).
How can I get 'user123' into a variable in PHP? I just need to get the very last part of the URL. I don't want to use ? as part of the URL, but right now I'm getting a 404 because the URL doesn't exist.
I'm not sure if I need to modify the .htaccess file? The only modification I have in it so far is to remove .php requirement in URL.

A: Can you try this. I edited it the fist answer was wrong. Now it is right.
<?php
$url="www.domain.com/profile/user123";
$arr=explode("/",$url);
$userVariable=end($arr);
?>

you can use $userVariable in anywhere on your php document. After triying can you write your result?

A: if($usr == 'user123')
header ('location: www.domain.com/profile/''');


text:
Q: cacheManager.getCache always return null but the value is in cacheManager bean when inspect the object I'm trying to use Spring Cache to store data, generated by another method inside Service class.
This method marked with @Cacheable is a public method, the cache is being called in Controller layer.
When I do debugging, I inspect the object cacheManager, I found that it contains the map that I stored, but when calling the method cacheManager.getCache("cache") it return null.
Question is why that method return null while the object is holding the value?
This is the config, service and controller:
Spring bean config:
@EnableCaching
public class CachingConfig {

    @Bean
    public CacheManager cacheManager() {
        return new ConcurrentMapCacheManager("optCache");
    }
}

Service:
public void verify(Request request, String authorization) {
        String memberId = parseAuthToken(authorization).getMembershipID();
        buildOtpCache(memberId, request.getTokenUUID(), 0)
    }

    @Cacheable("otpCache")
    public OTPCache buildOtpCache(String memberId, String uuid, int counter) {
        return OTPCache.builder()
            .memberId(memberId)
            .tokenUUID(uuid)
            .timestamp(LocalDateTime.now())
            .counter(counter)
            .build();
    }

Controller:
@Override
    public void verifyOTP(MeOTPVerifyRequest verifyOTPRequest, String authorization) {
        String memberId = parseAuthToken(authorization).getMembershipID();
        Collection<String> a = cacheManager.getCacheNames();
        OTPCache OTPCache = cacheManager.getCache("cache").get(memberId, OTPCache.class);
        otpService.verify(verifyOTPRequest, authorization);
    }

EDIT:
This is my new service class, remove @Cacheable annotation:
public void verify(Request request, String authorization) {
        String memberId = parseAuthToken(authorization).getMembershipID();
        cacheManager.getCache("optCache").put(memberId, buildOtpCache(memberId, request.getTokenUUID(), 0));
    }

    public OTPCache buildOtpCache(String memberId, String uuid, int counter) {
        return OTPCache.builder()
            .memberId(memberId)
            .tokenUUID(uuid)
            .timestamp(LocalDateTime.now())
            .counter(counter)
            .build();
    }


text:
Q: Easy way to cusomize views of Rails' scaffold generator? I know how to create a new generator in Rails. However, I simply want to tweak the views a bit. Is there an easy way to do this? I guess I could go into the directory in my operating system where Rails resides and modify those files (I assume that's easy). But then those changes will apply to every Rails project, not just the one I care about at the moment. And it'll get wiped away when I update Rails (frequently).
Using Rails 3.2.13, but happy to upgrade to 4.0 beta if that helps.

A: You can find the answer in this RailsCast, note particularly the section on "Customizing Templates". You create the files in your Rails root lib/ directory, so it won't apply to every app, just your current one, and it will be independent of Rails versions.


text:
Q: Android Studio: Cannot change layout button properties Created a button in Android Studio(most recent version). Trying to change the properties of the button but no changes are ever saved. Am I missing something?

A: Nevermind I found that you should goto The Text Mode and change some things there. Would be nice if Design Mode can edit as well though.


text:
Q: Как создать псевдокод для известной задачи Мне дали функцию для написания псевдокода. Проблема в том, что я даже не понимаю, как должна работать эта функция. Кто-то должен помочь мне объяснить работу этой функции, пожалуйста.
Получить заряд у источника питания. Источник питания отдает все возможное количество заряда

\param[in] delta - запрашиваемое количество заряда

\param[in|out] amountОfСharge - реальное количество заряда у источника питания

\return - отданное количество заряда

int reduceCharge(int delta, int *amountОfСharge)

A: По идее так:
int reduceCharge(int delta, int *amountОfСharge)
{
    // result - это отданное количество заряда
    // Если запрашиваемое количество заряда меньше, чем есть у источника питания,
    // то result = delta, иначе отдаем весь заряд источника питания
    int result = (delta < *amountOfCharge) ? delta : *amountOfCharge;

    // Отнимаем у источника питания заряд, который запросили
    *amountOfCharge -= result;

    // Возвращаем результат
    return result;
}


text:
Q: How to know the name of the excel file you link in the formula EPPLUS In order to find out worksheet relationship, I am using EPPLUS to read the formula inside the cell of excel using this code:
string cellValue = workSheet.Cells[row, col].Formula

*

*For cell reference to another worksheet in the same work book. For example, in the same workbook, a cell in Sheet1 refer to another cell in Sheet2

result of cellValue will like Sheet2!A1
Ok, I know that it will link to Sheet2 in the same workbook

*

*For cell reference to another worksheet in other work book. For example, a cell in Sheet1 workbook A refer to another cell in Sheet1 in workbook B

result of cellValue will like [1]Sheet1!A1
The name of the work B is not shown, it just show [1] like example above. I won't know what is [1].
Whether any method help me know that [1] is workbook B and the location of workbook B ?
I have google but don't find out yet.
Thank you.


text:
Q: GWT - Way around Access-Control-Allow-Origin? I'm making an internet application with GWT, and one of the features that I've been stuck on for a few weeks is getting the users contact data from google data. I've tried things like GWT-GData and they don't seem to play nicely with the current version of GWT, so I tried going the more traditional approach with OAuth and doing an HTTP Get request. I haven't been receiving anything back as a response, and couldn't figure out why, and I happened across my javascript error log and I'm getting:
"Origin [site name here] is not allowed by Access-Control-Allow-Origin"
I've done some reading and I have a decent idea of what's going on, but I don't know how to get around it in GWT. I've found plenty of read-ups on how to get around it with other platforms, but I haven't seen anything for GWT. Can anyone offer any wisdom?
Edit:
Here is the code I'm using:
public static void doGet(String url, String oauthToken) {

        RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
        try {
            Request request = builder.sendRequest(oauthToken, new RequestCallback() {
                @Override
                public void onError(Request request, Throwable e) {
                    GWT.log(e.toString(), e);
                }

                @Override
                public void onResponseReceived(Request request, Response response) {
                    Window.alert("HEADER:" + response.getHeadersAsString()
                            + "\nSTATUS: " + response.getStatusText()
                            + "\nTEXT: " + response.getText());
                }
            });
        } catch (RequestException e) {
            GWT.log(e.toString(), e);
        }
    }

A: There's nothing you can do but configure the server to accept the origin of the request (i.e. add it to the returned Access-Control-Allow-Origin.
Because it's GData, it might however simply be a mistake on your side re. the requested URL: there's no Access-Control-Allow-Origin when you request data in Atom format, only when requesting JSON (and the value is then * which allows everyone, so shouldn't cause any issue like you're seeing): http://code.google.com/p/chromium/issues/detail?id=45980#c2

A: While this doesn't answer the original question, the following may help others who have the same underlying issue that arrived at this page (I'm using a GWT client with a Groovy web server). This did the trick on the server:
HttpExchange.getResponseHeaders().add("Access-Control-Allow-Origin","*");


text:
Q: Restore repository to a previous GIT commit I would like to "roll back" a Git repository to a previous commit.

*

*I have committed many times (30?) since the [PREVIOUS COMMIT].

*I do NOT want to retain the history or changes of these later commits. I want to delete everything after the [PREVIOUS COMMIT].

Can someone please explain the process for this? Thanks.

A: You would use git reset --hard [PREVIOUS COMMIT]  This resets the repository to the commit dropping all changes.
https://www.kernel.org/pub/software/scm/git/docs/git-reset.html


text:
Q: How can I do Accumlative summation? In this code I do Sum over r and x
rgt[rf_, n_, m_] := ParallelSum[x r, {r, 0, rf, n}, {x, 1, 5, m}]

then I want to get the results for different rf as follows
Table[rgt[rf,1,1],{rf,6,20,2}]//AbsoluteTiming
{0.077568,{315,540,825,1170,1575,2040,2565,3150}}

Note that at each rf the Sum over r starts always from 0 but this can be avoided if I can just add the Sum of the earlier step to the next one. How can I do that?

A: Outer product approach:
rgt[rf_, n_, m_] := Accumulate@Total[
   Outer[Times, Range[0, rf, n], Range[1, 5, m]],
   {2}
   ]

rgt[20, 1, 1][[7 ;; ;; 2]] // AbsoluteTiming

{0.000026, {315, 540, 825, 1170, 1575, 2040, 2565, 3150}}


text:
Q: Script only runs partially when run as cron I wrote a script that uses a program to create a CSV from an iCOBOL flat file. Unfortunately, the program just adds on to the end of the file and doesn't overwrite it. So I added a line to the script to first remove the file. Everything works well when I run it manually. When I have cron run it, it seems to just delete the file and then stop. Did I miss something? Please see my code below.
#!/bin/bash
cd /home/directory
rm -f file.csv
icreorg -O l flatfile file.csv

The icreorg is the program that is generating the csv.
Thank you!


text:
Q: strtok() c++ How do I split a string with strtok() and put each part in a vector? I'm trying to implement a basic terminal (like bash), and I'm currently trying to take in user input (as if they were entering commands in bash) and split up each by spaces and put it in a vector so I can read from the vector and attend to each command one by one.
I can't seem to get my code to compile, what am I doing wrong? (here's what I have so far):
#include <iostream>
#include <cstring>
#include <vector>
#include <string>
using namespace std;

int main(){
    vector<string> cmdline;
    string command = "";
    cout << '$';
    getline(cin, command);

    command.c_str();
    char* tokchar;
    tokchar = strtok(command, " ");

    while(tokchar){
        cmdline.push_back(tokchar);
        tokchar = strtok(NULL, " ");
    }
 return 0;
 }

Specifically, the compiler error is: cannot convert 'std::string' to 'char*'for argument 1 to 'char* strtok(char*, const char*)'
It says the error is on the line where I set tokchar =...;
I'm not sure if this code will do what I'm hoping. How would I fix it and make it put all of the command line arguments into a vector separated by " "?

A: You are using C++ types with a function that's more idiomatic to C.  Consider boost::split for C++.
All of:
char* tokchar;
tokchar = strtok(command, " ");

while(tokchar){
    cmdline.push_back(tokchar);
    tokchar = strtok(NULL, " ");
}

could be replaced (without errors) by:
boost::split( cmdline, command, boost::is_any_of(" ") );


text:
Q: Add number of observations per group in barplot (ggplot2) I am trying to add the number of observations to my plot, but I don't know if I am approaching this right.
I drew a my plot using the ggplot2 and tidyverse packages.
What I want is to add the number of observations (in the Obs column of the data) on top of each of the columns of the graph. However, it looks like I am not doing it right because it takes the value for each part of the column.
Does anyone know how to solve this?
Thank you very much!
Code for the graph
Euk_one %>%
  drop_na(`Length Stretch`) %>%
  mutate_at(c("GGA","GGG","GGT","GGC"),~.x/`Length Stretch`) %>%
  group_by(interval) %>% select(c(interval, "GGA","GGG","GGT","GGC", Obs))%>%
  summarize_all(mean) %>%pivot_longer(-c(interval, Obs)) %>%
  ggplot(aes(x=interval, y=value, fill=name)) + geom_col() +
  ggtitle("Eukarya 1 Codon Stretches - Distribution of codons ")+
  labs(fill= "Codons") +
  theme(axis.text.x = element_text(angle = 45)) + geom_text(aes(label=Obs), vjust = -.25)

Example Data
structure(list(interval = structure(c(2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L,
4L, 4L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("[6,7]",
"(7,8]", "(8,9]", "(9,10]"), class = "factor"), `Length Stretch` = c(8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 10, 10, 10,
10, 10, 10, 6, 6, 6, 6, 6, 7, 6, 6, 6, 6, 6, 6, 7, 6, 6, 6, 7,
7, 6, 6, 7, 6, 6, 7, 7, 7, 6), GGA = c(0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 7, 0, 6, 0, 0, 0, 0, 0, 7, 6, 6, 0, 0, 0,
0), GGG = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), GGT = c(8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10,
6, 6, 6, 6, 6, 7, 6, 6, 6, 6, 6, 6, 0, 6, 0, 6, 7, 7, 6, 6, 0,
0, 0, 7, 7, 7, 6), GGC = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), `Length Gene` = c(5250,
5250, 3021, 1905, 2910, 2973, 2367, 3021, 2931, 2754, 2424, 2862,
2436, 5061, 4935, 23949, 23988, 24024, 2733, 2733, 2358, 2358,
2733, 2733, 2838, 2079, 2100, 1998, 2835, 1197, 1197, 2838, 1998,
3795, 3795, 3795, 1320, 1827, 2088, 663, 10395, 10545, 2340,
2340, 1323, 1977, 2085, 4773, 10557, 10554, 1920), NumGens = c(19297,
19297, 19297, 19297, 19297, 19297, 19297, 19297, 19297, 19297,
19297, 19297, 19297, 19297, 19297, 19297, 19297, 19297, 19297,
19297, 19297, 19297, 19297, 19297, 19297, 19297, 19297, 19297,
19297, 19297, 19297, 19297, 19297, 19297, 19297, 19297, 19297,
19297, 19297, 19297, 19297, 19297, 19297, 19297, 19297, 19297,
19297, 19297, 19297, 19297, 19297), Count = c(1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1), Obs = c(13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L,
13L, 13L, 13L, 13L, 13L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L,
6L, 6L, 27L, 27L, 27L, 27L, 27L, 27L, 27L, 27L, 27L, 27L, 27L,
27L, 27L, 27L, 27L, 27L, 27L, 27L, 27L, 27L, 27L, 27L, 27L, 27L,
27L, 27L, 27L)), class = "data.frame", row.names = c(NA, -51L
))

Example of the plot

A: As you have only one value to plot as a label per interval, you can filter your dataframe using distinct function from dplyr and set a single y value to plot it:
library(tidyverse)
Euk_one %>%
  drop_na(`Length Stretch`) %>%
  mutate_at(c("GGA","GGG","GGT","GGC"),~.x/`Length Stretch`) %>%
  group_by(interval) %>% dplyr::select(c(interval, "GGA","GGG","GGT","GGC", Obs))%>%
  summarize_all(mean) %>%pivot_longer(-c(interval, Obs)) %>%
  ggplot(aes(x=interval, y=value, fill=name)) + geom_col() +
  ggtitle("Eukarya 1 Codon Stretches - Distribution of codons ")+
  labs(fill= "Codons") +
  theme(axis.text.x = element_text(angle = 45)) +
  geom_text(inherit.aes = FALSE, data = . %>% distinct(interval, Obs),
            aes(x = interval, y = 0.25, label=Obs))

Does it answer your question ?


text:
Q: Usage of the Present Perfect Continuous I heard this in a breezy conversation between an American and a non-native speaker carried on in a third country. The latter said:

*

*"You are American! I have been in America, in Texas, I have been working in an IT company".

Is the Present Perfect Continuous pertinent here and correct altogether?

A: The present perfect continuous (also called present perfect progressive) is a verb tense which is used to show that an action started in the past and has continued up to the present moment Walmart One. The present perfect continuous usually emphasizes duration, or the amount of time that an action has been taking place.


text:
Q: Retrofit 2 swagger response is 200 but can not get token from response body I try to get connect and get token with Retrofit 2 from a swagger restful service ,I get the response is 200 but can not get token from response body
private void login() {
        Call<User> call=userClient.login("user","123","password");

        call.enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {

                if(response.isSuccessful()){
                    token=response.body().getToken();
                    Toast.makeText(LoginActivity.this,token,Toast.LENGTH_SHORT).show();

                }else{
                    Toast.makeText(LoginActivity.this,"login not correct",Toast.LENGTH_SHORT).show();
                }

            }

            @Override
            public void onFailure(Call<User> call, Throwable t) {

                Toast.makeText(LoginActivity.this,"error",Toast.LENGTH_SHORT).show();

            }
        });
    }

A: Create the User class like this
 public class User {

@SerializedName("access_token")
@Expose
private String accessToken;
@SerializedName("token_type")
@Expose
private String tokenType;
@SerializedName("expires_in")
@Expose
private Integer expiresIn;

public String getAccessToken() {
return accessToken;
}

public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}

public String getTokenType() {
return tokenType;
}

public void setTokenType(String tokenType) {
this.tokenType = tokenType;
}

public Integer getExpiresIn() {
return expiresIn;
}

public void setExpiresIn(Integer expiresIn) {
this.expiresIn = expiresIn;
}

}

and then try like this
token=response.body().getAccessToken();

Your retrofit instance should be like
Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Constants.your_baseUrl)
            .addConverterFactory(GsonConverterFactory.create())
            .build();


text:
Q: Difference between three dependencies in one example, I saw three dependencies block in build.gradle.
example:
root folder: build.gradle
1.
buildscript{
 dependencies{
 }
}

2.Under android block
android{
 dependencies{
 }
}

*I see one more dependencies block on root folder
buildscript{
 }
 dependencies{
 }
  android{
 }
First two are been explained in Android developer site.
1st: is applicable for complete project
2nd: per module.
I am not understanding what 3rd dependency block means.

A: It's a bit confusing because Android Studio by default shows both build.gradle files right next to each other (when using the Android view).

If you switch to the Project view you can see the actual structure and where the different build.gradle files are located.

The build.gradle (Project: MyApplication) file is in the root folder of the project and its configuration settings apply to every module in the project. A module is an isolated piece of the bigger project. In a multi-module project, these modules have their own jobs but work together to form the whole project. Most Android projects only have one module, the app module.
The build.gradle (Module: app) file here is in the app folder. Its build settings apply only to the app module. If there were another module, then the it would have its own build.gradle file, too. As an example, I made a library project with three modules: a library module, a demo app module, and another app module that I plan to use for testing. Each of them have their own build.gradle files that I can tweak.

In a basic project, almost everything you need to edit will be in the app module's build.gradle file. You can remember it like this:

You're making an app, so go to the build.gradle (Module: app) file.

Further reading

*

*Configure Your Build (Android documentation--very readable and useful)

*Introduction to multi-project builds (Gradle documentation)

A:
First two are been explained in Android developer site. 1st: is applicable for complete project 2nd: per module.

It is not exact.
The buildscript block can be specified in the root level but also in the module build.gradle file.
These dependencies block only controls the dependencies for the buildscript process itself, not for the application code.

2.Under android block

android{
 dependencies{
 }
}

It is not correct.
The correct syntax is:
android {
  ...
}
...
dependencies {
    ...
}

Don't put these dependencies in the top-level file.


text:
Q: Can Salient Theme Nectar Slider support transparent background image? I'm editing a website which was designed in Wordpress with the Salient theme including Nectar Sliders.
The Nectar Slider automatically fills image transparent backgrounds with black.  There don't seem to be any options for this in Wordpress.
Is there a css file that can be modified?

A: Stylesheets for installed themes are located in Appearance > Editor, and are
hidden until you select the theme on the right.
It looks like Salient's Nectar Slider in particular cannot have a transparent background.  Overriding background-color to transparent makes the actual image transparent.


text:
Q: UIKeyboardWillShowNotification not firing in iOS8 I am trying to listen to the notification UIKeyboardWillShowNotification but for some reason its not getting fired in iOS8 and I see some undocumented notifications (UIKeyboardCandidateCorrectionDidChangeNotification) showing up in the console.
Anyone facing same error?

A: Try this!
Declare
BOOL _keyboardWillhide = YES;

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    _keyboardWillHide = NO;
    return YES;
}

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    _keyboardWillHide = NO;
    return YES;
}

if (_keyboardWillHide) {
    //Do something if keyboard is hide
    ...
}
//set back to Yes if keyboard willHide
_keyBoardWillHide = YES;

A: It works fine for me in Xcode 6.0.1 building for iOS8 on an iPhone 5s. Currently, the simulator in Xcode 6.0.1 doesn't seem to be opening keyboards.
Here is the code I use to register for the notification:
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardWillShow:)
                                             name:UIKeyboardWillShowNotification
                                           object:nil];

This works with the system and custom keyboards running on an actual device.  Hopefully there is a typo in your code somewhere.  If not, feel free to post what you are comfortable with for a second set of eyes.


text:
Q: How do I parse this output? Im trying to output just the "name:" element if the "achieved:" is true.
This is using the SteamAPI.
Its basically getting the data and storing it to the "achievements" variable.
steam.getUserAchievements(id, config.app).then(achievements => {
I tried doing something such as achievements.name but that didn't work.
Any ideas?
PlayerAchievements {
  steamID: '76561198170684483',
  gameName: 'Deadside',
  achievements: [
    Achievement {
      api: 'DS_FirstStep',
      name: 'First step',
      description: 'Make you first step in game',
      achieved: true,
      unlockTime: 1598449807
    },
    Achievement {
      api: 'DS_Weap_FirstBlood',
      name: 'First blood',
      description: 'Kill an enemy',
      achieved: true,
      unlockTime: 1598451567
    },
    Achievement {
      api: 'DS_Weap_SteelArms',
      name: 'Cold Steel',
      description: 'Kill 10 AI bots with melee weapons',
      achieved: false,
      unlockTime: 0
    },
    Achievement {
      api: 'DS_Weap_Gun',
      name: 'Gunslinger',
      description: 'Kill 100 AI bots with Pistols',
      achieved: false,
      unlockTime: 0
    },
    Achievement {
      api: 'DS_Weap_SMG',
      name: 'Need for Lead',
      description: 'Kill 100 AI bots with SMGs',
      achieved: false,
      unlockTime: 0
    },
    Achievement {
      api: 'DS_Weap_AR',
      name: 'Lead Storm',
      description: 'Kill 100 AI bots with Assault Rifles',
      achieved: true,
      unlockTime: 1598737115
    },
    Achievement {
      api: 'DS_Weap_ShotGun',
      name: 'Son of a Shotgun',
      description: 'Kill 100 AI bots with Shotguns',
      achieved: true,
      unlockTime: 1598755630
    },
    Achievement {
      api: 'DS_Weap_Snip',
      name: 'Rifleman',
      description: 'Kill 100 AI bots with Rifles',
      achieved: false,
      unlockTime: 0
    },
    Achievement {
      api: 'DS_Weap_Gren',
      name: 'Hottest Potato',
      description: 'Kill 10 AI bots with Grenades',
      achieved: false,
      unlockTime: 0
    },
    Achievement {
      api: 'DS_Weap_Headshot',
      name: 'Headshot!',
      description: 'Kill 50 AI bots with headshot',
      achieved: true,
      unlockTime: 1598801600
    },
    Achievement {
      api: 'DS_Weap_LastBullet',
      name: 'Last bullet',
      description: 'Kill 10 AI bots with the last bullet in a clip',
      achieved: true,
      unlockTime: 1598826382
    },
    Achievement {
      api: 'DS_Weap_KillPlayer',
      name: 'There can only One',
      description: 'Kill 10 players',
      achieved: false,
      unlockTime: 0
    },
    Achievement {
      api: 'DS_Weap_AllWeapons',
      name: 'Full Arsenal',
      description: 'Kill one AI bot with each weapon',
      achieved: false,
      unlockTime: 0
    },
    Achievement {
      api: 'DS_MF_Any',
      name: 'Modder',
      description: 'Put any mod onto a weapon',
      achieved: true,
      unlockTime: 1598456376
    },
    Achievement {
      api: 'DS_Craft_Any',
      name: 'Mr. Fix-It',
      description: 'Craft any item',
      achieved: true,
      unlockTime: 1598450912
    },
    Achievement {
      api: 'DS_Craft_Base',
      name: "A man's home is his castle",
      description: 'Build your first base',
      achieved: true,
      unlockTime: 1598737891
    },
    Achievement {
      api: 'DS_Craft_BreakUp',
      name: 'Field Doctor',
      description: 'Tear any item to rags',
      achieved: true,
      unlockTime: 1598450049
    },
    Achievement {
      api: 'DS_Craft_Lumberjack',
      name: 'Lumberjack',
      description: 'Chop 100 logs',
      achieved: false,
      unlockTime: 0
    },
    Achievement {
      api: 'DS_Trade_Any',
      name: 'Trader',
      description: 'Buy or sell 100 items',
      achieved: true,
      unlockTime: 1598458913
    },
    Achievement {
      api: 'DS_FoodWater_Any',
      name: 'Gourmet',
      description: 'Consume all kinds of food and drinks',
      achieved: false,
      unlockTime: 0
    }
  ]
}

A: From the code which you provided we can see that PlayerAchievements class has an Array achievements which contains an Achievement class.
You can do the following in order to get the achievement name -
steam.getUserAchievements(id, config.app).then(achievements => {
console.log(achievements.achievements[0].name)
})

it will log the first achievement name similarly you can access other achievements also as it is an array.


text:
Q: Make hover to whole div by JS When l want to make hover to div it's going to hover entire of div divs
l tried to make set height for overlay but its lost!
<div id="Overlay" onmouseover="hoverDown()" onmouseout="hoverUp()" onload="muteOther()">

#Overlay {
    width: 100%;
    height: 100%;
    position: absolute;
    opacity: 0;
}

function hoverUp() {
    var a = document.getElementById("Overlay");

    a.style.opacity = "0";
    a.style.transition = "all 1s";

}

function hoverDown() {
    var a = document.getElementById("Overlay");
    a.style.opacity = "1";

    setTimeout(function () {
        a.style.opacity = "0";
        a.style.transition = "all 1s";
    }, 4000);

}

When l will move the cursor to the div its Overlay appear and when its out Overlay despair

A: Try include the JavaScript inside a <script> Tag. And in addition you can use attr_for_div=func(this) and func(this) in js which this is equal to var a=doc....


text:
Q: finding ratio of an array of intergers between 2 integers l and r. in javascript You are given an array of integers a and two integers l and r. You task is to calculate a boolean array b, where b[i] = true if there exists an integer x, such that a[i] = (i + 1) * x and l ≤ x ≤ r. Otherwise, b[i] should be set to false.

function boundedRatio(a, l, r) {
  let b = []
  for (let i = l; i <= r; i++) {
    //
    for (let j = 0; j < a.length; j++) {
      let result = (j + 1) * i

      if ((j + 1) * i === a[j] && l <= i <= r) {
        b.push(true)
      } else {
        b.push(false)
      }

    }
  }

  return b

  boundedRatio([8, 5, 6, 16, 5], 1, 3)
  // [false, false, true, false, true]

A: Your main loop should be over the array a. For each of them, you need a loop over l through r. In that loop you should just set a variable to inidcate whether the bounded value is found. Once you find it you can break out of the loop. Then you push that onto the result.
The main loop and push can be combine with map().

function boundedRatio(a, l, r) {
  let b = a.map((el, i) => {
    let bounded = false;
    for (let x = l; x <= r; x++) {
      if ((i + 1) * x == el) {
        bounded = true;
        break;
      }
    }
    return bounded;
  })

  return b;
}

console.log(boundedRatio([8, 5, 6, 16, 5], 1, 3));

Here's how it looks with a for loop instead of map().

function boundedRatio(a, l, r) {
  let b = [];
  for (let i = 0; i < a.length; i++) {
    let bounded = false;
    for (let x = l; x <= r; x++) {
      if ((i + 1) * x == a[i]) {
        bounded = true;
        break;
      }
    }
    b.push(bounded);
  }

  return b;
}

console.log(boundedRatio([8, 5, 6, 16, 5], 1, 3));

A: You can write down this code in C# also like that.
bool[] solution(int[] numbers, int left, int right) {
bool [] result=new bool[numbers.Length];
for(int i =0; i < numbers.Length; i++ )
{
    bool bounded = false;
    for(int x = left; x <= right; x++)
    {
        if((i+1)*x == numbers[i])
        {
            bounded= true;
            break;
        }
    }
    result[i] = bounded;
}
return result;

}


text:
Q: Ajax returns status code 200, success function not triggering There are quite a few topics about this, but none of them were any help.
Everything is working fine, the data gets inserted into the db, and (i'm using spring mvc as back-end) my controller handles everything correctly as well.
Ajax-code;
$.ajax({
                type: "POST",
                url: "http://localhost:8080/NotePath/register",
                data: "email=" + email + "&password=" + password + "&name=" + name,
                succes: function(response){
                    $("#formMail, #formPass, #formUsername").val("");
                    $("#loginRegister, #whiteBg").fadeOut();
                },
                error: function(xhr,err){
                    alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
                    alert("responseText: "+xhr.responseText);
                }
});

Controller code;
@RequestMapping(value = "/register")
public @ResponseBody String registerUser(@RequestParam(value = "email") String    email, @RequestParam(value ="password") String password,
        @RequestParam(value = "name") String name, Model model){

    String status = "";

    Boolean isEmailTaken = registerServiceImpl.isEmailTaken(email);
    Boolean isNameTaken = registerServiceImpl.isNameTaken(name);

    if(isEmailTaken == false && isNameTaken == false){
        try {
            registerServiceImpl.registerUser(email, password, name);
            status = "Succes";
        } catch (Exception e) {
            status = "Error";
            e.printStackTrace();
        }
    }else if(isEmailTaken == true){

        status = "mail taken";

    }else if(isNameTaken == true){

        status = "name taken";

    }

    return status;

}

I even tried returning a responseEntity;
return new ResponseEntity<String>(status, respHeader, HttpStatus.OK);

When I look at my response header (using google chrome) it even says "mail taken" or "name taken" or whatever message that should appear. But for some reason the ajax success function is not getting triggered...
Weird thing is that I have other ajax calls that do work without any problem.
I thought getting a status code of 200 meant that everything was...well....OK :p

A: You're not registering the callback correctly.
succes: function(response){ should be success: function(response) {


text:
Q: Can I really create a global variable with every declaration of a Type? So I wrote this code and was kind of surprised when it compiled (I am using gcc version 5.1.0):
struct Mine
{
    const int* ptr;
    Mine(const int x)
      : ptr([=]()
         {
           static const int n = x;
           return &n;
         }()
        ){}
};
Mine first = 12;
Mine second = 13;

The reason I am surprised is that each declaration of Mine creates a new "global" variable.
So here is the question:
Am I supposed to be allowed to do this?

A: There is only one n and all ptr's are equal.
So, no.


text:
Q: Android - Rotate video frames before sending to Wowza Streaming Engine using WebRTC I want to stream video from android camera to Wowza Streaming Engine (WSE) using WebRTC. When device in landscape mode, everything work well. Then I try to stream by putting the device in portrait mode.
The first thing I notice in WSE player is the video stream has been rotated 90 counter-clockwise. I figured out that WebRTC do not rotate each video frame that comes out from onPreviewFrame API before sending to WSE and unfortunately WSE do not support any mechanisms to rotate video frame at their side at least so far.
So I checked out WebRTC android native source code and modify it to rotate each video frame before sending to WSE. And right now I can see the video stream in portrait mode in WSE player.
But it has an issue is sometimes video stream look so weird. Please see the following images.
A normal image
A weird image
I put camera to a fix position. At the first time WSE player displays the first one, but sometimes the second one is showed up.
And here is the file in WebRTC source code that I changed.
~/webrtc/src/sdk/android/src/jni/androidvideotracksource.cc
void AndroidVideoTrackSource::OnByteBufferFrameCaptured(const void* frame_data,
                                                        int length,
                                                        int width,
                                                        int height,
                                                        VideoRotation rotation,
                                                        int64_t timestamp_ns) {
  RTC_DCHECK(camera_thread_checker_.CalledOnValidThread());

  int64_t camera_time_us = timestamp_ns / rtc::kNumNanosecsPerMicrosec;
  int64_t translated_camera_time_us =
      timestamp_aligner_.TranslateTimestamp(camera_time_us, rtc::TimeMicros());

  int adapted_width;
  int adapted_height;
  int crop_width;
  int crop_height;
  int crop_x;
  int crop_y;

  if (!AdaptFrame(width, height, camera_time_us, &adapted_width,
                  &adapted_height, &crop_width, &crop_height, &crop_x,
                  &crop_y)) {
    return;
  }

  const uint8_t* y_plane = static_cast<const uint8_t*>(frame_data);
  const uint8_t* uv_plane = y_plane + width * height;
  const int uv_width = (width + 1) / 2;

  RTC_CHECK_GE(length, width * height + 2 * uv_width * ((height + 1) / 2));

  // Can only crop at even pixels.
  crop_x &= ~1;
  crop_y &= ~1;
  // Crop just by modifying pointers.
  y_plane += width * crop_y + crop_x;
  uv_plane += uv_width * crop_y + crop_x;

  rtc::scoped_refptr<I420Buffer> buffer =
      buffer_pool_.CreateBuffer(adapted_width, adapted_height);

  nv12toi420_scaler_.NV12ToI420Scale(
      y_plane, width, uv_plane, uv_width * 2, crop_width, crop_height,
      buffer->MutableDataY(), buffer->StrideY(),
      // Swap U and V, since we have NV21, not NV12.
      buffer->MutableDataV(), buffer->StrideV(), buffer->MutableDataU(),
      buffer->StrideU(), buffer->width(), buffer->height());

  // TODO: Rotate I420 frame 90 degrees clockwise.
  rtc::scoped_refptr<I420Buffer> rotated_buffer =
      I420Buffer::Rotate(*buffer, kVideoRotation_90);

  OnFrame(VideoFrame(rotated_buffer, rotation, translated_camera_time_us));
}

I added this line of code to rotate I420 frame 90 degrees clockwise.
// TODO: Rotate I420 frame 90 degrees clockwise.
  rtc::scoped_refptr<I420Buffer> rotated_buffer =
      I420Buffer::Rotate(*buffer, kVideoRotation_90);

I would appreciate any help!

A: Finally I have figured out a solution to solve this problem. Below are my steps:
Step 1: Make sure you lock your streaming activity to portrait orientation
Step 2: Change this method in the file in WebRTC android native source code
~/webrtc/src/sdk/android/src/jni/androidvideotracksource.cc
Original Version:
void AndroidVideoTrackSource::OnByteBufferFrameCaptured(const void* frame_data,
                                                        int length,
                                                        int width,
                                                        int height,
                                                        VideoRotation rotation,
                                                        int64_t timestamp_ns) {
  RTC_DCHECK(camera_thread_checker_.CalledOnValidThread());

  int64_t camera_time_us = timestamp_ns / rtc::kNumNanosecsPerMicrosec;
  int64_t translated_camera_time_us =
      timestamp_aligner_.TranslateTimestamp(camera_time_us, rtc::TimeMicros());

  int adapted_width;
  int adapted_height;
  int crop_width;
  int crop_height;
  int crop_x;
  int crop_y;

  if (!AdaptFrame(width, height, camera_time_us, &adapted_width,
                  &adapted_height, &crop_width, &crop_height, &crop_x,
                  &crop_y)) {
    return;
  }

  const uint8_t* y_plane = static_cast<const uint8_t*>(frame_data);
  const uint8_t* uv_plane = y_plane + width * height;
  const int uv_width = (width + 1) / 2;

  RTC_CHECK_GE(length, width * height + 2 * uv_width * ((height + 1) / 2));

  // Can only crop at even pixels.
  crop_x &= ~1;
  crop_y &= ~1;
  // Crop just by modifying pointers.
  y_plane += width * crop_y + crop_x;
  uv_plane += uv_width * crop_y + crop_x;

  rtc::scoped_refptr<I420Buffer> buffer =
      buffer_pool_.CreateBuffer(adapted_width, adapted_height);

  nv12toi420_scaler_.NV12ToI420Scale(
      y_plane, width, uv_plane, uv_width * 2, crop_width, crop_height,
      buffer->MutableDataY(), buffer->StrideY(),
      // Swap U and V, since we have NV21, not NV12.
      buffer->MutableDataV(), buffer->StrideV(), buffer->MutableDataU(),
      buffer->StrideU(), buffer->width(), buffer->height());

  OnFrame(VideoFrame(rotated_buffer, rotation, translated_camera_time_us));
}

Modified Version:
void AndroidVideoTrackSource::OnByteBufferFrameCaptured(const void* frame_data,
                                                        int length,
                                                        int width,
                                                        int height,
                                                        VideoRotation rotation,
                                                        int64_t timestamp_ns) {
  RTC_DCHECK(camera_thread_checker_.CalledOnValidThread());

  int64_t camera_time_us = timestamp_ns / rtc::kNumNanosecsPerMicrosec;
  int64_t translated_camera_time_us =
      timestamp_aligner_.TranslateTimestamp(camera_time_us, rtc::TimeMicros());

  int adapted_width;
  int adapted_height;
  int crop_width;
  int crop_height;
  int crop_x;
  int crop_y;

  if (!AdaptFrame(width, height, camera_time_us, &adapted_width,
                  &adapted_height, &crop_width, &crop_height, &crop_x,
                  &crop_y)) {
    return;
  }

  const uint8_t* y_plane = static_cast<const uint8_t*>(frame_data);
  const uint8_t* uv_plane = y_plane + width * height;
  const int uv_width = (width + 1) / 2;

  RTC_CHECK_GE(length, width * height + 2 * uv_width * ((height + 1) / 2));

  // Can only crop at even pixels.
  crop_x &= ~1;
  crop_y &= ~1;
  // Crop just by modifying pointers.
  y_plane += width * crop_y + crop_x;
  uv_plane += uv_width * crop_y + crop_x;

  rtc::scoped_refptr<I420Buffer> buffer =
      buffer_pool_.CreateBuffer(adapted_width, adapted_height);

  nv12toi420_scaler_.NV12ToI420Scale(
      y_plane, width, uv_plane, uv_width * 2, crop_width, crop_height,
      buffer->MutableDataY(), buffer->StrideY(),
      // Swap U and V, since we have NV21, not NV12.
      buffer->MutableDataV(), buffer->StrideV(), buffer->MutableDataU(),
      buffer->StrideU(), buffer->width(), buffer->height());

  // TODO: Comment out this line of code to apply custom code.
  // OnFrame(VideoFrame(buffer, rotation, translated_camera_time_us));

  // TODO: The custom code to rotate video frame before passing
  // to next layers of WebRTC.

  // Rotate I420 frame rotation degrees.
  // Value of the rotation is 90 or 270 based on camera orientation.
  rtc::scoped_refptr<I420Buffer> rotated_buffer =
      I420Buffer::Rotate(*buffer, rotation);

  // Make sure the I420 frame has valid side in portrait mode.
  rtc::scoped_refptr<I420Buffer> final_buffer =
      buffer_pool_.CreateBuffer(height, width);
  final_buffer->ScaleFrom(*rotated_buffer);

  // After rotating the I420 frame, set value of the rotation to 0.
  // This mean we do not want to rotate the frame in next layers anymore.
  rotation = kVideoRotation_0;

  // Pass processed frame to the next layers.
  OnFrame(VideoFrame(final_buffer, rotation, translated_camera_time_us));
}

Now my stream is displayed perfectly on Streaming Wowza Engine Player.


text:
Q: Align a data label below a point on a bubble graph (Chart.JS) I am trying to position a label related to the dataset below a point on a bubble graph and to have the value displayed on top of the point.
I have tried returning two different values, but it only allows me to return one.
Because of this I have returned both values within the same string.
Is it possible to return the label and position it below the value of the dataset and to put the value above the point of the dataset?
If it isn't possible would it be possible to somehow get the text to align to the center after the line break I have added to the string?
Here is what I have so far
This is what I am trying to achieve, but with the value above the bubble
Here is my code so far:
var ctx = document.getElementById('myChart').getContext('2d');

var myChart = new Chart(ctx, {

    type: 'bubble',

    data: {
        datasets: [
            {
                label: 'Top',
                data: [
                    {x: 110, y: 0, r: 12, name: "Performance"}
                ],
                backgroundColor: "rgba(255,255,255,1)",
                borderColor: "rgba(91,182,209,1)",
                borderWidth: 2,
                hoverBackgroundColor: "rgba(255,255,255,1)",
                hoverBorderWidth : 2
            },
            {
                label: 'Average',
                data: [
                    {x: 75, y: 0, r: 12, name: "Performance"}
                ],
                backgroundColor: "rgba(255,255,255,1)",
                borderColor: "rgba(91,182,209,1)",
                borderWidth: 2,
                hoverBackgroundColor: "rgba(255,255,255,1)",
                hoverBorderWidth : 2
            },
            {
                label: 'You 2017',
                data: [
                    {x: 55, y: 0, r: 15, name: "Performance"}
                ],
                backgroundColor: "rgba(255,255,255,1)",
                borderColor: "rgba(91,182,209,1)",
                borderWidth: 2,
                hoverBackgroundColor : "rgba(255,255,255,1)",
                hoverBorderWidth : 2
            },
            {
                label: 'You 2018',
                data: [
                    {x: 90, y: 0, r: 15, name: "Performance"} // The labe needs to be
                ],
                backgroundColor: "rgba(255,255,255,1)",
                borderColor: "rgba(91,182,209,1)",
                borderWidth: 2,
                hoverBackgroundColor : "rgba(255,255,255,1)",
                hoverBorderWidth : 2
            }
        ]
    },
    options: {
        legend: {
            display: false
        },
        plugins: {
            datalabels: {
                anchor: function (context) {
                    var value = context.dataset.data[context.dataIndex];
                    return value.x < 1000 ? 'end' : 'center';
                },
                align: function (context) {
                    var value = context.dataset.data[context.dataIndex];
                    return value.x < 1000 ? 'end' : 'center';
                },
                color: function (context) {
                    var value = context.dataset.data[context.dataIndex];
                    return value.x < 1000 ? context.dataset.borderColor : 'white';
                },
                font: {
                    weight: 'bold'
                },
                formatter: function (value, context) {
                    ctx.textAlign = "center";
                    return context.dataset.label + "\n" + Math.round(value.x);
                },
                offset: 2,
                padding: 0
            }
        },
        maintainAspectRatio: false,
        scales: {
            yAxes: [{
                id: 'first-y-axis',
                type: 'linear',
                ticks: {
                    min: 0,
                    max: 1,
                    stepSize: 1,
                    display: false
                },
                gridLines: {
                    display: false,
                    drawBorder: false
                }
            }],
            xAxes: [
                {
                    id: 'first-x-axis',
                    ticks: {
                        min: 50, // Controls where axis starts
                        max: 120, // Controls where axis finishes
                        stepSize: 70 // Control the gap between the first x-axis value and the last x-axis value
                    },
                    gridLines: {
                        display: false,
                        lineWidth: 3 // Width of bottom line
                    }
                }
            ]

        }
    }

});

Any help or suggestions would be greatly appreciated ^_^

A: I figured this out by applying 'textAlign' within the charts parameters and set it to centre.
You can see this in the code below:
plugins: {
    datalabels: {
        anchor: function (context) {
            var value = context.dataset.data[context.dataIndex];
            return value.x < 1000 ? 'end' : 'center';
        },
        align: function (context) {
            var value = context.dataset.data[context.dataIndex];
            return value.x < 1000 ? 'end' : 'center';
        },
        color: function (context) {
            var value = context.dataset.data[context.dataIndex];
            return value.x < 1000 ? context.dataset.borderColor : 'white';
        },
        textAlign: 'center',
        font: {
            weight: 'bold',
            alignment: 'right' // Is this the place to be doing this?
        },
        formatter: function (value, context) {
            return context.dataset.label + '\n' + Math.round(value.x);
        },
        offset: 2,
        padding: 0
    }
},

Hope this helps ^^


text:
Q: How to convert OpenCV Mat to Halide Image and back? My goal is augment my pre-existing image processing pipeline (written in Halide) with OpenCV functions such as NL means denoising. OpenCV functions will not be capable of using Halide's scheduling functionality, so my plan is to realize each Halide Func before each OpenCV stage. The remaining question is how to best convert from a Halide Image (the result of the Func realization) to an OpenCV Mat (as input to an OpenCV function) and from OpenCV Mat to Halide Image when done. My Halide Images are of type float and have 3 channels.
One obvious solution to this is to write functions which copy the data from one data type to the other, but this strikes me as wasteful. Not only will it take precious time to copy over the data, but it will also waste memory since the image will then be stored as two different data types. Is there a way to use pointers or data buffers to simply re-wrap the image data in a new format? Hopefully this process would be reversible so I can go from Halide to OpenCV, and then after the OpenCV function is done back to Halide.

A: buffer_t is gone now, so I should update this answer. The current way to make a buffer that wraps an OpenCV mat (which uses an interleaved storage layout) is:
Halide::Runtime::Buffer<float>::make_interleaved(image.data, image.cols, image.rows, image.channels());

If the OpenCV matrix has padding between the rows, the longer form is:
halide_dimension_t shape[3] = {{0, image.cols, image.step1(1)},
                               {0, image.rows, image.step1(0)},
                               {0, image.channels(), 1}};
Halide::Runtime::Buffer<float> buffer(image.data, 3, shape);

a halide_dimension_t is the min coordinate, the extent, and then the stride/step in that dimension.

A: Yes, you can avoid copying data. I see two possible approaches: either allocate memory yourself and refer to that memory in both an OpenCV Mat instance and a Halide buffer_t structure; or let OpenCV's Mat class allocate the memory and refer to that memory in a buffer_t structure.
For the first approach, you can use a Mat constructor that takes a data pointer:
float* data = new float[3 * width * height];
cv::Mat image(height, width, CV_32FC3, data, AUTO_STEP);

For the second approach, you can use the usual constructor or Mat::create method:
cv::Mat image(height, width, CV_32FC3);

Either way, you can use something like the following code to wrap the memory in a Halide buffer_t structure:
buffer_t buffer;
memset(&buffer, 0, sizeof(buffer));
buffer.host = image.data;
buffer.elem_size = image.elemSize1();
buffer.extent[0] = image.cols;
buffer.extent[1] = image.rows;
buffer.extent[2] = image.channels();
buffer.stride[0] = image.step1(1);
buffer.stride[1] = image.step1(0);
buffer.stride[2] = 1;

Now you should be able to operate on the same memory with both OpenCV and Halide functions.


text:
Q: Having an archive page with categories and tags I'd like to have an archive (alternative to search) with Categories and Tags listed on one page. Is this possible? Can't seem to find any information on it.
Title/Archive Search<
Browse by category:
cat 1, cat 2 etc.
(Something more specific) Browse by Tags:
tag 1, tag 2 etc.

A: Something like this maybe?
<?php get_header(); ?>

    <?php the_post(); ?>

<?php the_title(); ?>

    <?php get_search_form(); ?>

Browse by month:

        <?php wp_get_archives('type=monthly'); ?>

Browse by category:

         <?php wp_list_categories(); ?>

Browse by tags:

         <?php wp_tag_cloud(','); ?>

<?php get_sidebar(); ?>
<?php get_footer(); ?>


text:
Q: How can I configure Xwayland (to set NoTrapSignals to the correct value) I have created /etc/X11/xorg.conf.
Section "ServerFlags"
    Option "NoTrapSignals" "true"
EndSection

It successfully affects my GNOME session if I start a GNOME session which uses X and not Wayland.  I have checked this by killing the X server with SIGABRT, and verifying that it does not try to print it's own backtrace by catching the signal.
However the config file doesn't have the effect I really wanted, which is to achieve the same behaviour for the Xwayland instance, which GNOME starts when I start a normal GNOME session with Wayland.
I can't even find the log messages from Xwayland, to see if it mentions anything about where it reads configuration from!
I notice Xorg has a man page, but Xwayland does not.  None of the options Xwayland is running with (-rootless -terminate -core -listen 4 -listen 5 -displayfd 6) are documented in man Xorg, though to be fair GNOME also passes -displayfd to Xorg when running a native X session.
Does anyone know how to do this?
Environment

*

*Fedora 27

*GNOME

*gnome-session-3.26.1-1.fc27.x86_64

*xorg-x11-server-Xwayland-1.19.6-5.fc27.x86_64

Context
I have an annoying XWayland crash.  I'm having difficulty understanding it from the core dump my system saves.  I desperately want to disable the built-in X backtrace generator.  It's just getting in the way, the backtrace generator itself is vulnerable to crashes, and most importantly by catching the error signal, I believe it stops Linux from logging the exact cause of the SIGBUS error in the kernel log.
I say this is the correct value for NoTrapSignals, because it's an inherently fragile feature, and AFAICT it's pointless in an unprivileged Xwayland server.  It's not like the bad old days of user mode setting, where the kernel couldn't reset the display to text mode, so you desperately hoped the X server would still be able to do so if it crashed.

A:
I say this is the correct value for NoTrapSignals, because it's an inherently fragile feature, and AFAICT it's pointless in an unprivileged Xwayland server. It's not like the bad old days of user mode setting, where the kernel couldn't reset the display to text mode, so you desperately hoped the X server would still be able to do so if it crashed.

If that's right, the answer is that this is a bug in Xwayland, and Xwayland should be fixed to behave correctly without needing some config file.

Comparing attempts to run Xorg and Xwayland under strace, suggests that Xwayland does not look for any configuration file, only XKB data files.
Both /usr/libexec/Xorg and /usr/bin/Xwayland will print usage advice, if you pass --help as an option.  Xorg includes a section "Device Dependent Usage" with options to set the logfile or config file.  Xwayland mentions none of these.  So Xwayland does not appear to be configurable like Xorg is.
Technically Xwayland seems to get run with -core "generate core dump on fatal error".  Xorg does not, though it claims to support the same option.  From the evidence so far it feels like this is irrelevant though, particularly since NoTrapSignals does not affect whether or not a core dump is generated.

Option "NoTrapSignals" "boolean"
This prevents the Xorg server from trapping a range of unexpected fatal signals and exiting cleanly. Instead, the Xorg server will die and drop core where the fault occurred. The default behaviour is for the Xorg server to exit cleanly, but still drop a core file. In general you never want to use this option unless you are debugging an Xorg server problem and know how to deal with the consequences.


text:
Q: Passing SWI-Prolog Query from Java Program I have a Query generated by my Java Program in Query Variable. I want to send this to SWI-Prolog to get the solution of this. The following shows the subcode I wrote in Java to communicate with SWI-Prolog.
  Process P= new ProcessBuilder("C:\\Program Files\\swipl\\bin\\swipl-win.exe").start();
        BufferedReader processOutput = new BufferedReader(new InputStreamReader(P.getInputStream()));
        BufferedWriter processInput = new BufferedWriter(new OutputStreamWriter(P.getOutputStream()));

        String commandToSend = Query;
         processInput.write(commandToSend);

But the SWI-Prolog Window opens up but the comand I am writing to ProcessInput is not being sent to SWI-Prolog. Can someoe suggest me the best way to do this? I need the output of the Query Execution from SWI-Prolog in a File as well.

A: Save your query to external text file and execute swipl from command line (with appropriate options set) and redirect output to another text file. Then, read that output file.
Example:

*

*Save your query to QUERY.TXT as :- query.

*Run swipl with redirection to OUTPUT.TXT: swipl -s QUERY.TXT -g halt --quiet > OUTPUT.TXT

*Read contents of OUTPUT.TXT

Also, I suspect you should use combination of Runtime.getRuntime().exec(...) and waitFor(...) to wait for swipl for generating output.


text:
Q: Calculate churn rate using a query instead of a stored procedure I am writing queries for some KPIs (Key Performance Indicators) to track user engagement. One such KPI is "Churn Rate", which I am calculating for a given month by:
Churn rate = (Total users deleted in month)/(Total users on the 1st of month)
I am using a users table with the following columns:
created_at, deleted_at
My process is to get all relevant months of user activity (in this case, based on "created_at" column, since we are getting several new users per month. We also have an activity log table which might technically be more accurate to use but doesn't go back as far) and then loop over them in a stored procedure. For each month, I'm calculating who was deleted that month and who was active on the first of that month (created on or before the 1st of the month and either not deleted or deleted after the first of that month). Then I'm dividing them to find churn rate and inserting into a temporary table. Here is my stored procedure:
DROP PROCEDURE ChurnRate;

DELIMITER $$
CREATE PROCEDURE ChurnRate()
BEGIN
    DECLARE start_date  DATETIME;
    DECLARE end_date  DATETIME;
    DECLARE cur_date DATETIME;
    DECLARE current_month VARCHAR(255);
    DECLARE end_month VARCHAR(255);
    DECLARE deleted_count BIGINT;
    DECLARE active_user_count BIGINT;
    DECLARE churn_rate FLOAT;

    SELECT created_at FROM users ORDER BY created_at ASC LIMIT 1 INTO start_date;
    SELECT created_at FROM users ORDER BY created_at DESC LIMIT 1 INTO end_date;
    SET cur_date = start_date;
    SET current_month = SUBSTR(cur_date,1,7);
    SET end_month = SUBSTR(end_date,1,7);
    DROP TEMPORARY TABLE IF EXISTS churn_table;
    CREATE TEMPORARY TABLE churn_table
    (
        user_month VARCHAR(255),
        deleted_count BIGINT,
        active_user_count BIGINT,
        churn_rate FLOAT
    );

loop_label:  LOOP
        SELECT COUNT(U.id) FROM users AS U WHERE SUBSTR(U.deleted_at,1,7) = current_month INTO deleted_count;
        SELECT COUNT(U.id) FROM users AS U
            WHERE (U.deleted_at >= DATE_ADD(DATE_ADD(LAST_DAY(cur_date),INTERVAL 1 DAY),INTERVAL -1 MONTH) OR U.deleted_at IS NULL)
            AND SUBSTR(U.created_at,1,7) <= current_month
            INTO active_user_count;
        INSERT INTO churn_table (user_month, deleted_count, active_user_count, churn_rate) VALUES (current_month, deleted_count, active_user_count, (deleted_count/active_user_count));
        SET cur_date = DATE_ADD(cur_date, INTERVAL 1 MONTH);
        SET current_month = SUBSTR(cur_date,1,7);
        IF current_month <= end_month THEN
            ITERATE  loop_label;
        END  IF;
        LEAVE loop_label;
    END LOOP;
    SELECT * FROM churn_table;
END$$

DELIMITER ;

CALL ChurnRate();

Here is a sample of some data that was produced:

user_month
churn_rate_percentage

2019-12
0

2020-01
0.0396982

2020-02
0

2020-03
0

2020-04
0

2020-05
0.112116

2020-06
0.59691

2020-07
0.26689

2020-08
0.144374

2020-09
0.141767

2020-10
0.125

2020-11
0.272904

2020-12
0.14937

My problem is this: I am using an API that requires this to be a select query. I have previously tried writing select queries for this, but they have been flawed. Grouping by "deleted_at" will not work because we will not show months for which no users have been deleted. Grouping by "created_at" and using subqueries ends up being extremely slow, as we have about 50k users. Is there a clean, efficient way to write this as a select query without affecting performance?
If there is not, I will have to write a chron to run this procedure and export the data.
Thank you

A: You shouldn't use loops in SQL that is often an indication you are doing something wrong.
Here is how to do this in a single query:
-- recursive CTE to create list of months of interest
with RECURSIVE base_months(d,y,m) AS
(
   SELECT DateSerial(Year(min(create_at)), Month(min(create_at)), "1"),
          min(create_at) , year(min(create_at)) , month(min(create_at))
   FROM users
 UNION ALL
   SELECT data_add(d INTERVAL 1 MONTH)  , year(data_add(d INTERVAL 1 MONTH)) , month(data_add(d INTERVAL 1 MONTH))
   FROM base_months
   WHERE YEAR(d) <= YEAR(CURDATE()) && MONTH(d) <= MONTH(CURDATE())
)
select
  b.y as year,
  b.m as month,
  count(u.created_at) as total_user
  sum(case when month(u.deleted_at) = b.m and year(u.deleted_at = b.y) then 1 else 0 end) as left_this_month
from base_months b
-- for each month join to the users table
join user u on u.created_at < b.d and (u.deleted_at > b.d or u.deleted_at is null)
group by b.y, b.m

If this isn't clear, first we use a recursive CTE to get all the months and years of interest -- you could do a non-recursive query on the table with a group by if only want to include create date months that are in the table -- but I think that would give you interesting results since months that don't have anyone created in that month would not be included.
Then I join that back to the users table with filters on the join to only include the rows we want to count for the given year and month.  We use group by and aggregation functions to find the results.

A: Looping is likely to be terribly slow.
Is this how you decide if a user exists on Nov 1, 2020?
WHERE created_at < '2020-11'
  AND deleted_at > '2020-11'

Hence, a COUNT(*) with that test would give that count?
For deletions for that month:
WHERE LEFT(deleted_at, 7) = '2020-11'

Putting those together into a single query or all months:
SELECT  LEFT(created_at, 7) AS yyyymm,
        ( SELECT COUNT(*)
              FROM users
              WHERE created_at < yyyymm
                AND deleted_at > yyyymm
        ) AS new_users,
        ( SELECT COUNT(*)
              FROM users
              WHERE deleted_at >= yyyymm
                AND deleted_at  < CONCAT(yyyymm, '-01')
        ) AS deleted_users
    FROM users
    GROUP BY yyyymm
    ORDER BY yyyymm

That gives you 3 columns; check it out.  To get the churn:
SELECT LEFT(created_at, 7) AS yyyymm,
       ( SELECT ... ) / ( SELECT ... ) AS churn
    FROM users
    GROUP BY yyyymm
    ORDER BY yyyymm


text:
Q: repaint() fails to work I wanted to draw an image on my panel based on the data I receive from another thread. I am  sure the data and consequent pixel array works well, but the repaint() would never work. Can anyone tell me what's going wrong here?
import javax.swing.*;
import java.awt.*;
import java.awt.image.*;

/** Create an image from a pixel array. **/
public class PicturePlaza extends JApplet
{
  ImagePanel fImagePanel;
  ReadCom   readComPort;
  Thread readPortThread;

  public void init () {
    // initiate the read port thread so that it can receive data
     readComPort = new ReadCom();
     readPortThread = new Thread(readComPort,"ReadCom");
     readPortThread.start();

     Container content_pane = getContentPane ();
     fImagePanel = new ImagePanel ();
     content_pane.add (fImagePanel);

  }

  // Tell the panel to create and display the image, if pixel data is ready.
  public void start () {
      while(true){
          if(readComPort.newPic){
              fImagePanel.go();
          }
          try {
                    Thread.sleep(4000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
      }
  }

/** Create an image from a pixel array. **/
  class ImagePanel extends JPanel{
      Image fImage;
      int fWidth = ReadCom.row, fHeight = ReadCom.col;

      void go() {
                    //update the image if newPic flag is set to true
                    fImage = createImage (new MemoryImageSource (fWidth, fHeight, ReadCom.fpixel, 0, fWidth));
                    repaint();
                    readComPort.newPic = false; //disable the flag, indicating the image pixel has been used
      }

      /** Paint the image on the panel. **/
      public void paintComponent (Graphics g) {
        super.paintComponent (g);
        g.drawImage (fImage, 0, 0, this );
      }
  }
}

Thanks

A: Just a little note on repaint().  repaint() schedules a repaint of the screen, it won't always do it immediately in my experience.  I found the best solution is to directly call paint() yourself.
Graphics g;
g = getGraphics();
paint(g);

I put this as a new function to call in my code when I wanted it to paint immediately.  Also this will not erase the previous graphics on the screen, you will have to do that manually.

A: Try repaint(); and then validate(); in your Applet (PicturePlaza).


text:
Q: How can I perform a union with two single-field Matlab structs I currently have two single-field Matlab structs that list image names. I would like to combine them into a single struct with no duplicates - i.e.
a(1).img = 'aa.jpg'
a(2).img = 'bb.jpg'

b(1).img = 'bb.jpg'
b(2).img = 'cc.jpg'

I would like for ab to have value(s):
ab(1) = 'aa.jpg'
ab(2) = 'bb.jpg'
ab(3) = 'cc.jpg'

Is there a non=brute force way of doing this?

A: You can concatenate the values from each of the structs using a comma-separated list followed by unique to get the unique values. Then, passing this to the struct function will create an array of structs containing the values.
S = struct('img', unique({a.img, b.img}, 'stable'))

If you don't actually need a struct out and just want a cell array of the unique values, you can eliminate the final call to struct.
unique({a.img, b.img}, 'stable')


text:
Q: Do spaces with equivalent fundamental group share the same Universal Cover Just the question above. I have not been able to find a clear answer for this.
I am leaning towards yes but want to be sure.

A: $S^1$ has fundamental group $\mathbb Z$, and universal cover $\mathbb R$.
$S^1\times[0,1]$ also has fundamental group $\mathbb Z$, and has universal cover $\mathbb R\times[0,1]$.

Answer to the follow-up: Not all simply connected spaces (these have trivial fundamental group and are its own universal cover) are homotopy-equivalent: $S^2$ and $[0,1]$.


text:
Q: Best way to get all substrings matching a RegExp in Dart I want to get a list of substrings matching a RegExp in a string. What is the best way to do this?
RegExp object from dart:core has Iterable<Match> allMatches(String input, [int start=0]) method. This is kind of what I need, but I want to get Iterable of Strings, not matches.
There is also method String stringMatch(String input), which returns a String, but only a first match.
So I wrote myslef this function using map:
Iterable<String> _allStringMatches(String text, RegExp regExp) {
  Iterable<Match> matches = regExp.allMatches(text);
  List<Match> listOfMatches = matches.toList();

  // TODO: there must be a better way to get list of Strings out of list of Matches
  Iterable<String> listOfStringMatches = listOfMatches.map((Match m) {
    return m.input.substring(m.start, m.end);
  });

  return listOfStringMatches;
}

but it seems to me that it is pretty basic functionality and I can't believe it is not in anywhere in the API. I guess there must be a better way to do such a basic task.

A: If your regexp contains only one group (like new RegExp(r'(\S+)')) you can rewrite your function to:
Iterable<String> _allStringMatches(String text, RegExp regExp) =>
    regExp.allMatches(text).map((m) => m.group(0));


text:
Q: Is it possible to conditionally serialize CDATA? I have seen the solution to get XmlSerializer to output a CDATA section, but is it then possible to conditionally achieve this, based on another value?
The following code demonstrates the result I want:
enum LogItemType
{
   Default,
   Xml
}

class LogItem
{
   public string Name { get; set; }
   public LogItemType Type { get; set; }
   [XmlIgnore]
   public string Value { get; set; }
   public XmlCDataSection ValueString
   {
      if(Type == LogItemType.Xml)
         // return CDATA
      else
         // return string (not CDATA)
   }
}

A: Change the return type of your ValueString property to XmlCharacterData, which is the base class for XmlText and XmlCDataSection.  Then return one or the other depending on the state of your Type property:
public class LogItem
{
    public string Name { get; set; }
    public LogItemType Type { get; set; }

    [XmlIgnore]
    public string Value { get; set; }

    [XmlElement("Value")]
    [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
    public XmlCharacterData ValueString
    {
        get
        {
            if (Value == null)
                return null;
            else if (Type == LogItemType.Xml)
                // return CDATA
                return new XmlDocument().CreateCDataSection(Value);
            else
                // return string (not CDATA)
                return new XmlDocument().CreateTextNode(Value);
        }
        set
        {
            Value = value == null ? null : value.Value;
        }
    }
}

The output will be either:

<LogItem>
    <Name>test</Name>
    <Type>Default</Type>
    <Value>this is a test string</Value>
</LogItem>

or

<LogItem>
    <Name>test</Name>
    <Type>Xml</Type>
    <Value><![CDATA[this is a test string]]></Value>
</LogItem>

Alternatively, if you want your Value text to be the value of the LogItem itself (rather than the value of a nested element) you can do:
    [XmlText]
    [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
    public XmlNode [] ValueString
    {
        get
        {
            if (Value == null)
                return null;
            else if (Type == LogItemType.Xml)
                // return CDATA
                return new XmlNode[] { new XmlDocument().CreateCDataSection(Value) };
            else
                // return string (not CDATA)
                return new XmlNode[] { new XmlDocument().CreateTextNode(Value) };
        }
        set
        {
            Value = value == null ? null : string.Concat(value.Select(n => n.Value).ToArray());
        }
    }

(Note that an array is returned not a single item.  XmlSerializer seems to require this.)


text:
Q: Get some sort of notification on certain events in public channel I'm on a telegram group of wich I'm not admin. In that particular channel, there are lots of messages and "useless" information. I want to make something so when someone in the group says a particular word, I'll get a notification (maybe a private msg?). I've searched but other answers mention the bot API, but, as far as I have found, bots can't be added to groups without being admin, not even with the invitation link. How can I access the messages of the group to process them?

A: As you said, bots can't get message in channel without administrator permission, and they can't join group by themselves.
If you want to get all messages in group, please disable privacy mode via /setprivacy in @BotFather, and re-invite to group.


text:
Q: Difference between "Present Simple" and "Present Perfect"
I'm really upset. My dress is torn.
I'm really upset. My dress has been torn.

I think these sentences mean the same. But in the active voice, they don't.

I'm really upset. I tear my dress.
I'm really upset. I have torn my dress.

According to English grammar rules, the present simple tense expresses general ideas.
Why do they mean the same in the passive voice?

A: Short answer:

I'm really upset. My dress is torn

will not usually be read as a passive construction, with torn as the past participle of tear. It will normally be read as a sentence that uses the adjective tear as a subject complement of my dress–similar to My dress is new.
If this answers your question, I'm glad. If this does not answer your question, I'm not sure what you're asking.
Long answer:
I think your question is
Since in the active voice the simple present refers to a general truth, as opposed to the present perfect, which refers to a specific action; why, then, does this not apply to the passive forms?
My answer is that this  does apply to the passive forms.
But you have to make sure you are looking at passive forms to see that it does. Let's start with the active voice:

I'm really upset. I have torn my dress.

This states your emotion after the specific action of tearing your dress.

I'm really upset. I tear my dress.

In the context of reporting your present emotion, I tear my dress does not usually refer to a specific action. It could if it was a case of the "demonstration present"  or "running commentary" present, when you can use the simple present instead of the present progressive to report what you are doing right this moment. But this is a special usage of the present tense.
So, one can take the meaning of I tear my dress here as referring not to a specific action, but to a general truth, especially in the sense of a repeated or habitual action. This is clearer if we join the two sentences:

I'm really upset when(ever) I tear my dress.

Here, now it's also clear that I'm really upset also does not report on one's present emotion but states a general truth. A caveat to this is that you can say this statement as a statement of  general truth when you are experiencing one instance (occurrence) of this general truth, that is, of tearing your dress.
Now, for the passive voice (or passive constructions).

I'm really upset. My dress is torn.

This sentence can be read as a passive construction; but it doesn't have to be.
In fact, without an agent stated with by, this sentence would usually be interpreted as using torn as an adjective (not as the passive form of tear).
In this case, the two sentences report your present emotion at/over the current state of your dress. Here

My dress is torn

works like

My dress is new.

Both torn and new are adjectives, acting as subject complements.
To make it clear that My dress is torn is a passive construction, you could state an agent, as in

I'm really upset. My dress is torn by the dog.

Now, you are in the same situation as the active construction. And this can be taken as a general truth:

I'm really upset when(ever) my dress is torn by the dog.

But without an agent stated, and without any  context My dress is torn is unlikely to be interpreted as a passive construction.
As for the present perfect passive

I'm really upset. My dress has been torn.

The most  natural way to read this  is as a passive. When you do this, this is not stating a general truth but reporting your present emotion about the specific past action of your dress having been torn by an unstated agent. Again, you could make the agent explicit by adding by the dog.
But, again, you could use the two sentences to report a general truth if you combined them:

I'm really upset when(ever) my dress has been torn.