text:
Q: Android ListView scrolls the entire screen I have created a layout containing many linear layouts, and I have, in one of the linear layouts, 3 ListViews set side by side. I want to make each one of them scrollable, but singularily. For example, I want to be able to scroll one of them without anything else being affected.
Right now, if I set "android:nestedScrollingEnabled="true"" for any one of the lists, the entire screen scrolls. I want the scrolling of the list to be confined to the layout the list is in (so I can scroll the list and the rest of the screen stays in place).
How can I do that? So far, it's either no scrolling at all, or scrolling the entire screen. I just want the list to scroll.
Thanks!
PS: Here's how the relevant part of the XML looks like (nothing special about it):
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:layout_marginBottom="@dimen/list_vertical_margin">

       <ListView
            android:id="@+id/realtime_vehicle_list"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1" />

        <ListView
            android:id="@+id/realtime_errors_list"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1" />

        <ListView
            android:id="@+id/realtime_depot_list"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1" />
</LinearLayout>

A: One of your LinearLayouts is in a ScrollView, I guess. So remove the ScrollView.

A: Try to add the next following code in the activity that contains those Listviews:
ListView mylistview = (ListView) findViewById(R.id.mylistview);
mylistview.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        v.getParent().requestDisallowInterceptTouchEvent(true);
        return false;
    }

A: I've figured it out. Apparently, the layout "continues" beyond the screen. I only put a few more elements to test if it scrolls, but in reality, the reason why only the 3rd list was scrolling and the other two weren't is because the 3rd list had more elements, and it went beyond its limits. That's why it was scrolling.
I was equating the "going out of the screen" with the idea that the list should scroll, but it's just a design problem - the operating system didn't think that the list was going off the screen.
As soon as I put more elements into the other two lists, they are now all scrolling.


text:
Q: Is 'where do you sit' idiomatic? I often use the expression

Where do you sit on the second floor?
Where does the clerk sit here in this building?

Obviously I use the verb sit to mean location?

What is your location at work?

'Sit' expression is the exact translation of the phrase I would use in my native language.
So Is my expression idiomatic?
Edit:
If it is not, what is idiomatic phrase to say it

A: I would say that it's only idiomatic if the person doesn't normally sit at their workstation. Hence, in the context of an office, it's not idiomatic, but, in the context of a salon (where the hairdressers generally stand while they work), then it could be considered idiomatic.
The real question is, are there contexts where you'd use the phrase "where someone sits" if they are not generally sitting down in that location? For example:

The pickers take their baskets to the roadways, where the foreman sits with several women and a number of baskets of about a bushel capacity lined with canvas.

Does that foreman have a chair at the side of the road? If not, I may have just found the phrase used as an idiom.
That all said, if you want to ask where somebody works, then asking:

Where do you sit on the second floor?

is perfectly fine.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a way to create a mock dataset of an actual survey, using R? Is there a way to create a mock dataset of an actual survey?
I will be analyzing and reporting results of a survey that is currently being conducted.
I don't want to wait until the survey is closed to start analyzing the data. While the data is being collected, I would like to start working on the script for analysis and visualizations, and for that I need data that are similar to the data being collected.
Is it possible to create a mock dataset with the actual structure and variables of the survey? The survey has different types of questions, including arrays, single choice, multiple choice, and open ended questions. I know I could wait until I have 10 or 20 responses and start working on that? Could I create a random dataset based on those responses?
I'd be grateful if someone could give some ideas about this. Cheers.

A: It depends on the format (e.g. column names etc.) of your expected data. Here, you can simulate binary vectors:
library(tidyverse)
set.seed(1337)

select_m_out_of_n <- function(n, m) {
  if (m > n) stop("Can not choose more items than the number of options")

  res <- rep(FALSE, n)
  selected <- sample(n, m)
  res[selected] <- TRUE
  res
}

# q1 one out of 5
simulated_survey <- tibble(person_id = seq(3)) %>%
  mutate(
    # single choice
    q1 = person_id %>% map(~ select_m_out_of_n(5, 1)),

    # binary choice
    q1 = person_id %>% map(~ select_m_out_of_n(1, 1)),

    # multiple choice
    q2 = person_id %>% map(~ select_m_out_of_n(5, 2)),
    q3 = person_id %>% map(~ select_m_out_of_n(4, 2))
  )
simulated_survey
#> # A tibble: 3 x 4
#>   person_id q1        q2        q3
#>       <int> <list>    <list>    <list>
#> 1         1 <lgl [1]> <lgl [5]> <lgl [4]>
#> 2         2 <lgl [1]> <lgl [5]> <lgl [4]>
#> 3         3 <lgl [1]> <lgl [5]> <lgl [4]>

# answers of first person
simulated_survey %>%
  slice(1) %>%
  as.list()
#> $person_id
#> [1] 1
#>
#> $q1
#> $q1[[1]]
#> [1] TRUE
#>
#>
#> $q2
#> $q2[[1]]
#> [1] FALSE FALSE  TRUE  TRUE FALSE
#>
#>
#> $q3
#> $q3[[1]]
#> [1] FALSE  TRUE  TRUE FALSE

Created on 2021-11-11 by the reprex package (v2.0.1)


text:
Q: dsbulk unload is failing on large table trying to unload data from a huge table, below is the command used and output.
$ /home/cassandra/dsbulk-1.8.0/bin/dsbulk unload --driver.auth.provider PlainTextAuthProvider --driver.auth.username xxxx  --driver.auth.password xxxx --datastax-java-driver.basic.contact-points 123.123.123.123 -query "select count(*) from sometable with where on clustering column and partial pk -- allow filtering"  --connector.name json --driver.protocol.compression LZ4 --connector.json.mode MULTI_DOCUMENT -maxConcurrentFiles 1 -maxRecords -1 -url dsbulk --executor.continuousPaging.enabled false --executor.maxpersecond 2500 --driver.socket.timeout 240000
Setting dsbulk.driver.protocol.compression is deprecated and will be removed in a future release; please configure the driver directly using --datastax-java-driver.advanced.protocol.compression instead.
Setting dsbulk.driver.auth.* is deprecated and will be removed in a future release; please configure the driver directly using --datastax-java-driver.advanced.auth-provider.* instead.
Operation directory: /home/cassandra/logs/COUNT_20210423-070104-108326
total | failed | rows/s |      p50ms |      p99ms |     p999ms
    1 |      1 |      0 | 109,790.10 | 110,058.54 | 110,058.54
Operation COUNT_20210423-070104-108326 completed with 1 errors in 1 minute and 50 seconds.

Here are the dsbulk records --
cassandra@somehost> cd logs
cassandra@somehost> cd COUNT_20210423-070104-108326/
cassandra@somehost> ls
operation.log  unload-errors.log
cassandra@somehost> cat operation.log
2021-04-23 07:01:04 WARN  Setting dsbulk.driver.protocol.compression is deprecated and will be removed in a future release; please configure the driver directly using --datastax-java-driver.advanced.protocol.compression instead.
2021-04-23 07:01:04 WARN  Setting dsbulk.driver.auth.* is deprecated and will be removed in a future release; please configure the driver directly using --datastax-java-driver.advanced.auth-provider.* instead.
2021-04-23 07:01:04 INFO  Operation directory: /home/cassandra/logs/COUNT_20210423-070104-108326
2021-04-23 07:02:55 WARN  Operation COUNT_20210423-070104-108326 completed with 1 errors in 1 minute and 50 seconds.
2021-04-23 07:02:55 INFO  Records: total: 1, successful: 0, failed: 1
2021-04-23 07:02:55 INFO  Memory usage: used: 212 MB, free: 1,922 MB, allocated: 2,135 MB, available: 27,305 MB, total gc count: 4, total gc time: 98 ms
2021-04-23 07:02:55 INFO  Reads: total: 1, successful: 0, failed: 1, in-flight: 0
2021-04-23 07:02:55 INFO  Throughput: 0 reads/second
2021-04-23 07:02:55 INFO  Latencies: mean 109,790.10, 75p 110,058.54, 99p 110,058.54, 999p 110,058.54 milliseconds
2021-04-23 07:02:58 INFO  Final stats:
2021-04-23 07:02:58 INFO  Records: total: 1, successful: 0, failed: 1
2021-04-23 07:02:58 INFO  Memory usage: used: 251 MB, free: 1,883 MB, allocated: 2,135 MB, available: 27,305 MB, total gc count: 4, total gc time: 98 ms
2021-04-23 07:02:58 INFO  Reads: total: 1, successful: 0, failed: 1, in-flight: 0
2021-04-23 07:02:58 INFO  Throughput: 0 reads/second
2021-04-23 07:02:58 INFO  Latencies: mean 109,790.10, 75p 110,058.54, 99p 110,058.54, 999p 110,058.54 milliseconds

cassandra@somehost> cat unload-errors.log
Statement: com.datastax.oss.driver.internal.core.cql.DefaultBoundStatement@1083fef9 [0 values, idempotence: <UNSET>, CL: <UNSET>, serial CL: <UNSET>, timestamp: <UNSET>, timeout: <UNSET>]
SELECT batch_id from .... allow filtering (Cassandra timeout during read query at consistency LOCAL_ONE (1 responses were required but only 0 replica responded))
        at com.datastax.oss.dsbulk.executor.api.subscription.ResultSubscription.toErrorPage(ResultSubscription.java:534)
        at com.datastax.oss.dsbulk.executor.api.subscription.ResultSubscription.lambda$fetchNextPage$1(ResultSubscription.java:372)
        at com.datastax.oss.driver.internal.core.cql.CqlRequestHandler.setFinalError(CqlRequestHandler.java:447) [4 skipped]
        at com.datastax.oss.driver.internal.core.cql.CqlRequestHandler.access$700(CqlRequestHandler.java:94)
        at com.datastax.oss.driver.internal.core.cql.CqlRequestHandler$NodeResponseCallback.processRetryVerdict(CqlRequestHandler.java:859)
        at com.datastax.oss.driver.internal.core.cql.CqlRequestHandler$NodeResponseCallback.processErrorResponse(CqlRequestHandler.java:828)
        at com.datastax.oss.driver.internal.core.cql.CqlRequestHandler$NodeResponseCallback.onResponse(CqlRequestHandler.java:655)
        at com.datastax.oss.driver.internal.core.channel.InFlightHandler.channelRead(InFlightHandler.java:257)
        at java.lang.Thread.run(Thread.java:748) [24 skipped]
Caused by: com.datastax.oss.driver.api.core.servererrors.ReadTimeoutException: Cassandra timeout during read query at consistency LOCAL_ONE (1 responses were required but only 0 replica responded)

Cassandra's system.log snippet ----
DEBUG [ScheduledTasks:1] 2021-04-23 00:01:48,539  MonitoringTask.java:152 - 1 operations timed out in the last 5015 msecs:
<SELECT * FROM my query being run with limit - LIMIT 5000>, total time 10004 msec, timeout 10000 msec/cross-node
INFO  [ScheduledTasks:1] 2021-04-23 00:02:38,540  MessagingService.java:1302 - RANGE_SLICE messages were dropped in last 5000 ms: 0 internal and 1 cross node
. Mean internal dropped latency: 0 ms and Mean cross-node dropped latency: 10299 ms
INFO  [ScheduledTasks:1] 2021-04-23 00:02:38,551  StatusLogger.java:114 -
Pool Name                    Active   Pending      Completed   Blocked  All Time Blocked
ReadStage                         1         0     1736872997         0                 0
ContinuousPagingStage             0         0            586         0                 0
RequestResponseStage              0         0     1483193130         0                 0
ReadRepairStage                   0         0        9079516         0                 0
CounterMutationStage              0         0              0         0                 0
MutationStage                     0         0      351841038         0                 0
ViewMutationStage                 0         0              0         0                 0
CommitLogArchiver                 0         0          32961         0                 0
MiscStage                         0         0              0         0                 0
CompactionExecutor                0         0       12034828         0                 0
MemtableReclaimMemory             0         0          68612         0                 0
PendingRangeCalculator            0         0              9         0                 0
AntiCompactionExecutor            0         0              0         0                 0
GossipStage                       0         0       20137208         0                 0
SecondaryIndexManagement          0         0              0         0                 0
HintsDispatcher                   0         0           3798         0                 0
MigrationStage                    0         0              8         0                 0
MemtablePostFlush                 0         0         338955         0                 0
PerDiskMemtableFlushWriter_0         0         0          66297         0                 0
ValidationExecutor                0         0         247600         0                 0
Sampler                           0         0              0         0                 0
MemtableFlushWriter               0         0          41757         0                 0
InternalResponseStage             0         0         525242         0                 0
AntiEntropyStage                  0         0         767527         0                 0
CacheCleanupExecutor              0         0              0         0                 0
Native-Transport-Requests         0         0      958717934         0                65
CompactionManager                 0         0
MessagingService                n/a       0/0
Cache Type                     Size                 Capacity               KeysToSave
KeyCache                  104857216                104857600                      all
RowCache                          0                        0                      all

A: The problem is that you are running an unload command in DSBulk to perform a SELECT COUNT() which means it has to do a full table scan to return a single row.
In addition, ALLOW FILTERING is not recommended unless you restrict the query to a single partition. In any case, the performance of ALLOW FILTERING is very unpredictable even in optimal situations.
I suggest that you instead use the DSBulk count command which is optimised for counting rows or partitions in Cassandra. For details, see the Counting data with DSBulk example.
There's also additional examples in this DSBulk Counting blog post which Alex Ott already linked in his answer. Cheers!

A: Expand select count(*) from sometable with where on clustering column and partial pk -- allow filtering with an additional condition on the token ranges, like this: and partial pk token(full_pk) > :start and token(full_pk) <= :end - in this case, DSBulk will perform many queries against specific token ranges that are sent to multiple nodes, and won't create the load onto the single node as in your case.
Look into the documentation for -query option, and for 4th blog in this series of blog posts about DSBulk, that could provide more information & examples: 1, 2, 3, 4, 5, 6


text:
Q: Same IntersectionObserver for mutiple elements - how to properly target intersected element with classList.add() I'm working with the great code provided here by Ziyad and Ruslan Korkin, but when I want to use Classlist on the entry.target, I get stuck ... classList.add or classList.remove does not work as expected.
In the part of this code where element is intersecting, how can I properly target the one intersecting element and add/remove class from classList on it? I can fire some JS there okay (.remove works), but classList.add does not. What am I missing?
let observerOptions = {
rootMargin: '0px',
threshold: 0.5
}

var observer = new IntersectionObserver(observerCallback, observerOptions);

function observerCallback(entries, observer) {
    entries.forEach(entry => {
        if(entry.isIntersecting) {
          //do something
          // want to do entry.target.classList.add('square-transition');

        }
          // want to do entry.target.classList.remove('square-transition');
    });
};

let target = '.targetSelector';
document.querySelectorAll(target).forEach((i) => {
    if (i) {
        observer.observe(i);
    }
});

A: You were missing an else statement that would be triggered whenever the entry is not intersecting.
function observerCallback(entries, observer) {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      entry.target.classList.add('square-transition');
    } else {
      entry.target.classList.remove('square-transition');
    }
  });
};


text:
Q: Is a Bluetooth profile always required to be used when sending data between an iOS device and a Bluetooth device? I'm new to Bluetooth, but searching the web, I've found the following description of Bluetooth profiles:
"A Bluetooth profile is a specification regarding an aspect of Bluetooth-based wireless communication between devices. In order to use Bluetooth technology, a device must be compatible with the subset of Bluetooth profiles necessary to use the desired services. A Bluetooth profile resides on top of the Bluetooth Core Specification and (optionally) additional protocols. While the profile may use certain features of the core specification, specific versions of profiles are rarely tied to specific versions of the core specification. For example, there are Hands-Free Profile (HFP) 1.5 implementations using both Bluetooth 2.0 and Bluetooth 1.2 core specifications."
So, I have an MSP430 board with the CC256X Bluetooth module on it, and I want to transfer data between that device and my iOS device. Does that device always have to communicate with my iOS device using a Bluetooth profile? If so, could you please shed some light as to what the simplest profile to make this happen is? As far as my design constraints, all I want to do is press a button on my iOS application, and have that turn an LED on my board. Thus, I just need the board to react to a simple characteristic change.

A: Please check
profiles/SimpleProfile/simpleGATTProfile.c

and
profiles/SimpleProfile/simpleGATTProfile.h

That's as simple as it ever gets. Once you write a profile with service and characteristics, you just have to include it in your code and use them just like any other service and characteristic.
Coming to your requirement, you need to have a characteristic with write permission in your profile. When you press the button in iOS application, write a value 1 to this characteristic. This will trigger writeCB to your embedded application code. You can use
HalLedSet( HAL_LED_2, HAL_LED_MODE_ON );

to turn on the LED in this callback.


text:
Q: iOS 7.1 UISearchBar gray view I work at an application and I tested today on iOS 7.1. Until now my search bar was normal:

But now I have this problem:

A gray view appears and I don't know how to remove it because I don't have this view in my code.  Does anyone have the same problem? It is an iOS 7.1 bug?

A: My quick fix used some code I found here: https://stackoverflow.com/a/18664917/1153630
And then:
searchBar.backgroundImage = [UIImage imageWithColor:[UIColor clearColor]];

I'm still not very impressed by it though: will update answer when I find a better way.
You may also want to checkout: Colour changed in iOS7.1, how to change searchBar colour?

A: As @dave noted above, you can just use say:
searchBar.backgroundImage = [[UIImage alloc] init];

which avoids the need for the category on UIImage incorporated in @Jugale's example.


text:
Q: MatPlotLib not displaying both graphs when sharing X axes This is a bit of an odd problem I've encountered. I'm trying to read data from a CSV file in Python, and have the two resulting lines be inside of the same box, with different scales so they're both clear to read.
The CSV file looks like this:
Date,difference,current
11/19/20,      0,      606771
11/20/20,      14612,      621383
and the code looks like this:
data = pd.read_csv('data.csv')
time = data['Time']
ycurr = data['current']
ydif = data['difference']

fig, ax = plt.subplots()
line1, = ax.plot(time, ycurr, label='Current total')
line1.set_dashes([2, 2, 10, 2])  # 2pt line, 2pt break, 10pt line, 2pt break

line2, = ax.twinx().plot(time, ydif, dashes=[6, 2], label='Difference')

ax.legend()
plt.show()

I can display the graphs with the X-axis having Date values and Y-axis having difference values or current values just fine.
However, when I attempt to use subplots() and use the twinx() attribute with the second line, I can only see one of two lines.

I initially thought this might be a formatting issue in my code, so I updated the code to have the second line be ax2 = ax1.twin(x) and call upon the second line using this, but the result stayed the same. I suspect that this might be an issue with reading in the CSV data? I tried to do read in  x = np.linspace(0, 10, 500) y = np.sin(x) y2 = np.sin(x-0.05) instead and that worked:

A: Everything is working as expected but probably not how you want it to work!
So each line only consists of two data points which in the end will give you a linear curve. Both of these curves share the same x-coordinates while the y-axis is scaled for each plot. And here comes the problem, both axes are scaled to display the data in the same way. This means, the curves lie perfectly on top of each other. It is difficult to see because both lines are dashed.
You can see what is going on by changing the colors of the line. For example add color='C1' to one of the curves.
By the way, what do you want to show with your plot? A curve consisting of two data points mostly doesn't show much and you are better of if you just show their values directly instead.


text:
Q: Print Preview White Border around image in IE and Firefox Firefox and IE display the border around image while doing print preview. It is a simple page with two div each div contains one image width of 400px and the container div is 800px. I do not want the white border in between the two images which I am getting while doing print preview. Is there anything I am doing wrong here?? (in chrome it does not display the white border.)
I have tried this code also for print css but no luck..

The code is:
<!DOCTYPE html>

A: Try adding this CSS:
img { border: 0; }


text:
Q: Python to run geopy via ActivePython Trying to get a location using Python and Google Maps, so I tried to use Geopy module by installing activepython using pypm install geopy but i get a problem which is  geo required  business  edition subscription. Can any one help me?
 Thanks in advance.

A:
geo required business edition subscription

No. You are probably using the Windows 64-bit build, which requires Business Edition to install all packages (as even this page should tell you with the "lock" icon).
Try the 32-bit version instead.


text:
Q: Transform my Code to redirect to User Profile This code
$threadOut .= "
".$uData->user_login."
".$this->formatDate($post->date)."
ID )."'>".__("My Profile")."".get_avatar($post->from_user, 60)."	";

echos some data and a link (My Profile) wich redirects to:
http: // mydomain.com / user/
This code filters the users data (username):
.$u->user_login.

I dont get it :( Can anyone help me to transform the first code - so it redirects my "My Profile" Link to:
http:  //  mydomain.com /user /username
All other parts should stay the same. Thank you so much - best regards

A: $threadOut .= "
".$uData->user_login."
".$this->formatDate($post->date)."
ID ).$uData->user_login."'>".__("My Profile")."".get_avatar($post->from_user, 60)."	";

Added .$uData->user_login. to the link


text:
Q: Python parent class modifiable by child class or dynamic attribute? So I am not even sure if what I want to do is possible but I thought I would ask and find out.
I want to build a chef "databag" via python. This is pretty much just a python dictionary. There are other things that need to happen with this databag that are encapsulated in the Databag class.
Now for the meat of the question...
I want to add key/values to this dictionary but need to build it in a way that is easily extensible. NOTE: the autodict is a class that makes it so you can build a dictionary using dot notation.
Here is what I am trying to do:
databag = Databag(
  LogGroup=Sub("xva-${environment}-${uniqueid}-mygroup"),
  RunList=[
    "mysetup::default",
    "consul::client"
  ]
)
databag.Consul()  <-- Trying to add consul key/values to databag
print(databag.to_dict())
print(databag.to_string_list())

So you can see how I add the "consul" key values to the already existing databag object.
Here are the class definitions. I know this is wrong which is why I am here to see if this is even possible.
Databag Class
class Databag(object):

def __init__(self,uniqueid=Ref("uniqueid"),environment=Ref("environment"),LogGroup=None,RunList=[]):
    self.databag = autodict()
    self.databag.uniqueid = uniqueid
    self.databag.environment = environment
    self.databag.log.group = LogGroup
    self.runlist=RunList

def to_string_list(self):
    return self.convert_databag_to_string(self.databag)

def to_dict(self):
    return self.databag

def get_runlist(self):
    return self.convert_to_runlist_string(self.runlist)

Consul Class
class Consul(Databag):

  def __init__(self, LogGroup=None):
      if LogGroup == None:
          Databag.consul.log.group = Databag.log.group
      else:
          Databag.consul.log.group = LogGroup

As you can see the Consul class is supposed to access the databag dictionary of the Databag class and add the "consul" variables, almost like an attribute. However, I don't want to add a new function to the databag class every time otherwise that class will end up being very, very large.

A: I was able to get something like this to work with the following method. Although I am up for an suggestions to get this to work. I just read the help posted on this link:
http://www.qtrac.eu/pyclassmulti.html
EDIT: This method is a lot easier:
Note: This uses the exact same implementation of the old method.
consul.py
from classes.databag.utils import *

class Consul:
    def Consul(self, LogGroup=None):
        if LogGroup == None:
            self.databag.consul.log.group = self.databag.log.group
        else:
            self.databag.consul.log.group = LogGroup

databag.py
from classes.databag.utils import autodict
from classes.databag import consul

class Databag(consul.Consul):

    def __init__(self,uniqueid=Ref("uniqueid"),environment=Ref("environment"),LogGroup=None,RunList=[]):
        self.databag = autodict()
        self.databag.uniqueid = uniqueid
...
...

Folder Structure
/classes/
    databag/
        utils.py
        databag.py
        consul.py
testing.py

---- OLD METHOD -----
How I implemented it
from classes.databag.databag import *

databag = Databag(
    LogGroup=Sub("xva-${environment}-${uniqueid}-traefik"),
    RunList=[
        "mysetup::default",
        "consul::client"
    ]
)
databag.Consul()

print(databag.to_dict())
print(databag.to_string_list())

lib.py
def add_methods_from(*modules):
    def decorator(Class):
       for module in modules:
           for method in getattr(module, "__methods__"):
               setattr(Class, method.__name__, method)
       return Class
return decorator

def register_method(methods):
    def register_method(method):
        methods.append(method)
        return method
    return register_method

databay.py
from classes.databag import lib, consul

@lib.add_methods_from(consul)
class Databag(object):

    def __init__(self,uniqueid=Ref("uniqueid"),environment=Ref("environment"),LogGroup=None,RunList=[]):
        self.databag = autodict()
        self.databag.uniqueid = uniqueid
    ....
    ....

consul.py
from classes.databag import lib

__methods__ = []
register_method = lib.register_method(__methods__)

@register_method
def Consul(self, LogGroup=None):
    if LogGroup == None:
        self.databag.consul.log.group = self.databag.log.group
    else:
        self.databag.consul.log.group = LogGroup

Folder Structure
/classes/
    /databag
        lib.py
        databag.py
        consul.py
        utils.py
/testing.py


text:
Q: Reg~x for the N~number Would be grateful your help.
What would be elegant Regx to check a String whether it holds a number ?  any suggestions? thanks.

A: I don't think that an exception (even if it is triggered) is that much more expensive than a regular expression - you'd have to profile it and see if it really makes a difference.
That said, a regular expression that implements the BigDecimal grammar according to the Java Docs is
[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?

Explanation:
[+-]?       # optional sign
(?:         # required significand: either...
 \d+        # a number
 (?:\.\d*)? # optionally followed by a dot, optionally followed by more digits
 |          # or...
 \.\d+      # just a dot, followed by digits (in this case required)
)           # end of significand
(?:         # optional exponent
 [eE]       # required exponent indicator
 [+-]?      # optional sign
 \d+        # required digits
)?          # end of exponent

If you want to allow different number formats (and thousands separators) you could first get those values from DecimalFormatSymbols and build your regex with it.
Something like this (I don't know Java, so feel free to correct my Syntax Errors):
// you need java.util.regex.Pattern and java.text.DecimalFormatSymbols
string ds = Pattern.quote(DecimalFormatSymbols.getDecimalSeparator())
string gs = Pattern.quote(DecimalFormatSymbols.getGroupingSeparator())
string ms = Pattern.quote(DecimalFormatSymbols.getMinusSign())
string es = Pattern.quote(DecimalFormatSymbols.getExponentSeparator())

string myre =
    "(?xi)\n       # verbose, case-insensitive regex" +
    "[+" +ms+ "]?  # optional sign\n" +
    "(?:           # required significand: either...\n" +
    " (?:\\d{1,3}(?:" +gs+ "\\d{3}|\\d++) # a number with optional thousand separators,\n" +
    " (?:" +ds+ "\\d*)? # optionally followed by a dot, optionally followed by more digits\n" +
    " |            # or...\n" +
      ds+ "\\d+    # just a dot, followed by digits (in this case required)\n" +
    ")             # end of significand\n" +
    "(?:           # optional exponent\n" +
      es+ "        # required exponent indicator\n" +
    " [+" +ms+ "]? # optional sign\n" +
    " \\d+         # required digits\n" +
    ")?            # end of exponent"

boolean foundMatch = subjectString.matches(myregex);

You could then replace the locale-dependent bits back into their US counterparts before handing the number over for BigDecimal conversion, if that's not locale-aware.

A: Take a look at the implementation of the Apache's NumberUtils.isNumber. I wouldn't recommend using regular expressions for such validation.

A: Do not use regular expressions, they almost always are not the answer to any problem. You might accept some regex and then later on find out that it does not cover all situations. If you really want to know if a string has a BigDecimal, why not ask the source BigDecimal itself, after all it by definition is always right while using a regular expression cant always be right, you might just get it wrong.


text:
Q: Unable to push my django app to heroku due to requirements So I'm trying to deploy my Django app to heroku (using their tutorial) and I get the following error
Terminal info:
diaj3@diaj3-TUF-Gaming-FX505DD-FX505DD:~/Desktop/direct_bet$ git push heroku master
Counting objects: 9177, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (5988/5988), done.
Writing objects: 100% (9177/9177), 20.59 MiB | 1.29 MiB/s, done.
Total 9177 (delta 2148), reused 9177 (delta 2148)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Python app detected
remote: cp: cannot create regular file '/app/tmp/cache/.heroku/requirements.txt': No such file or directory
remote: -----> Installing python-3.6.10
remote: -----> Installing pip
remote: -----> Installing SQLite3
remote: Sqlite3 successfully installed.
remote: -----> Installing requirements with pip
remote:        ERROR: Could not find a version that satisfies the requirement apt-clone==0.2.1 (from -r /tmp/build_ca7b1fda063f2c983e5082dbb19235bf/requirements.txt (line 1)) (from versions: none)
remote:        ERROR: No matching distribution found for apt-clone==0.2.1 (from -r /tmp/build_ca7b1fda063f2c983e5082dbb19235bf/requirements.txt (line 1))
remote:  !     Push rejected, failed to compile Python app.
remote:
remote:  !     Push failed
remote: Verifying deploy...
remote:
remote: !   Push rejected to protected-chamber-65006.
remote:
To https://git.heroku.com/protected-chamber-65006.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/protected-chamber-65006.git'

Here's the Tree info
Even tho the requirements file is there, I still get the error when pushing:
├── aposta_segura
│   ├── asgi.py
  ...
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── app
│   ├── admin.py
│   ├── apps.py
  ...
│   ├── tests.py
│   ├── urls.py
│   └── views.py
├── db.sqlite3
├── manage.py
├── requirements.txt
├── static
 ...
└── venv
    ├── bin
    │   ├── activate
...


text:
Q: Electron desktopCapturer to Web API frequency all 0s ==== SOLVED ====
To be 100% honest I'm not sure what I did, but I have a fully working audio bar visualizer based on desktop audio. I went back to the original codepen (link below) I started working off of and edited everything as needed to accept a media stream, and it works.
Full Code
const {desktopCapturer} = require('electron')

desktopCapturer.getSources({types: ['window', 'screen']}, (error, sources) => {
  if (error) throw error
  for (let i = 0; i < sources.length; ++i) {
     if (sources[i].name === 'Entire screen') {
        navigator.mediaDevices.getUserMedia({
          audio: { mandatory : { chromeMediaSource: 'desktop' }},
          video: { mandatory : { chromeMediaSource: 'desktop' }}
        })
        .then((stream) => handleStream(stream))
        return
     }
  }
})

function handleStream (stream)
{
  const context = new AudioContext()
  let src = context.createMediaStreamSource(stream)
  let analyser = context.createAnalyser()

  let canvas = document.getElementById("canvas")
  canvas.width = window.innerWidth
  canvas.height = window.innerHeight
  let ctx = canvas.getContext("2d")

  src.connect(analyser)
  analyser.fftSize = 256

  let bufferLength = analyser.frequencyBinCount
  let dataArray = new Uint8Array(bufferLength)
  let WIDTH = canvas.width
  let HEIGHT = canvas.height
  let barWidth = (WIDTH / bufferLength) * 2.5
  let barHeight
  let x = 0

   function renderFrame()
   {
      requestAnimationFrame(renderFrame)
      x = 0

      analyser.getByteFrequencyData(dataArray)
      ctx.fillStyle = "#000"
      ctx.fillRect(0, 0, WIDTH, HEIGHT)

      for (let i = 0; i < bufferLength; i++)
      {
         barHeight = dataArray[i]

         let r = barHeight + (25 * (i / bufferLength))
         var g = 250 * (i/bufferLength)
         var b = 50

         ctx.fillStyle = `rgb(${r}, ${g}, ${b})`
         ctx.fillRect(x, HEIGHT - barHeight, barWidth, barHeight)

         x += barWidth + 1
      }
   }
   renderFrame()
}

Codepen I used as a starting point
https://codepen.io/nfj525/pen/rVBaab
Original Post
I'm working on setting up a desktop visualizer that will graph the users desktop audio.
desktopCapture appears to be grabbing the media as sending it to a video tag displays the stream, along with an echo of the media. Since I only need the audio, I'm setting the mediaStraem to an AudioContext MediaStreamSource, which also appears to be working as I get an audio echo if I connect the analyser to the ctx destination. The issue I'm running into is when I try to get the frequency data its returning an array of only 0s. Below is my current code
const {desktopCapturer} = require('electron')

desktopCapturer.getSources({types: ['window', 'screen']}, (error, sources) => {
  if (error) throw error
  for (let i = 0; i < sources.length; ++i) {
     if (sources[i].name === 'Entire screen') {
        navigator.mediaDevices.getUserMedia({
          audio: {
              mandatory : {
                  chromeMediaSource: 'desktop'
              }
          },
          video: {
             mandatory: {
                chromeMediaSource: 'desktop',
             }
          }
        })
        .then((stream) => handleStream(stream))
        return
     }
  }
})

function handleStream (stream) {

   let audioCtx = new AudioContext();
   let source = audioCtx.createMediaStreamSource(stream);
   let analyser = audioCtx.createAnalyser()

   //uncommenting results in echo, but still all 0s
   //analyser.connect(audioCtx.destination)

   analyser.fftSize = 256
   let bufferLength = analyser.frequencyBinCount
   let dataArray = new Uint8Array(bufferLength)

   console.log(dataArray)

}

===== EDIT =====
I've been able to get this working; kind of but am still running into a slight issue.
1) I had connect the source and the analyzer with
source.connect(analyser)

2) Had to fill the dataArray with time domain with
getByteTimeDomainData

3) Outstanding issue is when there is no media playing the dataArray is filled with values of 126, 127, & 128 making the bars "dance" at almost full height.
4) The FPS also seems extremely fast, but have some plans to fix that
Current somewhat working code :
const {desktopCapturer} = require('electron')

desktopCapturer.getSources({types: ['window', 'screen']}, (error, sources) => {
  if (error) throw error
  for (let i = 0; i < sources.length; ++i) {
     if (sources[i].name === 'Entire screen') {
        navigator.mediaDevices.getUserMedia({
          audio: {
              mandatory : {
                  chromeMediaSource: 'desktop'
              }
          },
          video: {
             mandatory: {
                chromeMediaSource: 'desktop',
             }
          }
        })
        .then((stream) => handleStream(stream))
        return
     }
  }
})

function handleStream (stream) {

   const audioCtx = new AudioContext()
   let source = audioCtx.createMediaStreamSource(stream)
   let analyser = audioCtx.createAnalyser()
   source.connect(analyser) //Had To Connect Source To Analyser
   analyser.fftSize = 128

   let bufferLength = analyser.frequencyBinCount
   let dataArray = new Uint8Array(bufferLength)

   let canvas = document.getElementById("canvas")
   canvas.width = window.innerWidth
   canvas.height = window.innerHeight
   let canvasCtx = canvas.getContext("2d")

   let WIDTH = canvas.width;
   let HEIGHT = canvas.height;
   let barWidth = (WIDTH / bufferLength);
   let barHeight;
   let x = 0;

   function draw() {

      var drawVisual = requestAnimationFrame(draw)
      analyser.getByteTimeDomainData(dataArray) //added to the draw to fill the dataArray

      canvasCtx.fillStyle = "#000";
      canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);

      var x = 0;

      for (let i = 0; i < bufferLength; i++) {
        barHeight = dataArray[i];

        let r = 50
        let g = 250
        let b = 50

        canvasCtx.fillStyle = `rgb(${r}, ${g}, ${b})`
        canvasCtx.fillRect(x, HEIGHT - barHeight, barWidth, barHeight);

        x += barWidth + 1;
      }
   }
draw()
}


text:
Q: Must every magnetic configuration have a north and south pole? Magnets have a magnetic north and south pole. Solenoids too have north and south pole from which magnetic fields comes out and goes in respectively. But is it that every magnetic configuration have a north and south pole? Electrons have magnetic moment and they can be regarded as very tiny magnets. So, where is its north and south pole?

A: You van have two pairs of north/south if you wish.

A: Yes, in the absence of magnetic monopoles, every magnet must have a north and south pole.


text:
Q: Is `gcloud dns record-sets import --delete-all-existing` transactional? When updating the contents of a zone using:
gcloud dns record-sets import RECORDS_FILE --zone=ZONE --delete-all-existing --zone-file-format

Is this operation atomic? i.e. if I have a record in RECORDS_FILE which already exists in the zone, will it continue to serve throughout, or will there be a blip where it's unavailable?

A: Using --delete-all-existing flag in gcloud dns record-sets import will delete existing record-sets BEFORE importing the record-sets in the records-file.
If you noticed any blips please open a bug with reproduction steps on Google Issue Tracker and we will investigate it.

A: It isn't documented if import is transactional, but if you require that, you can use
gcloud dns record-sets transaction


text:
Q: Global variable which can be accessed by any class I would like to create a global variable (basically a flag var) which can be modified and accessed by any class in Objective C? Any examples are appreciated.

A: Singleton pattern.
http://www.galloway.me.uk/tutorials/singleton-classes/
Always reference the object through the "sharedManager" message, that will create a new object or give you the existing one.

A: Objective C is a strict superset of ANSI C, so the steps used to create and use a plain C global variable can be used in Objective C.
In exactly one .m file, outside of any class interface, method or subroutine scope, declare or instantiate your global variable (and initialize it if you don't want it to start with a garbage value):
BOOL myGlobalFlag = NO;

To make these globals easy to find (you may need to find them, since the use of global variables is thought to be at a higher risk of being involved in certain types of bugs), put them at the top of the file, just after any required includes.  Or put all your globals in one easy to find central file, such as the App Delegate, the file containing main(), or a file only containing all the globals, such as my_apps_globals.c included in your project.
In at least one .h file belonging to any class, .m, or .c file where you want to access this variable, and outside of any class interface or struct definition, declare this variable as externally accessible:
extern BOOL myGlobalFlag;

Then use the variable inside any method or subroutine, anywhere in your app, that includes any of the above header files.
-(void)dummyMethod {
  if (myGlobalFlag) NSLOG(@"the Flag is set!!!");
}

A: Remember that Objective-C has good old "C" running under the covers.  So you can create a global variable in Objective-C just like in C.

A: Check this. At your appname.pch file import some class, say application delegate as it is easy to access from application singleton. Add a scrip there like
#define MY_APP_DELEGATE  (((MYAppDelegate *)[UIApplication sharedApplication].delegate))

and from any class use the delegate variables in this way:
int val1 = MY_APP_DELEGATE.myvar;
MY_APP_DELEGATE.myvar = 1;


text:
Q: How to read files from openshift docker image I have deployed my dotnet project in openshift.currently, it is working fine.i can't access the files from opendhift docker image.actually what i did that i pushed my files to my git repository.then i point my git in openshift for deployment.i have created a new folder in my git, then i build my solution in openshift at the time new docer image is created and app has worked.i can't access the new folders files from openshift.for running my app i have added one environment variable in openshift."DOTNET_STARTUP_PROJECT" :"MYAPP.Csproj".is there any way for reading files from openshift docker image.

A: I didn't get an answer. then I moved to azure Storage.then I am accessing files from azure


text:
Q: Exporting Room database to another folder or directory inst working I'm trying to export Database file from root directory to download directory. The database is created using Room, everything is working perfectly, i can add data, delete and update data , but when i try to export database it gives exception
java.io.FileNotFoundException: /storage/emulated/0/storage/emulated/0/Download: open failed: ENOENT (No such file or directory)
Screen shot while debugging
i am using following lines of code to export db.
private void exportDB() {
    try {
        File sd = Environment.getExternalStorageDirectory();
        File data = Environment.getDataDirectory();
        boolean ans = sd.canWrite();
        //if (ans) {

        String currentDBPath ="/data/" + getPackageName() + "/databases/" + SAMPLE_DB_NAME + "";
        String backupDBPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
        File currentDB = new File(data, currentDBPath);
        File backupDB = new File(sd, backupDBPath);

        if (currentDB.exists()) {
            FileChannel src = new FileInputStream(currentDB).getChannel();
            FileChannel dst = new FileOutputStream(backupDB).getChannel();
            dst.transferFrom(src, 1, src.size());
            src.close();
            dst.close();
        }
    } catch (Exception e) {
        Log.e("MYAPP", "exception", e);

        Toast.makeText(MainActivity.this, "" + e, Toast.LENGTH_SHORT).show();
    }

Please have a look at this and guide me, Thank you in advance

A: Try
String backupDBPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + SAMPLE_DB_NAME;

and to be sure that the Download directory exists follow File backupDB = new File(sd, backupDBPath);
with
backupDB.getParentFile().mkDirs();

*

*This assumes that you want the backup file name to be the same as the database file name. If not then you may wish to use something other than SAMPLE_DB_NAME.

Edit
If the above still fails then you are not providing the required permissions. You need to refer to https://developer.android.com/training/data-storage/
As an example here's a slightly modified version of your code:-
private void exportDB() {

    /* get an alternative backup location where permissions exist */
    File bkp = new File( MainActivity.this.getDatabasePath("x").getParent() + File.separator + "backups" + File.separator + "bkp_" + SAMPLE_DB_NAME);

    try {
        File sd = Environment.getExternalStorageDirectory();
        File data = Environment.getDataDirectory();
        boolean ans = sd.canWrite();

        String currentDBPath = "/data/" + getPackageName() + "/databases/" + SAMPLE_DB_NAME + "";
        String backupDBPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
        File currentDB = new File(data, currentDBPath);
        /* requires permissions */
        File backupDB = new File(sd, backupDBPath);
        backupDB.getParentFile().mkdirs();
        /* uses ....databases/backups directory */
        bkp.getParentFile().mkdirs();
        backupDB = bkp;

        if (currentDB.exists()) {
            FileChannel src = new FileInputStream(currentDB).getChannel();
            FileChannel dst = new FileOutputStream(backupDB).getChannel();
            dst.transferFrom(src, 0, src.size()); //<<<<< 0 not 1
            src.close();
            dst.close();
        }
    } catch (Exception e) {
        Log.e("MYAPP", "exception", e);

        Toast.makeText(MainActivity.this, "" + e, Toast.LENGTH_SHORT).show();
    }
}

As can be seen this now backs up the database (sla_database) file :-

Warning
Unless you have specifically forced Journal mode then you need to consider the files as outlined in red above.
You can see that the database file backed up is 4k. Yet the -wal file and -shm file are both quite a bit larger. The -wal file contains changes to the database that are waiting to be applied (checkpointed).
So you either need to backup the -wal -shm files as well or fully checkpoint the database (closing the database will fully checkpoint the database). see https://sqlite.org/wal.html


text:
Q: Android JNI: Getting backtrace from remote device How can i get a stack trace from a device in case of a crash in native library?
I want to email it to myself, but i can't find a way to get this information in the application. I can see the backtrace and other information when i type "adb logcat" but if i run logcat from the application, i cannot get the same information, long story short, "i cannot see my own crash report with logcat". I believe this is a relatively new thing that an application can only see the logs it has written itself.
So there are thousands of people who writes native library for android, how do they get the report and backtrace if their native code crashes?
Thank you.


text:
Q: Python pygraphviz not working due to dot not found in path I am trying to get the fast-autocomplete library to work. I have a virtualenv with Python 3.6 installed for this. Everything else works but when I am trying to visualize the graph, I keep getting the following error:
    File "/Users/rishi/code/search-env/lib/python3.6/site-packages/pygraphviz/agraph.py", line 1569, in _which
        raise ValueError("No prog %s in path." % name)
    ValueError: No prog dot in path.

I have already installed the following:

*

*pygraphviz and graphviz as suggested here and here.

*pydot installed with dot at /usr/local/bin/dot
I am on OSx Mojave. What am I missing?


text:
Q: How to test rollback is working as expected? I am trying to write an integration/unit test where an exception is applied to a DAO after a save has been performed - in order to validate the rollback behaviour.  My thoughts were to create a Spring AOP aspect - and apply @AfterReturning advice to the 'save' method on the DAO.
The DAO is already proxied via @Transactional advice.
Does this seem like the right way to go ?
So far I'm trying to use a Spring ProxyFactory - to proxy the DAO in the unit test.
E.g.
 ProxyFactory pf = new ProxyFactory(new MyFaultInjectingAspect());
 pf.setTarget(myDao);
 MyDao proxiedDao = (BookmarkDao) pf.getProxy();

Thank you.
FYI:  relates to this Is it ok to use DataSourceTransactionManager for ORM persistence instead of HibernateTransactionManager?

A: From your DB side you can issue a lock by using select for update.
http://dev.mysql.com/doc/refman/5.0/en/innodb-locking-reads.html
http://dev.mysql.com/doc/refman/5.0/en/innodb-locking-reads.html
And try to commit with your application, you should see a transaction rolled back exception, but with different reason.
updated link.

A: I guess there is other approach without any AOP that really checks that nothing is written in the DB:
If you have a test that verifies (if there is no exception) that the transaction is commited, and the entity is written to the DB, then you only need simple second test.
In this test you must do the same but with exception. And then you must only verify that noting is written to the DB. So you do not need the AOP Stuff, and your test becomes more meaningful because it test in the end what you really want. (I hopefully understand it right, that role back is only the technique to prohibit the database change.)

A: It looks like you're trying to do something similar to this:
How to rollback a database transaction when testing services with Spring in JUnit?


text:
Q: Is there any way to get call back from powerpoint, when any presentation opens? (Powerpoint 2016- Mac version) I need to open my OS X application when any powerpoint presentation opens.
I got VBA call back when powerpoint open (Auto_Open()). But I need a call back for each presentation open.
In windows we can open  each presentation in separate powerpoint app (difference instance).
In Mac , Powerpoint app will open once and all presentation will open under same powerpoint application (Powerpoint 2016- Mac version) .
I need a call back when each presentation file open and I need to do run code snippets in my cocoa application.

A: An idea of possible work around is to loop checking the presentations opened, and compare it with presentations already open before.
First, when this script starts running, it checks if PowerPoint is running (-> if not then quit). If PP runs, then the script records the number of open presentations.
Then script goes through a loop : in this example, it repeats 100 times (just for my test, but it should be repeat for ever !). For each iteration, it looks for list of PP presentation and compares with list before: if a presentation is not in previous list, then it is new, jut open !
The script also stops when you quit PowerPoint showing an alert (bloc try).
tell application "System Events" to set PP_Running to exists (processes where name is "Microsoft PowerPoint")
if not PP_Running then return -- Power point is not launched !
tell application "Microsoft PowerPoint" to set Old_list to name of every presentation -- get initial list of open presentations

repeat with I from 1 to 100 -- for test, but it should be repeat with no limit

try
    tell application "Microsoft PowerPoint" to set New_list to name of every presentation
on error
    display alert "PowerPoint no longer launched"
    return -- quit the loop
end try
repeat with aDoc in New_list
    if not (Old_list contains aDoc) then -- new document has been opened !!
        set Old_list to New_list
        log "Open new document = " & aDoc -- do what ever you need to do !!
    end if
end repeat
delay 0.5
set I to I + 1
end repeat

Tested on El Capitain / PP 2011 : but I think there is nothing changed from PP 2011 to PP 2016 in the 'name of every presentation'.


text:
Q: Post ArrayList to PHP and add it to MySQL database I am creating an app similar to those from online stores
I did an ArrayList for products added to the shopping cart.
How I must do to send this into my PHP script and add this to MySQL database.
I tried return count of my ArrayList elements, but I can't.
This is PHP code:
<?php
$postedArray = $_POST["arrayToPOST"];
$response = array();

if(isset($postedArray))
{
    $count = count($postedArray);
    $response["Count"] = $count;
    $response["postedArray"] = $postedArray;

}
else
{
    $response["Count"] = 0;
    $response["postedArray"] = "ERROR ON POST";
}

echo json_encode($response);

?>

This is my function in Android app:
val arrayList: ArrayList<String> = ArrayList<String>()

    arrayList.add("First value")
    arrayList.add("Second value")
    arrayList.add("Third value")

    val gson = GsonBuilder()
        .setLenient()
        .create()

    val retrofit = Retrofit.Builder()
        .addConverterFactory(GsonConverterFactory.create(gson))
        .baseUrl("http://192.168.100.11/")
        .build()

    val webAPIInterface = retrofit.create(WebAPIInterface::class.java)

    var call = webAPIInterface.postData(arrayList)

    call.enqueue(object : Callback<ResponsePOJO> {
        override fun onFailure(call: Call<ResponsePOJO>?, t: Throwable?) {
            Log.e("MainActivity", "Retrofit 2 ERROR: "+t.toString())

        }

        override fun onResponse(call: Call<ResponsePOJO>?, response: Response<ResponsePOJO>?)
        {
            Log.v("MainActivity", "RESPONSE: "+response!!.body().toString())

            if(response!!.isSuccessful)
            {
                Log.v("MainActivity", "Response is successful")

                Log.v("MainActivity", "")

            }
            else
            {
                Log.e("MainActivity", "Response isnt successful")
            }

        }

    })

I looking for solution in internet, but I found nothing.
Please help !


text:
Q: Cross-compile Windows binaries on Linux using Clang I know clang works on both Linux and Windows (kinda).
Does there exist a project like Mingw for Clang?
Edit: I am using only standard c++11 library functions.


text:
Q: How to convert files from Dos to Unix in VBA I want to convert all files to dos to unix format from a folder using VBA excel.
i can find all the files from drive by using following code.
Sub list_all_files(myFilepath As String, filecounter() As Variant, counter1 As Integer)
    With Application.FileSearch
    .NewSearch
    .LookIn = myFilepath
    .filename = "*.*"
    counter = 0
        If .Execute(SortBy:=msoSortByLastModified, SortOrder:=msoSortOrderDescending) > 0 Then
        counter1 = .FoundFiles.Count
            For i1 = 1 To .FoundFiles.Count
                counter = counter + 1
                filecounter(counter) = .FoundFiles(i1)
            Next i1
        End If
    End With
End Sub

But How to convert arrayof(files). I want to save the files on the same path.
Thanks in advance.

A: You would have to open each file in turn and run a find-and-replace operation on the input: vbCrLf (DOS) goes to vbLf (Unix). You'd then have to write that updated file back out to another file... Alternatively, rather than doing this sequentially, you could scan through each file, writing it back to another at the same time but ignoring all the carriage returns.
A quick Google found example code (e.g., here) to do the trick.


text:
Q: Scala case class Option value chaining case class Person(@BsonProperty("first_name") firstName:Option[String],@BsonProperty("second_name")  secondName:Option[String],@BsonProperty("person_age") var  age:Int)

val me = Some(Person(Some(Ambareesh),Some(B),23))

      Or

val me = None

      Or

val me = Some(Person(Some(Ambareesh),None,23))

     Or

val me = Some(Person(None,None,23))

someOperation(me.secondName / None) //How can I implement this behavior in single line.
someOperation(me.firstName / None)

def someOperation(name:Option[String]){
   //Do ...
 }

My doubt regarding the argument (instance of Person) to method someOperation. The argument itself is an Option value and fields are also Options. If either of this is None(argument or argument.fieldName) I want None as return else the field value as Some(fieldValue). Is it possible?

A: someOperation(me.flatMap(_.secondName))

See ScalaDoc.
You can use map for non-Option properties: me.map(_.age) is Option[Int].

A: If your someOperation returns an Option that you could also use a for comprehension.
val result: Option[String] = for {
   person <- me
   firstName <- someOperation(person.firstName)
   secondName<- someOperation(person.secondName)
} yield <use firstName, secondName here>

This will give you whatever result you want to calculate or None.

A: As I understood, you need to extract person fields and pass it into the method someOperation. Right?
If so, you can use pattern matching for this:
someOperation(
  me match {
    case Some(person) => person.firstName
    case None => None
  }
)


text:
Q: Java stack Overflow with recursion so i'm writing a program that will sort a custom arrayList of strings using quicksort. (I have to custom write all the code for a class). However, I keep getting a stack overflow error and I don't know why. (I'm a beginner so take it easy).
void quickSort () {
    recursiveQuickSort(0, numElements-1);
}
// Recursive quicksort
public void recursiveQuickSort(int start, int end) {
    // if size 1 or less, don't need to do anything
    int pivotPosition = 0;
    if (start <=1 || end <= 1 ) {

    } else
        pivotPosition =partition(start, end);
        recursiveQuickSort(start, pivotPosition-1);
        recursiveQuickSort(pivotPosition+1, end);
}
static int partition(int start, int end) {
    int pivot = end;
    end--;
    while(true) {
        while (true) {
            if (end < start) {
                break;
            }
            if (end < pivot) {
                end = end;
                break;
            } else end --;
        }
        while(true) {
            if (end < start) {
                break;
            }
            if (start > pivot) {
                start = start;
                break;
            } else start++;
        }
        if(end < start) {
            break;
        }
        else
            swap(start, end);
    }
             swap(end+1, pivot);
     return end + 1;
}

A: You are missing curly braces on the else in recursiveQuickSort, so recursive calls are performed unconditionally.
Add curly braces to fix this:
public void recursiveQuickSort(int start, int end) {
    // if size 1 or less, don't need to do anything
    int pivotPosition = 0;
    if (start <=1 || end <= 1 ) {

    } else { // <<== Here
        pivotPosition =partition(start, end);
        recursiveQuickSort(start, pivotPosition-1);
        recursiveQuickSort(pivotPosition+1, end);
    }        // <<== Here
}


text:
Q: Best practice to find out if SwiftyJSON dictionary has key I'm trying to find a way to get the value of a key in a SwiftyJSON dictionary and return a default string, if the key is not set. The following example works fine, but I'm not really satisfied. Do you know a more elegant way?
Example:
let users: JSON = [
    ["id": 1, "name": "one"],
    ["id": 2],
    ["id": 3, "name": "three"]
]

for (key: String, user: JSON) in users {
    println(user.object.objectForKey("name") != nil
        ? user["name"].stringValue
        : "default")
}

A: It seems, SwiftyJSON sets the error property when subscript non-existing key.
So, this should works:
for (key: String, user: JSON) in users {
    let name = user["name"];
    println(name.error == nil ? name.stringValue : "default")
}

For example: w/ Version 6.1.1 (6A2006), SwiftyJSON github current master:
let users: JSON = [
    ["id": 1, "name": "one"],
    ["id": 2],
    ["id": 3, "name": NSNull()],
    ["id": 4, "name": "four"],
]

for (key: String, user: JSON) in users {
    let name = user["name"];
    name.isEmpty
    println(name.error == nil ? name.stringValue : "default")
}

prints:
one
default

four

A: If you need to check if a SwiftyJSON dictionary has a key, you can compare it with JSON.null as follows:
user["name"] == JSON.null // true if the key does not exist

Using that method, your code could look like this:
let users: JSON = [
    ["id": 1, "name": "one"],
    ["id": 2],
    ["id": 3, "name": "three"]
]

for (key, user) in users {
    print(user["name"] != JSON.null ? user["name"].stringValue : "default")
}

If you just want to provide a default value, then you can use the Nil Coalescing Operator in Swift (??) like this:
let users: JSON = [
    ["id": 1, "name": "one"],
    ["id": 2],
    ["id": 3, "name": "three"]
]

for (key, user) in users {
    print(user["name"].string ?? "default")
}

SwiftJSON provides the string method, which returns an optional value (String?), contrary to stringValue which always returns a String.

A: The latest version of SwiftyJSON has the exists() function.
NOTE: Their latest documentation does not reflect the code very well... The actual method is exists()
// Returns boolean

json["name"].exists()

A: Objects of type JSON have a calculated property called null. This returns NSNull if the element requested does not exist, nil if it does. You can therefore test for the existence of a specific object by extracting it from its parent JSON and testing to see if the null property exists. I personally handle it like this:
let object = json["key"]
if object.null == nil {
    // Do something with 'object'
} else {
    // Key does not exist - handle the error
}

In your specific case, you could use this:
for (key: String, user: JSON) in users {
    let name = user.object.objectForKey("name")
    println(name.null == nil ? name.stringValue : "default")
}

...but since we know we're looking for a string we can cut that down even further. All you actually need to do is drop the 'Value' part of stringValue, since string will return nil if it cannot generate a string from its content. Also, check out the nil coalescence operator ??. It's designed to provide a default for optional variables, so try this:
for (key: String, user: JSON) in users {
    println(user["name"].string ?? "default")
}

Nice and compact!

A: As far as I can tell, this works:
let users: JSON = [
    ["id": 1, "name": "one"],
    ["id": 2],
    ["id": 3, "name": "three"]
]

for jsonDict in users.arrayValue {
    println(jsonDict["name"].string ?? "default")
}

To explain, you want to cast the JSON object to the types you expect to get. If you want the type to always succeed (not optional), use xxxValue. Hence, we cast the root object using arrayValue.
arrayValue returns [JSON], which we traverse in the loop. We don't need to case the jsonDict: JSON to object, as SwiftyJSON is smart enough to assume it is a dict from the subscript operators.
Finally, trying to fetch a key from the dict, then checking if the key can be retrieved as a string using .string, which is an optional. Use null coalescing to assign a default value.
Please see the SwiftJSON doc for string and stringValue

A: Note: This answer is no longer valid
Seems like the perfect use of if let syntax. Because accessing the subscript will return an optional, bind it to a variable in an if let block. This will tell you wether or not the key was in the JSON.
if let name = user["name"] {    // returns optional
    // user["name"] was non-nil, is now stored in ``name""
    // do something with ``name""
}
else {
    // user did not have key "name"
    // here would be the place to return "default"
    // or do any other error correction if the key did not exist
}


text:
Q: Order Topology Example Topology by Munkres says,

The set $X= \{1,2\}\times \mathbb{Z}_+$ in dictionary order is another example of ordered set with smallest element. Denoting $1\times n$ by $a_n$ and $2\times n$ by $b_n$ we can represent $X$ by $$a_1, a_2,\dots ; b_1, b_2, \dots$$
The order topology on $X$ is not discrete topology. Most one-point sets are open, but there is an exception $-$ the one-point set $\{b_1 \}$. Any open set containing $b_1$ must contain the basis element about $b_1$ (by definition), and any basis element containing $b_1$ contains point of the $a_i$ sequence.

I did not understand why "any basis element containing $b_1$ contains point of the $a_i$ sequence".

A: A basis element containing $b_1$ is an open interval $(c,d)$ where $c<b_1<d$.  We thus must have $c=a_n$ for some $n$.  In that case, we have $a_{n+1}>a_n=c$ and $a_{n+1}<b_1<d$ so $a_{n+1}$ is also an element of $(c,d)$.  Thus the interval $(c,d)$ contains a point of the $a_i$ sequence, namely $a_{n+1}$.
(Actually, there is one more possibility, which is that $c$ might be $-\infty$.  I'll let you figure out how to handle that case.)


text:
Q: git log pretty format doesn't work with line limiters Hi so I think pretty format doesn't work with -L<start>,<end>:<file>
If my git command is only
git log --pretty=format:"%H\t%an\%s" --author=author_name file

then all is well. But if I add
git log --pretty=format:"%H\t%an\%s" --author=author_name -L100,200:file

then I get the git diff for those lines but without the pretty formatting.
Any knows of any work around? I need simple format that I can control. Thanks!


text:
Q: CodeIgniter not storing sessions in IE I am using version 2.1.3 of CodeIgniter, and primarily use Chrome or FireFox, but I am learning that some of my clients are having issues with my systems not allowing them to log in. The system log indicates that the user has logged in, but I check if the session variable is set to determine whether the control panel or login screen needs to be displayed.
For some reason, the session variables are not set in at least IE8 and below, so the login screen keeps showing, even though the log says the user is logged in.
I checked this: CodeIgniter IE not storing sessions correctly and this is not applicable to me.
I am not using Ajax for this, so this is not it either: PHP Session lost in CodeIgniter IE only
Also, this is not loaded in an iFrame. So, I doubt there are P3P problems: CodeIgniter 2.x sessions and Internet Explorer
What could be the cause of this?
Thanks!

A: I could just guess, hope its helpful.
Check your php files if you have a closing tag ?> and if you have a whitespace after it. This cause to return a blank response, because of the whitespace, and this breaks the session and cookies.
Do you have some mechanism for regenerating session id`s
Thats all i can come up with, hope i`ve helped.
Regards

A: I found this article, and it appears to solve the problem for me, but I want to test more before accepting my own answer.
http://ellislab.com/forums/viewthread/211955/#982986
Hope this helps someone else.
Regards,
Kobus


text:
Q: ImageView image not resizing with ImageView I have a TableLayout with cells of ImageViews. What I am trying to do is create a zooming effect by incrementing the size of the ImageViews in the tabel. This works perfectly for zooming out( the picture resizes with the ImageView) but, the problem is with zooming in. The picture does not resize when the ImageView is made bigger.
Here is an example:

I want the image to be the same size as the ImageView(each black square is an ImageView)
Here is my code for the zooming ( any tips on better implementation would be appreciated, don't want to use pinch zoom ).
zoomIndex ranges from -2, 2. (only allow them to zoom twice in each direction)
zoomInThreshold = 2, zoomOutThreshold = -2.
defaultSize = 50, zoomIncrement = 15;

                if(zoomIndex < zoomInThreshold)
                    defaultSize += zoomIncrement;

                for(int i = 0; i < table.getChildCount(); ++i)
                {
                    TableRow row = (TableRow)table.getChildAt(i);
                    for(int r = 0; r < row.getChildCount(); ++r)
                    {
                        ImageView img = (ImageView)row.getChildAt(r);

                        if(zoomIndex  < zoomInThreshold)
                        {
                            TableRow.LayoutParams imgLayoutParams = new TableRow.LayoutParams(
                                    defaultSize,
                                    defaultSize
                            );
                            img.setLayoutParams(imgLayoutParams);

                            if(img.getDrawable() != null)
                            {
                                img.setAdjustViewBounds(true);
                                img.setMaxHeight(defaultSize);
                                img.setMaxWidth(defaultSize);
                                img.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
                            }
                        }
                    }
                }
                if(zoomIndex < zoomInThreshold)
                    zoomIndex++;

A: Figured out the problem, this problem only happens when I load my drawings from the xml files. All I had to do was add this line when loading the drawing
img.setAdjustViewBounds(true);

This is how it fits in:
                if(drawableID != -1)
                {
                    Bitmap pic = BitmapFactory.decodeResource(getResources(), drawableID);
                    Bitmap resizedBitmap = Bitmap.createScaledBitmap(pic, 50, 50, true);
                    im.setImageBitmap(resizedBitmap);

                    ic.setImage(im);

                    im.setTag(ic);

                    im.setAdjustViewBounds(true);

                    //rotate the icon
                    im.setScaleType(ImageView.ScaleType.MATRIX);
                    Matrix matrix = new Matrix();
                    matrix.set(im.getImageMatrix());
                    matrix.postRotate(rotAngle, pic.getWidth() / 2, pic.getHeight() / 2);
                    im.setImageMatrix(matrix);

                    im.setOnLongClickListener(longListen);//only set this listener if there is something there
                }

I only had img.setAdjustViewBounds(true); in my zoom buttons press.


text:
Q: How To Identify Files with Identical Content But a Different Arrangement of the Data I'm testing an upgrade we ran on an application that processes data. I took archived data that has already run through the system before and comparing it with output from the newly upgraded application. I'm noticing that the data is the same but the arrangement of the data in the new output is different. For example, in the new file line 57's data used to be on line 43 in the old output. Is there a way to detect that the files contain identical content? When I run a file compare in TextPad or do an MD5 hash compare, it doesn't detect that the files have the same content. It sees them as different files.

A: A hash compare is meaningless. Since e.g. two files with
foo
bar

and
bar
foo

would generate a completly different hash. Otherwise hash functions would be really broken.
I think your only chance here is to look if every line in file A is in file B (line by line). Maybe you could implement a sort algorithm. This could be done concurrent on both files and then you could compare the hash of these two files since the sort algorithm is deterministic in its output.

A: As Enak and Dominique have mentioned, sorting text files line by line and then comparing the two will reveal with complete certainty if anything is missing or not.
You might calculate some aggregate values of both files and compare them for sufficient proof though, which will be a lot faster. Are the number of words and characters the same? What about the number of different alphabets? Count all 26 alphabets in both files (you could also do the same for any character set of your choice), if their numbers match up exactly, there is a very high probability that both files contain the same information. This is on the same lines as your hashing approach, but obviously isn't as reliable.
If you need to know with certainty, you will have to compare each line of file A with each line of file B somehow. If the lines are completely shuffled, sorting the lines in file A and B and then comparing the files will be the best option. If there is locality however (line number x of file A tends to stay around location x in file B), you might as well just compare the two files without sorting, but rather by starting your search for line x of file A around location x in file B.


text:
Q: Images working/showing in my new Rails app Update: o.k. this is strange, in the brower, i can access the images at localhost:3000/assets/images/rails.png but when I put that path in the seeds.rb file and then load the page, it shows that it's trying to find the image in /assets/rails.png i.e. it's skipping over the images folder...any ideas?
Is it possible that rails is configured somewhere to only look into two folders?
I'm using a book called Agile web Development with Rails to learn how to use the framework but there seem to be some slight differences. It supplies code for rails 3.0 and 3.1 (I'm using the latter) but it's not always working as expected.  Thus far we have created scaffolding for Products class and used seeds.rb to put some data in the sqlite3 database. There are images in the assets/images folder for each "product" but it's not showing.
I experimented in the seeds.rb file with the path for the images but it didn't work.
Images are in the folder app/assets/images
I will show you the following files, all of which in some way deal with the images
1.app/views/products/_form.html.erb
2.app/views/products/index.html.erb
3. db/seeds.rb
UPDATE: in the logfile, it says there is a routing error for the images.
Started GET "/assets/wd4d.jpg" for 127.0.0.1 at Tue Sep 27 11:01:43 -0400 2011
Served asset /wd4d.jpg - 404 Not Found (3ms)

ActionController::RoutingError (No route matches [GET] "/assets/wd4d.jpg"):

Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.1.0/lib/action_dispatch/middleware/templates/rescues/routing_error.erb within rescues/layout (0.5ms)

Started GET "/images/ruby.jpg" for 127.0.0.1 at Tue Sep 27 11:01:43 -0400 2011

ActionController::RoutingError (No route matches [GET] "/images/ruby.jpg"):

app/views/products/_form.html.erb
<%= form_for(@product) do |f| %>
  <% if @product.errors.any? %>

<%= pluralize(@product.errors.count, "error") %> prohibited this product from being saved:

      <% @product.errors.full_messages.each do |msg| %>

<%= msg %>

      <% end %>

  <% end %>

    <%= f.label :title %>

    <%= f.text_field :title %>

    <%= f.label :description %>

    <%= f.text_area :description, :rows => 6 %>

    <%= f.label :image_url %>

    <%= f.text_field :image_url %>

    <%= f.label :price %>

    <%= f.text_field :price %>

    <%= f.submit %>

<% end %>

2.app/views/products/index.html.erb

Listing products

<% @products.each do |product| %>
  <tr class="<%= cycle('list_line_odd', 'list_line_even') %>">

      <%= image_tag(product.image_url, :class => 'list_image') %>

<%= product.title %>

<%= truncate(strip_tags(product.description),
               :truncate => 80) %>

      <%= link_to 'Show', product %>

      <%= link_to 'Edit', edit_product_path(product) %>

      <%= link_to 'Destroy', product,
                  :confirm => 'Are you sure?',
                  :method => :delete %>

<% end %>

<%= link_to 'New product', new_product_path %>

*

*3. db/seeds.rb  (notice here that I experimented with image url)
Product.delete_all
Product.create(:title => 'Web Design for Developers',
  :description =>
    %{
        blah blah
      },
  :image_url =>   'wd4d.jpg',
  :price => 42.95)

. . .
Product.create(:title => 'Programming Ruby 1.9',
  :description =>
    %{
        blah blah.
      },
  :image_url => '/images/ruby.jpg',
  :price => 49.50)

. . .
Product.create(:title => 'Rails Test Prescriptions',
  :description =>
    %{
        blah blah
      },
  :image_url => '/images/rtp.jpg',
  :price => 43.75)

A: Ok, So I've been working through this book to and you have to make changes in 2 places.
In the seed file, just reference the name of the jpg. Since you're using rails 3.1, anything inside of assets/images/ can be referenced just by it's name.
You'll have to make a change in the views as well. Download the source for the book here http://pragprog.com/titles/rails4/source_code and look at what they have for depot 2 in for the products#index view. They got really sloppy with this release.

A: Have a look at the Rails 3.1 Guide to Asset Pipeline. In section 2.2 Coding Links to Assets, you will find the following:

In regular views you can access images in the assets/images directory like this:
<%= image_tag "rails.png" %>

As I understand your code (I may be wrong here), you try to store the filename of an image in the database, and show that image later together with the other object data. So you should try to remove the path from it, use just the filename. And then denote it by using the method image_tag.

A: I had the same problem and then realized that when I downloaded the test images for the Depot application, they got saved as XXX.jpeg instead of XXX.jpg. As a result, the URL's in seeds.rb didn't match the filenames in assets/images.

A: The only thing that worked for me was:
<%= image_tag('/assets/images/' + product.image_url, class: 'list_image') %>


text:
Q: Presto - pivot table Hi I have a table like this:
Session id  Property
1           Radar
2           Bullet
1           Bullet
3           Radar
2           Price

I want to convert it into like this:
Radar   Bullet   Price
  1       1
          2        2
  3

A: For a fixed list of properties, you can do conditional aggregation:
select session_id,
    max(case when property = 'Radar'  then 1 else 0 end) as radar,
    max(case when property = 'Bullet' then 1 else 0 end) as bullet,
    max(case when property = 'Price'  then 1 else 0 end) as price
from mytable
group by session_id

This puts the session id in the first column and 0/1 values in each column, depending on whether the given session owns the given property.
To generate the exact output you showed (which might be a little less helpful than the above), you would do:
select
    case when max(case when property = 'Radar'  then 1 else 0 end) = 1 then session_id end as radar,
    case when max(case when property = 'Bullet' then 1 else 0 end) = 1 then session_id end as bullet,
    case when max(case when property = 'Price'  then 1 else 0 end) = 1 then session_id end as price
from mytable
group by session_id


text:
Q: Converting a md5 hash byte array to a string How can I convert the hashed result, which is a byte array, to a string?
byte[] bytePassword = Encoding.UTF8.GetBytes(password);

using (MD5 md5 = MD5.Create())
{
    byte[] byteHashedPassword = md5.ComputeHash(bytePassword);
}

I need to convert byteHashedPassword to a string.

A:    public static string ToHex(this byte[] bytes, bool upperCase)
    {
        StringBuilder result = new StringBuilder(bytes.Length*2);

        for (int i = 0; i < bytes.Length; i++)
            result.Append(bytes[i].ToString(upperCase ? "X2" : "x2"));

        return result.ToString();
    }

You can then call it as an extension method:
string hexString = byteArray.ToHex(false);

A: Well, you could use the string constructor that takes bytes and an encoding, but you'll likely get a difficult to manage string out of that since it could contain lots of fun characters (null bytes, newlines, control chars, etc)
The best way to do this would be to encode it with base 64 to get a nice string that's easy to work with:
string s = Convert.ToBase64String(bytes);

And to go from that string back to a byte array:
byte[] bytes = Convert.FromBase64String(s);

A: I always found this to be the most convenient:
string hashPassword = BitConverter.ToString(byteHashedPassword).Replace("-","");

For some odd reason BitConverter likes to put dashes between bytes, so the replace just removes them.
Update:
If you prefer "lowercase" hex, just do a .ToLower() and boom.
Do note that if you are doing this as a tight loop and many ops this could be expensive since there are at least two implicit string casts and resizes going on.

A: You can use Convert.ToBase64String and Convert.FromBase64String to easily convert byte arrays into strings.

A: If you're in the 'Hex preference' camp you can do this. This is basically a minimal version of the answer by Philippe Leybaert.
string.Concat(hash.Select(x => x.ToString("X2")))

B1DB2CC0BAEE67EA47CFAEDBF2D747DF

A: Well as it is a hash, it has possibly values that cannot be shown in a normal string, so the best bet is to convert it to Base64 encoded string.
string s = Convert.ToBase64String(bytes);

and use
byte[] bytes = Convert.FromBase64(s);

to get the bytes back.

A: I know this is an old question, but I thought I would add you can use the built-in methods (I'm using .NET 6.0):

*

*Convert.ToBase64String(hashBytes); (Others have already mentioned this)

*Convert.ToHexString(hashBytes);

A: For anyone interested a Nuget package I created called CryptoStringify allows you to convert a string to a hashed string using a nice clean syntax, without having to play around with byte arrays:
using (MD5 md5 = MD5.Create())
{
    string strHashedPassword = md5.Hash(password);
}

It's an extension method on HashAlgorithm and KeyedHashAlgorithm so works on SHA1, HMACSHA1, SHA256 etc too.
https://www.nuget.org/packages/cryptostringify


text:
Q: Can you get the content of a github file with javascript? Is there any way to get the content of a text file (txt/jss/html/...) with javascript or any other way, inserting it to a variable? (Also jquery is ok)
I mean:
abc.txt contains some text, that ttext should be stored into a variable.
Thanks

A: Yeah, it's pretty straightforward all you have to do is change the string a little bit like so, for example here is json file from a github repo
https://github.com/arnav7633/tej.js/blob/main/tsconfig.json
now that string gets changed to
https://raw.githubusercontent.com/arnav7633/tej.js/main/tsconfig.json
The domain changes. Then make a simple axios/fetch query to that URL

(async() => {
const res = await axios.get("https://raw.githubusercontent.com/arnav7633/tej.js/main/tsconfig.json")
console.log(res.data)
})()
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>


text:
Q: Animate circular progress with Swift I'm trying to animate the an arc using UIBezierPath when the user clicks on this custom control.  The bezier path simply snaps forward without any animation.
The reason I override the drawrect is because I want to display this custom control in interface builder.  Is there a good approach for displaying the circular progress in interface builder and have the progress animate?
Here is my code:
import Foundation
import UIKit
import QuartzCore

@IBDesignable class CircleControl:UIControl {
    @IBInspectable var progressTotal:CGFloat = 100

    @IBInspectable var progressCounter:CGFloat = 20
    {
    willSet(newProgressCounter) {
        let animation = CABasicAnimation(keyPath: "strokeEnd")
        animation.duration = 0.5;
        animation.toValue = newProgressCounter;
        animation.delegate = self;
        layer.addAnimation(animation, forKey: "strokeEnd")
    }

    didSet {
        setNeedsDisplay()
    }
    }

    override func drawRect(rect: CGRect) {
        let center = CGPointMake(bounds.size.width / 2, bounds.size.height / 2)
        let radius = bounds.size.width / 2;
        let pi = CGFloat(M_PI)
        let sliceAngle:CGFloat = (2 * pi) / progressTotal

        let progressAngle:CGFloat = sliceAngle * progressCounter
        let startAngle:CGFloat = CGFloat(-M_PI_2) + sliceAngle
        let endAngle:CGFloat = startAngle + progressAngle;

        let path = UIBezierPath()
        path.addArcWithCenter(center, radius: radius - 5, startAngle: startAngle, endAngle: endAngle, clockwise: true)
        path.lineWidth = 5
        path.stroke()
    }

    override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) {
        println("touch")

        self.progressCounter = 80
    }

    override func touchesEnded(touches: NSSet!, withEvent event: UIEvent!) {
        self.progressCounter = 20
    }
}

A: You cannot animate inside of IB.  You might be able to do this in a playground but IB is for layout only - it does not do animations.  You must preview in the simulator or playgrounds.


text:
Q: check php variable in javascript function I've downloaded a template for web.
In this template, there is a php script to send email. In this script there is a validate() function, in which there is a variable $return_array. one of its value is $return_array['success'] that could be '0' or '1'. In another file, a javascript one, there is a click() function, that manages the value of 'success' in the php script doing if(html.success == '1')...but it does not work as expected, infact it is always '0'...what do I need to check?
Here is the html form:
<form method="POST" action="send_form_email.php" id="contactform">

                Inserisci il tuo nome
                    <input type="text" class="input-field" id="name" name="name" value="">

                Inserisci la tua e-mail
                    <input type="text" class="input-field" id="email" name="email" value="">

                Scrivi il tuo messaggio
                    <textarea id="message" name="message" style="min-height: 160px;"></textarea>

                Invia E-Mail

Il tuo messaggio &egrave stato inviato correttamente!

Impossibile inviare il messaggio. Riprovare pi&ugrave tardi.

        </form>

and here is the function into the php
<?php
// EDIT THE 2 LINES BELOW AS REQUIRED
$send_email_to = "mail.address@email.com";
$email_subject = "Feedback subject";
function send_email($name,$email,$email_message)
{
  global $send_email_to;
  global $email_subject;
  $headers = "MIME-Version: 1.0" . "\r\n";
  $headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
  $headers .= "From: ".$email. "\r\n";
  $message = "Email = ".$email."
";
  $message .= "Name = ".$name."
";
  $message .= "Message = ".$email_message."
";
  @mail($send_email_to, $email_subject, $message,$headers);
  return true;
}

function validate($name,$email,$message)
{
  $return_array = array();
  $return_array['success'] = '1';
  $return_array['name_msg'] = '';
  $return_array['email_msg'] = '';
  $return_array['message_msg'] = '';
  if($email == '')
  {
    $return_array['success'] = '0';
    $return_array['email_msg'] = 'email is required';
  }
  else
  {
    $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
    if(!preg_match($email_exp,$email)) {
      $return_array['success'] = '0';
      $return_array['email_msg'] = 'enter valid email.';
    }
  }
  if($name == '')
  {
    $return_array['success'] = '0';
    $return_array['name_msg'] = 'name is required';
  }
  else
  {
    $string_exp = "/^[A-Za-z .'-]+$/";
    if (!preg_match($string_exp, $name)) {
      $return_array['success'] = '0';
      $return_array['name_msg'] = 'enter valid name.';
    }
  }

  if($message == '')
  {
    $return_array['success'] = '0';
    $return_array['message_msg'] = 'message is required';
  }
  else
  {
    if (strlen($message) < 2) {
      $return_array['success'] = '0';
      $return_array['message_msg'] = 'enter valid message.';
    }
  }
  return $return_array;
}

$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];

$return_array = validate($name,$email,$message);

if($return_array['success'] == '1')
{
    send_email($name,$email,$message);

}
header('Content-type: text/json');
echo json_encode($return_array);
die();
?>

and following the javascript code:
$('#button-send').click(function(event){
    $('#button-send').html('Invio in corso...');
    event.preventDefault();

    //$('html, body').scrollTo( $('#contact'), 'fast' );
    $.ajax({
        type: 'POST',
        url: 'send_form_email.php',
        data: $('#contactform').serialize(),
        success: function(html) {
            if(html.success == '1')
            {
                $('#button-send').html('Invia E-Mail');
                $('#success').show();

            }
            else
            {
                $('#button-send').html('Invia E-Mail');
                $('#error').show();
                console.log(html);
            }
        },
        error: function(){
            $('#button-send').html('Invia E-Mail');
            $('#error').show();
            console.log("not html.success");
        }
    });

});

EDIT:
I've edited the php part adding at the end the json_encode and content type, but when there is an error, like name missing or mail missing, I expect to see something appears near the input form, but it does not...

A: Use return json_encode($return_array); Instead of return $return_array;.
Json encode returns key => value pair array .
Also use dataType: "json" OR dataType: "jsonp"  in ajax call.


text:
Q: change the format of laravel API Errors and Exceptions I write api for the applications with laravel.
for example I have two field which are "city_id" and "address" and I validate them with these rules :
$request->validate([
    'city_id' => 'bail|required|numeric',
    'address' => 'required'
]);

if validation fails the response will be :
{
"message": "The given data was invalid.",
"errors": {
    "city_id": ["The city id field is required."]
  }
}

everything is fine but I want change the validation error at api response to this :
{
 "msg" => 'The city id field is required.'
}

actually I want send one error without the key .  where can I change that?

A: You can write/modify the Laravel exceptions handler. Here you can read more about it here https://laravel.com/docs/5.8/errors or here https://laravel.com/docs/6.x/errors (depends what version of Laravel you using)
Example:
class Handler extends ExceptionHandler
{

    ...

    public function render($request, Exception $e)
    {
       if ($exception instanceof ValidationException) {
           return new JsonResponse(
                  ['msg' => $e->getMessage()],
                  400
           );
       }
    }

    ...

}


text:
Q: strace -c doesn't report exit system calls I'm working through some homework, and I need to report which system calls a C program makes use of.
I noticed though that exit doesn't show up in strace reports.
#include <stdlib.h>

int main() {
    exit(0);
}

┌─[brendon@parrot]─[~/Desktop/Classes/OSInternals/Lab3]
└──╼ $gcc exit.c
┌─[brendon@parrot]─[~/Desktop/Classes/OSInternals/Lab3]
└──╼ $strace -c ./a.out
% time     seconds  usecs/call     calls    errors syscall
------ ----------- ----------- --------- --------- ----------------
 38.74    0.001056         150         7           mmap
 11.12    0.000303         151         2           openat
 10.20    0.000278         139         2           fstat
 10.09    0.000275         137         2           close
  9.21    0.000251         251         1           arch_prctl
  7.45    0.000203          67         3           mprotect
  6.20    0.000169         169         1           munmap
  5.25    0.000143         143         1           read
  1.76    0.000048          48         1         1 access
  0.00    0.000000           0         1           brk
  0.00    0.000000           0         1           execve
------ ----------- ----------- --------- --------- ----------------
100.00    0.002726                    22         1 total

As you can see, exit doesn't show up in the report. Am I wrong that it's a system call? Reading usr/include/x86_64-linux-gnu/asm/unistd_64.h, I can see an exit entry:
. . .
#define __NR_execve 59
#define __NR_exit 60
#define __NR_wait4 61
. . .

What am I missing here?
Running on Parrot OS.

I was hesitant to post this because it's not clear if this is ontopic enough. I can delete this promptly if it's decided that it's not.

A: For some reason it doesn't show up in the -c summary but it does show up in the regular strace output:
#include <stdlib.h>

int main(void)
{
    exit(69);
}

$ strace ./exit
execve("./exit", ["./exit"], 0x7ffddc502ce0 /* 42 vars */) = 0
brk(NULL)                               = 0x563a56e63000
access("/etc/ld.so.preload", R_OK)      = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
fstat(3, {st_mode=S_IFREG|0644, st_size=113870, ...}) = 0
mmap(NULL, 113870, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7f16c8537000
close(3)                                = 0
openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3
read(3, "\177ELF\2\1\1\3\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\260A\2\0\0\0\0\0"..., 832) = 832
fstat(3, {st_mode=S_IFREG|0755, st_size=1824496, ...}) = 0
mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f16c8535000
mmap(NULL, 1837056, PROT_READ, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7f16c8374000
mprotect(0x7f16c8396000, 1658880, PROT_NONE) = 0
mmap(0x7f16c8396000, 1343488, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x22000) = 0x7f16c8396000
mmap(0x7f16c84de000, 311296, PROT_READ, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x16a000) = 0x7f16c84de000
mmap(0x7f16c852b000, 24576, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1b6000) = 0x7f16c852b000
mmap(0x7f16c8531000, 14336, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7f16c8531000
close(3)                                = 0
arch_prctl(ARCH_SET_FS, 0x7f16c8536500) = 0
mprotect(0x7f16c852b000, 16384, PROT_READ) = 0
mprotect(0x563a565ba000, 4096, PROT_READ) = 0
mprotect(0x7f16c857a000, 4096, PROT_READ) = 0
munmap(0x7f16c8537000, 113870)          = 0
exit_group(69)                          = ?
+++ exited with 69 +++

$ strace -c ./exit
% time     seconds  usecs/call     calls    errors syscall
------ ----------- ----------- --------- --------- ----------------
  0.00    0.000000           0         1           read
  0.00    0.000000           0         2           close
  0.00    0.000000           0         2           fstat
  0.00    0.000000           0         7           mmap
  0.00    0.000000           0         4           mprotect
  0.00    0.000000           0         1           munmap
  0.00    0.000000           0         1           brk
  0.00    0.000000           0         1         1 access
  0.00    0.000000           0         1           execve
  0.00    0.000000           0         1           arch_prctl
  0.00    0.000000           0         2           openat
------ ----------- ----------- --------- --------- ----------------
100.00    0.000000                    23         1 total

Given that -c measures the time spent in each system call, I guess it doesn't make any sense to measure exit (which never returns).