text:
Q: spring-mvc CassandraTemplate NoClassDefFoundError I have some troubles with my pom.xml while working with spring-data-cassandra.
My pom.xml looks like -
<properties>
        <java-version>1.6</java-version>
        <org.springframework-version>3.1.1.RELEASE</org.springframework-version>
        <org.aspectj-version>1.6.10</org.aspectj-version>
        <org.slf4j-version>1.6.6</org.slf4j-version>
    </properties>
    <dependencies>
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${org.springframework-version}</version>
            <exclusions>
                <!-- Exclude Commons Logging in favor of SLF4j -->
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>

        <!-- Cassandra -->

        <dependency>
            <groupId>org.apache.cassandra</groupId>
            <artifactId>cassandra-all</artifactId>
            <version>2.2.3</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-cassandra</artifactId>
            <version>1.3.0.RELEASE</version>
        </dependency>

My main controller class is something like below -
public String insertEmp(Locale locale, Model model, @ModelAttribute Employee emp) {
    logger.info("Create method in home controller", locale);

    String serverIP = "127.0.0.1";
    String keyspace = "jetset";

    Cluster cluster = Cluster.builder()
      .addContactPoints(serverIP)
      .build();

    Session session = cluster.connect(keyspace);

    CassandraOperations cassandraTemplate = new CassandraTemplate(session);

    model.addAttribute("serverTime", "Test" );
    //employeeService.createEmployee(emp);
    cassandraTemplate.insert(emp);

    return "admin/index";
}

Now when i am running the program i am getting below error -
Caused by: java.lang.NoClassDefFoundError: org/springframework/core/DefaultParameterNameDiscoverer
    at org.springframework.data.mapping.model.PreferredConstructorDiscoverer.<init>(PreferredConstructorDiscoverer.java:38) ~[spring-data-commons-1.11.0.RELEASE.jar:na]
    at org.springframework.data.mapping.model.BasicPersistentEntity.<init>(BasicPersistentEntity.java:92) ~[spring-data-commons-1.11.0.RELEASE.jar:na]
    at org.springframework.data.cassandra.mapping.BasicCassandraPersistentEntity.<init>(BasicCassandraPersistentEntity.java:83) ~[spring-data-cassandra-1.3.0.RELEASE.jar:na]
    at org.springframework.data.cassandra.mapping.BasicCassandraMappingContext.createPersistentEntity(BasicCassandraMappingContext.java:123) ~[spring-data-cassandra-1.3.0.RELEASE.jar:na]
    at org.springframework.data.cassandra.mapping.BasicCassandraMappingContext.createPersistentEntity(BasicCassandraMappingContext.java:54) ~[spring-data-cassandra-1.3.0.RELEASE.jar:na]
    at org.springframework.data.mapping.context.AbstractMappingContext.addPersistentEntity(AbstractMappingContext.java:299) ~[spring-data-commons-1.11.0.RELEASE.jar:na]
    at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentEntity(AbstractMappingContext.java:179) ~[spring-data-commons-1.11.0.RELEASE.jar:na]
    at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentEntity(AbstractMappingContext.java:139) ~[spring-data-commons-1.11.0.RELEASE.jar:na]
    at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentEntity(AbstractMappingContext.java:66) ~[spring-data-commons-1.11.0.RELEASE.jar:na]
    at org.springframework.data.cassandra.core.CassandraTemplate.getTableName(CassandraTemplate.java:217) ~[spring-data-cassandra-1.3.0.RELEASE.jar:na]
    at org.springframework.data.cassandra.core.CassandraTemplate.doInsert(CassandraTemplate.java:641) ~[spring-data-cassandra-1.3.0.RELEASE.jar:na]
    at org.springframework.data.cassandra.core.CassandraTemplate.insert(CassandraTemplate.java:237) ~[spring-data-cassandra-1.3.0.RELEASE.jar:na]
    at org.springframework.data.cassandra.core.CassandraTemplate.insert(CassandraTemplate.java:232) ~[spring-data-cassandra-1.3.0.RELEASE.jar:na]
    at org.jetset.estate.HomeController.insertEmp(HomeController.java:91) ~[classes/:na]

This looks like a pom issue, but i am not able to figure it out.
Please suggest.
Thanks.
AJ

A: Ok, got it fixed.
I was choosing wrong spring distribution with spring-data-cassandra.
Switched to spring 3.2.8 and cassandra to 1.0.0 and issue was fixed.
Hope this helps some one else as well.


text:
Q: How to shrink git pack file I have git repo with android app and It looks like one of developers didn't gitignore correctly so .apk files were committed and repo became huge (repo is ~300Mb, app size is ~30Mb).
I deleted some garbage:
git filter-branch --index-filter 'git rm --cached --ignore-unmatch ./app/release/app-release.apk' --tag-name-filter cat -- --all

git filter-branch --index-filter 'git rm --cached --ignore-unmatch ./app/build/outputs/apk/debug/app-debug.apk' --tag-name-filter cat -- --all

Repo size became smaller, it's 200Mb now,
but when I'm searching for big commits:
git verify-pack -v .git/objects/pack/pack-*.idx | sort -k 3 -n | tail -20

I still see commits which contain .apk files, but I can't even checkout those commits:

So the question is how can I shrink that pack file?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Early Google Drive access to test applications? I would like to add Google Drive integration to an application immediately.  Is there a means to create or access some type of test account?
I have requested Google Drive on both my personal and application Google accounts, both of these requests appear to have been wait-listed.
The application Google account has both the Drive API and Drive SDK services enabled for this application, and the Drive SDK section has been configured.
Might there be a way I can gain immediate access as a developer?

A: There's no early Google Drive access for developers, but requests are being approved as we speak, so it shouldn't take long.

A: If you have an apps account, it is immediate. It worked for me. I think they are rolling out to gmail accounts at a later stage.

A: I can't say for sure, but you may get access faster if you pay to upgrade your storage to 25GB. I've gotten access to Google Drive two hours after I bought the storage upgrade.


text:
Q: Is python assignment strictly evaluated right to left? In other words is
d = {}
d["key"] = len(d)

safe in Python?
I know this is undefined behaviour in C++; where the program might get a reference to the element before computing the value it's going to assign to it. Is this similar in Python or is len(d) always computed before d.__getitem__("key")?

A: Yes, in Python it is safe: the evaluation order of an expression is from left to right, but in an assignment statement the right side is evaluated before the assignment happens. Also an arithmetic expression is evaluated in the arithmetic order of their suffixes.
5.14. Evaluation order

Python evaluates expressions from left to right. Notice that while
  evaluating an assignment, the right-hand side is evaluated before the
  left-hand side.
In the following lines, expressions will be evaluated in the
  arithmetic order of their suffixes:

A: Yes, the RHS of an assignment is evaluated before the LHS; this is the case whether the LHS is an attribute reference, a subscription or a slicing.
From https://docs.python.org/3/reference/simple_stmts.html#assignment-statements:

An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right.

The succeeding language in the section discusses how assignment to different target syntaxes are defined, but does so from the standpoint that the expression list has already been evaluated to yield an object.
Indeed, the order of evaluation within the LHS is also defined; the container is evaluated before the subscript:

*

*If the target is a subscription: The primary expression in the reference is evaluated. It should yield either a mutable sequence object (such as a list) or a mapping object (such as a dictionary). Next, the subscript expression is evaluated.


text:
Q: Comparing predictiveness of alternative class definitions using linear regression I am comparing highly-correlated ways to classify patients as sick (1) or well (0). I want to see whether the way you define sickness impacts how well sickness predicts clinical outcomes.
I have built a linear regression model for each definition of sick to predict a continuous clinical outcome. I would like to determine whether the regression coefficient from each of the models is statistically significantly different from that of each of the other models, in a pair-wise fashion. For example, suppose using definition A leads to a larger positive coefficient than using definition B. This suggests that sickness is a stronger predictor of the outcome under definition A than under definition B. I want to be able to assess the whether this increase in ability to predict the outcome under definition A is statistically significant. [Edit- note that I am not interested in comparing the fit of the regressions, but rather the size of the coefficient]
I have defined a 95% confidence interval around each of the coefficients (with lower and upper bounds set to the standard error times qnorm(.025), so one strategy is to just consider any coefficients with overlapping confidence intervals to not be statistically-significantly different. However, I have two concerns:

*

*I'm not sure how rigorous this is even in the case of a single comparison, and

*I'd like to correct for multiple comparisons, and the methods I know to do this require comparing p-values, not confidence intervals.

Here are some dummy data:
df <- data.frame("defA"=c(0,0,0,0,1,1,1,1,1,1),
             "defB"=c(0,0,0,1,0,1,0,1,1,1),
             "defC" =c(0,1,0,0,0,1,1,0,1,1),
             "outcome"=c(0,2,1,4,2,8,7,9,10,9))
lm.a <- lm(outcome~defA, data=df)
lm.b <- lm(outcome~defB, data=df)
lm.c <- lm(outcome~defC, data=df)

Here's how I calculated the confidence intervals:
coefA <- summary(lm.a)$coefficients["defA",1]
lowboundA <- summary(lm.a)$coefficients["defA",1] + summary(lm.a)$coefficients["defA",2]*qnorm(.025)
upboundA <- summary(lm.a)$coefficients["defA",1] + summary(lm.a)$coefficients["defA",2]*qnorm(.975)


text:
Q: Having trouble understanding this context in Array.map callback I have the following snippet in a React component. This is a trivial example, but I'm trying to better my understanding of the this keyword and its context
const NAVBAR_ITEM_TITLES = ["Home", "About", "Contact"];

function makeNavbarItems() {
  return NAVBAR_ITEM_TITLES.map(item => ({
    title: item,
    handleButtonClick() {
      console.log(`clicked the ${this.title} button`);
    },
  }));
}

const Navbar = () => {
  const navbarItems = makeNavbarItems();

  return (
    <>
      {navbarItems.map(item => (
        <div>
          <button key={item.title} onClick={item.handleButtonClick}>
            {item.title}
          </button>
        </div>
      ))}
    </>
  );
};

I wrote  a small function that returns some anonymous objects to populate a navbar. However, the this context inside the anonymous object that map returns is undefined. I understand that if I create a named object like myObj then I may access the title property such as myObj.title, but I'd like to gain understanding of what I'm doing wrong and how to fix it.
Cheers.

A: You already have access to the item string, which you're aliasing it as title: there is no need to use this at all:
function makeNavbarItems() {
  return NAVBAR_ITEM_TITLES.map(item => ({
    title: item,
    handleButtonClick() {
      console.log(`clicked the ${item} button`);
    },
  }));
}

A: this always refer to the object in the current context, and in this case, the new object you are creating with your prototype. As @Terry said, it's not really necessary here. In some case, you will need this to differentiate between two expression with the same name but on different scope. (e.g. A global variable and a local one of the same name).


text:
Q: My flutter app doesn't connect to the internet when is on private network (vpn) I'm making an App for my company and I need it to work on a private network (VPN) but when I'm on VPN it doesn't work, tried to print the result witch should give me a json instead gives me this "

401 - Unauthorized: Access is denied due to invalid
  credentials.

", but if I change the URL to "[https://randomuser.me/api/?results=15][1]" I get the data with no problem.
I tried to check connectivity when I'm on VPN and gives me result none.
...
class _MyHomePageState extends State<MyHomePage> {

  var _connection = 'Unknown';
  Connectivity connectivity;
  StreamSubscription<ConnectivityResult> subscription;

  String url = 'myUrl';
  List data;

  Future<String> makeRequest() async {
    var response = await http
        .post(url, headers: {'Accept': 'application/json'});

  print('________________________________________________________________________^^^^ '+ response.body );
    setState(() {
      var extractdata = json.decode(response.body);
      //data = extractdata;
      //print( data[0]["name"]["first"]);
    });

  }

  @override
  void initState() {
    super.initState();
    connectivity = new Connectivity();
    subscription = connectivity.onConnectivityChanged.listen( (ConnectivityResult result){print('RESULT');print(result);});
    this.makeRequest();
  }

  @override
  void dispose(){
    subscription.cancel();
    super.dispose();
  }
...

this is the console result
Performing hot restart...
Syncing files to device SM J500FN...
Restarted application in 5 173ms.
I/flutter (16502): RESULT
I/flutter (16502): ConnectivityResult.none
I/flutter (16502): ________________________________________________________________________^^^^ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
I/flutter (16502): <html xmlns="http://www.w3.org/1999/xhtml">
I/flutter (16502): <head>
I/flutter (16502): <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
I/flutter (16502): <title>401 - Unauthorized: Access is denied due to invalid credentials.</title>
I/flutter (16502): <style type="text/css">
I/flutter (16502): <!--
I/flutter (16502): body{margin:0;font-size:.7em;font-family:Verdana, Arial, Helvetica, sans-serif;background:#EEEEEE;}
I/flutter (16502): fieldset{padding:0 15px 10px 15px;}
I/flutter (16502): h1{font-size:2.4em;margin:0;color:#FFF;}
I/flutter (16502): h2{font-size:1.7em;margin:0;color:#CC0000;}
I/flutter (16502): h3{font-size:1.2em;margin:10px 0 0 0;color:#000000;}
I/flutter (16502): #header{width:96%;margin:0 0 0 0;padding:6px 2% 6px 2%;font-family:"trebuchet MS", Verdana, sans-serif;color:#FFF;
I/flutter (16502): background-color:#555555;}
I/flutter (16502): #content{margin:0 0 0 2%;position:relative;}
I/flutter (16502): .content-container{background:#FFF;width:96%;margin-top:8px;padding:10px;position:relative;}
I/flutter (16502): -->
I/flutter (16502): </style>
I/flutter (16502): </head>
I/flutter (16502): <body
E/flutter (16502): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: FormatException: Unexpected character (at character 1)
E/flutter (16502): <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org...
E/flutter (16502): ^
E/flutter (16502):
E/flutter (16502): #0      _ChunkedJsonParser.fail (dart:convert/runtime/libconvert_patch.dart:1357:5)
E/flutter (16502): #1      _ChunkedJsonParser.parseNumber (dart:convert/runtime/libconvert_patch.dart:1253:9)
E/flutter (16502): #2      _ChunkedJsonParser.parse (dart:convert/runtime/libconvert_patch.dart:921:22)
E/flutter (16502): #3      _parseJson (dart:convert/runtime/libconvert_patch.dart:29:10)
E/flutter (16502): #4      JsonDecoder.convert (dart:convert/json.dart:491:36)
E/flutter (16502): #5      JsonCodec.decode (dart:convert/json.dart:149:41)
E/flutter (16502): #6      _MyHomePageState.makeRequest.<anonymous closure> (package:doi_report/homepage.dart:30:30)
E/flutter (16502): #7      State.setState (package:flutter/src/widgets/framework.dart:1122:30)
E/flutter (16502): #8      _MyHomePageState.makeRequest (package:doi_report/homepage.dart:29:5)
E/flutter (16502): <asynchronous suspension>
E/flutter (16502): #9      _MyHomePageState.initState (package:doi_report/homepage.dart:42:10)
E/flutter (16502): #10     StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:3846:58)
E/flutter (16502): #11     ComponentElement.mount (package:flutter/src/widgets/framework.dart:3711:5)
E/flutter (16502): #12     Element.inflateWidget (package:flutter/src/widgets/framework.dart:2956:14)
E/flutter (16502): #13     Element.updateChild (package:flutter/src/widgets/framework.dart:2759:12)
E/flutter (16502): #14     SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:4876:14)
E/flutter (16502): #15     Element.inflateWidget (package:flutter/src/widgets/framework.dart:2956:14)
E/flutter (16502): #16     Element.updateChild (package:flutter/src/widgets/framework.dart:2759:12)
E/flutter (16502): #17     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3747:16)
E/flutter (16502): #18     Element.rebuild (package:flutter/src/widgets/framework.dart:3559:5)
E/flutter (16502): #19     ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:3716:5)
E/flutter (16502): #20     ComponentElement.mount (package:flutter/src/widgets/framework.dart:3711:5)
E/flutter (16502): #21     Element.inflateWidget (package:flutter/src/widgets/framework.dart:2956:14)
E/flutter (16502): #22     Element.updateChild (package:flutter/src/widgets/framework.dart:2759:12)
E/flutter (16502): #23     SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:4876:14)
E/flutter (16502): #24     Element.inflateWidget (package:flutter/src/widgets/framework.dart:2956:14)
E/flutter (16502): #25     Element.updateChild (package:flutter/src/widgets/framework.dart:2759:12)
E/flutter (16502): #26     SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:4876:14)
E/flutter (16502): #27     Element.inflateWidget (package:flutter/src/widgets/framework.dart:2956:14)
E/flutter (16502): #28     Element.updateChild (package:flutter/src/widgets/framework.dart:2759:12)
E/flutter (16502): #29     SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:4876:14)
E/flutter (16502): #30     Element.inflateWidget (package:flutter/src/widgets/framework.dart:2956:14)
E/flutter (16502): #31     Element.updateChild (package:flutter/src/widgets/framework.dart:2759:12)
E/flutter (16502): #32     SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:4876:14)
E/flutter (16502): #33     Element.inflateWidget (package:flutter/src/widgets/framework.dart:2956:14)
E/flutter (16502): #34     Element.updateChild (package:flutter/src/widgets/framework.dart:2759:12)
E/flutter (16502): #35     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3747:16)
E/flutter (16502): #36     Element.rebuild (package:flutter/src/widgets/framework.dart:3559:5)
E/flutter (16502): #37     ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:3716:5)
E/flutter (16502): #38     StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:3864:11)
E/flutter (16502): #39     ComponentElement.mount (package:flutter/src/widgets/framework.dart:3711:5)
E/flutter (16502): #40     Element.inflateWidget (package:flutter/src/widgets/framework.dart:2956:14)
E/flutter (16502): #41     Element.updateChild (package:flutter/src/widgets/framework.dart:2759:12)
E/flutter (16502): #42     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3747:16)
E/flutter (16502): #43     Element.rebuild (package:flutter/src/widgets/framework.dart:3559:5)
E/flutter (16502): #44     ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:3716:5)
E/flutter (16502): #45     ComponentElement.mount (package:flutter/src/widgets/```

A: The problem was in the server type of authentication, I had windows authentication enable and that was the problem not allowing for my app to reach the data I wanted to retrieve from a php file. although I must say that checking the connectivity and when I was on vpn the result was none made me think that the problem was in the app and not in the server.
it's working with windows authentication disabled but the result of checkconnection is still none.


text:
Q: libraries to plot topological data analysis persistence diagrams, complexes, and barcodes I am starting to do some Topological Data Analysis and am looking for a good plotting library to produce the diagrams of complexes, barcodes, and persistence diagrams. The most popular TDA libraries like DIPHA, GUDHI, and others can computer the information for barcodes and other summaries, but don't seem to have plotting capabilities to visualize these summaries. I think that the R TDA package has plotting capabilities, but I think this might be rather limited--especially if there are a large number of points. What packages have others been using to plot this info?

A: After doing some more searching and comparison, I figure that using a library such as plotly or bokeh are the proper choices. These tools are compatible with the jupyter notebooks and can generate interactive 3D figures within jupyter notebooks. Both websites have a good setof examples/models to emulate.
Using these libraries, I should be able to take results computed in DIPHA and Gudhi and then generate plots within python.
UPDATED:
One big improvement in the last few months is that Gudhi has a set of python bindings. So the python Gudhi package will plot results using Matplotlib.

A: Javaplex can be used to plot these diagrams, as witnessed in its documentation (it's from Matlab I think).
Maybe someone finds these notebooks useful. They utilize javaplex from Scala, a JVM functional language.


text:
Q: Create an Access Query to see if in another field? I am creating queries for my database, and I want to know if the Artist_Name Field Value (A string) is part of a field in a different table, Band. I want to see if the Artist_Name is in the Band_Members field. Both are short text fields. I am using the Design View to create this query, which I will later edit in SQL. I will attach an Image to show my Query Relationships and Fields: Query Relationships

A: *

*You can use DCount function to count the number of records in Band having Band_Members equal to Artist_Name.

*You can create a left join from Artist table to Band table, on fields Artist_Name and Band_Members, but note that it may blow up the number of records in your output if artists are part of multiple bands.

I don't understand the field Band.Band_Members though; I suppose there is some one-to-may relationship between a band and it's members.


text:
Q: False Positives on S1172 - "Unused method parameters should be removed" I'm getting false positives from the rule csharpsquid:S1172 - "Unused method parameters should be removed" for the following code:
public class ExampleConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        return null;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

Both Convert and ConvertBack are part of the IMultiValueConverter implementation, and the rule states "virtual, override methods and interface implementations are ignored". However, in this case it fires for every parameter in both Convert and ConvertBack.
Is this a bug with the rule, or is it possible that I have set up something incorrectly?

A: The C# plugin at the moment analysis each file individually, and with only mscorlib added as a reference. The IMultiValueConverter is defined in PresentationFramework.dll, which is not added to the references to include in the compilation, therefore the compiler can't find it, and can't know that the two methods are part of that interface.
You won't face the same issue with SonarLint for Visual Studio, because that uses the all the references. (But this only works on the developer machine.) We are currently working on bringing this same accurate information to the SonarQube platform.


text:
Q: Is there any application about aws-iot device shadow? I have read the document of aws-iot, and successfully run the sample code.
I would like to know some applications using device shadow.  Real-world application is better.


text:
Q: DJANGO | Redirect/Disable URLs based on environment variables Usecase: I have some features that I don't want to release as of yet so I want to disable certain URLs or redirect them to 404/505s in production environment.
Is there a way to accomplish that using just the environment settings instead of popping out routes in urls/urlpatterns.

A: You could read the environment variable from os.environ and if it is a certain value (or just present in this example) append your paths that enable the feature(s)
import os

from django.urls import path

from . import views

urlpatterns = [
    path('foo/', views.foo),
]

if os.environ.get('ENABLE_FEATURE'):
    urlpatterns.append(path('bar/', views.bar))


text:
Q: Serial port won't open in linux ubuntu I can't open serial port to start communication in linux ubuntu. I've tried this:
int OpenPort(void) {

int fd;

fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);

if(fd == -1)
{
  printf("Failed to open port.\n");
}
else
{
    fcntl(fd, F_SETFL, 0);
    printf("Opened!\n");
}

return(fd);
}

int main()
{
  int x = OpenPort();
  printf("%i\n", x);

  exit(0);
}

I'm new in linux and found this code online, but it doesn't work for me.

A: You need to run as superuser/root to access serial port in linux. Try running your binary as sudo. If you can verify this is the problem but you do not want your process to be run by root user there are options you can use in your code to obtain root privileges. This answer might be useful reading How to programmatically gain root privileges?


text:
Q: How to play audio files to microphone input I was wondering how could I achieve a call chat between me and some other person which the other person does not hear me talk but rather the audio file.
Let's say I own an audio file which contains a voice that says "Hello", he will hear that instead of my voice.
Thank you in advanced.

A: Short answer: NO, this is not possible,
this is clearly explained in the android developer web:

Note: You can play back the audio data only to the standard output device. Currently, that is the mobile device speaker or a Bluetooth headset. You cannot play sound files in the conversation audio during a call.

the reason why, is not explained in the android web but it must be for sure to avoid criminal actions.


text:
Q: Set cron's maximum run counter How do I setup cron to run only for a specific number of times? Let's say I want to setup cron so that it runs hourly, but when the scheduler has already run five times, I want to stop cron. How do I do it?

A: According to my best knowledge there is no way to run cron for a specific number of times.
As a workaround you could implement i.e. counter in text file, to count how many times the command has been already launched.
Then, in cron, your command has to be wrapper in short script (i.e. bash) which would include condition to check how many times the command has been already launched. The exemplary code below:

counter = read_counter;
if [ counter < 5 ]; then
launch_command;
increment_counter;
fi

I hope I helped somehow.


text:
Q: "No pixel is not drawn to". No...not structure in this sentence. Could you clarify it in a simpler one? "No pixel is not drawn to". No...not structure in this sentence. Could you clarify it in a simpler one?

Calling clear before drawing anything is mandatory, otherwise the
contents from previous frames will be present behind anything you
draw. The only exception is when you cover the entire window with what
you draw, so that no pixel is not drawn to. In this case you can avoid
calling clear (although it won't have a noticeable impact on
performance).


text:
Q: Can we delete a trigger in Quicksilver? I can add a trigger by clicking on + under Triggers -> All Triggers.
But, I can't find a way to delete a trigger. Is it possible to delete a trigger completely in Quicksilver? Thank you

A: Yes, just select the trigger you want to delete, and then press the minus symbol in the window's bottom border, next to the plus symbol.


text:
Q: streamWriter escapes some lines I am trying to read a large text file (14MB), each line into a list of strings, then get the distinct strings out of it, then write it back to another text file, I use the following code:
    static void removeDuplicates(string filename)
    {
        //Reading from the file
        Console.WriteLine("Reading from the file....");
        StreamReader sr = new StreamReader(filename);
        List<string> namesList = new List<string>();
        while (!sr.EndOfStream)
        {
            namesList.Add(sr.ReadLine());
        }

        //Getting the distinct list
        namesList=namesList.Distinct().ToList<string>();

        Console.WriteLine("Writing to the new file");
        //writing back to the file
        StreamWriter sw = new StreamWriter(filename + "_NoDuplicates",false);
        for (int i = 0; i < namesList.Count; i++)
        {
            sw.Write(namesList[i] + "\r\n");

        }
    }

The problem is the streamWriter always stops writing after certain number of lines, always stops writing at the same place
I made sure that the List contents are right, and that the loop goes through all the items in the list, it's just the streamWriter problem.
The list contains 1048577 items before the Distinct(), and 880829 after the Distinct();
The streamWriter stops writing in the middle of the string number 880805 and doesn't write anything after that, it even stops in the middle of a word !
Why is that happening, what am I doing wrong?

A: If you're not getting an error then my guess is that the last bit of the file is still buffered.  Try adding a call to sw.Flush() to the end of  your method.
And, of course, you need to close the stream, which should flush the buffer anyway.
Explanation
The StreamWriter internally uses a buffer.  Every time you call Write() the data is actually written to the buffer in memory.  When the buffer fills up it gets flushed to the disk.
The problem you were seeing is because the last few lines of the file you're writing didn't fill up the buffer, so there was no trigger to flush the buffer to disk.  It always occurs at the same point in the file because that is the last whole-number of multiple of the size of the buffer.  By closing the stream you cause any remaining data to be flushed to disk.


text:
Q: "portal" and "fuse.portal" meaning in mount system command's output in Linux In mount system command's output in Debian Linux 10-like OS I have following string:
portal on /run/user/1000/doc type fuse.portal (rw,nosuid,nodev,relatime,user_id=1000,group_id=1000)
What means this string?

A: It seems that it's used by flatpak and gnome/gtk and kde/qt for desktop applications isolation. See: https://docs.flatpak.org/en/latest/sandbox-permissions.html#portals


text:
Q: determining finite subgroups of a multiplicative group This problem deals with finite subgroups of the multiplicative group of a field $(F^*)$.
Consider the field of complex numbers $\mathbb{C}$. How many subgroups of order 4 does $\mathbb{C}^*$ have?
Is this group cyclic?
Attempted work:
Consider the field of $\mathbb{C}$. Clearly, $\mathbb{C}^*$ has elements of order $1,2,3,4...$ with the subgroups of $\mathbb{C}^*$ also having orders $1,2,3,4...$ Now, Let $x \in \mathbb{C}^*$ with unity $x^4=1$.
$$ \Rightarrow x=(1)^{\frac{1}{4}}$$
$$ \Rightarrow x^2=|x^2|=4$$
$$ \Rightarrow x^3=|x^3|=4$$
$$ \Rightarrow x^4=|x^4|=4$$
So the number of cyclic subgroups of order 4 in $\mathbb{C}^*$ is 4.

A: If $z$ is an element of a group $G \subseteq \Bbb C^{\ast}$ of order $4$, then $z$ is a root of $x^4 - 1$.
Since $\Bbb C$ is a field, there are at most four such roots. Since:
$x^4 - 1 = (x^2 + 1)(x^2 - 1) = (x + i)(x - i)(x + 1)(x - 1)$, we see there are precisely four such roots. These form a cyclic group of order $4$: $\langle i\rangle = \langle -i\rangle$.
Thus $\{1,i,-1,-i\}$ is the sole subgroup of order four in $\Bbb C^{\ast}$ (there is no subgroup isomorphic to $V$, since $\Bbb C^{\ast}$ has but one element of order $2$, namely, $-1$).


text:
Q: Second page = ParentalKey() definition, to use one snippen in different Page models I defined two Relationship(Orderable, models.Model) to be able to use one modelsnippet inside differen Page models like:
class GroupstageTournamentModel(models.Model):
...
class GroupstageTournamentRelationship(Orderable, models.Model):
    page = ParentalKey('TournamentPage',
        related_name='groupstage_tournament_relationship')
    match = models.ForeignKey('GroupstageTournamentModel',
        related_name='match_tournament_relationship')
    panels = [
        PageChooserPanel('match')
    ]
class MatchesScreencastRelationship(Orderable, models.Model):
    page = ParentalKey('ScreencastPage',
        related_name='groupstage_screencast_relationship')
    match = models.ForeignKey('GroupstageTournamentModel',
        default="", related_name='match_screen_relationship')
    panels = [
        PageChooserPanel('match')
    ]

class TournamentPage(Page):
    starts_at = models.DateTimeField(blank=True)
    ends_at = models.DateTimeField(blank=True)

    content_panels = Page.content_panels + [
        FieldPanel('title'),
        FieldPanel('starts_at'),
        FieldPanel('ends_at'),
        InlinePanel(
            'groupstage_tournament_relationship', label="Group game:",
            panels=None, min_num=1),
    ]

    def __str__(self):
        return self.title

class ScreencastPage(Page):

    content_panels = Page.content_panels + [
        FieldPanel('title'),
        InlinePanel(
            'groupstage_screencast_relationship', label="Playing First",
            panels=None, max_num=1),
    ]

    parent_page_types = ['home.HomePage']
    subpage_types = []

    def __str__(self):
        # return self.title
        return '{} \n Nächste: {}'.format(self.groupstage_relationship, self.final_phase_relationship)

As you can see my idea was to use one of them insite TournamentPage and another inside ScreencastPage. If i do that this way i get this error:
ERROR:
django.core.exceptions.FieldError: Local field 'id' in class 'GroupstageTournamentRelationship' clashes with field of the same name from base class 'GroupstageTournamentModel'.

how can this problem be solved? Is it possible to add somehow the second ParentalKey for relationship with ScreencastPage and use it direct inside GroupstageTournamentModel like you did in backerydemo?
UPDATE
I changed GroupstageTournamentModel from model.Model to ClusterableModel and i changed related_name so that it different in both of related_name's
related_name='groupstage_tournament_relationship' and related_name='groupstage_screencast_relationship'. I did migrations again and got the same error. Here is my GroupstageTournamentRelationship class:
class GroupstageTournamentModel(ClusterableModel):
    number = models.PositiveSmallIntegerField(
        help_text="Add the unique number of this Match.")
    starts_at = models.DateTimeField()
    # Team 1
    team_1 = models.ForeignKey(
        TeamRooster,
        null=True, blank=True,
        on_delete=models.SET_NULL,
        related_name="+",
    )
    team_1_dress = ColorField(default='#ff0000', blank=True)
    team_1_first_halftime_score = models.PositiveSmallIntegerField(blank=True, default="")
    # Team 2
    team_2 = models.ForeignKey(
        TeamRooster,
        null=True, blank=True,
        on_delete=models.SET_NULL,
        related_name="+",
    )
    team_2_dress = ColorField(default='#0066ff', blank=True)
    team_2_first_halftime_score = models.PositiveSmallIntegerField(blank=True, default="")

    panels = [
        FieldPanel('number', classname="6"),
        FieldPanel('starts_at', classname="6"),
        MultiFieldPanel([
            FieldRowPanel([
                FieldPanel('team_1', classname="6"),
                FieldPanel('team_1_dress', classname="6"),
                FieldPanel('team_1_first_halftime_score', classname="3"),
            ]),
        ], classname="full", heading="Team 1"),
        MultiFieldPanel([
            FieldRowPanel([
                FieldPanel('team_2', classname="6"),
                FieldPanel('team_2_dress', classname="6"),
                FieldPanel('team_2_first_halftime_score', classname="3"),
            ]),
        ], classname="full", heading="Team 2"),
    ]

    def __str__(self):
        return '{} vs {} {} - {}'.format(self.team_1, self.team_2, self.starts_at, self.number)

    class Meta:
        verbose_name = 'Gruppenphase Spiel'
        verbose_name_plural = 'Gruppenphase'

UPDATE
In migration file i found following, and Im not sure what happens if I remove that:

UPDATE
I shortened the model and added "TournamentPage" for clarity.

A: I deleted my migration files included 0001_inicial.py and did again py manage.py makemigrations and it all worked !


text:
Q: Can I use AWS Device Farm with WebdriverIO Mobile testing? I have a webdriverIO framework built. I am trying to setup a webdriverIO config file to connect to AWS Device Farm, and obtaining a mobile device, then running the appium based tests.
Maybe something like this? for the config file for iOS?
But the issue I have is the following:

*

*How do I point to the IPA file that I have uploaded to the server?

*How do I connect to the AWS Device Farm?

*Is it safe to assume since AWS Device Farm runs an appium server, the supported capabilities is what I should use from appium?

const { join } = require('path');
const { config } = require('./wdio.conf');

config.specs = [
    './tests/specs/**/*.spec.js',
];

config.capabilities = [
    {
        platformName: 'iOS',
        maxInstances: 1,
        'appium:deviceName': 'iPhone 12',
        'appium:platformVersion': '14.4',
        'appium:orientation': 'PORTRAIT',
        'appium:automationName': 'XCUITest',
        'appium:app': 'replace this with your locally built app - full path to app file',
//        'appium:app': join(process.cwd(), './apps/iOS-Simulator-NativeDemoApp-0.2.1.app.zip'),
        'appium:noReset': true,
        'appium:newCommandTimeout': 240,
    },
];

exports.config = config;

A: For these questions:

*

*How do I point to the IPA file that I have uploaded to the server?

AWS Device Farm uses a server-side execution platform, where you upload your app and test code using the CreateUpload API (ref https://docs.aws.amazon.com/devicefarm/latest/APIReference/API_CreateUpload.html).

*How do I connect to the AWS Device Farm?

You do not connect to AWS Device Farm from your local client, you Schedule a run on Device Farm using the ScheduleRun API (ref https://docs.aws.amazon.com/devicefarm/latest/APIReference/API_ScheduleRun.html)

*Is it safe to assume since AWS Device Farm runs an appium server, the supported capabilities is what I should use from appium?

Yes, Device Farm executes your test on a server-side platform using an Appium server at localhost:4723
Please see this blog post for a detailed walk-through that should clarify some of these things for you: https://aws.amazon.com/blogs/mobile/testing-mobile-apps-with-cucumber-and-appium-through-testng-on-aws-device-farm/


text:
Q: Laravel Eloquent ->with() and ->select() conflict with each other Consider this code:
Articles
::select('article_id', 'article_text')  //This one does not work as expected
->with([
    'user' => function($q){
        $q->select('user_id', 'user_name'); // This one works fine
    }
])
->get();

When building query in Eloquent, we can use ->with() to retreive associated models. We can also attach ->select(), to determine which columns should be selected from associated model. However, looks like we loose possibility to specify which columns should be selected from the base model we are querying.
In this example, because of the first ::select, the final results returned do not include user, because it's not included in the ::select list. If I include it there, then it throws an error about column not found. Eloquent is not smart enough to understand that I mean relationship, not column.
Is it possible to specify which columns should be returned from user as well as from article ?

A: You can select the columns you want with eager loading constraints but you still need to at the least select the columns that are used for the relationship.
Random example:
User::with(['tickets' => function ($q) {
    $q->select('user_id');
}])->select('id')->get();

Those are the minimum fields needed for that to return results for the relationship and have them attached to the correct models.
You would need to select a minimum of user_id from tickets and id from users. Those are the columns used for this relationship. tickets.user_id -> users.id
Query Log:
'select `id` from `users`'

'select `user_id` from `tickets` where `tickets`.`user_id` in ( .... )'

Having those fields gives you what you need for the relationship to return results, now you can add additional fields to those selects.
I hope that helps.


text:
Q: How do I label my BarLegend? How do I add a label to my BarLegend? I would like to add the label "Depth" to the right of my BarLegend.
BarLegend[{GrayLevel, {0, 1}}]

A: What about this:
Row[{BarLegend[{GrayLevel, {0, 1}}],
  Rotate[Style["   Depth", 14], 90 Degree]}]

??

A: Based on @MarcoB comment:
BarLegend[{GrayLevel, {0, 1}}, LegendLabel -> Placed[Rotate["Depth", -Pi/2], Right]]


text:
Q: jQuery not receiving JSON encoded data from PHP script I'm trying to get jQuery to retrieve PHP variables and insert them into input values. I was looking everywhere trying to find a solution.
Here's jQuery code.
$(document).ready() {
$(function() {
    $.ajax({
      type: 'POST',
      url: 'loadstuff.php',
      data: {
            'something': something,
            'different': different,
            'another': another
            },
      dataType: 'json',
      success: function(data) {
        $('input[name=get_seomething_here]').val( 'something' );
        $('input[name=get_different_here]').val( 'different' );
        $('input[name=get_another_here]').val( 'another' );
}
    });

});
});

And here's PHP side.
//connecting to db etc.

$query = "SELECT something, different, another FROM stuff WHERE id='1'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array( $result );

echo(json_encode(array('something' => $row['something'],
'different' => $row['different'],
'another' => $row['another']
)));

A: I think it should be:
$('input[name=get_seomething_here]').val( data.something );
$('input[name=get_different_here]').val( data.different );
$('input[name=get_another_here]').val( data.another );

A: aletzo is right.. but before doing that you have to do like:
data = eval("(" + data + ")");

Then you can use data.something, data.different and data.another


text:
Q: Jquery Galleria Classic Skin - thumbnail rows instead of scrolling I'm looking for a way to have Galleria classic skin have multiple rows of thumbnails rather than the scrolling thumbnail nav. Any idea where this would be housed?
Right now the thumbnails scroll left to right, I'd rather them drop to a new line after they exceed the width of the main photo frame and I'd rather not construct a whole table
I've tried expanding the thumbnail container to accommodate two rows, height-wise, but it doesn't know to drop them down.
Again, any help would be greatly appreciated

A: I was able to get two rows of thumbnails by altering the galleria-thumbnails div to 100px height and 100% width.
Edit: you may wish to change the height of galleria-container and galleria-thumbnails-container to accomodate the extra height of the galleria-thumbnails div

A: The container holding the thumbnails needs its width reduced to the size of the widget as well, then the thumbnails will wrap onto the second row.


text:
Q: Matlab matrix dimagree error only in standalone app I have to convert my Matlab function to a standalone application. I build it using the Matlab build tool, that part is ok.
However, I get a dimagree error while running my standalone program, even if it works just fine in Matlab; here the code which seems to be wrong :
% INITIALISATIONS
% find connected components
cc = bwconncomp(bw);
% find areas and centroids
stats = regionprops(cc, 'Area','Centroid');
% keep only the particles in the right dimensions
all_areas = cat(1, stats(:).Area);
idx = zeros(size(all_areas));
fprintf('\nSize all_areas : %d %d \n',size(all_areas,1), size(all_areas,2));
fprintf('\nSize idx : %d %d \n',size(idx,1), size(idx,2));
fprintf('\nProgram paused. Press enter to continue.\n');
pause;
idx = all_areas > minArea & all_areas < maxArea;

Error shows up at the last line of the above code. I get :
??? Error using lt
Matrix dimensions must agree.
Error in ==> stats at 46
Error in ==> statPart at 83
MATLAB:dimagree

As you can see, I tried to initialize idx with zeros(), and I output the size of idx and all_areas, they are the same when I run the program. So I'm out of idea now, I really need help here...
[EDIT]
Here is the code I use to handle statPart function inputs :
function [BW2,stat] = statPart(varargin)
i = 1;
while i<=length(varargin),
    argok = 1;
    if ischar(varargin{i}),
        switch varargin{i},
            % argument IDs
            case 'minArea', i = i+1; minArea = varargin{i};
            case 'maxArea', i = i+1; maxArea = varargin{i};
            case 'subImgSize', i = i+1; subImgSize = varargin{i};
            case 'image', i = i+1; Igray = varargin{i};
            otherwise argok = 0;
        end
    else
        argok = 0;
    end
    if ~argok,
        disp(['(statPart) Argument invalide ignore #' num2str(i+1)]);
    end
    i = i+1;
end

Thank you!

A: The error message states that he problem arises in lt (the less-than comparison) of this line:
idx = all_areas > minArea & all_areas < maxArea;

because  minArea and maxArea are not of the same dimensions all_areas. They either have to be of size(all_areas) or scalars, which they are not.
From your check, minArea and maxArea are [50 48 48], which is the ASCII equivalent of "200". They are received as strings from the command line, and you should use str2num to convert them into numbers before you handle their values.
I don't understand, however, why they are not equal to your input strings "2" and "20000". How are you parsing your input parameters? That would be a good place to start looking for the problem, but without additional information I won't be able to help you further.
Also, you mention in the comments that disPart calls statPart. What is disPart, and what is its relation to statPart?


text:
Q: $N \lhd G, G/N$ are Nilpotent $ \not \Rightarrow G$ is Nilpotent Apparently that if we have $N \lhd G, G/N$ are Nilpotent $ \not \Rightarrow G$ is Nilpotent.
I am trying to find a simple example of this.
It currently seems unintuitive since if we have $N, G/N$ nilpotent, then we can 'mash together' elements in $G/N$ by elements in $G$ to get them into $N$ in a finite number of steps, and we can also 'mash' the elements in $N$ down to the identity in a finite number of steps, so initially I'd think the opposite statement is true.
Could someone please enlighten me on how to think about this? Any obvious counterexamples?

A: A classic example is that $S_3$ is not nilpotent, but $A_3\cong\Bbb{Z}/3\Bbb{Z}$ and $S_3/A_3 \cong \Bbb{Z}/2\Bbb{Z}$ are both nilpotent, and $A_3\lhd S_3.$ Thus, $S_3$ is an example of such a group.

A: $S_3$ is not very enlightening from my point of view, because it's in a sense too clumped; one can consider fundamental group of Klein bottle as more picturesque example. It's a semidirect product $\mathbb Z \rtimes \mathbb Z$, where action is by negation. (there's a presentation: $\langle a, b \, | \, [a, b] = b^2\rangle$ if you are more combinatorial-minded) Computing its lower central series is an interesting exercise.
Also reading some proof of Hall's theorem may be helpful (moreso proving it by yourself): if for $N \triangleleft G$ both $G/[N, N]$ and $N$ are nilpotent, then $G$ is.


text:
Q: Como substituir tags html e salvar em um novo arquivo Estou tentando verificar um arquivo .html, remover algumas tags e criar um novo arquivo com as alterações feitas.
No método que estou utilizando no momento (js, gulp) eu acabo fazendo vários replaces em cadeia, acredito que esse não seja a melhor maneira, gostaria de saber um método melhor de fazer isso.
Segue o código da minha task atual:

var gulp = require("gulp");
var fs = require("fs");

gulp.task("fixes", function(done) {
  var conteudo;

  fs.readFile("index.html", "utf-8", (err, data) => {
    if (err) throw err;
    conteudo = data;

    var t = data.replace(/(<body>|<\/body>)/g, "");
    var final = t.replace(/<meta charset="utf-8">/, "");

    fs.writeFile("dist.html", final, err => {
      if (err) throw err;
    });
  });

  console.log("Novo arquivo criado!");
  done();
});


text:
Q: gnome-screenshot doesn't autosave but interactively asks for a save directory I've specified an auto-save-directory in dconf-editor under org.gnome.gnome-screenshot however it still asks me for a save directory every time I take a screenshot.

In prior Linux Mint versions (17, 17.3, ...) it went like this: I press Print, the screen goes white, and then I continue doing what I was doing (with a screenshot being made and put into the auto-save-directory)
In 18 however a dialog pops up after it goes white and asks me interactively what I want to name the screenshot and what folder I want to put it in.
I find this very annoying since I put them all in the same folder and don't bother with filenames since the current date and time are usually descriptive enough (plus they're chronologically sorted). Can I change the behavior of gnome-screenshot or are there any alternative programs?

A: Here is a workaround (tldr: delete default shortcuts and replace them with shortcuts that call scripts which activate gnome-screenshots and set the desired save path). See https://cialu.net/how-to-change-default-gnome-screenshot-savings-folder/ for complete instructions.
*edit to add more detail:
Per instructions given at the link above, referencing this bug https://bugzilla.gnome.org/show_bug.cgi?id=699642, this issue is not going to change. Here's how to work around it in case the link breaks in future.
1) Go to Keyboard Settings > Shortcuts > Screenshots. You'll see some shortcuts already assigned; the top three should be to save a full screenshot, save a screenshot of a window, and save a screenshot of an area.
2) Disable the default shortcut keys (by default PrintScreen Alt+PrintScreen and Shift+PrintScreen) for these commands by selecting the shortcut and pressing the Backspace key.
3)Now select the Custom Shortcuts menu, and make three new shortcuts for the same behaviors (save complete screenshot, one of just one window, or one of just the selected area). For the command for each shortcut type the command sh -c, followed by the path to the executable script you want to fire for that command.
example: sh -c '/home/user/.scripts/screenshot-full.sh'
would be my command to take a full screenshot
4)In the directory where you keep your executable shell scripts, (~/.scripts in the example) write scripts to perform each desired behavior.
examples:
full screen capture
#!/bin/bash
DATE=$(date +%F-%T)
gnome-screenshot -f /home/user/screenshot_directory/Screenshot-$DATE.png
window capture
#!/bin/bash
DATE=$(date +%Y-%m-%d-%H:%M:%S)
gnome-screenshot -w -f /home/user/screenshot_directory/Screenshot-$DATE.png
area capture
#!/bin/bash
DATE=$(date +%Y-%m-%d-%H:%M:%S)
gnome-screenshot -a -f
/home/user/screenshot_directory/Screenshot-$DATE.png
5) Make each script executable by running the chmod command.
examples:
sudo chmod a+x '/home/user/.scripts/screenshot-full.sh'
sudo chmod a+x '/home/user/.scripts/screenshot-window.sh'
sudo chmod a+x '/home/user/.scripts/screenshot-area.sh'
That's all there is to it. Now when you press the shortcut keys, the script will execute and the screenshots taken will be automatically saved to your chosen screenshot_directory.
(If your shell fu is strong, you can also do the same thing with a single script by having the shortcuts pass options to it. Developing this more elegant version is left as an exercise to the reader.)

A: I'm using scrot . Detailed post on how to set it up with shortcut key and saving to a specific folder here: https://askubuntu.com/a/1238869/730518


text:
Q: How can I redirect a result of a Mongo variable to a collection, and then export it to a csv file I have a beginner MongoDB question, but I am really stuck on this.
So, I have a dataset of some medical data

and I need to calculate the averages and the standard deviations for the each column and store it in a table represented below.

So, I have made an aggregation
var average_age = db.ilp.aggregate(
{$match: {"age":{$ne:-1}}},
{"$group":{
"_id": null,
"avg_age": {"$avg":"$age"}
}
})

tried to store it into a variable and I get the following output for this variable:
{ "_id" : null, "avg_age" : 44.74614065180103 }
But when I want to insert this into a new collection, by db.test.insert(average_age), I get the following output:

After I make a desired collection, I want to redirect it to a csv file.
I appreciate any help you could provide.
P.S. also, I can you tell me why, first time when I call the variable average_age, it outputs the correct value showed above, and after that when I call it, it doesn't output anything, like it is empty.

A: You need to add as last pipeline $out operator.
db.ilp.aggregate([
    {$match: {"age":{$ne:-1}}},
    {"$group":{
        "_id": null,
        "avg_age": {"$avg":"$age"}
    },
    {$out: "collection-name"}
])

When you assign db.ilp.aggregate(...)or call db.ilp.find(...) methods, MongoDB returns cursor.
cursor.toArray() returns an array that contains all the documents from a cursor
var average_age = db.ilp.aggregate(...).toArray();

Note:  Do not use $out stage if you wish get all results

A: Aside from Valijon's excellent answer, you also have the option of creating a view and use mongoexport to save the collection as a CSV file directly. This has the advantage that you can export the view many times, updating the averages every time you export it:
db.createView('ilp_averages', 'ilp', [
  { $match: { "age": { $ne:-1 } } },
  {"$group": {
    "_id": null,
    "avg_age": {"$avg":"$age"}
  }])

And export with:
mongoexport --host <mongodbinstance>:<port> --type csv -d=<yourdb> -c=ilp_averages -o=ilp_averages.csv

Note that the correct syntax for mongoexport depends on the version of MongoDB that you are using, there could be slight variations.


text:
Q: cant seem to get img src into variable I am using jquery to try and get the img src of a bunch of imgs in a div and storing the values as per code below... but i am getting undefined as the output of the variable newHomeHeroCarouselFetchedIMGSRC - can anyone help as to why?
$('.newHomeHeroCarouselFetchedIMGs img').each(function() {
let newHomeHeroCarouselFetchedIMGSRC = $(this).attr('data-src');
console.log(newHomeHeroCarouselFetchedIMGSRC);
});

Example of markup of the newHomeHeroCarouselFetchedIMGs div is below:


text:
Q: How to rename files in order I need to sort and rename files in a test directory such that based on the bolded number the file will be renamed 1-5 in groups of 5. I was able to sort them but now need to rename them 1,2,3,4, or 5. This is what I have so far:
 find . -maxdepth 1 -type f -name '*.txt' | sort -nt_ -k2,2 -k7,7
./FoilHole_6862563_Data_6834945_6834947_20190608_255634_Image.txt
./FoilHole_6862563_Data_6834952_6834954_20190608_255710_Image.txt
./FoilHole_6862563_Data_6834959_6834961_20190608_255748_Image.txt
./FoilHole_6862563_Data_6834935_6834937_20190608_255827_Image.txt
./FoilHole_6862563_Data_6834967_6834969_20190608_255906_Image.txt
./FoilHole_6862568_Data_6834945_6834947_20190608_060123_Image.txt
./FoilHole_6862568_Data_6834952_6834954_20190608_060159_Image.txt
./FoilHole_6862568_Data_6834959_6834961_20190608_360237_Image.txt
./FoilHole_6862568_Data_6834935_6834937_20190608_460316_Image.txt
./FoilHole_6862568_Data_6834967_6834969_20190608_560354_Image.txt

What I now need to do is rename them as:
./FoilHole_6862563_Data_6834945_6834947_20190608_1_Image.txt
./FoilHole_6862563_Data_6834952_6834954_20190608_2_Image.txt
./FoilHole_6862563_Data_6834959_6834961_20190608_3_Image.txt
./FoilHole_6862563_Data_6834935_6834937_20190608_4_Image.txt
./FoilHole_6862563_Data_6834967_6834969_20190608_5_Image.txt
./FoilHole_6862568_Data_6834945_6834947_20190608_1_Image.txt
./FoilHole_6862568_Data_6834952_6834954_20190608_2_Image.txt
./FoilHole_6862568_Data_6834959_6834961_20190608_3_Image.txt
./FoilHole_6862568_Data_6834935_6834937_20190608_4_Image.txt
./FoilHole_6862568_Data_6834967_6834969_20190608_5_Image.txt

A: As hacky bash script:
#!/bin/bash
while IFS= read -r file; do
  newprefix=${file%%_Data*}
  if [ "$prefix" != "$newprefix" ]; then
    cnt=1
    prefix=$newprefix
  fi
  newfile=$(echo "$file" | sed "s/[0-9]*\(_Image.txt\)/$cnt\1/")
  echo mv "$file" "$newfile"
  ((cnt++))
done < <(find . -maxdepth 1 -type f -name '*.txt' | sort -nt_ -k2,2 -k7,7)

Output:
$ ./script.sh
mv ./FoilHole_6862563_Data_6834945_6834947_20190608_255634_Image.txt ./FoilHole_6862563_Data_6834945_6834947_20190608_1_Image.txt
mv ./FoilHole_6862563_Data_6834952_6834954_20190608_255710_Image.txt ./FoilHole_6862563_Data_6834952_6834954_20190608_2_Image.txt
mv ./FoilHole_6862563_Data_6834959_6834961_20190608_255748_Image.txt ./FoilHole_6862563_Data_6834959_6834961_20190608_3_Image.txt
mv ./FoilHole_6862563_Data_6834935_6834937_20190608_255827_Image.txt ./FoilHole_6862563_Data_6834935_6834937_20190608_4_Image.txt
mv ./FoilHole_6862563_Data_6834967_6834969_20190608_255906_Image.txt ./FoilHole_6862563_Data_6834967_6834969_20190608_5_Image.txt
mv ./FoilHole_6862568_Data_6834945_6834947_20190608_060123_Image.txt ./FoilHole_6862568_Data_6834945_6834947_20190608_1_Image.txt
mv ./FoilHole_6862568_Data_6834952_6834954_20190608_060159_Image.txt ./FoilHole_6862568_Data_6834952_6834954_20190608_2_Image.txt
mv ./FoilHole_6862568_Data_6834959_6834961_20190608_360237_Image.txt ./FoilHole_6862568_Data_6834959_6834961_20190608_3_Image.txt
mv ./FoilHole_6862568_Data_6834935_6834937_20190608_460316_Image.txt ./FoilHole_6862568_Data_6834935_6834937_20190608_4_Image.txt
mv ./FoilHole_6862568_Data_6834967_6834969_20190608_560354_Image.txt ./FoilHole_6862568_Data_6834967_6834969_20190608_5_Image.txt

The counter variable cnt is reset to 1 whenever the filename prefix changes, e.g. when ./FoilHole_6862563 changes to ./FoilHole_6862568.
To really rename the files you have to remove the echo in the script.

A: You can combine bash arithmetic with the rename command:
i=0
find . -maxdepth 1 -type f -name '*.txt' |
sort -nt_ -k2,2 -k7,7 |
while read filename ; do
    rename -v "s/[0-9]+_Image/$((i%5+1))_I/" ${filename}
    i=$((i+1))
done

Try it out with the -n option of the rename command, that just shows what is being done.
WARNING:
Filenames come from a piped input and the variable filename is set using the read builtin here. This WILL break if your filenames do not match the format you specified in your question, e.g. filenames with spaces, newlines, etc. So be aware that you would need to use a different approach then, e.g. find's -print0 option in combination with xargs -0.
In this case a helper file for the counter is used and ? used as the variable replacement:
echo -1 > file_counter
find -name '*txt' -print0 |
sort -znt_ -k2,2 -k7,7 |
xargs -I ? -0 bash -c '
     i=$(($(cat file_counter)+1))
     rename -n -v "s/[0-9]+_Image/$(($i%5+1))/"  ?
     echo $i > file_counter
'


text:
Q: Opening multiple netcdf files with same dimensions and data variables in xarray There are two netCDF files that have 3 dimensions ('lon', 'lat', 'time'). The names and values of dimensions are equal in two files. These files have 12 data variables that the name of data variables are same but the values are different. I want to open this big files with open_mfdataset in xarray that the all data variables in both files read, but the result returns only 12 data variables of one of files. What is the correct setting in open_mfdataset command?
xdf = xr.open_mfdataset(file_path + '*.nc', concat_dim='time')


text:
Q: CarPlay's setRootTemplate fails to run completion handler or work using async/await When using CarPlay's setRootTemplate method, I am unable to get either the completion handler or async/await to work properly. I need to perform some actions after the root template is loaded, but neither of these options allow for this.
This method is documented here, saying:

CarPlay calls completion after it presents the template. The Boolean parameter is true when the presentation succeeds; otherwise, it's false and CarPlay provides an error that describes the failure. CarPlay throws an exception if the presentation fails and you don't provide a closure.

Example 1: Completion Handler
interfaceController.setRootTemplate(tabBarTemplate, animated: false) { didSucceed, error in
    print("This completion handler never runs...")
}

Note: The above does work if you pass nil to the completion argument.
Example 2: Async/await
    do {
        print("This appears in console...")

        try await interfaceController.setRootTemplate(tabBarTemplate, animated: true)

        print("This doesn't...")
    } catch {
        print("error \(error.localizedDescription)")
    }

The synchronous version of this method does work, but it throws a deprecation warning in iOS 15.
Is this a bug, or is there something obvious that I'm missing?

A: As per the apple developer documentation setRootTemplate has 3 parameters.
I found a wrong syntax in your code.
use completion argument as below
self.interfaceController?.setRootTemplate(listTemplate, animated: true, completion: { success, error in
  print("onCompletion")
  print(success)
  print(error)
})

hope it helps...


text:
Q: Why only one NIC obtains an IP address? I'm learning on how to set up a network properly, and I'm a bit stuck.
I've created two separate Ubuntu Server VMs in VirtualBox, then connected them through an internal network (intnet0). With CLI manager I've set up DHCP server, and it works fine, both are getting IP addresses correctly.
Now, when I add second interface to one of the machines (host only network), this Ubuntu obtains IP for only one card, and it's always the first one. In this example, I've added host-only adapter as first, then internal network adapter as second:

I suspect it's some kind of Linux setting, but I have no idea which one; I've already set the second NIC up with:
sudo ip link set enp0s8 up

but it's still not getting an address.
On the other hand, /etc/network/interfaces is empty. Should I configure it, or configure my networking manager through netplan? A push in the right direction would be greatly appreciated.


text:
Q: Make background blink with lwjgl I've compiled the Get Started example from the lwjgl.org webpage (http://www.lwjgl.org/guide) and now I wanted to continuously change to background-color. So, I wanted something like a blinking effect. But I don't get the background to switch its color permanently with glClearColor, when the program is running.
I've tried to do this in the loop() function in the while loop with glClearColor. But that seems wrong, as the glClearColor Method is only called outside the while loop. For instance in the following code, the background color takes the color that was lastly called with glClearColor.
...
 private void loop() {
    // This line is critical for LWJGL's interoperation with GLFW's
    // OpenGL context, or any context that is managed externally.
    // LWJGL detects the context that is current in the current thread,
    // creates the ContextCapabilities instance and makes the OpenGL
    // bindings available for use.
    GLContext.createFromCurrent();

    // Set the clear color
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

    // Run the rendering loop until the user has attempted to close
    // the window or has pressed the ESCAPE key.
    while ( glfwWindowShouldClose(window) == GL_FALSE ) {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear the framebuffer

        /* Switch permanently between red and green background color
            - doesn't work, no blinking, just green background color */
        glClearColor(1.0f, 0.0f, 0.0f, 0.0f);
        glClearColor(0.0f, 1.0f, 0.0f, 0.0f);

        glfwSwapBuffers(window); // swap the color buffers

        // Poll for window events. The key callback above will only be
        // invoked during this call.
        glfwPollEvents();
    }
}
...

I'm very new to lwjgl, thus I think I'm making some basic mistake and the background color shouldn't be changed in that way I did at all. Is there something to handle the background in lwjgl to achieve this?
I should mention that I'm using lwjgl 3, not lwjgl 2. And it seems to be that there is no Display Class anymore. GLFW seems to be the replacement for that.

A: In the while loop below, think that each iteration represent your 1 frame. In your scene you will see a change only after glfwPollEvents() call after each iteration. That's why changing color 2 times at one iteration won't affect anything.
while ( glfwWindowShouldClose(window) == GL_FALSE ) {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear the framebuffer

    /* Switch permanently between red and green background color
        - doesn't work, no blinking, just green background color */
    glClearColor(1.0f, 0.0f, 0.0f, 0.0f);
    glClearColor(0.0f, 1.0f, 0.0f, 0.0f);

    glfwSwapBuffers(window); // swap the color buffers

    // Poll for window events. The key callback above will only be
    // invoked during this call.
    glfwPollEvents();
}

At below, I wrote a simple solution for your problem. If you change the color at every frame you cannot see the change because it will be very fast, so I did a small trick that change your color at every 30 frame. You can write an alternative using time dependent color change instead of frame count.
Correct Version:
boolean redOrGreen = true; // true = Green false = Red
int  counter = 0;
int  COLORCHANGEAT = 30;

while ( glfwWindowShouldClose(window) == GL_FALSE ) {

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear the framebuffer

    counter++;
    if(counter == COLORCHANGEAT) {
       redOrGreen = !redOrGreen;
       counter = counter % COLORCHANGEAT;
    }

    if(redOrGreen == true)
       glClearColor(1.0f, 1.0f, 0.0f, 0.0f);
    else
       glClearColor(0.0f, 1.0f, 0.0f, 0.0f);

    glfwSwapBuffers(window); // swap the color buffers

    // Poll for window events. The key callback above will only be
    // invoked during this call.
    glfwPollEvents();
}


text:
Q: Несколько видео в одном Скажите, как можно скопировать данный плеер, чтобы он также показывал, как на этом сайте? Насколько я понимаю, здесь используется IFRAME, но не уверен и поэтому нужна помощь.
Задача состоит в том, чтобы вывести плеер в материале Joomla. Чтобы была возможность выбора видео, а по окончанию серии, сразу же автоматически начиналась бы вторая.

A: Они используют http://uppod.ru/ так что читайте документацию и настраивайте под свой вкус.


text:
Q: Does Object's constructor call super()? Which superclass constructor would that call? If the Object class contains default constructor generated by compiler then it must have a super(); declaration. If this declaration is there than which parent class constructor is it calling? And how?
Because Object is the parent of all classes, I think if I call super(); in the Object class constructor then it should give us compile time error because we know Object doesn't inherit from anything.
class Test
{
    Test()
    {
        super();
    }
    public static void main(String[] args)
    {
        Test t = new Test();
    }
}

A: No. JLS-8.8.9. Default Constructor says (in part)

If the class being declared is the primordial class Object, then the default constructor has an empty body. Otherwise, the default constructor simply invokes the superclass constructor with no arguments.


text:
Q: Does the modification of the LHS always happen strictly after the RHS has been evaluated during assignment for built-in type? This should be a quite elementary question...
Let a be a variable of type T, and f() be any kind of function which returns T (or T&, or anything that can be assigned to T). Now, assume f() does not modify a. Consider:
a = f();

For T to be a user-defined type, I can be sure that a will only be modified after the evaluation of f() has finished. Because a = f(); is a call of the operator=() function, and the execution will not go into the function body before the argument is evaluated.
For T to be a built-in type, may I ask if the data in a is never modified before the evaluation of f() is finished?

The reason that I would like to confirm this is because I really want to make sure that in any cases where such a f() throws an exception, we can safely say that the data in a is not corrupted.


text:
Q: Handshake problems with CloudMQTT - Angular I'm trying to develop a Web-App using Angular + Ionic and I cannot establish an handshake with the server of my instance in CloudMQTT. The error given is

Error during Websocket handshake: net::: ERR_CONNECTION_RESET

How can I solve this problem?
This is my connection code in the app-module.ts:
export const MQTT_SERVICE_OPTIONS: IMqttServiceOptions = {
  hostname: 'tailor.cloudmqtt.com',
  port: 34804,
  username: 'user',
  password: 'pass',
};

This is the code in the component:
export class DetailsComponent implements OnInit {

  public sensorName: string;
  public values: any[];

  private subscription: Subscription;

  constructor(private actRoute: ActivatedRoute, private mqttService: MqttService) { }

  ngOnInit() {

     this.sensorName = this.actRoute.snapshot.paramMap.get('sensorName');

     console.log('I am trying to connect!');

     this.subscription = this.mqttService.observe('sensors/' + this.sensorName).subscribe((message: IMqttMessage) => {
        let value: any;
        value = message.payload.toString();
        console.log(value);
        let parsedValue: any;
        if ( this.sensorName === 'Humidity' || 'Temperature' ) {
           parsedValue = parseInt(value, 10);
        } else {
          parsedValue = parseFloat(value);
        }
        this.values.push(parsedValue);
        });

    }

}


text:
Q: How to set a variable string with a float value in datafactory I have the following value:
"Value": 8.371582
but I have to assign it to a string variable, how can I do it

A: I don't know where you get the value to set the variable. I tested and the value "8.371582" can be assigned to the variable successfully.
For example, I create a string variable aa:

Set the variable value "8.371582":

Run this active and check the variable value:

In Data Factory, the float or other data type will be converted to String automatically if the variable type is set as String.


text:
Q: Problem with export date to csv file, how to export date to excel I have problem with export of date to my .csv file.
I have this two strings:
string Time = DateTime.Now.ToString("H:mm:ss");
string Date = DateTime.Now.ToString("dd:HH:yyyy");

Time is working normal and I get to csv file right data, but Date is written to cell as "0,905324074074074".
I found the problem, when creating the csv I have pName[2] = Date+";";
There is ; for shift to next cell, but it does this weird thing, i do not know why.
Code for create csv:
        private void SaveFileMeasure(string fileNameWithPath, string textMer, bool deleteExist)
    {
        try
        {
            try
            {
                if (!deleteExist)
                {
                    File.AppendAllText(fileNameWithPath, textMer);
                }
                else
                {
                    File.WriteAllText(fileNameWithPath, textMer);
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show("Vytvoření souboru neproběhlo v pořádku.");
            }
        }
        finally
        {
        }
    }

Thank for help.

A: Your format of date is incorrect, Try "dd:MM:yyyy"
string date = DateTime.Now.ToString("dd:MM:yyyy");

.Net Fiddle


text:
Q: i am getting an error "cannot find symbol variable fragment" I'm getting following error:

cannot find symbol variable fragment

How to fix this error?
public boolean onNavigationItemSelected(MenuItem item) {

    int id = item.getItemId();

    if (id == R.id.toi) {
        fragment= new FragmentOne();
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.content_frame, fragment);
        ft.commit();

        return true;
    }  else if ( id ==R.id.thehindu){

    }else if (id == R.id.support) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

A: Change:
fragment= new FragmentOne();

To:
Fragment fragment= new FragmentOne();


text:
Q: Why do some threads not close/ stop within my session of JMeter? Why do some threads not close/ stop within my session of JMeter?
I have a simple https request to a URL, 1500users, 20second ramp up, 5 iteration
For some reason the threads freeze when ramping down, for example 1500users would ramp down but when reach around the 30mark the 30 threads freeze and dont stop, any ideas?

A: Don't ever run your JMeter tests in GUI mode, use GUI only for tests development and/or debugging. When it comes to load test execution make sure you run your test in command-line non-GUI mode.
Also make sure you are following JMeter Best Practices and recommendations from 9 Easy Solutions for a JMeter Load Test "Out of Memory" Failure article.


text:
Q: c# sql How to get row selected value? I used datagrid to show sql table datagrid.
And I showed one column on datagrid from sql.
Now I want to determine that which rows is now open & what is that values.
Like this.
See what I want to do.
And I used this code to show datatable on my datagrid.
string ConString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(ConString))
{

    SqlCommand cmd = new SqlCommand("SELECT roll FROM cmt_7th WHERE name IS Null And department IS Null And phone IS Null", con);
    SqlDataAdapter sda = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable("cmt_7th");
    sda.Fill(dt);
    MydataGrid_roll.ItemsSource = dt.DefaultView;

}

And its show only row column. But I want to declare like my previous image.

A: You can get the selected row value with this code:
string em = dataGridView1.CurrentRow.Cells[2].FormattedValue.ToString();
You store the value in a string called em like the above, you can change the name for sure, and then cell[] is like an array, it stores each intersection of a row and a column in there, so for instance if you have 3 columns and two rows, the first intersection of the row and column is of index 0 and so on and so forth.

A: You could select all values that you are interested in up front of but only display the "roll" column in the DataGrid:
string ConString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(ConString))
{

    SqlCommand cmd = new SqlCommand("SELECT roll, tc, tf, pc, pf FROM cmt_7th WHERE name IS Null And department IS Null And phone IS Null", con);
    SqlDataAdapter sda = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable("cmt_7th");
    sda.Fill(dt);
    MydataGrid_roll.AutoGenerateColumns = false;
    MydataGrid_roll.Columns.Add(new DataGridTextColumn() { Header = "roll", Binding = new Binding("roll") });
    MydataGrid_roll.ItemsSource = dt.DefaultView;
}

You can then retrive any column values of the selected row in the DataGrid like this:
DataRowView drv = MydataGrid_roll.SelectedItem as DataRowView;
if(drv != null)
{
    int selectedRoll = Convert.ToInt32(drv["roll"]);
    if(drv["tc"] != DBNull.Value)
    {
        string selectedTc = drv["tc"].ToString();
    }
    //...
}


text:
Q: Why doesn't Rails throw an exception when we access an undefined instance variable in the view? Suppose we have the following implementation:
app/controllers/cars_controller.rb
class CarsControllers < ApplicationController
  def index
    @test = '7'
  end
end

app/views/cars/index.html.erb
My test variable is <%= @test %>.
Here is an undefined variable <%= @test2 %>.

How come accessing @test2 doesn't throw an exception (Given we are trying to access an instance variable)?

A: Undefined instance variable value will always nil, If you will access it, it will not throw any exception, while local variable will throw exception if did not defined it, if you want to check instance variable is assigned or not you can use .present? method.
Here are simple example of it
Instance variable
2.5.1 :009 > @undefined
 => nil
2.5.1 :010 > @undefined.present?
 => false
2.5.1 :011 > defined? @undefined
 => nil

2.5.1 :014 > @defined = "test"
 => "test"
2.5.1 :015 > @defined.present?
 => true
2.5.1 :016 > defined? @defined
 => "instance-variable"

Local variable
2.5.1 :017 > undefined_local
Traceback (most recent call last):
        1: from (irb):17
NameError (undefined local variable or method `undefined_local' for main:Object)
2.5.1 :018 > undefined_local.present?
Traceback (most recent call last):
        1: from (irb):18
NameError (undefined local variable or method `undefined_local' for main:Object)
2.5.1 :019 > defined? undefined_local
 => nil
 2.5.1 :020 > defined_local = "test"
 => "test"
2.5.1 :021 > defined? defined_local
 => "local-variable"

Hope this is enough to understand the concept

A: It doesn't pose a problem in your example because @test2 simply returns nil when undefined.
You can verify this in an irb console session:
2.6.2 :001 > @test2
 => nil

However ... if you were to call a method assumed to be provided by @test2 then you'd have a problem:
2.6.2 :002 > @test2.name
Traceback (most recent call last):
        1: from (irb):2
NoMethodError (undefined method `name' for nil:NilClass)

In that case, you definitely would receive an error when Rails tried to render the view.

A: In most programming languages, instance variables must be declared before they can be assigned. Ruby is the diametric opposite – instance variables cannot be declared at all. Instead, an instance variable in Ruby comes into existence the first time it is assigned.
That's why accessing an instance variable that has not been assigned does not raise an error.
@test2 is nil when it is accessed before assignment.
See docs: https://www.sitepoint.com/common-trip-ups-new-rubyists-part/


text:
Q: Alt + D in Windows 10 Alt + D is not working in the file explorer. I have a personal windows license. Is it possible to open this shortcut? Or I just basically have to use F4, which do the job but have disadvantages.
By the way, I am using Turkish Keyboard Layout.

A: I want to answer my own question because I found a solution for this problem. Basically, I change the language of Windows. It works!
However, If you are using Windows 10 Single Language, you can do the steps described by the user "Tatoline", and after setting your default language as English, this will do the job. This is not the complete solution of the problem but at least it works.
Click Here In Order To Solve Single Language Problem
I hope this works for others and help someone who encounters this particular issue.


text:
Q: URL Rewrite IIS 7.5 "?" character int the request url I have a incoming request URL which is:
http://localhost/MyService/myservice.svc?serverInfo&pVersion=00

I wrote a rule into the webconfig (with the URL Rewrite in IIS Manager):
<rule name="ServerInfo" stopProcessing="true">
                    <match url="myservice[.]svc[\?]serverInfo[&]pVersion[=]([^]+)" />
                    <action type="Redirect" url="myservice.svc/folder/serverInfo/pVersion={R:1}" />
                </rule>

But it's not working because i use a "?" character in the match url.
How should I change the regular expression to work properly?
(I must make a redirect / rewrite because it's a restful WCF service and it's don't support the type of the incoming url)

A: Do this instead:
<rule name="ServerInfo" stopProcessing="true">
  <match url="myservice.svc" ignoreCase="true" />

  <conditions logicalGrouping="MatchAll">
    <add input="{QUERY_STRING}" pattern="serverInfo&pVersion=([^]+)" />
  </conditions>

  <action type="Redirect"
          url="myservice.svc/folder/serverInfo/pVersion={C:1}"
          appendQueryString="false"
          redirectType="Found" />
</rule>


text:
Q: Map source class to a target field I'm working on spring boot application where, I have two classes namely A and B.
@Data
class A{
 int id;
 String name;
}

@Data
class B{
 int bId;
 A a;
}

I need to map a field of class B which is a using mapstruct. How to map a source class A to target field a as well as to class B.
Example mapper will be like
@Mapping(source="id", target="bId")
B fromClassA(A a);

A: You can use @AfterMapping, something like this:
@Mapping(source="id", target="bId")
B fromClassA(A a);
@AfterMapping
default void fillAinB(@MappingTarget B target, A source) {
  b.setA(source);
}

A: The best way to do the mapping would be to define it in @Mapping.
e.g.
@Mapping(source="id", target="bId")
@Mapping(target = "a", source="a")
B fromClassA(A a);

You can use the name of the parameter in the Mapping#source


text:
Q: Firebase console does not display data I received this error in my browser console:

WebSocket connection to 'wss://s-usc1c-nss-109.firebaseio.com/.ws?v=5&ns=dashroad-fleet-management' failed: WebSocket is closed before the connection is established.

If I navigate to other projects in Firebase, their data load and display just fine.
Edit 1: New error in browser console upon page reload:

WebSocket connection to
  'wss://s-usc1c-nss-109.firebaseio.com/.ws?v=5&ns=dashroad-fleet-management'
  failed: Error in connection establishment: net::ERR_NAME_NOT_RESOLVED
qh.open @
  third_party/javascript/firebase/firebase_js_minified.jslib:176

Edit 2: If I let the browser tab be, eventually the data is loaded once the WebSocket connection is established (the WebSocket Connection error stops appearing)

A: If this error occurs in chrome, just ignore it. There was a problem with webkit \ chrome, some websocket related issues.
This error can also occur due to malformed URL.
What does Err_name_not_resolved mean?
DNS is the network service that translates a website's name to its Internet address. This error is most often caused by having no connection to the Internet or a misconfigured network. It can also be caused by an unresponsive DNS server or a firewall preventing Google Chrome from accessing the network.
Source google
net::ERR_NAME_NOT_RESOLVED
This seems to DNS resolution problem. Enter DNS servers addresses manually in the Internet Protocol (IP) v4 settings in your computer network settings. Use public DNS addresses such as 8.8.8.8, 8.8.4.4, 4.2.2.2 etc.


text:
Q: Convert multiples sequences from fastq to fasta in a folder I want to convert all the fastq files contained in a folder to fasta format, each file will keep the original name but in fasta extension, I have made the next code in perl, however it only extract the last sequence of each file !!!
#!/usr/bin/perl

use strict;
use warnings;
use Getopt::Long;

my ($dir, $files, $file_name, $file_format);

    GetOptions (
                'dr=s'  =>\$dir
                );

foreach $files (glob("$dir/*.fastq")) {
        open LINE, "<", $files or die "can't read open $files";
            while(
                    defined(my $head    = <LINE>)       &&
                    defined(my $seq     = <LINE>)       &&
                    defined(my $qhead   = <LINE>)       &&
                    defined(my $quality = <LINE>)
            ){
                        substr($head, 0, 1, '>');
                        ($file_name, $file_format) = split (/\./,$files);
                        open OUTFILE, '>', $file_name.".fasta";
                        print OUTFILE $head, $seq;
            }
}
close LINE;
close OUTFILE;
exit;

and extra question, I want to use the pice next code, as a subroutine, I want to develop the same scrip to have the option of convert all fastq files in a folder or single file to fasta file !!!
while(
                        defined(my $head    = <LINE>)       &&
                        defined(my $seq     = <LINE>)       &&
                        defined(my $qhead   = <LINE>)       &&
                        defined(my $quality = <LINE>)
                ){

A: Kinda of new to perl myself and don't know a thing about bioinformatics, but it looks like you are overwriting the output file with every turn of the while loop.   I think you want to append to the file so you want a >> not just >.  example
open OUTFILE, '>>', $file_name.".fasta";

Hope that helps.


text:
Q: Selenium - How to hover on a point with double/float coordinates? Currently, Selenium's Actions class only has this as a function for moveToElement:
public Actions moveToElement(WebElement toElement, int xOffset, int yOffset {
    action.addAction(new MoveToOffsetAction(mouse, (Locatable) toElement, xOffset, yOffset));
    return this;
}

However, the website's coordinates have float coordinates (ex. (200.5,0)). Is there any way I can hover to this specific point?
[EDIT]:
This is the method I'm trying to do. Works perfectly fine with whole number coordinates
public void hoverPt(String xAxis) throws Exception //Use Build Interaction
{
int x = Integer.parseInt(xAxis);
WebDriver driver = WebManager.getDriver();
WebElement lineGraph = driver.findElement(By.xpath("[xpath of chart plane]"));
Actions builder = new Actions(driver);
builder.moveToElement(lineGraph, x, 0).build().perform();
Thread.sleep(5000);
}

The String xAxis was fetched from an excel sheet, then I just parsed it to int so I can parameterize it to moveToElement.

A: You can use Robot class for this:
    Point p = toElement.getLocation();
    int x = p.getX();
    int y = p.getY();
    Dimension d = toElement.getSize();
    int h = d.getHeight();
    int w = d.getWidth();
    Robot r = new Robot();
    r.mouseMove(x + (w/2), y+(h/2) +80);


text:
Q: Executing testcases from jenkins and getting error We have automated few test cases and trying to execute the same test cases from jenkins and getting below error:
+ pybot -x junit.xml run.robot
==============================================================================
Run
==============================================================================
sip-001                                                               | PASS |
------------------------------------------------------------------------------
sip-002                                                               | PASS |
------------------------------------------------------------------------------
Run                                                                   | PASS |
2 critical tests, 2 passed, 0 failed
2 tests total, 2 passed, 0 failed

Output:  /opt/bitnami/apps/jenkins/jenkins_home/jobs/integration-test/workspace/output.xml
[ ERROR ] Reading XML source '/opt/bitnami/apps/jenkins/jenkins_home/jobs/integration-test/workspace/output.xml' failed: ImportError: No module named expat; use SimpleXMLTreeBuilder instead

Here Testcases are passed but results junit.xml are not generating.
The same testcases if we execute from Ubuntu machine. /path/run.robot .
The Testcases are passed and results are generating like junit.xml, output.xml etc..
Manually testcases are executing fine and results are generating.
Can anyone please guide me in resolving the above error which we got while executing from Jenkins.

A: You can use https://wiki.jenkins-ci.org/display/JENKINS/Robot+Framework+Plugin robotframework plugin to display results in Jenkins.

A: WORKAROUND: This won't help you keep using Jenkins, but I had a similar issue with Test Cases running fine when I executed them manually from the command prompt on Windows or running Robot Framework in Eclipse. When running in Jenkins I got failures and never was able to get an answer from anyone, anywhere. I finally just dumped Jenkins all together and set up a Windows Task Manager to have the Robot Framework test case run from there instead. I'll continue using that until someone gets me a real fix or answer that I can actually implement. By the way: Thanks for the negative! Keep them coming.


text:
Q: Continuous Collision Detection - how to find the collision according to these 2 equations in C++
I know this topic is known - Continuous Collision Detection
I have 2 Spheres that I have to find intersection between them as shown in the image.
the equations refer to the upper draw and I need to find the minimal t and then check something about the distance. I have no idea what these equations mean.

*

*what is each variable?  I guess p10 and p20 are the first positions and v1 \ v2 are the direction vectors.

*no acceleration, no mass..

*the equations refer to 2 spheres that move. if ONLY ONE sphere moves, the equations solve
it too because then, the velocity of 1 sphere will be zero.

*so how do I have to solve the equations? to find the minimal t that....?
thanks a lot!

A: This is probably a question for StackExchange Mathematics. But here's my answer: The two equations tell you where the centers P_1 and P_2 of the circles or balls are at some point in time t are. Now you need to find a value for t for which the distance between P_1 and P_2 is the sum of the radii which I will call d (like distance). According the the theorem of Pythagoras the square of the distance of the two points is the sum of the squares of the coordinate differences. This square of the distance is a quadratic polynomial in t, i.e. a*t*t+b*t+c. Now you can find the value of t where the two balls or circles collide by setting this equal to d*d and solving for t. If there is no solution, then the balls/circles won't collide.


text:
Q: Duplicates quotes method hash join I have a hash with those elements
@ratings = {"PG"=>"1", "PG-13"=>"1"}

I select only the keys and separate it with ,
keys = @ratings.keys.join("','")

I want to use them in a select in query:
Movies.where(:rating => [keys])

But it only works with a simple value, because when there are more, the quotes are duplicated:
SELECT "movies".* FROM "movies" WHERE "movies"."rating" IN ('PG'',''PG-13')

Why does it duplicate the quote?

A: By using the join you are passing a string to your where clause and the layer that generates the SQL string is sanitizing your input. I assume you are using ActiveRecord? If so, then simply pass the array directly.
Movies.where(:rating => @ratings.keys)


text:
Q: Installing flex on Mac Parallels I am trying to install Flex 3 on my Windows 7 Virtual machine (parallels desktop) on my Mac Pro.
The problem seems to be some sort of conflict between the copy of Flex 3 Builder installed on Mac OS X.
The installer tries to install Flex in x:/Program Files/Adobe/Flex Builder 3/
but since Parallels Desktop connects all directories, there resides the Flex Builder 3 installation of MAC.
I get this error Log:
!SESSION 2010-04-22 16:09:23.031 -----------------------------------------------
eclipse.buildId=unknown
java.version=1.5.0_11
java.vendor=Sun Microsystems Inc.
BootLoader constants: OS=win32, ARCH=x86, WS=win32, NL=de_DE
Framework arguments:  -application org.eclipse.update.core.standaloneUpdate -command install -from file:\C:\Program Files\Adobe\Flex Builder 3 Windose\com.adobe.flexbuilder.update.site/ -featureId com.adobe.flexbuilder.feature.standalone -version 3.0.214193
Command-line arguments:  -application org.eclipse.update.core.standaloneUpdate -command install -from file:\C:\Program Files\Adobe\Flex Builder 3 Windose\com.adobe.flexbuilder.update.site/ -featureId com.adobe.flexbuilder.feature.standalone -version 3.0.214193
!ENTRY org.eclipse.update.core 4 0 2010-04-22 16:09:29.187
!MESSAGE Cannot install featurecom.adobe.flexbuilder.feature.standalone 3.0.214193

A: I had the same problem and the solution was deactivate the option "enable share profile" on the parallels virtual machine options (well, i am not sure if on english his name is that).
After it i could install any program (including flex builder) without problems. :)


text:
Q: Change menu when front user loggs in - Wordpress I have two menus, difference is only one page. I have front end users build using 'front end only user' plugin. I want to show one menu when user is logged out and secon when user is logged in.
I have tried severaln plugins 'nav  role menu' i 'if menu' but they are not working.
Also tried with this code but 0 success.
function my_wp_nav_menu_args( $args = '' ) {

if( is_user_logged_in() ) {
    $args['menu'] = 'logged-in';
} else {
    $args['menu'] = 'logged-out';
}
    return $args;
}
add_filter( 'wp_nav_menu_args', 'my_wp_nav_menu_args' );

What might be a problem.

A: use this snippet or override your current code to display the menus in theme.
<?php
if( is_user_logged_in() ) {
  wp_nav_menu( array( 'theme_location' => 'login-menu');
} else {
  wp_nav_menu( array( 'theme_location' => 'logout-menu');
}
?>

hope this will helps you.
For more information.

*

*Show Different Navigation Menu to your Members and Non-members

*Showing a different menu in Primary Navigation location conditionally in Genesis


text:
Q: How to set variable value while publishing the build artifacts? Below is the code snippet that I used to read the AppName from appsettings.json file.
Startup.cs → ConfigureServices()
services.Configure<CustomConfig>(Configuration.GetSection("CustomConfig"));
services.AddSingleton(resolver => resolver.GetRequiredService<IOptions<CustomConfig>>().Value);

CustomConfig.cs
public class CustomConfig
{
   public string AppName { get; set; }
}

But my requirement is, AppName will change based on different customers but at the same time that should not be maintained in the appsettings.json file.
So my question is, how to set a variable value while publishing the application, instead of reading it from configuration files/environment level variables?

A: ASP.NET Core doesn't use build configurations, and the published code is not specific to any sort of environment. That's by design. Your best bet is to probably assign each customer their own environment. Then, you could have customer-specific appsettings.json files: appsettings.Customer1.json, appsettings.Customer2.json, etc.
The actual environment that's utilized is controlled by the ASPNETCORE_ENVIRONMENT environment variable, typically, though there's other ways to specify the environment. Depending on how you're ultimately hosting this, the best method for doing that differs. If you're running in a container or something like Azure App Services, then just stick with the ASPNETCORE_ENVIRONMENT environment variable, which can be easily set per running instance.
If you're starting the app from the command line directly, you can pass the environment via the --environment command line argument when calling running dotnet.
If you're hosting these all on the same IIS server, for instance, then you can add it to the Web.config, but you'd probably want a more robust solution than that. If you create publish profiles for each customer, then you can add the the following to each publish profile (.pubxml):
<PropertyGroup>
  <EnvironmentName>Customer1</EnvironmentName>
</PropertyGroup>

Then, when you publish with that particular profile, that environment will be added to the Web.config for you automatically. However, this is just a more automated way of getting the value in the Web.config. There's no functional difference in the actual published app, and you could easily go in after the fact and switch the environment to something else.


text:
Q: Redirect /category/item/id-title.html to /category/title using .htaccess If I have the following old links: example.com/category/item/id-tile.html
how can I redirect them to example.com/category/title
Category changes based on category, item is static, id and title change also. I tried to figure a way through .htaccess, but I don't know how do deal with the id-title thing.


text:
Q: Algorithm to find all possible combinations of a group of LEGOs? The other day I walked by a LEGO store in The Mall I was shopping at, and it brought back some memories. Then that got me thinking: There's got to be some mathematical algorithm to find all the possible combinations of any given group of LEGO pieces. (If you don't know what LEGOs are, see this link). I'm not great in the math department, but I was wondering if anyone's already  come up with something like this, or if someone could. I just thought this would be an interesting idea.
Edit: I understand that this is quite a bit more difficult than I thought when I originally proposed the idea, so for the sake of simplification, suppose that they're just regular 2x4 legos of the same color. The number of them would be 2. After that we could try 3 to see if our algorithm works.