text:
Q: How can i persist only parent object not child object in jpa? I have two class A and class B. class A is parent and class B is child
Now I want to persist only A. And I can also update B in future.
 @Entity
 @Table(name = "A")
 public class A{
   @Id
   @Column(name="id")
   @GeneratedValue(strategy=GenerationType.AUTO)
   private long id;
 }

 @Entity
 @Table(name = "N")
 public class B{
   @ManyToOne
   @JoinColumn(name = "id")
   private A a;
 }

when I persist only A then I need to set B object in A. If not set B object in A then get exception. If set B object in A then both object are persist.
Thanks

A: suppose the solution for your question is You need to specifiy the realtionship between A and B(somthing like @ManyToOne).
Or if A is not an own Entity, then mark it with @Embeddable, and add @Embedded to the variable declaration in B .
@Entity
@Table(name = "A")
@Embeddable
 public class A{
 @Id
 @Column(name="id")
 @GeneratedValue(strategy=GenerationType.AUTO)
 private long id;
}

 @Entity
 @Table(name = "N")
 public class B{

  @Embedded
  private A a;
}


text:
Q: Using sed to comment out lines that contain a specific string of text Please bear with me as I'm new to the forums and tried to do my research before posting this.  What I'm trying to do is to use sed to look through multiple lines of a file and any line that contains the words 'CPU Usage" I want it to comment out that line and also 19 lines immediately after that.
Example file.txt
This is some random text CPU USAGE more random text
Line2
Line3
Line4
Line5
etc.

I want sed to find the string of text CPU usage and comment out the line and the 19 lines following
#This is some random text CPU USAGE more random text
#Line2
#Line3
#Line4
#Line5
#etc.

This is what I've been trying but obviously it is not working since I'm posting on here asking for help
sed '/\/(CPU Usage)s/^/#/+18 > File_name
sed: -e expression #1, char 17: unknown command: `^'

I'd like to be able to use this on multiple files. Any help you can provide is much appreciated!

A: GNU sed has a non-standard extension (okay, it has many non-standard extensions, but there's one that's relevant here) of permitting /pattern/,+N to mean from the line matching pattern to that line plus N.
I'm not quite sure what you expected your sed command to do with the \/ part of the pattern, and you're missing a single quote in what you show, but this does the trick:
sed '/CPU Usage/,+19 s/^/#/'

If you want to overwrite the original files, add -i .bak (or just -i if you don't mind losing your originals).
If you don't have GNU sed, now might be a good time to install it.

A: This can easily be done with awk
awk '/CPU Usage/ {f=20} f && f-- {$0="#"$0}1' file

When CPU Usage is found, set flag f=20
If flag  f is true, decrements until 0 and for every time, add # in front of the line and print it.

A: Think this should work, cant test it, if anyone finds something wrong just let me know :)
awk '/CPU Usage/{t=1}t{x++;$0="#"$0}x==19{t=0;x=0}1' file

redpajama_set_name: RedPajamaStackExchange


text:
Q: Formarray inside formArray in angular 4 I am trying to implement formarray inside formarray but its not working, tried below too but doesn't work.
How to get FormArrayName when the FormArray is nested in another FormArray?
could someone please help me where am i doing wrong in below code
HTML

  <mat-radio-group matInput formControlName="Applies">
    <mat-radio-button *ngFor="let applie of applies" [value]="applie.id">{{applie.value}}</mat-radio-button>
  </mat-radio-group>

        <mat-icon *ngIf="MainFormGroup.get('FormArrayOne').length > 1" (click)="removeMarket(i)">remove_circle</mat-icon>
        <mat-icon (click)="addOne()"> add_circle</mat-icon>
        <mat-form-field>
          <input matInput formControlName="OneField" value="">
        </mat-form-field>

              <mat-form-field class="formfieldsControl">
                <input matInput formControlName="Destination">
              </mat-form-field>

TS
public ngOnInit() {
  this.MaintFormGroup = this._fb.group({
    Applies : '',
    FormArrayOne: this._fb.array([
      this.initArrayOne(),
    ])
  });
}
public initArrayOne() {
  return this._fb.group({
    OneField: '',
    FormArrayTwo : this._fb.array([
      this.initFormArrayTwo()
    ])
  });
}
public addMarket() {
  const control = <FormArray> this.MaintFormGroup.get('FormArrayOne');
  control.push(this.initArrayOne());
}
public removeMarket(i: number) {
  const control = <FormArray> this.MaintFormGroup.get('FormArrayOne');
  control.removeAt(i);
}
public initFormArrayTwo() {
  return this._fb.group({
    Destination : ''
  });
}
public addFormArrayTwo() {
  const Control = <FormArray> this.MaintFormGroup.get('FormArrayTwo');
  Control.push(this.initFormArrayTwo());
}
public removeFormArrayTwo(j: number) {
  const Control = <FormArray> this.MaintFormGroup.get('FormArrayTwo');
  Control.removeAt(j);
}

A: This link is more of a gist to the problem but you can take a look at this project i created on stackblitz which has deep nested forms .


text:
Q: How to disable Orientation Sensor during "Shake" action I'm developing an app which use pitch/roll values and I also want to implement a "shake" functionality. With code below, I toast every of desired actions but, when I shake phone it sometimes catch this action as "shake" and short roll/pitch. I want to separate "shake" from pitch/roll actions.
App should work on Android 2.2, so that is also limitation on available sensors.
I tried to block Orientation sensor with boolean variable accelerometer, but it is not working. Any suggestions?
public void onSensorChanged(SensorEvent event) {
    // TODO Auto-generated method stub
    synchronized (this) {
        switch (event.sensor.getType()){

        case Sensor.TYPE_ACCELEROMETER:
            float[] values = event.values;
            float x = values[0];
            float y = values[1];
            float z = values[2];

            accelerometer = true;
            mAccelLast = mAccelCurrent;
            mAccelCurrent = (float) FloatMath.sqrt((float) (x*x + y*y + z*z));
            float delta = mAccelCurrent - mAccelLast;
            mAccel = mAccel * 0.9f + delta;

            if (mAccel>2.5){
                Toast.makeText(this, "SHAKE!!!!", Toast.LENGTH_SHORT).show();
            } else {
                accelerometer=false;
            }

        break;

        case Sensor.TYPE_ORIENTATION:
            if (!accelerometer){
            pitch = event.values[1];
            roll = event.values[2];

            if (pitch > Constants.PITCH_ANGLE && pitchUpAction == false && roll < Constants.BASE_ANGLE && roll > - Constants.BASE_ANGLE) {
                oriStartTime = System.currentTimeMillis();
                pitchUpAction = true;
            } else if (pitch < - Constants.PITCH_ANGLE && pitchDownAction == false && roll < Constants.BASE_ANGLE && roll > - Constants.BASE_ANGLE){
                oriStartTime = System.currentTimeMillis();
                pitchDownAction = true;
            } else if (roll > Constants.ROLL_ANGLE && rollLeftAction == false && pitch < Constants.BASE_ANGLE && pitch > - Constants.BASE_ANGLE){
                oriStartTime = System.currentTimeMillis();
                rollLeftAction = true;
            } else if (roll < - Constants.ROLL_ANGLE && rollRightAction == false && pitch < Constants.BASE_ANGLE && pitch > - Constants.BASE_ANGLE){
                oriStartTime = System.currentTimeMillis();
                rollRightAction = true;
            }

            if ((pitchUpAction || pitchDownAction) && pitch < Constants.BASE_ANGLE && pitch > -Constants.BASE_ANGLE){
                oriElapsedTime = System.currentTimeMillis() - oriStartTime;

                if(oriElapsedTime>(2*1000)) {
                    if(pitchUpAction){
                        Toast.makeText(getBaseContext(), "Pitch up 2s", Toast.LENGTH_SHORT).show();
                    } else if(pitchDownAction){
                        Toast.makeText(getBaseContext(), "Pitch down 2s", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    if(pitchUpAction){
                        Toast.makeText(getBaseContext(), "Pitch up short", Toast.LENGTH_SHORT).show();
                    } else if(pitchDownAction){
                        Toast.makeText(getBaseContext(), "Pitch down short", Toast.LENGTH_SHORT).show();
                    }
                }
                pitchUpAction = pitchDownAction = false;
            } else if ((rollLeftAction || rollRightAction) && roll < Constants.BASE_ANGLE && roll > -Constants.BASE_ANGLE){
                oriElapsedTime = System.currentTimeMillis() - oriStartTime;

                if(oriElapsedTime>(2*1000)) {
                    if(rollLeftAction){
                        Toast.makeText(getBaseContext(), "Roll Left 2s", Toast.LENGTH_SHORT).show();
                    } else if(rollRightAction){
                        Toast.makeText(getBaseContext(), "Roll Right 2s", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    if(rollLeftAction){
                        Toast.makeText(getBaseContext(), "Roll left short", Toast.LENGTH_SHORT).show();
                    } else if(rollRightAction){
                        Toast.makeText(getBaseContext(), "Roll right short", Toast.LENGTH_SHORT).show();
                    }
                }
                rollLeftAction = rollRightAction = false;
            }
            }

        break;
        }
    }
}


text:
Q: Android - problem with Google API and Youtube Data v3 I am facing an issue with Youtube API v3, in particolar with Google API (gapi for short).
My final goal is to call the Youtube Data API videos/list to obtain all the info about a specific video.
As per documentation, i followed the recommended steps until step 5 (the example there is a bit outdated) but without success.
Android quickstart doc: https://developers.google.com/youtube/v3/quickstart/android
So, i checked their API docs on how to compose said request here, and i tried composing the request with the parameters part: "snippet" and id: "o-YBDTqX_ZU" (or any other id). There you can see their implementation: uncheck OAuth 2.0 and leave only API Key, then Execute / Show code / Java. I tried to readjust their code to my needs.
https://developers.google.com/youtube/v3/docs/videos/list?hl=en
https://developers.google.com/explorer-help/guides/code_samples#java
Here's my app-level build.gradle
plugins {
  id 'com.android.application'
  id 'kotlin-android'
}

android {
  compileSdk 30

  defaultConfig {
    applicationId "com.example.testyoutubeapi"
    minSdk 23
    targetSdk 30
    versionCode 1
    versionName "1.0"

    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
  }

  buildTypes {
    release {
      minifyEnabled false
      proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
  }
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
  kotlinOptions {
    jvmTarget = '1.8'
  }
}

dependencies {

  implementation 'androidx.core:core-ktx:1.6.0'
  implementation 'androidx.appcompat:appcompat:1.3.1'
  implementation 'com.google.android.material:material:1.4.0'
  implementation 'androidx.constraintlayout:constraintlayout:2.1.0'

  implementation 'com.google.android.gms:play-services-auth:19.2.0'
  implementation 'pub.devrel:easypermissions:0.3.0'

  implementation 'com.google.api-client:google-api-client:1.23.0'
  implementation 'com.google.oauth-client:google-oauth-client-jetty:1.23.0'
  implementation 'com.google.apis:google-api-services-youtube:v3-rev192-1.23.0'
  implementation 'com.google.api-client:google-api-client-android:1.23.0' exclude module: 'httpclient'

  implementation 'com.google.apis:google-api-services-tasks:v1-rev48-1.23.0' exclude module: 'httpclient'
  implementation 'com.google.http-client:google-http-client-gson:1.23.0' exclude module: 'httpclient'

  testImplementation 'junit:junit:4.13.2'

  androidTestImplementation 'androidx.test.ext:junit:1.1.3'
  androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

}

And here is my YoutubeAPI class
class YoutubeAPI() {

    companion object {
        const val DEVELOPER_KEY = "AIzaS......" // API key
        const val APPLICATION_NAME = "API code samples"
        private val JSON_FACTORY: JsonFactory = JacksonFactory.getDefaultInstance()
    }

    private fun getService(): YouTube {
        val httpTransport: HttpTransport = AndroidHttp.newCompatibleTransport() //GoogleNetHttpTransport.newTrustedTransport();
        return YouTube.Builder(httpTransport, JSON_FACTORY, null)
            .setApplicationName(APPLICATION_NAME)
            .build();
    }

    fun start(): VideoListResponse {
        val youtubeService = getService()
        val request: YouTube.Videos.List = youtubeService.videos()
            .list("snippet")
            .setKey(DEVELOPER_KEY)
            .setId("o-YBDTqX_ZU")

        return request.execute()
    }
}

Here, when calling AuthorizationCodeInstalledApp(flow, LocalServerReceiver()).authorize("user") an error is thrown, saying that the operation is not permitted
E/AndroidRuntime: FATAL EXCEPTION: Thread-2
    Process: com.example.testyoutubeapi, PID: 2209
    java.net.SocketException: socket failed: EPERM (Operation not permitted)
        at java.net.Socket.createImpl(Socket.java:492)
        at java.net.Socket.getImpl(Socket.java:552)
        at java.net.Socket.setSoTimeout(Socket.java:1180)
        at com.android.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:143)
        at com.android.okhttp.internal.io.RealConnection.connect(RealConnection.java:116)
        at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:186)
        at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:128)
        at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:97)
        at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:289)
        at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:232)
        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:465)
        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:131)
        at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.connect(DelegatingHttpsURLConnection.java:90)
        at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:30)
        at com.google.api.client.http.javanet.NetHttpRequest.execute(NetHttpRequest.java:104)
        at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:981)
        at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
        at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
        at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
        at com.example.testyoutubeapi.YoutubeAPI.start(YoutubeAPI.kt:47)
        at com.example.testyoutubeapi.MainActivity.onCreate$lambda-1$lambda-0(MainActivity.kt:23)
        at com.example.testyoutubeapi.MainActivity.$r8$lambda$6AdxmbUe_rlaFrgzSeLUApTyS2A(Unknown Source:0)
        at com.example.testyoutubeapi.MainActivity$$ExternalSyntheticLambda1.run(Unknown Source:4)
        at java.lang.Thread.run(Thread.java:919)

A: The problem here is that Google disable api calls after 90 days of inactivity.
Maybe create a request that fires every X days (or ask your backend dev to do it).
If that's not the case, this is a permnission-related problem. Please be sure to have the following permissions in your manifest file
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Then, simply uninstall the app on the emulator, then

*

*Build -> Clean Project

*Build -> Rebuild Project

*File -> Invalidate Caches / Restart

Run your app again and it should work!


text:
Q: Como remover registros duplicados no MySQL com condição WHERE Minha tabela de catálogo de endereços tem muitos endereços duplicados para cada cliente. Note na imagem abaixo que tenho muitos CEPs duplicados para o mesmo cliente com o ID 12.

Preciso remover os endereços duplicados onde postcode e parent_id sejam maior que 1 e manter um endereço na mesma condição, ou seja, tem que manter um 14402-408, 14403-707, 60150-170 e 81050-130.
De uma maneira simples precisaria do seguinte:
DELETE * FROM catalog_address
WHERE parent_id AND postcode > 1

Não consegui achar caso semelhante, vi bastante questões de remover duplicados como abaixo:
Como deletar todos os duplicados, exceto um?, mas ao meu ver não resolve meu caso.
Como seria a instrução MYSQL para este caso?
Obrigado!

A: Você pode fazer um INNER JOIN com a mesma tabela para encontrar os duplicados. No seu caso será considerado duplicado se houver outro registro com o mesmo parent_id, o mesmo post_code e um entity_id menor:
DELETE b
FROM `catalog_address` a
INNER JOIN `catalog_address` b ON a.`parent_id` = b.`parent_id` AND a.`post_code` = b.`post_code` AND a.`entity_id` < b.`entity_id`
WHERE a.`parent_id` > 1 AND a.`post_code` > 1;

Para consultar os registros que serão removidos no DELETE acima, utilize o SELECT abaixo:
SELECT b.*
FROM `catalog_address` a
INNER JOIN `catalog_address` b ON a.`parent_id` = b.`parent_id` AND a.`post_code` = b.`post_code` AND a.`entity_id` < b.`entity_id`
WHERE a.`parent_id` > 1 AND a.`post_code` > 1;


text:
Q: Confused about PL/SQL snippet with dynamic SQL This snippet runs w/o errors unless I uncomment for loop, in which case I getting
Error report:
ORA-06550: line 12, column 41:
PL/SQL: ORA-00942: table or view does not exist

My question is why error occurs with for loop uncommented?
set serveroutput on
declare
  v_sql varchar2(2000);
  v_tmp number;
begin
  dbms_output.enable(null);
  v_sql := 'CREATE TABLE tmp_bank_codes (name varchar2(256), code varchar2(256))';
  dbms_output.put_line('Will do ' || v_sql);
  execute immediate v_sql;
  v_sql := 'INSERT INTO tmp_bank_codes (name, code) VALUES (''Bank of America'', ''BOANY (NY)'')';
  dbms_output.put_line('Will do ' || v_sql);
  execute immediate v_sql;
--for bank_code in (select name, code from tmp_bank_codes) loop
--  select 1 into v_tmp from dual;
--end loop;
execute immediate 'drop table tmp_bank_codes';
rollback;

end;
/

A: The error is because you use dynamic sql to create the table and the in the for loop you are using the table.
While compiling the procedure, compiler doesnt know that you have created the table with dynamic sql
Here are your options:

*

*make the for loop also with Dynamic SQL

*change the dymamic sql to create the table to normal sql statement

I would prefer the second option, as the dynamic sql will not take the cached execution plans, thus slows down the query
For option 1 you could do this, replace your commented code part with the following
v_sql :='for bank_code in (select name, code from tmp_bank_codes) loop
        select 1 into v_tmp from dual;
        end loop';
execute immediate v_sql;

A: This is a parser error. tmp_bank_codes doesn't exist at compile-time.

A: First the engine tries to compile your anonymous script. In this first step tmp_bank_codes table does not exists.
A solution would be something like
execute immediate `select 1 from tmp_bank_codes where rownum = 1` into v_tmp;


text:
Q: query builder get modal instance I'm using Laravel 5.5.
I'm trying to get an object instance with the Query Builder of Laravel.
public function functionName(Request $request) {
    $seance = Seance::where('id_seance', '=', $request->idSeance)->get();

    return $seance->type_seance;
}

My model : Seance(id_seance, type_seance, capacite_seance, niveau_seance, avec_coach, date_seance, heure_seance).
However I get this error :

Exception: Property [type_seance] does not exist on this collection
  instance

Thank's for help!

A: Use first() instead of get() to get an object instead of collection of objects:
$seance = Seance::where('id_seance', $request->idSeance)->first();

The difference between these methods is explained here.

A: Get() method return a collection object it's like an array, you need to use first method to get the first object:
public function functionName(Request $request) {
    $seance = Seance::where('id_seance', '=', $request->idSeance)->first();

    return $seance->type_seance;
}

You can use find() method too but id_seance should be the primary key of your table:
$seance = Seance::find($request->idSeance);
return $seance->type_seance;

A: When using the get() method, it will return a collection rather than an instance of the model. I suggest using thefirst() method instead.
Better yet, useSeance::find($request->idSeance) or Seance::findOrFail($request->idSeance). This assumes that you've defined your primary key on your model correctly.


text:
Q: Windows 10 possible bug for Gigabit ISP connections for main network device? I am super frustrated with this topic as my main problem is that I have a Gigabit connection and is not working as expected on Windows 10 normal boot. I am starting to think that this is a new recent bug but I was not able to find anything related to this... FYI I sometimes reach 1010 Mbps, so my ISP is not the problem and you will see why.
So the issue is, as I stated, that my Gigabit network does not reach even 400 Mbps on my Windows 10, current hardware and software info:

*

*OS: Windows 10 Pro

*Version: 20H2

*Build: 19042.630

*CPU: i9 9900x

*OS installed on a Samsung NVMe M2 960 PRO (512 Gb)

*Motherboard: Asus ROG x299 e-gaming (it can handle 1 Gbps and it comes with integrated AC WiFi)

*My router: Asus ROG GT-AC5300

Things I have tried (even all together):

*

*Shutting everything down on my network

*Shutting everything down on my PC (processes)

*Doing a fresh install (format 100%)

*Changing network cable from CAT5 to CAT6

*Connect directly to Modem

*I tried changing Bandwidth Reserve on Policy Manager

*I tried the CMD auto tuning thing

*I tried turning off Automatic Proxy

*I tried turning off IPv6

*I tried turning off Large packets or something like that

*I think more things but it will not matter you will see why

*I do not have an antivirus apart of Windows Defender

*My Firewall is off

Things I have tried that seems to show different results on the same OS and PC (and this is why I think it is a new Windows 10 bug):

*

*I also have dual boot (Ubuntu 18.04 + Ubuntu 20.04) and both downloads mostly everything and instantly at 110 Mb/s (950 mbps)

*I have tried using my Wifi connection (I have previously said my motherboard has a Wifi connection too) and it starts downloading same thing at higher speeds, ethernet uses approximately 300 mbps, and Wifi (on status says 840 Mbps connection), I get download speeds of 600 Mbps - 500 Mbps when downloading same thing.

*I boot my windows on safe boot with network and I instantly have 950 mbps on my downloads but on normal boot NOT, only 300 mbps

*I have tried a fresh install using latest windows ISO tool, and when I started using it (without installing any software), I tried downloading something (that I know will get me max speed) and I got same 300 mbps speed, changed to safe boot with network again and I got 950 Mbps again...

So, this is clearly not a configuration thing nor a driver problem as I have the latest driver from the motherboard support page and makes no difference on normal boot but makes a difference on safe boot...
I am 99% sure this is a bug or something like that because when I turn off my ethernet (from network panel) and starts using Wifi, the speeds goes instantly up, but if I go back to Ethernet, I get this problem (on normal boot) again... As I mentioned before, I also tried changing the Reserve bandwidth on the Policy manager, and it made no difference...
I remember starting to close mostly all applications like Steam, Spotify, even software that uses 0 internet like Nvidia Broadcast, iCUE (for my lights and AIO block) and after closing some of them (because of amount, not specific apps) it started using 950 Mbps again... so this is clearly a Windows 10 bug...
Another info I can give is that (any browser) gives 750 Mbps more or less for download using http://speedtest.net but if I go to the Windows 10 app (that you can find on the store) I get 320 - 300 mbps... and if I download (games) with Uplay I get something between 500 mbps (60 Mb/s) but Steam and other apps cannot use more than 400 - 300 mbps, I have to do the wired to wifi change and start using wifi on normal boot to use at least 500 to 600 mbps (my motherboard's wifi cannot handle more).
What else can I try ? Again, remember that on safe boot with network or using other OS or changing main connection from wired (1 gbps) to wifi (840 mbps) gives me full speed or 3/4 of it...


text:
Q: Maven failure to find maven-plugins:maven-cobertura-plugin I try to compile maven web project with
<dependency>
    <groupId>org.springframework.ws</groupId>
    <artifactId>spring-ws</artifactId>
    <version>3.0.5-FINAL</version>
</dependency>

The problem is that when I try compile it I get the following errors:

[ERROR] Failed to execute goal on project inferx-d2aserver: Could
  not resolve dependencies for project
  com.inferx:inferx-d2aserver:war:4.0: The following artifacts could not
  be resolved: maven-plugins:maven-cobertura-plugin:plugin:1.3,
  maven-plugins:maven-findbugs-plugin:plugin:1.3.1,
  org.springframework.ws:spring-ws:jar:3.0.5.RELEASE: Failure to find
  maven-plugins:maven-cobertura-plugin:plugin:1.3 in
  http://repository.springsource.com/maven/bundles/release was cached in
  the local repository, resolution will not be reattempted until the
  update interval of com.springsource.repository.bundles.release has
  elapsed or updates are forced -> [Help 1] [ERROR]

I use Apache Maven 3.0.3, Java: 1.7.0 OS: Windows 7 (64 bit)

A: I was also facing similar issue. I just excluded jaxen from Jdom dependency and it worked for me.
jdom 1.1.2 includes jaxen 1.1.3 which imports those artifacts.
      <dependency>
        <groupId>org.jdom</groupId>
        <artifactId>jdom</artifactId>
        <version>1.1.2</version>
        <exclusions>
            <exclusion>
               <groupId>jaxen</groupId>
               <artifactId>jaxen</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

A: It look like your pom or parent pom contains a wrong definition of the maven-coberatura-plugin which should be fixed first. Furthermore remove the folder in your local repository.

A: I am not sure if this is the same case since my dependencies is different. I got similar error message with the same dependencies error so I removed both dependencies from ~/.m2/repository/jaxen/jaxen/1.1.3/jaxen-1.1.3.pom and the project is compile fine now.

A: From the error message related to cobertura version, it looks like you may be having a pom.xml corresponding to maven 1.
The following are maven 1.x versions of the plugins and not supported.

*

*maven-plugins:maven-cobertura-plugin:plugin:1.3,

*maven-plugins:maven-findbugs-plugin:plugin:1.3.1

A: Removing the pom is not the solution; in future builds may be you need them. Best solution according to my opinion is to modify the POM of corresponding jars. Like if you are getting error because of any jar; actually there is the dependency defined in its POM. So use <exclude>. That will work for sure.


text:
Q: C Programming with loops for exam Hi all I have an exam for one of my uni classes tomorrow and am struggling with the last practice question they gave us. It is as follows. If someone could assist me (with code, rather than verbally) with this question I would be greatly appreciative.

Write a C program which reads integers from the keyboard, stopping when an odd number greater than 20 is entered. The total number of even and odd numbers entered should then be displayed to the screen.

[Edit]
So far what I have done is as follows since I am unsure on how to make it stop when a number greater than 20 is inputted.
#include <stdio.h>
int main() {
  int number;
  int i;
  int n;
  int val;
  printf("Please enter numbers:");
  scanf("%d",&val);
  if(i=0; i>20; i++) {
    printf("Please enter numbers:");
    scanf("%d",&val);
  }
}

The expected output for this program should be that it prints out the total number of even and odd numbers. THis is done once the user has entered x amount of values up until a number greater than 20 is entered.
My new code is as follows, however I am very confused on how to define the section for the odd or even numbers.
#include <stdio.h>
int main(){

int even=0;
int odd=0;
int x;
int num;

while(x<20){
    printf("Please enter a number");
    scanf("%d",&x);

    if(x>20){
    for (x = 1; x <= num; x++)
    {
    if (x % 2 == 0)
        even = even + x;
    else
        odd = odd + x;
    }

}}}

A: Your program should be
#include <stdio.h>

/* Readability is important. So, indent your code */
/* Notice how I corrected your code and also made it more readable */

int main(void){

    int even = 0;
    int odd = 0;
    int x = 0; /* Initialize x */
    /* int num; Unused variable */

    while(x <= 20 || x % 2 == 0) /* Stop when x is greater than 20 or x is odd */
    {
        printf("\nPlease enter a number");
        scanf("%d", &x);

        if (x % 2 == 0)
            even = even + 1; /* +1, not +x. Or `even++;` */
        else
            odd = odd + 1;   /* +1, not +x. Or `odd++;`  */
    }

    printf("Even numbers = %d", even);
    printf("Odd numbers = %d", odd);

    return 0;
}


text: Q: why dictionary of american idioms says "of is usually retained before pronouns" why dictionary of american idioms says "of is usually retained before pronouns" such as order someone off ((of)something) to command someone to get off something.(Of is usually retained before pronouns) The teacher ordered Tom off of his steps


text:
Q: How can I visit a package's homepage via the pip command? Being new to both Python and particularly the pip package manager, I'm wondering if pip has an internal command for quickly opening a package's home page on the web.
If not possible by default, is there any available solution(s) for extending pip with this functionality (e.g. pip homepage django-boss)?
For comparison, I'm looking for something equivalent to Homebrew's:
brew home somepackage, which opens somepackage's home page in your default web browser.

A: pip doesn't provide the functionality you require.
The pypi-tools package may serve as a base for a solution. It installs the pypi command which allows to search for packages in PyPI or show the information for a specific package:
$ pypi -s django-boss
 name:                django-boss
 summary:             Django management commands, revisited.
 version:             0.6.3
 author:              Zachary Voase
 author_email:        zacharyvoase@me.com
 classifiers:
 home_page:           http://github.com/zacharyvoase/django-boss
 package_url:         http://pypi.python.org/pypi/django-boss
 release_url:         http://pypi.python.org/pypi/django-boss/0.6.3
 docs_url:

By perusing the package's source you should be able to integrate the module into a script of yours that gets the package's url and then invokes a browser with it.


text:
Q: How to rotate text on table with two rowspan using bootstrap ok, i've been trying hours to make my HTML code working for rotating text on my table, but doesnt seem to work.
here is jsfiddle, if anyone is willing to help me, I will appreciate that
https://jsfiddle.net/zmxr9kyh/
here my html code

$(function() {
  var header_height = 0;
  $('table th span').each(function() {
    if ($(this).outerWidth() > header_height) header_height = $(this).outerWidth();
  });

  $('table th').height(header_height);
});
th {
  position: relative;
  padding: 10px;
}
th span {
  bottom: 0;
  display: inline-table;
  left: 50%;
  position: absolute;
  transform: rotate(-90deg);
  transform-origin: 0 50% 0;
  white-space: pre;
  width: 100;
  margin-left: auto;
  margin-bottom: -110;
}

        VALIDASI

        JUMLAH RECORD

      NO.
      PROGRAM STUDI
      IDENTITAS MAHASISWA

        %

      MAHASISWA PT

        %

      KURIKULUM

        %

      NILAI

        %

      AKM

        %

      DAYA TAMPUNG

        %

      LAPORAN %

        MHS

          KELAS KKULIAH

        NILAI

        AKM

        A

        C

        N

A: writing-mode is your friend:
th span {
  writing-mode: tb-rl;
}

You might have to add vendor prefixes.

*

*Updated JSFiddle

*More information

*Browser support of writing-mode


text:
Q: Speedup of reduce function? I tried to run this $15$ variable feasibility linear programming to see what the solution looks like. Unfortunately it is taking too much time on my laptop. Is there a way to speed it up? Any tips will help.
  Reduce[{0 <= a <= 1, 0 <= b <= 1, 0 <= c <= 1, 0 <= d <= 1,
   0 <= e <= 1, 0 <= f <= 1, a + b + c == d + e + f == 2,
   0 <= k <= Min[a, d], 0 <= l <= Min[a, e],
   0 <= m <= Min[a, f], 0 <= p <= Min[b, d],
   0 <= q <= Min[b, e], 0 <= r <= Min[b, f],
   0 <= s <= Min[c, d], 0 <= t <= Min[c, e],
   0 <= u <= Min[c, f],
   l + m + k + p + q + r + s + t + u == 4}, {a, b, c, d, e, f, k, l, m,
   p, q, r, s, t, u}]

A: The conditions of
Reduce[{
  a + b + c == 2,
  d + e + f == 2,
  0 <= k <= Min[a, d, (a + d)/2],
  0 <= l <= Min[a, e, (a + e)/2],
  0 <= m <= Min[a, f, (a + f)/2],
  0 <= p <= Min[b, d, (b + d)/2],
  0 <= q <= Min[b, e, (b + e)/2],
  0 <= r <= Min[b, f, (b + f)/2],
  0 <= s <= Min[c, d, (c + d)/2],
  0 <= t <= Min[c, e, (c + e)/2],
  0 <= u <= Min[c, f, (c + f)/2],
  l + m + k + p + q + r + s + t + u == 4}, {a, b, c, d, e, f, k, l, m, p, q, r, s, t, u}]

translate to conditions with the forms matrix.var ≥ vec, matrix.var = vec and
matrix.var ≤ vec with the following matrices and vectors
(* Greater than 0 *)
mat1 = PadLeft[IdentityMatrix[{9, 15}][[;; 9, ;; 9]], {9, 15}];
vec1 = ConstantArray[{0, 1}, 9];

(* Equal to 2 *)
mat2 = PadRight[{{1, 1, 1, 0, 0, 0}, {0, 0, 0, 1, 1, 1}}, {2, 15}];
vec2 = ConstantArray[{2, 0}, 2];

(* Equal to 4 *)
mat3 = {Join[{0, 0, 0, 0, 0, 0}, ConstantArray[1, 9]]};
vec3 = {{4, 0}};

(* Less than inequalities *)
With[{kToU = PadLeft[IdentityMatrix[{9, 15}][[;; 9, ;; 9]], {9, 15}],
      aToC = PadRight[ArrayFlatten[Evaluate[DiagonalMatrix[{#, #, #}]] &[{{1}, {1}, {1}}]], {9, 15}],
       def = Join[#, #, #] &[PadRight[RotateLeft[IdentityMatrix[{3, 6}], {0, 3}], {3, 15}]]},
  mat4 = Join[kToU - aToC, kToU - def, kToU - (aToC + def)/2]];
vec4 = ConstantArray[{0, -1}, 27];

and the remaining inequalites are
varMinMax = PadRight[ConstantArray[{0, 1}, 6], 15, {{-∞, ∞}}];

To minimize a linear combination of the variables, evaluate this code:
LinearProgramming[RandomReal[{-2, 2}, 15],
 Join[mat1, mat2, mat3, mat4],
 Join[vec1, vec2, vec3, vec4],
 varMinMax]


text:
Q: MATLAB index out of bounds error I have wrote the following snippet of code however, I am receiving an index out of bounds error. I am unsure how to fix this. Does anyone know how I can resolve it. Thanks in advance!
image = imread('image_3.jpg');

%parameters
N = 100;
smth = rgb2gray(image);

% Calculating size of image
[row col] = size(image);

eline = smth; %eline is simply the image intensities

[grady,gradx] = gradient(double(smth));

eedge = -1 * sqrt ((gradx .* gradx + grady .* grady)); %eedge is measured by gradient in the image

m1 = [-1 1];
m2 = [-1;1];
m3 = [1 -2 1];
m4 = [1;-2;1];
m5 = [1 -1;-1 1];

cx = conv2(smth,m1,'same');
cy = conv2(smth,m2,'same');
cxx = conv2(smth,m3,'same');
cyy = conv2(smth,m4,'same');
cxy = conv2(smth,m5,'same');

for i = 1:row
for j= 1:col-1

    eterm(i,j) = (cyy(i,j)*cx(i,j)*cx(i,j) -2 *cxy(i,j)*cx(i,j)*cy(i,j) + cxx(i,j)*cy(i,j)*cy(i,j))/((1+cx(i,j)*cx(i,j) + cy(i,j)*cy(i,j))^1.5);
end
end

??? Attempted to access cyy(1,901); index out of bounds because
size(cyy)=[700,900].

Error in ==> snake at 31
    eterm(i,j) = (cyy(i,(j-1)+1)*cx(i,j)*cx(i,j) -2
    *cxy(i,j)*cx(i,j)*cy(i,j) +
    cxx(i,j)*cy(i,j)*cy(i,j))/((1+cx(i,j)*cx(i,j) +
    cy(i,j)*cy(i,j))^1.5);

A: Change the line where you calculate image size to:

[row col] = size(smth);

image is rgb and so is (I presume) 700 by 900 by 3.   Because the input has three dimensions and you're only asking for two outputs, it multiplies the last two dimensions together, giving col = 2700.


text:
Q: Python scheduled task to run every 14 days I am currently working on a program that needs to run every 14 days. I have looked into Schedule which works fine, but I have a few doubts about how to go about this.
I will create a service which will handle the execution of the python program itself on a CentOS 7 system.
The issue here is that every 14 days I will run a function that generates a lot of email addresses and send them to a support entity. I am afraid that if something unintended happens, and the program restart - the support entity will get spammed with emails outside the time frame in which they should receive emails.
As far as I can tell, Schedule does not have any way of determining if the program has restarted, and therefore a reboot of either the system or the service will cause this behaviour.
Would it be a correct solution to write a date to a text file after each completed function run, and then check that text file once a day to determine whether the function should run or not? This method would survive a service and/or system reboot, but is it a "correct" way of doing it?
****UPDATE**** Having the cronjob run on specific days of the month (for example 1st and 15th.) is not sufficient. This could cause gaps in the data which the program processes. The script makes a call which pulls data from 14 days back, and this is the maximum number of days supported by the script (licensing and stuff, can't be changed so not that important except that it is a limitation). So it need to run on lets say odd or even week numbers (to get 14 days).
Any ideas on how to accomplish this given this new information?.

A: You should look into the use of cron (or google it yourself if you dont like the link).
I suggest creating a simple Python script that is called by cron every 14 days. The crontab entry could look like the following:
# this will run at 00:01 on the 15th and 30th of every month
1 0 */15 * * /path/to/python/script.py

# this will run at 00:01 on the 1st and 15th of every month
1 0 1,15 * * /path/to/python/script.py

You still could make your script write some sort of result (with maybe a timestamp) to a file, so that you could easily check that file to see if it ran correctly (or log some error info).
# this will run at 00:01 on the 1st and 15th of every month
1 0 1,15 * * /path/to/python/script.py >> /path/to/logfile.log 2>&1

EDIT
You can also configure cron to run every Monday (or another day) if the 1st and 15th of every month are not sufficient. And the script could check a log file to see if it was run the previous Monday to assure it only executes your business logic every 2 weeks.
# this will run at 00:01 once a week on Mondays
1 0 * * 1 /path/to/python/script.py >> /path/to/logfile.log 2>&1


text:
Q: Get_post not displaying data I have a custom post type testimonial and am trying to display the title, content and the featured image.
This is my code:
    <?php
$args = array('posts_per_page' => -1, 'post_status' => 'publish', 'post_type' => 'testimonial');
$testimonialsposts = get_posts($args);
?>

    <?php
    foreach ($testimonialsposts as $post)
    {

    setup_postdata($post);
    ?>

        <img src="<?= get_post_meta($post->ID, '_wp_attached_file', true); ?>"/>

<?= get_post($post->ID, 'content', true); ?>

<?= get_post($post->ID, 'post_title', true); ?>

        <?php wp_reset_postdata();
        } ?>

But I am getting nothing. When I tried to echo the details after setup_postdata its only echoing "array".
When I var_dump the $post it shows all the data also.
This is what i get when I var_dump $post

object(WP_Post)#614 (24) { ["ID"]=> int(69) ["post_author"]=>
  string(1) "1" ["post_date"]=> string(19) "2017-08-22 02:26:43"
  ["post_date_gmt"]=> string(19) "2017-08-22 02:26:43"
  ["post_content"]=> string(575) "Lorem Ipsum is simply dummy text of
  the printing and typesetting industry. Lorem Ipsum has been the
  industry's standard dummy text ever since the 1500s, when an unknown
  printer took a galley of type and scrambled it to make a type specimen
  book. It has survived not only five centuries, but also the leap into
  electronic typesetting, remaining essentially unchanged. It was
  popularised in the 1960s with the release of Letraset sheets
  containing Lorem Ipsum passages, and more recently with desktop
  publishing software like Aldus PageMaker including versions of Lorem
  Ipsum." ["post_title"]=> string(13) "testimonial_1" ["post_excerpt"]=>
  string(0) "" ["post_status"]=> string(7) "publish"
  ["comment_status"]=> string(6) "closed" ["ping_status"]=> string(6)
  "closed" ["post_password"]=> string(0) "" ["post_name"]=> string(11)
  "testimonial" ["to_ping"]=> string(0) "" ["pinged"]=> string(0) ""
  ["post_modified"]=> string(19) "2017-08-22 02:27:07"
  ["post_modified_gmt"]=> string(19) "2017-08-22 02:27:07"
  ["post_content_filtered"]=> string(0) "" ["post_parent"]=> int(0)
  ["guid"]=> string(63)
  "http://192.168.0.202/clinic202/?post_type=testimonial&p=69"
  ["menu_order"]=> int(0) ["post_type"]=> string(11) "testimonial"
  ["post_mime_type"]=> string(0) "" ["comment_count"]=> string(1) "0"
  ["filter"]=> string(3) "raw" }

What am I doing wrong?

A: I understand you are using get_posts but this is what i would do, query the posts and loop by using wordpress loop instead using foreach.
try this
<?php
    query_posts(array(
        'post_type' => 'testimonial',
        'posts_per_page' => -1,
    ));
    if (have_posts()) : while (have_posts()) : the_post(); ?>

         <?php echo wp_get_attachment_image( get_post_thumbnail_id( $post->ID ), '', 'false', array( "class" => "img-responsive" ) ); ?>

<?php the_content();?>

<?php the_title(); ?>

<?php endwhile; endif;
      wp_reset_postdata();
      wp_reset_query(); ?>

also you are closing foreach inside
 which will break your html code.


text:
Q: How retain_grad() in pytorch works? I found its position changes the grad result in a simple test in pytorch, I want to see grad in a non-leaf tensor, so I use retain_grad():
import torch
a = torch.tensor([1.], requires_grad=True)
y = torch.zeros((10))
gt = torch.zeros((10))

y[0] = a
y[1] = y[0] * 2
y.retain_grad()

loss = torch.sum((y-gt) ** 2)
loss.backward()
print(y.grad)

it gives me a normal output:
tensor([2., 4., 0., 0., 0., 0., 0., 0., 0., 0.])

but when I use retain grad() before y[1] and after y[0] is assigned:
import torch
a = torch.tensor([1.], requires_grad=True)
y = torch.zeros((10))
gt = torch.zeros((10))

y[0] = a
y.retain_grad()
y[1] = y[0] * 2

loss = torch.sum((y-gt) ** 2)
loss.backward()
print(y.grad)

now the output changes to:
tensor([10.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.])

I can't understand the result at all.

A: Okay so what's going on is really weird.
What .retain_grad() essentially does is convert any non-leaf tensor into a leaf tensor, such that it contains a .grad attribute (since by default, pytorch computes gradients to leaf tensors only).
Hence, in your first example, after calling y.retain_grad(), it basically converted y into a leaf tensor with an accessible .grad attribute.
However, in your second example, you initially converted the entire y tensor into a leaf tensor; then, you created a non-leaf tensor (y[1]) within your leaf tensor (y), which is what caused the confusion.
y = torch.zeros((10))  # y is a non-leaf tensor

y[0] = a  # y[0] is a non-leaf tensor
y.retain_grad()  # y is a leaf tensor (including y[1])
y[1] = y[0] * 2  # y[1] is a non-leaf tensor, BUT y[0], y[2], y[3], ..., y[9] are all leaf tensors!

The confusing part is:
y[1] after calling y.retain_grad() is now a leaf tensor with a .grad attribute. However, y[1] after the computation (y[1] = y[0] * 2) is now not a leaf tensor with a .grad attribute; it is now treated as a new non-leaf variable/tensor.
Therefore, when calling loss.backward(), the Chain rule of the loss w.r.t y, and particularly looking at the Chain rule of the loss w.r.t leaf y[1] now looks something like this:


text:
Q: syntax error: unexpected literal "http://localhost:8080/cargautil.txt", expecting comma or ) En Go Tengo este código, pero al compilar me sale este error: syntax error: unexpected literal "http://localhost:8080/cargautil.txt", expecting comma or )  cuál podría ser una solución?
Cómo podría arreglar el error que me sale?
package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {

    co := Downloadedcode(datos "http://localhost:8080/cargautil.txt")
    fmt.Println(co)
}

func Downloadedcode(datos string)string{
    link,err := http.Get(datos)
    Capturaerror(err)

    reqBody,err := ioutil.ReadAll(link.Body)
    Capturaerror(err)
    return string(reqBody)

}

func Capturaerror(e error) {
    if e != nil {
        fmt.Println(e)
    }
}

A: Aquí estaba el error
co := Downloadedcode(**datos** "http://localhost:8080/cargautil.txt")

No era necesario volver a llamar datos.


text:
Q: Parameterising a paraboloid I am given this question below, and I was hoping for some guidance as to why I am getting my answer incorrect...
Question:
Consider the flux integral
∬Sf⋅n̂ dS,
where f= [0,y,2z] and S is the paraboloid surface shown below.

This paraboloid has height 2 and maximum radius 2.
(a) Based on cylindrical polar coordinates, enter the parameterisation
p(r,t)=(x(r,t),y(r,t),z(r,t)),
such that 0≤r<2 and 0≤t<2π gives the paraboloid surface above.
So, my answer is: [rcos(t), rsin(t), 0.5*r^2*(cos(t)^2) + 0.5*r^2*(sin(t))^2], and when I plotted this, my graph seems to be identical to the above graph, yet my answer is wrong. My teacher said that I need to consider the height with the paraboloid when the radius is 2, and that I am only a constant out...
I appreciate any help!

A: The paraboloid can be expressed as
$$x^2+y^2=2z$$
which can be parametrized as below,
$$x(r,t)=r\cos t$$
$$y(r,t)=r\sin t$$
$$z(r,t)=\frac 12 r^2$$
You may just have to simplify your $z$ function.


text:
Q: Only act on turnOff() once all objects that have called turnOn() call turnOff() I want to have 2 static functions called turnOn() and turnOff().
Say objectA calls turnOn(), then objectB calls turnOn(). Then objectA calls turnOff(), it should not turn off because objectB turned it on as well.
Also say objectA calls turnOn(), then objectB calls turnOn(). Then objectB calls turnOff(), it should not turn off because objectA hasn't turned it off yet.
Finally, if objectA and objectB turn it on, it turns off when they both turn it off.
I was thinking keeping track of how many turnOn and TurnOff's are called and make sure it matches, but thats not truly accurate because objectA can call turnOff() twice.
So whats the best sort of way to handle this?
Thanks!

A: This sounds like reference counting

A: The simplest method is as you describe: keep a count.  If you're really concerned with an object turning it off when it hasn't turned it on, you can keep a list of all objects that have turned it on, and remove them from the list when they turn it off.  If the list is empty, you can actually turn it off.

A: Edit:  The example code is in c# -- I didn't realize this wasn't a c# question.  If you have hashtables, dictionaries, or even 2-d arrays (tables) in your language, this same basic pattern should still work.
It sounds like you need a modified sort of ref count -- a count that goes by object.  How about something like this:

public class Switch
{
  private bool On;
  private Dictionary<object, int> ReferenceCounts = new ...
  public void TurnOn(object source)
  {
     int count = 0;
     if(ReferenceCounts.ContainsKey(source))
        count = ReferenceCounts[source];
     count++;
     ReferenceCounts[source] = count;
     On = true;
  }

  public void TurnOff(object source)
  {
    if(!ReferenceCounts.ContainsKey(source))
       return;

    int count = ReferenceCounts[source];
    count--;
    if(count == 0)
      ReferenceCounts.Remove(source)
    else
      ReferenceCounts[source] = count;

    if(ReferenceCounts.Count == 0)
      this.On = false;
  }
}

A: I'm not 100% sure this is what you're looking for but I think you'll want to have a static array to determine what is on or not. Also... fair warning, I didn't test this code. This is a very rough estimate of what I thought you might be looking to do.
class Switchable {
    static var _onObjects:Array=new Array  ;
    static public  function turnOn(obj:Object):Void {
        if (_onObjects.indexOf(obj) == -1) {
            _onObjects.push(obj);
        }
    }
    static public  function turnOff(obj:Object):Void {
        var index=_onObjects.indexOf(obj);
        if (isOn() && index >= 0) {
            _onObjects=_onObjects.splice(index,1);
        }
    }
    static public  function isOn():Boolean {
        return _onObjects.length > 0;
    }
}
class ObjectA {
    public function Foo():Void {
        Switchable.turnOn(this);
    }
    public function Bar():Void {
        Switchable.turnOff(this);
    }
}
class ObjectB {
    public function Foo():Void {
        Switchable.turnOn(this);
    }
    public function Bar():Void {
        Switchable.turnOff(this);
    }
}
class Test {
    static public  function Main():Void {
        trace(Switchable.isOn());
        var a:ObjectA=new ObjectA  ;
        var b:ObjectB=new ObjectB  ;
        a.Foo();
        trace(Switchable.isOn());
        b.Foo();
        trace(Switchable.isOn());
        a.Bar();
        trace(Switchable.isOn());
        b.Bar();
        trace(Switchable.isOn());
    }
}

A: The solution has two parts:
- a static object counter, as suggested elsewhere,
- and a per-object isTurnedOn flag that prevents turning the object on or off twice, something along the lines of this pseudo-code:
...
private static in count = 0;
private boolean isTurnedOn = false;
...
public void TurnON() {
    if (!isTurnedOn) {
        isTurnedOn = true;
        ++count;
    }
}

public void TurnOff() {
    if (isTurnedOn) {
        isTunedOn = false;
        --count;
        if (count == 0) {
            // the conter reached 0, do soemthing
            // but do not forget to protect against concurretn access
    }
 }

Please note that this construct allows turning the object repeatedly on and off. If you want to prevent this, probably you should use two separate booleans for isTurnedOn and isTurnedOff.


text:
Q: referents of they I am not sure whether the following uses of they are acceptable in educated speech when referring to a singular referent:

*

*I swear more when I'm talking to a boy because I'm not afraid of shocking them.

*No girl should have to wear school uniform because it makes them look like a sack of potatoes.

*I had a friend in Paris, and they had to visit the doctor for a month.

*A teacher asked me to give their book to John.

A:
I swear more when I'm talking to boys because I'm not afraid of shocking them.

better matches plurality.

No girl should have to wear a school uniform because it makes them look like a sack of potatoes.

no girl is not specific, so using them is OK. However:

Girls should not have to wear a school uniform because it makes them look like a sack of potatoes.

would be more natural.

I had a friend in Paris, and he/she had to visit the doctor for a month.

Obviously you know the gender of the friend, so just use it.

A teacher asked me to give his/her book to John.

Again, you know the gender of the teacher, so use it.

A: I would say that 1 is correct because it implies you are talking about all boys in the plural, not just the one you are swearing at.
I would say that 2 is correct because again you are implying many girls.
3 I would say is not correct and the correct word would be he or she, but by using they you can cover both sexes at once.
4 Again this simply covers the case for not declaring the sex of the teacher.  In our politically correct world I expect this term to become more used so as not to draw attention to those who feel they are neither he or she.

A: Oxford Living Dictionaries give this among their examples of gender-neutral they:

'I mentioned this to someone at work today and they looked at me as if I were a space alien.'

In a usage note, Oxford comment that, recently:

they is now being used to refer to specific individuals (as in Alex is bringing their laptop).

Your question was, in effect, whether gender-neutral they was acceptable in "educated speech" in cases where the gender of the referent is already known - as in Oxford's example above.
In my experience, the answer is yes.
Still, there remain some who would criticise such usage, as the other responses to your question show.  Even in contexts where the referent's gender is unknown, there are prescriptivists who would prefer to avoid they, though their number and influence are undoubtedly diminishing, and on the whole they are more likely to object to written use than to spoken.
(I agree with user3169 that the first two sentences would sound more natural in the plural, and I also agree with Ermintrude that even if those two sentences are left as they are, they are less likely to raise objections than the other two, because the listener might interpret "them" as shorthand for "the girls" or "the boys" rather than as a gender-neutral singular.)


text:
Q: UITableView deleteRowsAtIndexPaths doesn't delete row I have UIView designed in IB, and UITableView on it. In view contoller's viewDidLoad method I init my custom UITableViewContoller and sets dataSource and delegate:
- (void)viewDidLoad {
    [super viewDidLoad];
    ...
    GoodsTableController *goodsController = [[GoodsTableController alloc] init];
    goodsController.data = [[orderData objectForKey:@"Result"] objectForKey:@"Items"];
    self.gtc = goodsController;
    [goodsController release];

    goodsTable.delegate = self.gtc;
    goodsTable.dataSource = self.gtc;
    [goodsTable reloadData];}

Intresting in GoodsTableController:
//in the header file
@interface GoodsTableController : UITableViewController {
        NSMutableArray *data;
}

@property (nonatomic, retain) NSMutableArray *data;

//implementation

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
        NSLog(@"Current data size %d", [data count]);
        return [data count];
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
        if (editingStyle == UITableViewCellEditingStyleDelete) {
                NSLog(@"Deleting row at index %d", indexPath.row);
                [self.tableView beginUpdates];

                [self.data removeObjectAtIndex:indexPath.row];
                [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

                [self.tableView endUpdates];
                [self.tableView reloadData];
        }
}

For debug I used NSLog, and I saw that array was changed, its size was changed, tableView:numberOfRowsInSection was called, but table don't update. Row don't hides. That is log:
2011-04-07 13:08:18.784 Test[32300:207] Current data size 2 //first call tableView:numberOfRowsInSection: by reloadData in View Controller after set data
2011-04-07 13:08:23.486 Test[32300:207] Current data size 2 //call after slide on row
2011-04-07 13:08:26.091 Test[32300:207] Deleting row at index 0
2011-04-07 13:08:26.093 Test[32300:207] Current data size 1 //call after endUpdate
2011-04-07 13:08:26.096 Test[32300:207] Current data size 1 //call after reloadData

A: I have researched the mechanism of UITableView's delete, insert & reload. I am maintaining my project in Github countering this problem.
https://github.com/VansonLeung/VanTableController
It includes a working unit test in it. Normally in order to animate UITableView's cell animation, we have to do something like this:
[tableView_ beginUpdates];
[tableView_ deleteRowsAtIndexPaths: indexPathDelete withRowAnimation:UITableViewRowAnimationAutomatic];
[tableView_ insertRowsAtIndexPaths: indexPathInsert withRowAnimation:UITableViewRowAnimationAutomatic];
[tableView_ reloadRowsAtIndexPaths: indexPathReload withRowAnimation:UITableViewRowAnimationAutomatic];
[tableView_ endUpdates];

We have to determine the delete rows, insert rows & reload rows' indexPath arrays and it's a very nasty work! My project work is basically a wrapper for generating these indexPaths to make life easier.

A: Try this
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView  numberOfRowsInSection:(NSInteger)section
{
    int count = [NSMutableArray count];
    return count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView   dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero   reuseIdentifier:CellIdentifier] autorelease];
    }

    cell.selectionStyle = UITableViewCellSelectionStyleBlue;
    cell.textLabel.text = [NSMutableArray objectAtIndex:indexPath.row];
    return cell;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)aTableView  editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (!indexPath) return
    {
        UITableViewCellEditingStyleNone;
    }

    if (indexPath.row == ([NSMutableArray count]))
    {
        return UITableViewCellEditingStyleInsert;
    }
    else
    {
        return UITableViewCellEditingStyleDelete;
    }

    return UITableViewCellEditingStyleNone;
}

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Code for do anything after select row in table view
}

- (void)tableView:(UITableView *)aTableView  commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        [recordedFileList removeObjectAtIndex:indexPath.row];
        [recordTableView reloadData];
    }
}

- (BOOL)tableView:(UITableView *)tableView   canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (void)tableView:(UITableView *)tableView  moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
    NSString *item = [[NSMutableArray objectAtIndex:fromIndexPath.row] retain];
    [NSMutableArray removeObject:item];
    [NSMutableArray insertObject:item atIndex:toIndexPath.row];
    [item release];
}

A: The problem was in undefined tableView in GoodsTableController instance.
Fixed code:
- (void)viewDidLoad {
        [super viewDidLoad];
        ...
        GoodsTableController *goodsController = [[GoodsTableController alloc] init];
        goodsController.data = [[orderData objectForKey:@"Result"] objectForKey:@"Items"];
        self.gtc = goodsController;
        [goodsController release];

        goodsTable.delegate = self.gtc;
        goodsTable.dataSource = self.gtc;

        //Fix there:
        self.gtc.tableView = goodsTable;
        [goodsTable reloadData];
}


text:
Q: Nested Vertical RecycleView of fixed height (Scroll issue) I have designed this layout layout in which i have a NestdScrollView which contains 3 RecycleViews. On each RecycleView item click appears another NestedRecycleView appears with is inside ScrollView of height 200dp. NestedRecycleView scroll does not work. In the image there are more than 4 "list items" but only 4 are shown, it is not scrollable. When I scroll the parent NestdScrollView scrolls.

Someone commented about this being bad design, if anyone has a idea
  how to approach this kindly share your ideas also.

RecycleView Adapter
  public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {

        private List<String> mData;
        private LayoutInflater mInflater;
        private ItemClickListener mClickListener;
        private Context context;

        // data is passed into the constructor
        MyRecyclerViewAdapter(Context context, List<String> data) {
            this.mInflater = LayoutInflater.from(context);
            this.mData = data;
            this.context=context;
        }

        // inflates the row layout from xml when needed
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = mInflater.inflate(R.layout.list_item_text, parent, false);
            return new ViewHolder(view);
        }

        // binds the data to the TextView in each row
        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            String animal = mData.get(position);
            holder.myTextView.setText(animal);
        }

        // total number of rows
        @Override
        public int getItemCount() {
            return mData.size();
        }

        // stores and recycles views as they are scrolled off screen
        public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
            TextView myTextView;
            RecyclerView recyclerViewNested;
            ScrollView nestedScrollViewRecycleView;

            ViewHolder(View itemView) {
                super(itemView);
                myTextView = itemView.findViewById(R.id.text_view);
                recyclerViewNested = itemView.findViewById(R.id.recycle_view_nested);
                nestedScrollViewRecycleView= itemView.findViewById(R.id.nested_scrollview_in_recycleview);
                myTextView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        ArrayList<String> list12 = new ArrayList<String>(
                                Arrays.asList("list item", "list item", "list item","list item","list item", "list item", "list item","list item","list item", "list item", "list item","list item","list item", "list item", "list item","list item","list item", "list item", "list item","list item"));
                        nestedScrollViewRecycleView.setVisibility(View.VISIBLE);

                        MyRecyclerViewAdapter adapter = new MyRecyclerViewAdapter(context, list12);
                        LinearLayoutManager layoutManager = new LinearLayoutManager(context, recyclerViewNested.VERTICAL, false);
                        recyclerViewNested.setLayoutManager(layoutManager);
                        recyclerViewNested.setAdapter(adapter);

                    }
                });
                //itemView.setOnClickListener(this);
            }

            @Override
            public void onClick(View view) {
                if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
            }
        }

        // convenience method for getting data at click position
        String getItem(int id) {
            return mData.get(id);
        }

        // allows clicks events to be caught
        void setClickListener(ItemClickListener itemClickListener) {
            this.mClickListener = itemClickListener;
        }

        // parent activity will implement this method to respond to click events
        public interface ItemClickListener {
            void onItemClick(View view, int position);
        }
    }

MainActivity
public class MainActivity extends AppCompatActivity {

    public static final int SWIPE_THRESHOLD = 100;
    public static final int SWIPE_VELOCITY_THRESHOLD = 100;
    private static final String TAG = "MainActivity";

    ArrayList<String> list2;
    NestedScrollView NestedScroll1;
    ConstraintLayout constraintLayout;
    RecyclerView recyclerView1;
    //vars

 private boolean mSwiping = false;
    private float mDownX = 0;
    private float xCoOrdinate;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView1 = findViewById(R.id.firstColumn);
        RecyclerView recyclerView2 = findViewById(R.id.secondColumn);
        RecyclerView recyclerView3 = findViewById(R.id.thirdColumn);
        NestedScroll1 = findViewById(R.id.scrollview_nested);

        ArrayList<String> list12 = new ArrayList<String>(
                Arrays.asList("A", "column1", "test1", "1", "2", "3", "1", "2", "3", "1", "2", "3", "1", "2", "3", "1", "2", "3", "2", "3", "1", "2", "3", "1", "2", "3", "1", "2", "3", "1", "2", "3"));
        list2 = new ArrayList<String>(
                Arrays.asList("B", "column3", "test3", "111", "211", "311", "111", "211", "311", "111", "211", "311", "111", "211", "311", "111", "211", "311", "311", "111", "211", "311", "111", "211", "311", "111", "211", "311"));

        // set up the RecyclerView
        MyRecyclerViewAdapter adapter = new MyRecyclerViewAdapter(this, list12);

        configRecyclerView(recyclerView1, adapter);
        configRecyclerView(recyclerView2, adapter);
        configRecyclerView(recyclerView3, adapter);

    recyclerView2.addOnItemTouchListener(getOnItemTouchListener());
    recyclerView3.addOnItemTouchListener(getOnItemTouchListener());

    }

    private void configRecyclerView(RecyclerView recyclerView, MyRecyclerViewAdapter adapter) {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext(), recyclerView.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
    }

private RecyclerView.OnItemTouchListener getOnItemTouchListener() {
        return new RecyclerView.OnItemTouchListener() {
            @SuppressLint("LongLogTag")
            @Override
            public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent ev) {
                Log.d("TableView OnswipeTouchListener: ", " recycleViewOdds item onInterceptTouchEvent");

                switch (ev.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        mDownX = ev.getX();
                        mSwiping = false;

                        //coordinate for moving
                        xCoOrdinate = constraintLayout.getX() - ev.getRawX();

                        break;
                    case MotionEvent.ACTION_CANCEL:
                        //return true;
                    case MotionEvent.ACTION_UP:
                        if (mSwiping) {

                            /// this return true block touch event
                            Log.d("TableView OnswipeTouchListener:", "Recycle view odds OnItemTouchListener: you swiped!");
                            return true;
                        }
                        break;
                    case MotionEvent.ACTION_MOVE:
                        float xMove = ev.getX();
                        float xDelta = Math.abs(xMove - mDownX);

                        if (xDelta > 5) {
                            mSwiping = true;
                            // this one also
                            return true;
                        }
                        break;
                }

                return false;
            }

            private Rect rect;

            @SuppressLint("LongLogTag")
            @Override
            public void onTouchEvent(RecyclerView rv, MotionEvent event) {

                int limitLeft = constraintLayout.getLeft();
                int limitRight = constraintLayout.getRight();

                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:

                        break;
                    case MotionEvent.ACTION_MOVE:
                        //   Log.d("OnSwipeTouchListener Class", "recycleViewOdds action move");

                        //Restrict move to constraintLayout width
                        // Log.d("Recycleview TouchListener windowwidth: ", limitLeft + ", " + limitRight);

                        float range = event.getRawX() + xCoOrdinate;

                        if (Math.abs(range) > limitLeft - 350 && Math.abs(range) < limitRight - 250) {
                            //constraintLayout.scrollTo((int) (event.getRawX() + xCoOrdinate),0);
                            constraintLayout.animate().x(event.getRawX() + xCoOrdinate).setDuration(0).start();
                            constraintLayout.setAlpha(0.7f);
                        }

                        break;
                    case MotionEvent.ACTION_UP:
                        Log.d("TableView OnswipeTouchListener:", "recycleViewOdds action up");
                        constraintLayout.animate().alpha(1).translationX(0).translationY(0);

                        break;

                    case MotionEvent.ACTION_CANCEL:
                        constraintLayout.animate().alpha(1).translationX(0).translationY(0);

                        Log.d("TableView OnswipeTouchListener:", "recycleViewOdds action cancel");
                        break;
                }
            }

            @SuppressLint("LongLogTag")
            @Override
            public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
                Log.e("TableView OnswipeTouchListener:", "recycleViewOdds item touch intercept disallow request");

            }
        };
    }

}

activity_main.xml

<androidx.core.widget.NestedScrollView
    android:id="@+id/scrollview_nested"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:text="Hello World!"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/firstColumn"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_centerHorizontal="true"
            android:nestedScrollingEnabled="false"
            app:layout_constraintEnd_toStartOf="@id/secondColumn"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/secondColumn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="16dp"
            app:layout_constraintEnd_toStartOf="@id/thirdColumn"
            app:layout_constraintLeft_toRightOf="@id/firstColumn"
            app:layout_constraintTop_toTopOf="parent" />

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/thirdColumn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="16dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintLeft_toRightOf="@id/secondColumn"
            app:layout_constraintTop_toTopOf="parent" />
    </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.core.widget.NestedScrollView>

list_item_text.xml
  <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="10dp">

    <TextView
        android:id="@+id/text_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:layout_marginBottom="8dp"/>
    <ScrollView
        android:id="@+id/nested_scrollview_in_recycleview"
        android:layout_width="match_parent"
        android:visibility="gone"
        android:background="@color/colorAccent"
        android:layout_height="200dp">
        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recycle_view_nested"
            android:layout_width="match_parent"
            android:nestedScrollingEnabled="false"
            android:layout_height="wrap_content"/>

    </ScrollView>

</LinearLayout>

A: My suggestion would be in "list_item_text", In this, you have a scroll view and recycler view encapsulated, I am assuming these items will be very less in number around 5-10 and mostly will be visible on the screen, So there won't be any performance issue If we directly add LinearLayout in a parent layout dynamically by iterating a loop, only con of this approach will be that the views which are out of the screen, will be loaded into memory (which is not in recycler view), But considering your number of items, This is accepted, most of your items will be visible on the screen, And obviously It will save an extra overhead of Recyclerview population, rendering and all. Hope It will solve your touch issue.

A: Add recyclerView.setNestedScrollingEnabled(false); to all RecyclerViews and check if that solves the problem with scrolling.

A: activity_main.xml
Please add android:nestedScrollingEnabled="true" in all RecyclerView Tags...

list_item_text.xml
Please add android:fillViewport="true" in ScrollView Tag
then change android:layout_height="wrap_content" to android:layout_height="0dp" in RecyclerView Tag...


text:
Q: Can't access port forwarded to Windows 7 machine Before, I never had this problem with Windows 7 – the router always had the same settings like below.

*

*Installed Windows 7, all drivers, etc.

*Updated Windows 7 to SP1 (a bunch of KBs before SP1 appeared in update)

*Port 12000 forwarded on Gigaset sx763 to my local IP (192.168....)

*Entered that IP as my static IP

*Disabled firewall on Windows 7 machine (not on the router – on the router, it was always on and needed)

Problem:
In our local network you can see that 12000 belongs to me, but I can't get access from outside.
Any advice? I've been playing for almost 3 hours with settings etc.

A: The culprit is still the firewall. Sometimes even on disabling the firewall, it is not deactivated for all ports. Be sure to do that with an administrator account.
Additionally, instead of deactivating the firewall, I would suggest to keep that on and configure it to accept connections on your needed ports.
Still, if you wish to keep the firewall off, be sure to checkout the page where all blocked and allowed programs and ports are listed.


text:
Q: How to check if the string size is greater thatn its container's size? in my div of the size e.g 100x200px, I have a html-formatted string. I want to limit the count of displayed character's of that string, if the string size (or length?) is grater that this div size (then I want to use tooltip). Any ideas how to do that ? I could convert that string to the plain version and then check the size, but is it a good idea ?

I've found that article to check:
http://blog.mastykarz.nl/measuring-the-length-of-a-string-in-pixels-using-javascript/

I've noticed the another problem, the string trimming seems to be working, but, I'd like to view the trimmed string saving its html tags

A: Create an identical div (but with no scroll restrictions) with the string inside somewhere off the page where the user cannot see it, and check the size of that.
Then loop through the string while removing a few characters at a time until it fits.

A: You can put the string in another (hidden) element like a span, disable wrapping in style - in script you can get the width of this span and can compare if it is bigger than your div.
Dont forget to set appropriate styles like white-space:nowrap
For limiting the fixed size field you can just set overflow:hidden (you have to set overflow:visible on the invisible span). This way, the characters get cut off and the users maybe see, that there is more text.


text:
Q: Activate two path from one relay I have to make a modification for a device in the field, that has only one NO relay that can be triggered. Now, there are two connectors, where on one, the GND needs to be deactivated and on the other, the power supply pin. I would also like to take into account the bouncing of the relay and counteract it, as well as robustness in terms of noise, that could be coupled in.
So I tried to simulate everything in LTSpice and this is what I came up with:

It seems to work pretty decent, but I think this can be optimized more. I cannot use the relay directly to replace the mosfets, since I want to prevent the GND from bouncing in the 5V supply case. I also added a snubber parallel to the relay. Do you see any potential issues?


text:
Q: Теряются строки при чтении из файла Здравствуйте.Хочу прочитать строки из файла , в файле 6177 строк.Пи чтении теряю ровно 60 строк.Это где то из середины.Первые и последние выходят.
public class Data {

    public static int countStr []= new int[114];

    public static void main(String[] args) throws IOException {
        //заполняю countStr[] числами.Числа  разные.
        initItem();

        File f = new File("text.txt");

        FileReader fR = new FileReader(f);

        BufferedReader bf = new BufferedReader(fR);

        int cnt =0;

        for(int i =0 ;i <countStr.length;i++){

              cnt +=1;
                if(i!=cnt&&cnt<114){

                     for(int k =0;k<countStr[cnt];k++){
                      //Если в ячейке массива напр.7 , то вывожу семь строк.
                              System.out.println(bf.readLine());
                      }
                 }else{
                      System.out.println("массив закончился");
                 }

        }

        fR.close();
        bf.close();


text:
Q: Splitting a string with delimiters and conditions I'm trying to split a general string of chemical reactions delimited by whitespace, +, = where there may be an arbitrary number of whitespaces. This is the general case but I also need it to split conditionally on the parentheses characters () when there is a + found inside the ().
For example:
    reaction= 'C5H6 + O = NC4H5 + CO + H'

Should be split such that the result is
     splitresult=['C5H6','O','NC4H5','CO','H']

This case seems simple when using filter(None,re.split('[\s+=]',reaction)). But now comes the conditional splitting. Some reactions will have a (+M) which I'd also like to split off of as well leaving only the M. In this case, there will always be a +M inside the parentheses
For example:
    reaction='C5H5 + H (+M)= C5H6 (+M)'
    splitresult=['C5H5','H','M','C5H6','M']

However, there will be some cases where the parentheses will not be delimiters. In these cases, there will not be a +M but something else that doesn't matter.
For example:
    reaction='C5H5 + HO2 = C5H5O(2,4) + OH'
    splitresult=['C5H5','HO2','C5H5O(2,4)','OH']

My best guess is to use negative lookahead and lookbehind to match the +M but I'm not sure how to incorporate that into the regex expression I used above on the simple case. My intuition is to use something like filter(None,re.split('[(?<=M)\)\((?=\+)=+\s]',reaction)). Any help is much appreciated.

A: That seems overly complicated to handle with a single regular expression to split the string. It'd be much easier to handle the special case of (+M) separately:
halfway = re.sub("\(\+M\)", "M", reaction)
result = filter(None, re.split('[\s+=]', halfway))

A: So here is the regex which you are looking for.
Regex: ((?=\(\+)\()|[\s+=]|((?<=M)\))
Flags used:

*

*g for global search. Or use them as per your situation.

Explanation:

*

*((?=\(\+)\() checks for a ( which is present if (+ is present. This covers the first part of your (+M) problem.

*((?<=M)\)) checks for a ) which is present if M is preceded by ). This covers the second part of your (+M) problem.

*[\s+=] checks for all the remaining whitespaces, + and =. This covers the last part of your problem.
Note: The care for digits being enclosed by () ensured by both positive lookahead and positive lookbehind assertions.
Check Regex101 demo for working
P.S: Make it suitable for yourself as I am not a python programmer yet.

A: You could use re.findall() instead:

re.findall(pattern, string, flags=0)
  Return all non-overlapping
  matches of pattern in string, as a list of strings. The string is
  scanned left-to-right, and matches are returned in the order found. If
  one or more groups are present in the pattern, return a list of
  groups; this will be a list of tuples if the pattern has more than one
  group. Empty matches are included in the result unless they touch the
  beginning of another match.

then:
import re
reaction0= 'C5H6 + O = NC4H5 + CO + H'
reaction1='C5H5 + H (+M)= C5H6 (+M)'
reaction2='C5H5 + HO2 = C5H5O(2,4) + OH'
re.findall('[A-Z0-9]+(?:\([1-9],[1-9]\))?',reaction0)
re.findall('[A-Z0-9]+(?:\([1-9],[1-9]\))?',reaction1)
re.findall('[A-Z0-9]+(?:\([1-9],[1-9]\))?',reaction2)

but, if you prefer re.split() and filter(), then:
import re
reaction0= 'C5H6 + O = NC4H5 + CO + H'
reaction1='C5H5 + H (+M)= C5H6 (+M)'
reaction2='C5H5 + HO2 = C5H5O(2,4) + OH'
filter(None , re.split('(?<!,[1-9])[\s+=()]+(?![1-9,])',reaction0))
filter(None , re.split('(?<!,[1-9])[\s+=()]+(?![1-9,])',reaction1))
filter(None , re.split('(?<!,[1-9])[\s+=()]+(?![1-9,])',reaction2))

the pattern for findall is different from the pattern for split,
because findall and split are looking for different things; 'the opposite things', indeed.
findall, is looking for that you wanna (keep it).
split, is looking for that you don't wanna (get rid of it).
In findall, '[A-Z0-9]+(?:([1-9],[1-9]))?'
match any upper case or number > [A-Z0-9],
one or more times > +, follow by a pair of numbers, with a comma in the middle, inside of parenthesis > \([1-9],[1-9]\)
(literal parenthesis outside of character classes, must be escaped with backslashes '\'), optionally > ?
\([1-9],[1-9]\) is inside of (?: ), and then,
the ? (which make it optional); ( ), instead of (?: ) works, but, in this case, (?: ) is better; (?: ) is a no capturing group: read about this.
try it with the regex in the split


text:
Q: 20.04 LTS Since upgrade from 19.10 laptop doesn't suspend anymore after lid close My Lenovo P50 laptop used to suspend nicely when I closed the lid on Ubuntu 19.10. After the upgrade this doesn't work anymore. When I execute the command sudo systemctl suspend then the laptop still goes into a very rapid full functional suspend. So something seems to go wrong somewhere in handling the lid close event from acpi.
I'm using gnome-tweak-tools and it has the toggle to suspend on lid close enabled as expected.
I also checked the configuration in /etc/systemd/logind.conf and it seems perfect:
HandleLidSwitch=suspend
HandleLidSwitchExternalPower=suspend
HandleLidSwitchDocked=suspend
LidSwitchIgnoreInhibited=yes

I haven't found anything noticable in the /var/log/syslog.
The workaround I found is the following:
Create a file called /etc/acpi/events/laptop-lid-close with the following content:
event=button/lid LID close
action=/etc/acpi/laptop-lid-close.sh

And create a file /etc/acpi/laptop-lid-close.sh with the following content and gave it execute rights (chmod +x /etc/acpi/laptop-lid-close.sh):
#!/bin/sh

systemctl suspend

Would be better if this workaround would not be necessary ofcourse
Acpi seems to fire off 'lid close' events as it should, otherwise the workaround would not work.
Also the suspend itself must be working on my laptop as well for the same reason.
Any clues on how to learn why this doesn't work out of the box?

A: I had similar with a fresh UbuntuDDE install. I found answers in various sources (this one is probably the most relevant Ubuntu 18.04 - Dell XPS13 9370 no longer suspends on lid close). The issue is the laptop not going into "deep" sleep. Run this command
cat /sys/power/mem_sleep

And if you get the result below, then this is the issue.
[s2idle] deep

To change it, edit your grub file (location: /etc/default/grub) to add this text to the GRUB_CMDLINE_LINUX_DEFAULT line
mem_sleep_default=deep

Then update grub
sudo update-grub

and reboot. After reboot, run this again
cat /sys/power/mem_sleep

and confirm now that your result is
s2idle [deep]

Then you should be good to go.


text:
Q: Can't see OData fields in API return object when using paging I am creating an API in .NET 6 that returns a IQueryable object fetch from a database using o-data filters. I've managed to enable the odata filters and I can now run queries in the database by hitting the API endpoint. The issue I am running into now is that I would like to enable paging in the API response, but when I turn on this parameter I do not get a "next" field in the API response as I would expect. Here is a sample endpoint :
[HttpGet("CosmosTestIQueriable")]
[EnableQuery(PageSize =2)]
public ActionResult UseIqueriable()
{
    var result = this.container.GetItemLinqQueryable<CosmosItem>(true);
    return Ok(result);
}

This is the code I use to configure OData in my service:
builder.Services.AddControllers()
    .AddOData(options => options
                    .Select()
                    .Filter()
                    .OrderBy()
                    .SetMaxTop(100)
                    .Count())
    .AddODataNewtonsoftJson();

By turning on [EnableQuery(PageSize =2)], the API does cap the number of results to 2, but I don't think it is possible for the user to query the next page with this method. Am I using the wrong method for enabling this?

A: Try to add option SkipToken
builder.Services.AddControllers()
    .AddOData(options => options
                    .Select()
                    .Filter()
                    .OrderBy()
                    .SetMaxTop(100)
                    .SkipToken()
                    .Count())
    .AddODataNewtonsoftJson();


text:
Q: Аналог функции dpois (язык R) в python (распределение Пуассона) В языке R имеется функция dpois для вычисления распределения Пуассона, которой, в качестве операндов, передается некая lambda (вещественное число), и вектор неких неотрицательных квантилей.
Предположим, что мне необходимо вычислить распределение для lambda=1.435678, вектор от 0 до 4.
В R это будет выглядеть так:
dpois(x=(0:4), lambda=1.435678)

[1] 0.23795398 0.34162529 0.24523196 0.11735804 0.04212209

Вопрос в следующем - с помощью какого модуля в python можно получить такой же результат?
Пробовал через numpy.random.poisson, но получил что-то не то:
from numpy.random import poisson as poi

print poi(1.435678, 4)

>>> [1 4 1 1]

A: numpy.random.poisson - это аналог rpois() в R, т.е. генератор случайных чисел.
dpois() вычисляет значения плотности распределения (или, точнее, Probability Mass Function). В Python:
scipy.stats.poisson.pmf(k, mu, loc)

https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.poisson.html
http://www.astroml.org/book_figures/chapter3/fig_poisson_distribution.html


text:
Q: shared pointer forward declaration I have an interface Interface.
I also have a .h file InterfaceFwd.h which looks something like
#ifndef Blah
#define Blah
#include <boost/shared_ptr.hpp>
class Interface;
typedef boost::shared_ptr<Interface> InterfacePtr;
#endif

I also have Interface.h
#ifndef SomeOtherBlah
#define SomeOtherBlah
class Interface
{
   virtual ~Interface()
   {
   }
   ...
};
typedef boost::shared_ptr<Interface> InterfacePtr;
#endif

Do I need to worry that if both files are included there will be duplicate declaration of InterfacePtr? On my compiler this compiles fine, but does the standard One-Definition Rule allow multiple identical typedef-declarations? Also, do you think I should include InterfaceFwd.h into Interface.h instead of redeclaring InterfacePtr or it's fine as it is?
Thanks in advance

A: The one definition rule doesn't apply to typedefs. A typedef (on its own) doesn't define a new variable, function, class type, enumeration type or template. You are explicitly allowed to redefine a previous typedef-name to refer to the type that it already refers to.
7.1.3 [dcl.typedef]:

In a given non-class scope, a typedef specifier can be used to redefine the name of any type declared in that scope to refer to the type to which it already refers.


text:
Q: Solving a Convex Resource Allocation Problem - Log of a Linear Term with Linear Equality Constraints I want to solve the following optimization problem
$$\begin{array}{ll} \text{maximize} & \displaystyle\sum_{i=1}^n \log_{2}(1+a_i x_i)\\ \text{subject to} & \displaystyle\sum_{i=1}^n (c_i - x_i) a_i = b\\ & 0 \leq x_i \leq c_i\end{array}$$
where $a_i \geq a_2 \geq \dots \geq a_n$, $b \in \mathbb R^+$ and $c_1 = c_2 = \dots = c_n$ are given.
I tried to solve this problem using Lagrange multipliers
$$\mathcal{L}(x,\lambda,\mu,\nu)=\sum_{i=1}^n\log_{2}(1+a_ix_i) + \lambda \left( \sum_{i=1}^n(c_i-x_i)a_i - b \right) - \mu_i (x_i-c_i) + \nu_ix_i$$
We need to have $\frac{d\mathcal{L}}{dx_i}=0$; therefore
$$\sum_{i=1}^n \frac{a_i}{\ln(2)\times(1+a_ix_i)}-\lambda a_i-\mu_{i}+\nu_{i}=0$$
In particular, my problem always has
$$\sum_{i=1}^{n-1} a_i c_i < b < \sum_{i=1}^n a_i c_i$$
How can I obtain the optimal values of $x_i$

A: I think your best approach is duality.  First, note that $\log_2$ and $\ln$ differ by a multiplicative constant $\ln(2)$. Thus, we can minimize with $\ln$ and obtain the same optimal value, and I will use $\ln$ instead of $\log_2$ in my derivations. Second, I will treat it as a minimization problem, and therefore write $-\ln$ instead of $\ln$.
Giving a Lagrange multiplier only to the equality constraint, you obtain the Lagrangian
$$
\begin{aligned}
L(x, \lambda)
 &= -\sum_{i=1}^n \ln(1+a_i x_i) + \lambda \left[ \sum_{i=1}^n (c_i - x_i) a_i - b \right] \\
 &= \sum_{i=1}^n \left[-\ln(1+a_i x_i) - \lambda a_i x_i  \right] + \lambda \Bigl[\underbrace{-b + \sum_{i=1}^n a_i c_i}_{C} \Bigr]
\end{aligned}
$$
Since the Lagrangian and the constraints $0 \leq x_i \leq c_i$ are both separable in $x_i$, the dual objective is:
$$
q(\lambda) = \sum_{i=1}^n \min_{x_i} \biggl\{ -\ln(1+a_i x_i) - \lambda a_i x_i :~ 0 \leq x_i \leq c_i \biggr\} + \lambda C
$$
Note, that each of the elements in the sum above is a minimization of a convex function of the form $-\ln(1+ax) -bx$ over an interval, and it is quite easy to find a closed form solution (if you need help, please say so). From this solution you will also obtain a formula from recovering the optimal $x_i$ from the optimal $\lambda$.
Now, your dual problem is the one-dimensional optimization problem $\max_{\lambda} q(\lambda)$, which can be easily solved by a numerical method, such as the Golden Section search. After finding the optimal $\lambda^*$ you can recover $x^*$.
P.S. If you really want a really reliable method in terms of approximating the optimum in terms of the objective value, you can compute an approximate $x_i$ after every iteration of the the Golden Section search, and stop when the primal-dual gap is below some threshold.
Update
Since there are many questions about computing $q(\lambda)$, here are the details. First, I will denote by $g_i(x_i, \lambda)$ the objective inside the minimum. That is, we solve
$$
\min_{x_i} \biggl\{g_i(x_i, \lambda) = -\ln(1+a_i x_i) - \lambda a_i x_i :~ 0 \leq x_i \leq c_i \biggr\}
$$
The minimum is either a stationary point inside the interior of the interval $I = [0, c_i]$ or one of its endpoints.  First, note that if $\lambda \geq 0$ then $g_i$ is a decreasing function, and in this case there are no stationary points. Thus, for any stationary point we must have $\lambda < 0$.
To find a stationary point, we solve:
$$
\frac{d g_i}{d x_i} = -\frac{a_i}{1+a_i x_i} - \lambda a_i = 0.
$$
Since $a_i > 0$ we can divide both sides by $a_i$, and obtain the equation
$$
\frac{1}{1+a_i x_i} = -\lambda
$$
Since $\lambda \neq 0$, we take the inverse on both sides, multiply by $a_i$, and obtain
$$
1+a_i x_i = -\frac{1}{\lambda},
$$
which is equivalent to
$$
a_i x_i = -1-\frac{1}{\lambda},
$$
or
$$
x_i = -\frac{1+\lambda}{a_i \lambda}.
$$
Using the fact that $\lambda < 0$, we conclude that the point above is inside the interior of $I$ if and only if
$$
-1 < \lambda < -\frac{1}{1 + c_i a_i},
$$
in that case the expression for $x_i$ above is the minimizer, and the minimum is
$$
g_i\left(-\frac{1+\lambda}{a_i \lambda}, \lambda\right) = \ln(-\lambda) + \lambda + 1
$$
Otherwise, either the left endpoint $x_i=0$ or the right endpoint $x_i=c_i$ is the minimizer. To summarize,
$$
q_i(\lambda) = \min_{x_i} \biggl\{g_i(x_i, \lambda) :~ 0 \leq x_i \leq c_i \biggr\} = \begin{cases}
\ln(-\lambda) + \lambda + 1 & -1 < \lambda < -\frac{1}{1 + c_i a_i} \\
\min(0, -\ln(1+a_i c_i)-\lambda a_i c_i) & \text{otherwise}
\end{cases}
$$
The dual objective is
$$
q(\lambda) = \sum_{i=1}^n q_i(\lambda) + \lambda C
$$
It is possible to simplify  the expressions above, but it is not required to do so in order to write code which evaluates $q(\lambda)$ in order to solve it numerically.


text:
Q: Javascript ajax: Не получается взять инфо с сайта Всем привет.
Проблема в том, что с одного сайта не получается взять инфо. Например, берем ссылку "http://www.owww.obnovi.com/main/8345-skachat-film-kak-ukrast-neboskreb-2011-besplatno.html". Делаю ajax запрос и вывожу в alert, получаю вот что:

С любым другим сайтом все нормально.. Либо сайт неправильно построен?
Может это быть из за того, что не указан какой документ? типо: "!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"

A: Перекодируйте в utf8, затем только используйте ajax. И будете жить долго и счастливо))
A: Проблемы с кодировкой, попробуй сменить у себя кодировку в скрипте, что бы совпадало с кодировкой этой страницы
A: Используйте кодировку такую же, как и на сайте. А на сайте windows-1251.
A: Покажите как вы получаете значение tmp_ajax? Вас не смущает, что Вы пытаетесь в div вставить <html>, <head>, <body>?.. Или я не правильно понял?


text:
Q: Find out precentage of point x and y between two other points In my android app I have simple "map", which is satellite map based image. I have exact LatLngpositions on two corners of this map: Left-Top and Right-Bottom to be precise. Now, by given LatLng point I want to create a small view add place it on the map (a marker). In order to this I have to calculate percentage x and y in pixels on my "map".
So to sum up here's my data:
LatLng MAP_LEFT_TOP; //constant point
LatLng MAP_RIGHT_BOTTOM; //constant point
LatLng location; //point, which should be inside map rectangle

What I have to calculate:
float percentageX; //percentage x position of "location" on the map
float percentageY; //percentage y position of "location" on the map

Here I found function:
LatLng interpolate(LatLng from, LatLng to, double fraction)

https://github.com/googlemaps/android-maps-utils/blob/master/library/src/com/google/maps/android/SphericalUtil.java
and I need something, which works in the opposite way. Here's my implementation, but it doesn't give me correct result (the same for y/longitude):
double findFractionX(double latitudeLeftTop, double latitudeRightBottom, double latitude){
    return (latitude - latitudeLeftTop) / (latitudeRightBottom - latitudeLeftTop);
}

Then I can get final position of the marker like this:
float imageViewWidth; //width of the imageView holding map
float imageViewHeight; //height of the imageView holding map
float x = percentageX * imageViewWidth;
float y = percentageY * imageViewHeight;

Edit:
my mistake was using latitude to get x and longitude to get y while it's just the opposite.
Still something's wrong, here's how it looks in the app:

Here's where it should have been (I used scribble to make this example):

Just to make it clear I'm talking about point named "1.1", don't pay your attention for the others, they're hardcoded in the image itself.

A: Since I got another idea to write up, I'll just put both in a full answer to have more space.
First, check if you don't accidentally switched long/lat or x/y:
Long = x and lat = y.
Then, how does you view look that you add? While you get the exact position of the map marker, simply adding a view to that location may look off.
The view itself probably has a width and height itself and you may want it placed on top of the marker like when clicking on a store on Google maps? If you just put it at the calculated position, it will put its top-left corner at that position.


text:
Q: How to create a button in TinyMCE 4 that increments font size Has anyone managed to create a button in TinyMCE 4 that will increment the font size of the selected text by, say, 1px?
The problem I'm having is getting ahold of the  selected text, whether it's in a span already or not.
I'm willing to modify the TinyMCE source.
Thanks for any ideas.

A: You don't need to modify the source code, you can create a plugin.
Here is the documentation of how to create a plugin for TinyMCE:
http://www.tinymce.com/wiki.php/Tutorials:Creating_a_plugin
based on that you can create your own button (see working example)
here is part of the code:
var currentFontSize = new Number($(tinyMCE.activeEditor.selection.getNode()).css('font-size').replace('px','')); //remove the px part
currentFontSize =  currentFontSize + 1; //increase font by one

tinymce.activeEditor.formatter.register('mycustomformat', {
  inline : 'span',
  styles : {'font-size' : currentFontSize + 'px'} //this is the font size incremented by one
});

tinymce.activeEditor.formatter.apply('mycustomformat'); //apply the format to the selected text


text:
Q: Run Google Chrome application from url I am trying to run Google Chrome application using a url, I tried the following:
chrome-extension://gfkmokjholoinfcnlolbjfaokmoegeoh/

But it didn't work, as I get:
chrome-extension://invalid/

Any suggestions?

A: chrome-extension://pnhechapfaindjhompbnflcldabbghjo/html/nassh.html

Use full path if you know.

A: You have to list the resources you are accessing in web_accessible_resources in your manifest.