问:
My app crashes fatal exception Unable to add window
I am very new to Android development and I have created this quiz game. My problem is the app randomly crashes after a few minutes it has been opened. The crashes are at random times so I can't figure out what causes the crashing. Below is the logcat error code whenever the app crashes

```<code>11-16 18:39:10.573 19023-19023/com.noxeternal.quizgame E/AndroidRuntime: FATAL EXCEPTION: main
                                                                     Process: com.noxeternal.quizgame, PID: 19023
                                                                     android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@d70d3e4 is not valid; is your activity running?
                                                                         at android.view.ViewRootImpl.setView(ViewRootImpl.java:679)
                                                                         at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:342)
                                                                         at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:94)
                                                                         at android.app.Dialog.show(Dialog.java:322)
                                                                         at com.noxeternal.quizgame.MainActivity.gameOver(MainActivity.java:287)
                                                                         at com.noxeternal.quizgame.MainActivity.access$300(MainActivity.java:19)
                                                                         at com.noxeternal.quizgame.MainActivity$9.onFinish(MainActivity.java:307)
                                                                         at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:127)
                                                                         at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                         at android.os.Looper.loop(Looper.java:154)
                                                                         at android.app.ActivityThread.main(ActivityThread.java:6176)
                                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
                                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)
</code>```

Here are the codes mentioned at the logcat.

```<code>private void gameOver(){
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
    alertDialogBuilder
            .setMessage("Game over! Your score is " + mScore + " points.")
            .setCancelable(false)
            .setPositiveButton("NEW GAME",
                    new DialogInterface.OnClickListener(){
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i){
                            finish();
                            startActivity(new Intent(getApplicationContext(),MainActivity.class));
                        }
                    })
            .setNegativeButton("Exit",
                    new DialogInterface.OnClickListener(){
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i){
                            Intent intent = new Intent(MainActivity.this, MainMenu.class);
                            startActivity(intent);
                            finish();
                        }
                    });
    AlertDialog alertDialog = alertDialogBuilder.create();
    alertDialog.show();
}

private void startTimer(){
    long millisInFuture = 60000;
    long countDownInterval = 1000;

    timer.setText("Time remaining: " + timer);
    countDownTimer = new CountDownTimer(millisInFuture, countDownInterval) {
        @Override
        public void onTick(long millisUntilFinished) {
            if(isPaused){
                cancel();
            } else {
                timer.setText("Time remaining: " + millisUntilFinished / 1000);
                remainingTime = millisUntilFinished;
            }
        }
        @Override
        public void onFinish() {
            gameOver();
        }
    };
    countDownTimer.start();
}
</code>```

Thank you!

答:
Try to modify this code:

```<code> @Override
 public void onClick(DialogInterface dialogInterface, int i){
     finish();
     startActivity(new Intent(getApplicationContext(),MainActivity.class));
 }
</code>```

to this:

```<code>@Override
public void onClick(DialogInterface dialogInterface, int i) {
     startActivity(new Intent(getApplicationContext(),MainActivity.class));
     finish();
}
</code>```

Body:
I am very new to Android development and I have created this quiz game. My problem is the app randomly crashes after a few minutes it has been opened. The crashes are at random times so I can't figure out what causes the crashing. Below is the logcat error code whenever the app crashes

11-16 18:39:10.573 19023-19023/com.noxeternal.quizgame E/AndroidRuntime: FATAL EXCEPTION: main
                                                                     Process: com.noxeternal.quizgame, PID: 19023
                                                                     android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@d70d3e4 is not valid; is your activity running?
                                                                         at android.view.ViewRootImpl.setView(ViewRootImpl.java:679)
                                                                         at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:342)
                                                                         at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:94)
                                                                         at android.app.Dialog.show(Dialog.java:322)
                                                                         at com.noxeternal.quizgame.MainActivity.gameOver(MainActivity.java:287)
                                                                         at com.noxeternal.quizgame.MainActivity.access$300(MainActivity.java:19)
                                                                         at com.noxeternal.quizgame.MainActivity$9.onFinish(MainActivity.java:307)
                                                                         at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:127)
                                                                         at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                         at android.os.Looper.loop(Looper.java:154)
                                                                         at android.app.ActivityThread.main(ActivityThread.java:6176)
                                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
                                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)

Here are the codes mentioned at the logcat.

private void gameOver(){
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
    alertDialogBuilder
            .setMessage("Game over! Your score is " + mScore + " points.")
            .setCancelable(false)
            .setPositiveButton("NEW GAME",
                    new DialogInterface.OnClickListener(){
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i){
                            finish();
                            startActivity(new Intent(getApplicationContext(),MainActivity.class));
                        }
                    })
            .setNegativeButton("Exit",
                    new DialogInterface.OnClickListener(){
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i){
                            Intent intent = new Intent(MainActivity.this, MainMenu.class);
                            startActivity(intent);
                            finish();
                        }
                    });
    AlertDialog alertDialog = alertDialogBuilder.create();
    alertDialog.show();
}

private void startTimer(){
    long millisInFuture = 60000;
    long countDownInterval = 1000;

    timer.setText("Time remaining: " + timer);
    countDownTimer = new CountDownTimer(millisInFuture, countDownInterval) {
        @Override
        public void onTick(long millisUntilFinished) {
            if(isPaused){
                cancel();
            } else {
                timer.setText("Time remaining: " + millisUntilFinished / 1000);
                remainingTime = millisUntilFinished;
            }
        }
        @Override
        public void onFinish() {
            gameOver();
        }
    };
    countDownTimer.start();
}

Thank you!

Body:
Try to modify this code:

 @Override
 public void onClick(DialogInterface dialogInterface, int i){
     finish();
     startActivity(new Intent(getApplicationContext(),MainActivity.class));
 }

to this:

@Override
public void onClick(DialogInterface dialogInterface, int i) {
     startActivity(new Intent(getApplicationContext(),MainActivity.class));
     finish();
}


来源: stackexchange

问:
Handle commas in quoted strings in Tcl
I'm using the following line in Tcl to parse a comma-separated line of fields. Some of the fields may be quoted so they can contain comma's:

```<code>set line {12,"34","56"}
set fresult [regsub -all {(\")([^\"]+)(\",)|([^,\"]+),} $line {{\2\4} } fields]
puts $fields
{12} {34} "56"
</code>```

(It's a bit strange that the last field is quoted instead of braced but that's not the problem here)

However, when there is a comma in the quote, it does not work:

```<code>set line {12,"34","56,78"}
set fresult [regsub -all {(\")([^\"]+)(\",)|([^,\"]+),} $line {{\2\4} } fields]
puts $fields
{12} {34} "{56} 78"
</code>```

I would expect:
{12} {34} {56,78}

Is there something wrong with my regexp or it there something tcl-ish going on?

答:
Use the following regsub

```<code>% set line {12,"34","56,78"}

% regsub -all {(,")|(",)|"} $line " " line

% set line

12 34  56,78  <<< Result
</code>```

Here all the occurrences of ," or ", or " (in order) are replaced by space

ContentLicense: CC BY-SA 2.5

Title: Handle commas in quoted strings in Tcl

Body:
I'm using the following line in Tcl to parse a comma-separated line of fields. Some of the fields may be quoted so they can contain comma's:

set line {12,"34","56"}
set fresult [regsub -all {(\")([^\"]+)(\",)|([^,\"]+),} $line {{\2\4} } fields]
puts $fields
{12} {34} "56"

(It's a bit strange that the last field is quoted instead of braced but that's not the problem here)

However, when there is a comma in the quote, it does not work:

set line {12,"34","56,78"}
set fresult [regsub -all {(\")([^\"]+)(\",)|([^,\"]+),} $line {{\2\4} } fields]
puts $fields
{12} {34} "{56} 78"

I would expect:
{12} {34} {56,78}

Is there something wrong with my regexp or it there something tcl-ish going on?

Body:
Use the following regsub

% set line {12,"34","56,78"}

% regsub -all {(,")|(",)|"} $line " " line

% set line

12 34  56,78  <<< Result

Here all the occurrences of ," or ", or " (in order) are replaced by space


问:
Exiting an infinite loop with a key in c++ on linux
i have an infinite loop that should be ended if i pressed any key. The program runs in linux. I have stumbled upon a function Here is a bit of my code :

```<code>int main(){
      While(1){
        ParseData(); //writing data to a text file
      }
return 0;
}
</code>```

so i know that i can terminate the process by using ctrl + c in terminal, but it seems that it will interrupt the writing process so the datas are not written completely halfway through the process. I read that i need to use function from ncurses library , but i can't quite understand any.

Can someone help me with it? Thanks!

答:
Why do you need a key to exit a program that didn't finish writing to a file, even if you make the loop exits on key press it will interrupt the file writing too if not finished. </p>

<p>Why you just exit the loop when the data finishes writing to the file, like the following: </p>

```<code>isFinished = false;
While(!isFinished ){
    ParseData(); //writing data to a text file
   //after data finsihes
   isFinished = false;
  }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i have an infinite loop that should be ended if i pressed any key. The program runs in linux. I have stumbled upon a function Here is a bit of my code :

int main(){
      While(1){
        ParseData(); //writing data to a text file
      }
return 0;
}

so i know that i can terminate the process by using ctrl + c in terminal, but it seems that it will interrupt the writing process so the datas are not written completely halfway through the process. I read that i need to use function from ncurses library , but i can't quite understand any.

Can someone help me with it? Thanks!

Body:
Why do you need a key to exit a program that didn't finish writing to a file, even if you make the loop exits on key press it will interrupt the file writing too if not finished.

Why you just exit the loop when the data finishes writing to the file, like the following:

isFinished = false;
While(!isFinished ){
    ParseData(); //writing data to a text file
   //after data finsihes
   isFinished = false;
  }


问:
Not able to drag a formula calculating days
I have a formula which gives me the day ie Monday , Tuesday etc. But the problem i am having is that i am not able drag the formula to give me the next day.

I am trying to drag this along the row.

```<code>=TEXT(WEEKDAY(DATE(CurrentYear,1,1),1),"aaa")
</code>```

So if i drag i should get the below formulea which i am not getting.

```<code>=TEXT(WEEKDAY(DATE(CurrentYear,1,2),1),"aaa")
</code>```

Therefore the next formula will have a 2 in the formula , and then the next will have 3 in the formula and so.

答:
dragging only updates cell references not numbers. You need to write your formula to reference a cell location in some way. Try

=TEXT(WEEKDAY(DATE(CurrentYear,1,Column(a1)),1),"aaa")

Body:
I have a formula which gives me the day ie Monday , Tuesday etc. But the problem i am having is that i am not able drag the formula to give me the next day.

I am trying to drag this along the row.

=TEXT(WEEKDAY(DATE(CurrentYear,1,1),1),"aaa")

So if i drag i should get the below formulea which i am not getting.

=TEXT(WEEKDAY(DATE(CurrentYear,1,2),1),"aaa")

Therefore the next formula will have a 2 in the formula , and then the next will have 3 in the formula and so.


问:
How to solve "Missing Marketing Icon. iOS Apps must include a 1024x1024px"
I am uploading app in iTunes from Xcode 9.0...This error is showing on the last step. How to solve this? 1024x1024px icon is present in my icons list

答:
Its mandatory to add app icon of size 1024*1024 in image asset for Xcode 9 or later. Other wise it will give following error after uploading build to app store. So please make sure to add app icon in image asset before uploading app.

Dear developer, We have discovered one or more issues with your recent delivery for "CarPal". Your delivery was successful, but you may wish to correct the following issues in your next delivery: Missing Marketing Icon - iOS Apps must include a 1024x1024px Marketing Icon in PNG format. Apps that do not include the Marketing Icon cannot be submitted for App Review or Beta App Review. After you’ve corrected the issues, you can use Xcode or Application Loader to upload a new binary to iTunes Connect.


问:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint
When I run the following migration, I am getting the following error:

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint

I have an existing database and refactoring the model to include a navigation property.

See the original model and then the new model:

Original model:

```<code>public class Student
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Country { get; set; }
}
</code>```

New model:

```<code>public class Student
{
     public int ID { get; set; }
     public string Name { get; set; }
     public int CountryID { get; set; }
     public virtual Country Country { get; set; }
}

public class Country
{
     public int ID { get; set; }
     public string Country { get; set; }
}
</code>```

Add-Migration navigation property:

```<code>public override void Up()
{
            CreateTable(
                "dbo.Countries",
                c => new
                    {
                        ID = c.Int(nullable: false, identity: true),
                        CountryName = c.String(),
                    })
                .PrimaryKey(t => t.ID);

            AddColumn("dbo.Students", "CountryID", c => c.Int(nullable: false));
            CreateIndex("dbo.Students", "CountryID");
            AddForeignKey("dbo.Students", "CountryID", "dbo.Countries", "ID", cascadeDelete: true);
            DropColumn("dbo.Students", "Country");
}
</code>```

Update-Database error:

System.Data.SqlClient.SqlException (0x80131904): The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_dbo.Students_dbo.Countries_CountryID". The conflict occurred in database "aspnet-navprop-20141009041805", table "dbo.Countries", column 'ID'.

答:
Against your Student entity you can mark your CountryId property as nullable using a question mark appended to the type, i.e. </p>

```<code>public class Student
{
     public int ID { get; set; }
     public string Name { get; set; }
     public int? CountryID { get; set; }
     public virtual Country Country { get; set; }
}
</code>```

Body:
When I run the following migration, I am getting the following error:

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint

I have an existing database and refactoring the model to include a navigation property.

See the original model and then the new model:

Original model:

public class Student
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Country { get; set; }
}

New model:

public class Student
{
     public int ID { get; set; }
     public string Name { get; set; }
     public int CountryID { get; set; }
     public virtual Country Country { get; set; }
}

public class Country
{
     public int ID { get; set; }
     public string Country { get; set; }
}

Add-Migration navigation property:

public override void Up()
{
            CreateTable(
                "dbo.Countries",
                c => new
                    {
                        ID = c.Int(nullable: false, identity: true),
                        CountryName = c.String(),
                    })
                .PrimaryKey(t => t.ID);

            AddColumn("dbo.Students", "CountryID", c => c.Int(nullable: false));
            CreateIndex("dbo.Students", "CountryID");
            AddForeignKey("dbo.Students", "CountryID", "dbo.Countries", "ID", cascadeDelete: true);
            DropColumn("dbo.Students", "Country");
}

Update-Database error:

System.Data.SqlClient.SqlException (0x80131904): The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_dbo.Students_dbo.Countries_CountryID". The conflict occurred in database "aspnet-navprop-20141009041805", table "dbo.Countries", column 'ID'.

Body:
Against your Student entity you can mark your CountryId property as nullable using a question mark appended to the type, i.e.

public class Student
{
     public int ID { get; set; }
     public string Name { get; set; }
     public int? CountryID { get; set; }
     public virtual Country Country { get; set; }
}


问:
Unable to extract zip file which generated using php
I have written the PHP script to generate the zip file. it's working fine when I use rar software to extract it but not getting extract with rar software. I can't ask to users to install rar software to extract downloaded zip file.

I don't know where i am commiting mistakes.
Here i attached error screen shot which i get when try to open zip file.

```<code>// Here is code snippet
$obj->create_zip($files_to_zip, $dir . '/download.zip');

// Code for create_zip function
//create the archive
$zip = new ZipArchive();
if ($zip->open($destination, $overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
    return false;
}
//add the files
foreach ($valid_files as $file) {
    $filearr = explode('/', $file);
    $zip->addFile($file, end($filearr));
}
$zip->close();
</code>```

答:
If $valid_files is a glob'd array, use basename() instead of end(), your zip might not actually have added any files causing for it to be an invalid zip (however that would be visible in the size of the zip file).

Also try winrar/winzip/7zip and see what they return, microsoft's internal zip engine might not be up to date enough to open the zips.

Body:
I have written the PHP script to generate the zip file. it's working fine when I use rar software to extract it but not getting extract with rar software. I can't ask to users to install rar software to extract downloaded zip file.

I don't know where i am commiting mistakes.
Here i attached error screen shot which i get when try to open zip file.

// Here is code snippet
$obj->create_zip($files_to_zip, $dir . '/download.zip');

// Code for create_zip function
//create the archive
$zip = new ZipArchive();
if ($zip->open($destination, $overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
    return false;
}
//add the files
foreach ($valid_files as $file) {
    $filearr = explode('/', $file);
    $zip->addFile($file, end($filearr));
}
$zip->close();


问:
creating common header and sidebar across all the page using react router

App.js

```<code>class App extends Component {
    render() {
    return (
      <Router history={history}>
        <Switch>
          <Route path="/" exact component={Login} />
          <div>
            <Header />
            <div className="main">
              <SideBar />
              <Route
                path="/dashboard"
                exact
                component={RequireAuth(Dashboard)}
              />
              <Route path="/profile" exact component={RequireAuth(Profile)} />
            </div>
          </div>
        </Switch>
      </Router>
   );
 }
}
</code>```

Here i want Header and Sidebar to be common across all the pages while i change the route and i am getting the result but i think it is not a standard way to do so,please suggest and help me,that how should i create the common layout for
 some set of pages and another layout for other pages,like

```<code> <Router history={history}>
  <Switch>
   <layout1>
    <Route path="/dashboard" exact component={RequireAuth(Dashboard)}/>
    <Route path="/profile" exact component={RequireAuth(Profile)} />
   </layout1>

   <layout2>
    <Route path="/otherinfo1" exact component={RequireAuth(OtherInfo1)}/>
    <Route path="/otherinfo2" exact component={RequireAuth(OtherInfo2)} />
   </layout2>
  </Switch>
 </Router>
</code>```

i am using react router 4.2.2

and every time i login and redirect to dashboard, jquery functionality doesn't work, always i need to refresh the page to run jquery related stuffs(if could help)

答:
You could prefix, you two sets of routes with an identifier and set that as a Route path, All other routes can go inside the respective container Layout

```<code><Router history={history}>
  <Switch>
   <Route path="/layout1" component={FirstContainer}/>
   <Route path="/layout2" component={SecondContainer}/>
  </Switch>
</Router>
</code>```

Then you FirstContainer would be like

```<code>const FirstContainer = ({match}) => (
    <div>
         {/* other stuff */}
         <Route path={`${match.path}/dashboard`} exact component={RequireAuth(Dashboard)}/>
         <Route path={`${match.path}/profile`} exact component={RequireAuth(Profile)} />
         {/* other stuff */}
    </div>

)
</code>```

and SecondContainer

```<code>const SecondContainer = ({match}) => (
    <div>
         {/* other stuff */}
         <Route path={`${match.path}/otherinfo1`} exact component={component={RequireAuth(OtherInfo1)}}/>
         <Route path={`${match.path}/otherinfo2`} exact component={RequireAuth(OtherInfo2)} />
         {/* other stuff */}
    </div>

)
</code>```

Body:
App.js

class App extends Component {
    render() {
    return (
      <Router history={history}>
        <Switch>
          <Route path="/" exact component={Login} />

              <SideBar />
              <Route
                path="/dashboard"
                exact
                component={RequireAuth(Dashboard)}
              />
              <Route path="/profile" exact component={RequireAuth(Profile)} />

        </Switch>
      </Router>
   );
 }
}

Here i want Header and Sidebar to be common across all the pages while i change the route and i am getting the result but i think it is not a standard way to do so,please suggest and help me,that how should i create the common layout for
 some set of pages and another layout for other pages,like

 <Router history={history}>
  <Switch>
   <layout1>
    <Route path="/dashboard" exact component={RequireAuth(Dashboard)}/>
    <Route path="/profile" exact component={RequireAuth(Profile)} />
   </layout1>

   <layout2>
    <Route path="/otherinfo1" exact component={RequireAuth(OtherInfo1)}/>
    <Route path="/otherinfo2" exact component={RequireAuth(OtherInfo2)} />
   </layout2>
  </Switch>
 </Router>

i am using react router 4.2.2

and every time i login and redirect to dashboard, jquery functionality doesn't work, always i need to refresh the page to run jquery related stuffs(if could help)

Body:
You could prefix, you two sets of routes with an identifier and set that as a Route path, All other routes can go inside the respective container Layout

<Router history={history}>
  <Switch>
   <Route path="/layout1" component={FirstContainer}/>
   <Route path="/layout2" component={SecondContainer}/>
  </Switch>
</Router>

Then you FirstContainer would be like

const FirstContainer = ({match}) => (
    <div>
         {/* other stuff */}
         <Route path={`${match.path}/dashboard`} exact component={RequireAuth(Dashboard)}/>
         <Route path={`${match.path}/profile`} exact component={RequireAuth(Profile)} />
         {/* other stuff */}
    </div>

)

and SecondContainer

const SecondContainer = ({match}) => (
    <div>
         {/* other stuff */}
         <Route path={`${match.path}/otherinfo1`} exact component={component={RequireAuth(OtherInfo1)}}/>
         <Route path={`${match.path}/otherinfo2`} exact component={RequireAuth(OtherInfo2)} />
         {/* other stuff */}
    </div>

)


问:
Import a script from package in setup.py
I want to use a setup.py which imports from a script which is part of the package that has to be installed. This script just contains a dict that contains the strings for creating entry points. I haven't hardcoded them in the setup.py because I want to use this list again later from the installed package.

Just for clearance here my directory structure and important files:

```<code>PackageA
|_package_a
| |_models
| |_modules
| | |_do_query.py
| | |_...
| |_setup_cfg.py
| |_ __init__.py
| |_...
|_ __init__.py
|_setup.py
</code>```

__init__.py in package_a:

```<code>from .setup_cfg import setup_config
</code>```

setup_cfg.py:

```<code>setup_config = {
    'scripts': [
        'do_query'
    ]
}
</code>```

setup.py:

```<code>    # -*- coding: utf-8 -*-

from setuptools import setup, find_packages
from .package_a import setup_config

with open('README.rst') as f:
    readme = f.read()

with open('LICENSE') as f:
    license = f.read()

setup(
    ...,
    entry_points={
        'console_scripts': ['{}=package_a.modules.{}:main'.format(script, script) for script in setup_config.get('scripts')]
    },
)
</code>```

I can make the import from .package_a import setup_config and pycharm resolves this import correctly. However, if I try to install the package via pip3 install . it fails with ModuleNotFoundError: No module named '__main__.package_a'; '__main__' is not a package

(we use pip instead of python setup.py install as we want to have the whole source folder installed in site-packages instead of a bundled version)

Can anyone explain me that exception or provide a proper way to achieve such a configuration? (The dict in setup_config.py must be accesible from setup.py as well when importing the installed package.

答:
I faced the similar problem, and also resolved it in very strange way, i really don't know the reason it is working, even i thought it should not work.

i just imported without relative path

eg:

```<code>from package_a import setup_config
</code>```

just removed the relative path(dot removed), it worked. pycharm is throwing error, but when in ran pip3 install . it worked. please let me know if it works for you.

Body:
I want to use a setup.py which imports from a script which is part of the package that has to be installed. This script just contains a dict that contains the strings for creating entry points. I haven't hardcoded them in the setup.py because I want to use this list again later from the installed package.

Just for clearance here my directory structure and important files:

PackageA
|_package_a
| |_models
| |_modules
| | |_do_query.py
| | |_...
| |_setup_cfg.py
| |_ __init__.py
| |_...
|_ __init__.py
|_setup.py

__init__.py in package_a:

from .setup_cfg import setup_config

setup_cfg.py:

setup_config = {
    'scripts': [
        'do_query'
    ]
}

setup.py:

    # -*- coding: utf-8 -*-

from setuptools import setup, find_packages
from .package_a import setup_config

with open('README.rst') as f:
    readme = f.read()

with open('LICENSE') as f:
    license = f.read()

setup(
    ...,
    entry_points={
        'console_scripts': ['{}=package_a.modules.{}:main'.format(script, script) for script in setup_config.get('scripts')]
    },
)

I can make the import from .package_a import setup_config and pycharm resolves this import correctly. However, if I try to install the package via pip3 install . it fails with ModuleNotFoundError: No module named '__main__.package_a'; '__main__' is not a package

(we use pip instead of python setup.py install as we want to have the whole source folder installed in site-packages instead of a bundled version)

Can anyone explain me that exception or provide a proper way to achieve such a configuration? (The dict in setup_config.py must be accesible from setup.py as well when importing the installed package.

Body:
I faced the similar problem, and also resolved it in very strange way, i really don't know the reason it is working, even i thought it should not work.

i just imported without relative path

eg:

from package_a import setup_config

just removed the relative path(dot removed), it worked. pycharm is throwing error, but when in ran pip3 install . it worked. please let me know if it works for you.


问:
Badge icon resource/view
Is there a built in badge icon like the info icon so that I can show status updates on other views in my app? It's easy enough to duplicate manually but I'd like to use a built in resource if it's available.</p>

答:
Check out CustomBadge, the site is in German, but theres sample source code there.

You can also steal a badge from a tabbar view like this:

.h

```<code>IBOutlet UITabBarItem *tabbarItem;
UIView *badgeView;
</code>```

.m

```<code>badgeView = [[UIView alloc] initWithFrame:CGRectMake(25,100, 32, 32)];
badgeView.backgroundColor = [UIColor clearColor];
badgeView.clipsToBounds = NO;
[badgeView addSubview:[((UIView *)[tabbar.subviews objectAtIndex:0]).subviews objectAtIndex:0]];
</code>```

and to set the value for that badge:

```<code>tabbarItem.badgeValue = unreadCount;
</code>```

Note that you don't have to use a UITabbar thats visible in your app, you are simple stealing the badge resource.

Title: Badge icon resource/view

Body:
Check out CustomBadge, the site is in German, but theres sample source code there.

You can also steal a badge from a tabbar view like this:

.h

IBOutlet UITabBarItem *tabbarItem;
UIView *badgeView;

.m

badgeView = [[UIView alloc] initWithFrame:CGRectMake(25,100, 32, 32)];
badgeView.backgroundColor = [UIColor clearColor];
badgeView.clipsToBounds = NO;
[badgeView addSubview:[((UIView *)[tabbar.subviews objectAtIndex:0]).subviews objectAtIndex:0]];

and to set the value for that badge:

tabbarItem.badgeValue = unreadCount;

Note that you don't have to use a UITabbar thats visible in your app, you are simple stealing the badge resource.


问:
Mapping JSON to Class automatically - design issue
I am using a certain API which returns JSON data in the following format:

```<code>entities {
    entity#1 { [property#1:value, property#2:value] },
    entity#2 { [property#3:value, property#4:value] }
}
</code>```

The entities in this JSON are defined manually, which means each entity can have unique properties. What is the best way to parse this kind of data?

At the moment, I'm making a unique class for each entity that I define on the API however the amount of entities that I define could be well over 100.

Is there a way in Java to create a single class that would have the shared properties pre-defined, and then add properties to that same class on runtime?

答: Yes, you could use Jackson to do deserialization (http://www.baeldung.com/jackson-deserialization) and define a custom mapper that would deserialize the dynamic variables into a Map instead.

Body:
I am using a certain API which returns JSON data in the following format:

entities {
    entity#1 { [property#1:value, property#2:value] },
    entity#2 { [property#3:value, property#4:value] }
}

The entities in this JSON are defined manually, which means each entity can have unique properties. What is the best way to parse this kind of data?

At the moment, I'm making a unique class for each entity that I define on the API however the amount of entities that I define could be well over 100.

Is there a way in Java to create a single class that would have the shared properties pre-defined, and then add properties to that same class on runtime?


问:
HTML for list with dashes and custom font colour
I am finalising a Wordpress website, but my last challenge is to create a bullet list with dashes instead of dots - the dashes must also be in white to match the font colour.

I've tried a few answers here but nothing seems to work right!

Text and dashes must be white (as it's on a blue background)

– sustainable growth,

– increase profits,

– expand market share and

– improve efficiency

答:
Since the dash "–" is not a supported value for bullet lists style type, you could use an image as Vinod suggested in his answer or –IHMO– use the ::before pseudo-element to simulate the required style for an easier solution.

ul {
  background-color: blue;
  color: white;
  list-style-type: none;
}

li::before {
  content: "– ";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>sustainable growth,</li>
  <li>increase profits,</li>
  <li>expand market share and</li>
  <li>improve efficiency</li>
</ul></code>```

Another (cooler) solution (with little browser support yet) would be using @counter-style to define your own bullet style.

Please note that if you are using production browsers this will only work in Firefox. (Nov '17)

@counter-style dash {
  system: cyclic;
  symbols: "–";
  suffix: " ";
}

ul {
  background-color: blue;
  color: white;
  list-style-type: dash;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>sustainable growth,</li>
  <li>increase profits,</li>
  <li>expand market share and</li>
  <li>improve efficiency</li>
</ul></code>```

Body:
Since the dash "–" is not a supported value for bullet lists style type, you could use an image as Vinod suggested in his answer or –IHMO– use the ::before pseudo-element to simulate the required style for an easier solution.

ul {
  background-color: blue;
  color: white;
  list-style-type: none;
}

li::before {
  content: "– ";
}

<ul>
  <li>sustainable growth,</li>
  <li>increase profits,</li>
  <li>expand market share and</li>
  <li>improve efficiency</li>
</ul>

Another (cooler) solution (with little browser support yet) would be using @counter-style to define your own bullet style.

Please note that if you are using production browsers this will only work in Firefox. (Nov '17)

@counter-style dash {
  system: cyclic;
  symbols: "–";
  suffix: " ";
}

ul {
  background-color: blue;
  color: white;
  list-style-type: dash;
}

<ul>
  <li>sustainable growth,</li>
  <li>increase profits,</li>
  <li>expand market share and</li>
  <li>improve efficiency</li>
</ul>


问:
What is this es6 syntax called?
I am relatively new to es6. I came across the following syntax and can't figure out what is it called.</p>

```<code>let parameter = 'key1';
const obj = {
    'key1': 'value1',
    'key2': 'value2',
    'key3': 'value3',
  }[parameter];
</code>```

答:
Statement 1: variable declaration and definition.

Statement 2: variable declaration, inline object definition and accessing it using an indexer.

FYI: your code is plain old JavaScript. Only the const and let keywords are ECMAScript 6.

Title: What is this es6 syntax called?

Body:
I am relatively new to es6. I came across the following syntax and can't figure out what is it called.

let parameter = 'key1';
const obj = {
    'key1': 'value1',
    'key2': 'value2',
    'key3': 'value3',
  }[parameter];


问:
customization array adapter to add edittext values to ListView
in my main activity there are tow edit texts one for student name and one for student college, also there is an Add student button, as the following code the onClick function for the Add student button will insert the values of the edit texts to a list view :

```<code>public class Students extends AppCompatActivity {

//Initializing ...
EditText NameEditText;
EditText CollegeEditText;
Button AddButton;
ListView StudentListView;
ArrayList<Student> list;
ArrayAdapter<Student> adapter;
Random rand = new Random();
@Override
protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_students);
</code>```

//Getting references ...

```<code>AddButton=(Button) findViewById(R.id.AddBtn);
NameEditText=(EditText) findViewById(R.id.StudentName);
CollegeEditText=(EditText) findViewById(R.id.College);
StudentListView=(ListView) findViewById(R.id.StudentListView);

//define the array list of students  .
list=new ArrayList<Student>();

//set the communication between the ArrayList and the adapter.

adapter=new ArrayAdapter<Student>(this,android.R.layout.simple_list_item_1,list);
//set the communication between the Adapter and the ListView.

    StudentListView.setAdapter(adapter);

OnClickListener listener=new OnClickListener() {
    @Override
    public void onClick(View v) {
        int ID=rand.nextInt(50) + 1;
        Student student=new Student();
        student.setID(ID);
        student.setName(NameEditText.getText().toString());
        student.setCollege(CollegeEditText.getText().toString());

        list.add(student);
        NameEditText.setText("");
        CollegeEditText.setText("");
        adapter.notifyDataSetChanged();
    }
};
    AddButton.setOnClickListener(listener);

}}
</code>```

As you can see I've created a student class and list of student and used Array adapter to add the values to the ListView.

What I really want is to custom my ListView so each row of the list view would look like this

ListViewRow.xml

So i'm customizing the Array Adapter class to Student Array Adapter as the following code :

```<code>class StudentAdapter extends ArrayAdapter <Student>{

public Context context;
public List<Student>students;

public StudentAdapter(@NonNull Context context, List<Student> list) {
    super(context,R.layout.student_row, list);
    this.context=context;
    this.students=list;

}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {

    LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View rowView = inflater.inflate(R.layout.student_row, parent, false);
    TextView name = (TextView) rowView.findViewById(R.id.Name);
    TextView college = (TextView) rowView.findViewById(R.id.College);
</code>```

//what to do next???

```<code>}
</code>```

}

I want to set the value of each Text View in the Student Row
how can I complete my student Adapter?

答:
Ok, let me see if i got this right.

You have an array of Students
This array, you will pass to the Custom adapter as a List
You have a custom XML Layout for the ListItems (R.layout.student_row)
IN this Layout, you have to TextViews (Name and college)

Now what you want to do, is display the data from the students list in the Item of the List View. To do so, try the following:

```<code>@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {

    LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View rowView = inflater.inflate(R.layout.student_row, parent, false);
    TextView name = (TextView) rowView.findViewById(R.id.Name);
    TextView college = (TextView) rowView.findViewById(R.id.College);

   Student student = getItem(position);

   name.setText(student.getname());
   college.setText(student.getCollege());

   return rowView;

}
</code>```

Explanation:

Student student = getItem(position);

```<code>//You are passing a List of Students to the Custom Adapter
public StudentAdapter(@NonNull Context context, List<Student> list) {
    super(context,R.layout.student_row, list);
    this.context=context;
    this.students=list;
}
</code>```

The dapter will iterate through all the Elements in the list. Therefore, ther will be as many List Items as there are Items in the List of Students.

If you CTRL + Click on the Array Adapter (that you extend in the custom adapter) you will get to the ArrayAdapter Java Class. Here you can search for the getPosition() function.

```<code> /**
     * Returns the position of the specified item in the array.
     *
     * @param item The item to retrieve the position of.
     *
     * @return The position of the specified item.
     */
    public int getPosition(@Nullable T item) {
        return mObjects.indexOf(item);
    }
</code>```

This means, that you will get the Student at the current position of the Student List.

Body:
in my main activity there are tow edit texts one for student name and one for student college, also there is an Add student button, as the following code the onClick function for the Add student button will insert the values of the edit texts to a list view :

public class Students extends AppCompatActivity {

//Initializing ...
EditText NameEditText;
EditText CollegeEditText;
Button AddButton;
ListView StudentListView;
ArrayList<Student> list;
ArrayAdapter<Student> adapter;
Random rand = new Random();
@Override
protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_students);

//Getting references ...

AddButton=(Button) findViewById(R.id.AddBtn);
NameEditText=(EditText) findViewById(R.id.StudentName);
CollegeEditText=(EditText) findViewById(R.id.College);
StudentListView=(ListView) findViewById(R.id.StudentListView);

//define the array list of students  .
list=new ArrayList<Student>();

//set the communication between the ArrayList and the adapter.

adapter=new ArrayAdapter<Student>(this,android.R.layout.simple_list_item_1,list);
//set the communication between the Adapter and the ListView.

    StudentListView.setAdapter(adapter);

OnClickListener listener=new OnClickListener() {
    @Override
    public void onClick(View v) {
        int ID=rand.nextInt(50) + 1;
        Student student=new Student();
        student.setID(ID);
        student.setName(NameEditText.getText().toString());
        student.setCollege(CollegeEditText.getText().toString());

        list.add(student);
        NameEditText.setText("");
        CollegeEditText.setText("");
        adapter.notifyDataSetChanged();
    }
};
    AddButton.setOnClickListener(listener);

}}

As you can see I've created a student class and list of student and used Array adapter to add the values to the ListView.

What I really want is to custom my ListView so each row of the list view would look like this

ListViewRow.xml

So i'm customizing the Array Adapter class to Student Array Adapter as the following code :

class StudentAdapter extends ArrayAdapter <Student>{

public Context context;
public List<Student>students;

public StudentAdapter(@NonNull Context context, List<Student> list) {
    super(context,R.layout.student_row, list);
    this.context=context;
    this.students=list;

}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {

    LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View rowView = inflater.inflate(R.layout.student_row, parent, false);
    TextView name = (TextView) rowView.findViewById(R.id.Name);
    TextView college = (TextView) rowView.findViewById(R.id.College);

//what to do next???

}

}

I want to set the value of each Text View in the Student Row
how can I complete my student Adapter?

Body:
Ok, let me see if i got this right.

You have an array of Students
This array, you will pass to the Custom adapter as a List
You have a custom XML Layout for the ListItems (R.layout.student_row)
IN this Layout, you have to TextViews (Name and college)

Now what you want to do, is display the data from the students list in the Item of the List View. To do so, try the following:

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {

    LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View rowView = inflater.inflate(R.layout.student_row, parent, false);
    TextView name = (TextView) rowView.findViewById(R.id.Name);
    TextView college = (TextView) rowView.findViewById(R.id.College);

   Student student = getItem(position);

   name.setText(student.getname());
   college.setText(student.getCollege());

   return rowView;

}

Explanation:

Student student = getItem(position);

//You are passing a List of Students to the Custom Adapter
public StudentAdapter(@NonNull Context context, List<Student> list) {
    super(context,R.layout.student_row, list);
    this.context=context;
    this.students=list;
}

The dapter will iterate through all the Elements in the list. Therefore, ther will be as many List Items as there are Items in the List of Students.

If you CTRL + Click on the Array Adapter (that you extend in the custom adapter) you will get to the ArrayAdapter Java Class. Here you can search for the getPosition() function.

 /**
     * Returns the position of the specified item in the array.
     *
     * @param item The item to retrieve the position of.
     *
     * @return The position of the specified item.
     */
    public int getPosition(@Nullable T item) {
        return mObjects.indexOf(item);
    }

This means, that you will get the Student at the current position of the Student List.


问:
How can I check if two segments intersect?
How can I check if 2 segments intersect?

I've the following data:

```<code>Segment1 [ {x1,y1}, {x2,y2} ]
Segment2 [ {x1,y1}, {x2,y2} ]
</code>```

I need to write a small algorithm in Python to detect if the 2 lines are intersecting.

答:
We can also solve this utilizing vectors.

Let's define the segments as [start, end]. Given two such segments [A, B] and [C, D] that both have non-zero length, we can choose one of the endpoints to be used as a reference point so that we get three vectors:

```<code>x = 0
y = 1
p = A-C = [C[x]-A[x], C[y]-A[y]]
q = B-A = [B[x]-A[x], B[y]-A[y]]
r = D-C = [D[x]-C[x], D[y]-C[y]]
</code>```

From there, we can look for an intersection by calculating t and u in p + t*r = u*q. After playing around with the equation a little, we get:

```<code>t = (q[y]*p[x] - q[x]*p[y])/(q[x]*r[y] - q[y]*r[x])
u = (p[x] + t*r[x])/q[x]
</code>```

Thus, the function is:

```<code>def intersects(a, b):
    p = [b[0][0]-a[0][0], b[0][1]-a[0][1]]
    q = [a[1][0]-a[0][0], a[1][1]-a[0][1]]
    r = [b[1][0]-b[0][0], b[1][1]-b[0][1]]

    t = (q[1]*p[0] - q[0]*p[1])/(q[0]*r[1] - q[1]*r[0]) \
        if (q[0]*r[1] - q[1]*r[0]) != 0 \
        else (q[1]*p[0] - q[0]*p[1])
    u = (p[0] + t*r[0])/q[0] \
        if q[0] != 0 \
        else (p[1] + t*r[1])/q[1]

    return t >= 0 and t <= 1 and u >= 0 and u <= 1
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How can I check if 2 segments intersect?

I've the following data:

Segment1 [ {x1,y1}, {x2,y2} ]
Segment2 [ {x1,y1}, {x2,y2} ]

I need to write a small algorithm in Python to detect if the 2 lines are intersecting.

LastEditorDisplayName: Roger Pate

Body:
We can also solve this utilizing vectors.

Let's define the segments as [start, end]. Given two such segments [A, B] and [C, D] that both have non-zero length, we can choose one of the endpoints to be used as a reference point so that we get three vectors:

x = 0
y = 1
p = A-C = [C[x]-A[x], C[y]-A[y]]
q = B-A = [B[x]-A[x], B[y]-A[y]]
r = D-C = [D[x]-C[x], D[y]-C[y]]

From there, we can look for an intersection by calculating t and u in p + t*r = u*q. After playing around with the equation a little, we get:

t = (q[y]*p[x] - q[x]*p[y])/(q[x]*r[y] - q[y]*r[x])
u = (p[x] + t*r[x])/q[x]

Thus, the function is:

def intersects(a, b):
    p = [b[0][0]-a[0][0], b[0][1]-a[0][1]]
    q = [a[1][0]-a[0][0], a[1][1]-a[0][1]]
    r = [b[1][0]-b[0][0], b[1][1]-b[0][1]]

    t = (q[1]*p[0] - q[0]*p[1])/(q[0]*r[1] - q[1]*r[0]) \
        if (q[0]*r[1] - q[1]*r[0]) != 0 \
        else (q[1]*p[0] - q[0]*p[1])
    u = (p[0] + t*r[0])/q[0] \
        if q[0] != 0 \
        else (p[1] + t*r[1])/q[1]

    return t >= 0 and t <= 1 and u >= 0 and u <= 1


问:
RxJava2 toList() never emits
So I have following Disposable which doesn't work. I am using Room to get all rows from a table as a list, map each of them to something and create a list and then it doesn't continue from there.</p>

```<code>storedSuggestionDao
    .getSuggestionsOrderByType() //Flowable
    .doOnNext(storedSuggestions -> Timber.e("storedSuggestions: " + storedSuggestions)) //this work
    .flatMapIterable(storedSuggestions -> storedSuggestions)
    .map(Selection::create) ))
    .doOnNext(selection -> Timber.e("Selection: " + selection)) // works
    .toList()
    .toObservable() // nothing works after this...
    .doOnNext(selections -> Timber.d("selections: " + selections))
    .map(SuggestionUiModel::create)
    .doOnNext(suggestionUiModel -> Timber.d("suggestionUiModel: " + suggestionUiModel))
    .subscribe();
</code>```

答:
I think in your case you don't need to call .toObserable()

It should be like this

```<code>storedSuggestionDao
.getSuggestionsOrderByType() //Flowable
.doOnNext(storedSuggestions -> Timber.e("storedSuggestions: " + storedSuggestions)) //this work
.flatMapIterable(storedSuggestions -> storedSuggestions)
.map(Selection::create) ))
.doOnNext(selection -> Timber.e("Selection: " + selection)) // works
.toList() // you don't have to call .toObserable()
.map(SuggestionUiModel::create)
.subscribe();
</code>```

Title: RxJava2 toList() never emits

Body:
So I have following Disposable which doesn't work. I am using Room to get all rows from a table as a list, map each of them to something and create a list and then it doesn't continue from there.

storedSuggestionDao
    .getSuggestionsOrderByType() //Flowable
    .doOnNext(storedSuggestions -> Timber.e("storedSuggestions: " + storedSuggestions)) //this work
    .flatMapIterable(storedSuggestions -> storedSuggestions)
    .map(Selection::create) ))
    .doOnNext(selection -> Timber.e("Selection: " + selection)) // works
    .toList()
    .toObservable() // nothing works after this...
    .doOnNext(selections -> Timber.d("selections: " + selections))
    .map(SuggestionUiModel::create)
    .doOnNext(suggestionUiModel -> Timber.d("suggestionUiModel: " + suggestionUiModel))
    .subscribe();

Body:
I think in your case you don't need to call .toObserable()

It should be like this

storedSuggestionDao
.getSuggestionsOrderByType() //Flowable
.doOnNext(storedSuggestions -> Timber.e("storedSuggestions: " + storedSuggestions)) //this work
.flatMapIterable(storedSuggestions -> storedSuggestions)
.map(Selection::create) ))
.doOnNext(selection -> Timber.e("Selection: " + selection)) // works
.toList() // you don't have to call .toObserable()
.map(SuggestionUiModel::create)
.subscribe();


问:
Anyone did php codeigniter pagination with sorting?
i'm working in php codeigniter. and i worked with pagination but how to sorting the field data like a Datatable pagination. Please help me</p>

答:
In view, between tag form:

```<code><!--Código para capturar la ordenación-->
  <input type="hidden" id="orderby" name="orderby" value="<?php if (isset($orderby)) echo $orderby; ?>">
  <input type="hidden" id="tipoOrderby" name="tipoOrderby" value="<?php if (isset($tipoOrderby)) echo $tipoOrderby; ?>">
</code>```

If you put this piece of code in your head table in view:

```<code> <thead>
              <tr>
                <th> Column 1 <a  href="#" data-type="order" data-field="column1"><i class="fa fa-sort"></i></a></th>
                <th> Column 2 <a href="#" data-type="order" data-field='column2'><i class="fa fa-sort"></i></a></th>
              </tr>
            </thead>
</code>```

In jquery (file.js), (could be improved by you):

```<code>// Código para controlar la ordenación de la tablas
      $(document).find('a[data-type="order"]').each(function () {
        if ($(this).data("field") == document.form1.orderby.value) {
          if (document.form1.tipoOrderby.value == "ASC") {
            $(this).data("order", "DESC");
            $("i", this).addClass('fa-sort-desc');
          } else {
            $("i", this).addClass('fa-sort-asc');
            $(this).data("order", "ASC");
          }
        } else {
          $("i", this).addClass('fa-sort');
          $(this).data("order", "ASC");
        }
        $(this).click(function (event) {
          event.preventDefault();
          document.form1.orderby.value = $(this).data("field");
          document.form1.tipoOrderby.value = $(this).data("order");
          document.form1.submit();
        });
      });
</code>```

In Codeigniter controller:

```<code>   if($form_data['orderby'] == ""){ //Default sort
      $orderby = "name";
      $tipoOrderby = 'ASC';
    }
    else{
      $orderby = $this->input->post('orderby');
      $tipoOrderby = $this->input->post('tipoOrderby');
    }
  //Returns values view
  $data['orderby'] = $orderby;
  $data['tipoOrderby'] = $tipoOrderby;
</code>```

Last, you should include this in your query model =)

```<code>$query = $this->model->get($pages, $this->uri->segment($config['uri_segment']), $where, $orderby, $tipoOrderby);
</code>```

Any doubts?

Body:
In view, between tag form:

<!--Código para capturar la ordenación-->
  <input type="hidden" id="orderby" name="orderby" value="<?php if (isset($orderby)) echo $orderby; ?>">
  <input type="hidden" id="tipoOrderby" name="tipoOrderby" value="<?php if (isset($tipoOrderby)) echo $tipoOrderby; ?>">

If you put this piece of code in your head table in view:

 <thead>
              <tr>
                <th> Column 1 <a  href="#" data-type="order" data-field="column1"><i class="fa fa-sort"></i></a></th>
                <th> Column 2 <a href="#" data-type="order" data-field='column2'><i class="fa fa-sort"></i></a></th>
              </tr>
            </thead>

In jquery (file.js), (could be improved by you):

// Código para controlar la ordenación de la tablas
      $(document).find('a[data-type="order"]').each(function () {
        if ($(this).data("field") == document.form1.orderby.value) {
          if (document.form1.tipoOrderby.value == "ASC") {
            $(this).data("order", "DESC");
            $("i", this).addClass('fa-sort-desc');
          } else {
            $("i", this).addClass('fa-sort-asc');
            $(this).data("order", "ASC");
          }
        } else {
          $("i", this).addClass('fa-sort');
          $(this).data("order", "ASC");
        }
        $(this).click(function (event) {
          event.preventDefault();
          document.form1.orderby.value = $(this).data("field");
          document.form1.tipoOrderby.value = $(this).data("order");
          document.form1.submit();
        });
      });

In Codeigniter controller:

   if($form_data['orderby'] == ""){ //Default sort
      $orderby = "name";
      $tipoOrderby = 'ASC';
    }
    else{
      $orderby = $this->input->post('orderby');
      $tipoOrderby = $this->input->post('tipoOrderby');
    }
  //Returns values view
  $data['orderby'] = $orderby;
  $data['tipoOrderby'] = $tipoOrderby;

Last, you should include this in your query model =)

$query = $this->model->get($pages, $this->uri->segment($config['uri_segment']), $where, $orderby, $tipoOrderby);

Any doubts?


问:
square numbers given in an sequence
Given a positive integer sequence of numbers in an array with common difference 2
for e.g 2 4 6 8
Now replace each number by its square. Perform the computations efficiently.
I was asked this question in an interview and i gave him o(n) solution using bitwise operator since it is operation in the multiples of 2.If there is any better method please suggest.</p>

答:
It really depends on the interviewer, and what they think is "the right thing". If it were me, I'd think the (n << 2) + 4 were neat, but on the other hand, I'd hate to see it in my code. It takes more thinking to maintain, and there's a fair chance a good optimizer might do just as good a job.

I think the phrase "perform the operation efficiently" is probably our clue that the interviewer was looking for a fast computation. It's still O(n), but let's not forget that when you are comparing two O(n) algorithms, the coefficients start to matter again.

Title: square numbers given in an sequence

LastEditorDisplayName: Aryabhatta


问:
How to set a custom environment variable in EMR to be available for a spark Application
I need to set a custom environment variable in EMR to be available when running a spark application.

I have tried adding this:

```<code>                   ...
                   --configurations '[
                                      {
                                      "Classification": "spark-env",
                                      "Configurations": [
                                        {
                                        "Classification": "export",
                                        "Configurations": [],
                                        "Properties": { "SOME-ENV-VAR": "qa1" }
                                        }
                                      ],
                                      "Properties": {}
                                      }
                                      ]'
                   ...
</code>```

and also tried to replace "spark-env with hadoop-env
but nothing seems to work.

There is this answer from the aws forums. but I can't figure out how to apply it.
I'm running on EMR 5.3.1 and launch it with a preconfigured step from the cli: aws emr create-cluster...

答: For me replacing spark-env to yarn-env fixed issue.

Body:
I need to set a custom environment variable in EMR to be available when running a spark application.

I have tried adding this:

                   ...
                   --configurations '[
                                      {
                                      "Classification": "spark-env",
                                      "Configurations": [
                                        {
                                        "Classification": "export",
                                        "Configurations": [],
                                        "Properties": { "SOME-ENV-VAR": "qa1" }
                                        }
                                      ],
                                      "Properties": {}
                                      }
                                      ]'
                   ...

and also tried to replace "spark-env with hadoop-env
but nothing seems to work.

There is this answer from the aws forums. but I can't figure out how to apply it.
I'm running on EMR 5.3.1 and launch it with a preconfigured step from the cli: aws emr create-cluster...


问:
getting an error- listen EADDRINUSE :::3000 on windows machine
I've searched a lot and I understand there is some process or server running on port 3000, but how can I stop that and run a new express http server on port 3000. There are few answers which tell it for Unix environment..but how to release the port on windows environment using cmd terminal.
Closing the task using PID also didn't work for me.
Thanks in advance </p>

答:
In windows 10, open task manager and go to Details tab.

There you will find node.exe running.

End that task and your port will be released.


问:
Getting String value from enum in Java
I have a enum defined like this and I would like to be able to obtain the strings for the individual statuses. How should I write such a method?

I can get the int values of the statuses but would like the option of getting the string values from the ints as well.

```<code>public enum Status {
    PAUSE(0),
    START(1),
    STOP(2);

    private final int value;

    private Status(int value) {
        this.value = value
    }

    public int getValue() {
        return value;
    }
}
</code>```

答:
I believe enum have a .name() in its API, pretty simple to use like this example:

```<code>private int security;
public String security(){ return Security.values()[security].name(); }
public void setSecurity(int security){ this.security = security; }

    private enum Security {
            low,
            high
    }
</code>```

With this you can simply call

```<code>yourObject.security()
</code>```

and it returns high/low as String, in this example

Title: Getting String value from enum in Java

Body:
I have a enum defined like this and I would like to be able to obtain the strings for the individual statuses. How should I write such a method?

I can get the int values of the statuses but would like the option of getting the string values from the ints as well.

public enum Status {
    PAUSE(0),
    START(1),
    STOP(2);

    private final int value;

    private Status(int value) {
        this.value = value
    }

    public int getValue() {
        return value;
    }
}

Body:
I believe enum have a .name() in its API, pretty simple to use like this example:

private int security;
public String security(){ return Security.values()[security].name(); }
public void setSecurity(int security){ this.security = security; }

    private enum Security {
            low,
            high
    }

With this you can simply call

yourObject.security()

and it returns high/low as String, in this example


问:
Built.io integration failed in iOS application due to ambiguous method call error
I am trying to integrate built.io in iOS application using Xcode 9.1 and swift 4 but it failed due to ambiguous save call error, although I have only called this method once still it says ambiguous call. I am unable to identify the problem.
I referred this link to integrate sdk in iOS :

Code used is

import UIKit
import Contentstack
import BuiltIO

class ViewController: UIViewController {

```<code>func built(){
    var builtApplication : BuiltApplication = Built.application(withAPIKey: "")
    var pc : BuiltClass = builtApplication.class(withUID: "test")
    var projectObject:BuiltObject = pc.object()

    projectObject.save { (responseType, err) in //ambiguous error here on save call
        if err != nil {
            print("Err")
        } else {
            print("Success")
        }
    }
}
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}
</code>```

}

I have installed sdk in project using cocoapod. Below image contains application screenshot that shows error. I am using BuiltObject class object to call save method but when I jump into save method it takes me to method of BuiltKeyStore class, and I completely don't understand why? Please help, Thanks in advance

答:
You need to pass completionBlock as a parameter instead of inline.
Try the below code which works fine for Swift 3.2 & 4,

```<code>    let completionBlock:BuiltRequestCompletionHandler = { (responseType:BuiltResponseType, error:Error?) in
        if error != nil {
            print("Err")
        } else {
            print("Success")
        }
    }

    projectObject.save(completionBlock)
</code>```

Give it a try that should definitely work.

Body:
I am trying to integrate built.io in iOS application using Xcode 9.1 and swift 4 but it failed due to ambiguous save call error, although I have only called this method once still it says ambiguous call. I am unable to identify the problem.
I referred this link to integrate sdk in iOS :

Code used is

import UIKit
import Contentstack
import BuiltIO

class ViewController: UIViewController {

func built(){
    var builtApplication : BuiltApplication = Built.application(withAPIKey: "")
    var pc : BuiltClass = builtApplication.class(withUID: "test")
    var projectObject:BuiltObject = pc.object()

    projectObject.save { (responseType, err) in //ambiguous error here on save call
        if err != nil {
            print("Err")
        } else {
            print("Success")
        }
    }
}
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

}

I have installed sdk in project using cocoapod. Below image contains application screenshot that shows error. I am using BuiltObject class object to call save method but when I jump into save method it takes me to method of BuiltKeyStore class, and I completely don't understand why? Please help, Thanks in advance

Body:
You need to pass completionBlock as a parameter instead of inline.
Try the below code which works fine for Swift 3.2 & 4,

    let completionBlock:BuiltRequestCompletionHandler = { (responseType:BuiltResponseType, error:Error?) in
        if error != nil {
            print("Err")
        } else {
            print("Success")
        }
    }

    projectObject.save(completionBlock)

Give it a try that should definitely work.


问:
Exiting an infinite loop with a key in c++ on linux
i have an infinite loop that should be ended if i pressed any key. The program runs in linux. I have stumbled upon a function Here is a bit of my code :

```<code>int main(){
      While(1){
        ParseData(); //writing data to a text file
      }
return 0;
}
</code>```

so i know that i can terminate the process by using ctrl + c in terminal, but it seems that it will interrupt the writing process so the datas are not written completely halfway through the process. I read that i need to use function from ncurses library , but i can't quite understand any.

Can someone help me with it? Thanks!

答:
You can declare an atomic_bool and move your main loop to another thread. Now you can wait with a simple cin, once the user presses any key you exit your loop.

```<code>std::atomic_boolean stop = false;

void loop() {
    while(!stop)
    {
        ParseData(); // your loop body here
    }
}

int main() {

    std::thread t(loop); // Separate thread for loop.

    // Wait for input character (this will suspend the main thread, but the loop
    // thread will keep running).
    std::cin.get();

    // Set the atomic boolean to true. The loop thread will exit from
    // loop and terminate.
    stop = true;

    t.join();
    return 0;
}
</code>```

Body:
i have an infinite loop that should be ended if i pressed any key. The program runs in linux. I have stumbled upon a function Here is a bit of my code :

int main(){
      While(1){
        ParseData(); //writing data to a text file
      }
return 0;
}

so i know that i can terminate the process by using ctrl + c in terminal, but it seems that it will interrupt the writing process so the datas are not written completely halfway through the process. I read that i need to use function from ncurses library , but i can't quite understand any.

Can someone help me with it? Thanks!

Body:
You can declare an atomic_bool and move your main loop to another thread. Now you can wait with a simple cin, once the user presses any key you exit your loop.

std::atomic_boolean stop = false;

void loop() {
    while(!stop)
    {
        ParseData(); // your loop body here
    }
}

int main() {

    std::thread t(loop); // Separate thread for loop.

    // Wait for input character (this will suspend the main thread, but the loop
    // thread will keep running).
    std::cin.get();

    // Set the atomic boolean to true. The loop thread will exit from
    // loop and terminate.
    stop = true;

    t.join();
    return 0;
}


问:
php + jqgrid + export to excel
Somebody knows a way to export the data from a jqgrid to excel?

I want to do a report using this jqgrid that i think is  awsome. But i need to save or print this report somehow, because is information to be keeped.
Somebody knows any way??

答:
I solved your problem .and now iam able to export data excel with column names please refer my code.

```<code>function exportExcel()
    {
        var mya=new Array();
        mya=$("#tblnoupdate").getDataIDs();  // Get All IDs
        var data=$("#tblnoupdate").getRowData(mya[0]);     // Get First row to get the labels
        var colNames=new Array();
        var ii=0;
        for (var i in data){colNames[ii++]=i;}    // capture col names
        var html="";
            for(k=0;k<colNames.length;k++)
            {
            html=html+colNames[k]+"\t";     // output each Column as tab delimited
            }
            html=html+"\n";                    // Output header with end of line
        for(i=0;i<mya.length;i++)
            {
            data=$("#tblnoupdate").getRowData(mya[i]); // get each row
            for(j=0;j<colNames.length;j++)
                {
             html=html+data[colNames[j]]+"\t"; // output each Row as tab delimited
                }
            html=html+"\n";  // output each row with end of line

            }
        html=html+"\n";  // end of line at the end
        document.forms[0].csvBuffer.value=html;
        document.forms[0].method='POST';
        document.forms[0].action='<?php echo $baseurl;?>csvexport.php';  // send it to server which will open this contents in excel file
        document.forms[0].target='_blank';
        document.forms[0].submit();
    }
</code>```

Please let me know if you face  any problem.

Title: php + jqgrid + export to excel

Body:
I solved your problem .and now iam able to export data excel with column names please refer my code.

function exportExcel()
    {
        var mya=new Array();
        mya=$("#tblnoupdate").getDataIDs();  // Get All IDs
        var data=$("#tblnoupdate").getRowData(mya[0]);     // Get First row to get the labels
        var colNames=new Array();
        var ii=0;
        for (var i in data){colNames[ii++]=i;}    // capture col names
        var html="";
            for(k=0;k<colNames.length;k++)
            {
            html=html+colNames[k]+"\t";     // output each Column as tab delimited
            }
            html=html+"\n";                    // Output header with end of line
        for(i=0;i<mya.length;i++)
            {
            data=$("#tblnoupdate").getRowData(mya[i]); // get each row
            for(j=0;j<colNames.length;j++)
                {
             html=html+data[colNames[j]]+"\t"; // output each Row as tab delimited
                }
            html=html+"\n";  // output each row with end of line

            }
        html=html+"\n";  // end of line at the end
        document.forms[0].csvBuffer.value=html;
        document.forms[0].method='POST';
        document.forms[0].action='<?php echo $baseurl;?>csvexport.php';  // send it to server which will open this contents in excel file
        document.forms[0].target='_blank';
        document.forms[0].submit();
    }

Please let me know if you face  any problem.


问:
Eclipse:I cannot import javax.json (or javax.json.stream)
Trying to use GSON and JSON-api. No issues with importing GSON into my code.

Getting error ("cannot find symbol" message in Eclipse compiler) when importing JSON-api.

The end result is that I want to use "JsonParser" which according to an Oracle page (click here for link) is inside javax.json.

Here's a snippet of my java code:

```<code>package com.myorg.core.impl.view.tools;

import com.google.gson.Gson; //no error

import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.json; // error
//also tried import javax.json.stream same results.
</code>```

I have the following lines in my pom.xml

```<code>    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
    </dependency>
    <dependency>
        <groupId>javax.json</groupId>
        <artifactId>javax.json-api</artifactId>
        <version>1.1.2</version>
    </dependency>
    <!-- I also tried version 1.0. same result -->
</code>```

In both dependencies, I can see the jar files in my Eclipse .m2 repository

```<code>myuser@myusers-MacBook-Pro : repository
=> find ~/.m2 -iname "*gson*" -type f
/Users/myuser/.m2/repository/com/google/code/gson/gson/2.7/gson-2.7.jar
/Users/myuser/.m2/repository/com/google/code/gson/gson/2.7/gson-2.7.jar.lastUpdated
/Users/myuser/.m2/repository/com/google/code/gson/gson/2.7/gson-2.7.jar.sha1
/Users/myuser/.m2/repository/com/google/code/gson/gson/2.7/gson-2.7.pom
/Users/myuser/.m2/repository/com/google/code/gson/gson/2.7/gson-2.7.pom.lastUpdated
/Users/myuser/.m2/repository/com/google/code/gson/gson/2.7/gson-2.7.pom.sha1
/Users/myuser/.m2/repository/com/google/code/gson/gson-parent/2.7/gson-parent-2.7.pom
/Users/myuser/.m2/repository/com/google/code/gson/gson-parent/2.7/gson-parent-2.7.pom.lastUpdated
/Users/myuser/.m2/repository/com/google/code/gson/gson-parent/2.7/gson-parent-2.7.pom.sha1
11:54:03 Thu Nov 16
myuser@myusers-MacBook-Pro : repository
=> find ~/.m2 -iname "*json-api*" -type f
/Users/myuser/.m2/repository/javax/json/javax.json-api/1.1.2/javax.json-api-1.1.2.jar
/Users/myuser/.m2/repository/javax/json/javax.json-api/1.1.2/javax.json-api-1.1.2.jar.lastUpdated
/Users/myuser/.m2/repository/javax/json/javax.json-api/1.1.2/javax.json-api-1.1.2.jar.sha1
/Users/myuser/.m2/repository/javax/json/javax.json-api/1.1.2/javax.json-api-1.1.2.pom
/Users/myuser/.m2/repository/javax/json/javax.json-api/1.1.2/javax.json-api-1.1.2.pom.lastUpdated
/Users/myuser/.m2/repository/javax/json/javax.json-api/1.1.2/javax.json-api-1.1.2.pom.sha1
</code>```

答:
Firstly about your import

```<code>import javax.json; // error, sure it will be an error
</code>```

Above should tell you something like

Only a type can be imported. javax.json resolves to a package

So import type or types with a wildcard:

```<code>import javax.json.*;
import javax.json.stream.*;
</code>```

or just the JsonParser

```<code>import javax.json.stream.JsonParser;
</code>```

The end result is that I want to use "JsonParser"

You have dependency for javax.json-api in your pom.

It is just an API having  only

```<code>package javax.json.stream;

interface JsonParser { ...
</code>```

On the other hand GSON does not implement that but has its own

```<code>package com.google.gson;

public final class JsonParser // not implementing above mentioned
</code>```

I am not an expert with all the JSON libraries available but at a very quick glance could not find any JsonParser implementations strictly implementing that interface in that package.

Maybe you manage with com.google.gson.JsonParser only?

Body:
Trying to use GSON and JSON-api. No issues with importing GSON into my code.

Getting error ("cannot find symbol" message in Eclipse compiler) when importing JSON-api.

The end result is that I want to use "JsonParser" which according to an Oracle page (click here for link) is inside javax.json.

Here's a snippet of my java code:

package com.myorg.core.impl.view.tools;

import com.google.gson.Gson; //no error

import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.json; // error
//also tried import javax.json.stream same results.

I have the following lines in my pom.xml

    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
    </dependency>
    <dependency>
        <groupId>javax.json</groupId>
        <artifactId>javax.json-api</artifactId>
        <version>1.1.2</version>
    </dependency>

In both dependencies, I can see the jar files in my Eclipse .m2 repository

myuser@myusers-MacBook-Pro : repository
=> find ~/.m2 -iname "*gson*" -type f
/Users/myuser/.m2/repository/com/google/code/gson/gson/2.7/gson-2.7.jar
/Users/myuser/.m2/repository/com/google/code/gson/gson/2.7/gson-2.7.jar.lastUpdated
/Users/myuser/.m2/repository/com/google/code/gson/gson/2.7/gson-2.7.jar.sha1
/Users/myuser/.m2/repository/com/google/code/gson/gson/2.7/gson-2.7.pom
/Users/myuser/.m2/repository/com/google/code/gson/gson/2.7/gson-2.7.pom.lastUpdated
/Users/myuser/.m2/repository/com/google/code/gson/gson/2.7/gson-2.7.pom.sha1
/Users/myuser/.m2/repository/com/google/code/gson/gson-parent/2.7/gson-parent-2.7.pom
/Users/myuser/.m2/repository/com/google/code/gson/gson-parent/2.7/gson-parent-2.7.pom.lastUpdated
/Users/myuser/.m2/repository/com/google/code/gson/gson-parent/2.7/gson-parent-2.7.pom.sha1
11:54:03 Thu Nov 16
myuser@myusers-MacBook-Pro : repository
=> find ~/.m2 -iname "*json-api*" -type f
/Users/myuser/.m2/repository/javax/json/javax.json-api/1.1.2/javax.json-api-1.1.2.jar
/Users/myuser/.m2/repository/javax/json/javax.json-api/1.1.2/javax.json-api-1.1.2.jar.lastUpdated
/Users/myuser/.m2/repository/javax/json/javax.json-api/1.1.2/javax.json-api-1.1.2.jar.sha1
/Users/myuser/.m2/repository/javax/json/javax.json-api/1.1.2/javax.json-api-1.1.2.pom
/Users/myuser/.m2/repository/javax/json/javax.json-api/1.1.2/javax.json-api-1.1.2.pom.lastUpdated
/Users/myuser/.m2/repository/javax/json/javax.json-api/1.1.2/javax.json-api-1.1.2.pom.sha1

Body:
Firstly about your import

import javax.json; // error, sure it will be an error

Above should tell you something like

Only a type can be imported. javax.json resolves to a package

So import type or types with a wildcard:

import javax.json.*;
import javax.json.stream.*;

or just the JsonParser

import javax.json.stream.JsonParser;

The end result is that I want to use "JsonParser"

You have dependency for javax.json-api in your pom.

It is just an API having  only

package javax.json.stream;

interface JsonParser { ...

On the other hand GSON does not implement that but has its own

package com.google.gson;

public final class JsonParser // not implementing above mentioned

I am not an expert with all the JSON libraries available but at a very quick glance could not find any JsonParser implementations strictly implementing that interface in that package.

Maybe you manage with com.google.gson.JsonParser only?


问:
drupal 7 - programmatically disable block
How programmatically disable blocks under drupal 7?</p>

答:
The real reason is why would you want to disable block?
if you want to show a block depending on users, to do a db attack is not a good solution.

I think you can do that with region and preprocess system. A region can show anythings, blocks, text or nothing.

Example :

```<code>function HOOK_preprocess_node(&$variables, $hook){
    //check the current user code...
    //..
    if (_condition_is_ok){
        $block = module_invoke('module', 'block_view', 'block_name');
        $variables["my_block"] = $block["content"];
    }
}
</code>```

If you do that dont forget to check the variable is set in your tpl :)

I don't think that the better way to do that but it's better than use db_update, db_update write directly in your db, and by pass the drupal engine.

Body:
The real reason is why would you want to disable block?
if you want to show a block depending on users, to do a db attack is not a good solution.

I think you can do that with region and preprocess system. A region can show anythings, blocks, text or nothing.

Example :

function HOOK_preprocess_node(&$variables, $hook){
    //check the current user code...
    //..
    if (_condition_is_ok){
        $block = module_invoke('module', 'block_view', 'block_name');
        $variables["my_block"] = $block["content"];
    }
}

If you do that dont forget to check the variable is set in your tpl :)

I don't think that the better way to do that but it's better than use db_update, db_update write directly in your db, and by pass the drupal engine.


问:
iccube DEFAULT time dimension vs NON-DEFAULT
What are the differences between a DEFAULT time dimension and another time dimension ?
Is it just like for the default measure, i.e. used if no measure is mentionned in a MDX?

Can we do exactly the same things with a non-default time dimension ?

I'm thinking about Evolutions, running sums, avg, dtXXX functions, ytd function.

答:
The DEFAULT time dimension is the one that is going to be used in custom rollup aggregation (www) when you do not define any hierarchy and a few MDX time functions when no hierarchy is defined (Ytd, Qtd, Mtd, Wtd ...).

Apart from that there is no difference with a regular time dimension.


问:
Does the Log method cost a lot of execution time?
In my project, the Log function has been used in many places, and there isn't any "if statement" to control it.we use just like this:

```<code>...
String s = generateString();
Log.d(TAG, "result is : " + s);
...
</code>```

When I see the consumer of time by the android profiler, the Log function seems to cost a lot of time.

Does anyone know the actual time consume of Log function?Thank you very much!

答:
Addition to Gils Answer which is correct:
I recommend using Timber for Android Logging.

Besides a lot of helpful features Timber can add to your development, you can do something like that to avoid Log statements in your release app:

```<code>public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        //Only log when we are in DEBUG mode
        if (BuildConfig.DEBUG) {
            Timber.plant(new Timber.DebugTree());
        }
}
</code>```

Body:
In my project, the Log function has been used in many places, and there isn't any "if statement" to control it.we use just like this:

...
String s = generateString();
Log.d(TAG, "result is : " + s);
...

When I see the consumer of time by the android profiler, the Log function seems to cost a lot of time.

Does anyone know the actual time consume of Log function?Thank you very much!

Body:
Addition to Gils Answer which is correct:
I recommend using Timber for Android Logging.

Besides a lot of helpful features Timber can add to your development, you can do something like that to avoid Log statements in your release app:

public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        //Only log when we are in DEBUG mode
        if (BuildConfig.DEBUG) {
            Timber.plant(new Timber.DebugTree());
        }
}


问:
Incrementing ratio button id in for loop
In a for loop i'm rendering radio buttons, but i need to increment the  radio button id to radio1,radio2 and so on. how can i do it ?

Please help.

            <input id="radio1" name="radio" [(ngModel)]="demandValue" [value]="demand.value" type="radio">
            {{demand.name}}
```

答:
use index let i = index; and provide it to your id. But your ngModel and ngValue objects should be coming from your Demands array. Otherwise if you select the value in a radio button, it will affect to all radio buttons.

Try this.

            <input id="radio{{I + 1 }}" name="radio" [(ngModel)]="demandValue" [value]="demand.value" type="radio">
            {{demand.name}}
```

Body:
use index let i = index; and provide it to your id. But your ngModel and ngValue objects should be coming from your Demands array. Otherwise if you select the value in a radio button, it will affect to all radio buttons.

Try this.

<span class="radio-radio-wrapper padding-radio" *ngFor="let demand of Demands; let i = index;">
            <input id="radio{{I + 1 }}" name="radio" [(ngModel)]="demandValue" [value]="demand.value" type="radio">
            <span class="radioLabel"><label class="custom-control-description" for="radio{{I + 1}}">{{demand.name}}</label></span>
</span>


问:
kextutil says my kernel extension signature is invalid, but code sign says it is valid. It does not load
This is the first time I have ever tried to sign a kernel extension, so I am open to the possibility that I'm doing it wrong.

I requested a kernel signing certificate from Apple.  I was required to fill out a form that demonstrated that I really needed to create an in-kernel driver, rather than a user space driver that talked to an IOUserClient.

```<code>$ sudo kextutil FL2000.kext/
Password:
Notice: /Library/Extensions/FL2000.kext has debug properties set.
Diagnostics for /Library/Extensions/FL2000.kext:
Code Signing Failure: code signature is invalid
Untrusted kexts are not allowed
ERROR: invalid signature for com.frescologic.FL2000, will not load
</code>```

It doesn't load at boot - it needs to because it is a graphics driver.

```<code>$ codesign --verify -vvvv FL2000.kext/
FL2000.kext/: valid on disk
FL2000.kext/: satisfies its Designated Requirement

$ codesign --display -vvvv FL2000.kext/
Executable=/Library/Extensions/FL2000.kext/Contents/MacOS/FL2000
Identifier=com.frescologic.FL2000
Format=bundle with Mach-O thin (x86_64)
CodeDirectory v=20200 size=1590 flags=0x0(none) hashes=44+3 location=embedded
Hash type=sha256 size=32
CandidateCDHash sha1=83a0328f9af971484b7e30c8d04e68a96dee72c1
CandidateCDHash sha256=cd6c72d17f00d2eed36078eece6a5b536c482772
Hash choices=sha1,sha256
Page size=4096
CDHash=cd6c72d17f00d2eed36078eece6a5b536c482772
Signature size=4693
Authority=Mac Developer: Michael Crawford (YU8CSARZFD)
Authority=Apple Worldwide Developer Relations Certification Authority
Authority=Apple Root CA
Signed Time=Nov 10, 2017, 1:10:07 PM
Info.plist entries=20
TeamIdentifier=444JK52Q93
Sealed Resources version=2 rules=13 files=2
Internal requirements count=1 size=184
</code>```

Help me O Stackoverflow-Wan.  You're my only hope!

答:
I should have spotted this in your codesign output, but your comments make it clear: the problem is with the certificate you are using. Apple issues 4 kinds of Mac codesigning certificates:

"Mac Developer" certificates are for signing apps destined for the Mac App Store during the development phase. This is the type of certificate you appeared to be trying to use for signing a kext. This won't work. It will sign it OK, but kextd etc. won't accept the signature.

"Developer ID Application" certificates are for signing apps which will be distributed outside the App Store. A special variant of this type of certificate includes the certificate extension "( 1.2.840.113635.100.6.1.18 )" - only with this extension, it becomes possible to sign kexts such that they are accepted by macOS.

"Developer ID Installer" certificates are for signing Installer .pkg files/bundles. If you are distributing an app via a DMG or ZIP file, you shouldn't need this, but if you need an installer, possibly because what you're distributing isn't an app, but a kext or system service, then you should create an installer package and sign that with such a certificate.

"Mac Distribution" certificates are what you use to sign the build of an app before submitting it to the Mac App Store. These are also irrelevant to kext signing.

Presumably for security reasons, certificate types 2-4 are only issued to Team Agents in an Apple Developer account. Lowly developers are only given "Mac Developer" certificates, which are intended to be purely temporary, so they're not very security-relevant.

So to summarise, your problem is that you're using a "Mac Developer" certificate to sign a kext. You need to use a "Developer ID Application" certificate instead, specifically one that was issued after the development team was granted kext signing privileges by Apple. If you haven't applied for kext signing privileges, you can do so using this form. (It sounds like you have done so previously, but I'm pointing it out for the benefit of people in the same situation who might stumble across this in the future.)

Body:
This is the first time I have ever tried to sign a kernel extension, so I am open to the possibility that I'm doing it wrong.

I requested a kernel signing certificate from Apple.  I was required to fill out a form that demonstrated that I really needed to create an in-kernel driver, rather than a user space driver that talked to an IOUserClient.

$ sudo kextutil FL2000.kext/
Password:
Notice: /Library/Extensions/FL2000.kext has debug properties set.
Diagnostics for /Library/Extensions/FL2000.kext:
Code Signing Failure: code signature is invalid
Untrusted kexts are not allowed
ERROR: invalid signature for com.frescologic.FL2000, will not load

It doesn't load at boot - it needs to because it is a graphics driver.

$ codesign --verify -vvvv FL2000.kext/
FL2000.kext/: valid on disk
FL2000.kext/: satisfies its Designated Requirement

$ codesign --display -vvvv FL2000.kext/
Executable=/Library/Extensions/FL2000.kext/Contents/MacOS/FL2000
Identifier=com.frescologic.FL2000
Format=bundle with Mach-O thin (x86_64)
CodeDirectory v=20200 size=1590 flags=0x0(none) hashes=44+3 location=embedded
Hash type=sha256 size=32
CandidateCDHash sha1=83a0328f9af971484b7e30c8d04e68a96dee72c1
CandidateCDHash sha256=cd6c72d17f00d2eed36078eece6a5b536c482772
Hash choices=sha1,sha256
Page size=4096
CDHash=cd6c72d17f00d2eed36078eece6a5b536c482772
Signature size=4693
Authority=Mac Developer: Michael Crawford (YU8CSARZFD)
Authority=Apple Worldwide Developer Relations Certification Authority
Authority=Apple Root CA
Signed Time=Nov 10, 2017, 1:10:07 PM
Info.plist entries=20
TeamIdentifier=444JK52Q93
Sealed Resources version=2 rules=13 files=2
Internal requirements count=1 size=184

Help me O Stackoverflow-Wan.  You're my only hope!


问:
Is it possible to execute two commands sequentially using commands.json?
I am using Mads Kristensen's Command Task Runner extension in Visual Studio 2017, to help when working with a colleague's JS work. I have set up a commands.json file, which we use to Lint and Build his work:

```<code>{
    "commands": {
        "chat-lint": {
            "fileName": "powershell.exe",
            "workingDirectory": "./Scripts/Chat",
            "arguments": "-Command yarn run lint:fix"
        },
        "chat-build": {
            "fileName": "powershell.exe",
            "workingDirectory": "./Scripts/Chat",
            "arguments": "-Command yarn run build"
        }
    },
    "-vs-binding": {
        "BeforeBuild": [],
        "AfterBuild": []
    }
}
</code>```

I would like to be able to execute two commands within one of the steps: that is, to execute yarn install before yarn run build, within the "chat-build" task. Is that possible, or do I really need to create a .ps1 file to do that? Would be great if I can execute two commands sequentially.

答: Of course, I could just put two Powershell commands there, separated by a semicolon: "arguments": "-Command yarn install; yarn run build"</p>

Body:
I am using Mads Kristensen's Command Task Runner extension in Visual Studio 2017, to help when working with a colleague's JS work. I have set up a commands.json file, which we use to Lint and Build his work:

{
    "commands": {
        "chat-lint": {
            "fileName": "powershell.exe",
            "workingDirectory": "./Scripts/Chat",
            "arguments": "-Command yarn run lint:fix"
        },
        "chat-build": {
            "fileName": "powershell.exe",
            "workingDirectory": "./Scripts/Chat",
            "arguments": "-Command yarn run build"
        }
    },
    "-vs-binding": {
        "BeforeBuild": [],
        "AfterBuild": []
    }
}

I would like to be able to execute two commands within one of the steps: that is, to execute yarn install before yarn run build, within the "chat-build" task. Is that possible, or do I really need to create a .ps1 file to do that? Would be great if I can execute two commands sequentially.


问:
SQL to select and swap id columns so parameter appears in left hand column
I'm looking to put together an SQL query for a matrix-like table to select a certain value (which can appear in either column) and then switch the id columns so that the search value always appears on the left hand side.

I'm having trouble explaining it coherently to search for an answer, but here's an example:

DB Table

```<code>id1 | id2 | value
----|-----|-------
 1  |  4  |  0.2
 2  |  1  |  0.3
 3  |  1  |  0.5
 2  |  3  |  0.1
</code>```

Desired output if I'm looking for value 1, note the last two columns switching position:

```<code>id1 | id2 | value
----|-----|-------
 1  |  4  |  0.2
 1  |  2  |  0.3
 1  |  3  |  0.5
</code>```

My current SQL is as follows:

```<code>SELECT (id1, id2, value) FROM db-table WHERE 1 in (id1, id2);
</code>```

Which gets the correct values, but without swapping. The result is:

```<code>id1 | id2 | value
----|-----|-------
 1  |  4  |  0.2
 2  |  1  |  0.3
 3  |  1  |  0.5
</code>```

I'm using sqlite3 but I can translate/fix domain specific issues if someone is able to point me in the right direction. Thanks!

答:
Does this do what you want,

```<code>Select IIF(id1<=id2,id1,id2) id1, iif(id1>id2,id1,id2) id2,value
From table
</code>```

If IIF not valid in SQLite try CASE statement.

```<code>Select case when id1<=id2 then id1 else id2 end id1,
       Case when id1>id2  then id1 else id2 end id2
From table
Where 1 in (id1,id2)
</code>```

Body:
I'm looking to put together an SQL query for a matrix-like table to select a certain value (which can appear in either column) and then switch the id columns so that the search value always appears on the left hand side.

I'm having trouble explaining it coherently to search for an answer, but here's an example:

DB Table

id1 | id2 | value
----|-----|-------
 1  |  4  |  0.2
 2  |  1  |  0.3
 3  |  1  |  0.5
 2  |  3  |  0.1

Desired output if I'm looking for value 1, note the last two columns switching position:

id1 | id2 | value
----|-----|-------
 1  |  4  |  0.2
 1  |  2  |  0.3
 1  |  3  |  0.5

My current SQL is as follows:

SELECT (id1, id2, value) FROM db-table WHERE 1 in (id1, id2);

Which gets the correct values, but without swapping. The result is:

id1 | id2 | value
----|-----|-------
 1  |  4  |  0.2
 2  |  1  |  0.3
 3  |  1  |  0.5

I'm using sqlite3 but I can translate/fix domain specific issues if someone is able to point me in the right direction. Thanks!

Body:
Does this do what you want,

Select IIF(id1<=id2,id1,id2) id1, iif(id1>id2,id1,id2) id2,value
From table

If IIF not valid in SQLite try CASE statement.

Select case when id1<=id2 then id1 else id2 end id1,
       Case when id1>id2  then id1 else id2 end id2
From table
Where 1 in (id1,id2)


答:
You mean something more like:</p>

```<code>SELECT * FROM
(
 SELECT
  CASE WHEN id1 < id2 THEN id1 ELSE id2 END as id1,
  CASE WHEN id1 < id2 THEN id2 ELSE id1 END as id2,
  value
 FROM db-table
) a
WHERE id1 = 1
ORDER BY value
</code>```

Title: SQL to select and swap id columns so parameter appears in left hand column

Body:
You mean something more like:

SELECT * FROM
(
 SELECT
  CASE WHEN id1 < id2 THEN id1 ELSE id2 END as id1,
  CASE WHEN id1 < id2 THEN id2 ELSE id1 END as id2,
  value
 FROM db-table
) a
WHERE id1 = 1
ORDER BY value


问:
Writing files to a user directory temporary folder using Java in Websphere 9
I have an application which has multipart file attachment module. In this, I have created a logic which writes the files to the local application server(Tomcat in my case) temp folder and gets deleted once it has been uploaded.

I used this logic for creating files,

```<code>File tmpFile = new File(System.getProperty("user.install.root") + File.separator + file.getOriginalFilename());
        file.transferTo(tmpFile);
</code>```

This works as expected in Tomcat, but deploying the same in Websphere 9 environment, throws the below exception,

[11/13/17 20:20:45:946 IST] 000000f2 SystemErr     R Caused by:
  java.io.FileNotFoundException: C:\Program
  Files\IBM\WebSphere\AppServer_1\profiles\AppSrv01\temp\WIN7VSNode04\server1\project name\project name.war\null\tmpfiles\uploaded file.extension
  (The system cannot find the path specified.)

What might be the issue here?

Thanks in advance.

答:
A variable is null when you're concatenating the path:

```<code>...\project name.war\null\tmpfiles\...
                     ^^^^
</code>```

Fix that and it should probably work.

Body:
I have an application which has multipart file attachment module. In this, I have created a logic which writes the files to the local application server(Tomcat in my case) temp folder and gets deleted once it has been uploaded.

I used this logic for creating files,

File tmpFile = new File(System.getProperty("user.install.root") + File.separator + file.getOriginalFilename());
        file.transferTo(tmpFile);

This works as expected in Tomcat, but deploying the same in Websphere 9 environment, throws the below exception,

[11/13/17 20:20:45:946 IST] 000000f2 SystemErr     R Caused by:
  java.io.FileNotFoundException: C:\Program
  Files\IBM\WebSphere\AppServer_1\profiles\AppSrv01\temp\WIN7VSNode04\server1\project name\project name.war\null\tmpfiles\uploaded file.extension
  (The system cannot find the path specified.)

What might be the issue here?

Thanks in advance.

Body:
A variable is null when you're concatenating the path:

...\project name.war\null\tmpfiles\...
                     ^^^^

Fix that and it should probably work.