text:
Q: youtube output on my app without using a standard browser with webview I want to put the webversion of youtube in my application where you can do everything(like watch and search videos,..) without using a standard browser. I have written this code but every time pop ups which browser I want to use (like Google chrome,..)but I want to let it display on my appscreen and I have set the permission of internet already.
here the code:
youtube.xml:
 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <WebView
        android:id="@+id/webView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

youtube.java:
package com.example.listentomusic;

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;

public class Youtube extends Activity {

    public  void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.youtube);
    WebView wv = (WebView)findViewById(R.id.webView1);
    wv.loadUrl("http://www.youtube.com");
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }
}

A: You need to create your CustomWebViewClient & set it to your webView.
Like this -
 private class CustomWebViewClient extends WebViewClient {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
}

Now set this CustomeWebViewClient to your webView-
    WV.setWebViewClient(new CustomWebViewClient());

Also main(String[] args) is of no use, remove it.


text:
Q: How to hide text without ID? I'm writing a css style for a web page that displays text without id, inside a div. Here's the bit i'm interested in:

    <meta content="***" itemprop="width"></meta>
    <meta content="***" itemprop="height"></meta>

     text1:

    text2:

    text3:

I want to know how do i hide ' text3:' without hiding 'text1: and text2:' with css, using
{ text-indent: 100%;   white-space: nowrap;   overflow: hidden;  }
or { display: none !Important; }, or whatever else.. ?
And if that is not possible, how can i hide all three of them ?

A: To hide all text nodes (not the preferred solution, but requested nonetheless); you could try to collapse the visibility on the parent div and then restore it on the html elements:

.wal2 {
  visibility: collapse;
}
a,
br,
table,
img {
  visibility: visible;
}

  <meta content="***" itemprop="width"></meta>
  <meta content="***" itemprop="height"></meta>

  text1:

  link

  text2:

  link

  link

  text3:

      table cell

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using Tensorflow's inference graph in Unity First, let me clarify somethings, I don't know python.
I am currently working on my final year project and I needed a good Object detection technique, after trying many methods (color threshold, Haar-Classifiers), I stumbled around tensorflow, found myself a good tutorial, followed it and got the detector I want.
The problem:
I need and I want to work on Unity, Unity only supports C#.
I found an asset called TensorflowSharp but didn't know how to use it. The fact is I don't want to train on Unity, I trained on python I just need to use the "frozen inference graph" (as named in the tutorial) in unity to detect the object I want.
Please, I have to present in a month, any help is appreciated.

A: You can take a look at my TFClassify-Unity example. It uses trained model from official Tensorflow repo, but you can try your own by renaming its extension from '.pb' to '.bytes' and replacing default one with it.


text:
Q: Can't install ZMQ php extension. Unable to find libzmq installation. But it installed via "brew install zmq". MacOS Mojave I installed zeromq via brew install zeromq, and after tried to install php extension via pecl install zmq-beta. But I received error

Unable to find libzmq installation.

I can't find the solution. I added zmq lib files to $PATH and I can "ping" it in bash. I'm using custom php instalation via brew (php@5.6).  pkg-config also installed.

A: I solved this problem! Just installed zeromq manually from master as described here in the "Development master" section. I used first way.


text:
Q: jQuery each function return always first option I try to browse a select with jQuery and using each function but my alert in my each me back X times (where x is the number of option) the value of my first option ..
An idea?
$("#selectionChamp option").each(function(){
        alert($("#selectionChamp option").val());
    });

A: .val() (and really all of the jQuery getters) returns the requested value for the first element in the matched set. Within the context of .each(), to access the element currently being evaluated use this:
$("#selectionChamp option").each(function(){
    alert($(this).val());
});

A: $("#selectionChamp option").each(function(){
    console.log(this.value);
});


text:
Q: Java: How do I set a color in a child class? I'm trying to set a color in a child class with getters/setters but there's a compile error.
//world.java
import java.awt.Color;

public class world {
    private Color color;

    public Color getColor() {
        return color;
    }
    public void setColor(Color color) {
        this.color = color;
    }
}

//object.java
public class object extends world {
    public object{
        setColor(new world.Color(255,0,0); //compile error
    }
}

I can easily solve this by importing java.awt.Color in the child and typing setColor(new Color(255,0,0), but isn't it redundant when it's already imported in the parent? I also tried other syntax such as setColor(world.setColor(new Color(255,0,0))) but that gives a different error. What's the correct syntax to do this correctly?

A: Using new world.Color(255,0,0); is incorrect in quite some ways. For the Java compiler you request a inner static class named Color for the class named world. It wont result in a compile error if you add this to your codebase:
//world.java (different to World.java)
class world {
    public static class Color {
         public Color(int r, int g, int b) {}
    }
}

So you can correct this by using new Color(255, 0, 0);.
And also an import statement is not a redundancy. In Java every java file defines a compilation unit. This unit stands for itself. Every class you reference by type (class/interface directly named) must be resolvable by only knowing the package name, the class name and its definitions (inner classes / interfaces, annonymous classes etc). Since Color comes from a distant package the compilation unit (your java-file) must contain a reference to the class Color. This can be done by using the import statement or referencing the Color class by its full name (= package + "." + class-name) meaning java.awt.Color.

A: Just simply
   setColor(new Color(255,0,0); //no compile error

(You have to have the import statement in each files you use the classes...)
Explanation:
The class at hand extends world - that means the setColor() method is "just there" without declaring it again. It will set the color instanct field of the world class just properly, without explicitly specifying that... Methods and fields with the static modifier are always related to the class itself, and not the instances of the class
Why is setColor(world.setColor(new Color(255,0,0))) not working?
This syntax is for accessing static methods of the world class - but such a method does not exist. What you have is a non-static method, which is totally appropriate in this case, as the color value is related to each instance of the class individually. So in this case, the world.setColor() syntax is not valid.
GameObject swapped for world, as per OPs comment
Some rules to take

*

*Class Names Start With Capitals

*Don't use names that are similar to, or exactly like JDK library classes. Especially true for Object, String, and the like!!!

A: No, an import is not redundant simply because it was specified in the file containing the superclass.  The import's scope is the source file in which it's located.  A subclass (or any other class for that matter) located in a different source file needs its own imports.
You can import java.awt.Color; again in the child class source file, and refer to Color by its simple name.
setColor(new Color(255, 0, 0));

Or you can supply a fully-qualified reference when needed:
setColor(new java.awt.Color(255, 0, 0));

The JLS, Section 6.3 has this to say on the scope of an import:

The scope of a type imported by a single-type-import declaration
  (§7.5.1) or a type-import-on-demand declaration (§7.5.2) is all the
  class and interface type declarations (§7.6) in the compilation unit
  in which the import declaration appears, as well as any annotations on
  the package declaration (if any) of the compilation unit .

By "compilation unit", it means the source code file.

A: The problem here is that the Color class is not a member of world, so new world.Color(255,0,0) is not valid. In that point, you can only say new Color(255,0,0).
That is to say, that the even though your world class is importing Color, it is not defining Color.


text:
Q: Confirmatory Factor Analysis elimination process For my thesis, I conducted a survey with 89 questions, resulting in 6 variables in total. The scales I used for the variables are already validated in the literature.
Now, I want to find out, which items I need to eliminate due to their respective influence on not only one specific but several variables. I conducted a confirmatory factor analysis but am now unsure how the elimination procedure works. How do I know, what item to drop? Is there a certain threshold to use? Do I look closer at Std.all of Variances?
Unfortunately, I couldn't find the answer in the literature and forums online, so I'd really appreciate your support!


text:
Q: Query to undefined location because of value-binding to object? I've got a controller like this:
import Ember from 'ember';

export default Ember.ArrayController.extend({
  currentTrack: {'https://cdn.clougfront.com/superimage.jpg'}
})

and a template-file like this:
<div class="song">
  <img {{bind-attr src=currentTrack.artwork_url}} />
</div>

For some reason this causes Ember to send a HTTP-request to http://localhost:4200/undefined . It doesn't happen when currentTrack is just a string.
How can I prevent that but still us currentTrack as an object (it normally has more attributes. I just left them out for the sake of simplicity)?


text:
Q: H2OConnectionError: Unexpected HTTP error: How to increase memory in H2O? While loading my dataset using python code on the AWS server using Spyder, I get the following error:
  File "<ipython-input-19-7b2e7b5812b3>", line 1, in <module>
    ffemq12 = load_h2odataframe_returns(femq12) #; ffemq12 = add_fold_column(ffemq12)

  File "D:\Ashwin\do\init_sm.py", line 106, in load_h2odataframe_returns
    fr=h2o.H2OFrame(python_obj=returns)

  File "C:\Program Files\Anaconda2\lib\site-packages\h2o\frame.py", line 106, in __init__
    column_names, column_types, na_strings, skipped_columns)

  File "C:\Program Files\Anaconda2\lib\site-packages\h2o\frame.py", line 147, in _upload_python_object
    self._upload_parse(tmp_path, destination_frame, 1, separator, column_names, column_types, na_strings, skipped_columns)

  File "C:\Program Files\Anaconda2\lib\site-packages\h2o\frame.py", line 321, in _upload_parse
    ret = h2o.api("POST /3/PostFile", filename=path)

  File "C:\Program Files\Anaconda2\lib\site-packages\h2o\h2o.py", line 104, in api
    return h2oconn.request(endpoint, data=data, json=json, filename=filename, save_to=save_to)

  File "C:\Program Files\Anaconda2\lib\site-packages\h2o\backend\connection.py", line 415, in request
    raise H2OConnectionError("Unexpected HTTP error: %s" % e)

I am running this python code on Spyder on the AWS server. The code works fine up to half the dataset (1.5gb/3gb) but throws an error if I increase the data size. I tried increasing the RAM from 61gb to 122 GB but it is still giving me the same error.
Loading the data file
femq12 = pd.read_csv(r"H:\Ashwin\dta\datafile.csv")
ffemq12 = load_h2odataframe_returns(femq12)

Initializing h2o
h2o.init(nthreads = -1,max_mem_size="150G")

Loading h2o

Connecting to H2O server at http://127.0.0.1:54321... successful.
  --------------------------  ------------------------------------  H2O cluster uptime:         01 secs  H2O cluster timezone:       UTC  H2O
  data parsing timezone:  UTC  H2O cluster version:        3.22.1.3  H2O
  cluster version age:    18 days  H2O cluster total nodes:    1  H2O
  cluster free memory:    133.3 Gb  H2O cluster total cores:    16  H2O
  cluster allowed cores:  16  H2O cluster status:         accepting new
  members, healthy H2O connection proxy:  H2O internal security:
  False  H2O API Extensions:         Algos, AutoML, Core V3, Core V4
  Python version:             2.7.15 final

I suspect it is a memory issue. But even after increasing RAM and max_mem_size, the dataset is not loading.
Any ideas to fix the error would be appreciated. Thank you.

A: Solution: Don't use pd.read_csv() and h2o.H2OFrame(), and instead use h2o.import_file() directly.
The error message is on the POST /3/PostFile REST command. Which, as far as I can tell from your code and log snippets, means it is uploading to localhost? That is horribly inefficient.
(If not localhost, i.e. your datafile.csv is on your computer, which is outside of AWS, then upload it to S3 first. If you are doing some data munging on your computer, do that, then save it as a new file, and upload that to S3. It doesn't have to be S3: it could be the hard disk if you only have a single machine in your H2O cluster.)
For some background see also my recent answers at https://stackoverflow.com/a/54568511/841830 and https://stackoverflow.com/a/54459577/841830.  (I've not marked as duplicate, as though the advice is the same, in each case, the reason is a bit different; here I wonder if you are hitting a limit for maximum HTTP POST file size, perhaps at 2GB? I suppose it could also be running out of disk space, from all the multiple temp copies be made.)


text:
Q: Migrate from Jasmine 1.3 to 2.0 with karma I'd like to migrate an AngularJS project from Jasmine 1.3 to 2.x.
After some (solved) peer-version problems with modules karma, karma-jasmine and grunt-karma, I encounter additional problems.
Command line: grunt karma:unit
Fatal error: Cannot call method 'push' of undefined

My questions:

*

*do I have to change karma.conf.js when upgrading to Jasmine 2.x?

*Is Jasmine 2 + karma working reliable or is it better to stay with 1.3 at the moment?

*What am I doing wrong?


text:
Q: display: inline, but on different lines Inline elements are great, because their width is the width of the content and because it's possible to center them with on rule of CSS:
text-align: center

But inline elements stay on the same line. Is it possible to align them vertically?
Fiddle: http://jsfiddle.net/_bop/NhVaF/
Full screen fiddle: http://jsfiddle.net/_bop/NhVaF/show
Please don't:

*

*Change the HTML in the example. Change the CSS!

*Come up with other techniques to center elements, unless you have a better solution that works on elements with unspecified width and doesn't need tons of containers and/or float hacks.

Thanks in advance!

A: In your markup, if the span are on different rows you could add on the parent container:
white-space: pre-line;

With this CSS declaration, your span are still centered, and you don`t have to add HTML markup.

pre-line
  - This value will cause sequences of whitespace to collapse into a single space character. Line breaks will occur wherever
  necessary to fill line boxes, and at new lines in the markup (or at
  occurrences of "\a" in generated content). In other words, it's like
  normal except that it'll honor explicit line breaks.

You can find more informations here about white-space:

*

*http://reference.sitepoint.com/css/white-space

*http://www.w3.org/TR/css3-text/#white-space

For an IE7 compatibility, you could also add on the parent container:
*white-space: pre /*FixIE7*/;

A: You need some holding block to hold your spans if you want to display it on top of another. This is the best I can do.
http://jsfiddle.net/NhVaF/5/

A: If you want to make it work without altering the html, then your best bet is to simply float: left; clear: left; like so:
span {
    float: left;
    clear: left;
    color: #FFF;
    padding: 30px;
}

display: block; will not work because it requires you to set a width (or else they'll fill the available space).
display: inline-block; will not work because still display on the same line.

A: I was just playing around with this too, and found my solution by simply placing <br> after each inline-block element. I know it's altering the html but only slightly!
If you want to create line breaks with CSS try using the :after pseudo class. Would something like this work?
div.class:after {
  content:"\a";
  white-space: pre;
}

break :after trick: https://stackoverflow.com/a/10934138/6586407


text:
Q: Best Way To Reduce Video and Audio file size in android? We have audio and video recording option in our android application, the audio file format is .mp3 and video file format is .3gp just I want to reduce the file size from actual size without losing quality. For Example, the video file is 3MP it should be 2 or 1 mp.

A: Sounds like you want to reduce resolution (eg: picture size in width/height).
Check MediaRecorder API manual for options :

*

*setVideoSize(int width, int height) command which can set video output size (note : "Must be called after setVideoSource()" from SDK manual).

*setVideoEncodingBitRate(int bitRateNumber) command can reduce filesize (in bytes) but could also affect visual quality. Some numbers make small file bytes but visually keep same image quality to the eyes. Research how bitrate settings affect visual image.
Experiment with above and see what works best for you.
Try first with setVideoSize(width, height).


text:
Q: Maximum length of linked list in java? I have to compare the time it takes to perform four operations on an array compared to the same operations on a list. How do I find the max value of the length of an array or linked list, where I only have to find the value of the shorter one because to compare the time the number of elements has to be equal. So my question is 1. do linked lists have a max number because I know arrays are just Integer.MAX_INTEGER. And 2. what is this max number because I have to do multiple tests with of equal numbers of elements with exact spacing between the number. Here's my code if that matters.
private static class Node{
 private String string;
 private Node next;
 public Node(String e, Node n){
 string=e;
 next=n;
   }
 public String getElement(){return string;}
 public Node getNext(){return next;}
public void setNext(Node n){next=n;}
}

A: Max # of linked array depends on the memory size. For Java you can take a look at the JVM mem size to figure that out. The space usage for both link list and array is the same. The only difference is that Array requires continues memory allocation and linked list doesn't. So generally speaking link list should always have a bigger size cap than array. (If the memory is not allocated at all then both has the same max cap)


text:
Q: How to set local alias for a machine? I would like to set an alias on my local PC for a network machine. I know that it can be done by adding an entry in the hosts file as long as the IP address of the machine is also specified. However, the problem is that IPs are dynamically assigned by a DHCP server so I don't know for sure the IP address. Is there a way to define just an alias based on the machine's network name?
P.S.: I'm running Windows Server 2008 R2.

A: Windows only supports IP to Hostname mapping. You cannot set up local aliases using the hosts file.
If you have control over the DNS for the network, you can create a CNAME record that maps one name to another name.
If you do not have control over the network's DNS - you are out of clean options (barring a frankensteined DNS server running on your localhost just for the creation of your own CNAMEs. shudders)

A: On networks where WINS is enabled/configured, one can refer to another machine by using the network name wherever a hostname is taken, and the OS libraries will map it to the IP address appropriately.

A: This "kinda" works (it depends on your version of windows )
in HOSTS (C:\Windows\System32\drivers\etc\hosts)
Specify:
127.0.0.1 testb
In regedit, create a DWORD as follows:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa
New DWORD
DisableLoopbackCheck
Set to 1
PING works on both Windows Server 2012 and 2019. Specifying the new alias in an explorer window (or opening it with a program) works fine in Windows Server 2012, but fails on Windows 2019 (it gets into credentialing loop and does not accept valid credentials)


text:
Q: On understanding correlation of bind and inheritance Today I was reading the MDN documentation on Function.prototype.bind(). Under the section Bound functions used as constructors there is an example that I cannot quite understand.
I ran the following piece of code both in Node.js (v.4.4.5) and Google Chrome ( v58.0.3029.81)
function Point(x, y) {
  this.x = x;
  this.y = y;
}

Point.prototype.toString = function() {
  return this.x + ',' + this.y;
};

var p = new Point(1, 2);
p.toString(); // '1,2'

var emptyObj = {};
var YAxisPoint = Point.bind(emptyObj, 1/*x*/);

var axisPoint = new YAxisPoint(5);
console.log(axisPoint.toString()); // '1,5'

console.log(axisPoint instanceof Point); // true
console.log(axisPoint instanceof YAxisPoint); // true
console.log(new Point(17, 42) instanceof YAxisPoint); // true

I can clearly see why axisPoint is an instance of both Point and YAxisPoint. But how in the world can new Point(17,42) be an instance of YAxisPoint?

A:
But how in the world can new Point(17,42) be an instance of YAxisPoint?

Because instanceof works special with bound functions (those created from .bind() calls). Usually it would check whether the object inherits from the constructors .prototype, but bound functions don't have a .prototype. Instead, when you use instanceof on a bound function, it checks whether the object is an instance of the target function (that bind() was called upon). So
… instanceof YAxisPoint

is exactly equivalent to
… instanceof Point

You can check this in the specs (ES5, ES6).


text:
Q: Can not resolve junit-jupiter-params:5.6.2 and junit-jupiter-engine:5.6.2 with Gradle 6.1.1 I have an Android project with 2 Android modules and one pure Java module.
After updating the android build tools to com.android.tools.build:gradle:4.0.0 and the gradle wrapper to gradle-6.1.1-all the pure Java module can not resolve junit anymore.
I get the following error while syncing with the gradle files:
Failed to resolve: org.junit.jupiter:junit-jupiter-params:5.6.2
Failed to resolve: org.junit.jupiter:junit-jupiter-engine:5.6.2

If I try to run the tests directly I get the following output:
Could not resolve all files for configuration ':domain:testCompileClasspath'.
   > Could not resolve org.junit.jupiter:junit-jupiter-params:5.6.2.
     Required by:
         project :domain
      > Cannot choose between the following variants of org.junit.jupiter:junit-jupiter-params:5.6.2:
          - javadocElements
          - sourcesElements
        All of them match the consumer attributes:
          - Variant 'javadocElements' capability org.junit.jupiter:junit-jupiter-params:5.6.2:
              - Unmatched attributes:
                  - Found org.gradle.category 'documentation' but wasn't required.
                  - Found org.gradle.docstype 'javadoc' but wasn't required.
                  - Required org.gradle.jvm.version '7' but no value provided.
                  - Required org.gradle.libraryelements 'classes' but no value provided.
                  - Found org.gradle.status 'release' but wasn't required.
                  - Required org.jetbrains.kotlin.platform.type 'jvm' but no value provided.
              - Compatible attributes:
                  - Required org.gradle.dependency.bundling 'external' and found compatible value 'external'.
                  - Required org.gradle.usage 'java-api' and found compatible value 'java-runtime'.
          - Variant 'sourcesElements' capability org.junit.jupiter:junit-jupiter-params:5.6.2:
              - Unmatched attributes:
                  - Found org.gradle.category 'documentation' but wasn't required.
                  - Found org.gradle.docstype 'sources' but wasn't required.
                  - Required org.gradle.jvm.version '7' but no value provided.
                  - Required org.gradle.libraryelements 'classes' but no value provided.
                  - Found org.gradle.status 'release' but wasn't required.
                  - Required org.jetbrains.kotlin.platform.type 'jvm' but no value provided.
              - Compatible attributes:
                  - Required org.gradle.dependency.bundling 'external' and found compatible value 'external'.
                  - Required org.gradle.usage 'java-api' and found compatible value 'java-runtime'.

How can I tell Gradle where it should look for the correct junit dependencies?

A: The solution I have found for a similar issue (mine was with org.junit.jupiter:junit-jupiter-api) is to update the source compatibility of the tests to 1.8.
compileJava {
    sourceCompatibility = "1.7"
    targetCompatibility = "1.7"
}
compileTestJava {
    sourceCompatibility = "1.8"
    targetCompatibility = "1.8"
}

This way the production source is still compatible with 1.7 to allow the Android build.


text:
Q: Refresh auth token dynamically when API fails and retry the API call which failed I have a token which expires periodically. I am using AFNetworking 3.0.
Steps:

*

*API is called

*Token has expired and 401 happens.

*Need to fetch token

*Continue the API call with new token

How can I do that, considering that the backend can change the token expiration time?

A: Typically you would have a an API Client class that all of your network requests funnel through so that you can catch your 401 failures, parse them for your expired token message in the headers (so you can allow true 401's to pass through) and refresh your tokens before retrying your original request.
You can go a step further by using a session manager to prevent other requests from going out until your token has been completely refreshed, but you basically just need to add refresh logic when your request returns and retry the original request.
Here is a rough idea of how I handle it.
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:newRequest completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (response) {
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
            NSString *headerError = [httpResponse.allHeaderFields objectForKey:@"Www-Authenticate"];
            if (headerError) {
                if ([headerError rangeOfString:@"The access token expired"].location != NSNotFound) {
                    //refresh here

                    // exit to avoid calling completion handler
                    return;
                }
            } else {
                if (httpResponse.statusCode == 401) {
                    // user does not have access
                    NSLog(@"Unauthorized Network Request");
                }
            }
        }

        if (completionHandler) {
            completionHandler(response,responseObject,error);
        }
    }];

    [dataTask resume];


text:
Q: How to implement pagination for multikey indexes in Tarantool? I have multikey index over field that store an array of integers.
How I can implement cursor-based pagination using it?
In real if tuple has more than one value in array field it tuple will be selected #tuple[array_field_idx] times.
Yesterday I implemented "distinct" select (using ffi to get tuple pointer address), but it seems that it will not be works with pagination.
Have you any ideas how it can be implemented in Tarantool?

A: In order to implement pagination for multikey index you should know something about Tarantool internals.
I will write code that works for Tarantool 2.3+ (but it could be broken in future). Please test them carefully and update FFI definition in case of upgrade Tarantool version.
So, let's start. Firstly you should know that Tarantool BTree stores data in special structure memtx_tree_data that contains a pointer to your tuple and hint. It's special number that allows to speedup comparisons between tuples for simple tree index and it's a position of indexed element in array.
Firstly, we should to understand how to extract tuple hint with a tuple.
It could be done using some piece of FFI code and tree iterator.
local ffi = require('ffi')

ffi.cdef([[

typedef struct index_def;

typedef struct index;

typedef struct memtx_tree;

typedef struct mempool;

typedef uint64_t hint_t;

enum iterator_type {
    /* ITER_EQ must be the first member for request_create  */
    ITER_EQ               =  0, /* key == x ASC order                  */
    ITER_REQ              =  1, /* key == x DESC order                 */
    ITER_ALL              =  2, /* all tuples                          */
    ITER_LT               =  3, /* key <  x                            */
    ITER_LE               =  4, /* key <= x                            */
    ITER_GE               =  5, /* key >= x                            */
    ITER_GT               =  6, /* key >  x                            */
    ITER_BITS_ALL_SET     =  7, /* all bits from x are set in key      */
    ITER_BITS_ANY_SET     =  8, /* at least one x's bit is set         */
    ITER_BITS_ALL_NOT_SET =  9, /* all bits are not set                */
    ITER_OVERLAPS         = 10, /* key overlaps x                      */
    ITER_NEIGHBOR         = 11, /* tuples in distance ascending order from specified point */
    iterator_type_MAX
};

typedef struct iterator {
    /**
     * Iterate to the next tuple.
     * The tuple is returned in @ret (NULL if EOF).
     * Returns 0 on success, -1 on error.
     */
    int (*next)(struct iterator *it, struct tuple **ret);
    /** Destroy the iterator. */
    void (*free)(struct iterator *);
    /** Space cache version at the time of the last index lookup. */
    uint32_t space_cache_version;
    /** ID of the space the iterator is for. */
    uint32_t space_id;
    /** ID of the index the iterator is for. */
    uint32_t index_id;
    /**
     * Pointer to the index the iterator is for.
     * Guaranteed to be valid only if the schema
     * state has not changed since the last lookup.
     */
    struct index *index;
};

struct memtx_tree_key_data {
    /** Sequence of msgpacked search fields. */
    const char *key;
    /** Number of msgpacked search fields. */
    uint32_t part_count;
    /** Comparison hint, see tuple_hint(). */
    hint_t hint;
};

struct memtx_tree_data {
    /* Tuple that this node is represents. */
    struct tuple *tuple;
    /** Comparison hint, see key_hint(). */
    hint_t hint;
};

typedef int16_t bps_tree_pos_t;
typedef uint32_t bps_tree_block_id_t;

typedef uint32_t matras_id_t;

struct matras_view {
    /* root extent of the view */
    void *root;
    /* block count in the view */
    matras_id_t block_count;
    /* all views are linked into doubly linked list */
    struct matras_view *prev_view, *next_view;
};

struct memtx_tree_iterator {
    /* ID of a block, containing element. -1 for an invalid iterator */
    bps_tree_block_id_t block_id;
    /* Position of an element in the block. Could be -1 for last in block*/
    bps_tree_pos_t pos;
    /* Version of matras memory for MVCC */
    struct matras_view view;
};

typedef struct tree_iterator {
    struct iterator base;
    struct memtx_tree_iterator tree_iterator;
    enum iterator_type type;
    struct memtx_tree_key_data key_data;
    struct memtx_tree_data current;
    /** Memory pool the iterator was allocated from. */
    struct mempool *pool;
};

]])

local function get_tree_comparison_hint(box_iterator_state)
    if box_iterator_state == nil then
        return nil
    end

    local casted = ffi.cast("struct tree_iterator*", box_iterator_state)
    --
    -- IMPORTANT: hint is zero-based (as arrays in C)
    -- Lua arrays is one-based.
    --
    return casted.current.hint
end

return {
    get_tree_comparison_hint = get_tree_comparison_hint,
}

Then consider following example:
local box_iterator = require('common.box_iterator')

box.cfg{}

local space = box.schema.create_space('dict', {
    format = {
        {name = 'id', type = 'number'},
        {name = 'bundles', type = 'array'}
    },
    if_not_exists = true,
})

space:create_index('pk', {
    unique = true,
    parts = {
        {field = 1, type = 'number'}
    },
    if_not_exists = true,
})

space:create_index('multikey', {
    unique = false,
    parts = {
        {field = 2, type = 'string', path = '[*]'},
        -- Note: I intentionally add primary index parts here
        {field = 1, type = 'number'}
    },
    if_not_exists = true,
})

space:replace({1, {'a', 'b', 'c', 'd'}})
space:replace({2, {'b', 'c'}})
space:replace({3, {'a', 'd'}})
space:replace({4, {'c', 'd'}})

for iter_state, tuple in space.index.multikey:pairs({'a'}, {iterator = 'GE'}) do
    local position = box_iterator.get_tree_comparison_hint(iter_state) + 1
    print(
        string.ljust(tostring(tuple), 30),
        position,
        tuple[2][tonumber(position)]
    )
end

os.exit()

Output is:
# Tuple                         Hint   Indexed element
[1, ['a', 'b', 'c', 'd']]       1ULL    a
[3, ['a', 'd']]                 1ULL    a
[1, ['a', 'b', 'c', 'd']]       2ULL    b
[2, ['b', 'c']]                 1ULL    b
[1, ['a', 'b', 'c', 'd']]       3ULL    c
[2, ['b', 'c']]                 2ULL    c
[4, ['c', 'd']]                 1ULL    c
[1, ['a', 'b', 'c', 'd']]       4ULL    d
[3, ['a', 'd']]                 2ULL    d
[4, ['c', 'd']]                 2ULL    d

As you see the order is strictly determined.
Tarantool returns me tuples in order that is determined with (a) indexed value - tuple[path_to_array][hint+1] and primary key.
The second condition is common for all Tarantool secondary non-unique indexes.
Tarantool internally merge primary key to every non-unique index.
All you need is to specify it explicitly in your schema.
So the next term is cursor. Cursor allows you to continue iteration since place where you previously stopped. For unique indexes cursor is fields of this indexes, for non-unique index it's fields of this indexes with merger primary key (for details see key_def.merge function, currently it doesn't support multikey indexes but it's useful if you need to understand how to work index parts merge).
Following combination (merge(secondary_index_parts, primary_index_parts)) is always unique value that allows to to continue iteration since strictly determined place.
Let's return back to my example. E.g. I stopped at the row [1, ['a', 'b', 'c', 'd']]       3ULL    c. My cursor is {'c', 1}.
Well, now I could continue since this point:
-- "GE" is changed to "GT" to skip already scanned tuple: [1, ['a', 'b', 'c', 'd']]
for iter_state, tuple in space.index.multikey:pairs({'c', 1}, {iterator = 'GT'}) do
    local position = box_iterator.get_tree_comparison_hint(iter_state) + 1
    print(
        string.ljust(tostring(tuple), 30),
        position,
        tuple[2][tonumber(position)]
    )
end
--[[
Result:
[2, ['b', 'c']]                 2ULL    c
[4, ['c', 'd']]                 1ULL    c
[1, ['a', 'b', 'c', 'd']]       4ULL    d
[3, ['a', 'd']]                 2ULL    d
[4, ['c', 'd']]                 2ULL    d
--]]

You can compare with previous snippet and understand that I continue scan since needed value and don't scan redundant values and don't lose anything.
Such approach isn't quite clear and it's not completely comfortable.
You need to extract some magic value from Tarantool internals,
store them anywhere. But we use such approach in our projects because we don't have any alternatives yet :)


text:
Q: Is there a better way to reference the final child class (which can vary) in a series of extended classes? In the application I am currently developing, there is one crucial function which calls one of many possible public static methods:
$methodID = // carve up user's input to arrive at this

$importantValue = {{className}}::$methodID($arg); // {{ }} are to emphasize this is not the finished line of code....see below

However, the problem I am encountering is that className can vary depending on the user input. The base class is A, but className is either A or B depending on the user input:
class A {
    // all the base methods
}

class B extends A {
    // certain user inputs necessitate these additional methods
}

My (perhaps a hack) solution right now is to initiate, then edit the value of, a public static variable to change the identity of {{className}} above as necessary:
publicValues::$myClass = $conditions_for_class_B_exist ? 'B' : 'A';

so that the finished line of code is:
$className = publicValues::$myClass;

$importantValue = $className::$methodID($arg);

There must be a better way, especially since future updates will likely require extending to a third class, i.e., C.
Is there an object-oriented solution to referencing a variably-extended class?

A: I believe that late static bindings, using the keyword static are the solution you're looking for.
http://php.net/manual/en/language.oop5.late-static-bindings.php
<?php
class A {
    public static function who() {
        echo __CLASS__;
    }
    public static function test() {
        static::who(); // Here comes Late Static Bindings
    }
}

class B extends A {
    public static function who() {
        echo __CLASS__;
    }
}

B::test(); // Outputs "B"
?>


text:
Q: Regex matching multiple occurrences per file and per line First post, so here goes. I'm writing a script that does intelligent search and replace on a file tree. Essentially, the script gets each file's contents into a buffer string and performs a match with a pre-defined pattern, in this case the pattern is /^[^\r\n]*(vendor)[^\r\n]*$/im. The pattern should find any case-insensitive forms of "vendor" and give me the entire line that was matched. I need to see the whole line in order to determine whether or not to replace the occurrence. This pattern performs well for any number of separate line occurences in a given file.
However, if there are multiple occurrences on a given line, the pattern will only match one of those occurrences, and skip the others. I'm trying to determine if I need to have a second pattern to do additional searching on the matched line, or if I can accomplish this purpose with a single pattern that does all of the above.
Just a sample of what I'm hoping to produce. An example of a single line, multi-occurrence match:

Enthusiastically revolutionize
web-enabled VENDOR potentialities
vendors installed base e-tailers.

I would like to output something similar to this (again, the ouput isn't the issue here, it's whether or not I can match it all with one pattern):

Multiple occurrences in line:  ||
Enthusiastically revolutionize
web-enabled VENDOR potentialities
vendors installed base e-tailers. ||
Replace? (y,n,q)  || ...abled VENDOR poten... ||
Replace? (y,n,q)  || ...ties vendors insta... ||

Please let me know if I am unclear on my objective. Thanks for any help and response to this!

A: If you are using
/^[^\r\n]*(vendor)[^\r\n]*$/im

I would suggest adding the g (global) operator
/^[^\r\n]*(vendor)[^\r\n]*$/img


text:
Q: Display `.move {cursor: move;}` icon on html element without image I need to apply .move {cursor: move;}  on my  element  in my HTML. Is it possible at all?

A: As far as I'm aware there isn't a Unicode for this so you would have to use an icon. For example purposes, I've added a base64 image but this could be in any format

.move {
  display:inline-block;
  width:20px;
  height:20px;
  background-image: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/PjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iQ2FwYV8xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB4PSIwcHgiIHk9IjBweCIgdmlld0JveD0iMCAwIDMyIDMyIiBzdHlsZT0iZW5hYmxlLWJhY2tncm91bmQ6bmV3IDAgMCAzMiAzMjsiIHhtbDpzcGFjZT0icHJlc2VydmUiPjxnPjxnIGlkPSJtb3ZlIj48Zz48cG9seWdvbiBzdHlsZT0iZmlsbDojMDMwMTA0OyIgcG9pbnRzPSIxOCwyMCAxOCwyNiAyMiwyNiAxNiwzMiAxMCwyNiAxNCwyNiAxNCwyMCAiLz48cG9seWdvbiBzdHlsZT0iZmlsbDojMDMwMTA0OyIgcG9pbnRzPSIxNCwxMiAxNCw2IDEwLDYgMTYsMCAyMiw2IDE4LDYgMTgsMTIgIi8+PHBvbHlnb24gc3R5bGU9ImZpbGw6IzAzMDEwNDsiIHBvaW50cz0iMTIsMTggNiwxOCA2LDIyIDAsMTYgNiwxMCA2LDE0IDEyLDE0ICIvPjxwb2x5Z29uIHN0eWxlPSJmaWxsOiMwMzAxMDQ7IiBwb2ludHM9IjIwLDE0IDI2LDE0IDI2LDEwIDMyLDE2IDI2LDIyIDI2LDE4IDIwLDE4ICIvPjwvZz48L2c+PC9nPjxnPjwvZz48Zz48L2c+PGc+PC9nPjxnPjwvZz48Zz48L2c+PGc+PC9nPjxnPjwvZz48Zz48L2c+PGc+PC9nPjxnPjwvZz48Zz48L2c+PGc+PC9nPjxnPjwvZz48Zz48L2c+PGc+PC9nPjwvc3ZnPg==);

}

A: Here is a fancy way to create this using CSS:

.move {
  height: 100px;
  width: 100px;
  background: #000;
  position: relative;
  display:inline-block;
  margin: 50px;
  transform: rotate(45deg);
}

.move:after {
  content: "";
  position: absolute;
  z-index: 1;
  height: calc(100% - (8% * 2));
  width: calc(100% - (8% * 2));
  top: 8%;
  left: 8%;
  background: linear-gradient(to right, #000 33.33%, #fff 33.33%, #fff 66.66%, #000 66.66%) 0 50%/100% 33.33% no-repeat,
  linear-gradient(to right, #fff 33.33%, #000 33.33%, #000 66.66%, #fff 66.66%);
  transform: rotate(-45deg);
}


text:
Q: pandas efficient groupby apply two dataframe together with tqdm Method 1 (clear but very slow)
product_ids = df1.product_id.unique()
store_ids= df1.store_id.unique()

with tqdm(total=product_ids.shape[0]*store_ids.shape[0]) as t:
    for product_id in product_ids:
        p1 = df1.loc[(df1.product_id==product_id)]
        p2 = df2.loc[(df2.product_id==product_id)]
        for store_id in store_ids:
            df11 = p1.loc[(p1.store_id==store_id)]
            df22 = p2.loc[(p2.store_id==store_id)]
            train_predict(df11, df22)
            t.update()

Method 2 (fast but I don't like )
df1 = df1.reset_index()
df2 = df2.reset_index().set_index(['store_id', 'product_id'])

def _reduce(df_orderitems):
    MIN_ORDERITEMS_COUNT = 30

    store_id = df_orderitems.store_id.iloc[0]
    product_id = df_orderitems.product_id.iloc[0]

    try:
        ## !!!! here refer to global df2, I don't like  !!!!!
        df_stockquantitylog = df2.loc[(store_id, product_id)]
        ## !!!! here refer to global df2, I don't like  !!!!!
    except KeyError:
        logger.info('## df_orderitems shape:%s , cannot find (%s, %s)' % (df_orderitems.shape, store_id, product_id) )
        return

    train_predict(df_orderitems, df_stockquantitylog)

tqdm.pandas()
df1.groupby(['store_id', 'product_id']).progress_apply(_reduce)

I need tqdm to show progress bar, but Method1 is very slow(I think because of inefficient print). Method 2 which have tqdm's pandas patch, another key point I think is groupby.apply . But I can't figure out how to make method 1 as fast as method 2.
Note:
df1.shape[0] != df2.shape[0] , can't merge.
They are dumped from database . For example,  there may be  10 rows with same store_id A   and product_id B in df1 , and 100 rows with same store_id A   and product_id B in df2 . They can't be merged before proper processing:
Need:

*

*select by store_id and product_id first (in each df1 and df2)

*You can't do join without selections.  I have to apply different aggregation with df1[(df1.store_id==A)&(df1.product_id==B)]) and df2[(df2.store_id==A)&(df2.product_id==B)]), to give they same DatatimeIndex for merging , because some meta data columns need aggregate by date. You can't do this without selections, because different combinations of store_id and product_id have duplicated dates.

*Then the two result are mergable(joinable)

*train model

A: So if your only concern with Method 2 is that you don't want to look at the global df2, why not pass it in as a second parameter to your function?
Eg.
def _reduce(df_orderitems, df_): ...

But I wouldn't suggest doing precisely either of the methods you've outlined here.
Iterating through a dataframe like you do in Method 1 is never going to be as fast as using apply, because apply is internally optimized using Cython. In fact, it's going to be extremely slow (as you've found). Here is a good explanation as to why and your options for making operations faster.
Your question is a bit vague as to why else you don't like method 2, but I'd do two things, if I were in your shoes.

*

*I'd use the SQL-like operations in pandas to join the two dataframes together.

You have overlapping columns ('store_id' and 'product_id') that appear in both df1 and df2, so I'd do an SQL-style join in pandas to combine the two dataframes. That way you don't have to deal with the indexing bits you're currently doing.
Let's first create some dummy data that I think represents your situation:
  df1 = pd.DataFrame({"store_id": ['A','A','A','B','B'],
                      "product_id": [0, 1, 2, 1, 0],
                      "record_number": [0, 1, 2, 3, 4],
                      "data": [21, 22, 28, 26, 25]})

  df2 = pd.DataFrame({"store_id":['A','A','A','B','B', 'B'],
                      "product_id": [0, 1, 2, 0, 1, 2],
                      "more_data":[35, 39, 36, 33, 37, 32]})

Then you can use the join function to merge the two dataframes, SQL-style, on the overlapping columns (join uses the indices of the dataframe). This maps the data from df2 onto the data in df1 to create a new, merged dataframe. (Described in detail in the pandas docs)
 merged = df1.join(df2.set_index(['store_id','product_id']),
                   how='left',
                   on=['store_id','product_id'],
                   rsuffix='_df2_data')

Which gives you
    store_id  product_id  record_number  product_data  more_product_data
  0        A           0              0            21                 35
  1        A           1              1            22                 39
  2        A           2              2            28                 36
  3        B           1              3            26                 37
  4        B           0              4            25                 33

Depending on your data completeness, you probably want to check for NaNs
You can also filter, transform, etc your data as your need (if there are other steps to your processing step)

*Then I'd use apply (progress_apply) to do the prediction step

You can either create a new function, or use a lambda function, depending on your situation
def train_predict(a, b):
    return a + b

def predict_outcome(df_row):
    return train_predict(df_row[['product_data']].values[0],
                         df_row[['more_product_data']].values[0])

tqdm.pandas(desc='predict the outcome')
merged['prediction'] = merged.progress_apply(lambda x:  train_predict(x['product_data'],x['more_product_data']),
                                             axis='columns')

# or

tqdm.pandas(desc='predict the outcome')
merged['prediction'] = merged.progress_apply(predict_outcome, axis='columns')

(the axis='columns' argument tells apply to iterate through the df's rows)


text:
Q: Convert local image to base64 javascript As Convert local image to base64 string in Javascript . I know how to use it, but it work if image file include in project, not work with another folder. I'm test in android device and my image path like:

/storage/extSdCard/1.jpg

How can i convert image from local mobile device to base64?

A: function readImage(url, callback) {
    var request = new
    XMLHttpRequest();   request.onload = function() {
       var file = new FileReader();
       file.onloadend = function() {
          callback(file.result);
       }
       file.readAsDataURL(request.response);   };
       request.open('GET', url);
       request.responseType = 'blob';
       request.send();
}

and call function
readImage('[path image] ',  function(base64) {  console.info(base64);
});


text:
Q: Transfer folder to AWS Ubuntu server. Permission denied (publickey) I installed shiny server on an AWS EC2 Ubuntu instance following instruction here: https://www.rstudio.com/products/shiny/download-server/
I tried to transfer a folder to a remote directory: /srv/shiny-server
by typing in terminal:
scp -r path/Publickey path/folder ubuntu@ec2-52-15-128-161.us-east-2.compute.amazonaws.com:/srv/shiny-server

Then I got:
Permission denied (publickey).
lost connection

Any help will be appreciated!

A: It looks like the key that was being used is not accepted for the user ubuntu on your server. If path/Publickey is your key and the key is in ~ubuntu/.ssh/authorized_keys, you'll need the -i flag. Without it, ssh will look in the user's default (i.e. ~/.ssh/id_rsa). This should do it:
scp -i path/Publickey -r path/folder ubuntu@ec2-52-15-128-161.us-east-2.compute.amazonaws.com:/srv/shiny-server


text:
Q: GuzzleHttp resulted in 404 not found on a route that exists I am sending request to POST api.myserver.com/v1/oauth/token to get a token with client_credentials as follows:
$client = new GuzzleHttp\Client; // A guzzle client
$response = $this->client->post('http://api.myserver.com/v1/oauth/token', [
  'form_params' => [
    'grant_type' => 'client_credentials',
    'client_id' => 'MY_CLIENT_ID',
    'client_secret' => 'MY_CLIENT_SECRET',
    'scope' => ''
  ],
  'headers' => [
    'Accept' => 'application/json'
  ]
));

I am using apiato framework so the default laravel passport token generating routes have been modified to something like api.myserver.com/v1/oauth/token and hence the path.
Now the code above is throwing a 404 not found exception when I run it from the browser. It's working fine when I run it on POSTman. And also it works fine when I run it in the test environment.
Client error: `POST http://api.myserver.com/v1/oauth/token` resulted in a `404 Not Found` response:
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" co (truncated...)

I tried changing the path to http://myserver.com/oauth/token with no luck. What could be going wrong?

A: This is happening to me specifically with the client_credentials grant_type. If I use authorization_code it works. Not sure why yet.

A: Well, the reason you're getting 404 when you try to reach this endpoint using the browser is because it is a POST request. When you reach a URL via browser it is a GET request.


text:
Q: Proof of equivalence of solutions to initial value problem given same gradient I have two functions $x(t)$ & $y(t)$ I have $x(0) = y(0)$ and that  $\dot{x} = f(x,y)$ & $\dot{y} = g(x,y)$ I have that when $x = y$, $\dot{x} = \dot{y}$.
I want to show that $x(t) = y(t)$, I don't know how to formalise this however.


text:
Q: Using @material-ui/lab's DataGrid component, how do you access the current active filters? I am integrating material-ui's data grid into one of my pages. The goal is to be able to catch the state of the filters and sorts for all the columns and save that as a link at the top of the page so users do not need to reset up the spreadsheet with their preferred values each time they load the page. The following code successfully  'pauses' the filter changes and at the point where I have the alert box I can capture all the sort orders by using
this.getSortModal()

However, I cannot find a similar function to capture the current active filter(s). How do I access the active filters in this componenet? Here is the rest basic jsx file:
import React, { useState } from "react";
import ReactDOM from 'react-dom';
import { DataGrid, GridRowsProp, GridColDef } from '@material-ui/data-grid';
import "regenerator-runtime/runtime";

function filterModelChanged()
{
    //Need to catch the sort and filter preferences here

    alert("you got in");
}
function Example({ initialRows, columns }) {
    //const [filters, setFilters] = useState({});
    const [rows, setRows] = useState(initialRows);
    //const filteredRows = getRows(initialRows, filters);

    return (
        <div style={{ height: 300, width: '100%' }}>
        <DataGrid rows={rows} columns={columns} onFilterModelChange={filterModelChanged}/>
            </div>
    );
}

//
async function getData() {
    let response = await fetch("/services/reader_worklist_services/getList",
                                {credentials:"same-origin"});
    return await response.text();
}

//Need to wait till all elements are present before 'latching' onto them with the react componenet
document.addEventListener("DOMContentLoaded", function(event) {
    getData().then(function(data) {
        const rootElement = document.getElementById('reader_worklist_container');
        const jsData = JSON.parse(data);
        //const rows = createRowData(50);
        //ReactDOM.render(<Example initialRows={rows} columns={columns} />, rootElement);
        ReactDOM.render(<Example initialRows={jsData.rows} columns={jsData.columns}  />, rootElement);
        //alert("your data is: " + data);
    });
});

A: Both onFilterModelChange() and onSortModelChange() change expose the corresponding model within the params of the callback. In the case of filtering, onFilterModelChange() exposes a GridFilterModelParams model. Because of this, you could do something like the following:
const onFilterModelChange = (filterObject) => {
    // Do something here
};

Resources:

*

*https://material-ui.com/api/data-grid/


text:
Q: SnakeYAML polymorphy I want to parse Docker-compose.yml with SnakeYAML (or some other parser). The issue I run into is with attributes that can either be a String or a more complex object, like configs, which support a "short" syntax and a "long" syntax:
short
version: "3.3"
services:
  redis:
    image: redis:latest
    deploy:
      replicas: 1
    configs:
      - my_config
      - my_other_config
configs:
  my_config:
    file: ./my_config.txt
  my_other_config:
    external: true

long
version: "3.3"
services:
  redis:
    image: redis:latest
    deploy:
      replicas: 1
    configs:
      - source: my_config
        target: /redis_config
        uid: '103'
        gid: '103'
        mode: 0440
configs:
  my_config:
    file: ./my_config.txt
  my_other_config:
    external: true

How can I map this to SnakeYAML? Currently I have created Java Beans to model the different elements, and model configs as List<String> but that obviously only works for the short syntax.

A: If SnakeYaml encounters a String where it expects to deserialize an object, it looks for a constructor with a String argument.
So in the example, it is enough to define a JavaBean for the long syntax of config, and then add a constructor to that which takes the short syntax as argument.


text:
Q: Unable to connect to mysql container on Asp.Net Core I'm trying to containerize an Asp.Net Core application using Docker but on docker compose up aspnet app logs Unable to connect to any of the specified MySQL hosts and exits. I've read that Docker uses it's own internal network and provides DNS to connect to other container, so I use mysql service name in connection string, but it still doesnt connect.It was working, when I only used docker to run mysql container, and exposed port 3306 to host, but for some reason it doesnt work now. What am I missing?docker-compose
version: '3'

services:
  mysql:
    image: mysql:8
    environment:
      MYSQL_DATABASE: ctox_db
      MYSQL_ROOT_PASSWORD: 019638
    volumes:
      - mysqldata:/var/lib/mysql
    networks:
      - ctox_net

  ctoxweb:
    build: .
    depends_on:
      - mysql
    environment:
      - "ConnectionStrings:AppContext=server=mysql; port=3306; database=ctox_db; user=root; password=019638"
    links:
      - mysql
    networks:
      - ctox_net

volumes:
  mysqldata:

networks:
  ctox_net:
    driver: bridge

Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    // other services ...
    var appContextConnection = Configuration.GetConnectionString("AppContext");
    services.AddDbContext<AppDbContext>(options =>
        options
            .UseLazyLoadingProxies()
            .UseMySql(appContextConnection, ServerVersion.AutoDetect(appContextConnection)));
}

PS I added environment variables to configuration, connection string is pulled correctly.

A: It turns out that the problem was not in the docker-compose or web app but in the mysql container. I thought that depends_on would magically wait for mysql server to start and be ready to receive connections, however as documentations suggests (Control startup) developer should rather depend on application itself to wait for database and try to reestablish connection.For someone who needs a quick fix that might be acceptable on small projects (be aware, it's not recommended) just add restart: on-failure to your web app in docker-compose file


text:
Q: Way to generate Gson in Java I looking for the best solution to generate Gson in Java:
For example I want to get String like:
{
   "mainContainer":{
      "firstContainer":{
         "value":"1"
      },
      "secondContainer":{
         "value":"2"
      }
   }
}

The first way (faster to implement) it to use JsonBuilderFactory:
JsonBuilderFactory factory = Json.createBuilderFactory(config);
JsonObject value = factory.createObjectBuilder()
     .add("mainContainer", factory.createObjectBuilder()
         .add("firstContainer", factory.createObjectBuilder()
             .add("value", "1")
         .add("secondContainer", factory.createObjectBuilder()
             .add("value", "2"))
     .add("phoneNumber", factory.createArrayBuilder()))
.build();

and the second solution (I think it should works faster):
public class JsonClass {
    MainContainer mainContainer;
    public JsonClass(String projectId, String parentKey){
            mainContainer = new MainContainer(projectId, parentKey);
    }
    class MainContainer{
        private FirstContainer firstContainer;
        private SecondContainer secondContainer;
        public MainContainer(String f, String s){
            firstContainer = new FirstContainer(f);
            secondContainer = new SecondContainer(s);
        }
        class FirstContainer{
            protected String value;
            public FirstContainer(String value){this.value = value;}
        }
        class SecondContainer{
            private String value;
            public SecondContainer(String value){this.value = value;}
        }
    }
}

and then:
String myJson = gson.toJson(new JsonClass("1","2"));
What solution is better? I dont care about implementation time, just about works time.


text:
Q: Выбор платформы для написания программы Добрый всем вечер (день, утро, ночь).
Собираюсь написать небольшую программу для планирования и учета факта оказания услуг клиентам, выгрузки в региональные органы власти отчетов в формате Эксел.
Сейчас эти задачи решаются в экселе. Но, естественно, работать неудобно.
Планирую использовать C#. Изучаю.
Но есть пара проблем. Пока пара.))
1. Какую платформу использовать для разработки оконного интефейса Windows Forms или Windows Presentation Foundation?
2. Какую СУБД выбрать FireBird, MySQL или MS SQL Express?
Какие преимущества или минусы можно выделить при сравнении программного обеспечения? Возможно есть типовые решения?
Прошу совета.


text:
Q: set background color for body depending on if/else statement I don't know if this is possible but I want to know if I can set the background color of a page depending on an if/else statement?
What I want is that if the if statement is met, then I want the background color of the body to be white, if the else statement is met where it contains a div, then I want the background color of the body to be grey.
Can this be done?
      <?php

if (page()){

//all the code in the page

}else{
?>

<?php

}

?>

UPDATE:
<?php

        if (page()){
?>

    <body class="bodypage <?php echo page()? "color1":"color2" ?>" >

<?php

    }else{

    <a href="<?php echo $pages[$currentPages+1] ?>">Continue with Current Assessment

    }

?>

A: Yes it can be. How about you use a predefined class that have the background color you need:
.color1 {
   background-color:red;
}
.color2 {
   background-color:yellow;
}

<body class="boxed <?php echo page()? "color1":"color2" ?>" >

UPDATE:
<body class="bodypage <?php echo page()? "color1":"color2" ?>" >
<?php if (page()){?>
... all the page code
<?php else {?>

   <a href="<?php echo $pages[$currentPages+1] ?>">Continue with Current Assessment

?>

A: A zillion ways to do this.
PHP:
$bodyClass = $condition ? 'foo' : 'bar';
...
echo <<< END_HTML

END_HTML;

CSS:
body.foo { background-color:#fff; }
body.bar { background-color:#888; }

..is one way to do it.
Cheers

A: Try this
<body <?php if(true) {echo('style="background:red"'); } else { echo('style="background:white"'); } ?> >

A: You can do it this way using javascript & jQuery:

Or in php you can just echo that code, with some changes.

A: Try to minimize the php influence on your design. (CSS for design, html for semantics, php for structure and javascript for interaction)
To accomplish this I recommend sending a hidden input to the browser containing a value:
if(statement) {
  $color = '#ffffff';
} else {
  $color = '#ff0000';
}

echo '<input id="pageColor" type="hidden" value="'.$color.'" />';

Now do the following with (for example) jquery:
$(document).ready(function() {
  //change bg color based on input value
  $('body').css('background-color', $('#pageColor').val());
});

A: Yep, you can do this.
One of the most elegant ways:
PHP part:
<?php
$style = 'background:'; # property
$given = page() ? 'red;' : 'black;'; # Ternary operator
$style .= $given; # Concatenate two strings
?>

HTML part:
<div class="boxed" style='<?php echo $style; ?>'>

Also you can create special CSS classes with predefined variety of CSS properties:
PHP part:
<?php
$class = page() ? 'first' : 'second'; # CSS classes defined in your stylesheet.
?>

HTML part:
<div class="boxed <?php echo $class;?>">

And here you go. That's just a quick demonstration, you can replace this with you parameters.


text:
Q: MIPS Coding Assignment: Translating multiplication via repeated addition I have an assignment and I have to convert a line of C++ code into MIPS and then run the code. I have been continuously getting the same error, and some suggestions on how to fix it would be great. The info needed is below.
I have been given this C++ Code to convert to MIPS.
int multiply(int x, int y)
{
    int product=0;
if(x>y)
    for(int i=0;i<y;i++)
        product+=x;
if(y>x)
    for(int i=0;i<x;i++)
        product+=y;
return product;
}

I have converted it to MIPS Code here:
multiply(int, int):
        daddiu  $sp,$sp,-48
        sd      $fp,40($sp)
        move    $fp,$sp
        move    $3,$4
        move    $2,$5
        sll     $3,$3,0
        sw      $3,16($fp)
        sll     $2,$2,0
        sw      $2,20($fp)
        sw      $0,0($fp)
        lw      $3,16($fp)
        lw      $2,20($fp)
        slt     $2,$2,$3
        beq     $2,$0,.L2
        nop

        sw      $0,4($fp)
        b       .L3
        nop

.L4:
        lw      $3,0($fp)
        lw      $2,16($fp)
        addu    $2,$3,$2
        sw      $2,0($fp)
        lw      $2,4($fp)
        addiu   $2,$2,1
        sw      $2,4($fp)
.L3:
        lw      $3,4($fp)
        lw      $2,20($fp)
        slt     $2,$3,$2
        bne     $2,$0,.L4
        nop

.L2:
        lw      $3,20($fp)
        lw      $2,16($fp)
        slt     $2,$2,$3
        beq     $2,$0,.L5
        nop

        sw      $0,8($fp)
        b       .L6
        nop

.L7:
        lw      $3,0($fp)
        lw      $2,20($fp)
        addu    $2,$3,$2
        sw      $2,0($fp)
        lw      $2,8($fp)
        addiu   $2,$2,1
        sw      $2,8($fp)
.L6:
        lw      $3,8($fp)
        lw      $2,16($fp)
        slt     $2,$3,$2
        bne     $2,$0,.L7
        nop

.L5:
        lw      $2,0($fp)
        move    $sp,$fp
        ld      $fp,40($sp)
        daddiu  $sp,$sp,48
        jr      $31
        nop

I continue to receive this error code, and I am trying to figure out how to fix this:
spim: (parser) syntax error on line 1 of file D:/Sophomore Year ('21-'22)/Spring Semester - 2022/CS-3365 (Intro to Comp Org and Arch)/MIPS Assignment 2.asm
  multiply(int, int):
          ^

Does anyone have any suggestions?

A: It seems you are using the assembly generated by a MIPS64 compiler instead the one generated by a MIPS32 one. If this is a homework assignment you probably should just compile the C function manually instead of using a compiler.
Using godbolt you may see the assembly for a couple of MIPS32 compilers.
Here goes one of them (mips gcc 5.4) along with a sample call:
.data
str: .asciiz "Result: "
.text
main:

# sample multiplication
  la $a0, str
  li $v0, 4
  syscall  # print msg

  li $a0, 10  # test multiply 10 * 5
  li $a1, 5
  jal multiply_int_int   # compute multiplication
  move $a0, $v0
  li $v0, 1
  syscall    # print result

  li $v0, 10
  syscall    # exit

multiply_int_int:
        addiu   $sp,$sp,-32
        sw      $fp,28($sp)
        move    $fp,$sp
        sw      $4,32($fp)
        sw      $5,36($fp)
        sw      $0,8($fp)
        lw      $3,32($fp)
        lw      $2,36($fp)
        nop
        slt     $2,$2,$3
        beq     $2,$0,$L2
        nop

        sw      $0,12($fp)
$L4:
        lw      $3,12($fp)
        lw      $2,36($fp)
        nop
        slt     $2,$3,$2
        beq     $2,$0,$L2
        nop

        lw      $3,8($fp)
        lw      $2,32($fp)
        nop
        addu    $2,$3,$2
        sw      $2,8($fp)
        lw      $2,12($fp)
        nop
        addiu   $2,$2,1
        sw      $2,12($fp)
        b       $L4
        nop

$L2:
        lw      $3,36($fp)
        lw      $2,32($fp)
        nop
        slt     $2,$2,$3
        beq     $2,$0,$L5
        nop

        sw      $0,16($fp)
$L7:
        lw      $3,16($fp)
        lw      $2,32($fp)
        nop
        slt     $2,$3,$2
        beq     $2,$0,$L5
        nop

        lw      $3,8($fp)
        lw      $2,36($fp)
        nop
        addu    $2,$3,$2
        sw      $2,8($fp)
        lw      $2,16($fp)
        nop
        addiu   $2,$2,1
        sw      $2,16($fp)
        b       $L7
        nop

$L5:
        lw      $2,8($fp)
        move    $sp,$fp
        lw      $fp,28($sp)
        addiu   $sp,$sp,32
        jr       $31
        nop


text:
Q: Why ^*$ matches "127.0.0.1" I don't understand, why does the following regular expression:
^*$

Match the string "127.0.0.1"? Using Regex.IsMatch("127.0.0.1", "^*$");
Using Expresso, it does not match, which is also what I would expect. Using the expression ^.*$ does match the string, which I would also expect.
Technically, ^*$ should match the beginning of a string/line any number of times, followed by the ending of the string/line. It seems * is implicitly treated as a .*
What am I missing?
EDIT:
Run the following to see an example of the problem.
using System;
using System.Text.RegularExpressions;

namespace RegexFubar
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Regex.IsMatch("127.0.0.1", "^*$"));
            Console.Read();
        }
    }
}

I do not wish to have ^*$ match my string, I am wondering why it does match it. I would think that the expression should result in an exception being thrown, or at least a non-match.
EDIT2:
To clear up any confusion. I did not write this regex with the intention of having it match "127.0.0.1". A user of our application entered the expression and wondered why it matched the string when it should not. After looking at it, I could not come up with an explanation for why it matched - especially not since Expresso and .NET seems to handle it differently.
I guess the question is answered by it being due to the .NET implementation avoiding throwing an exception, even thought it's technically an incorrect expression. But is this really what we want?

A: Asterisk (*) matches the preceding element ZERO OR MORE times. If you want one or more, use the + operator instead of the *.
You are asking it to match an optional start of string marker and the end of string marker. I.e. if we omit the start of string marker, you're only looking for the end of string marker... which will match any string!
I don't really understand what you are trying to do. If you could give us more information then maybe I could tell you what you should have done :)

A: Well, theoretically you are right, it should not match. But this depends on how the implementation works internally. Most regex impl. will take your regex and strip ^ from the front (taking note that it must match from start of the string) and strip $ from the end (noting that it must to the end of the string), what is left over is just "*" and "*" on its own is a valid regex. The implementation you are using is just wrong regarding how to handle it. You could try what happens if you replace "^*$" just with "*"; I guess it will also match everything. It seems like the implementation treats a single asterisk like a ".*".
According to ISO/IEC 9945-2:1993 standard, which is also described in the POSIX standard, it is broken. It is broken because the standard says that after a ^ character, an asterisk has no special meaning at all. That means "^*$" should actually only match a single string and this string is "*"!
To quote the standard:

The asterisk is special except when used:

*

*in a bracket expression

*as the first character of an entire BRE (after an initial ^, if any)

*as the first character of a subexpression (after an initial ^, if any); see BREs Matching Multiple Characters .

So if it is the first character (and ^ doesn't count as first character if present) it has no special meaning. That means in this case an asterisk should only match one character and that is an asterisk.

Update
Microsoft says

Microsoft .NET Framework regular
expressions incorporate the most
popular features of other regular
expression implementations such as
those in Perl and awk. Designed to be
compatible with Perl 5 regular
expressions, .NET Framework regular
expressions include features not yet
seen in other implementations, such as
right-to-left matching and on-the-fly
compilation.

Source: http://msdn.microsoft.com/en-us/library/hs600312.aspx
Okay, let's test this:
# echo -n 127.0.0.1 | perl -n -e 'print (($_ =~ m/(^.*$)/)[0]),"\n";'
-> 127.0.0.1
# echo -n 127.0.0.1 | perl -n -e 'print (($_ =~ m/(^*$)/)[0]),"\n";'
->

Nope, it does not. Perl works correctly. ^.*$ matches the string, ^*$ doesn't => .NET's regex implementation is broken and it does not work like Perl 5 as MS claims.

A: If you try
Regex.Match("127.0.0.1", "^*1$")

You'll see it also matches. The Match.Index property has a value of 8, meaning that it matched the last '1', not the first one. It makes sense, because "^*" will match zero or more beginning-of-lines and there is zero beginning-of-line before '1'.
Think of the way "a*1$" would match because there is no 'a' before "1$". So "a*$" would match with the end of line, like your example does.
By the way, the MSDN docs don't mention '*' ever matching simply '*' except when escaped as '\*'. And '*' by itself will throw an exception, not match '*'.

A: You are effectively saying "match a string that contains nothing or anything". So it's going to match. The ^ and $ bindings don't really make a difference in this case.

A: Illegal regexp apart, what you want to write is most likely not that.
You write: "^*$ should match the beginning of a string/line any number of times, followed by the ending of the string/line", which implies you want multiline regexps, but you forget that a line cannot start twice, without a line end inbetween.
Also, what you're asking in your requirements actually fits "127.0.0.1" :) A ^ is not a line feed/carriage return but also the begin of a line, and $ is not just a newline but the end of a line.
Also, * matches as much as possible (except when ungreedy mode is set), which means that the regexp /^.**$/ regexp will match everything. If you want to manage newlines, you have to code these explicitly.
Hope this clarifies something :)

A: The POSIX regex standard is really old and limited. The few tools that still follows it today, such as grep, sed and friends, are mostly on a unix/linux shell. Perl and PCRE are two, much extended flavors, in which almost nothing mentioned in the POSIX standard still holds true.
http://www.regular-expressions.info/refflavors.html
In PCRE and Perl, the engine treats ^ and $ as tokens that match the beginning and end of the string (or line if the multiline flag is set). * simply repeats the ^ marker zero or more times (in this case, exactly zero times). The engine thus only looks for the end of the source string, which matches any string.

A: Using RegexDesigner, I can see it's matching on a 'null' token after '127.0.0.1'. Seems that because you haven't specified a token and the plus matches zero or more times, it matches on the 'null' token.
The following regex should work:
^+$


text:
Q: Is VSS 2008 free? In my company we use Visual Studio 2008. Is VSS 2008 free?

A: The last version of Visual Source Safe was VSS 2005.
I'm not sure if it has been released free or not...but even if it was, I'd suggest you stear clear. There are plenty of Open Source alternatives with good Visual Studio Integration.
You could try Subversion (server based), Git (distributed), or Mercurial (distributed).

A: First off, there is no VSS 2008. There is VSS 2005.
Second, it comes with certain versions of Visual Studio.
From this blog entry:

There is no VSS 2008

and

Q: Where do I get VSS2005 anyway?
A: If you have a Team Edition of Visual Studio 2005 or later, then VSS2005 is included in your license.  It was included on the VSTS 2005 set of discs; you can also download it from MSDN.  If you have a Professional Edition of Visual Studio or lower then you need to purchase VSS separately.

A: From Wikipedia:

The final version of the product,
  Visual SourceSafe 2005, is retired
  from mainstream support on 12 April
  2011 with extended support ending on
  12 April 2016.

There is no VSS 2008.


text:
Q: Nesting elements in css I have the following html:

Title1

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus varius rutrum aliquet.

and I am trying to apply some css to the image.
When I try
.m-card-with-icon {
min-height: 244px;
text-align: left;
background-color: #fafafa;
color: #848484;
cursor: pointer;
display: block;
position: relative;

   .top {
        min-height: 100px;
        line-height: 60px;
        padding: 20px 180px 20px 40px;
        text-transform: capitalize;
        display: table;
        width: 100.5%;

        img.icon {
            position: absolute;
            right: 25px;
            top: 25px;
            width: 140px;
            height: 140px;
            background-color: #fff;
            border-radius: 100%;
            padding: 10px;
            display: table-cell;
            vertical-align: middle;
        }

   }

}

whatever style I apply to img.icon does not show up - the images remain left-aligned.
Is there a problem with how I am nesting css?

A: Probably, you want this:
(We don't use nesting. Instead, you can "simulate" nesting by put parent element before child: .m-card-with-icon .top).
.m-card-with-icon {
    min-height: 244px;
    text-align: left;
    background-color: #fafafa;
    color: #848484;
    cursor: pointer;
    display: block;
    position: relative;
}

.m-card-with-icon .top {
    min-height: 100px;
    line-height: 60px;
    padding: 20px 180px 20px 40px;
    text-transform: capitalize;
    display: table;
    width: 100.5%;
}

.m-card-with-icon .top img.icon {
    position: absolute;
    right: 25px;
    top: 25px;
    width: 140px;
    height: 140px;
    background-color: #fff;
    border-radius: 100%;
    padding: 10px;
    display: table-cell;
    vertical-align: middle;
}

A: I don't think you can nest using css, but rather use scss or sass or less.
if you use scss then it will become
.m-card-with-icon {
  min-height: 244px;
  text-align: left;
  background-color: #fafafa;
  color: #848484;
  cursor: pointer;
  display: block;
  position: relative;

   .top {
    min-height: 100px;
    line-height: 60px;
    padding: 20px 180px 20px 40px;
    text-transform: capitalize;
    display: table;
    width: 100.5%;

      .icon {
        position: absolute;
        right: 25px;
        top: 25px;
        width: 140px;
        height: 140px;
        background-color: #fff;
        border-radius: 100%;
        padding: 10px;
        display: table-cell;
        vertical-align: middle;
      }
   }
 }

A: On another note, if you have control over the HTML, it would be ideal to use something like SMACSS or BEM.
Instead of nesting, you'll find that if you scope your CSS to use a single, unique class for every specific node. If you use a name prefixing methodology you can keep your class names organized.
For example rather than .m-card-with-icon top {} you can target .m-card-with-icon-top {}
Nesting can create complicated specificity rules and performance problems and you may find that a flat CSS might make your CSS more object oriented and modular.


text:
Q: How to resolve /check1 failed with the error "dispatch_unknown_error" error in slack channel? I want to run/trigger a jenkins job from slack channel. For that I was trying to use slash command.
But when I am entering the command, I am getting,
/check1 failed with the error "dispatch_unknown_error" error in slack.
Here /check1 is command name which I have given.
Can anyone Please Please tell me, what is issue here, and how to resolve it?
If you have some anoter way to trigger a jenkins job from slack channel, that is also fine.


text:
Q: Crash in Android UDP server UPDATED:
I get crash in this Android UDP server example:
    //------------------------------------------------------------
public class AsyncReceiveUdp2 extends AsyncTask<String, Void, Boolean> {
    @Override
    protected Boolean doInBackground(String... f_url) {
        int udp=111;
        String txt="";
        byte[] packet = new byte[2000];
        DatagramPacket dp = new DatagramPacket(packet, packet.length);
        DatagramSocket ds = null;
        try {
            ds = new DatagramSocket(udp);
            ds.setSoTimeout(10000);
            printLog("Ready");
            ds.receive(dp);
            printLog("Received");
            ...
        } catch (SocketException e) {
            printLog("Error1");
            e.printStackTrace();
        } catch (IOException e) {
            printLog("Error2");
            e.printStackTrace();
        } finally {
            if (ds != null) {
                ds.close();
            }
        }

        return null;
    }
}

I get my "error2" message.
The reason is "java.net.SocketTimeoutException".
It happens after 10 seconds.
But I sent UDP packet from another computer.
Hmm, I don't understand how it works....
 Any ideas please!

Sorry for extra line, the site said that my post is mostly code
Sorry for extra line, the site said that my post is mostly code
Sorry for extra line, the site said that my post is mostly code

A: You cannot run network threads on the UI thread, Android policy forbids it. Make a new thread or use AsyncTask


text:
Q: Multiple UICollectionView in one controller I have a view set up with two UICollectionViews. Each of these views has an array backing it with different sizes. collection1 is backed by array1, and collection2 is backed by array2. The problem is, what ever number is returned for collection1 from numberOfItemsInSection is being applied to both collection views.
For instance, if array1 is size 4 and array2 is size 5, both collections will show 4 elements. If array1 is size 5 and array2 is size 4, when I scroll collection2 all the way it calls cellForItemAtIndexPath with an itemIndex of 5 for collection2 and I get an NSRangeException.
How can I make each collectionView use it's own size?
- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section;
{
    if(view == self.colleciton1){
        return self.array1.count;
    } else if (view == self.collection2){
        return self.array2.count;
    }

    return 0;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath;
{
    if(cv == self.collection1){
        CharacterCell *cell = [cv dequeueReusableCellWithReuseIdentifier:FIRST_CELL_IDENTIFIER forIndexPath:indexPath];
        cell.label.text = self.array1[indexPath.item];
        return cell;
    } else if (cv == self.collection2){
        EpisodeCell *cell = [cv dequeueReusableCellWithReuseIdentifier:SECOND_CELL_IDENTIFIER forIndexPath:indexPath];
        cell.label.text = self.array2[indexPath.item];
        return cell;
    }

    return nil;
}

I've included a git repo with a project illustrating the problem.
git@github.com:civatrix/MultipleCollectionViews.git

A: Probably it would be easier to use ContainerViews and have two separate UICollectionView Controllers for each UICollectionView

A: The problem was that I was using the same layout object for each collection. In retrospect that makes sense, but you have to make sure you create different layouts for each collectionView.

A: What you have should work. Are self.colleciton1 and self.collection2 IBOutlets? If so, can you double check that they are hooked up correctly?


text:
Q: Implement of original strlcpy function on Libc #include <stdio.h>
#include <string.h>

size_t  ft_strlcpy(char *dst, const char *src, size_t dstsize)
{
    unsigned int    i;
    unsigned int    dst_len;

    i = 0;
    dst_len = strlen(dst);
    if (dstsize > 0)
    {
        while (src[i] != '\0' && i < dstsize - 1)
        {
            dst[i] = src[i];
            i++;
        }
        dst[i] = '\0';
    }
    return (strlen(src));
}

int    main(void)
{
    char dst[100] = "HelloWorld!";
    char dst2[100] = "HelloWorld!";

    const char src[11] = "teststring";
    int dstsize = -1;
    printf("mine : %zu\n", ft_strlcpy(dst, src, dstsize));
    printf("%s\n", dst);
    printf("string.h : %zu\n", strlcpy(dst2, src, dstsize));
    printf("%s\n", dst2);

    return (0);
}

This code is my code of implementing strlcpy on my own.
but I have one doubt question.
when dstsize is negative number, my fucntion don't print any error message.
but original strlcpy print Tracetrap error(maybe SIGILL in linux. I'm using OS X)

I have searched most of bsd original c library github, but all of them work same as my code. I want to know the difference. how original strlcpy print error when dstsize is negative number?
This question's point is "how to print trace trap error when dstsize is negative number like original function?(I know it will be converted to size_t max number.)"

A: There is no reason to compute the length of the string in dst for strlcpy: dst_len = strlen(dst); is useless and counterproductive.
Here is a modified version:
size_t  ft_strlcpy(char *dst, const char *src, size_t dstsize)
{
    size_t    i;

    i = 0;
    while (i + 1 < dstsize && src[i] != '\0') {
        dst[i] = src[i];
        i++;
    }
    if (i < dstsize) {
        dst[i] = '\0';
    }
    while (src[i] != '\0') {
        i++;
    }
    return i;
}

Regarding your question:

how to print trace trap error when dstsize is a negative number?(I know it will be converted to size_t max number.)

If the destination size passed by the caller is a negative number, ie: the result of some computation that produces or would produce a negative number using signed arithmetics, it is converted to size_t modulo SIZE_MAX + 1, hence the value is huge.
You can detect this by comparison:
 if (dstsize > SIZE_MAX >> 1) {
     fprintf(stderr, "ft_strlcpy: huge dstsize indicates a negative value was passed: %zd\n", dstsize);
     abort();
 }


text:
Q: Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0. - Android Studio I'm new to Android Studio and when I try to run my app I get this error:
Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.
Use '--warning-mode all' to show the individual deprecation warnings.

I understand I should run gradle build with --warning-mode all see the deprecated features, and --stacktrace to pinpoint where it's coming from but I don't how to run it, and I don't even know where the  gradle build is.
So I'd appreciate if you could point me in the direction of the gradle, and how to run it, a screenshot would be clearer though..
If you need any information, I'm happy to provide it. Thank you, in advance..


text:
Q: Can the C# method interface be redesign to get rid of `new string[] {}` to improve readability? Having a method as follows, I would like to simplify passing the arguments when using it:
public virtual Segment AddDataElement(string[] dataElement)
{
    dataElementList.Add(dataElement);
    return this;
}

The method is called many times like this:
message.AddSegment("NAD")
    .AddDataElement(new string[] { partyFunctionCodeQualifier })
    .AddDataElement(new string[] { partyIdentifier, "", "92" });

Is it possible to modify the method definition so that it would be possible to write more readable call lile this?
message.AddSegment("NAD")
    .AddDataElement(partyFunctionCodeQualifier)
    .AddDataElement(partyIdentifier, "", "92");

Can the later be internally transformed to the earlier form?

A: Yes, you can absolutely do this.
Firstly, you can use implicit array typing to reduce new string[] to new[]:
.AddDataElement(new[] { partyFunctionCodeQualifier })

Secondly, you can change the parameter to be a parameter array with the params keyword:
public virtual Segment AddDataElement(params string[] dataElement)

At that point, you can indeed specify just a single string - or multiple strings without building an array in source code. The compiler will create the array for you.


text:
Q: My Update Query Retrieves Nulls Access 2007 I created an update query through access 2007, I simply wanted to update the empty rows to another columns in the table.
                    UPDATE DISTINCTROW (ChangeList INNER JOIN (Current_INFO INNER JOIN Master_Database ON
                    Current_INFO.[HEADER ID] = Master_Database.[HEADER ID]) AND (Current_INFO.[HG ID] = Master_Database.[HG ID])) ON
                    ChangeList.[ZIP/POSTALCODE] = Master_Database.[ZIP/POSTALCODE]) INNER JOIN ChangeRequest ON
                    Master_Database.[ZIP/POSTALCODE] = ChangeRequest.[ZIP/POSTALCODE] SET ChangeList.[CHANGE TA TO] = [Master_Database]![TA]
                    WHERE (((UCase([ACTION]))='UPDATE'));

This however doesn't work, it just returns me null values however if i turn this query into a simple select where i call [Master_Database]![TA] it returns me  the values i require.
Can anyone assist me please.Thank you!


text:
Q: saving state on compound view widgets Question
How do you save view widget instance state when, by using XML-defined widget layouts, components of the individual widget instances all have the same ID?
Example
Take, for example, the NumberPicker widget that's used in the TimePicker widget (note that NumberPicker is not exposed to the SDK). This is a simple widget with three components which are inflated from number_picker.xml: one increment button, one decrement button, and one EditText where you can directly enter a number. In order for the code to interact with these widgets, they all have IDs (R.id.increment, R.id.decrement and R.id.timepicker_input respectively).
Let's say you have three NumberPickers in an XML layout and you give them distinct IDs (eg. R.id.hour, R.id.minute).¹ This layout is then inflated to the content view of an activity. We decide to change the activity's orientation, so Activity.onSaveInstanceState(Bundle) helpfully saves our view state for each view that has an ID (this is the default behavior).
Unfortunately, the three NumberPickers have EditTexts that all share the same ID — R.id.timepicker_input. Thus, when the activity is restored, the one furthest down in the view hierarchy is the one whose state seems to be preserved for all three of them. Additionally, the focus goes to the first NumberPicker when restored regardless of which one had focus when saved.
TimePicker gets around this problem by preserving the state itself, separately. Unfortunately, this won't preserve the cursor position or the focused view without a lot more work. I'm not sure how it preserves that state if it does at all (and quickly playing with a time input dialog seems to indicate that it can somehow).
Please see the sample code to demonstrate this issue:
https://github.com/xxv/AndroidNumberPickerBug

¹ In the view hierarchy, this sets the ID of the LinearLayout that NumberPicker extends to your IDs.

A: I stumbled across the same issue when trying to create my own compound view. From looking at the Android source code I believe the correct way to implement compound views is for the compound view itself to take on the responsibility of saving and restoring the instance state of its children and to prevent the calls to save and restore instance state from being passed onto the child views. This works around the issue of the IDs of child views not being unique when you have more then one instance of the same compound view in an activity.
This might sound complicated but it is really quite easy and the APIs actually make provision for this exact scenario. I've written a blog post here on how this is done but essentially in your compound view you need to implement the following 4 methods, customising onSaveInstanceState() and onRestoreInstanceState() to meet your specific requirements.
@Override
protected Parcelable onSaveInstanceState() {
    Parcelable superState = super.onSaveInstanceState();
    return new SavedState(superState, numberPicker1.getValue(), numberPicker2.getValue(), numberPicker3.getValue());
}

@Override
protected void onRestoreInstanceState(Parcelable state) {
    SavedState savedState = (SavedState) state;
    super.onRestoreInstanceState(savedState.getSuperState());

    numberPicker1.setValue(savedState.getNumber1());
    numberPicker2.setValue(savedState.getNumber2());
    numberPicker3.setValue(savedState.getNumber3());
}

@Override
protected void dispatchSaveInstanceState(SparseArray container) {
    // As we save our own instance state, ensure our children don't save
    // and restore their state as well.
    super.dispatchFreezeSelfOnly(container);
}

@Override
protected void dispatchRestoreInstanceState(SparseArray container) {
    /** See comment in {@link #dispatchSaveInstanceState(android.util.SparseArray)} */
    super.dispatchThawSelfOnly(container);
}

Regarding the problem with NumberPicker/TimePicker, as mentioned in another comment there appears to be a bug with NumberPicker and TimePicker. To fix it you could override both and implement the solution I've described.

A: I just ran into the exact same problem with a compound view
with three NumberPickers. I found a solution on another site
that involved reassigning the Id of the timepicker_input to
a unique random Id. This works but is complicated because once
a new Id is chosen, that Id must persist across configuration
changes so extra code is required to do that.
For my application, and probably in 99% of others, a much
simpler approach (hack) works. I realized that the namespace for
Ids has room for 65536 unique identifiers (0x7f090000 to
0x7f09ffff), but my application is only using 20 or so,
and they are allocated monotonically increasing from the
beginning. Furthermore, the NumberPicker widget itself
has a unique identfier within the tree (for example as in
the original post, R.id.hour, R.id.minute and R.id.second).
My solution is to reassign the Id of the EditText widget
to the Id of the NumberPicker widget plus an offset.
This is a one line change to the NumberPicker code. Simply
add:
mText.setId(getId() + 1000);

After the following line in NumberPicker.java:
mText = (EditText) findViewById(R.id.timepicker_input);

The offset of course can be adjusted based on application requirements.
I imagine the same approach will work for other compound widgets.
For the above example, this approach allows the state of the
individual EditText widgets to be saved and restored, and the
focused view as well.

A: I'm a little late to the game, but I wanted to give my input.
You can use the android:tag to group each View. Thus, you can 'reload' each state.
From the Android Developer website:

android:tag
Supply a tag for this view containing a String, to be retrieved later
  with View.getTag() or searched for with View.findViewWithTag().

A: I have a compound Widget with a state description consisting of a single integer mValue
Now override the following two methods like so:
@Override
protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
    if(getId() != NO_ID) {
        Parcel p = Parcel.obtain();
        p.writeInt(mValue);
        p.setDataPosition(0);
        container.put(getId(), new MyParcelable(p));
    }
}

@Override
protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
    if(getId() != NO_ID) {
        Parcelable p = container.get(getId());
        if(p != null && p instanceof MyParcelable) {
            MyParcelable mp = (MyParcelable) p;
            updateAllValues(mp.getValue());
        }
    }
}

In dispatchSaveInstanceState(), you're serializing your state. More complex states will require more complex storage structures.
Make sure to setDataPosition() correctly.
I'm only saving the state if the widget has an id assigned which I'm using as the parcel's tag
In dispatchRestoreInstanceState(), you're unpacking your parcel.
I'm only performing the unpack if the widget has an id assigned and the container contains a parcel with a tag matching this id.
The Parcelable must also be of the proper class.
Unpacking will be more complicated for more complex widgets.
The last component needed is a Parcelable subclass like the following:
static class MyParcelable implements Parcelable {

    private int mValue;

    private MyParcelable(Parcel in) {
        mValue = in.readInt();
    }

    public int describeContents() {
        return 0;
    }

    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(mValue);
    }

    int getValue() {
        return mValue;
    }

    public static final Parcelable.Creator<MyParcelable> CREATOR
        = new Parcelable.Creator<MyParcelable>() {

            public MyParcelable createFromParcel(Parcel source) {
                return new MyParcelable(source);
            }

            public MyParcelable[] newArray(int size) {
                return new MyParcelable[size];
            }
    };

}

Using this framework is much easier than manipulating fragments and managing configuration

A: Quite simple: You don't. Just go and disable the orientation change crap in your manifest file. The view state save mechanism is inherently flawed, they simply didn't think this through.
If you want to keep your state, you cannot reuse an id within a single activity. Which essentially means that you cannot use a single layout more than once, which makes more complex Widgets like TimePicker basically impossible to do properly.
You can make children keep their state by overriding dispatchSaveInstanceState and hacking it in, but I didn't find a way to keep focus as well, besides managing that yourself as well.
I think they could fix this by making state scope without breaking the API, but don't hold your breath.


text:
Q: process text info displayed by calling a terminal command in Matlab When I run a terminal command it generates some text data in the terminal display. Suppose blck is some executable software tool installed on my desktop. I call this tool in the terminal on a file named main.txt in the current working directiory like this:-
$ blck -f main.txt

This prints some information immediately below the command call. I have to process this text to glean some information from it. I have the matlab code to process this text. But how to call this terminal command in Matlab and then transfer the resulting text information to Matlab variables. once I have the information displayed from the command call in Matlab then I can simply run my processing code on it.


text:
Q: Facebook graph api - does not return shares for some posts I have problem with graph api since about 2 months. Api does not return shares count for same posts from my fanpage. All posts has the same restrictions.
My endpoint:
https://graph.facebook.com/{fanpageId}/posts?access_token={token}&fields=application,created_time,likes.summary(true),comments.summary(true),shares,name,link,from,type,picture&limit=100

I have no idea why...


text:
Q: How to change file extension from .txt to .rtf in ios programmatically? How do I change a file extension from .txt to .rtf in iOS programmatically?
In xml parsing I'm getting rtf data with rtf tags.
Is it possible to save data in a rtf file without tags?
If we load that file, this was loading with rtf tags in webview.
If we open and save that file physically, it opens in the WebView.
Is there any way to do this task (File Open & Save) programmatically using iOS.
If we load the rtf file from FTP server, upto tables it was loading(only plain text before tables)

A: using function of NSString
NSString *string2 = [[NSString alloc] initWithContentsOfFile:@"whateverFile.rtf"];

get the text only from the file and save it in .txt format using the
NSMutableString *mutstr2 = [[NSMutableString alloc] init];
[mutstr2 setString: string2];
[mutstr2 writeToFile:@"whatevertxt.txt" atomically:YES encoding:NSUnicodeStringEncoding error:&error];

you could write the file in .txt. format... i guess that is the best way to do what u want


text:
Q: Convert to JSON without using split in Python Scrapy dict = {clientId: "300",id: "new",ctime: "6/3/2022",mtime: "6/3/2022"}

I try this but its not working:
JO = json.joads(dict)

clientId = JO['clientId']

id = JO['id']

TypeError: string indices must be integers
i want data like that:
clientId = 300
id = new
ctime = 6/3/2022
mtime = 6/3/2022

A: According to me, you shoudn't assign dict as variable, even its works but shouldn't assign. second your passingclientId variable as key, which you haven't defined so I took as string.
In case of your existing code update this:
d = json.dumps(dict)
JO = json.loads(d)

clientId = JO['clientId']
clientId

Or you can also try this without Json.
Dict = {'clientId': "300",'id': "new",'ctime': "6/3/2022",'mtime': "6/3/2022"}

clientId = Dict['clientId']
id = Dict['id']
ctime = Dict['ctime']
mtime = Dict['mtime']