text:
Q: Полноценный эмулятор мобильного браузера Столкнулся с такой проблемой, мой веб-проект на Vue отлично работает в консоле разработчика хрома в режиме эмулятора мобилок. Когда зашёл с реального устройства, половина функционала не работало, как позже выяснилось опера мобайл и андройд мобайл не поддерживают некоторые html тэги или атрибуты.
Существуют ли какие ни будь эмуляторы мобильных браузеров, что бы удобно тестить на работоспособность своё веб-приложение под мобилки.?
Я наткнулся на это https://dev.opera.com/articles/opera-mobile-emulator/
Но, кажется, этот проект уже давно помер.

A: Попробуйте использовать Genimotion. Вы получите эмуляторы без установки Android Studio овер 10 gb

A: Гайд по эмулятору Android из Android Studio: https://developer.android.com/studio/run/emulator
Гайд по эмулятору iOS из Xcode:
https://ali-dev.medium.com/how-to-use-xcode-ios-simulator-for-responsive-web-testing-on-mac-7870ee4fc22b


text:
Q: is Second Screen capable of 16:9 via AirPlay over AppleTV in iOS 5.0.1 i think about extending support within one of my apps to handle a second screen via AppleTV.
The question is:
If i just mirror my App, the nice 46" LCD TV shows only a 4:3 Letterbox Image of my App. Is it possible to use the full 16:9 ratio if i change my app to render a different screen for Apple TV / AirPlay?

A: Absolutely. In iOS 5, a mirrored AirPlay screen can be used as a secondary UIScreen, which can have content different from what is on the device screen. That's what you want to do.
You can see how to do this here:
https://github.com/quellish/AirplayDemo
Your device screen is mirrored until you start using that secondary UIScreen, and you can remove the window you attach the to the UIScreen and go back to mirroring. This lets you control when you're putting custom content on there, and when you're just mirroring.

A: Absolutely - see Real Racing HD 2 for a great example!

redpajama_set_name: RedPajamaStackExchange


text:
Q: error: package rx.android.schedulers does not exist after changing compilesdk Hi I updated my gradle and android studio and since then I started getting build errors.
Once I changed compileSdkVersionto 28, I started getting error: package rx.android.schedulers does not exist
I also get this error in my build as shown in the pic bellow

Here are my dependencies from build.gradle
   dependencies {

    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation fileTree(dir: "$buildDir/native-libs", include: 'native-libs.jar')

    implementation 'com.android.support:multidex:1.0.2'
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.jenzz.appstate:appstate:3.0.1'
    implementation 'com.jenzz.appstate:adapter-rxjava2:3.0.1'
    implementation 'com.android.support:design:28.0.0'
    implementation 'com.android.support:cardview-v7:28.0.0'
    implementation 'com.android.support:recyclerview-v7:28.0.0'
    implementation group: 'joda-time', name: 'joda-time', version: '2.3'
    implementation 'com.mikhaellopez:circularprogressbar:1.1.1'
    implementation 'io.realm:android-adapters:2.0.0'
    implementation 'com.jakewharton.rxbinding2:rxbinding-recyclerview-v7:2.0.0'
    implementation 'com.github.arimorty:floatingsearchview:2.1.1'
    implementation 'uk.co.chrisjenx:calligraphy:2.3.0'
    implementation 'com.laimiux.rxnetwork:rxnetwork:0.0.4'
    // implementation 'org.opencv:opencv-android:2.4.8'
    // implementation group: 'com.github.andrejlukasevic', name: 'document-scanner', version: '4.0.0'
    // implementation 'com.mlsdev.rximagepicker:library:2.0.2'
    implementation 'com.google.firebase:firebase-messaging:15.0.0'
    debugImplementation 'com.21buttons:fragment-test-rule:1.0.0'
    //Retrofit, RxJava and OkHttp,Gson,Dagger,ButterKnife.
    implementation 'com.squareup.retrofit2:retrofit:2.1.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
    implementation 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
    implementation 'frankiesardo:icepick:3.1.0'
    annotationProcessor 'frankiesardo:icepick-processor:3.1.0'

    implementation group: 'com.squareup.retrofit2', name: 'adapter-rxjava2', version: '2.2.0'
    implementation 'io.michaelrocks:libphonenumber-android:8.9.0'

    implementation ('com.google.dagger:dagger:2.0.2'){
        exclude group: 'com.google.guava'
    }
    annotationProcessor ('com.google.dagger:dagger-compiler:2.0.2'){
        exclude group: 'com.google.guava'
    }
    implementation 'com.jakewharton:butterknife:8.8.1'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
    compileOnly 'javax.annotation:jsr250-api:1.0'
    implementation 'com.android.support:support-annotations:24.2.0'
    implementation 'com.jakewharton.rxrelay2:rxrelay:2.0.0'
    implementation 'com.jakewharton.rxrelay:rxrelay:1.1.0'
    implementation 'com.futuremind.recyclerfastscroll:fastscroll:0.2.5'
    implementation group: 'io.reactivex.rxjava2', name: 'rxandroid', version: '2.0.1'
    implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.0'
    implementation 'com.jakewharton.timber:timber:4.5.1'
    implementation 'com.google.code.gson:gson:2.5'
    implementation 'com.squareup.retrofit2:retrofit-mock:2.1.0'
    implementation 'com.github.bumptech.glide:glide:3.7.0'
    implementation 'com.github.fafaldo:fab-toolbar:1.2.0'
    implementation 'com.instabug.library:instabug:8.1.1'
    implementation 'com.wdullaer:materialdatetimepicker:3.5.2'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    implementation 'net.hockeyapp.android:HockeySDK:4.1.5'
    implementation 'com.jakewharton.rxbinding2:rxbinding-appcompat-v7:2.0.0'
    implementation 'com.tbruyelle.rxpermissions2:rxpermissions:0.9.4@aar'
    implementation group: 'com.joooonho', name: 'selectableroundedimageview', version: '1.0.1'
    implementation 'com.mixpanel.android:mixpanel-android:5.+'
    debugImplementation 'com.squareup.leakcanary:leakcanary-android:1.5'
    //releaseImplementation 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'

    testImplementation 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
    testImplementation 'junit:junit:4.12'
    testImplementation 'org.mockito:mockito-core:1.9.5'
    testImplementation 'com.google.dexmaker:dexmaker:1.1'
    testImplementation 'org.powermock:powermock-api-mockito:1.6.4'
    testImplementation 'org.powermock:powermock-module-junit4:1.6.4'
    testImplementation 'org.powermock:powermock-core:1.6.4'
    testImplementation 'org.powermock:powermock-module-junit4-rule:1.5.4'
    testImplementation 'org.powermock:powermock-classloading-base:1.6.4'
    testImplementation 'org.powermock:powermock-classloading-xstream:1.5.4'
    testImplementation 'org.powermock:powermock-module-testng:1.6.4'
    testImplementation 'com.squareup.retrofit2:retrofit:2.1.0'
    testImplementation 'com.squareup.retrofit2:converter-gson:2.1.0'
}

my java file where I am getting the error
import rx.android.schedulers.AndroidSchedulers;
@Override
    protected void onResume() {
        super.onResume();
        DoPayApplication.updateIsAppLive(Boolean.TRUE);
        publishRelay.call(StartStopAppMonitor.START_STOP_APP_MONITOR);
        compositeSubscription.add(publishRelay.asObservable().observeOn(AndroidSchedulers.mainThread()).subscribe(iView -> {

I changed the import to use
import io.reactivex.android.schedulers.AndroidSchedulers;

That gave me this error

When i was with compileSdkVersion 26 it did not give me this error with respect to rxAndroid/rxJava.
This started after changing compileSdkVersion to 28
I am really confused, could you please shed some light on how to fix this.
Thanks
R

A: first of all, when you start using API 28, you need to start migrating to AndroidX
for example, change: implementation 'com.android.support:appcompat-v7:28.0.0'
to: implementation 'androidx.appcompat:appcompat:1.0.0' and i think your first error gets fixed.

A: this solved my issues
implementation 'io.reactivex:rxjava:1.0.12'


text:
Q: Adding rows and columns dynamically to table control I need to create UI using winforms which is similar to the diagram. The table needs
row one   - one label and 20 buttons
row two   - combox box, box and 20 buttons
row three - combox box, box and 20 buttons
row four  - combox box, box and 20 buttons
In the column zero of the row zero, i need to add label and from next column need to add buttons
In the column zero of the row one,need combobox and button and then from column1 again buttons.
How to do add combox box and button to the same column(column zero) using the tablecontrolpanel, the width of the column zero should be not changed.
I am using table control to add the 20 buttons, but don't know how to add the button and combox box to the same column.


text:
Q: Displaying latest news and upcoming events on the front page of Moodle site I am new to moodle and I am working to develop a theme for moodle site. I have to show three boxes next to other on the front page. one box will show upcoming events and other will show latest news. I have noticed the boxes of latest news and upcoming events are displaying correctly in inner pages but I don't know how to display these boxes on the front page. I am using moodle 2.3.3. Any help would be appreciated.

A: you can add your code into the "summary" of the frontpage, using Moodle's HTML editor.
If you're comfortable with php and html, you should add your boxes directly into the frontpage.php from your Moodle theme (/theme/*your_current_theme*/layout/frontpage.php).
Edit your frontpage.php, it may looks like this :

                                <?php echo $OUTPUT->main_content() ?>

                                HERE IS THE PLACE TO ADD BOXES.


text:
Q: Removing some items in Recyclerview using databinding shows empty space I am using Firebase as my backend. I am using recyclerview to show a list of users. I've achieved that but now I now want to display only some users based on their "category" in the JSON. When I display the list without the gridview it works fine when I try to display the list in gridview I am seeing empty spaces in place of the users I've removed.
Below is code. My GridRecylerview
  mFragmentChatsBinding.rvChats.setHasFixedSize(true);
    RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 2);

    mFragmentChatsBinding.rvChats.setLayoutManager(mLayoutManager);

My JSON Response
    {"xxxxx@gmail,com":{
    "category":"admin",
    "email":"xxxx@gmail,com",
    "hasLoggedInWithPassword":false,
    "name":"xxxx"},
     "yyyy@gmail,com":{
    "category":"user",
    "email":"yyyy@gmail,com",
    "hasLoggedInWithPassword":false,
    "name":"yyy",}}

My Recyclerview Code
 private void initializeFirebase() {
    final Query refUsers = FirebaseDatabase.getInstance()
            .getReference(ConstantsFirebase.FIREBASE_LOCATION_USERS);
    refUsers.keepSynced(true);
        mAdapter = new FirebaseRecyclerAdapter<User, ChatsItemHolder>(User.class, R.layout.adapter_item_chats,
                ChatsItemHolder.class, refUsers) {
            @Override
            public ChatsItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                adapterItemChatsBinding = DataBindingUtil.inflate(LayoutInflater
                        .from(parent.getContext()), viewType, parent, false);
                //adapterItemChatsBinding.tvUserName.setTypeface(Typefaces.get(getActivity(), Constants.FONT_ROBOT_REGULAR));

                return new ChatsItemHolder(adapterItemChatsBinding);
            }
            @Override
            protected void populateViewHolder(ChatsItemHolder viewHolder, User user, int position) {

                        if (user.getCategory().equals("admin")) {
                            viewHolder.setIsRecyclable(false);                             viewHolder.mAdapterItemChatsBinding.lnItemRow.removeAllViews();                               viewHolder.mAdapterItemChatsBinding.lnItemRow.setPadding(0, 0, 0, 0);
                        } else {
                            viewHolder.bindUser(user, ChatsFragment.this);
                        }
             mAdapter.notifyDataSetChanged();
}

I am using the following code to not show the users I want
 if (user.getCategory().equals("admin")) {
                            viewHolder.setIsRecyclable(false);
                            viewHolder.mAdapterItemChatsBinding.lnItemRow.removeAllViews();                               viewHolder.mAdapterItemChatsBinding.lnItemRow.setPadding(0, 0, 0, 0);
                        } else {
                            viewHolder.bindUser(user, ChatsFragment.this);
                        }

Is there any better way to remove some items in the recyclerview. If yes, What is it? If no, why am I getting empty spaces when I am using gridrecyclerview and working fine when I show a normal recyclerview?

A: Instead of removing the view remove the item from the list and set

adapter.notifyDataSetChanged();

A: I think you can try to refresh you gridView or your adaptor.
For example
adapter.notifyDataChanged();
 grid.invalidateViews();
 grid.setAdapter(adapter);


text:
Q: Intel Rapid Start Technology Incompatible with Whole-Disk Encryption? I have a brand new Dell XPS 15 laptop, and I'm getting the following message popping up from time to time.

Searching around, I see that Windows 8.1 is supposed to have whole disk encryption enabled by default for systems that support it.
The problem is that when I go to Windows 8.1's settings under PC and devices | PC info, I see no mention of disk encryption. The articles I've read suggest this indicates that my system does not support it.
Questions:

*

*Why am I getting this message if my system doesn't support whole-disk encryption, and is there a way to determine for sure if this encryption is enabled or not?

*Does anyone know what terrible things happen if I leave both Intel Rapid Start Technology and whole-disk encryption enabled?

*Can anyone imagine why Dell is sending out computers, apparently, with invalid configurations.
Update
Actually, the link in the message does contain some helpful information, such as:

What full disk encryption solutions work best with Intel Rapid Start Technology?
  To maintain the benefits of Intel Rapid Start Technology and full disk encryption, we recommend using a hardware-based full disk encryption solution and enabling an ATA security password.
Published guidance for software-based full disk encryption usually involves disabling Windows Standby/Sleep state and using Hibernate or Shut Down instead. Disabling the Sleep state means that Intel Rapid Start Technology may not be used.

But I'm still unclear why I can't confirm disk encryption is enabled.


text:
Q: [Python3]How to plot 55 columns using seaborn/matplotlib thanks in advance.
I wonder how to use the Seaborn + Matplotlib combination to make a beautiful bar chart.
Here is the sample dataset that I have:
         2015-01 2015-02 2015-03 2015-04 2015-05
negative   28      13       12     33      7
positive   78      20       19     3       55
neutral    17      5        45     24      9

And I want the bar chart to look like this click me, this is the chart I used excel to create, but I wonder how to use python to do the same thing? Or similar things?

A: If your dataframe is Pandas DataFrame, you can do:
df.T.plot.bar(width=0.8, edgecolor='w', linewidth=3)

which gives you:

A: It is possible with the following:
import pandas as pd
import io
import seaborn as sns
import matplotlib.pyplot as plt

Data
df = pd.read_csv(io.StringIO("""
2015-01 2015-02 2015-03 2015-04 2015-05
negative 28 13 12 33 7
positive 78 20 19 3 55
neutral 17 5 45 24 9
"""), sep=" ", engine="python")

ndf = df.stack().reset_index()

ndf.columns = ['Emotion','Date','Count']

Seaborn
sns.set_theme(style="whitegrid")
tips = sns.load_dataset("tips")
ax = sns.barplot(x="Date", hue="Emotion", y="Count", data=ndf)


text:
Q: Latest Xamarin Forms .NET Standard App, Asset Catalog / Default App Icon broken? I think perhaps the Visual Studio tooling is messed up in the latest version. I've successfully migrated an older pre-3.0 PCL XamForms app to a .NET Standard XamForms app and everything is working EXCEPT that app icon.
I get the default icon no matter what I do:

I've deleted and recreated the asset catalog several times, and it looks like the info.plist is correctly pointing to it because it can get my other images out of it inside the app.
It looks like info.plist points to Resources/AssetCatalog.xcassets/LaunchImages.launchimage under Resources, but the actually AssetCatalog isn't under the Resources folder.
If I close and reopen visual studio, then open the asset catalog, everything shows up in "Unknown" instead of it's correct place.
I'm not sure what to do to fix it.
WINDOWS MACHINE
Microsoft Visual Studio 2017 Version 15.7.3
VisualStudio.15.Release/15.7.3+27703.2026
Microsoft .NET Framework Version 4.7.03056
Xamarin 4.10.10.1 (f1760154c)
Xamarin Designer 4.12.1 (f3257e429)
Xamarin.Android SDK 8.3.3.2 (HEAD/dffc59120)
Xamarin.iOS and Xamarin.Mac SDK 11.12.0.4 (64fece5)
WINDOWS NUGET
.NET Standard Library 2.0.1
Newtonsoft JSON 11.0.2
sqlite-net-pcl 1.4.118
Xamarin Forms 3.0.0.561731
MAC MACHINE
XCode 9.4
Xamarin.iOS 11.12.0.4 (64fece54)
Windows and Mac fully updated, I've run Visual Studio and XCode and looked for updates on both, there are no other nuget updates on the Windows machine. I'm out of ideas to try at this point.
I can repro it on a BRAND NEW project. Just create a new XamForms project and add a image list to the Asset Catalog. Boom, you'll never have an app icon again. Uninstall / Reinstalling Visual Studio didn't help.

A: It is a known issue of visual studio.
Change XSAppIconAssets(the key inside info.plist) from Resources/Images.xcassets/AppIcons.appiconset to Images.xcassets/AppIcons.appiconset , it should be able to solve the issue.
Refer to Xamarin forms: Launcher icon for ios


text:
Q: How to use MS Graph to access files stored in a group without administrator privileges My app needs to access the files stored in a group's default document library as described in the docs like this:
/groups/{group-id}/drive

In order to do this the app needs to obtain the group ID. But according to this post and the documentation the authenticated user needs administrator privileges if the app wants to read the users's group information.
How can the app obtain a group ID if the authenticated user does not have admin privileges?

A: Your app need to be consented once by the administrator and after that it can access the information it requires. The permission scope required to access groups (Groups.Read or Groups.ReadWrite) require an administrator to consent, and the administrator can consent on behalf of the entire organization, in this case when a regular user uses the app they will not see a consent UI and the app will be able to access the information on their behalf. Code sample here: https://github.com/Azure-Samples/active-directory-dotnet-admin-restricted-scopes-v2


text:
Q: Spring Boot: Reading data using Spring Data JPA returns incorrect values I'm using Spring Boot in my application. I have a controller which accesses the service layer which accesses my implementation of Spring Data JPA's CrudRepository which interacts with Hibernate to fetch data from the database. All three of the following implementations of CrudRepository return incorrect objects:
public class ProductRepositoryImpl implements ProductRepository {

    @Autowired
    private SessionFactory sessionFactory;

    @SuppressWarnings("unchecked")
    public List<Product> findProductBatch(int start, int end) {
        Session session = sessionFactory.getCurrentSession();
        Query query = session.createQuery("from Product");
        query.setFirstResult(start);
        query.setMaxResults(end);
        List<Product> list = query.list();
        return list;
    }

    @SuppressWarnings({ "unused", "unchecked" })
    @Override
    public Iterable<Product> findAll() {
        Session session = sessionFactory.getCurrentSession();
        List<Product> products = session.createQuery("from Product").list();
        Iterable<Product> productIterable = products;
        return products;
    }

    @SuppressWarnings("unchecked")
    public List<Product> findBatch(int start, int end) {
        Session session = sessionFactory.getCurrentSession();
        Query query = session.createQuery("from Product");
        query.setFirstResult(start);
        query.setMaxResults(end);
        List<Product> list = query.list();
        return list;
    }

}

The findOne() method returns a record only if the parameter passed to it is zero, while the record's id is not zero. The following JSON response is returned upon sending a request:
{
  "productId": 0,
  "name": "xxxxxx",
  "productCategoryId": null,
  "created": 1482655958000,
  "createdBy": null
}

The record exists in the database but its id is 1 and it does have a "productCategoryId" but since it wasn't injected, it returned null.
The findAll() method returns the same record repeated many times and the findBatch() method returns a similar response.
Here's the rest of the code:
Product.java:
@Entity
public class Product {

    @Id
    private Integer productId;
    private String name;
    private Integer productCategoryId;
    @OneToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "productCategoryId", insertable = false, updatable = false)
    @Autowired
    private ProductCategory productCategory;
    private Date created;
    private Integer createdBy;

    public Product() {
    }

    public Product(Integer productId, String name, ProductCategory productCategory, Integer uomId, Date created, Integer createdBy) {
        this.productId = productId;
        this.name = name;
        this.productCategory = productCategory;
        this.created = created;
        this.createdBy = createdBy;
    }

    public Product(String name, ProductCategory productCategory) {
        this.name = name;
        this.productCategory = productCategory;
    }

    public Integer getProductId() {
        return productId;
    }

    public void setProductId(Integer productId) {
        this.productId = productId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getProductCategoryId() {
        return productCategoryId;
    }

    public void setProductCategoryId(Integer productCategoryId) {
        this.productCategoryId = productCategoryId;
    }

//  public ProductCategory getProductCategory() {
//      return productCategory;
//  }
//
//  public void setProductCategory(ProductCategory productCategory) {
//      this.productCategory = productCategory;
//  }

    public Date getCreated() {
        return created;
    }

    public void setCreated(Date created) {
        this.created = created;
    }

    public Integer getCreatedBy() {
        return createdBy;
    }

    public void setCreatedBy(Integer createdBy) {
        this.createdBy = createdBy;
    }
}

ProductCategory.java:
    @Entity
    public class ProductCategory {

    @Id
    private Integer productCategoryId;
    private String name;
    private Date created;
    private Integer createdBy;

    public ProductCategory() {
    }

    public ProductCategory(Integer productCategoryId, String name, Date created, Integer createdBy) {
        this.productCategoryId = productCategoryId;
        this.name = name;
        this.created = created;
        this.createdBy = createdBy;
    }

    public Integer getProductCategoryId() {
        return productCategoryId;
    }

    public void setProductCategoryId(Integer productCategoryId) {
        this.productCategoryId = productCategoryId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getCreated() {
        return created;
    }

    public void setCreated(Date created) {
        this.created = created;
    }

    public Integer getCreatedBy() {
        return createdBy;
    }

    public void setCreatedBy(Integer createdBy) {
        this.createdBy = createdBy;
    }
}

ProductServiceImpl.java
@Service
@Transactional
public class ProductServiceImpl implements ProductService {

 @Autowired
     private ProductRepository productRepository;

    public Product findOne(int productId) {
        return productRepository.findOne(productId);
    }

    public List<Product> findAll() {
        List<Product> products = new ArrayList<>();
        productRepository.findAll().forEach(products::add);
        return products;
    }

    @Override
    public List<Product> findBatch(int start, int end) {
        return productRepository.findBatch(start, end);
    }
}

ProductController.java:
@RestController
@RequestMapping("/products")
@EnableTransactionManagement
public class ProductController {

    @Autowired
    private ProductService productService;

    @RequestMapping(method = RequestMethod.GET)
    public List<Product> findAll() {
        List<Product> products = productService.findAll();
        return products;
    }

    @RequestMapping(value = "/{productId}", method = RequestMethod.GET)
    public Product findOne(@PathVariable int productId) {
        Product product = productService.findOne(productId);
        return product;
    }

    @RequestMapping(value = "/{start}/{end}", method = RequestMethod.GET)
    public List<Product> findBatch(@PathVariable int start, @PathVariable int end) {
        List<Product> list = productService.findBatch(start, end);
        return list;
    }
}

ApplicationContextConfig.java:
public class ApplicationContextConfig {

    @Bean
    public HibernateJpaSessionFactoryBean sessionFactory(EntityManagerFactory emf) {
        HibernateJpaSessionFactoryBean factory = new HibernateJpaSessionFactoryBean();
        factory.setEntityManagerFactory(emf);
        return factory;
    }
}

The response should also contain a full injected ProductCategory object which it does not.

A: So finally, the solution was to add this to my application.properties file:
spring.jpa.hibernate.ddl-auto=validate
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

The first line checks the presence of columns without changing their structure while the second line changes the default naming strategy that Hibernate validates for and avoids adding underscores to the table names.


text:
Q: Hiding elements with date loop jquery I want to hide elements (div's) but with date loop.
I have this table structure:
HTML

         1

         2

            25/01/2016 13:30

      4

      5

         1

         2

            24/01/2016 13:30

      4

      5

         1

         2

            23/10/2015 13:30

      4

      5

         1

         2

            18/11/2015 13:30

      4

      5

         1

         2

            18/08/2015 13:30

      4

      5

         1

         2

            18/01/2015 13:30

      4

      5

I have this for loop  to obtain the last 6 months.
Jquery

var str="";
 var monthNames = [ "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12" ];

                        for ( var i = 5; i >= 0; i--) {

                      var now = new Date();
                      var date = new Date(now.setMonth(now.getMonth() - i));
                      var datex = ("0" + date.getDate()).slice(-2) + "-" + ("0" + (date.getMonth() + 1)).slice(-2) + "-" + date.getFullYear();

                            str += ""+ monthNames[date.getMonth()] + "/" + date.getFullYear()+"\n";

                    }
                    alert(str);

And I have this code to find every element inside Div and hide/show
$(".container-c table tr td div#step_form_1").each(function()
                  {

                        $(this).find('span').filter(":contains('"+str+"')").length > 0 ? $(this).show() : $(this).parents('div.container-c').fadeOut();
                  });

But the way I put the variable inside filter(":contains('"+str+"')") hides all and not the array.
Here is my fiddle

A: You are actually doing a string concatenation instead of adding the elements into the array. You need to declare the str variable as an array and add the elements into it using push. During your each loop, you can use index of the each function to iterate through the corresponding element in the array.
 var pol = "25/01/2016";
 var str= [];
 var monthNames = [ "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12" ];

                        for ( var i = 5; i >= 0; i--) {

                      var now = new Date();
                      var date = new Date(now.setMonth(now.getMonth() - i));
                      var datex = ("0" + date.getDate()).slice(-2) + "-" + ("0" + (date.getMonth() + 1)).slice(-2) + "-" + date.getFullYear();

                            str.push(monthNames[date.getMonth()] + "/" + date.getFullYear());

                    }
                    alert(str);
                     $(".container-c table tr td div#step_form_1 span").each(function(index)
                  {

                        $(this).filter(":contains('"+str[index]+"')").length > 0 ? $(this).show() : $(this).parents('div.container-c').fadeOut();
                  });

Working example : https://jsfiddle.net/DinoMyte/6x80vabm/24/


text:
Q: Having an int I and number if iterations and a function DrawPoint(x,y) how to draw a circle? So we have a function  DrawPoint(x,y) that draws a point, we have to draw some number of points that would look like a circle. How to create such for(i=0; i<numberOfIterations; i++) to draw a circle?

A: // (cx, cy) is the center of the circle
// r is the circle radius
// the smaller the granularity, the better the circle will look
// to draw only numberOfIterations points, granularity
// should be 2*pi / numberOfIterations

for(i=0; i<2*pi; i+=granularity)
    DrawPoint(cx + r*sin(i), cy + r*cos(i));

A: One of the better algorithms for getting a decent circle is the Bresenham's circle algorithm, also called the Midpoint circle algorith.
The problem with the straight forward, basic circle routines is that they tend to have alias effects and not look right as a result, this algorithm gives a better approximation, though does not strictly fit your for(;;) loop requirement, though it is still an iterative loop.


text:
Q: Approach for server discovery / polling on same network I am writing Java program and I am creating multiple servers, each of them able to connect to multiple clients with threads.
I am looking to make each of them know of the existence of the other, and periodically check if a server has died or a new server has started, with the purpose of storing these in a list (each server has a list of all other servers on the network) and creating a small network.
What are some good approaches to tackling this?


text:
Q: Summarize accomplishing a condition between rows I have a dataframe like this:
Name Start End  Feature
A    50    100   N
A    55    97    R
A    160   200   L
B    300   350   Y
B    310   350   X
B    349   370   M

I would like to get a new dataframe grouping this by first, second and third column, but I would like to get two new variables: one counting the number of times column A is repeates and the other counting the number of different coordinates presenting a low overlapping (say that I want less than a 20% of overlaping, calculating it as length(overlaped_region)/mean(c(length(region1), length(region2)).
How can I achieve that?
I've tryed:
newdf<- df %>% group_by(Names, Start, End) %>% summarise (count(Start), ???)

How can I get a column counting the number of different coordinates overlaping less than 20% for each Name?
Name  Count1  Count2

A       3       2
B       3       2

A: You requested a dplyr solution based on the tag. I hope you don't have too many rows of data.
What you need to do this with dplyr is a non-equi join. The fuzzyjoin package offers this functionality:
library(dplyr)
library(fuzzyjoin)
df %>%
  mutate(Length = 1 + End - Start) %>%
  fuzzy_left_join(., .,
                  by = c("Name" = "Name", "ID" = "ID",
                         "Start" = "End", "End" = "Start"),
                  match_fun = list(`==`,`!=`,`<=`,`>=`)) %>%
  mutate(Overlap = abs(pmax(Start.x,Start.y,na.rm = TRUE) - pmin(End.x,End.y,na.rm=TRUE)),
         Low = Overlap / (Length.x + Length.y)/2 < 0.2) %>%
  group_by(Name.x) %>%
  summarise(Count1 = length(unique(ID.x)), Count2 = sum(!is.na(Low) & !Low))
#  Name.x Count1 Count2
#  <fct>   <int>  <int>
#1 A           3      2
#2 B           6      2

A better plan would likely be to use the GenomicRanges package.


text:
Q: Run AutoIt on remote machine using psexec I am trying to run an AutoIt script on a remote machine.
psexec.exe -accepteula \\remotemachine -u admin -p password "C:\Program Files\AutoIt3\AutoIt3.exe" "C:\Users\admin\runNotepad.au3"

I am trying to open a Notepad from the script and write something in it. I am also writing some logs from the script. Although I can see the logs, but I am not able to see anything happening on the screen.
I tried with argument -i 0 which opens an interactive screen which is not same as running the script on a local machine. Is there any other way to do it?

A: Finally I was able to figure it out. We should first find out the logon session ID of the remote machine for that user. I ran qwinsta command using psexec first to check the session ID
psexec \\remote -u admin -p password  qwinsta

This gives me a list of all the sessions. Checkout the active session the one which has a username associated with it.
In my case it was 2.
Then I ran this command with session ID as 2
psexec.exe -i 2 -accepteula \\remotemachine -u admin -p password "C:\Program Files\AutoIt3\AutoIt3.exe" "C:\Users\admin\runNotepad.au3"

A: Does this work?
#include <Date.au3>
#include <File.au3>

_LaunchProgramOnRemoteComputer("192.168.50.0", "TEST-PC", "usertest", "passtest", "D:\programToExecute.exe", "", True, "15")

; #FUNCTION# ====================================================================================================================
; Name...........: _LaunchProgramOnRemoteComputer
; Description ...: Copy and execute a program on remote computer.
;
; Syntax.........: _LaunchProgramOnRemoteComputer($ipaddress, $domain, $username, $password, $program[, $parameters = ""[, $show = True[, $timeout = "15"]]])
;
; Parameters ....: $ipadress    - IP Address of the remote computer.
;                 $domain     - Active Directory domain name or Remote computer name.
;                 $username - Username of the user who execute the program on the remote computer.
;                 $password - Password of the user who execute the program on the remote computer.
;                 $program      - Local path of the program to execute.
;                 $parameters  - Parameters of the program.
;                 $show     - Display the interaction with the remote Desktop (True or False).
;                 $timeout   - Timeout in seconds (like "20").
;
; Return values .: Success    - Returns the return code of the program executed.
;                 Failure     - 0  and sets @ERROR
;                                            1 : Timeout.
;                                            2 : PsExec service failed to start on the remote computer.
;                                            3 : The program could not be executed.
;
; Author ........: Jeremy Guillot
; Modified.......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......:
; ===============================================================================================================================
Func _LaunchProgramOnRemoteComputer($ipaddress, $domain, $username, $password, $program, $parameters = "", $show = True, $timeout = "15")

    ; We decompose the path of the program.
    Local $sProgramDrive, $sProgramDir, $sProgramFName, $sProgramExt
    _PathSplit($program, $sProgramDrive, $sProgramDir, $sProgramFName, $sProgramExt)

    ; Delete the file on the remote machine.
    RunAsWait($username, $domain, $password, 2, @ComSpec & ' /c del /F \\"' & $ipaddress & "\c$\" & $sProgramFName & $sProgramExt, "", @SW_HIDE)

    ; Copy the program on sharing 'c$' on the remote machine.
    RunAsWait($username, $domain, $password, 2, @ComSpec & ' /c copy /Y "' & $program & '" \\"' & $ipaddress & "\c$\" & $sProgramFName & $sProgramExt, "", @SW_HIDE)

    ; Parameters of the program.
    If $parameters <> "" Then $parameters = " " & $parameters

    ; Display the interaction with the remote Desktop.
    If $show Then
        $show = " -i"
    Else
        $show = ""
    EndIf

    ; Program execution.
    Local $iStdoutg = Run(@comspec & " /c PsExec \\" & $ipaddress & " -u " & $domain & "\" & $username & " -p " & $password & $show & " -h -n " & $timeout & " C:\" & $sProgramFName & $sProgramExt & $parameters, @ScriptDir & "\Tools\PsTools\", @SW_HIDE, 6)
    Local $sTimeoutBegin = _NowCalc()
    Local $sCommandResult = ""
    Local $sCurrentLine = ""
    While True
        If _DateDiff("s", $sTimeoutBegin, _NowCalc()) > $timeout Then
            ProcessClose("PsExec.exe")
            ProcessClose("PSEXESVC.exe")
            Return SetError(1, 0, 0)
        EndIf
        $sCurrentLine = StderrRead($iStdoutg)
        If @error Then ExitLoop
        If $sCurrentLine <> "" Then
            $sCommandResult = $sCommandResult & @CRLF & $sCurrentLine
        EndIf
    WEnd
    ;If $sCommandResult <> "" Then ConsoleWrite($sCommandResult & @CRLF)

    ; Closing the PsExec process in case they would not shut.
    ProcessClose("PsExec.exe")
    ProcessClose("PSEXESVC.exe")

    ; Remove the program on the remote machine.
    RunAsWait($username, $domain, $password, 2, @ComSpec & ' /c del /F \\"' & $ipaddress & "\c$\" & $sProgramFName & $sProgramExt, "", @SW_HIDE)

    ; Error handling.
    Local $bServiceStarted = False
    Local $bCommandExecuted = False
    Local $bCommandFinished = False
    If StringInStr($sCommandResult, "Connecting with PsExec service on") And Not $bServiceStarted Then $bServiceStarted = True
    If StringInStr($sCommandResult, "Starting " & $program & " on") And Not $bCommandExecuted Then $bCommandExecuted = True
    If StringInStr($sCommandResult, " exited on " & $ipaddress & " with error code") And Not $bCommandFinished Then $bCommandFinished = True

    If $bCommandFinished Then
        ; We get the return code of the program.
        $sCommandResult = StringStripCR(StringStripWS(StringStripWS($sCommandResult, 1), 2))
        Local $sCommandResultCodePosition = StringInStr($sCommandResult, "with error code ")
        $sCommandResult = StringTrimLeft($sCommandResult, $sCommandResultCodePosition)
        $sCommandResult = StringTrimLeft($sCommandResult, 15)
        $sCommandResult = StringTrimRight($sCommandResult, 1)
    Else
         If Not $bServiceStarted Then Return SetError(2, 0, 0)
         If Not $bCommandExecuted Then Return SetError(3, 0, 0)
    EndIf

     Return SetError(0, 0, $sCommandResult)

EndFunc

A: What OS are you using?  If it's Vista or later, did you try argument -i 1 ?  I believe session 0 is reserved for Windows services:  http://blogs.technet.com/b/askperf/archive/2007/04/27/application-compatibility-session-0-isolation.aspx


text:
Q: How much is right to do something? I have a question about the expression "How much is right to do something?".
Is it correct at all? I mean, when someone proposes me to do something, but I have a doubt about that action I ask "How much is right to do it?". Or should we ask "How much is it right to do it?" or in any other way?

A: To explore the origin of that it, let's take an example sentence:

Playing practical jokes is acceptable.

In order to ascertain the extent to which it is acceptable to play practical jokes, you first remodel the sentence:

It is acceptable to play practical jokes.  (It is a dummy pronoun)

Next, you reverse the subject "it" and the auxiliary verb "is": it is -> is it:

Is it acceptable to play practical jokes?

Next, you add an adverbial phrase, such as "to what extent":

To what extent is it acceptable to play practical jokes?

Or, simply move the adjective "acceptable" in this adverbial position and add "how":

How acceptable is it to play practical jokes?

It a similar vein, your sentence should have that it:

How proper is it to do something?

I changed "right" to "proper" and ditched "much" to comply with FumbleFinger's comments.

A: No, it is not correct, as @CopperKettle's answer explains.
However, in your situation:

someone proposes me to do something, but I have a doubt about that action

A more normal way to voice your doubt, asking if it's right to do what they propose, would be to just ask someone:

Is it right [to do that proposed thing]?

Or, to emphasize that

*

*someone suggested the action

*and you doubt it:

Is it really right [to do that proposed thing]?

You can replace "right" with synonyms like "ok", "proper", "acceptable", "correct", etc.
Unless I misunderstood your description of the situation, I think that final example would be the most idiomatic way to say it.

A: I wouldn't use that phrase at all, but instead say "How much should I do it?"
This flows much better.


text:
Q: Extract data from paginated database entries and pass to a form Stack Overflow won't allow me to post more than 2 hyperlinks and I need three, so to see my inquiry properly, please click on the link below:
http://bretleduc.com/inquiry.htm
This page I made:
[Paginated Data][1]
Shows questions/comments that people have entered in the following page:
[Contact Artist][2]
The theory is, once someone posts a comment or question, the artist (Jackson David, whom I'm making this page for) can see the comment and respond to it in the [Respond to a Question or Comment][3] page.  But right now, the artist has to copy and paste the Name and Email Address from the [Paginated Data][1] section to the [Respond to a Question or Comment][3] form.
What I'm trying to do is modify the [Paginated Data][1] page to include the ability to select an entry and have the Name and Email Address populate the Name and Email Address fields in another form.  This way, the artist can answer the customer's queries easier by just clicking on the paginated entry (maybe using a radio button for example) and having the customer's Name and Email Address automatically populate into the following form:
[Respond to a Question or Comment][3]
Here is the code for the [Paginated Data][1] page which I got from a script site:
<?php
// Adam's Custom PHP MySQL Pagination Tutorial and Script
// You have to put your mysql connection data and alter the SQL queries(both queries)
// This script is in tutorial form and is accompanied by the following video:
// http://www.youtube.com/watch?v=K8xYGnEOXYc
require("hidden.php");
//////////////  QUERY THE MEMBER DATA INITIALLY LIKE YOU NORMALLY WOULD
$sql = mysql_query("SELECT Comment_ID, Name, email, Comment FROM Comments ORDER BY Comment_ID DESC");
//////////////////////////////////// Adam's Pagination Logic ////////////////////////////////////////////////////////////////////////
$nr = mysql_num_rows($sql); // Get total of Num rows from the database query
if (isset($_GET['pn'])) { // Get pn from URL vars if it is present
    $pn = preg_replace('#[^0-9]#i', '', $_GET['pn']); // filter everything but numbers for security(new)
    //$pn = ereg_replace("[^0-9]", "", $_GET['pn']); // filter everything but numbers for security(deprecated)
} else { // If the pn URL variable is not present force it to be value of page number 1
    $pn = 1;
}
//This is where we set how many database items to show on each page
$itemsPerPage = 2;
// Get the value of the last page in the pagination result set
$lastPage = ceil($nr / $itemsPerPage);
// Be sure URL variable $pn(page number) is no lower than page 1 and no higher than $lastpage
if ($pn < 1) { // If it is less than 1
    $pn = 1; // force if to be 1
} else if ($pn > $lastPage) { // if it is greater than $lastpage
    $pn = $lastPage; // force it to be $lastpage's value
}
// This creates the numbers to click in between the next and back buttons
// This section is explained well in the video that accompanies this script
$centerPages = "";
$sub1 = $pn - 1;
$sub2 = $pn - 2;
$add1 = $pn + 1;
$add2 = $pn + 2;
if ($pn == 1) {
    $centerPages .= '  ' . $pn . '  ';
    $centerPages .= '  ' . $add1 . '  ';
} else if ($pn == $lastPage) {
    $centerPages .= '  ' . $sub1 . '  ';
    $centerPages .= '  ' . $pn . '  ';
} else if ($pn > 2 && $pn < ($lastPage - 1)) {
    $centerPages .= '  ' . $sub2 . '  ';
    $centerPages .= '  ' . $sub1 . '  ';
    $centerPages .= '  ' . $pn . '  ';
    $centerPages .= '  ' . $add1 . '  ';
    $centerPages .= '  ' . $add2 . '  ';
} else if ($pn > 1 && $pn < $lastPage) {
    $centerPages .= '  ' . $sub1 . '  ';
    $centerPages .= '  ' . $pn . '  ';
    $centerPages .= '  ' . $add1 . '  ';
}
// This line sets the "LIMIT" range... the 2 values we place to choose a range of rows from database in our query
$limit = 'LIMIT ' .($pn - 1) * $itemsPerPage .',' .$itemsPerPage;
// Now we are going to run the same query as above but this time add $limit onto the end of the SQL syntax
// $sql2 is what we will use to fuel our while loop statement below
$sql2 = mysql_query("SELECT Comment_ID, Name, email, Comment FROM Comments ORDER BY Comment_ID DESC $limit");
//////////////////////////////// END Adam's Pagination Logic ////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////// Adam's Pagination Display Setup /////////////////////////////////////////////////////////////////////
$paginationDisplay = ""; // Initialize the pagination output variable
// This code runs only if the last page variable is ot equal to 1, if it is only 1 page we require no paginated links to display
if ($lastPage != "1"){
    // This shows the user what page they are on, and the total number of pages
    $paginationDisplay .= 'Page ' . $pn . ' of ' . $lastPage. '        ';
    // If we are not on page 1 we can place the Back button
    if ($pn != 1) {
        $previous = $pn - 1;
        $paginationDisplay .=  '    Back ';
    }
    // Lay in the clickable numbers display here between the Back and Next links
    $paginationDisplay .= '' . $centerPages . '';
    // If we are not on the very last page we can place the Next button
    if ($pn != $lastPage) {
        $nextPage = $pn + 1;
        $paginationDisplay .=  '    Next ';
    }
}
///////////////////////////////////// END Adam's Pagination Display Setup ///////////////////////////////////////////////////////////////////////////
// Build the Output Section Here
$outputList = '';
while($row = mysql_fetch_array($sql2)){

    $Comment_ID = $row["Comment_ID"];
    $Name = $row["Name"];
    $email = $row["email"];
    $Comment = $row["Comment"];

    $outputList .= '
' . $Name . '

' . $email . '
' . $Comment . '

';

} // close while loop
?>

<title>Adam's Pagination</title>

Total Items: <?php echo $nr; ?>

<?php echo $paginationDisplay; ?>

<?php print "$outputList"; ?>

<?php echo $paginationDisplay; ?>

I think I need to put some sort of form in the following line from the code:
$outputList .= '
' . $Name . '

' . $email . '
' . $Comment . '

';

Further, it would be a bonus if we could make the selection of the entry automatically post the Name and Email Address to the
[Respond to a Question or Comment][3]
form without having to click a submit button.
If it would be easier to combine the code of [Paginated Data][1] and the code of [Respond to a Question or Comment][3] into one page, I can do that too.
Thanks all!

A: I finally got the page to work through blood sweat and tears. I removed some isset coding that was cluttering the input fields. I also changed the process from _POST to _GET.
Thanks for all your help!


text:
Q: How to handle many API calls with Swift 3 GCD I am building an swift app to interact with an MDM API to do large numbers of updates via PUT commands, and I am running in to issues with how to handle the massive numbers of API calls without overloading the servers.
I am parsing through a CSV, and each line is an update. If I run the commands asynchronously, it generates and sends ALL of the API calls immediately, which the server doesn't like.
But if I run the commands synchronously, it freezes my GUI which is less than ideal, as the end user doesn't know what's going on, how long is left, if things are failing, etc.
I have also tried creating my own NSOperation queue and setting the max number of items to like 5, and then putting the synchronous function in there, but that doesn't seem to work very well either. It still freezes the GUI with some really random UI updates that seem buggy at best.
The servers can handle 5-10 requests at a time, but these CSV files can be upwards of 5,000 lines sometimes.
So how can I limit the number of simultaneous PUT requests going out in my loop, while not having the GUI freeze on me? To be honest, I don't even really care if the end user can interact with the GUI while it's running, I just want to be able to provide feedback on the lines that have run so far.

I have a wrapper which a colleague wrote most of, and the async function looks like this:
func sendRequest(endpoint: String, method: HTTPMethod, base64credentials: String, dataType: DataType, body: Data?, queue: DispatchQueue, handler: @escaping (Response)->Swift.Void) {
    let url = self.resourceURL.appendingPathComponent(endpoint)
    var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 30.0)
    request.httpMethod = "\(method)"

    var headers = ["Authorization": "Basic \(base64credentials)"]
    switch dataType {
    case .json:
        headers["Content-Type"] = "application/json"
        headers["Accept"] = "application/json"
        if let obj = body {
            do {
                request.httpBody = try JSONSerialization.data(withJSONObject: obj, options: JSONSerialization.WritingOptions(rawValue: 0))
            } catch {
                queue.async {
                    handler(.badRequest)
                }
                return
            }
        }
    case .xml:
        headers["Content-Type"] = "application/xml"
        headers["Accept"] = "application/xml"
        request.httpBody = body
        /*if let obj = body {
            request.httpBody = (obj as! XMLDocument).xmlData
        }*/
    }
    request.allHTTPHeaderFields = headers

    session.dataTask(with: request) {
        var response: Response
        if let error = $2 {
            response = .error(error)
        } else {
            let httpResponse = $1 as! HTTPURLResponse
            switch httpResponse.statusCode {
            case 200..<299:
                if let object = try? JSONSerialization.jsonObject(with: $0!, options: JSONSerialization.ReadingOptions(rawValue: 0)) {
                    response = .json(object)
                } else if let object = try? XMLDocument(data: $0!, options: 0) {
                    response = .xml(object)
                } else {
                    response = .success
                }
            default:
                response = .httpCode(httpResponse.statusCode)
            }
        }

        queue.async {
            handler(response)
        }
        }.resume()

Then, there is a synchronous option which uses semaphore, which looks like this:
    func sendRequestAndWait(endpoint: String, method: HTTPMethod, base64credentials: String, dataType: DataType, body: Data?) -> Response {
    var response: Response!
    let semephore = DispatchSemaphore(value: 0)
    sendRequest(endpoint: endpoint, method: method, base64credentials: base64credentials, dataType: dataType, body: body, queue: DispatchQueue.global(qos: .default)) {
        response = $0
        semephore.signal()
    }
    semephore.wait()
    return response
}

Usage information is as follows:
class ViewController: NSViewController {

let client = JSSClient(urlString: "https://my.mdm.server:8443/", allowUntrusted: true)
let credentials = JSSClient.Credentials(username: "admin", password: "ObviouslyNotReal")

func asynchronousRequestExample() {
    print("Sending asynchronous request")

    client.sendRequest(endpoint: "computers", method: .get, credentials: credentials, dataType: .xml, body: nil, queue: DispatchQueue.main) { (response) in

        print("Response recieved")

        switch response {
        case .badRequest:
            print("Bad request")
        case .error(let error):
            print("Receieved error:\n\(error)")
        case .httpCode(let code):
            print("Request failed with http status code \(code)")
        case .json(let json):
            print("Received JSON response:\n\(json)")
        case .success:
            print("Success with empty response")
        case .xml(let xml):
            print("Received XML response:\n\(xml.xmlString(withOptions: Int(XMLNode.Options.nodePrettyPrint.rawValue)))")
        }

        print("Completed")
    }

    print("Request sent")

}

func synchronousRequestExample() {
    print("Sending synchronous request")

    let response = client.sendRequestAndWait(endpoint:  "computers", method: .get,credentials: credentials, dataType: .json, body: nil)

    print("Response recieved")

    switch response {
    case .badRequest:
        print("Bad request")
    case .error(let error):
        print("Receieved error:\n\(error)")
    case .httpCode(let code):
        print("Request failed with http status code \(code)")
    case .json(let json):
        print("Received JSON response:\n\(json)")
    case .success:
        print("Success with empty response")
    case .xml(let xml):
        print("Received XML response:\n\(xml.xmlString(withOptions: Int(XMLNode.Options.nodePrettyPrint.rawValue)))")
    }

    print("Completed")
}

override func viewDidAppear() {
    super.viewDidAppear()
    synchronousRequestExample()
    asynchronousRequestExample()

}

I have modified the send functions slightly, so that they take base64 encoded credentials off the bat, and maybe one or two other things.

A: Can't you just chain operations to send 3/4 requests at a time per operation?
https://www.raywenderlich.com/76341/use-nsoperation-nsoperationqueue-swift
Just so you know, NSOperation (also abstracted by Operation with Swift3) are running by default on background threads. Just be careful to not run heavy tasks in your completion block that might run tasks on the main thread (this will freeze your UI).
The only other case I see that can freeze your UI is by executing too many operations at once.

A: Well, I think I got this covered! I decided to climb out of the rabbit hole a ways and simplify things. I wrote my own session instead of relying on the wrapper, and set up semaphores in it, threw it in an OperationQueue and it seems to be working perfectly.
This was the video I followed to set up my simplified semaphores request. https://www.youtube.com/watch?v=j4k8sN8WdaM
I'll have to tweak the below code to be a PUT instead of the GET I've been using for testing, but that part is easy.
//print (row[0])
    let myOpQueue = OperationQueue()
    myOpQueue.maxConcurrentOperationCount = 3
    let semaphore = DispatchSemaphore(value: 0)
    var i = 0
    while i < 10 {
        let myURL = NSURL(string: "https://my.server.com/APIResources/computers/id/\(i)")
        myOpQueue.addOperation {

            let request = NSMutableURLRequest(url: myURL! as URL)
            request.httpMethod = "GET"
            let configuration = URLSessionConfiguration.default
            configuration.httpAdditionalHeaders = ["Authorization" : "Basic 123456789ABCDEFG=", "Content-Type" : "text/xml", "Accept" : "text/xml"]
            let session = Foundation.URLSession(configuration: configuration)
            let task = session.dataTask(with: request as URLRequest, completionHandler: {
                (data, response, error) -> Void in
                if let httpResponse = response as? HTTPURLResponse {
                    print(httpResponse.statusCode)
                    semaphore.signal()
                    self.lblLine.stringValue = "\(i)"
                    self.appendLogString(stringToAppend: "\(httpResponse.statusCode)")
                    print(myURL!)

                }
                if error == nil {
                    print("No Errors")
                    print("")
                } else {
                    print(error!)
                }
            })

            task.resume()
            semaphore.wait()

        }
        i += 1
    }


text:
Q: RegEx: Check for char at the start of string Some information:
I've got a Delphi XE Regular Expression:
(?<=[*+\/drt><=≥≤≠])\-

Inputstring:
-(2*3)

The RegEx must match a '-' that makes an expression negative. So for example:
-(2*3) //Must Match

But not:
2 - 3 //Must not Match

In the example above, the operator works as a minus, it does not make the whole expression negative.
My solution for this is my regular expression above, it only matches a minus after an operator. It won't match if the char before the minus is an variable, number or some other defined keywords.
My problem
If the minus is at the start of the string, the regular expression does not match, because there is no char in front, even though the character makes the whole expression negative. How can I match this minus, even if it's at the beginning of the string and has no character in front?

A: To match either start of string or a char inside the positive character class is
(?<=^|[*+/drt><=≥≤≠])-
    ^^

See the online demo.
However, if you only deal with standalone strings, it is more efficient to convert the positive lookbehind withj a positive character class and an alternative to a negative lookbehind with a negative character class:
(?<![^*+/drt><=≥≤≠])-

See another regex demo. Only test one string after another, not all in a multiline mode.
Note you do not need to escape - outside a character class. No need to escape the / char either, it is not a special regex metacharacter, and you do not need to use it as a regex delimiter in Delphi.

A: Maybe can you try?
(\-\().+(\))

Starts with "-(", any character, followed by ")".
Resulting...
-(2*3) //Must Match
2 - 3 //Must not Match
test -(2*3) //Must Match??
test -( 2*3 ) //Must Match??
test -() //Must not Match??
test -( ) //Must Match??


text:
Q: Riemann integrable or not? Let $(a_n)_1^\infty$ be an increasing sequence in $(0,1)$ with limit $1$ and define $f:[0,1]\to\mathbb{R}$ such that $f(x)=1$ if $x=a_n$ for some $n\in\mathbb{N}$ and $f(x)=0$ otherwise. Is $f$ Riemann integrable on $[0,1]$?
I think it is Riemann integrable since $f$ is bounded and has a countable number of discontinuities, namely the $a_n$'s. But I don't know how to rigorously show it.

A: Yes, it is integrable and its integral on $[0,1]$is $0$
There are only a countable set of discontinuity at your function which makes it integrable.

A: You are right about the Lebesgue criterion. Here is a proof of discontinuity.
Rigorous proof.
$\blacktriangleleft$ Suppose $a_n$'s are mutually distinct [otherwise we could discard those terms with repeated values]. In other words $(a_n)$ is increasing strictly. Take $\varepsilon_0 = 1/2$, then for each $a_n \in [0,1]$, for all $\delta \colon 0< \delta <\min\{a_{n+1}-a_n, a_n - a_{n-1}\}$, there is $x = a_n+\delta/2 \in (a_n -\delta, a_n+ \delta)$ s.t. $$|f(x)-f(a_n)| =|0-1|=1 >1/2 =\varepsilon _0.$$Hence $f$ is not continuous at $a_n \blacktriangleright$.

A: Since the set
$$\{a_n | n\in \mathbb{N}\}$$
is countable, it is of measure zero, and it is clear that this set is also the set of discontinuities of $f$ (see @xbh's answer), hence by Lebesgue criterion, $f$ is Riemann integrable on [0,1].


text:
Q: Unix change desktop background seamlessly So i have a python script which generates an image, and saves over the old image which used to be the background image.
I tried to make it run using crontab, but couldn't get that to work, so now i just have a bash script which runs once in my .bashrc whdn i first log in (i have a if [ firstRun ] kind of thing in there).
The problem is, that every now and then, when the background updates, it flashes black before it does - which is not very nice!
I currently have it running once a second, but i don't think it's the python that is causing the black screens, and more the way the image is changed over...
Is there a way I can prevent these ugly black screens between updates?
Here's all the code to run it, if you want to try it out...
from PIL import Image, ImageDraw, ImageFilter
    import colorsys
    from random import gauss
xSize, ySize = 1600,900

im = Image.new('RGBA', (xSize, ySize), (0, 0, 0, 0))
draw = ImageDraw.Draw(im)

class Cube(object):
    def __init__(self):
        self.tl = (0,0)
        self.tm = (0,0)
        self.tr = (0,0)
        self.tb = (0,0)
        self.bl = (0,0)
        self.bm = (0,0)
        self.br = (0,0)

    def intify(self):
        for prop in [self.tl, self.tm, self.tr, self.tb, self.bl, self.bm, self.br]:
            prop = [int(i) for i in prop]

def drawCube((x,y), size, colour=(255,0,0)):

    p = Cube()

    colours = [list(colorsys.rgb_to_hls(*[c/255.0 for c in colour])) for _ in range(3)]
    colours[0][1] -= 0
    colours[1][1] -= 0.2
    colours[2][1] -= 0.4
    colours = [tuple([int(i*255) for i in colorsys.hls_to_rgb(*colour)]) for colour in colours]

    p.tl = x,y #Top Left
    p.tm = x+size/2, y-size/4 #Top Middle
    p.tr = x+size, y #Top Right
    p.tb = x+size/2, y+size/4 #Top Bottom
    p.bl = x, y+size/2 #Bottom Left
    p.bm = x+size/2, y+size*3/4 #Bottom Middle
    p.br = x+size, y+size/2 #Bottom Right

    p.intify()

    draw.polygon((p.tl, p.tm, p.tr, p.tb), fill=colours[0])
    draw.polygon((p.tl, p.bl, p.bm, p.tb), fill=colours[1])
    draw.polygon((p.tb, p.tr, p.br, p.bm), fill=colours[2])

    lineColour = (0,0,0)
    lineThickness = 2

    draw.line((p.tl, p.tm), fill=lineColour, width=lineThickness)
    draw.line((p.tl, p.tb), fill=lineColour, width=lineThickness)
    draw.line((p.tm, p.tr), fill=lineColour, width=lineThickness)
    draw.line((p.tb, p.tr), fill=lineColour, width=lineThickness)
    draw.line((p.tl, p.bl), fill=lineColour, width=lineThickness)
    draw.line((p.tb, p.bm), fill=lineColour, width=lineThickness)
    draw.line((p.tr, p.br), fill=lineColour, width=lineThickness)
    draw.line((p.bl, p.bm), fill=lineColour, width=lineThickness)
    draw.line((p.bm, p.br), fill=lineColour, width=lineThickness)

# -------- Actually do the drawing

size = 100

#Read in file of all colours, and random walk them
with open("/home/will/Documents/python/cubeWall/oldColours.dat") as coloursFile:
    for line in coloursFile:
        oldColours = [int(i) for i in line.split()]

oldColours = [int(round(c + gauss(0,1.5)))%255 for c in oldColours]

colours = [[ int(c*255) for c in colorsys.hsv_to_rgb(i/255.0, 1, 1)] for i in oldColours]

with open("/home/will/Documents/python/cubeWall/oldColours.dat", "w") as coloursFile:
    coloursFile.write(" ".join([str(i) for i in oldColours]) + "\n")

for i in range(xSize/size+2):
    for j in range(2*ySize/size+2):
        if j%3 == 0:
            drawCube((i*size,j*size/2), size, colour=colours[(i+j)%3])
        elif j%3 == 1:
            drawCube(((i-0.5)*size,(0.5*j+0.25)*size), size, colour=colours[(i+j)%3])

im2 = im.filter(ImageFilter.SMOOTH)
im2.save("cubes.png")
#im2.show()

and then just run this:
#!/bin/sh
while [ 1 ]
do
    python drawCubes.py
sleep 1
done

And set the desktop image to be cubes.png

A: Well, you can change the current wallaper (in Gnome 3 compatible desktops) by running
import os
os.system("gsettings set org.gnome.desktop.background picture-uri file://%(path)s" % {'path':absolute_path})
os.system("gsettings set org.gnome.desktop.background picture-options wallpaper")

A: If you're using MATE, you're using a fork of Gnome 2.x. The method I found for Gnome 2 is : gconftool-2 --set --type string --set /desktop/gnome/background/picture_filename <absolute image path>.
The method we tried before would have worked in Gnome Shell.


text:
Q: MySQL count number occurrences I have this 2 tables:
Category:
cat_id|cat_type
   1  |    a
   2  |    b
   3  |    c
   4  |    d

and have
Meta:
met_id|met_name|user_id|met_type
   10 |  bla   |   2   |    1
   11 | blabla |   4   |    2
   12 |  foo   |   1   |    3
   13 | blafoo |   3   |    4
   14 | foofoo |   5   |    4

How can I return something like this ?
cat_type|occurences
  a   |     1
  b   |     1
  c   |     1
  d   |     2

met_type is a foreign key from Category.

A: SELECT c.cat_type
     , COUNT(m.met_type) AS  occurrences
FROM categoty c LEFT JOIN meta m ON c.cat_id = m.met_type
GROUP BY c.cat_type

A: SELECT cate.cat_type as 'cat_id', count(meta.met_type) as 'occurences'
FROM Category cate
LEFT JOIN Meta meta on(cate.cat_id = meta.met_type)
GROUP BY meta.met_type


text:
Q: Erro de stack overflow ao validar DateTime no setter Tenho uma classe chamada Appointment com um atributo string (que quero, em outra etapa do projeto, transformá-lo em DateTime) cujo setter usa o método DateTime.TryParse() para verificar se a String pode ser convertida para DateTime, da seguinte forma:
class Appointment
{
    DateTime dateValue; //Used for validation with DateTime.TryParse()
    public string Content { get; set; }
    private bool ValidDate;
    public string Date
    {
        get { return Date; }
        set
        {
            if (DateTime.TryParse(value, out dateValue))
            {
                this.Date = value;
                ValidDate = true;
            }
        }
    }

Já em outra classe, tenho um List que armazena abjetos da classe citada acima. Nela tenho um método chamado Insert_appoint() para instanciar e inserir um objeto do tipo Appointment dentro do List:
    private List<Appointment> Appointments = new List<Appointment>();
    public void Insert_Appoint(string element, string date)
    {
        Appointment Appoint = new(element, date);
        Appointments.Add(Appoint);
    }

Quando tento fazer fazer a operação na classe Main, mesmo usando como parâmetro uma String compatível com DateTime:
Schedule schedule = new Schedule();
schedule.Insert_Appoint("Do something", "15, 5, 2020");

ocorre um erro de Stack Overflow
O que pode estar ocorrendo? Há alguma outra maneira de fazer essa validação? Ou então se eu estou usando a função DateTime.TryParse() de forma errada.

A: Este é o problema:
this.Date

Dentro do método que seta o Date o código está setando o Date, então ele cria uma execução recursiva sem fim, conforme mostra a imagem. Provavelmente quer algo assim:
using System;

public class Appointment {
    public string Content { get; set; }
    private bool validDate = false;
    private DateTime date;
    public string Date {
        get { return Date.ToString(); }
        set {
            if (DateTime.TryParse(value, out var dateValue)) {
                date = dateValue;
                validDate = true;
            }
        }
    }
}

Coloquei no GitHub para referência futura.
Eu inclusive dei uma melhorada no código, mas ele ainda parece errado, não posso afirmar qual é o certo sem saber o objetivo, mas nem parece que a propriedade desta forma deveria existir, algo assim parece fazer mais sentido:
using System;

public class Appointment {
    public string Content { get; set; }
    private bool validDate = false;
    public DateTime Date { get; set; }
    public void SetDate(string date) {
        if (DateTime.TryParse(date, out var dateValue)) {
            Date = dateValue;
            validDate = true;
        }
    }
}

Coloquei no GitHub para referência futura.
Talvez possa deixar mudar a data de forma direta quando já tiver uma data, mas novamente, depende do objetivo.
Isso sequer é uma validação de fato. É só uma forma de ter um agendamento inicial sem uma data qualquer, o que costuma ser conceitualmente errado, mas não vou tentar resolver dos problemas da aplicação sem a conhecer detalhadamente.
A classe não está completa.


text:
Q: What port is used to send request by an Express app? I have an Express app A, that is configured to listen on 4455 port.
The app also uses axios to send requests to a different server B.
The server B is configured such that it replies to host:port from which it recieved the request.
In this case server A can't recieve response from B, because in the request the,  port of A keeps changing.
Does express server send and receive messages from the same port?

A: The port on which Express listens for incoming connections has nothing to do with the port used for requests that happen to be made from the same application.
Requests are typically made from a random(-ish) port, and it would require some effort if you want that port to be fixed (always the same). In fact, I'm not even sure if you can make axios use a specific local port from which it makes requests.
That leaves the following solution: you make a request using axios, somehow (I'm not sure how) record from which local port that request is being made, and after the request has finished, create a temporary (Express) server that listens for the response on that same local port. When server B has sent its response (or after a specific timeout), that server is stopped.
To be honest, the way that server B sends back its responses is quite uncommon, especially since requests are almost always made from a random port. I also don't understand why server B cannot send back the response over the existing connection.


text:
Q: curl via Jenkins only works sometimes I want to upload some files via ftp using curl command inside Jenkins Pipeline. The command I use looks like this:
sh "curl --verbose -T my.file --proxytunnel --proxy http://${PROXY_USER}:${PROXY_PASS}@MYPROXY:MYPROXYPORT ftp://${AZURE_USER}:${AZURE_PASS}@MYSITE.ftp.azurewebsites.windows.net/site/wwwroot/"

Sometimes, I click on "Build"-button in Jenkins 5 times in a row and all 5 builds are successful. Then, 10 minutes later, I click again the build-button and it fails 5 times in a row - without changing anything inside the Jenkins Job!
So it looks to me as if there is sometimes some kind of session cached and sometimes not. But I don't know which kind of session, because I set {http|https|ftp|no}_proxy, PROXY_USER and AZURE_USER.
Here is the error message when the build fails:
* About to connect() to proxy MYPROXY port 80 (#0)
*   Trying 1.2.3.4... connected
* Connected to MYPROXY (1.2.3.4) port 80 (#0)
* Establish HTTP proxy tunnel to MYSITE.ftp.azurewebsites.windows.net:21
* Proxy auth using Basic with user '****'
* Server auth using Basic with user 'MYUSER\****'
> CONNECT MYSITE.ftp.azurewebsites.windows.net:21 HTTP/1.1
> Host: MYSITE.ftp.azurewebsites.windows.net:21
> Proxy-Authorization: Basic xxx-xxx-xxx
> User-Agent: curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.27.1 zlib/1.2.3 libidn/1.18 libssh2/1.4.2
> Proxy-Connection: Keep-Alive
>
< HTTP/1.1 200 Connection Established
< Proxy-Agent: Zscaler/6.0
<
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed

  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0* Proxy replied OK to CONNECT request
< 220 Microsoft FTP Service
> USER MYUSER\****
< 331 Password required
> PASS ****
< 230 User logged in.
> PWD
< 257 "/" is current directory.
* Entry path is '/'
> CWD site
< 250 CWD command successful.
> CWD wwwroot
< 250 CWD command successful.
> EPSV
* Connect data stream passively
< 229 Entering Extended Passive Mode (|||10201|)
*   Trying 1.2.3.4... connected
* Connecting to MYSITE.ftp.azurewebsites.windows.net (1.2.3.4) port 80
* Establish HTTP proxy tunnel to MYSITE.ftp.azurewebsites.windows.net:10201
* Proxy auth using Basic with user '****'
* Server auth using Basic with user 'MYUSER\****'
> CONNECT MYSITE.ftp.azurewebsites.windows.net:10201 HTTP/1.1
> Host: MYSITE.ftp.azurewebsites.windows.net:10201
> Proxy-Authorization: Basic xxxxx
> User-Agent: curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.27.1 zlib/1.2.3 libidn/1.18 libssh2/1.4.2
> Proxy-Connection: Keep-Alive
>
< HTTP/1.1 200 Connection Established
< Proxy-Agent: Zscaler/6.0
<

  0     0    0     0    0     0      0      0 --:--:--  0:00:02 --:--:--     0* Proxy replied OK to CONNECT request
> TYPE I
< 200 Type set to I.
> STOR web.config
< 150 Opening BINARY mode data connection.
} [data not shown]

104   521    0     0  104   521      0    201  0:00:02  0:00:02 --:--:--   204* Remembering we are in dir "site/wwwroot/"

104   521    0     0  104   521      0    145  0:00:03  0:00:03 --:--:--   146
104   521    0     0  104   521      0    113  0:00:04  0:00:04 --:--:--   114
104   521    0     0  104   521      0     93  0:00:05  0:00:05 --:--:--    93
104   521    0     0  104   521      0     79  0:00:06  0:00:06 --:--:--   128
104   521    0     0  104   521      0     68  0:00:07  0:00:07 --:--:--     0
104   521    0     0  104   521      0     60  0:00:08  0:00:08 --:--:--     0
104   521    0     0  104   521      0     54  0:00:09  0:00:09 --:--:--     0
104   521    0     0  104   521      0     49  0:00:10  0:00:10 --:--:--     0
104   521    0     0  104   521      0     44  0:00:11  0:00:11 --:--:--     0
104   521    0     0  104   521      0     41  0:00:12  0:00:12 --:--:--     0
104   521    0     0  104   521      0     38  0:00:13  0:00:13 --:--:--     0
104   521    0     0  104   521      0     35  0:00:14  0:00:14 --:--:--     0
104   521    0     0  104   521      0     33  0:00:15  0:00:15 --:--:--     0
104   521    0     0  104   521      0     31  0:00:16  0:00:16 --:--:--     0
104   521    0     0  104   521      0     29  0:00:17  0:00:17 --:--:--     0
104   521    0     0  104   521      0     28  0:00:18  0:00:18 --:--:--     0
104   521    0     0  104   521      0     26  0:00:20  0:00:19  0:00:01     0
104   521    0     0  104   521      0     25  0:00:20  0:00:20 --:--:--     0
104   521    0     0  104   521      0     24  0:00:21  0:00:21 --:--:--     0
104   521    0     0  104   521      0     23  0:00:22  0:00:22 --:--:--     0
104   521    0     0  104   521      0     22  0:00:23  0:00:23 --:--:--     0
104   521    0     0  104   521      0     21  0:00:24  0:00:24 --:--:--     0
104   521    0     0  104   521      0     20  0:00:26  0:00:25  0:00:01     0
104   521    0     0  104   521      0     19  0:00:27  0:00:26  0:00:01     0
104   521    0     0  104   521      0     18  0:00:28  0:00:27  0:00:01     0
104   521    0     0  104   521      0     18  0:00:28  0:00:28 --:--:--     0
104   521    0     0  104   521      0     17  0:00:30  0:00:29  0:00:01     0
104   521    0     0  104   521      0     17  0:00:30  0:00:30 --:--:--     0
104   521    0     0  104   521      0     16  0:00:32  0:00:31  0:00:01     0
104   521    0     0  104   521      0     15  0:00:34  0:00:32  0:00:02     0
104   521    0     0  104   521      0     15  0:00:34  0:00:33  0:00:01     0
104   521    0     0  104   521      0     15  0:00:34  0:00:34 --:--:--     0
104   521    0     0  104   521      0     14  0:00:37  0:00:35  0:00:02     0
104   521    0     0  104   521      0     14  0:00:37  0:00:36  0:00:01     0
104   521    0     0  104   521      0     13  0:00:40  0:00:37  0:00:03     0
104   521    0     0  104   521      0     13  0:00:40  0:00:38  0:00:02     0
104   521    0     0  104   521      0     13  0:00:40  0:00:39  0:00:01     0
104   521    0     0  104   521      0     12  0:00:43  0:00:40  0:00:03     0< 425 Data channel timed out.
* server did not report OK, got 425

104   521    0     0  104   521      0     12  0:00:43  0:00:40  0:00:03     0* Connection #0 to host MYPROXY left intact

curl: (18) server did not report OK, got 425
> QUIT
< 221 Goodbye.
* Closing connection #0

Do you have any idea?

A: Solution was that I had to enter a different proxy server. As I learned, my company has different proxies: some for "normal" users and some for servers. The proxy used by the servers don't require basic auth. With this proxy, it works now.


text:
Q: how to run spark on yarn-client Am trying to run pyspark on yarn-client, am not sure what might be reason and the can't interpret the logs correctly
import sys
from pyspark.sql import SparkSession
from pyspark import SparkContext, SparkConf
conf = SparkConf()
conf.setMaster('yarn-client')
conf.setAppName('SPARK APP')
sc = SparkContext(conf=conf)
# sc= SparkContext.getOrCreate()
# sc.stop()

def mod(x):
    import numpy as np
    return (x, np.mod(x, 2))

rdd = sc.parallelize(range(1000)).map(mod).take(10)
print (rdd)

the code keeps throwing the below exception
Diagnostics: File file:/home/sw/.sparkStaging/application_1549971830990_0008/__spark_libs__3625483651625656288.zip does not exist
java.io.FileNotFoundException: File file:/home/sw/.sparkStaging/application_1549971830990_0008/__spark_libs__3625483651625656288.zip does not exist
        at org.apache.hadoop.fs.RawLocalFileSystem.deprecatedGetFileStatus(RawLocalFileSystem.java:598)
        at org.apache.hadoop.fs.RawLocalFileSystem.getFileLinkStatusInternal(RawLocalFileSystem.java:811)
        at org.apache.hadoop.fs.RawLocalFileSystem.getFileStatus(RawLocalFileSystem.java:588)
        at org.apache.hadoop.fs.FilterFileSystem.getFileStatus(FilterFileSystem.java:432)
        at org.apache.hadoop.yarn.util.FSDownload.copy(FSDownload.java:251)
        at org.apache.hadoop.yarn.util.FSDownload.access$000(FSDownload.java:61)
        at org.apache.hadoop.yarn.util.FSDownload$2.run(FSDownload.java:364)
        at org.apache.hadoop.yarn.util.FSDownload$2.run(FSDownload.java:362)
        at java.security.AccessController.doPrivileged(Native Method)
        at javax.security.auth.Subject.doAs(Subject.java:422)
        at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1924)
        at org.apache.hadoop.yarn.util.FSDownload.call(FSDownload.java:361)
        at org.apache.hadoop.yarn.util.FSDownload.call(FSDownload.java:60)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)

A: The issue was solved when I gave the user ownership and permissions to that path
chown sw /home/sw/.sparkStaging/


text:
Q: Syntax error or access violation mysql Raw query in laravel   $sqlQuery ="SELECT
           DISTINCT
          media_albume.albume_id,
         media_albume.albume_tittle,
            media_albume.created_user,
         CONCAT('$base_url',media.url) AS image_url
           FROM
         media_albume
        INNER JOIN media ON media.albume_id = media_albume.albume_id
         WHERE
        created_user =$userId
        GROUP BY
       media.albume_id";

      $results = DB::select($sqlQuery);
       /**this is my code ** /

when i run  this code with out  "Group By " it work  after adding Group By it triggerd below error
   "SQLSTATE[42000]: Syntax error or access violation: 1055 "

A: Laravel by default enables strict mode for MySQL which does prevent selecting columns that aren't aggregated when using group by.
You need to either adjust your query or disable strict mode in config/database.php.
I would recommend re-working your code to work with strict mode though (only select columns that are grouped/aggregated).


text:
Q: How can I run the full Flask Tutorial app in the Wingware IDE? How can I run the full Flask Tutorial app in the Wingware IDE?
I've been using Flask under Wing Pro 7.2 for some time, and can get control because I start Flask by doing app.run() in Wing.
I conceived a wish to trace through the official working version of the completed tutorial, obtained by
    git clone https://github.com/pallets/flask
This works fine (using 'flask run'), and I now have the complete source.  But there's no app.run() anywhere.  I tried putting one in init.py:
    def create_app(test_config=None):
        #...
        db.init_app(app)
        return app

    RUN = True
    if RUN:
        app= create_app()
        app.run()

and flask starts up, but throws an error on request 'localhost:5000/', which normally fires up a database form.
Is there a starting point in the Python code somewhere?
Or, is it possible to attach Wing to a running flask, and tell it about the source files?  There is a bit in the Wing manual about attaching, but it seems to demand information about the target that we lack.

A: I managed to start the tutorial by creating a file main.py in the same directory as the flaskr package, with this contents:
import flaskr
app = flaskr.create_app()
app.debug = False
app.run(use_reloader=True)

Then I set this as the main debug file in Wing.
To make debugging work correctly, you may also need to set the Python Executable in Project Properties (from the Project menu) to the Python command line or activated env you want to use.
Also, it is important to set Debug/Execute > Debug Child Processes in Project Properties to Always Debug Child Processes.  Otherwise the process actually running the app code is not debugged.
This works but results in a SQL error because the table 'post' does not exist if you did not already run the following first to initialize the database:
$ export FLASK_APP=flaskr
$ export FLASK_ENV=development
$ flask init-db

Once I did that, everything worked for me.


text:
Q: How to call two functions at a time in JavaScript? I have these two functions that have very similar code and almost the same variable names. I want to run the both of them, but only one is running.
Here are the functions:
function showSlides(n) {
  var i;

  var slides = document.getElementsByClassName("mySlides0");

  var dots = document.getElementsByClassName("dot");
  if (n > slides.length) {slideIndex = slides.length}
  if (n < 1) {slideIndex = 1}
  for (i = 0; i < slides.length; i++) {
      slides[i].style.display = "none";
  }
  for (i = 0; i < dots.length; i++) {
      dots[i].className = dots[i].className.replace(" active", "");
  }
  slides[slideIndex-1].style.display = "block";
  dots[slideIndex-1].className += " active";

    }

    ////////////////////////
    function showSlides1(n) {
    var i;

  var slides = document.getElementsByClassName("mySlides1");

  var dots = document.getElementsByClassName("dot");
  if (n > slides.length) {slideIndex = slides.length}
  if (n < 1) {slideIndex = 1}
  for (i = 0; i < slides.length; i++) {
      slides[i].style.display = "none";
  }
  for (i = 0; i < dots.length; i++) {
      dots[i].className = dots[i].className.replace(" active", "");
  }
  slides[slideIndex-1].style.display = "block";
  dots[slideIndex-1].className += " active";

}

and here is how I ran it:
showSlides1(slideIndex1);
showSlides(slideIndex);

A: First of all, as mentioned in the comments, you don't need the same function, just with different className, you can pass it by argument.
Second thing is that you forgot to assign your n argument to slideIndex.
The third thing is you searched for all dots in the document. You should search only for those in your slider.
I've prepared a working example for your code with some HTML and CSS included.

function showSlides(n, className) {
  var i;

 var slider = document.getElementsByClassName(className)[0];
  var slides = slider.getElementsByClassName('slide');
  var dots = slider.getElementsByClassName("dot");
  var slideIndex = 0;

  if (n > slides.length) {slideIndex = slides.length}
  else if (n < 1) {slideIndex = 1}
  else {slideIndex = n}

  for (i = 0; i < slides.length; i++) {
      slides[i].style.display = "none";
  }
  for (i = 0; i < dots.length; i++) {
      dots[i].className = dots[i].className.replace(" active", "");
  }
  slides[slideIndex-1].style.display = "block";
  dots[slideIndex-1].className += " active";

    }

showSlides(2, 'first-slider');
showSlides(3, 'second-slider');
.first-slider,
.second-slider {
  display: inline-block;
  width: 100px;
}
.slide {
  color: blue;
}

.dot {
  display: inline-block;
  padding: 3px 4px;
  border-radius: 50%;
  background: grey;
}
.dot.active {
  color: red;
}

     1

     2

     3

     4

     5

    1

    2

    3

    4

    5

     1

     2

     3

     4

     5

    1

    2

    3

    4

    5

A: function showSlides(n) {
  var i;

  var slides = document.getElementsByClassName("mySlides0");

  var dots = document.getElementsByClassName("dot");
  if (n > slides.length) {slideIndex = slides.length}
  if (n < 1) {slideIndex = 1}
  for (i = 0; i < slides.length; i++) {
      slides[i].style.display = "none";
  }

  slides[slideIndex-1].style.display = "block";

    }
    ///////////////////////////////////////////
function showSlides1(n) {
  var i;

  var slides = document.getElementsByClassName("mySlides1");

  var dots = document.getElementsByClassName("dot");
  if (n > slides.length) {slideIndex = slides.length}
  if (n < 1) {slideIndex = 1}
  for (i = 0; i < slides.length; i++) {
      slides[i].style.display = "none";
  }

  slides[slideIndex-1].style.display = "block";

    }

then call it normally
showSlides(slideIndex);

showSlides1(slideIndex)

this is the correct code @epascarello thanks.


text:
Q: PySide2 QWizard non linear pages I am trying to change my code from PyQt5 to PySide2. Most of the my scripts I simply have to change imports from PyQt5 to PySide2 and it works the same. However I tried to rework the licensewizard example in the Qt documentation from PyQt5 to PySide2. In PyQt5 it works perfectly, However, in PySide2 I get a error with exit code 139 (interrupted by signal 11: SIGSEGV). The PySide2 qwizard code for linear wizards like the class wizard example, works fine. Does anyone knows why it fails with the non linear wizards and why I get that error?
Thanks
The code below works for PyQt5. Replacing PyQt5 with PySide2 I get an error
Process finished with exit code 132 (interrupted by signal 4: SIGILL)
class IntroductionPage(QtWidgets.QWizardPage):
    def __init__(self):
        super(IntroductionPage, self).__init__()

        self.setTitle("Introduction")
        self.label = QtWidgets.QLabel("set this up")
        self.label.setWordWrap(True)
        self.layout = QtWidgets.QVBoxLayout()
        self.layout.addWidget(self.label)
        self.setLayout(self.layout)

    def nextId(self):
        return Wizard.class1

class ClassesPage1(QtWidgets.QWizardPage):
    def __init__(self):
        super(ClassesPage1, self).__init__()
        self.setTitle("Choices")
        self.setSubTitle("Choose 1")

        self.radButton1 = QtWidgets.QRadioButton('1A')
        self.radButton2 = QtWidgets.QRadioButton('1B')
        self.radButton3 = QtWidgets.QRadioButton('1C')

        self.layout = QtWidgets.QVBoxLayout()
        self.layout.addWidget(self.radButton1)
        self.layout.addWidget(self.radButton2)
        self.layout.addWidget(self.radButton3)
        self.class_selected1 = QtWidgets.QLineEdit()
        self.setLayout(self.layout)

    def nextId(self):
        if self.radButton2.isChecked():

            return Wizard.class2
        elif self.radButton3.isChecked():

            return Wizard.class2
        else:
            return Wizard.conclusion

class ClassesPage2(QtWidgets.QWizardPage):
    def __init__(self):
        super(ClassesPage2, self).__init__()
        #self.page = QWizardPage()
        self.setTitle("Classes for grade 2")
        self.setSubTitle("Please select a Class")

        self.radButton1 = QtWidgets.QRadioButton('2A')
        self.radButton2 = QtWidgets.QRadioButton('2B')
        self.radButton3 = QtWidgets.QRadioButton('2C')

        self.layout = QtWidgets.QVBoxLayout()
        self.layout.addWidget(self.radButton1)
        self.layout.addWidget(self.radButton2)
        self.layout.addWidget(self.radButton3)
        self.class_selected2 = QtWidgets.QLineEdit()

        self.setLayout(self.layout)

    def nextId(self):
        return Wizard.conclusion

class ClassesPage3(QtWidgets.QWizardPage):
    def __init__(self):
        super(ClassesPage3, self).__init__()
        self.setTitle("Classes for grade 3")
        self.setSubTitle("Please select a Class")

        self.radButton1 = QtWidgets.QRadioButton('3A')
        self.radButton2 = QtWidgets.QRadioButton('3B')
        self.radButton3 = QtWidgets.QRadioButton('3C')

        self.layout = QtWidgets.QVBoxLayout()
        self.layout.addWidget(self.radButton1)
        self.layout.addWidget(self.radButton2)
        self.layout.addWidget(self.radButton3)
        self.class_selected3 = QtWidgets.QLineEdit()

        self.setLayout(self.layout)

    def nextId(self):
        return Wizard.conclusion

class ConclusionPage(QtWidgets.QWizardPage):
    def __init__(self):
        super(ConclusionPage, self).__init__()

        self.layout = QtWidgets.QVBoxLayout()

        self.label = QtWidgets.QLabel(self)
        self.label2 = QtWidgets.QLabel(self)
        self.layout.addWidget(self.label)
        self.layout.addWidget(self.label2)
        self.setLayout(self.layout)

class Wizard(QtWidgets.QWizard):
    num_of_pages = 5
    (intro, class1, class2, class3, conclusion) = range(num_of_pages)

    def __init__(self):
        super(Wizard, self).__init__()
        self.setPage(self.intro, IntroductionPage())

        self.setPage(self.class1, ClassesPage1())
        self.setPage(self.class2, ClassesPage2())
        self.setPage(self.class3, ClassesPage3())
        self.setPage(self.conclusion, ConclusionPage())
        self.setStartId(self.intro)

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)

    wizard = Wizard()

    wizard.setWindowTitle("Set Up")
    wizard.setWizardStyle(QtWidgets.QWizard.MacStyle)
    wizard.show()

    sys.exit(app.exec_())

A: It seems that unlike PyQt5, PySide2 requires that you pass a parent, in your case the solution is to change the constructors of the classes:
class Some_Page(QtWidgets.QWizardPage):
    def __init__(self):
        super(Some_Page, self).__init__()

to:
class Some_Page(QtWidgets.QWizardPage):
    def __init__(self, *args, **kwargs):
        super(Some_Page, self).__init__(*args, **kwargs)

When we add a page, we pass the parent to him:
class Wizard(QtWidgets.QWizard):
    num_of_pages = 5
    (intro, class1, class2, class3, conclusion) = range(num_of_pages)

    def __init__(self, *args, **kwargs):
        super(Wizard, self).__init__(*args, **kwargs)
        self.setPage(self.intro, IntroductionPage(self))
        self.setPage(self.class1, ClassesPage1(self))
        self.setPage(self.class2, ClassesPage2(self))
        self.setPage(self.class3, ClassesPage3(self))
        self.setPage(self.conclusion, ConclusionPage(self))
        self.setStartId(self.intro)

Complete Code:
from PySide2 import QtWidgets
import sys

class IntroductionPage(QtWidgets.QWizardPage):
    def __init__(self, *args, **kwargs):
        super(IntroductionPage, self).__init__(*args, **kwargs)

        self.setTitle("Introduction")
        self.label = QtWidgets.QLabel("Welcome to the One Inc™'s Teacher Interactive Accessment tool. Follow the prompts to set up your Mark Sheet")
        self.label.setWordWrap(True)
        self.layout = QtWidgets.QVBoxLayout()
        self.layout.addWidget(self.label)
        self.setLayout(self.layout)

    def nextId(self):
        return Wizard.class1

class ClassesPage1(QtWidgets.QWizardPage):
    def __init__(self, *args, **kwargs):
        super(ClassesPage1, self).__init__(*args, **kwargs)
        self.setTitle("Choices")
        self.setSubTitle("Choose 1")

        self.radButton1 = QtWidgets.QRadioButton('1A')
        self.radButton2 = QtWidgets.QRadioButton('1B')
        self.radButton3 = QtWidgets.QRadioButton('1C')

        self.layout = QtWidgets.QVBoxLayout()
        self.layout.addWidget(self.radButton1)
        self.layout.addWidget(self.radButton2)
        self.layout.addWidget(self.radButton3)
        self.setLayout(self.layout)

    def nextId(self):
        if self.radButton2.isChecked():

            return Wizard.class2
        elif self.radButton3.isChecked():

            return Wizard.class2
        else:
            return Wizard.conclusion

class ClassesPage2(QtWidgets.QWizardPage):
    def __init__(self, *args, **kwargs):
        super(ClassesPage2, self).__init__(*args, **kwargs)
        #self.page = QWizardPage()
        self.setTitle("Classes for grade 2")
        self.setSubTitle("Please select a Class")

        self.radButton1 = QtWidgets.QRadioButton('2A')
        self.radButton2 = QtWidgets.QRadioButton('2B')
        self.radButton3 = QtWidgets.QRadioButton('2C')

        self.layout = QtWidgets.QVBoxLayout()
        self.layout.addWidget(self.radButton1)
        self.layout.addWidget(self.radButton2)
        self.layout.addWidget(self.radButton3)
        self.class_selected2 = QtWidgets.QLineEdit()

        self.setLayout(self.layout)

    def nextId(self):
        return Wizard.conclusion

class ClassesPage3(QtWidgets.QWizardPage):
    def __init__(self, *args, **kwargs):
        super(ClassesPage3, self).__init__(*args, **kwargs)
        self.setTitle("Classes for grade 3")
        self.setSubTitle("Please select a Class")

        self.radButton1 = QtWidgets.QRadioButton('3A', self)
        self.radButton2 = QtWidgets.QRadioButton('3B', self)
        self.radButton3 = QtWidgets.QRadioButton('3C', self)

        self.layout = QtWidgets.QVBoxLayout()
        self.layout.addWidget(self.radButton1)
        self.layout.addWidget(self.radButton2)
        self.layout.addWidget(self.radButton3)
        self.class_selected3 = QtWidgets.QLineEdit()

        self.setLayout(self.layout)

    def nextId(self):
        return Wizard.conclusion

class ConclusionPage(QtWidgets.QWizardPage):
    def __init__(self, *args, **kwargs):
        super(ConclusionPage, self).__init__(*args, **kwargs)

        self.layout = QtWidgets.QVBoxLayout()
        self.label = QtWidgets.QLabel(self)
        self.label2 = QtWidgets.QLabel(self)
        self.layout.addWidget(self.label)
        self.layout.addWidget(self.label2)
        self.setLayout(self.layout)

class Wizard(QtWidgets.QWizard):
    num_of_pages = 5
    (intro, class1, class2, class3, conclusion) = range(num_of_pages)

    def __init__(self, *args, **kwargs):
        super(Wizard, self).__init__(*args, **kwargs)
        self.setPage(self.intro, IntroductionPage(self))
        self.setPage(self.class1, ClassesPage1(self))
        self.setPage(self.class2, ClassesPage2(self))
        self.setPage(self.class3, ClassesPage3(self))
        self.setPage(self.conclusion, ConclusionPage(self))
        self.setStartId(self.intro)

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)

    wizard = Wizard()

    wizard.setWindowTitle("Set Up")
    wizard.setWizardStyle(QtWidgets.QWizard.MacStyle)
    wizard.show()

    sys.exit(app.exec_())


text:
Q: wpf InvokeCommandAction binding I have some problems with binding. I do not know how to do it.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GalaSoft.MvvmLight;
using ManyViews.Model;
using System.Collections.ObjectModel;
using System.Windows.Input;
using GalaSoft.MvvmLight.Command;

namespace ManyViews.ViewModel
{
    class ListViewModel : ViewModelBase
    {
        public void show()
        {
            System.Windows.MessageBox.Show("Raise");
        }
        public ListViewModel()
        {
            EventChecked = new RelayCommand(() => show());
        }
        public ICommand EventChecked { get; set; }
        public ObservableCollection<ListStruct> ShowList
        {
            get { return ListM.Items; }
            set { ListM.Items = value; RaisePropertyChanged("ShowList"); }
        }
        ListModel ListM = new ListModel();
    }
}

I always use static resource if i need to choose another context, but in this case it have no property data context in EventTrigger.
<UserControl x:Class="ManyViews.View.List"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
         xmlns:test="clr-namespace:ManyViews.ViewModel"
         mc:Ignorable="d"
         d:DesignHeight="300" d:DesignWidth="300">
<UserControl.Resources>
    <test:ListViewModel x:Key="Test"></test:ListViewModel>
</UserControl.Resources>
<Grid>
    <ListView ItemsSource="{Binding ShowList}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <CheckBox Content="{Binding name}">
                    <i:Interaction.Triggers >
                        <i:EventTrigger EventName="Checked">
                            <i:InvokeCommandAction  Command="{Binding DataContext.EventChecked, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type test:ListViewModel}}}"></i:InvokeCommandAction>
                        </i:EventTrigger>
                    </i:Interaction.Triggers>
                </CheckBox>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</Grid>

In this case I have error

"System.Windows.Data Error: 4 : Cannot find source for binding with
  reference 'RelativeSource FindAncestor,
  AncestorType='ManyViews.ViewModel.ListViewModel', AncestorLevel='1''.
  BindingExpression:Path=DataContext.EventChecked; DataItem=null; target
  element is 'InvokeCommandAction' (HashCode=43550996); target property
  is 'Command' (type 'ICommand')"

A: AncestorType={x:Type test:ListViewModel} is your problem.
There are no test:ListViewModels in the visual tree higher than the current item. There are only different controls, not (view)models.
Change it to search for ListView:
<i:InvokeCommandAction
     Command="{Binding DataContext.EventChecked, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListView}}}">
</i:InvokeCommandAction>