text:
Q: how can i start activity from notification without changing layout i am woriking on location tracker app everything is working perfect, but i got stuck when i impliment forground service to this app. i am new in this field so might be no idea to do.
when ever i close my app forground service work but when i click in notification UserActivity will open but the switch button changed into checked mode and forground service will be continue working.

what i want is when i click on notification activity should start but with switch button should not change. only when i click stop then it should change with forground service should stop

here is my service class
class LocationServiceforground:Service() {
private val CHANEL_ID = "forgroundService"
companion object{
    fun startService(context: Context,message:String){
        val startIntent = Intent(context,LocationServiceforground::class.java)
        startIntent.putExtra("inputextra",message)
        ContextCompat.startForegroundService(context,startIntent)
    }
    fun stopService(context: Context){
        val stopIntent = Intent(context,LocationServiceforground::class.java)
        context.stopService(stopIntent)
    }
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
    val input = intent?.getStringExtra("inputExtra")
    createNotificationChannel()
    val notificationIntent = Intent(this,UserActivity::class.java)
    val pendingIntent = PendingIntent.getActivity(this,0,notificationIntent,0)
    val notification = NotificationCompat.Builder(this,CHANEL_ID)
        .setContentTitle("forgrround working")
        .setContentText(input)
        .setSmallIcon(R.drawable.locationtrack)
        .setContentIntent(pendingIntent)
        .build()
    startForeground(1,notification)
    return START_NOT_STICKY
}
override fun onBind(intent: Intent): IBinder? {
    return null
}
private fun createNotificationChannel(){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
        val serviceChannel = NotificationChannel(CHANEL_ID,"forground service
1",NotificationManager.IMPORTANCE_DEFAULT)
        val manager = getSystemService(NotificationManager::class.java)
        manager!!.createNotificationChannel(serviceChannel)
    }
}

}
this is my UserActivity wehre i called start stop service funtion
class UserActivity : AppCompatActivity() {
lateinit var fusedLocationProviderClient: FusedLocationProviderClient
lateinit var locationRequest: LocationRequest
lateinit var locationCallback: LocationCallback
var isLocationSharing = false
lateinit var database : DatabaseReference
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_user)
    val username = intent.getStringExtra("username")
    val logoutBtn = findViewById<Button>(R.id.logoutUser)
    val switchBtn = findViewById<SwitchCompat>(R.id.switchBtn)
    val locationGif = findViewById<ImageView>(R.id.locationGif)
    Glide.with(this).load(R.drawable.locatiogif).into(locationGif)
    val beingTrack = findViewById<TextView>(R.id.beingTrack)
    val location = findViewById<ImageView>(R.id.location)

    fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
    locationRequest = LocationRequest.create().apply {
        interval = 200
        fastestInterval = 100
        priority = LocationRequest.PRIORITY_HIGH_ACCURACY
    }

    locationCallback = object : LocationCallback(){
        override fun onLocationResult(locationResult: LocationResult) {
            locationResult?:return
            database = FirebaseDatabase.getInstance().reference

            if (isLocationSharing){
                for (location in locationResult.locations){
                    val currentLat = location.latitude
                    val currentLong = location.longitude
                    database.child("$username").child("latitude").setValue(currentLat)
                    database.child("$username").child("longtitude").setValue(currentLong)
                }
            }
        }
    }
    logoutBtn.setOnClickListener {
        isLocationSharing = false
        LocationServiceforground.stopService(this)
        startActivity(Intent(this,LoginActivity::class.java))
    }
    switchBtn.setOnClickListener {
        if (switchBtn.isChecked){
            isLocationSharing = true
            LocationServiceforground.startService(this,"service started")
            Toast.makeText(this@UserActivity, "location enabled", Toast.LENGTH_SHORT).show()
            location.visibility = View.GONE
            beingTrack.visibility = View.VISIBLE
            locationGif.visibility = View.VISIBLE
        }else{
            isLocationSharing = false
            LocationServiceforground.stopService(this)
            location.visibility = View.VISIBLE
            beingTrack.visibility = View.INVISIBLE
            locationGif.visibility = View.GONE
            Toast.makeText(this, "location off", Toast.LENGTH_SHORT).show()
        }
    }
}

override fun onResume() {
    super.onResume()
    if (checkLocationPermission()){
        fusedLocationProviderClient.requestLocationUpdates(locationRequest,locationCallback,
Looper.getMainLooper())
    }
}
private fun checkLocationPermission():Boolean{
    var state = false
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
       if
 (this.checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
    ==PackageManager.PERMISSION_GRANTED
           && this.checkSelfPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION)==
   PackageManager.PERMISSION_GRANTED){
           state = true
       }else{
           ActivityCompat.requestPermissions(this,
  arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION,
 android.Manifest.permission.ACCESS_COARSE
  _LOCATION),101)
       }
    }else state = true
    return state
}

}
i hope what i mean you got, guid me please thank you


text:
Q: Why won't my an element go inline with my navbar? I have been trying to create a navbar for a website that I am working on, and it has been working relatively smoothly, except for when I try to add an element to the top of the page with the navbar, but it will be styled to stick out from the navbar (with a different color and size of the box).

#navbar ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #CC0000;
}

#navbar li {
    float: left;
}

#navbar li a {
    display: block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

#signup-nav{
    display: inline;
    float: right;
    font-size: 18px;
}

#signup-nav a {
    text-decoration: none;
}

Home

About

Fundraising Tips

Contact

SIGN UP

A: There are a number of ways to do this, and this isn't necessarily the best way, but it is one way. You could use a flex container and the justify-content property to position the elements.
If you set justify-content to space-between, this will distribute items evenly. As mentioned in the documentation:

The items are evenly distributed within the alignment container along
the main axis. The spacing between each pair of adjacent items is the
same. The first item is flush with the main-start edge, and the last
item is flush with the main-end edge.

Example:

#navbar {
  display: flex;  /* added */
  justify-content: space-between;  /* added */
  background-color: #CC0000;  /* added */
}

#navbar ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  /* background-color: #CC0000; */ /* removed */
}

#navbar li {
  float: left;
}

#navbar li a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

#signup-nav {
  display: inline;
  font-size: 18px;
}

#signup-nav h1 {
  margin: 0;  /* added */
}

#signup-nav a {
  text-decoration: none;
}

Home

About

Fundraising Tips

Contact

SIGN UP

A: The ul is a block element so it will take up the full width by default. One of the easiest ways to do this is using flexbox. The advantage of flexbox is that it is very flexible (surprise!) so it is very common for tasks like this.

*

*If you make your navbar display:flex, this will automatically fit all its child elements into the block.

*If you make your ul flex: 1; this lets it grow and shrink with the window.

*We don't need to give the signup link any flex value, and it will take as muchspace as it needs.

. For example, you can control if each individual elements grows and/or shrink with the window, make one (or more) a fixed with and let the rest take up the remaining space etc.
FYI for your example, you also need to make some other styling changes such as:

*

*padding on your signup link

*margin on the h1

*add the background colour to the whole navbar, not just the ul

*remove the float:right (no need for it anymore)

see the working example below with all the changes:

#navbar {
  display: flex;
  vertical-align: middle;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #CC0000;
}

#navbar ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  flex: 1;
}

#navbar li {
  float: left;
}

#navbar li a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

#signup-nav {
  font-size: 18px;
}

#signup-nav a {
  text-decoration: none;
  padding: 3px 16px;
  display:inline-block;
  background:orange;
  border:2px solid #000;
}

#signup-nav h1 {
  margin: 0;
}

Home

About

Fundraising Tips

Contact

SIGN UP

redpajama_set_name: RedPajamaStackExchange


text:
Q: Desktop sounds on smartphone I'm wondering if it's possible to play music files on my desktop but send the audio not to my desktop speakers but (i.e. using BlueTooth) to my smartphone's speaker?
That way I could just play all my music on my desktop and walk around with my phone and headset in the house when doing all kinds of stuff. ( mostly cleaning =/ )
Additional info:
--
OS: Ubuntu and Windows 7
Phone: HTC Touch HD

A: Only if your smartphone provided audio playback services (like a headset does), and as smartphones are devices that you connect headsets to, and not connect to other things as headsets I can't see any right minded smartphone manufacturer providing that facility. (It'd be only used by one person in a million, and not worth investing the time & money in implementing it).


text:
Q: download success but video don't shows in IOS cordova while using cordova plugin file transfer, download file successfully, it didn't shows anywhere, code added below:
var onGetDirectorySuccess = function(fileEntry) {
    downloadpostnow(fileEntry, 'http://50.63.14.130/Images/OrderProof/Plugd7a09191-7cdd-4f21-babd-041e3f914ebb.MOV');
}

var onGetDirectoryFail = function(error) {
    showError("There is an error while processing your download.",0);
    return false;
}

var onRequestFileSystemSuccess = function(fileSystem) {
    var entry=fileSystem.root;
    entry.getDirectory("plug", {create: true, exclusive: false}, onGetDirectorySuccess, onGetDirectoryFail);
}

window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onRequestFileSystemSuccess, null);

function downloadpostnow(fileEntry, uri){
var fileTransfer = new FileTransfer();
var fileURL = fileEntry.toURL();
var uri = encodeURI(uri);
var uriname = uri.split("/");
uriname = uriname[uriname.length-1];
fileTransfer.download(
    uri,
    fileURL+uriname,
    function (entry) {
        alert(JSON.stringify(entry));
        //showError("Download Completed.",1);
        fileTransfer.abort();
    },
    function (error) {
        fileTransfer.abort();
        //showError("There is an error while downloading your post.",0);
        return false;
    },
    true,
    {/**/}
);
}

using this function, file download complete, it wouldn't show in IOS

A: If you want to show downloaded video .
Here is what I do:

*

*(once!) Make sure all hidden files are visible on your Mac:
In terminal window run:
defaults write com.apple.Finder AppleShowAllFiles YES

*While in Xcode, open Organizer -> Devices, find your iPhone and from their find your application in Applications folder.

*At the bottom click Download and download the application to your desktop (anywhere)

*Open Finder, navigate to the downloaded file, right click on it and select Show Package Contents. The view will change to standard finder view with open files in that app. (Follow url file path)

*Go to the Documents folder, find your *.MOV file, right click on it and choose Open With -> Other.


text:
Q: Asp.net Boilerplate - There is no argument given that corresponds to the required formal parameter
Used ASP.NET boilerplate to create Multi Page Web Application
(includes login, register, user, role and tenant management pages
 https://aspnetboilerplate.com/Templates)
Getting below mention error while building the project. Kindly point me a direction to sort the mention issue.
Thank-you.
Error -
Severity    Code    Description Project File    Line    Suppression State
Error   CS7036  There is no argument given that corresponds to the required formal parameter 'organizationUnitRepository' of 'AbpRoleManager.AbpRoleManager(AbpRoleStore, IEnumerable>, ILookupNormalizer, IdentityErrorDescriber, ILogger>, IPermissionManager, ICacheManager, IUnitOfWorkManager, IRoleManagementConfig, IRepository, IRepository)'   test.Core   C:\test\4.6.0\aspnet-core\src\test.Core\Authorization\Roles\RoleManager.cs  25  Active

A: Easily fixed - just add the required params yourself.
public class RoleManager : AbpRoleManager<Role, User>
{
    public RoleManager(
        RoleStore store,
        IEnumerable<IRoleValidator<Role>> roleValidators,
        ILookupNormalizer keyNormalizer,
        IdentityErrorDescriber errors,
        ILogger<AbpRoleManager<Role, User>> logger,
        IPermissionManager permissionManager,
        ICacheManager cacheManager,
        IUnitOfWorkManager unitOfWorkManager,
        IRoleManagementConfig roleManagementConfig,
        IRepository<OrganizationUnit, long> organizationUnitRepository,
        IRepository<OrganizationUnitRole, long> organizationUntiRoleRepository)
        : base(
              store,
              roleValidators,
              keyNormalizer,
              errors, logger,
              permissionManager,
              cacheManager,
              unitOfWorkManager,
              roleManagementConfig,
              organizationUnitRepository,
              organizationUntiRoleRepository)
    {
    }
}

A: Looks like if you are trying to model your RoleManager after the one that designed to work with Abp your parameters don't match the ones that are required for the base class.
This link relates to the Sample they provide.
https://github.com/aspnetboilerplate/aspnetboilerplate/blob/dev/test/Abp.Zero.SampleApp/Roles/RoleManager.cs
This link refers to the implementation of the AbpRoleManager class itself.
https://github.com/aspnetboilerplate/aspnetboilerplate/blob/dev/src/Abp.ZeroCore/Authorization/Roles/AbpRoleManager.cs


text:
Q: Magento 2 - Header: Logo, Nav, and Mini Cart on one line I am using Magento 2.0 with a copy of the blank theme.
I am trying to get the logo, nav, and mini cart on one line but I can't figure it out.
How would I do this with the blank Magento theme?

A: To modify the HTML you need to move the navigation to the header.
For example:
<move element="catalog.topnav" destination="header-wrapper" after="logo"/>

But you will also need to do some styling to make it all work nicely together.

A: Solution:
Add the following to default.xml
<move element="header.panel" destination="header.panel.wrapper"/>
<move element="logo" destination="header.panel" before="catalog.topnav"/>
<move element="catalog.topnav" destination="header.panel" after="logo"/>
<move element="top.search" destination="header.panel" after="catalog.topnav"/>
<move element="top.links" destination="header.panel" before="minicart"/>
<move element="minicart" destination="header.panel" after="top.links"/>

Add the following in a custom CSS file:
.page-header {
    margin-top: 0px;
}
nav.navigation {
    max-width: 350px;
    background: #FFF;
    float: left;
}
.header.panel > .header.links {
    float: right !important;
}
div.minicart-wrapper {
    float: right !important;
}
div.block.block-search {
    float: right !important;
}

A: To get the correct order in the HTML source:
<move element="logo" destination="header.panel" before="-"/>
<move element="catalog.topnav" destination="header.panel" after="logo"/>
<move element="top.search" destination="header.panel" after="catalog.topnav"/>
<move element="top.links" destination="header.panel" after="top.search"/>
<move element="minicart" destination="header.panel" after="-"/>

The key here is in the two elements at opposite ends. They need to be anchored there using the dash.
It's also more transparent to not mix before and after attributes for the elements following the logo, but if you want you can do so.
The answer above results in this order:

*

*top.links

*minicart

*logo

*catalog.topnav

*top.search

This is because:

*

*top.links has to be before minicart and minicart after top.links

*logo has to be before catalog.topnav and catalog.topnav has to be after logo

*top.search has to be after catalog.topnav

The conditions are all met in the order displayed above and the logo block ends up after the minicart purely because of processing order.

A: Override the default.xml file in your custom theme's Magento_Theme/layout directory.
Move the navigation menu to header-wrapper:
<move element="navigation.sections" destination="header-wrapper" as="navigation_section" after="logo"/>


text:
Q: C++ pick which implementation of virtual base class to use based on runtime value I have a C++ pure virtual base class/ interface with several implementations which are defined in different places in the code, and other implementations may be added later. I need a way to register the available implementations, read in (from a configuration file, user input, etc) which implementation of the interface to use, and then construct an instance of that implementation.
How can I do this in a general way (ie, table driven, not with a switch/ case statement that lists each one of implementations explicitly)? I'm having trouble figuring how to go from a runtime value indicating the type to a compile time type that I can instantiate.
Does boost have anything like this?

A: The standard approach involves a creational pattern called factory, which instantiates a concrete type based on a user-supplied identifier.
If you're using Boost already, have a look at Boost.Functional/Factory, but it's not very difficult to build a table-based dispatching mechanism yourself. This is how you use the Boost version with run-time polymorphism:
struct abstract
{
    virtual ~abstract() = default;
    virtual void f() = 0;
};

struct concrete1 : abstract
{
    virutal void f() override;
};

struct concrete2 : abstract
{
    virutal void f() override;
};

typedef boost::function<abstract*()>  abstract_factory;

int main()
{
    // Here, each factory refers to a function, although sometimes
    // people use the term factory to mean the dispatch table itself.
    std::map<std::string, abstract_factory> factories;
    factories["foo"] = boost::factory<concrete1*>();
    factories["bar"] = boost::factory<concrete2*>();

    // Create a new concrete object.
    auto foo = factories["foo"]();

    // vtable dispatch "concrete1".
    foo->f();

    ...
}


text:
Q: Запуск проекта под администратором Добрый день! как я могу запустить свой проект на другом компьютере в одинаковом со мной домене с моими логином и паролем. Суть проблемы: написал программку которая обрабатывает csv файл в екселевскую табличку. На компьютерах, на которых работают пользователи с админскими правами все работает хорошо, но на компьютере с минимальными правами программа не работает. Обработка идет через npoi библиотеку, и я так понимаю что программе не хватает прав на создание файла и запуск процесса.
через манифест не подходит, т.к. у пользователя в теории нет пароля от админской учетки.
Listing:
https://gist.github.com/Rdk174/a9effd701735867d543379584e86a008

A: создаем bat файл, в котором пишем:
runas /user:domain\admin /savecred c:\windows\notepad.exe

Вместо admin - имя администратора на компьютере.
Вместо c:\windows\notepad.exe - путь до нужной программы.
При первом запуске спросится имя и пароль указанной учетной записи. Вводим, запускается программа. В следующий раз имя и пароль уже не спрашиваются (сохраняются из-за параметра savecred).


text:
Q: Setting the value for 'android: layout_below' property to a resource id from a different layout xml file I have a blueprint which looks as thus:
I have the tablayout widget specified in xml like this:
<android.support.design.widget.TabLayout
    android:id="@+id/tabLayout"
    style="@style/AppTabLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:background="@color/tabBg"
    android:minHeight="?attr/actionBarSize"
    app:tabTextColor="@color/grey"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

I set it up with a ViewPager scrolling to swipe views for each tab. Now in one of the views - Tab 3, I need to arrange my components below the @id/tabLayout
This is the content of tab3.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/secondtext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tabLayout"
        android:background="@android:color/white"
        android:text="second"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/thirdtext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/secondtext"
        android:background="@android:color/white"
        android:text="third"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

Both the second and third textviews are displayed behind the tabLayout, they are covered/hidden by the tabLayout. How do i specify the textviews to display right under the tabLayout so the text is visible?

A: Define an id to RelativeLayout in tab3.xml and use it.

A: A RelativeLayout, like any other layout, is only responsible for laying out it's direct children. Therefore, the android:layout_below and similar attributes, can only work for two views within the same RelativeLayout parent.
In this case, you'd have to add it to the ViewPager. Then the TextViews can be just at the top of their container, as that is now below the TabBar.
If this is no good for your other tabs. You can do one of:
- Have the TabBar be a fixed height and set that as margin to the textviews
- Query the height of TabBar at runtime an apply it as padding or margin in tab3.

A: Use linear layout with vertical orientation .. It will work :)


text:
Q: trim the decimal value with only numbers I have few fields in my tables with V1.5, 1.6, V1.6.7. I want to remove all the characters and retain only numbers in the table.

*

*V1.5 should change to 1.5

*V1.6.7 should change to 1.6.7

*1.6 should be as it as.

A: To remove everything that is not a digit or dot, you can use regexp_replace():
regexp_replace(the_column, '[^0-9.]', '', 'g')

e.g.
with data (version) as (
  values
    ('V1.5'),
    ('V1.6.7'),
    ('1.2.3'),
    ('3.4.5-alpha')
)
select version, regexp_replace(version, '[^0-9.]', '', 'g') as clean_version
from data;

returns:
version     | clean_version
------------+--------------
V1.5        | 1.5
V1.6.7      | 1.6.7
1.2.3       | 1.2.3
3.4.5-alpha | 3.4.5

To change the data in your table, use an UPDATE statement:
update the_table
   set the_column = regexp_replace(the_column, '[^0-9.]', '', 'g')
where the_column <> regexp_replace(the_column, '[^0-9.]', '', 'g');

The where clause prevents updates that don't change anything.
Of course, you need to replace the_column with your real column name that you want to change.


text:
Q: Prevent overwriting of blocks with same name in Go html/template I'm having difficulty in rendering the correct content using templates in Go.
I have a base template (base.tmpl) and 2 child templates (a.tmpl and b.tmpl).
// base.tmpl
{{ define "base" }}
  {{ template "header" . }}
  {{ template "content" . }}
  {{ template "footer" . }}
{{ end }}

// a.tmpl
{{ template "base" . }}
{{ define "content" }}
  This is a.tmpl
{{ end }}

// b.tmpl
{{ template "base" . }}
{{ define "content" }}
  This is b.tmpl
{{ end }}

When executing a.tmpl the contents of the content block in b.tmpl are inserted.
For example, rendering a.tmpl results in a page displaying:
This is b.tmpl

I am parsing the templates (see below) and returning and assigning the result to a variable x so I may call x.ExecuteTemplate(w, "a.tmpl", nil)
func parseTemplates() *template.Template {
    templ := template.New("")
    err := filepath.Walk("./templates", func(path string, info os.FileInfo, err error) error {
        if strings.Contains(path, ".tmpl") {
            _, err = templ.ParseFiles(path)
            if err != nil {
                log.Println(err)
            }
        }

        return err
    })

    if err != nil {
        panic(err)
    }

    return templ
}

I am assuming this is because when parsing the templates, Go keeps b.tmpl's content block definition as the most recent.
I'm wondering if there's a way where I can parse all templates at run time and simply call the template I want to execute without having to re-parse the header, content, footer etc. each time I execute the page.

A: Parse the templates for a and b separately.
atmpl, err := template.ParseFiles("base.tmpl", "a.tmpl")
if err != nil { /* handle error */ }

btmpl, err := template.ParseFiles("base.tmpl", "b.tmpl")
if err != nil { /* handle error */ }


text:
Q: Searching through JSON records with Rails Rails 7
MySQL 8

I have an Author Model, and one of the fields is personal_info, the migration for it was:
class CreateAuthors < ActiveRecord::Migration[7.0]
  def change
    create_table :authors do |t|
      t.json :personal_info
      ....

The format of the JSON that gets stored in the personal_info field is:
{
  'email':'someemail',
  'address':{
    'street':'Elm Street',
    'city':'some city',
    'state':'CA'
    'zip':'94001'
  }
}

What I would like to do, is query for all authors who live in California. I have not seen any examples where a record with nested JSON structures are used.
I tried the following:
authors = Author.where("personal_info->'$.address'->'$.state' = :state", state: 'CA')
authors = Author.where("personal_info->'$.address->$.state' = :state", state: 'CA')
authors = Author.where("personal_info->'address'->>'state' = ?", "CA")

But I'm getting an error:
(Object doesn't support #inspect)

Any ideas?


text:
Q: Results on Maximal subgroups of $\text{GL}(n,q)$ Consider, $\text{GL}(n,q)$, which is the group of $n\times n$ invertible matrices with entries from the finite fields $\mathbb{F}_q$, with $q$ elements.(We know $q$ is a prime-power). My question is really a broad one. What is known about maximal subgroups of $\text{GL}(n,q)$. By maximal subgroup, I mean the following: For a group $G$, a subgroup $H\leq G$ is maximal if there doesn't exist any proper subgroup of $G$ which properly contains $H$.
Is there any method by which one can construct maximal subgroups in $\text{GL}(n,q)$. The group $\text{SL}(n,q)$ is the subgroup of matrices with determinant 1. What are all maximal subgroups of $\text{GL}(n,q)$ containing $\text{SL}(n,q)$, and so on. Therefore, What I basically  want to know is what all is known, or if there is any very well-known result in this topic.
P.S- I searched a lot in the internet, but don't seem to find much on this or maybe there is no clear answer, I don't know. Any references will be highly appreciated.
Thanks in advance.

A: The factor group ${\text GL}(n,q)/{\text SL}(n,q)$ is the cyclic group $\Bbb{F}_q^*$ of order $q-1$ because the subgroup ${\text SL} (n,q)$ is the kernel of the $\text{det}$ homomorphism.
So maximal subgroups  of ${\text GL}(n,q)$ containing $\text{SL}(n,q)$ are in one-to-one correspondence with the maximal subgroups of that cyclic group and therefore with the prime divisors of $q-1$.
Update 1. There are maximal subgroups which are not above $SL(n, q)$. For example, any maximal subgroup containing all upper triangular nonsingular matrices.
Update 2. See also this text, sections 5-10 for a description of maximal subgroups of ${\text GL}(n,q)$.


text:
Q: Previewing/Updating some Pages causes "The requested URL was rejected" Error The wordpress site is suddenly having a problem where on some (not all) of the pages, when you click preview page or update changes it gives an error message:
"The requested URL was rejected. If you think this is an error, please contact the webmaster.
Your support ID is: 9641638102880218190"
This can be circumvented by entering the preview url directly into the browser or clicking "open in new tab" when you click the preview button. However you cannot right click and do this on the "Update" button so it does not solve my problem.
One thing I noticed is that these pages all tend to have 1 or more categories assigned to the page. Other than that I can't think of similarities between the pages it's occuring on.
So far I think it's caused by the PHP code... but this is my first wordpress site and I'm lost. Lots of googling showed that this has happened to others but there isn't a clear solution.
I've disabled some but not all my plugins since I do not want to lose data.
please teach me how to debug this problem

A: It turns our this error is caused by security software on the server. Meaning that a software that makes sure the hosting providers servers are safe is denying these requests.
You cannot fix this because it's on the hosting providers server, you have to call or email them and let them know this is happening.
I did they and they looked into it and told me there was a bug that was causing this error. They fixed it on their end and told me things should be fine now and they were.
So call them, you cannot fix it without your hosting provider's help.


text:
Q: Click on fcm notification to go to a particular activity with intent data I have created a chat application using Firebase.
How to go to a particular chat activity, when clicked on a notification with message data?

A: In your manifest file, you should declare the below intent filter for the activity that needs to be launched when an FCM notification is clicked :
<intent-filter>
       <action android:name="NEW_MESSAGE" />

       <category android:name="android.intent.category.DEFAULT" />
</intent-filter>

And in your activity that launches when them notification is clicked, you can receive the data from the notification using bundle as below:
Bundle extras = notificationIntent.getExtras();

A: There are two types of FCM messages: Notification and Data.
The simple messages sent from the Firebase console are of type Notification. This means that when receiving the message in the background you can't control which Activity to open. BUT when receiving the message in the foreground OR sending a Data message (sent from the Cloud Functions or your app server), you can catch the message on onMessageReceived and create your own notification.

link to Firebase about receiving messages : Receive Messages in an Android App
link to Firebase about FCM messages : About FCM Messages
link about starting an Activity from a Notification : Start an Activity from a Notification


text:
Q: WPF: The custom style is not working after changed the button background color After I clicked the button, the button's background color will always red. I hope the "isMouseOver" trigger still working.
Anyone can help me to solve this problem?
<Style TargetType="{x:Type Button}">
            <Setter Property="OverridesDefaultStyle" Value="True"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <Grid Background="{TemplateBinding Background}">
                            <ContentPresenter Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center" />
                        </Grid>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsMouseOver" Value="True">
                                <Setter Property="Background" Value="LightBlue"></Setter>
                            </Trigger>
                            <Trigger Property="IsMouseOver" Value="False">
                                <Setter Property="Background" Value="LightGray"></Setter>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

private void onClick(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;
            button.Background = Brushes.Red;
        }

A: Possible duplicate of Trigger won't change Background
Basically you have style values declared for background in your triggers but then you set a local value for background in your button's click handler. Local values will take precedence over style values.
One option is to change background for IsPressed trigger instead of doing it from your click handler:
<Trigger Property="IsPressed" Value="True">
    <Setter Property="Background" Value="Red"/>
</Trigger>

Technically you could do this a few other ways but that is likely the cleanest.


text:
Q: This question relates to "What" and "Whose" [Basically I want to know the names of all the teachers of X college so that I can choose what teacher would be perfect for me]
What teacher lectures are you providing?
Or
Whose teacher lectures are you providing?

A: Neither one of your sentences is quite correct. It is not common, and sounds odd, to refer to lectures as "teacher lectures."
You could say, "Whose lectures are you providing?" This is correct because "Whose" already indicates a possessive.
If you don't use "whose," you would have to indicate the possessive. You could say "What (or Which) teacher's lectures are you providing?" Note that I have added the possessive 's to "teacher."


text:
Q: How does fs.writeFileSync & fs.writeFile work for two processes writing same file concurrently Let's assume there's a file temp.json at version 1.
At time 0 process 1 reads version 1
At time 1 process 2 reads version 1
At time 3 process 2 fs.writeFileSync to version 2
At time 3 process 1 fs.writeFileSync to version 3
How does nodejs operates over these two conflicting writes?
To add to this all I tried using fs.writeFile concurrently from two processes and the end result of temp.json was mix of content from two processes. Help me understand this as well


text:
Q: How to solve a large set of multivariate compound linear inequality in Python? I'm working on trying to implement Dinur-Nissim algorithm and am stuck at how to solve the set of linear inequalities with multiple unknowns and a large number of equations along with constraints.
Example:
0.2<=c4<=0.66
0.66<=c3<=1.56
0.96<=c3+c4<=2.26
Constraints:
0<=ci<=1
and many other equations with the no of unknowns going till cn where n is the size of the database, so I need a solution which works for a large number of equations.
I've tried to look for some libraries but most of them solve Maximization or Minimization problems so am not sure if its possible to convert these equations to one of those problems.

A: Simple approach using scipy's linprog (Linear Programming; LP is probably the most specific/powerful optimization-problem-type usable here!):
Code
from scipy.optimize import linprog

c = [0, 0, 0, 0]                            # empty objective
A = [[0, 0, 0, -1], [0, 0, 0, 1],
     [0, 0, -1, 0], [0, 0, 1, 0],
     [0, 0, -1, -1], [0, 0, 1, 1]]
b = [-0.2, 0.66, -0.66, 1.56, -0.96, 2.26]

result = linprog(c, A, b, bounds=(0,1))
print(result)

Output
fun: -0.0
message: 'Optimization terminated successfully.'
nit: 3
slack: array([ 0.1 ,  0.9 ,  1.3 ,  1.  ,  1.  ,  0.34,  0.7 ,  0.  ,  0.  ,  0.  ])
status: 0
success: True
  x: array([ 0.  ,  0.  ,  0.66,  0.3 ])

The above is a basic usage of linprog:

*

*we don't need any objective and therefore keep all factors zero (see c)

*we need the form Ax <= b for our inequalities:

*

*0.96 <= c3+c4 <=> c3+c4 >= 0.96 <=> -c3 -c4 <= 0.96
Keep in mind, that linprog is not as stable as commercial solvers. You could solve this problem also with SLSQP.
The above, in combination with your description:

basically the last step involves making a decision based on the value of c, if ci>1/2 then xi=1 else xi=0, so I just need to find the region of c's which satisfy the inequalities

makes not much sense in the general-case, as the optimization, as described in your post, returns a feasible value and without additional modelling, the solver does not care about your threshold of 0.5. So you should check your theory again (i did not check out your algorithm to implement; maybe the nature of the problem allows for this approach).


text:
Q: VBScript to run a php script from task scheduler but minimized Yesterday I asked you this question;
Running a batch file from windows task scheduler, but hidden or minimized
The answer I selected was one suggesting I'd make a VBScript and use that, to run the original .bat file that executed the php script.
However, a comment on that suggestion, suggested to remove the .bat entirely and just run the php from the VBScript.
I decided that, that is what I wanted to do.
See here what I tried:
(This is written in followers.vbs)
CreateObject("Wscript.Shell").Run "C:\xampp\php\php.exe -f 'C:\xampp\htdocs\Test\FollowTrackerV2\followers.php'", 0, True

What I have entered in task scheduler:
Program / script: C:\xampp\htdocs\Test\FollowTrackerV2\followers.vbs
Parameters: <blank>
Start in: C:\xampp\htdocs\Test\FollowTrackerV2
When I execute the .vbs through task scheduler, it does not do anything visually and I am assuming it is not doing anything non-visible either since the php script is not being executed. (the php sends me an email, and I am not receiving any)
The php script works fine executing it from a .bat file so it must be in my VBScript.
If anyone could take a quick look and see if I am doing anything wrong, that'd be great.
Thanks!

A: Main change here is the file path without quotes.
Set WshShell = WScript.CreateObject("WScript.Shell")

WshShell.Run "C:\xampp\php\php.exe -f C:\xampp\htdocs\Test\FollowTrackerV2\followers.php", 0

A: It sounds like a permission issue with the scheduled task, try setting the scheduled task to run as an administrator user.


text:
Q: Is GCM (now FCM) free for any limit? I would like to know if Firebase Cloud Messaging is free or not for unlimited users?

A: In addition to the answer from AL.
From the Pricing page Faqs:

Which products are paid? Which are free?
Firebase's paid infrastructure products are the Realtime Database,
Firebase Storage, Hosting, and Test Lab. We offer a free tier for all
of these products except Test Lab.
Firebase also has many free products: Analytics, App Indexing,
Authentication, Dynamic Links, Cloud Messaging, Notifications,
Invites, Crash Reporting, &, Remote Config. You can use an unlimited
amount of these in all plans, including our free Spark Plan.

So, it's free. The limit is not mentioned anywhere in the docs, however there's a limit on the Firebase realtime database, as mentioned in the FAQs:

Firebase imposes hard limits on the number of connections to your app's database at the same time. These limits are in place to protect both Firebase and our users from abuse.
The free plan limit is 100, and cannot be raised. The Flame and Blaze
Plans have an initial limit of 10,000 simultaneous database
connections. This is to prevent abuse and can be raised by contacting
Firebase support with 24 hours notice.
This limit isn't the same as the total number of users of your app,
because your users don't all connect at once. We encourage you to
monitor your peak simultaneous database connections and upgrade if
needed.
We're working hard to remove the initial 10,000 simultaneous
connection cap on the Flame and Blaze plans.

So if you are using the Firebase Database to save your User's data and want to send a lot of Push Notifications to your user's devices using the FCM registration token stored in the Firebase Database, you might hit the limit in the free Spark plan, however it's really tough to hit the 10k limit.

A: Firebase Cloud Messaging (FCM) Connection Server (CCS) sits between the device and the app server. The following limits apply

*

*From the documentation here, it seems FCM does impose a limit of 1000 connections in parallel.

For each sender ID, FCM allows 1000 connections in parallel.

Sender Id is a unique numerical value created when you create your Firebase project, available in the Cloud Messaging tab of the Firebase console Settings pane. The sender ID is used to identify each app server that can send messages to the client app.
Note: Please correct me if this limit is not about the max connections from an app server to CCS

*Secondly, You should also read about Flow Control if you are using the XMPP connection server protocol (which has to be used if using device-to-cloud messaging). There should not be more than 100 unacknowledged messages towards CCS at any single point of time.

If the pending message count reaches 100, the app server should stop sending new messages and wait for CCS to acknowledge some of the existing pending messages

A: From the Firebase Cloud Messaging Docs:

Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably deliver messages at no cost.

A: You can refer to the official Firebase Pricings page. From there you will be able to see the types of projects that are available: SPARK, FLAME, BLAZE, to which all of them have FCM (along with Analytics, App Indexing, Authentication, Dynamic Links, Invites, Notifications, Crash Reporting & Remote Config) included for free.


text:
Q: Making an expensive call to an API and updating a loading bar on the UI with the current status of the call I am making a call to an API that could take a while to process. I want to show the user a loading bar on the UI.
I put some thought into how I would go about doing this, but I am not sure if it is the correct approach.

*

*User makes expensive call to the API.

*API returns an OK that it started processing. Maybe it will also return a threadId or something.

*I would then make subsequent calls using that threadId to figure out where it is at in the process to update the loading bar.

I am using an ASP.NET Webforms application that use HttpClient in the code-behind to make calls to an ASP.NET Core Web API. I am not making these calls directly through JavaScript.
If I were to use SignalR would I be adding SignalR to my webforms application or to the WebAPI?


text:
Q: Numerical complexity of different quantum chemistry approaches For the introductory course for the students I am trying to collect the brief overview of different quantum chemistry methods and their numerical complexity. The second point is surprisingly poorly explained in all textbooks I was able to find. In the best case, it is a small note like

The most computationally expensive step in the Hartree–Fock procedure is the  formation of the two-electron part, $G$, of the Fock matrix; the computation of G requires $O(n^4)$ steps, where $n$ is the number of basis functions (with integral screening this cost asymptotically approaches $O(n^2)$)

[source is "Parallel computing in quantum chemistry" by C.L. Janssen, 2008], but there are no estimates for all methods discussed in the book and I have problems to find this kind of information elsewhere.
Probably, there exists a more extended discussion of this point with more details (which part of the algorithm limits the complexity, what can be done to improve the scalability, etc.)?

A: Because different computational methods require somewhat different expertise, it seems to me that, for each and every method, complexity/computational cost is commented separately. Therefore the exact details needs to be investigated maybe from books dedicated to a particular computational method. But of course there are some experts in the field who collectively reported these data.
The first and the most recent paper I found has a paragraph where data for different methods are presented without any discussion.

... the scaling of other popular Quantum Chemistry methods, which ranges from $O(N^4)$ for Hartree Fock (HF) to $O(N^5)$ for MP2, $O(N^6)$ for MP3, and $O(N^7)$ for MP4, CISD(T) and CCSD(T), it still makes large scale simulations prohibitive.

There is another paper I found which is relatively old (1996) but the discussion is more thorough and the data is given on a table very nicely.

A: For your basic single-reference quantum chemistry ground state methods:
HF: ${\cal O}(N^4)$
DFT: ${\cal O}(N^3)$ or ${\cal O}(N^4)$ with HF-exchange
MP2: ${\cal O}(N^5)$
CCSD: ${\cal O}(N^6)$
and excited state methods:
TDHF: ${\cal O}(N^4)$
TDDFT: ${\cal O}(N^3)$ or ${\cal O}(N^4)$
$\mathrm{G}_0\mathrm{W}_0$: ${\cal O}(N^4)$
GW: ${\cal O}(N^5)$
EOMCCSD: ${\cal O}(N^6)$
It's probably more useful to know why these methods come with the aforementioned cost scalings. It's all about identifying the rate-limiting step in the calculation, which is typically a type of tensor contraction. Let's take Hartree-Fock for example. The most costly step comes from the construction of the effective one-body interaction, which for a conventional closed-shell calculation, looks like this
$$f_{\mu \nu} = 2h_{\mu \nu} + g_{\mu \nu}$$
$$g_{\mu \nu} =  \sum_{\rho \sigma} \langle \mu \rho | \nu \sigma \rangle P_{\rho \sigma} -
\frac{1}{2}\langle \mu \rho | \sigma \nu \rangle P_{\rho \sigma}$$
We can identify the first term in $g_{\mu\nu}$ as the Coulomb interaction and the second term as exchange. If one were to unravel the above tensor contraction to execute using some nested do/for loops, one would need something like this (using Fortran 90 as an example syntax):
do p = 1,N
    do q = 1,N
       K = 0.0
       J = 0.0
       do r = 1,N
          do s = 1,N
             K = K + V(p,q,r,s) * P(q,s)
             J = J + V(p,q,s,r) * P(q,s)
          end do
        end do
        g(p,q) = 2*K + J
    end do
end do

Clearly, the above loop has a computational expense that scales as $\mathcal{O}(N^4)$ because we have 4 nested loops, each running from $1$ to $N$. Another example we can do is CCSD. If you derive the CCSD equations (in spinorbital form for simplicity), one finds that the most expensive term is the so-called ladder diagram contribution $
\frac{1}{4}\sum_{mnef} v_{mn}^{ef} t_{ef}^{ij} t_{ab}^{mn}$ where $v_{pq}^{rs}$ are the antisymmetrized electron repulsion integrals and $t_{ab}^{ij}$ are the 2-body cluster amplitudes. If we were to repeat the above procedure of naively unravelling into nested "do" loops, one find that the ladder diagram has a cost that scales as $\mathcal{O}(N^8)$. Why then is CCSD listed as $\mathcal{O}(N^6)$? The answer is that the tensor contraction can be broken up into two steps. If one first computes $\chi_{mn}^{ij} = \sum_{ef} v_{mn}^{ef} t_{ef}^{ij}$, this operation scales as $\mathcal{O}(N^6)$. Then, one computes $\sum_{mn} \chi_{mn}^{ij} t_{ab}^{mn}$ which also scales as $\mathcal{O}(N^6)$. Thus, you can compute the $\mathcal{O}(N^8)$ contraction at the cost of no more than multiple $\mathcal{O}(N^6)$ operations, hence CCSD scales as $\mathcal{O}(N^6)$! These types of time-saving factorizations are easily deduced by inspection of the diagrammatic form of these many-body equations (or, one can just look at the tensor equations directly, however, it's a bit harder that way). Optimal factorization is of utmost importance in any quantum chemistry code.
And you can also reduce the scaling of MP2, TDHF, and HF using density-fitting and Cholesky decompositions by an order of magnitude to ${\cal O}(N^4)$ and ${\cal O}(N^3)$, respectively. There are also density-fitting type speedups (called least-squares tensor hypercontraction, or LS-THC) that can be applied to coupled-cluster that reduce the scaling of CCSD to ${\cal O}(N^4)$ which is probably the best you can get. Certainly, every method can have its scaling reduced dramatically by introducing some kind of orbital localization because the steep scaling of quantum chemistry stems from the fact that even atoms far away from each other, say on opposite ends of a molecule, end up interacting because the standard MO basis used is delocalized. However, localization comes with a heavy cost of losing orthonormality, so it's generally tricky implement. Actually, a very promising class of methods are the rank-compression methods like Cholesky decomposition because you can very robustly reduce the time needed for rate-limiting tensor contractions while having a very controllable and systematic error - something most other "fast scaling" approaches do not have.

A: The following figure is showing some numerical complexity for different methods in electronic structure calculations.

For more details you can visit this link.
Here is an excellent website for computational chemistry.


text:
Q: Change the Layout Background using image color code in Android I am using the viewPager for Gallery and used "Depth Page Transformation" for animation i need to set the background according to the image. The background color should match with the image color meaning it should pick the background color from the image. Does any one know this..please tell me.

A: Loop through all the pixel's color data and average the color values, ignore anything that is a shade of grey or transparent. I believe that is what Microsoft does in Windows 7 based on a recent blog post.
See this blog post: http://blogs.msdn.com/b/oldnewthing/archive/2011/12/06/10244432.aspx
This link showing how Chrome picks the dominant color may also be helpful.   http://www.quora.com/Google-Chrome/How-does-Chrome-pick-the-color-for-the-stripes-on-the-Most-visited-page-thumbnails
Find this snippet for android
http://forums.makingmoneywithandroid.com/android-development/406-%5Bhow-%5D-get-average-color-drawable-bitmap.html


text:
Q: SimpleModal with scrollbar script I am using SimpleModal script. Also I want to display in it a special DIV tag with long text. This DIV need to have his own scrollbar.
Sample code: www.sildev.pl/basic/index.html
You can download this from here: www.sildev.pl/basic.zip
As You can see it's working standalone, but together it crushes. Why? Can anybody fix it to me?
Regards,
Piotr.
EDIT:
I made this changes, but still got problem with project. It is very strange for me. Can you look at this again?
Updated version: www.sildev.pl/basic/index.html
ZIP: www.sildev.pl/basic.zip
How to make this scroll works?

A: It is because you have display none for <div id="basic-modal-content">
if you change in basic.js this line (line 21):
$('#basic-modal-content').modal();

to
$('#demo4').modal();

it will work
updates:
changes line 14 in basic.css file:
---from: #basic-modal-content {display:none;}
---to  #basic-modal-content {visibility:hidden;}


text:
Q: How to create an 'instance of' -like query in JPA 2.0? Say we've got an abstract @Entity Animal, and several entity classes that extend Animal, including Dog, Cat, Monkey and Bat.
How can I filter the results based on the extending entity's class?
Example:
There are checkboxes where the user can select which entities to retrieve.
[ ] Dog
[X] Cat
[X] Monkey
[ ] Bat

Now I want to retrieve the entities with a (Named)Query defined in the Animal class. What kind of query parameters can I put into the query so that only the Cat and Monkey objects will be returned?

A: You can use the discrimnator column and value to only search for certain subtypes of a given type. By default the discriminator column's name is DTYPE in JPA,the type is String and the value is the name of the class. You can however override this by adding the class level annotation @DiscriminatorColumn(name="KIND", discriminatorType=DiscriminatorType.INTEGER) (for the discriminator column's name and type) and @DiscriminatorValue("1") (for the specific discrimiminator value for a certain class). You can then use this in the WHERE clause of yoru JPQL query to only fetch certain subtypes, like: WHERE DTYPE="Dog" OR DTYPE="Cat"

A: I'm not absolutely sure it's supported by JPA, but the way to do it in Hibernate, regardless of the inheritance strategy, and thus even if you don't have a discriminator (or didn't map it as a property) is to use the implicit class property :
String jpql = "select a from Animal a where a.class in (:classes)";
Query q = em.createQuery(jpql).setParameter("classes",
                                            Arrays.asList(Cat.class, Monkey.class));

EDIT :
I just found it's possible in JPA2 using the TYPE operator :
String jpql = "SELECT a FROM Animal a WHERE TYPE(a) IN :classes";
Query q = em.createQuery(jpql).setParameter("classes",
                                            Arrays.asList(Cat.class, Monkey.class));


text:
Q: Symfony forward form submission Hello I'm having the following problem, I tried to follow this question's answer on how to do a form over many pages. This question
I made the following controller for the first form
public function reportarSeguimientoAction(Request $request)
{
    $em = $this->getDoctrine()->getManager();

    $seguimiento = new Seguimiento();

    $form = $this->createForm(SeguimientoType::class, $seguimiento);
    $form->handleRequest($request);

    if($form->isSubmitted() && $form->isValid())
    {
        $seguimiento = $form->getData();

        if($seguimiento->getAsistencia() == 1)
        {
            $response = $this->forward('AppBundle:Counselor:seguimientoDos', array(
                    'seguimiento' => $seguimiento,
            ));
            return $response;
        }
        else
        {
            $em->persist($seguimiento);
            $em->flush();
            return $this->redirectToRoute('success');
        }
    }

return $this->render('default/crearSeguimiento.html.twig', array(
            'form' => $form->createView(),
    ));
}

This redirects me to the second part of the form in case that a field is filled, it does not change the url though.
    public function seguimientoDosAction(Request $request, $seguimiento)
{
    $form = $this->createForm(SeguimientoAsistioType::class, $seguimiento);
    $form->handleRequest($Request);

    if($form->isSubmitted() && $form->isValid())
    {
        $seguimiento = $form->getData();
        $em = $this->getDoctrine()->getManager();
        $em->persist($seguimiento);
        $em->flush();
        return $this->redirectToRoute('success');
    }

    return $this->render('default/crearSeguimiento.html.twig', array(
            'form' => $form->createView(),
    ));
}

The appearance of the page does change yet it doesn't submit when clicking the submit button in the second form it just renders the first part of the form, it marks the first one as submitted. I'm guessing it has to do with it not being a redirection but I can't seem to be able to redirect passing the $seguimiento variable which contains the first part of the form to submit.
Any solution to either passing the variable on a redirect or submitting the second form is really welcome.


text:
Q: Getting error in sqlite ios NULL cString'? I'm building an iOS app using Storyboards.I am facing an issue in my sqlite database i'm getting the field value here
NSLog(@"selfuserid: %@",selfuserid);

but my code goes again to the below code.
NSString * selfuserid =[NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 1)];

here is my code:
-(NSArray *) getRecords:(NSString*) filePath where:(NSString *)whereStmt
{
NSMutableArray * students =[[NSMutableArray alloc] init];
sqlite3* db = NULL;
sqlite3_stmt* stmt =NULL;
int rc=0;
rc = sqlite3_open_v2([filePath UTF8String], &db, SQLITE_OPEN_READONLY , NULL);
if (SQLITE_OK != rc)
{
    sqlite3_close(db);
    NSLog(@"Failed to open db connection");
}
else
{
    NSString  * query = @"SELECT * from students";
    if(whereStmt)
    {
        query = [query stringByAppendingFormat:@" WHERE %@",whereStmt];
    }
    rc =sqlite3_prepare_v2(db, [query UTF8String], -1, &stmt, NULL);
    if(rc == SQLITE_OK)
    {
        while (sqlite3_step(stmt) == SQLITE_ROW) //get each row in loop
        {
NString * selfuserid =[NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 1)];//here the code comes again
NSString * profilepic =[NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 2)];
NSString * username =[NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 3)];
NSString * selectedsports =[NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 4)];
     NSDictionary *student =[NSDictionary dictionaryWithObjectsAndKeys:selfuserid,@"selfuserid",profilepic,@"profilepic",username,@"username",selectedsports,@"selectedsports", nil];
[students addObject:student];
NSLog(@"selfuserid: %@",selfuserid);i'm getting selfuserid here but code goes again to the above stm
NSLog(@"pic: %@",profilepic);
}
NSLog(@"Done");
sqlite3_finalize(stmt);
}
else
{
NSLog(@"Failed to prepare statement with rc:%d",rc);
}
sqlite3_close(db);
}
return students;
}

I'm getting this exception:
 Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[NSString stringWithUTF8String:]: NULL cString'

    *** First throw call stack:
    (
    0   CoreFoundation                      0x000000010450ef35 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x00000001041a7bb7 objc_exception_throw + 45
    2   CoreFoundation                      0x000000010450ee6d +[NSException raise:format:] + 205
    3   Foundation                          0x0000000103d0c464 +[NSString stringWithUTF8String:] + 78
    4   Playo                               0x0000000101a038f9 -[Play getRecords:where:] + 617
    5   Playo                               0x0000000101a06697 -[Play tableView:didSelectRowAtIndexPath:] + 231
    6   UIKit                               0x0000000104c26393 -[UITableView _selectRowAtIndexPath:animated:scrollPosition:notifyDelegate:] + 1293
    7   UIKit                               0x0000000104c264d4 -[UITableView _userSelectRowAtPendingSelectionIndexPath:] + 219
    8   UIKit                               0x0000000104b61331 _applyBlockToCFArrayCopiedToStack + 314
    9   UIKit                               0x0000000104b611ab _afterCACommitHandler + 516
    10  CoreFoundation                      0x0000000104443dc7 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
    11  CoreFoundation                      0x0000000104443d20 __CFRunLoopDoObservers + 368
    12  CoreFoundation                      0x0000000104439b53 __CFRunLoopRun + 1123
    13  CoreFoundation                      0x0000000104439486 CFRunLoopRunSpecific + 470
    14  GraphicsServices                    0x00000001063299f0 GSEventRunModal + 161
    15  UIKit                               0x0000000104b3e420 UIApplicationMain + 1282
    16  Playo                               0x0000000101a34813 main + 115
    17  libdyld.dylib                       0x0000000105f47145 start + 1
   )
   libc++abi.dylib: terminating with uncaught exception of type NSException

A: stringWithFormat does not crash if value is null
 NSString* str=[NSString stringWithFormat:@"%s",(const char*)sqlite3_column_text(statement, 0)];

A: Check these lines:
NString * selfuserid =[NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 1)];//here the code comes again
NSString * profilepic =[NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 2)];
NSString * username =[NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 3)];
NSString * selectedsports =[NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 4)];

What happens here that one of the above field is return NULL string. As I guess database design for these fields constrains has property that allow to insert NULL data to these fields.
So you have to check that if any one of these field returns NULL string then appropriately store an empty string.
Do the following for this:
Create one function to validate NULL strings:
- (NSString *) validateNilString:(NSString *)strValue {

    NSString *returnString = @"";

    @try {
        if (!strValue)
            return returnString;

        if ([strValue isKindOfClass:[NSNull class]])
            return returnString;

        if ([strValue isEqualToString:@"<nil>"])
            return returnString;

        if ([strValue isEqualToString:@"<null>"])
            return returnString;

        if ([strValue isEqualToString:@"NULL"])
            return returnString;

        if ([strValue isEqualToString:@"nil"])
            return returnString;

        if ([strValue isEqualToString:@"(null)"])
            return returnString;

        return strValue;
    }
    @catch (NSException *exception) {
        NSLog(@"Exception :%@",exception);
        return returnString;
    }
}

Check every string using this function for not null value:
NSString * selfuserid = [self validateNilString:[NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 1)]];
//here the code comes again
NSString * profilepic = [self validateNilString:[NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 2)]];
NSString * username = [self validateNilString:[NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 3)]];
NSString * selectedsports = [self validateNilString:[NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 4)]];


text:
Q: angularjs checkbox Incorrect response in console I have two criteria:
1) Only allow one of two boxes selected at one time.
2) Capture the name of the box that is selected.
However, when I print out the list of checkbox objects they are correct, but when I check in the console they are not correct. For example,
HTML:

 <input type="checkbox" value="{{treatment.name}}"
        ng-model="treatment.checked"
        ng-click="updateTreatment($index, treatment_list);
                  checkedTreatment(treatment_list)">
 Treatment {{treatment.name.toUpperCase()}}</input>

{{treatment_list}}

Controller:
$scope.treatment_list = [
    {
      name: 'a',
      checked: false
    }, {
      name: 'b',
      checked: false
    }
  ];

$scope.updateTreatment = function(position, treatment_list) {
    console.log(treatment_list);
    angular.forEach(treatment_list, function(treatment, index) {
      console.log(treatment.name, treatment.checked);
      if (position != index) {
        treatment.checked = false;
      }
    });
  };

$scope.$watch('treatment.checked', function (treatment) {
    console.log(treatment);
  });

Plunker:
https://plnkr.co/edit/Hkb4IeKxi0TRqHRJA4JN?p=preview

A: Inorder to fullfill your requirement you should just use a radio box whith ng-model, it will work out of the box for you.

A: Use radio buttons instead:

angular.module("app",[])
.controller('ExampleController', function($scope) {
      $scope.color = {
        name: 'blue'
      };
      $scope.specialValue = {
        "id": "12345",
        "value": "green"
      };
      $scope.colorChange = function(color) {
          console.log(color);
      };
})

<form name="myForm" ng-controller="ExampleController">

    <input type="radio" ng-model="color.name" value="red"
           ng-change="colorChange(color.name)" />
    Red

    <input type="radio" ng-model="color.name" ng-value="specialValue"
           ng-change="colorChange(color.name)" />
    Green

    <input type="radio" ng-model="color.name" value="blue"
           ng-change="colorChange(color.name)" />
    Blue

  <tt>color = {{color.name | json}}</tt>

 </form>
 Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.

For more infomation, see AngularJS input type=radio Directive API Reference


text:
Q: How to delete multiple dynamic textbox I have here my JS code that dynamically add textboxes.. I want to add another button that removes these textbox in case add button is accidentally clicked. Thanks!
<script language="javascript">
  row_no=0;
  function addRow(tbl,row){
    row_no++;
    if (row_no<=20){
      if (row_no<=20){
        if (row_no>=10){
           var textbox  = row_no+'.) <input type="text" size = "50"  maxlength= "50" name= "desk_user[]">';
        }
        if (row_no<10){
           var textbox  = row_no+'.  ) <input type="text" size = "20"  maxlength= "50" name= "desk_user[]">';
        }
        var textbox2 = '<input type="text" size = "60" maxlength= "250" name= "desk_report[]">';
        var textbox3 = '<input type="text" size = "60" maxlength= "250" name= "desk_action[]">';

        var tbl = document.getElementById(tbl);
        var rowIndex = document.getElementById(row).value;
        var newRow = tbl.insertRow(row_no);
        var newCell = newRow.insertCell(0);
        newCell.innerHTML = textbox;
        var newCell = newRow.insertCell(1);
        newCell.innerHTML = textbox2;
        var newCell = newRow.insertCell(2);
        newCell.innerHTML = textbox3;
      }
      if (row_no>20){
        alert ("Too Many Items. Limit of 20.");
      }
    }
  }
</script>

A: Do you want to remove all the input elements which you have add dynamically??
Is there any other contents available in the element in which you add those input elements?
If not and if you want to remove all the elements then try the following code..
for(i=0; i < row_no; i++){
   newRow.insertCell(i).innerHTML = '';
}

If this is not what you want then just modify your question to get proper answer. Because not specially said whether you need to remove all elements or particular elements and whether do you have any other contents in the element in which you add those input elements.


text:
Q: How to run a string as a command in VBA I have this simple VBA code below, and I don't know why is not working.
Sub Run()
    test = "MsgBox" & """" & "Job Done!" & """"
    Application.Run test
End Sub

What I want to do is to put the VBA Command into a variable as text and run it as a command. In this case, I want to run like MsgBox "Job Done!" and print just:

Job Done!

A: You may be tempted by adding your own string "Executer":
Sub StringExecute(s As String)
    Dim vbComp As Object
    Set vbComp = ThisWorkbook.VBProject.VBComponents.Add(1)
    vbComp.CodeModule.AddFromString "Sub foo()" & vbCrLf & s & vbCrLf & "End Sub"
    Application.Run vbComp.name & ".foo"
    ThisWorkbook.VBProject.VBComponents.Remove vbComp
End Sub

Sub Testing()
    StringExecute "MsgBox" & """" & "Job Done!" & """"
End Sub

A: Short answer is, you cannot do that (You should not do that) but ... read the following to find out why and see a work around!
As you know you are writing your code in a compiler. What you want to do is running human-legible line of text as a command which is not possible. While you run the program all of it is compiled to machine language. When you pass that line of text to it, it cannot recognize it as a command and you will end up getting an error. What you can do is passing arguments to it:
Sub Run()
 test = "Job Done"
 MsgBox(test)
End Sub

You can also run an executable which can be written as a text file within a macro and then runs within the same Sub (extension needs to be taken care of).
If you cannot change the variable (i.e. test) then you need to take another approach towards it. I would suggest something like extracting the argument which can be passed to the function and use that. Something like below;
Sub Run()

 test = "MsgBox" & """" & "Job Done!" & """"

 extest = Right(test, Len(test) - 7)

 MsgBox (extest)

End Sub

I believe there was a same question on SO but I couldn't find it. I will included it as a reference if found it.
P.S. These two posts may help to find an answer:
Access VBA - Evaluate function with string arguments
Excel VBA - How to run a string as a line of code
ANOTHER SOLUTION
This needs to trust the VB project. Quoting from ExcelForum and referencing to Programmatic Access To Visual Basic Project Is Not Trusted - Excel

Quote:

Place your Macro-Enabled Workbook in a folder which you can designate
 as macro friendly.
Then open the workbook.
Click on the Office Button -> Excel Options ->
Trust Center -> Trust Center Setting -> Trusted Locations.
Then you add your folder (where you have your Excel Macro-Enabled Workbook) as
 a trusted location.
Also you need to do this:
File -> Options -> Trust Center -> Trust Center Setting -> Macro Setting ->
Check the box beside "Trust access to the VBA project object model"
Close and re-open your workbook.
Those who use your macro should go through the same steps.

Unquote.

Then you can use this which I got from VBA - Execute string as command in Excel (This is not tested)
Sub test()
 Set VBComp = ThisWorkbook.VBProject.VBComponents.Add(vbext_ct_StdModule)
 VBComp.Name = "NewModule"
 Set VBCodeMod = ThisWorkbook.VBProject.VBComponents("NewModule").CodeModule

 Dim test As String
 test = "MsgBox " & """" & "Job Done!" & """"

 With VBCodeMod
    LineNum = .CountOfLines + 1
    .InsertLines LineNum, _
    "Sub MyNewProcedure()" & Chr(13) & test & Chr(13) & "End Sub"
 End With
 'run the new module
 Application.Run "MyNewProcedure"
 UserForm1.Show
 'Delete the created module
 ThisWorkbook.VBProject.VBComponents.Remove VBComp
End Sub

@A.S.H answer does the thing that last solution intends to implement. I am including it here for the sake of completeness. You can refer to the original answer and up-vote it.
Public Sub StringExecute(s As String)
    Dim vbComp As Object
    Set vbComp = ThisWorkbook.VBProject.VBComponents.Add(1)
    vbComp.CodeModule.AddFromString "Sub foo" & vbCrLf & s & vbCrLf & "End Sub"
    Application.Run vbComp.name & ".foo"
    ThisWorkbook.VBProject.VBComponents.Remove vbComp
End Sub

Sub Testing()
    StringExecute "MsgBox" & """" & "Job Done!" & """"
End Sub

A: If you need a solution which doesn't require special permissions, and has significantly more power than hard coding code, I maintain a library, stdLambda from stdVBA, for this kind of thing:
'Ensure module name is "mainModule"
Public Sub Main()
   Call stdLambda.bindGlobal("msgbox", stdCallback.CreateFromModule("mainModule","msgbox"))
   x = stdLambda.Create("msgbox(""hello world"")").Run()
End Sub
Public Function msgbox(ByVal sMessage as string) as long
   msgbox = VBA.msgbox(sMessage)
End Function

stdLambda syntax is vba-like but is a fully embedded programming language in its own right. See the documentation for more details.

A: I was up against a similar variation: the macro name was in a 'control specification' worksheet table. A custom ribbon was added with an 'onAction' parameter in the ribbon XML. The 'tag' Name was returned in the Ribbon call back macro that was then used to lookup the macro Name to run based on the XML tag name. Makes sense so far!!!! I already had the handling subs in an existing Code Module=[m0_RibbonCallBack]. In the [m0_RibbonCallBack] module I wanted to run the sub name=[mResetToCellA2] when I clicked the ribbon button with tagName=[Reset2CellA2]. In the 'control specification' worksheet table I did a vLookUp() on the tagname=[Reset2CellA2] and returned the string value from column 3 (onAction) ="mResetToCellA2". Now I need to run the macro string (macroName) name on the VBA side!!!
I wound up solving the challenge with this simple line:
Application.Run "m0_RibbonCallBack." & macroName
Cheers!


text:
Q: Angular SSR, Dynamic Page Won't Load - Status 504 Code: http://github.com/dbots-co/website
Directly connecting to a dynamic route (dashboard, bot page), seems to not work. However, directly connecting to docs does work.
This only happens when using Angular 10 Universal SSR.
Not Working: https://dbots.co/bots/774811448576573480
Working: https://dbots.co/docs/get-started
bot-page.component.ts:
async ngOnInit() {
    await this.service.init();

    this.user = this.service.getBot(this.id);
    this.bot = this.service.getSavedBot(this.id);
    if (!this.user || !this.bot)
      return this.router.navigate(['']);

    this.seo.setTags({
      description: this.bot.listing.overview,
      titlePrefix: this.user.username,
      titleSuffix: 'DBots',
      url: `bots/${this.id}`
    });

    this.analytics.botPageView({ botId: this.user.id });

    this.themeService.setNavbarBackground('var(--background-secondary)');
    document
      .querySelector('.navbar')
      .setAttribute('style', `margin-bottom: -5px;`);
  }

app-routing.module.ts:
const routes: Routes = [
    ...
    { path: 'bots/:id', component: BotPageComponent },
    ...
];


text:
Q: Need help writing a test class for a refresh action on a VF page I have created a VF Page Report for showing data based off of 2 dates.  The VF Page works great but I am unable to get the code coverage I need to deploy. Right now all but lines 17-18 and 24-34 are covered.  Pretty much the public void refresh() method.
VF PAGE
public class MonthlySeizureController1{
    public task taskRec                 { get; set; }
    public task taskRec1                { get; set; }
    public List<Case__c> theCases              { get; set; } // this was the ca reference
    public Map<Id, Business__c> businessMap   { get; set; } // this was the bus1 reference
    public MonthlySeizureController1(ApexPages.StandardController sc){
        this();
    }
    public MonthlySeizureController1() {
        taskRec = new task (ActivityDate__c = Date.today().addMonths(-1));
        taskRec1 = new task (ActivityDate__c = Date.today());
        // get the supply chain cases in the last month be careful of 10k cases in this result
        this.theCases = querySupplyChainCasesBetweenDates(taskRec.ActivityDate__c, taskRec1.ActivityDate__c);
        // collect the ids of the businesses in these cases
        Set<Id> businessIds = new Set<Id>();
        for (Case__c c : theCases) {
            for (BusinessCasesAssociation__c bca : c.BusinessCasesAssociations__r) {
                businessIds.add(bca.Business__c);
            }
        }
        // get the businesses related to these cases and assign them to the variable in the controller
        this.businessMap = queryBusinesses(businessIDs);
    }
    public void refresh() {
        this.theCases = querySupplyChainCasesBetweenDates(taskRec.ActivityDate__c, taskRec1.ActivityDate__c);
        // collect the ids of the businesses in these cases
        Set<Id> businessIds = new Set<Id>();
        for (Case__c c : theCases) {
            for (BusinessCasesAssociation__c bca : c.BusinessCasesAssociations__r) {
                businessIds.add(bca.Business__c);
            }
        }
        // get the businesses related to these cases and assign them to the variable in the controller
        this.businessMap = queryBusinesses(businessIDs);
    }

    public Map<Id, Business__c> queryBusinesses(Set<Id> businessIDs) {
        Map<Id, Business__c> result =  new Map<Id, Business__c>([SELECT Id
                                                                    , Name
                                                                    , Business_Name__c
                                                                    , Business_Type__c
                                                                    , (SELECT Street__c
                                                                            , Business_City__c
                                                                            , State_Province__c
                                                                            , Country__c
                                                                            , Zip_Postal_Code__c
                                                                        FROM BPR_Business_Addresses__r)
                                                                    , (SELECT Number_Type__c
                                                                            , Number__c
                                                                        FROM Business_Phone_Numbers__r)
                                                                    , (SELECT Email_Bus__c
                                                                        FROM Email_Businesses__r)
                                                                FROM Business__c
                                                                WHERE (Id = :businessIDs)]);
        return result;
    }
    public List<Case__c> querySupplyChainCasesBetweenDates(Date lowerDate, Date upperDate) {
        List<Case__c> cases = [SELECT Id
                                    , Name
                                    , CreatedDate
                                    , Owner.FirstName
                                    , Owner.LastName
                                    , Notification_Date__c
                                    , Incident_City__c
                                    , Incident_Country__r.Name
                                    , Total_Product__c
                                    , Comments_Postal_Express__c
                                    , (SELECT RecordType.Name
                                            , CreatedDate
                                            , Container__c
                                            , Ship_Date__c
                                            , Date_of_Retention__c
                                            , Carrier__c
                                            , Port_of_Loading__c
                                            , Port_of_Discharge__c
                                            , Container_Type__c
                                            , Place_of_Retention__c
                                            , Vessel__c
                                            , Master_BOL__c
                                            , House_BOL__c
                                        FROM Incident_Locations__r)
                                    , (SELECT Brand__c
                                            , Product_Detail__c
                                            , Product_Types__c
                                            , Total_Product_Quantity__c
                                        FROM Products__r)
                                    , (SELECT Business__c
                                            , Case__c
                                            , Business__r.Business_Name__c
                                            , Business__r.Business_Type__c
                                        FROM BusinessCasesAssociations__r)
                                    , (SELECT Subject_Name__r.Subject_Name__c
                                            , Subject_Name__r.Subject_Type__c
                                        FROM Subject_for_Cases__r)
                                FROM Case__c
                                WHERE Supply_Chain_Type__c = 'SEA'
                                    AND Id IN (SELECT IL__c FROM Supply_Chains__c WHERE CreatedDate >= :lowerDate AND CreatedDate <= :upperDate)
                                ORDER BY CreatedDate ASC];
        return cases;
    }
    public PageReference next(){
        PageReference nextpage = new PageReference('/apex/MonthlySeizureReport1ppv');
        return nextpage;
    }
}

Here is the test class that I have written so far.  Any help would be great.  Thanks.
UPDATED TEST CLASS 8/28/18
@isTest
public class MonthlySeizureController1Test {
public static testMethod void testMonthlySeizureController1() {
    PageReference pageRef = Page.MonthlySeizureReport1; //replace with your VF page name
    Test.setCurrentPage(pageRef);
    Date myDate = Date.newInstance(2017, 12, 22);
    Date myDate1 = Date.newInstance(2017, 12, 18);
    Date myDate2 = Date.newInstance(2017, 12, 31);
    //Add test data. For example, create a set of test Opportunities
Case__c testCase = new Case__c(Case_Name__c = 'Test Case'
                                , Notification_Date__c = myDate
                                , Incident_City__c = 'Oruro'
                                , Incident_Country__c = 'a08C000000AIGaPIAX'
                                , Comments_Postal_Express__c = 'test comments'
                                ,Supply_Chain_Type__c = 'SEA'
                                );
Supply_Chains__c testSupply = new Supply_Chains__c(RecordTypeId = '012C0000000cairIAA'
                                                    , Ship_Date__c = myDate
                                                    , Date_of_Retention__c = myDate
                                                    , IL__c = testCase.Id);
 Business__c testBus = new Business__c(Business_Name__c = 'Test Business'
                                , Business_Type__c = 'Exporter');
 BusinessCasesAssociation__c testBusCase = new BusinessCasesAssociation__c(Business__c = testBus.Id
                                        , Case__c = testCase.Id
                                        , How_are_the_business_and_case_related__c = 'Unknown'
                                        , Please_describe_the_relationship__c = 'test');
 Subject__c testSub = new Subject__c(First_Name__c = 'TestFirst'
                                , Last_Name__c = 'TestLast'
                                , Subject_Type__c = 'Exporter');
 Subject_for_Case__c testSubCase = new Subject_for_Case__c(Case_Name__c = testCase.Id
                                 , Subject_Name__c = testSub.Id);
    ApexPages.currentPage().getParameters().put('taskRec', '2017-12-18');
    ApexPages.currentPage().getParameters().put('taskRec1', '2017-12-31');
    ApexPages.StandardController sc = new ApexPages.StandardController(testcase);
    MonthlySeizureController1 controller = new MonthlySeizureController1(sc);
    controller.refresh();
    //Test Data
    System.assertNotEquals(null, testCase);
    System.assertNotEquals(null, testSub);
    System.assertNotEquals(null, testBus);
    System.assertNotEquals(null, testSubCase);
    System.assertNotEquals(null, testBusCase);
    System.assertNotEquals(null, controller.next());
}
}

A: I think you have missed Supply_Chain_Type__c='SEA' while inserting the Case. And you did not even called the refresh method.
Replace your test class with the following code
@isTest
public class MonthlySeizureController1Test {
public static testMethod void testMonthlySeizureController1() {
    PageReference pageRef = Page.MonthlySeizureReport1; //replace with your VF page name
    Test.setCurrentPage(pageRef);
    Date myDate = Date.newInstance(2017, 12, 22);
    Date myDate1 = Date.newInstance(2017, 12, 18);
    Date myDate2 = Date.newInstance(2017, 12, 31);
    //Add test data. For example, create a set of test Opportunities
Case__c testCase = new Case__c(Case_Name__c = 'Test Case'
                                , Notification_Date__c = myDate
                                , Incident_City__c = 'Oruro'
                                , Incident_Country__c = 'a08C000000AIGaPIAX'
                                , Comments_Postal_Express__c = 'test comments'
                                ,Supply_Chain_Type__c = 'SEA'
                                );
Supply_Chains__c testSupply = new Supply_Chains__c(RecordTypeId = '012C0000000cairIAA'
                                                    , Ship_Date__c = myDate
                                                    , Date_of_Retention__c = myDate
                                                    , IL__c = testCase.Id);
 Business__c testBus = new Business__c(Business_Name__c = 'Test Business'
                                , Business_Type__c = 'Exporter');
 BusinessCasesAssociation__c testBusCase = new BusinessCasesAssociation__c(Business__c = testBus.Id
                                        , Case__c = testCase.Id
                                        , How_are_the_business_and_case_related__c = 'Unknown'
                                        , Please_describe_the_relationship__c = 'test');
 Subject__c testSub = new Subject__c(First_Name__c = 'TestFirst'
                                , Last_Name__c = 'TestLast'
                                , Subject_Type__c = 'Exporter');
 Subject_for_Case__c testSubCase = new Subject_for_Case__c(Case_Name__c = testCase.Id
                                 , Subject_Name__c = testSub.Id);
    ApexPages.currentPage().getParameters().put('taskRec', '2017-12-18');
    ApexPages.currentPage().getParameters().put('taskRec1', '2017-12-31');
    ApexPages.StandardController sc = new ApexPages.StandardController(testcase);
    MonthlySeizureController1 controller = new MonthlySeizureController1(sc);
    controller.refresh();
    //Test Data
    System.assertNotEquals(null, testCase);
    System.assertNotEquals(null, testSub);
    System.assertNotEquals(null, testBus);
    System.assertNotEquals(null, testSubCase);
    System.assertNotEquals(null, testBusCase);
    System.assertNotEquals(null, controller.next());
}

}


text:
Q: Change accordion button collapsed icon color in Bootstrap 5 I am trying to change the Bootstrap 5's accordion's "accordion-button" color when it is collapsed.
I tried below. It changes the background but not the button's icon color.
.accordion-button.collapsed {
    color: white;
    background: blue;
}

What should I do to change the down (collapsed) icon of the accordion for Bootstrap 5?

A: .accordion-button::after {background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='%23fff'%3e%3cpath fill-rule='evenodd' d='M1.646 4.646a.5.5 0 0 1 .708 0L8 10.293l5.646-5.647a.5.5 0 0 1 .708.708l-6 6a.5.5 0 0 1-.708 0l-6-6a.5.5 0 0 1 0-.708z'/%3e%3c/svg%3e"); }

use this and it works perfectly customizing the css to this

A: Because it is a background-image (using the bootstrap icons) that is set in the ::after pseudo element, so change the image
Update - (based on OP comment)

It replaces the icon with the image. How do I change the color of the existing image (icon)?

So use the same background-image and change the fill to #fff
Note that SVG URL is encoded by boostrap

.accordion-button.collapsed {
  background: blue
}

.accordion-button.collapsed::after {
  background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='%23fff'%3e%3cpath fill-rule='evenodd' d='M1.646 4.646a.5.5 0 0 1 .708 0L8 10.293l5.646-5.647a.5.5 0 0 1 .708.708l-6 6a.5.5 0 0 1-.708 0l-6-6a.5.5 0 0 1 0-.708z'/%3e%3c/svg%3e");
}

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">

      <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
        Accordion Item #1
      </button>

        This is the first item's accordion body. It is hidden by default, until the collapse plugin adds the appropriate classes that we use to style each element. These classes control the overall appearance, as well as the showing and
        hiding via CSS transitions. You can modify any of this with custom CSS or overriding our default variables. It's also worth noting that just about any HTML can go within the .accordion-body, though the transition does limit overflow.

      <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
        Accordion Item #2
      </button>

        This is the second item's accordion body. It is hidden by default, until the collapse plugin adds the appropriate classes that we use to style each element. These classes control the overall appearance, as well as the showing
        and hiding via CSS transitions. You can modify any of this with custom CSS or overriding our default variables. It's also worth noting that just about any HTML can go within the .accordion-body, though the transition does limit overflow.

      <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
        Accordion Item #3
      </button>

        This is the third item's accordion body. It is hidden by default, until the collapse plugin adds the appropriate classes that we use to style each element. These classes control the overall appearance, as well as the showing and
        hiding via CSS transitions. You can modify any of this with custom CSS or overriding our default variables. It's also worth noting that just about any HTML can go within the .accordion-body, though the transition does limit overflow.

A: I needed to do something similar. I overrode the .accordion defaults. I did not need a new icon, just a new color. (I made fill=white for both collapsed and not). But you can see that this can easily change the icon as well.

A: This worked for me
.accordion-button:focus {
   z-index: 3;
   border-color: #279C88;
   outline: 0!important;
   /* I changed the color on this line */
   /* If you do not want any color, just delete */
   box-shadow: 0 0 0 0.25rem rgba(39, 156, 136, 0.25);
}

A: If you compile your own css via sass, you can set the variable $accordion-icon-active-color which will set the fill value of the SVG.


text:
Q: Usage of com.sap.cloud.sdk.s4hana.connectivity.rfc.BapiQuery inside Spring RestController I am trying to call a BAPI from a Spring REST controller.
The call to the backend system works fine, however returning the ResponseEntity leads to an error "getOutputStream() has already been called for this response"
@RequestMapping( method = RequestMethod.GET )
public ResponseEntity<List<ExportingCostCenterInformation>> getBusinessPartners()
{
    final ErpEndpoint endpoint = new ErpEndpoint(new ErpConfigContext("ErpQueryEndpoint_RFC"));

    final BapiQuery query = new BapiQuery("BAPI_COSTCENTER_GETLIST")
        .withExporting("CONTROLLINGAREA", "KOKRS", "1000");

    List<ExportingCostCenterInformation> ecci = null;
    try {
        ecci = query.execute(endpoint)
            .get("COSTCENTER_LIST")
            .getAsCollection()
            .asList(ExportingCostCenterInformation.class);
    } catch (UnsupportedOperationException | IllegalArgumentException | QuerySerializationException | DestinationNotFoundException | DestinationAccessException | QueryExecutionException e) {
        // ...
    }

    return ResponseEntity.ok(ecci);
}

Any ideas why this error comes up?

A: The getter & setter methods of class ExportingCostCenterInformation were not well defined. That was the issue.


text:
Q: Codeigniter Show All Duplicate Records in view I have this working query which will fetch duplicate records in Codeigniter
 function getDuplicatePartNumbers()
 {
    $this->db->select('*');
    $this->db->select('part_number');
    $this->db->select('count(*)');
    //$this->db->from('orders');
    $this->db->group_by('part_number');
    $this->db->having('count(*) > 1');
    $query = $this->db->get('pending_order');
    return $query->result_array();
}

I need to modify this since it will only return  the value that is duplicated, but it does not return all the duplicates
Example if I have
   id      name

   1        jane
   2        jane
   3         joe
   4        jane

Only 1 jane will appear, I want all jane in this case
Any ideas?

A: You've got the part_number and the count(*).
Give an alias to the count(*)
and use it to know the number of occurrences of each record retrieved.
$this->db->select('count(*) as occurrences');


text:
Q: Django: way to test what class a generic relation content_object is? In my project I have a class, NewsItem. Instances of NewsItem act like a wrapper. They can be associated with either an ArtWork instance, or an Announcement instance.
Here's how the NewsItem model looks:
class NewsItem(models.Model):
 content_type = models.ForeignKey(ContentType)
 object_id = models.PositiveIntegerField()
 content_object = generic.GenericForeignKey('content_type', 'object_id')
 date = models.DateTimeField(default=datetime.datetime.now,)
 class Meta:
  ordering = ('-date',)
 def __unicode__(self):
  return (self.title())
In a template I'm dealing with a NewsItem instance, and would like to output a certain bunch of html it it's 'wrapping' an Artwork instance, and a different bunch of html if it's wrapping an Announcement instance. Could someone explain how I can write a conditional to test for this?
My first naive try looked like this:
{% if news_item.content_object.type=='Artwork' %}do this{% else %}do that{% endif %}

A: You should use the ForeignKey to content_type, which stores this information.
{% if news_item.content_type.model == 'Artwork' %}


text:
Q: com.netledger.common.exceptions.NLUserError: No data was found When I right-click on a project in SDF and select NetSuite > Upload File(s) to Project, I get the following error partway through the upload:

com.netledger.common.exceptions.NLUserError: No data was found

This was working before, but it suddenly stopped while I was working on the project. What causes this error, and how do I fix it?

A: I got this error when I deleted a file in the filesystem but Eclipse didn't see that it had gone away, so it was still in the list of files in the NS Explorer pane. After I refreshed the project and the file disappeared from the list, I could upload the project without errors again.


text:
Q: Using an if/else statment to check that enum arguments exist I'm having a slight issue with my current piece of code and trying to check that arguments have been passed to enum before trying to continue with the program;
 enum arg {argName, sineArg, sampleArg, argC}eargs;

 int main(int argc, char *argv[]){

    long samplingRate = atol(argv[sampleArg]);
    float sineFreq = atof(argv[sineArg]);
    if (argC < eargs ){
        printf("Usage: sineFreq\tsamplingRate\n");
    }else{}
  }

The code compiles fine, although when run without arguments the program returns "Segmentation fault: 11" instead of the usage message that I want to print to console.

A: you have to do the check before accessing argv[...]
EDIT: the check itself is wrong too (eargs is undefined; you should write
int main(int argc, char *argv[]) {
    if (argc < argC)         /* --> you should change you naming conventions! */
        return EXIT_FAILURE;

    long samplingRate = atol(argv[sampleArg]);

A: you need to change argC  to argc, in the if statement...c is case-sensitive!!!

A: Your usage check is against eargs that has nothing to with the number of command line arguments passed. No matter how many arguments you pass, eargs is always going to be 0.
Also you should do the check before using any of the command line arguments. Place the condition at the start of main():
#include<stdio.h>
#include <stdlib.h>

enum arg {argName, sineArg, sampleArg, argC}eargs;

int main(int argc, char *argv[]) {

  /* if ( argc < 3) would be explicit and clear here */
  if (argc < argC ) { /* You expect at least two arguments */
    printf("Usage: sineFreq\tsamplingRate\n");
    return 1; // return from main on failure
  }

  long samplingRate = atol(argv[sampleArg]);
  float sineFreq = atof(argv[sineArg]);

  ....
}

I have also included standard headers as you are using printf() and atol()

A: When you run the code without arguments, this
 long samplingRate = atol(argv[sampleArg]);

accesses argv[2], which is undefined behavior, since you don't provide enough args (there are only argv[0] = program name and argv[1] = NULL indicating the end of the argv[]).


text:
Q: How to get this grid normal height? When I execute this
Grid[{{x, x}, {SpanFromAbove, x}, {SpanFromAbove, x}},
 ItemSize -> {{Automatic},
  {Automatic, {1 -> Scaled[0.2], 2 -> Scaled[0.4], 3 -> Scaled[0.4]}}},
 Frame -> All,
 Alignment -> {Center, Center}, Spacings -> {{2}, {1}}]

I get an extremely tall grid instead of a normal height grid.  Is this a bug or am I doing something wrong? Version 10.0.1 Win8.1 64bit
Update
This just keeps getting worse.  I am have used a Pane as some have suggested that the grid needs a sized container for it to work with Scaled. I get back a truncated grid.  This is really baffling.  Any ideas how to get this to work.
Pane[
 Grid[{{x, x}, {SpanFromAbove, x}, {SpanFromAbove, x}},
  ItemSize -> {{{Scaled[0.5]}},
   {Automatic, {1 -> Scaled[0.2], 2 -> Scaled[0.4], 3 -> Scaled[0.4]}}},
  Frame -> All, Alignment -> {Center, Center}, Spacings -> {{1}, {1}}],
 ImageSize -> {432, 216}]

It gives a cut off grid. ??? I can just make out the top of the "x" in the first column. It shouldn't be this difficult to have a grid a prescribed size and scale some rows within it.  I must be doing something wrong.

A: My advice, unless it is really basic problem, do not use SpanFrom~. Usually you will face "issues" like that. Next time try with nested Grids.
Like I've said, the whole layout management is broken and everyone who tried do something more complex than simple grid with automatic options will agree.
This is just another example, your case works if vertical heights sum up to: .5...
Framed[
 Grid[{
       {x, x},
       {SpanFromAbove, x},
       {SpanFromAbove, x}},
  ItemSize -> {
               {{Scaled@.499}},                  (*specX*)
               {Scaled@.1, Scaled@.2, Scaled@.2} (*specY*)
    }, Frame -> All, Alignment -> {Center, Center}, Spacings -> {0, 0}]
 ,
     ImageSize -> {432, 216}, FrameMargins -> 0, Alignment -> {Left, Top}]