text:
Q: Removing the KDE line while keeping the density plot histogram in Seaborns `distplot` import seaborn as sns, numpy as np
x = np.random.randn(100)
ax = sns.distplot(x)

This will give a density histogram with a line (I think it is the kernel fit or something)
However I want the SAME histogram but not the fitted line. I have tried with kde = False but this changes the y-axis so it is not longer a density plot but frequency histogram. How do I remove the line but keep the density plot (histogram)?

A: You can remove the kernel density estimate (kde) line by accessing the line objects from the axis object ax as following. This way, you still retain the density plot.
import seaborn as sns, numpy as np
x = np.random.randn(100)
ax = sns.distplot(x)

ax.get_lines()[0].remove()

A: Full docs here
The best way to remove this line is
import seaborn as sns, numpy as np
x = np.random.randn(100)

# Without the KDE line present, the bars will represent raw counts, not frequencies
ax = sns.distplot(x, kde=False)

# To plot frequencies (normalize the histogram), set the norm_hist argument to true
ax = sns.distplot(x, kde=False, norm_hist=True)

Both of these plot the bins without the KDE line. (Note that without the KDE line, the x-range of your graph will be slightly narrower.) If you'd wanted just the line and no bars, you could do ax = sns.distplot(x, hist=False).


text:
Q: group concat of fields in mongodb in aggregation My documents in collection,
{
    "_id" : "abc1",
    "Data" : {
        "Campaign Name" : "Campaign 1",
        "Ad Set Name" : "Adset 1",
        "Ad Name" : "Ad 1",
        "URL Tags" : "url tag 1"
    }
},
{
    "_id" : "abc2",
    "Data" : {
        "Campaign Name" : "Campaign 2",
        "Ad Set Name" : "Adset 1",
        "Ad Name" : "Ad 1",
        "URL Tags" : "url tag 1"
    }
},
{
    "_id" : "abc3",
    "Data" : {
        "Campaign Name" : "Campaign 2",
        "Ad Set Name" : "Adset 2",
        "Ad Name" : "Ad 2",
        "URL Tags" : "url tag 2"
    }
},
{
    "_id" : "abc4",
    "Data" : {
        "Campaign Name" : "Campaign 3",
        "Ad Set Name" : "Adset 1",
        "Ad Name" : "Ad 1",
        "URL Tags" : "url tag 1"
    }
}

Need something like this in output,
{
    "_id" : "Campaign 3",
    "total" : 60.0,
    "myField" : [ "url tag 1-Ad 1" ]
},
{
    "_id" : "Campaign 2",
    "total" : 120.0,
    "myField" : [ "url tag 1-Ad 1", "url tag 2-Ad 2" ]
},
{
    "_id" : "Campaign 1",
    "total" : 96.0,
    "myField" : [ "url tag 1-Ad 1" ]
}

What i have done(unsuccessfully) so far,
db.adsets.aggregate([
    {$group:{_id:"$Data.Campaign Name",total:{$sum:1}}},
    {$project:{_id:1,total:1,myField:{$concat:["$Data.URL Tags","-","$Data.Ad Name"]}}}
],{explain:false});

Currently getting this in output,
{
    "_id" : "Campaign 3",
    "total" : 60.0,
    "myField" : null
},
{
    "_id" : "Campaign 2",
    "total" : 120.0,
    "myField" : null
},
{
    "_id" : "Campaign 1",
    "total" : 96.0,
    "myField" : null
}

I don't know what i am doing wrong which is why i am getting null instead of concatenated string in myField. Please help!! Thanks in advance.

A: You can concatenate required values and push to an array during grouping:
db.adsets.aggregate([
    {$group:{
        _id:"$Data.Campaign Name",
        total : {$sum:1},
        myfield: {$push: {$concat:["$Data.URL Tags", "-", "$Data.Ad Name"]}}
        }
    }]
)

This should give output as you mentioned.
(As you mentioned in your question comment, myfield field will be an array as you need and not object like initial question)
If you don't want concatenated values to appear twice when same, you can use $addToSet instead of push
db.adsets.aggregate([
    {$group:{
        _id:"$Data.Campaign Name",
        total : {$sum:1},
        myfield: {$addToSet: {$concat:["$Data.URL Tags", "-", "$Data.Ad Name"]}}
        }
    }]
)

redpajama_set_name: RedPajamaStackExchange


text:
Q: convert encoding via iconv linux I used to convert encoding via iconv but today i stopped by something new to me
I made a testcase to make my question clear :
the goal is convert الحلقة الثالثة to its utf8 version :   الحلقة الثالثة

<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title> this text is from arabic language   </title>

 الحلقة الثالثة

tried to use encoding like ASCII , LATIN1 , windows-1252 but with no luck
how do i tell what is this type of encoding in order to convert it ??
both of  google translate + stackoverflow editor  was able to detect it and covert it ?
another example : this website http://kanjidict.stc.cx/recode.php was able to convert the encoding correctly if i check the Assume HTML (default: handle as plain text)
what i am missing and those 3 websites was do it  to convert it correctly ????

A: Well  ,
after one day working , i have found my lost command  , its a package i had installed called ascii2uni
simply by : sudo apt-get install ascii2uni
and after some testing i was able to convert one file to unicode by using this command
ascii2uni -a D source.html > target.html
and i was able to convert it using command line only
cheers

A: The idea is string substitution. Coding in Python3.
parse decimal only:
>>> import re
>>> s = r'Aßþ'
>>> r = re.compile(r'&#(\d+);')
>>> r.sub(lambda m:chr(int(m.group(1))), s)
'Aßþ'

parse hex and decimal:
>>> import re
>>> s = r'Aßþ'
>>> r = re.compile(r'&#(x?)(\w+);')
>>> r.sub(lambda m:chr(int(m.group(2), 10 if not m.group(1) else 16)), s)
'Aßþ'

A: Those numbers are called letter codes. There are special functions, related to url and html processing, that handle them - depending which language are you using.

In PHP, there is http://www.php.net/manual/en/function.htmlspecialchars-decode.php  In other languages should be similar functions also

A: recode html..utf8

this should work too, but pls make sure you read the usage manual for recode, it recodes files in place if not told otherwise.


text:
Q: Need help making this simple JQuery image hover script deprecate to just CSS only when javascript is disabled I currently have a very basic JQuery script accompanied by some CSS that helps create a smooth fading effect for when someone hovers over a product image on my site. What Id like to be able to do however is allow users that have Javascript disabled to still get a basic show/hide hover effect via CSS only. How might this be accomplished?
Thanks
Here is what I currently have going to give you an idea:
HTML

<a href="<?php the_permalink(); ?>" class="product_view_sm">..View Item..
<?php the_post_thumbnail('prod-img-sm', array('class' => 'single_product_img_sm', 'alt' => 'View Product')); ?>

CSS
ul.product_list_sm li {
    overflow: hidden;
    width: 192px;
    height: 192px;
    margin-right: 15px;
    margin-bottom: 15px;
    float: left;
    position: relative;
}

a.product_view_sm {
    font-family: aaaiightRegular;
    font-size: 15px;
    font-weight: normal;
    color: #000000;
    background: url(images/epr_store_product_overlay.png) no-repeat;
    width: 184px;
    height: 59px;
    padding: 125px 0px 0px 0px;
    position: absolute;
    top: 4px;
    left: 4px;
    display: block;
    text-align: center;
    z-index: 200;
}

img.single_product_img_sm {
    position: absolute;
    top: 0px;
    left: 0px;
    z-index: 100;
}

JQuery
// Fade anchor graphic in on hover for small products
$(document).ready(function() {
    $('a.product_view_sm').css("opacity","0");
    $('.product_list_sm li').hover(
        function(){
            $(this).find('a.product_view_sm').animate({
                opacity: 1
            }, 250);
        },
        function(){
            $(this).find('a.product_view_sm').animate({
                opacity: 0
            }, 250);
        }
    );
});

A: Based on your javascript, this should do the same thing without the animation
a.product_view_sm { opacity: 0; }
.product_list_sm li:hover a.product_view_sm { opacity: 1; }


text:
Q: False typescript errors in the browser window I have a line of code written using Typescript. The label argument has a string type this is clearly visible in the screenshot

At the same time, after compiling the code, an error appears in the browser window that says that label has the type any.

Please tell me what is the cause and how can I fix this behavior

A: Specify the label to be of type string
mdValue = filterData.value.map((label: string) => {
 // ...
});


text:
Q: what is meant "seg fs" in the linux kernel bootsect.s file When I reading the early Linux kernel code, I encountered a problem in boot/bootsect.s that was difficult to understanding."seg fs" ,What is it doing? If I want to change to AT&T's assembly syntax, How should I do!
    go: mov ax,cs
    mov dx,#0x4000-12   ! 0x4000 is arbitrary value >= length of
                ! bootsect + length of setup + room for stack
                ! 12 is disk parm size

! bde - changed 0xff00 to 0x4000 to use debugger at 0x6400 up (bde).  We
! wouldn't have to worry about this if we checked the top of memory.  Also
! my BIOS can be configured to put the wini drive tables in high memory
! instead of in the vector table.  The old stack might have clobbered the
! drive table.

    mov ds,ax
    mov es,ax
    mov ss,ax       ! put stack at INITSEG:0x4000-12.
    mov sp,dx
/*
 *  Many BIOS's default disk parameter tables will not
 *  recognize multi-sector reads beyond the maximum sector number
 *  specified in the default diskette parameter tables - this may
 *  mean 7 sectors in some cases.
 *
 *  Since single sector reads are slow and out of the question,
 *  we must take care of this by creating new parameter tables
 *  (for the first disk) in RAM.  We will set the maximum sector
 *  count to 18 - the most we will encounter on an HD 1.44.
 *
 *  High doesn't hurt.  Low does.
 *
 *  Segments are as follows: ds=es=ss=cs - INITSEG,
 *      fs = 0, gs = parameter table segment
 */

    push    #0
    pop fs
    mov bx,#0x78        ! fs:bx is parameter table address
    seg fs
    lgs si,(bx)         ! gs:si is source

    mov di,dx           ! es:di is destination
    mov cx,#6           ! copy 12 bytes
    cld

    rep
    seg gs
    movsw

    mov di,dx
    movb    4(di),*18       ! patch sector count

    seg fs
    mov (bx),di
    seg fs
    mov 2(bx),es

    mov ax,cs
    mov fs,ax
    mov gs,ax

    xor ah,ah           ! reset FDC
    xor dl,dl
    int     0x13

A: I assume it assembles as a fs prefix for the next instruction.  That would match the comments, and is the only thing that makes sense.
Should be easy enough to build it and disassemble (into AT&T syntax if you want).
In AT&T syntax, you can just use fs as a prefix to other mnemonics.
fs movsw

assembles to this (in 64-bit mode.  16-bit mode would skip the 66 operand-size prefix).
0000000000000000 <.text>:
   0:   64 66 a5                movsw  %fs:(%rsi),%es:(%rdi)

A: who can tell me to change this to be correct or not? !
__go:
movw    %cs         ,   %ax
movw    $0x4000-12  ,   %dx
movw    %ax         ,   %ds
movw    %ax         ,   %es
movw    %ax         ,   %ss
movw    %dx         ,   %sp
pushw   $0x0000
popw    %fs
movw    $0x0078     ,   %bx
lgs     %fs:(%bx)   ,   %si
movw    %dx         ,   %di
movw    $0x0006     ,   %cx
cld
rep
movw    %dx         ,   %di
movw    $0x12       ,   0x0004(%di)
movw    %di         ,   %fs:(%bx)
movw    %es         ,   %fs:0x0002(%bx)
movw    %cs         ,   %ax
movw    %ax         ,   %fs
movw    %ax         ,   %gs
xorb    %ah         ,   %ah
xorb    %dl         ,   %dl
int     $0x13


text:
Q: c++ string constructed as char array currently learning strings, i have the following:
string s;
s[0]='a'; s[1]='b';
cout<<s;

string s; s.clear();
s+='a'; s+='b';
cout<<s;

I get empty string as output from 1st example, and the 2nd works fine. I get that the 1st is undef behavior and that we 'push' an element the second time instead of assigning a value.
Any more clarification will be appreciated

A: string s;

creates empty string
s[0]='a'; s[1]='b';

this is undefined behavior, since empty string have size zero, so required buffer may not exists.
It "works" since all major compilers are using Small String Optimization (SSO). In this optimization size of string object, allows to keep small string inside that object not on a heap. As a result minimum capacity of std::string is none zero (15 in gcc if I remember correctly).
cout<<s;

Now deeding on how this stream operator is implemented it can print empty string (size size of string is zero) or "ab" or "ab<some thrash>".
On gcc it prints nothing.
To fix it you can:

*

*resize string first s.resize(2)

*use push_back API


text:
Q: google play service not bind with titanium studio android OS: Mac OS X - Yosemite

Using Titanium Studio
Problem
google_play_service not imported properly into titanium studio' android project.
Error when running the project
[ERROR] :  /Users/myself/Documents/Titanium_Studio_Workspace/Project/build/android/AndroidManifest.xml:27: error: Error: No resource found that matches the given name (at 'value' with value '@integer/google_play_services_version').
[ERROR] Application Installer abnormal process termination. Process exit value was 1

Note

SDK already having google_play_services library into {SDK}/extras/google/

If you have any solution then please share here.

Thank you in advance.


text:
Q: take a sample that has a specific mean Let's say I have a population like {1,2,3, ..., 23} and I want to generate a sample so that the sample's mean equals 6.
I tried to use the sample function, using a custom probability vector, but it didn't work:
population <- c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23)
mean(population)
minimum <- min(population)
maximum <- max(population)
amplitude <- maximum - minimum
expected <- 6
n <- length(population)
prob.vector = rep(expected, each=n)
for(i in seq(1, n)) {
  if(expected > population[i]) {
    prob.vector[i] <- (i - minimum) / (expected - minimum)
  } else {
    prob.vector[i] <- (maximum - i) / (maximum - expected)
  }
}
sample.size <- 5
sample <- sample(population, sample.size, prob = prob.vector)
mean(sample)

The mean of the sample is about the mean of the population (oscillates around 12), and I wanted it to be around 6.
A good sample would be:

*

*{3,5,6,8,9}, mean=6.2

*{2,3,4,8,9}, mean=5.6

The problem is different from sample integer values in R with specific mean because I have a specific population and I can't just generate arbitrary real numbers, they must be inside the population.
The plot of the probability vector:

A: You can try this:
m = local({b=combn(1:23,5);
           d = colMeans(b);
           e = b[,d>5.5 &d<6.5];
           function()sample(e[,sample(ncol(e),1)])})
m()
[1] 8 5 6 9 3
m()
[1]  6  4  5  3 13

breakdown:
b=combn(1:23,5) # combine the numbers into 5
d = colMeans(b) # find all the means
e = b[,d>5.5 &d<6.5] # select only the means that are within a 0.5 range of 6
sample(e[,sample(ncol(e),1)]) # sample the values the you need


text:
Q: Google Analytics iOS SDK 3.12 data not visible in dashboard I implemented Google Analytics in an app.
The problem is that I don't see anything in Google Analytics dashboard.
Here is the logs I can see in Xcode: ('...' are values I replaced)
2015-07-02 20:55:28.091 AppName[1619:931478] VERBOSE: GoogleAnalytics 3.12 -[GAIBatchingDispatcher persist:] (GAIBatchingDispatcher.m:517): Saved hit: {
    parameters =     {
        "&_crc" = 0;
        "&_s" = 51;
        "&_u" = ".oK9L";
        "&_v" = "mi3.1.2";
        "&a" = 1809611894;
        "&aid" = "...";
        "&an" = ...;
        "&av" = "3.0.3";
        "&cd" = Home;
        "&cid" = "...";
        "&dm" = "iPad3,4";
        "&ds" = app;
        "&sr" = 2048x1536;
        "&t" = screenview;
        "&tid" = "...";
        "&ul" = fr;
        "&v" = 1;
        "&z" = 14083819698118597511;
        gaiVersion = "3.12";
    };
    timestamp = "2015-07-02 18:55:28 +0000";
}

2015-07-02 20:55:36.043 AppName[1619:931478] VERBOSE: GoogleAnalytics 3.12 -[GAIRequestBuilder requestPostUrl:payload:compression:] (GAIRequestBuilder.m:167): building URLRequest for https://ssl.google-analytics.com/batch
2015-07-02 20:55:36.045 AppName[1619:931478] VERBOSE: GoogleAnalytics 3.12 -[GAIBatchingDispatcher dispatchWithCompletionHandler:] (GAIBatchingDispatcher.m:632): Sending hit(s) POST: https://ssl.google-analytics.com/batch
2015-07-02 20:55:36.077 AppName[1619:931363] INFO: GoogleAnalytics 3.12 -[GAIBatchingDispatcher didSendHits:response:data:error:] (GAIBatchingDispatcher.m:226): Hit(s) dispatched: HTTP status 200
2015-07-02 20:55:36.078 AppName[1619:931478] INFO: GoogleAnalytics 3.12 -[GAIBatchingDispatcher deleteHits:] (GAIBatchingDispatcher.m:529): hit(s) Successfully deleted
2015-07-02 20:55:36.088 AppName[1619:931478] INFO: GoogleAnalytics 3.12 -[GAIBatchingDispatcher didSendHits:] (GAIBatchingDispatcher.m:237): 8 hit(s) sent

So I am pretty sure the analytics data are sent (somewhere... on a server... in space...).
But I don't see any of it in the Analytics Dashboard. I can see on which screen I am in the Real time section, but I don't see global screen hits.
Here is the code if you see anything wrong:
// AppDelegate.swift
// Configure tracker from GoogleService-Info.plist.
var configureError:NSError?
GGLContext.sharedInstance().configureWithError(&configureError)
assert(configureError == nil, "Error configuring Google services: \(configureError)")

// Optional: configure GAI options.
var gai = GAI.sharedInstance()
gai.trackUncaughtExceptions = true  // report uncaught exceptions
gai.dispatchInterval = 10
gai.logger.logLevel = GAILogLevel.Verbose  // remove before app release

// Analytics.swift
class Analytics {

    static let sharedInstance = Analytics()

    init() {
        GAI.sharedInstance().trackerWithTrackingId("...")
    }

    func trackView(viewName: String) {
        println(viewName)
        let tracker = GAI.sharedInstance().defaultTracker
        tracker.set(kGAIScreenName, value: viewName)

        var builder = GAIDictionaryBuilder.createScreenView()
        tracker.send(builder.build() as [NSObject : AnyObject])
    }

}

A: The simple answer is that you just have to wait.
There are other posts stating that you need to wait 48h with a link to the documentation. I was not able to find the section in the new documentation.
For me the data were available the day after my tests.


text:
Q: Find differences in strings on pandas column I have the following pandas DataFrame from this CSV file
import pandas as pd
df=pd.read_csv('Last_year.csv')
df.groupby('School Status').size().plot(kind='pie', autopct='%1.1f%%')

I would like to know how I can remove the error which is causing me to have 3 divisions and not 2 as programmed
Here is the result

A: Seems like you're having these three dimensions in your DataFrame.
df['School Status'].unique()
array(['IN SCHOOL', 'OUT OF SCHOOL', 'OUT OF SCHOOL '], dtype=object)
So, if you'll remove whitespace after the last one, it should work properly:
Try this snippet:
import pandas as pd
df=pd.read_csv('Last_year.csv')
df['School Status'] = df['School Status'].replace({'OUT OF SCHOOL ': 'OUT OF SCHOOL'})
df.groupby('School Status').size().plot(kind='pie', autopct='%1.1f%%')

A: You may have more spaces in one of the labels.
To check what are the labels that pandas detects, you can use Series.unique().
You can remove whitespace from beginning and end for example by using str.strip element-wise, doing:
import pandas as pd  # This code is from OP
df=pd.read_csv('Last_year.csv')  # This code is from OP
df['School Status'] = df['School Status'].map(str.strip)
df.groupby('School Status').size().plot(kind='pie', autopct='%1.1f%%')  # This code is from OP
# Now you can plot your DF


text:
Q: Providing a mechanism for end users to install Silverlight 2.0 without going to the Microsoft site Our web-based application is installed at end-customers. Typically these customers do not have access to the internet. Part of the next version of our application is Silverlight 2.0 based.
When a browser without the Silverlight 2.0 plugin tries to access our the Silverlight portion of our app, the customer gets the standard "Install Microsoft Silverlight" image which, when clicked on, tries to go to the Microsoft download site.
Is there a way that we can control this page? We would like to provide the Silverlight plugin with our app so a user could then directly download it from our app when they don't already have the plugin installed.

A: You can use the javascript API which was originally available in v1 of Silverlight to edit things like the loading animation and also the Install mechanism.
Silverlight Javascript API


text:
Q: How can I generate weak SSH keys? I'm trying to put together a demonstration of the increasing difficulty of cracking SSH / RSA keys.
Ideally, I'd like to demonstrate cracking a 64-bit key, then a 128-bit, 256-bit, then, (possibly) a 512-bit, but never get to a 1024-bit, showing that the time increases drastically at each level.
However, ssh-keygen with the -b option seems to reject anything 512 and under as too small.
How can I deliberately generate weak keys?

A: openssl's genrsa subcommand can generate RSA key pairs as small as 64 bits. See genrsa(1).


text:
Q: How do Jetty and other containers leverage NIO while sticking to the Servlet specification? I'm new to NIO, and I am trying to figure out how Jetty leverages NIO.
My understanding of how traditional servlet containers that use Blocking IO service a request is as follows:

*

*A request arrives

*A thread is allocated to process the request and the servlet method (doGet etc) is invoked

*Servlet method is handed an InputStream and OutputStream

*The servlet method reads from the InputStream and writes to the OutputStream

*The InputStream and OutputStream are basically tied to the respective streams of the underlying Socket
What is different when an NIO connector is used? My guess is along the following lines:

*

*A request arrives

*Jetty uses NIO connector and buffers the entire request asynchronously

*Once request has been read completely wrap the buffer in an InputStream

*Create an empty response buffer (wrapped in an OutputStream)

*Allocate a thread and invoke the servlet method (doGet etc) handing the above wrapper streams

*Servlet method writes to the wrapped (buffered) response stream and returns from the servlet method

*Jetty uses NIO to write the response buffer contents to the underlying SocketChannel
From the Jetty documentation, I found the following:
SelectChannelConnector - This connector uses efficient NIO buffers with a non-blocking threading model. Jetty uses Direct NIO buffers, and allocates threads only to connections with requests. Synchronization simulates blocking for the servlet API, and any unflushed content at the end of request handling is written asynchronously.
I'm not sure I understand what Synchronization simulates blocking for the servlet API means?

A: You don't have it exactly correct.  When jetty uses an NIO connector (and 9 only supports NIO) it works as follows:

*

*Idle state as a few threads (1-4 depending on # cores) calling the selector, looking for IO activity.  This has been scaled to over 1,000,000 connections on Jetty.

*When selector sees IO activity, it calls a handle method on the connection, which either:

*

*something else has registered that it is blocked waiting for IO for this connection, so in that case the selector just wakes up whoever was blocked.

*otherwise a thread is dispatched to handle the connection.

*If a thread is dispatched, then it will attempt to read the connection and parse it.  What happens now depends on if the connection is http, spdy, http2 or websocket.

*

*for http, if the request headers are complete, the thread goes on to call the handling of the request (eventually this gets to the servlet) without waiting for any content.

*for http2/spdy another dispatch is required, but see the discussion about Eat-What-You-Kill strategy on the list: http://dev.eclipse.org/mhonarc/lists/jetty-dev/msg02166.html

*for websocket the message handling is called.

*Once a thread is dispatched to a servlet, it looks to it like the servlet IO is blocking, but underneath the level of HttpInputStream and HttpOutputStream all the IO is async with callbacks.  The blocking API uses a special blocking callback to achieve blocking.    This means that if the servlet chooses to use async IO, then it is just bypassing the blocking callback and using the async API more or less directly.

*A servlet can suspend using request.startAsync, in which case the dispatched thread is returned to the thread pool, but the associated connection is not marked as interested in IO. Async IO can be performed, but a AsyncContext event is need to either reallocate a thread or to re-enroll the connection for IO activity once the async cycle is complete.

This view is slightly complicated by http2 and spdy, which are multiplexed, so they can involve an extra dispatch.
Any HTTP framework that does not dispatch can go really really fast in benchmark code, but when faced with a real application that can do silly things like block on databases, files system, REST services etc... then lack of dispatch just means that one connection can hold up all the other connections on the system.
For some more info on how jetty handles async and dispatch see:

*

*https://webtide.com/asynchronous-callbacks/

*https://webtide.com/jetty-9-goes-fast-with-mechanical-sympathy/

*https://webtide.com/avoiding-parallel-slowdown-in-jetty-9/

*https://webtide.com/lies-damned-lies-and-benchmarks-2/

*https://webtide.com/jetty-in-techempower-benchmarks/


text:
Q: Custom AsyncTaskLoader with cache There are several tutorials on how to implement custom AsyncTaskLoaders but none I found discusses how to handle data caching - in all of them the data are just loaded and delivered.
Can you give me some hints how to implement custom AsyncTaskLoader that would return cached versions of data immediatelly but at the same time request an update of the data and deliver the updated vesions of them as soon as they arrive? Is this even possible with Loaders or do I have to use another mechanism and which?
Background: I have an IntentService which accepts requests for data loading and delivers the results in broadcasts. I have an UI (ListView) that should display that data from ArrayAdapter or CrusorAdapter. I need some "caching" layer that would keep lastest known versions of the data to be displayed immediatelly but issue their update and re-display them as soon as new data arrives.
Although this could be done using dumb SQLite database for immediate versions and broadcast receiver for new data update, I'd give a preference to something that would make this "backgorund" data loading mechanism transparent like Loader-derived class IMHO could be.

A: Yes, AsycnTask is the best way to do this. All you would do is write to your cache on the onPostExecute() of the AsyncTask. This could be done by creating a time stamp that compares data times and if there is a new time, use that data. Otherwise, you would have to compare all the data, and that can take precious time and resources, so it would depend on how much data you had.
Here is a link that might help:
http://developer.android.com/training/efficient-downloads/redundant_redundant.html


text:
Q: add dash after three characters in input type number In my angular project, I had input type number I need to add a dash after three characters. if add input type number is not working for me if add input type text its working fine.
<input type="number" id="bank-code" (keyup)="onKey($event.target.value)" [value]='value' maxlength="7" required />

onKey(event){
  var ele = event.split('-').join('');
  if(ele.length > 0){
    ele = ele.match(new RegExp('.{1,3}', 'g')).join("-");
  }
  this.value = ele;
}

A: Input type number does not allow non-numeric characters (because it's type=number). Notice you can input e character - it's because e is a valid number.
Try to use input type tel with pattern attribute, e.x.:
<input id='phone-num' type='tel' pattern="[0-9\-]+">


text: Q: Gap at the right sideof the page after using user-scalable in mobile I have used meta tag as <meta name="viewport" content="initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi"/> after using this the page showing white space on right side. Is there any solution for this?


text:
Q: How to set up an autoupdated blacklist for Dansguardian? I'm having issues setting up Dansguardian on my computer with Ubuntu 13.10. I'm trying to follow the steps in the Ubuntu Community Documentation for Dansguardian: https://help.ubuntu.com/community/DansGuardian
I installed the programs it specified via terminal command with no errors. Then I downloaded the blacklists from http://urlblacklist.com/?sec=download and extracted the files.
The next step is to run:
tar -xzf bigblacklist.tar.gz

I tried running that command, but get this response:
john-hill@johnhill-desktop:~$ tar -xzf bigblacklist.tar.gz
tar (child): bigblacklist.tar.gz: Cannot open: No such file or directory
tar (child): Error is not recoverable: exiting now
tar: Child returned status 2
tar: Error is not recoverable: exiting now
john-hill@johnhill-desktop:~$

Any ideas? Or is there a better way to set up the blacklists? Any help is appreciated.

A: Run the below commands on terminal,
cd /path/to/the/directory/which/contains/bigblacklist.tar.gz
tar -xzf bigblacklist.tar.gz

A: I think that you better off executing this script:
curl -L http://urlblacklist.com/downloads/UpdateBL | sudo sh


text:
Q: Prove that $\mathscr{F} = \sigma(\{f_\lambda^{-1}(B):\;\lambda \in \Lambda,\;B \in \mathscr{F}'\})$. Let $\Omega$ be a set, $(\Omega',\mathscr{F}')$ a measurable space, and
$$f_\lambda: \Omega \to \Omega',\quad \lambda \in \Lambda$$
functions indexed by an arbitrary set $\Lambda$. Let $\mathscr{F}$ be the intersection of all $\sigma$-algebras $\mathscr{D}$ of $\Omega$ such that $f_\lambda: (\Omega, \mathscr{D}) \to (\Omega',\mathscr{F}')$ is measurable for every $\lambda \in \Lambda$.Prove that
$\mathscr{F} = \sigma(\{f_\lambda^{-1}(B):\;\lambda \in \Lambda,\;B \in \mathscr{F}'\})$.
I believe I understand what is stated here. Could you give me any tips to start proving this?

A: Since $f_\lambda ^{-1}(B)\in \mathscr F$ for all $\lambda $ and all $B\in \mathscr F'$, $$\sigma \{f_\lambda ^{-1}(B)\mid \lambda \in \Lambda , B\in \mathscr F'\}\subset \mathscr F.$$
The other inclusion is by definition of $\mathscr F$.


text:
Q: Restrict records returned by view with group by rollup whilst modifying totals I need to create a view that has an average for some columns. This view will be accessed by month and year and I would like to create it as global (full table scan) and later use with different condition such as: Month 05 Year 2015 / Month 04 Year 2015
Right now I have created it like this:
create or replace view view_x_tipology as
select dt_ref, gg_ref, mm_ref, yyyy_ref, avg(pcr_qt) pcr_tot, avg(ltr_qt) ltr_tot, avg(tbr_qt) tbr_tot, avg(qt_total) day_total
  from stock_base
 group by rollup (dt_ref, gg_ref, mm_ref, yyyy_ref)

My main problem is that the grand total (I don't need sub totals) has only the three total with a value, and all the other fields is null
DT_REF      GG_REF MM_REF  YYYY_REF   PCR_TOT     LTR_TOT     TBR_TOT     TOT
28/05/2015  28     5       2015       118654      9433        19729       147816
28/05/2015  28     5                  118654      9433        19729       147816
28/05/2015  28                        118654      9433        19729       147816
28/05/2015                            118654      9433        19729       147816
29/05/2015  29     5       2015       132132      10022       19687       161841
29/05/2015  29     5                  132132      10022       19687       161841
29/05/2015  29                        132132      10022       19687       161841
29/05/2015                            132132      10022       19687       161841
                                      125393      9727,5      19708       154828,5

For example, I would like to query view_x_tipology in this way:
select *
  from view_per_tipology
 where mm_ref = 5
  and yyyy_ref = 2015

With this query, I need all days in 05/2015 with the last line with the average
UPDATE
As Ben said, i cant create a view with rollup that do this, i've used a simple union to calculate the average. Sure, this only work for months and year.
select dt_ref, gg_ref, mm_ref, yyyy_ref, pcr_qt, ltr_qt, tbr_qt, qt_total
  from stock_base
union
select null, null, mm_ref, yyyy_ref, avg(pcr_qt), avg(ltr_qt), avg(tbr_qt), avg(qt_total)
      from stock_base
     group by rollup (dt_ref, gg_ref, mm_ref, yyyy_ref)

The field qt_* on stock_base have already the sum of the day/month/year.
In union, i simply use AVG function to create the average.

A: The simple answer is that you can't... you're attempting to query data that doesn't exist. If you try to work around this by doing something like the following the total will still apply to your entire, original, result-set.
select *
  from view_per_tipology
 where ( mm_ref = 5 and yyyy_ref = 2015 )
    or dt_ref is null

You're going to have to write the query out each time. Alternatively, if you always want the current month, you can restrict your view to only contain this data.


text:
Q: URL Serialization Performance Issue in Sorl-Thumbnail I'm having a bit of a difficult time with performance using sorl-thumbnail. I'm hosting images on S3 with the S3Boto3Storage storage backend, I'm using Redis as my Key-Value Store and all queries have been cached inside it already. I'm using the following dependencies:
boto3==1.17.103
botocore==1.20.105
Django==3.2.4
django-redis==4.10.0
django-storages==1.11.1
redis==3.3.11
sorl-thumbnail==12.7.0

Now I run & time the following script:
from sorl.thumbnail import get_thumbnail

images = Image.objects.all()  # 7 images
for image in images:
    x = image.file
    y = x.url                                           # 1
    x = get_thumbnail(x, '800x600', crop='center')      # 2
    x = x.url                                           # 3

*

*Step 1: When I comment out #2 & #3, the script takes 0.193s

*Step 2: When I comment out #1 & #3, the script takes 0.0153s

*Step 3: When I comment out #1, the script takes 0.669s (!)

The odd thing is that when I debug the 3rd step, x seems to already have the attribute "url", so I don't know why it is taking so long to access it.
The connection to Redis is working and the query towards it is already activated in the 2nd step. Like I said earlier, the thumbnails have already been generated, the lookups are cached in Redis, so it is (I believe) unrelated to S3 thumbnail generation issues.
In production I have frequent queries for around 50 images at once... that amounts to more than 4s of url serialisation... Would appreciate any help! :)

A: Okay, figured out what was wrong. I had set AWS_S3_CUSTOM_DOMAIN in settings, but had accidentally overwritten it in my storage class:
from storages.backends.s3boto3 import S3Boto3Storage

class DefaultFileStorage(S3Boto3Storage):
     location = settings.AWS_DEFAULT_FILES
     file_overwrite = False
     custom_domain = False  # <-- Bottleneck!

After removing custom_domain = False, performance went up by 10x (literally).


text:
Q: How is .google a domain extension? I just visited blog.google. How does that work? Can organisations register their own domain extensions? If yes, what is the procedure and how expensive is that? If not, how did they achieve the blog domain then? Is there some networking trick to this that I am missing?

A: You can request a generic top level domain (gTLD) from ICANN, it's quite costly, so only really large organisations have the cash to splurge on them for purely window dressing (there's no real technical benefit except maybe not relying on anybody to handle the TLD above your domain, but you're still reliant on the root zone). Others buy them to start selling domains under that gTLD, for example .cloud or .expert.
Country code top level domains (ccTLD) are another thing entirely, they are restricted to countries with an ISO 3166 code (with some exceptions).
Further reading: https://en.wikipedia.org/wiki/Top-level_domain


text:
Q: Excluding NoData zones in zonal statistics as table in ArcGIS Pro I'm trying to calculate mean values of a raster within buffer zones. In the zonal statistics as table tool window, I unchecked 'Ignore NoData in Calculations' so that there is no mean calculated for zones which contain no data. It worked first with small 100m buffer zones. But this doesn't work with larger 500m buffer zones. The result still contains almost all buffers even if they contain no data cells from the raster.
Any idea why this happens?
The raster is 30m resolution.


text:
Q: granting Sp_helptext not working Whenever I run
Grant Execute on sp_helptext to USER

I get an error :

Msg 15151, Level 16, State 1, Line 1
  Cannot find the USER, because it does not exist or you do not have permission.

I am logged in as SA using master, so I tried using testing DB and it tells me to use master.
How do I create a server login, corresponding to two databases that have the ability to SELECT and do SP_Helptext. I am able to to do it in production DB just fine but whenever I restore to TESTING nothing I've tried works.

A: The syntax is perfect, but this shows that your user is not mapped with master table. What is your username to grant, Is it "USER"? change with other user to test.

By default users were able to see object definitions in SQL Server
  2000, but in SQL Server 2005 this functionality was removed to allow
  another layer of security.  By using a new feature called VIEW
  DEFINITION it is possible to allow users that only have public access
  the ability to see object definitions.
To turn on this feature across the board for all databases and all
  users you can issue the following statement:

USE master
GO
GRANT VIEW ANY DEFINITION TO PUBLIC (refer the last link)

Check this link.
Cannot find the user '', because it does not exist or you do not have permission
https://dba.stackexchange.com/questions/29969/cant-grant-role-permissions-under-sysadmin-login
http://www.mssqltips.com/sqlservertip/1593/granting-view-definition-permission-to-a-user-or-role-in-sql-server/


text:
Q: VBA: How to run another application from MS Access I've been trying to get this issue figured out, and it seems that I cannot find the solution to the problem anywhere. Here was the first part: VBA Shell command always returns "File Not Found" In that question, it wasn't finding the application in the %APPDATA% folder for some odd reason, likely a security setting.
I have since moved the import tool to the same directory that I store the database in, with the small hope of getting it to work correctly.
My objective is to click a button in MS Access and have it run my import tool directly. Right now, I have it opening the folder that holds the tool. This works on my development machine which has admin privileges, but does not work on other machines without admin privs. The code right now looks something like the following:
Dim hProcess as Long
Dim myPath as String
Dim ex as String

ex = "C:\WINDOWS\explorer.exe "
myPath = Environ("ProgramFiles(x86)") & "\mytool\"

hProcess = Shell(ex & myPath, vbNormalFocus)

This allows the folder that holds the file to be opened, but only on machine accounts which have full administrator privileges. When running this on a machine account that has less than full privileges, it simply does nothing.
I have also tried the following:
Dim hProcess As Long
Dim myPath as String

myPath = Environ("ProgramFiles(x86)") & "\mytool\mytool.exe"
hProcess = Shell(myPath, vbNormalFocus)

This section "seems" to work in that it loads the application "mytool.exe" when I look at the process manager. However, after a few seconds (maybe 20), a dialog pops up stating that the application "mytool.exe" has stopped working.
One thing to note here is that I have admin privileges on my development machine, but I have all privileges on my home machine. On my home machine, this second code works with no issue whatsoever. At my development machine, it crashes, while on a restricted user machine, it doesn't do anything at all.
Are there any suggestions on how to open this application from MS Access while using less-than-admin privileges? Either to run the application directly or to at least open the folder in which said application resides.
Thanks!
P.S. I have tried both ShellAndWait and RunApplication code found on stackoverflow, neither of which works in this instance.

A: I always use ShellExecute from the Windows API when I need to execute something in VBA.
As far as I know, it works on machines without full privileges as well.
Example:
Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" (ByVal hwnd As Long, _
    ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, _
    ByVal lpDirectory As String, ByVal lpnShowCmd As Long) As Long

Public Sub ShellEx(ByVal Path As String, Optional ByVal Parameters As String, Optional ByVal HideWindow As Boolean)

    If Dir(Path) > "" Then
        ShellExecute 0, "open", Path, Parameters, "", IIf(HideWindow, 0, 1)
    End If

End Sub

Now you can call ShellEx to run pretty much anything:
'run executable
ShellEx "c:\mytool.exe"

'open file with default app
ShellEx "c:\someimage.jpg"

'open explorer window
ShellEx "c:\"

Note that ShellEx has two optional parameters as well.
I didn't show this in the above examples, but you can:

*

*pass parameters to executables

*hide the window of the called executable

A: follow this link
MS ACCESS: LAUNCH AN APPLICATION FROM ACCESS 2003/XP/2000/97
here is an example of running an application in ms access
Private Sub Command1_Click()
Dim myPath As String
myPath = "C:\Program Files\mytool\mytool.exe"
Call Shell(myPath , 1)
End Sub

i wish it helps you

A: Just messing about with http://www.mombu.com/microsoft/scripting-wsh/t-vista-uac-problem-with-wscriptshell-run-method-1508617.html. I tried this on Windows 7 home PC.
Set objShell = CreateObject("Shell.Application")
myPath = Environ("ProgramFiles(x86)") & "\mytool"
Set objFolder = objShell.Namespace(myPath)
Set objFolderItem = objFolder.ParseName("mytool.exe")
objFolderItem.InvokeVerb "runas"

It might give you some ideas.

A: Check
Shell szFileName, vbNormalFocus

with some other executable. It can be some problem with your tool.


text:
Q: How .NET overrides non-virtual method in .NET Remoting? Consider following piece of code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RemotingNonVirtualCall
{
    class Program
    {
        static void Main(string[] args)
        {
             var domain = AppDomain.CreateDomain("Second Domain");
            A extA = (A)domain.CreateInstanceAndUnwrap(typeof(A).Assembly.FullName, typeof(A).FullName);
            Console.WriteLine(extA.CurrentDomain());
        }
    }

    [Serializable]
    sealed class A : MarshalByRefObject
    {
        public string CurrentDomain()
        {
            return AppDomain.CurrentDomain.FriendlyName;
        }
    }
}

Method A::CurrentDomain is non-virtual, class A is sealed. But CLR intercepts method call and redirect it to another instance. How it is possible? Is it some sort of voodoo magic? Does CLR make some exception in method calling for object inherited from MarshalByRefObject class? How is it performed?
Thanks for advance.

A: It's essentially magic, i.e. the ability to do this is built into the .NET runtime. The good news is that your code can also do this, if it needs to: http://msdn.microsoft.com/en-us/library/system.runtime.remoting.proxies.realproxy.aspx

A: The JIT compiler is keenly aware that it generates code for a proxy.  You can have a look-see with the SSCLI20 source code, clr\src\vm\jithelpers.cpp, search for "proxy".


text:
Q: Haskell: Template Haskell and the scope This code is compiled fine:
data None = None { _f :: Int }
type Simpl = Env

type Env = Int

However, I got an error with this code:
{-# LANGUAGE TemplateHaskell #-}
import Control.Lens

data None = None { _f :: Int }

type Simpl = Env

makeLenses ''None

type Env = Int

Error:
Not in scope: type constructor or class `Env'

I just added a single line makeLenses ''None between type declarations.
This means TemplateHaskell code could change the scope of type constructor?
Does anyone know the detail about this issue(or how to avoid this problem)?

A: If you reorder your code as follows, it works:
{-# LANGUAGE TemplateHaskell #-}
import Control.Lens

data None = None { _f :: Int }

type Simpl = Env

type Env = Int

makeLenses ''None

When you use Template Haskell splices to add new top-level declarations to your code, as makeLenses does, the order of declarations in your code suddenly matters!
The reason is that normally compiling a Haskell program involves first collecting all the top-level declarations and reordering them internally to put them in dependency order, and then compiling them one by one (or group by group for mutually recursive declarations).
With new declarations being introduced by running arbitrary code, because GHC doesn't know which declarations makeLenses might need to run, and also it doesn't know which new declarations it will produce. So it can't put the whole file in dependency order and just sort of gives up and expects the user to do it themselves, at least for deciding whether declarations should go before or after the splice.
The only online reference I can find that explains this is in the original Template Haskell paper, section 7.2, where it says that the algorithm is:

*

*Group the declarations as follows:

[d1,...,da]
splice ea
[da+2,...,db]
splice eb
...
splice ez
[dz+2,...,dN]

where the only splice declarations are the ones indicated explicitly, so that each group [d1,...,da], etc, are all ordinary Haskell declarations.

*

*Perform conventional dependency analysis, followed by type checking, on the first group. All its free variables should be in scope.

So the problem here is that the first group of declarations before the splice is being handled separately to the second group after the splice, and it can't see the definition of Env.
My general rule of thumb is to put splices like this at the bottom of the file if possible, but I don't think it's guaranteed that this will always work.


text:
Q: Progress Circles Not Aligned With Label The below code creates a progress circle with number in the middle.
I need each circle to have a label under it, but can't put it in either a span or div without disrupting the CSS circle; I ussed tables but I want it to look okay on mobile devices.
Any suggestions would be great.

body {
  font-family: 'Montserrat';
}

h1 {
  color: #63B8FF;
  text-align: center;
}

.progress-circle {
  position: relative;
  display: inline-block;
  margin: 1rem;
  width: 120px;
  height: 120px;
  border-radius: 50%;
  background-color: #ebebeb;
}

.progress-circle:after {
  content: '';
  display: inline-block;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  -webkit-animation: colorload 2s;
  animation: colorload 2s;
}

.progress-circle span {
  font-size: 1rem;
  color: #8b8b8b;
  position: absolute;
  left: 50%;
  top: 50%;
  display: block;
  width: 60px;
  height: 60px;
  line-height: 60px;
  margin-left: -30px;
  margin-top: -30px;
  text-align: center;
  border-radius: 50%;
  background: #fff;
  z-index: 1;
}

.progress-circle span:after {
  font-weight: 600;
  color: #8b8b8b;
}

.progress-circle.progress-45:after {
  background-image: linear-gradient(90deg, #ebebeb 50%, transparent 50%, transparent), linear-gradient(90deg, #b4b5aa 50%, #ebebeb 50%, #ebebeb);
}

}
@-webkit-keyframes colorload {
  0% {
    opacity: 0;
    transform: rotate(0deg);
  }

  100% {
    opacity: 1;
    transform: rotate(360deg);
  }
}

333

TAG A

4444

TAG b

555

TAG C

I have tried to use tables but does not look great on mobile device.

A: Checked the code, seems like the label under it doesn't ruin the circle, even if you use
 or . here is something you could do:
Use a container to control the behavior of the circles and the labels:

333

Tag A

4444

TAG b

555

TAG C

This way, you can control how the circle and the label behave in the webpage, you can give the class progressContainer a text-align: center; to make all of the code inside the class be centered (without using  which is bad practice), if you need to make them all align left, just change it from center to left.
I hope i understood your question correctly.


text:
Q: Can the type of USB 3.0 data cable slow down the transfer speed? I have a hard drive that needs USB 3.0 cable to transfer things from my computer. It usually takes 10 mins to transfer few movies.
Recently, my cable broke so I bought a new, longer USB 3.0 cable and now it takes 2 hours to transfer things from my computer to my hard drive. Why is that and how do i fix this?

A: Yes, a cable could cause poor performance. And especially if it's a cheap cable, which may not really meet the USB 3 electrical specification.
The other possible reason is that you may have used a different USB port on your computer from what you were using previously, when you were getting 10-minute transfer times. It's quite common for computers to have just one or two USB 3 ports, and a number of USB 2 ports also. If you've used one of the USB 2 ports, that would certainly slow things down also.


text:
Q: MySql case-sensitive with utf 8 format set system variables I have been trying to get my result as per the case-sensitive condition case.

I need to set it in this way only since I am using migration wizard to import data from postgres and there is some problem with case-sensitivity. I want mysql to insert data while importing in case-sensitive way.
if there is some other way to overcome problem then please help. utf8_bin is not working.


text:
Q: What are some popular distance measuring techniques between images? In machine learning, a lot of techniques require defining a metric between different data points. I want to know what are some popular metrics when the data are images.
An obvious way of measuring distance between images is to sum up the squares of pixel errors. But this is sensitive to simple transformations like translation. For example, even shifting the whole image by one pixel could result in a large distance.
What are some other distance measuring techniques that is more compatible with translation, rotations, etc.?

A: Wasserstein distance(earth mover's distance) and kullback leibler divergence are the two that I have come across while studying literature about Generative Adversarial Networks(GANs).


text:
Q: Simple Javascript function is not working on .ascx file I am trying to make a simple javascript function work in the .ascx file in my asp.net and vb.net application.   I have included the following html code inside the asp panel tag.

                     <asp:CheckBox ID="tick" runat="server" Text="Please tick the box to confirm the above information are correct" Checked="false" CssClass="small" onchange="EnableSubmit()" />

and the following javascript code  in the .ascx file

to understand the problem better that I am talking about and to  see my page live please go to the following link.
http://t.c.mypeoplebiz.com/sagepay-careers/2935-commercial-litigator-solicitor-1-3-years-pqe.aspx
and click apply now button.
A popup will appear. please give a email address to register. (don't worry. it does not have to be a original email address. just abc@xyz.com is fine).
When you upload a document then you can see the form.The check box is at the bottom of the page.

A: In your browser, right click the page, click view source (or however you do it for your browser). Notice that the ID's have changed? That makes it not find your elements to enable them.

One solution is to embed the client ID into your script with an inline server side expression. Another is to change the ClientIDMode. Setting the ClientIdMode to static will make the client side use the same ID on the client and server, avoiding the need for an inline expression.

A: ASP.NET mangles the IDs on anything set to runat="server".  You'll need to ask it for the actual id of that control.  As in:
function EnableSubmit() {

    var id = "<%= tick.ClientID %>";
    if (document.getElementById(id).checked == true) {

        ...
    }

}


text:
Q: TortoiseGit log not showing all expected commit messages in some environments Last week, I merged two git repositories into one, new repository following the steps outlined in this blog. To the best of my knowledge this all went smoothly. All files exist. I am able to find all commits by their SHA.
Now, I am inspecting the log history for a single file using TortoiseGit. I have "follow renames" enabled. When I view the history I do not see any commit messages for any of the branches I transitioned to the new repository, but I do see all commit messages for older branches:

When I run gitk --follow User.cs I am able to see the commit messages as expected:

Steps I've taken to try and solve:

*

*Update Git to latest: 2.10.2.windows.1

*Reinstall TortoiseGit. It was already the latest version: 2.3.0

*Delete the repository and pull it again.

*Went to TortoiseGit -> Settings -> Saved Data and cleared all.

*Looked for bug report on TortoiseGit Gitlab issue tracker. I did not find anything.

This issue occurs on two of my machines. Both machines were used when merging the two repositories. None of my coworkers experience this issue. They did not use their PCs to assist in merging the repositories.
Question: Is anyone aware of any other caches, settings, or other configuration options I should consider to repair my TortoiseGit instances?
For reference, the steps outlined in the blog are:
# Assume the current directory is where we want the new repository to be created
# Create the new repository
git init

# Before we do a merge, we have to have an initial commit, so we'll make a dummy commit
dir > deleteme.txt
git add .
git commit -m "Initial dummy commit"

# Add a remote for and fetch the old repo
git remote add -f old_a <OldA repo URL>

# Merge the files from old_a/master into new/master
git merge old_a/master

# Clean up our dummy file because we don't need it any more
git rm .\deleteme.txt
git commit -m "Clean up initial file"

# Move the old_a repo files and folders into a subdirectory so they don't collide with the other repo coming later
mkdir old_a
dir –exclude old_a | %{git mv $_.Name old_a}

# Commit the move
git commit -m "Move old_a files into subdir"

# Do the same thing for old_b
git remote add -f old_b <OldB repo URL>
git merge old_b/master
mkdir old_b
dir –exclude old_a,old_b | %{git mv $_.Name old_b}
git commit -m "Move old_b files into subdir"

##########################

# Bring over a feature branch from one of the old repos
git checkout -b feature-in-progress
git merge -s recursive -Xsubtree=old_a old_a/feature-in-progress

A: Please try to select All Branches above the refresh button (left-bottom) from the first picture what you shared. And you will find all the branches and commit histories.


text:
Q: Unable to connect remote server in c# and object reference not set to an instance of object while sending sms on mobile I am trying to send sms from c# windows application on mobile users. while
using this code the following error shows:

1) Unable to connect remote server
2) Object reference is not set to an instance object

try{
        String result;
        string userName = "abc@gmail.com";
        string hash = "hashkey";
        string numbers = "911234567890"; // in a comma seperated list
        string message = "This is your message";
        string sendermo = "TXTLCL";

        String url = "http://api.textlocal.in/send/?username=" + userName + "&hash=" + hash + "&numbers=" + numbers + "&message=" + message + "&sender=" + sendermo;
        //refer to parameters to complete correct url string

        StreamWriter myWriter = null;
        HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);

        objRequest.Method = "POST";
        objRequest.ContentLength = Encoding.UTF8.GetByteCount(url);
        objRequest.ContentType = "application/x-www-form-urlencoded";
        try
        {
            myWriter = new StreamWriter(objRequest.GetRequestStream());
            myWriter.Write(url);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            myWriter.Close();
        }

        HttpWebResponse objResponse = HttpWebResponse)objRequest.GetResponse();

        using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
        {
            result = sr.ReadToEnd();
            // Close and clean up the StreamReader
            sr.Close();
        }
             MessageBox.Show(" "+result);
        }
            catch (Exception ec)
        {
        MessageBox.Show(ec.Message);
    }
}


text:
Q: Is there a pattern for implementing a static variable in Go? I am having a brain freeze
I am trying to write a logging package to work with our enterprise logging system.
I want to create the logger and it associated data at the beginning and reuse it throughout the service lifetime.
something like this (pseudo code) at the entry point of the service
log := LogManager.CreateLogger("mylog", "DEBUG")

use the following code in the rest of the service and imported packages
log := LogManager.GetLogger()

log would be the same instance - the one instantiated at the beginning.
Thanks
G

A: A package-level variable that is initialized via init() should work for your use case.


text:
Q: In Java is there any way to share memory location to exchange some real-time small packets? Is there any better/smarter way to put and get a boolean value from memory system, but not using any TCP/UDP nor local file system method?
For example:

#both running as 1 application separately

$ java -cp /var/tmp/J.jar System.Backend

$ java -cp /var/tmp/J.jar System.Frontend

Where Backend does memory allocation, and Frontend reads it on the fly, none of them will be able to use TCP/UDP nor File system.

A: AFAIK, The only way to use shared memory in pure Java is to use memory mapped files.
If you want two pieces of code to share memory, the simplest thing to do is to use one JVM. There is rarely a good reason to use more than one JVM with tightly couple code.

A: If you can make one application to launch another via Process API, then they can communicate over standard input an output.


text:
Q: Refactoring! How to Re-Use a Variable in Database Query to retrieve data in Rails controller I am trying to refactor the code in my rails API which sends analytics data for charts (it is currently working). As I have the same code carried out on 1. Bookmarks, 2. Journals, 3. Goals and it isn't very dry.
I am trying to create 1 database query (using PostgreSQL) that can receive the type (bookmark, goal, journal) as a parameter... I have tried using [:type] and hard coding "type" where bookmark used to go for example...
Existing (working) code that I want to refactor:
class AnalyticsController < ApplicationController
  before_action :authenticate_user

  def entries_by_date
    bookmarks = current_user.bookmarks.group_by_day(
      :created_at,
      format: '%Y-%m-%d',
      range: 4.weeks.ago.midnight..Time.zone.now
    ).count
    journals = current_user.journals.group_by_day(
      :created_at,
      format: '%Y-%m-%d',
      range: 4.weeks.ago.midnight..Time.zone.now
    ).count
    goals = current_user.goals.group_by_day(
      :created_at,
      format: '%Y-%m-%d',
      range: 4.weeks.ago.midnight..Time.zone.now
    ).count

    entries_array = []
    entries_array.push(@bookmarks)
    entries_array.push(goals)
    entries_array.push(journals)

    total_entries_by_date = entries_array.inject { |memo, el| memo.merge(el) { |_k, old_v, new_v| old_v + new_v } }

    render json: {
      total_entries_by_date: total_entries_by_date,
      bookmarks: bookmarks,
      goals: goals,
      journals: journals
    }
  end
end

I have tried this:
....

  def entries_by_date
    def fetch_activity(type)
      current_user[:type].group_by_day(
        :created_at,
        format: '%Y-%m-%d',
        range: 4.weeks.ago.midnight..Time.zone.now
      ).count
    end

    @bookmarks = fetch_activity(bookmarks)
    @goals = fetch_activity(goals)
    @journals = fetch_activity(journals)

... (cont'd)

I have tried current_user.type... >> undefined local variable or method `bookmarks
I have tried current_user.[:type]... >> "Syntax error, unknown ["
I have tried current_user[:type]... >> NameError (undefined local variable or method `bookmarks'
I have tried current_user.%{type}... &  current_user.#{type}... &  current_user.${type}
Any guidance would be much appreciated :) I'm fairly new to the Ruby on Rails world and looking forward to seeing my code a little drier once I have a better understanding of how to re-use the variables being passed into a database query

A: To improve a bit on Spickerman's answer - you should consider extracting the buisness logic from the controller and place it in the model where it belongs:
class User < ApplicationRecord
  # Gets a single activity
  def fetch_activity(type)
    public_send(type).group_by_day(
      :created_at,
      format: '%Y-%m-%d',
      range: 4.weeks.ago.midnight..Time.zone.now
    ).count
  end

  # Gets a hash containing the counts of the users activities and total
  def fetch_activities(*types)
    types.each_with_object({}) do |key, hash|
      hash[key] = fetch_activity(key)
    end.then do |hash|
      hash.merge(total_entries_by_date: hash.values.sum)
    end
  end
  # ...
end

Models are much easier to test than controllers since you can just set it up and call the method right on the object instead of going though HTTP and parsing the response - which is a key reason why your controllers should be as skinny as possible:
class AnalyticsController < ApplicationController
  before_action :authenticate_user

  def entries_by_date
    render json: current_user.fetch_activities(:bookmarks, :goals, :journals)
  end
end

A: You were pretty close to the solution. Just use public_send and pass the name of the method you want to call as a string or symbol.
def entries_by_date
  @bookmarks = fetch_activity(:bookmarks)
  @goals = fetch_activity(:goals)
  @journals = fetch_activity(:journals)

  # ...
end

private

def fetch_activity(type)
  current_user.public_send(type).group_by_day(
    :created_at,
    format: '%Y-%m-%d',
    range: 4.weeks.ago.midnight..Time.zone.now
  ).count
end

@bookmarks = fetch_activity(bookmarks)
@goals = fetch_activity(goals)
@journals = fetch_activity(journals)


text:
Q: Product admin edit issue in magento 2 I am getting below error in console, when i try to edit product in admin
 Uncaught TypeError: data.some is not a function

Referred below link and used that didn't solve my issue.
Uncaught TypeError: data.some is not a function
Can anyone help me on this please?


text:
Q: KeyError: 'use_threading' not letting me runserver I'm new to coding in Python so bear with my errors. I keep encountering this error even when I haven't added anything into the code yet.
Watching for file changes with StatReloader
Exception in thread django-main-thread:
Traceback (most recent call last):
  File "C:\Users\[Name]\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner
    self.run()
  File "C:\Users\[Name]\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run
    self._target(self._args, self._kwargs)
  File "C:\Users\[Name]\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\[Name]\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\commands\runserver.py", line 127, in inner_run
    threading = options["use_threading"]
KeyError: 'use_threading'

Note: I did migrations and makemigrations just in case but I still get the same error.


text:
Q: Switching hard drives I have Windows 7 installed on a 640 GB hard drive, and Ubuntu on a 2TB. I have leaned towards storing all music, pictures, movies, etc. on Windows, and have low storage space. I was wondering if it was at all possible to swap the disks (putting Windows on the 2TB, and Ubuntu on the 640GB) without using a 3rd hard drive for transfer.
Edit: Output of df -h
udev            3.9G     0  3.9G   0% /dev
tmpfs           785M  9.5M  775M   2% /run
/dev/sdc2        47G  7.8G   37G  18% /
tmpfs           3.9G   30M  3.8G   1% /dev/shm
tmpfs           5.0M  4.0K  5.0M   1% /run/lock
tmpfs           3.9G     0  3.9G   0% /sys/fs/cgroup
/dev/sda1       1.4T   36G  1.3T   3% /home
/dev/sdc1       511M   22M  490M   5% /boot/efi
/dev/sda2       1.4T   70M  1.4T   1% /scratch
cgmfs           100K     0  100K   0% /run/cgmanager/fs
tmpfs           785M   60K  784M   1% /run/user/1000
/dev/sdd1       7.6G  1.1G  6.6G  15% /media/david/8615-2D9A
/dev/sr0        703M  703M     0 100% /media/david/UDF Volume

Output of sudo fdisk -l:
Disk /dev/sdb: 596.2 GiB, 640135028736 bytes, 1250263728 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: gpt
Disk identifier: 37AA04C9-275A-43E5-BFE2-4355CFC935DC

Device     Start        End    Sectors   Size Type
/dev/sdb1   2048 1250263039 1250260992 596.2G Microsoft basic data

Disk /dev/sda: 2.7 TiB, 3000592982016 bytes, 5860533168 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disklabel type: gpt
Disk identifier: 0CCD5B1E-CFED-4DEC-8416-B44E0CDFCFEA

Device          Start        End    Sectors  Size Type
/dev/sda1        2048 2867201266 2867199219  1.3T Linux filesystem
/dev/sda2  2867202048 5860532223 2993330176  1.4T Linux filesystem

Disk /dev/sdc: 55.9 GiB, 60022480896 bytes, 117231408 sectors

Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: gpt
Disk identifier: 41756814-F17E-4683-923A-2459F60FB188

Device         Start       End  Sectors  Size Type
/dev/sdc1       2048   1050623  1048576  512M EFI System
/dev/sdc2    1050624 100749311 99698688 47.6G Linux filesystem
/dev/sdc3  100749312 117229567 16480256  7.9G Linux swap

Disk /dev/sdd: 7.6 GiB, 8166703104 bytes, 15950592 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0xc3e0984f

Device     Boot Start      End  Sectors  Size Id Type
/dev/sdd1  *    11640 15950591 15938952  7.6G  c W95 FAT32 (LBA)

A: Could you give the output of df -h ?
I think it is possible if you have enough space available in the big disk to copy all the ubuntu filesystem using dd to it. Then you will have to manually modify the grub.
Thanks it seems to me that you have your /home in the big disk, and
the root / in the small one.
the output of sudo fdisk -l will be helpful to clarify.
Possibly 3 physical disks in sdb(all windows) sda(home and scratch) and sdc(EFI and linux fs).
To be sure please do lsblk -io KNAME,TYPE,SIZE,MOUNTPOINT
you can use the partition sda2 scratch to host your windows.


text:
Q: What is the best practice for recording a run number into a Postgres database through a Python connection? Every few days I have to load around 50 rows of data into a Postgres 14 database through a Python script. As part of this I want to record a run number as a column in the db. This number should be the same for all rows I am inserting at that time and larger than any number currently in that column in the database, but other than that its actual value doesn't matter (ie, I need to make the number myself, I'm not just pulling it in from somewhere else).
The obvious way to do this would be with two calls from Python to the database - one to get the current max run number and one to save the data with the run number set to one more than the number retrieved in the first query. Is this best practice? Is there a better way to do this with only one call? Would people recommend making a function in postgres that does this instead and then call that function? I feel like this is likely a common situation with accepted best practice but I don't know what it is.


text:
Q: Nativescript: Delegate Extending NSObject throws Error: This value is not a native object I'm trying to create a scroll-event delegate for ListView on iOS, based on the code example here: https://github.com/NativeScript/NativeScript/issues/2521#issuecomment-306447460
(The Android implementation works like a champ. iOS crashes in epic fashion)
A fatal error is thrown while executing the new function.
Delegate
class ScrollingUITableViewDelegateImpl extends NSObject implements UITableViewDelegate {

    private _originalDelegate: UITableViewDelegate;

    static ObjCProtocols = [UITableViewDelegate];

    static new():ScrollingUITableViewDelegateImpl {
      return <ScrollingUITableViewDelegateImpl>super.new();
    }

    static initWithOrigDelegate(original: UITableViewDelegate): ScrollingUITableViewDelegateImpl {
        const delegate = <ScrollingUITableViewDelegateImpl>ScrollingUITableViewDelegateImpl.new();
        delegate._originalDelegate = original;
        return delegate;
    }

    /* OriginalDelegate items */
    public tableViewWillDisplayCellForRowAtIndexPath(tableView: UITableView, cell: UITableViewCell, indexPath: NSIndexPath) {
      return this._originalDelegate.tableViewWillDisplayCellForRowAtIndexPath(tableView, cell, indexPath)
    }
    public tableViewWillSelectRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): NSIndexPath {
      return this._originalDelegate.tableViewWillSelectRowAtIndexPath(tableView, indexPath);
    }
    public tableViewDidSelectRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): NSIndexPath {
      tableView.deselectRowAtIndexPathAnimated(indexPath, true);
      return indexPath;
    }
    public tableViewHeightForRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): number {
      return this._originalDelegate.tableViewHeightForRowAtIndexPath(tableView, indexPath);
    }

    /* Scroll Delegate items */
    public scrollViewWillBeginDragging(scrollView:UIScrollView) {
        console.log('willbegindragging');
    }
    public scrollViewDidScroll(scrollView:UIScrollView) {
        console.log('didscroll');
    }
}

Error
***** Fatal JavaScript exception - application has been terminated. *****
Native stack trace:
1   0x100aa373c
NativeScript::reportFatalErrorBeforeShutdown(JSC::ExecState*, JSC::Exception*, bool, bool)
2   0x100ac92e4 NativeScript::FFICallback<NativeScript::ObjCMethodCallback>::ffiClosureCallback(ffi_cif*, void*, void**, void*)
3   0x1013cb088 ffi_closure_SYSV_inner
4   0x1013cc1b4 .Ldo_closure
5   0x1b211ea60 <redacted>
6   0x1b211f144 <redacted>
7   0x1b20860e8 <redacted>
8   0x1b2086da8 <redacted>
9   0x1b20880a8 <redacted>
10  0x1b206a298 <redacted>
11  0x1b2b7ff44 <redacted>
12  0x18a13da34 <redacted>
13  0x18a1429c4 <redacted>
14  0x18a0a19d4 <redacted>
15  0x18a0d02f4 <redacted>
16  0x1b26f736c <redacted>
17  0x185aea408 <redacted>
18  0x185ae9d08 <redacted>
19  0x185ae4cfc <redacted>
20  0x185ae45b8 CFRunLoopRunSpecific
21  0x187d58584 GSEventRunModal
22  0x1b26dcbc8 UIApplicationMain
23  0x1013cc044 ffi_call_SYSV
24  0x1013ca7a4 ffi_call_int
25  0x1013ca26c ffi_call
26  0x100a81630 NativeScript::FFICall::call(JSC::ExecState*)
27  0x10107ce14 JSC::LLInt::setUpCall(JSC::ExecState*, JSC::Instruction*, JSC::CodeSpecializationKind, JSC::JSValue, JSC::LLIntCallLinkInfo*)
28  0x101085a24 llint_entry
29  0x101085a34 llint_entry
30  0x101085a34 llint_entry
31  0x10107eee0 vmEntryToJavaScript
JavaScript stack trace:
1   new@file:///app/components/scroll-list-view/scroll-list-view.js:10:25
2   new@file:///app/components/scroll-list-view/scroll-list-view.js:10:25
3   initWithOrigDelegate@file:///app/components/scroll-list-view/scroll-list-view.js:13:59
4   initNativeView@file:///app/components/scroll-list-view/scroll-list-view.js:46:76
5   setNativeView@file:///app/tns_modules/tns-core-modules/ui/core/view-base/view-base.js:548:32
6   _setupUI@file:///app/tns_modules/tns-core-modules/ui/core/view-base/view-base.js:527:27
7   @file:///app/tns_modules/tns-core-modules/ui/core/view-base/view-base.js:534:27
8   eachChildView@file:///app/tns_modules/tns-core-modules/ui/layouts/layout-base-common.js:125:34
9   eachChild@file:///app/tns_modules/tns-core-modules/ui/core/view/view-common.js:868:27
10  _setupUI@file:///app/tns_modules/tns-core-modules/ui/core/view-base/view-base.js:533:23
11  @file:///app/tns_modules/tns-core-modules/ui/core/view-base/view-base.js:534:27
12  eachChildView@file:///app/tns_modules/tns-core-mo<\M-b\M^@\M-&>
JavaScript error:
file:///app/components/scroll-list-view/scroll-list-view.js:10:25: JS ERROR Error: This value is not a native object.
*** JavaScript call stack:
(
0   UIApplicationMain@[native code]
1   start@file:///app/tns_modules/tns-core-modules/application/application.js:272:26
2   run@file:///app/tns_modules/tns-core-modules/application/application.js:300:10
3   anonymous@file:///app/app.js:20:16
4   evaluate@[native code]
5   moduleEvaluation@:1:11
6   @:7:48
7   promiseReactionJob@:1:11
)
*** Terminating app due to uncaught exception****
 'NativeScript encountered a fatal error: Error: This value is not a native object.
at
1   new@file:///app/components/scroll-list-view/scroll-list-view.js:10:25
2   new@file:///app/components/scroll-list-view/scroll-list-view.js:10:25
3   initWithOrigDelegate@file:///app/components/scroll-list-view/scroll-list-view.js:13:59
4   initNativeView@file:///app/components/scroll-list-view/scroll-list-view.js:46:76
5   setNativeView@file:///app/tns_modules/tns-core-modules/ui/core/view-base/view-base.js:548:32
6   _setupUI@file:///app/tns_modules/tns-core-modules/ui/core/view-base/view-base.js:527:27
7   @file:///app/tns_modules/tns-core-modules/ui/core/view-base/view-base.js:534:27
8   eachChildView@file:///app/tns_modules/tns-core-modules/ui/layouts/layout-base-common.js:125:34
9   eachChild@file:///app/tns_modules/tns-core-modules/ui/core/view/view-common.js:868:27
10  _setupUI@file:///app/tns_modules/tns-core-modules/ui/core/view-base/view-base.js:533:23
11 <\M-b\M^@\M-&>

UPDATE
New Code
var ScrollingUITableViewDelegateImpl = (NSObject as any).extend({
_originalDelegate: null,

/* OriginalDelegate items */
tableViewWillDisplayCellForRowAtIndexPath(tableView: UITableView, cell: UITableViewCell, indexPath: NSIndexPath) {
    if (this._originalDelegate)
      return this._originalDelegate.tableViewWillDisplayCellForRowAtIndexPath(tableView, cell, indexPath)
    return null;
},
tableViewWillSelectRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): NSIndexPath {
   if (this._originalDelegate)
     return this._originalDelegate.tableViewWillSelectRowAtIndexPath(tableView, indexPath);
   return null;
  },
tableViewDidSelectRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): NSIndexPath {
    tableView.deselectRowAtIndexPathAnimated(indexPath, true);
    return indexPath;
},
tableViewHeightForRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): number {
    if (this._originalDelegate)
      return this._originalDelegate.tableViewHeightForRowAtIndexPath(tableView, indexPath);
    return null;
},

/* Scroll Delegate items */
scrollViewWillBeginDragging(scrollView:ScrollListView) {
  if (this._originalDelegate) {
    const owner:ListView = (this._originalDelegate['_owner'] as WeakRef<ListView>).get();
    owner.notify({eventName: ScrollListViewBase.ScrollEvent, object: owner});
  }
  else { console.log('no delegate'); }
},
scrollViewDidScroll(scrollView:ScrollListView) {
  if (this._originalDelegate) {
    const owner:ListView = (this._originalDelegate['_owner'] as WeakRef<ListView>).get();
    owner.notify({eventName: ScrollListViewBase.ScrollStateChangedEvent, object: owner});
  }
  else { console.log('no delegate'); }
}
}, {
   name: 'ScrollingUITableViewDelegateImpl',
   protocols: [UITableViewDelegate],
});

The updated code seems to run, but I'm running into a new error:

     JavaScript error:
     file:///app/tns_modules/tns-core-modules/ui/core/view/view-common.js:794:21: JS ERROR TypeError: child.layout is not a function. (In 'child.layout(childLeft, childTop, childRight, childBottom, setFram(
    0   UIApplicationMain@[native code]
    1   start@file:///app/tns_modules/tns-core-modules/application/application.js:272:26
    2   run@file:///app/tns_modules/tns-core-modules/application/application.js:300:10
    3   anonymous@file:///app/app.js:20:16
    4   evaluate@[native code]
    5   moduleEvaluation@:1:11
    6   @:7:48
    7   promiseReactionJob@:1:11
)

A: I think you might need to use the older method of extending classes, as shown here. For example, your delegate might look like this:
const ScrollingUITableViewDelegateImpl = (NSObject as any).extend({

  tableViewWillDisplayCellForRowAtIndexPath: function(tableView: UITableView, cell: UITableViewCell, indexPath: NSIndexPath) {
    // ... method implementation here
  }

  // ... more methods here

}, {
  protocols: [ UITableViewDelegate ]
});

const instance = new ScrollingUITableViewDelegateImpl();

A: I don't think these lines are valid neither required.
static new():ScrollingUITableViewDelegateImpl {
  return <ScrollingUITableViewDelegateImpl>super.new();
}

*

*It's a static method and super won't even be accessible here.

*It's a default method implemented in NSObject, you don't have to implement it again as you are extending it

A: resolved it using the extend method (removing the es2015 class B extends A and the static functions) like this:
import { ListView } from "tns-core-modules/ui/list-view/list-view";
import { ScrollListViewBase } from './scroll-list-view-common';
import { Length, View } from "tns-core-modules/ui/page/page";

export * from 'tns-core-modules/ui/list-view';

var ScrollingUITableViewDelegateImpl = (NSObject as any).extend({
  _originalDelegate: null,
  _owner: null,

  /* OriginalDelegate items */
  tableViewWillDisplayCellForRowAtIndexPath(tableView: UITableView, cell: UITableViewCell, indexPath: NSIndexPath) {
    if (this._originalDelegate)
      return this._originalDelegate.tableViewWillDisplayCellForRowAtIndexPath(tableView, cell, indexPath)
    return null;
  },
  tableViewWillSelectRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): NSIndexPath {
    if (this._originalDelegate)
      return this._originalDelegate.tableViewWillSelectRowAtIndexPath(tableView, indexPath);
    return null;
  },
  tableViewDidSelectRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): NSIndexPath {
    tableView.deselectRowAtIndexPathAnimated(indexPath, true);
    return indexPath;
  },
  tableViewHeightForRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): number {
    if (this._originalDelegate)
      return this._originalDelegate.tableViewHeightForRowAtIndexPath(tableView, indexPath);
    return null;
  },

  /* Scroll Delegate items */
  scrollViewWillBeginDragging(scrollView:UIScrollView) {
    this._owner.notify({eventName: ScrollListViewBase.ScrollEvent, object: this._owner});
  },
  scrollViewWillEndDragging(scrollView:UIScrollView, withVelocity: CGPoint,
    targetContentOffset: CGPoint) {
    this._owner.notify({eventName: ScrollListViewBase.ScrollEvent, object: this._owner});
  },
  scrollViewDidScroll(scrollView:UIScrollView) {
    this._owner.notify({eventName: ScrollListViewBase.ScrollEvent, object: this._owner});
  }
}, {
  protocols: [UITableViewDelegate],
});

export class ScrollListView extends ScrollListViewBase {
  /**
   * Variable __delegate
   *  The ios implementation of Nativescript `ListView` has a private var `_delegate`.
   *  That is being overridden here with the `property _delegate` that wraps
   *  the original delegate in one that provides scroll event listeners.
   *
   * This is hackish, but works well.
   */
  private __delegate: UITableViewDelegate;

  get _delegate():UITableViewDelegate { return this.__delegate; }
  set _delegate(v:UITableViewDelegate) {
    if (v == null) {
      this.__delegate = null;
    }
    else {
      const newDelegate = ScrollingUITableViewDelegateImpl.new();
      newDelegate._originalDelegate = v;
      newDelegate._owner = this;
      this.__delegate = newDelegate;
    }
  }
}


text:
Q: Irreversible encrypted password in HPE LoadRunner I have been running some performance test on one of my websites and I have been trying to encrypt my password for safety reasons. Every method I have tried is easily reversible if someone has access to my scripts. Does anyone know how to do this properly? LoadRunner documentation is quite poor. I have tried
Using parameters: (actual password can be seen in paramaters)
"Name=Username", "Value={Username}", ENDITEM,
"Name=Password", "Value={Password}", ENDITEM,

Using masked strings, can be also reversible.
"Name=Username", lr_unmask("5c5c433589e471556dd55bdac0336170f7c36ea3b32869fec2ee1ffa15"), ENDITEM,

Any help would be greatly appreciated, thanks

A: Use a public encryption algorithm.  Supply the decryption key for the data as part of a run time parameter (see run time settings for parameters).  Encrypt your parameter data with the key in question.  This way you can store your data encrypted, using a key which is only known by you before execution.

A: WebHttp protocol doesn't have an encryption feature. For encryption you can use the TruWeb protocol (https://admhelp.microfocus.com/truweb/en/latest/help/Content/TruWeb/TW-masking.htm) or implement your own way to use an encryption algorithm.
EDIT: Alternatively you can store values in VTS -
https://admhelp.microfocus.com/lr/en/12.60-12.61/help/WebHelp/Content/VTS/c_getting-started.htm


text:
Q: CSS Grid nested in a wrapper-div or a body element? In this series they all used a wrapper div.
MDN - CSS GRID Layout
Is this necessary, and if yes, why?

A: The purposes of wrappers are several, including:

*

*to group elements semantically, for instance to separate page heading
from body text from sidebar from footer.

*to group elements cosmetically, such as with a surrounding border or
a common background image or color.

*to group elements in layout, such as to keep them all in the same
column when columns are floated next to one another.

*to enable special positioning, as when a wrapper is given relative
positioning in order to contain child elements with absolute
positioning.

*to make it more convenient to specify elements in CSS and JavaScript
by referring to their parent, without having to id or class each
child element.

(Note: the var above should all be on one line)
So in this case, i think they all used a wrapper div just to group elements in layout.


text:
Q: Sticky sessions based on a cookie using nginx Currently, we are using apache2 as frontend, and tomcat as backend. We are using mod_proxy_balancer and AJP. Also we are using stickysession by JSESSIONID cookie:
<Proxy balancer://backend>
     BalancerMember ajp://127.0.0.1:8008 min=10 max=100 ping=5 connectiontimeout=40 ttl=60   retry=20 route=node-1
     BalancerMember ajp://127.0.0.1:8009 min=10 max=100 ping=5 connectiontimeout=40 ttl=60 retry=20 route=node-2
     ProxySet lbmethod=byrequests timeout=30
     ProxySet stickysession=JSESSIONID|jsessionid nofailover=Off
</Proxy>

and using jvmRoute parameter in web.xml to add tail to JSESSIONID cookie:
<Engine name="Catalina" defaultHost="localhost" jvmRoute="node-1">

We are looking to switch to using nginx for our frontend.  So far I haven't found any way to perform the same session affinity operation with nginx. Is there any solution for this? We are not using session replication, so getting sequential requests to the same backend is crucial.

A: Google suggests that there is an out-of-tree module for nginx that does this.  I've never used it, since I consider sticky sessions to be the work of satan, but it'll be the first option I'd use if I had to implement it.


text:
Q: ftp_site() doesn't want to change CHMOD on the folders I have a joomla page on which I want to install a few extensions. However due to the chmod permissions I am unable to upload and install the packages. Following the guide here I can see that in order for the plugins to be installed there are too many folders which permissions have to be changed.
For that I am creating a script which will iterate through each of the required folders and will change the permissions from 0775 to 0777.
<?php
// SET THE DESIRED CHMOD VALUE
if ($_GET['chmod']) {
        $ftp_chmod = $_GET['chmod'];
    }
    else {
        $ftp_chmod = "0755";
    }
echo "chmod=" . $ftp_chmod . '
';
echo getcwd() . '
';
$currdir = getcwd(); // get current directory

// ESTABLISH AN FTP LOGIN SESSION
$ftp_server='example.com';
$ftp_user='username';
$ftp_pass='*****';
$conn_id = ftp_connect("$ftp_server");

if ( ftp_login($conn_id, $ftp_user, $ftp_pass) ) {
    echo 'FTP CONNECTION IS SUCCESSFULL
';
}
else {
    echo 'BAD CREDENTIALS';
    exit();
}

// Define the folders for which the CHMODE will change the values
// There must be a leading space in front of the path in order for CHMOD to work
$folder_path = array(
    ' ' . $currdir . '/modules/',
    ' ' . $currdir . '/plugins/'
    ' ' . $currdir . '/tmp/',
    ' ' . $currdir . '/cache/'
);

echo '
';
foreach ( $folder_path as $key => $value )
{
    $path = trim($value); // The leading space must be trimed fo is_dir() function to work

    if ( is_dir($path) == true ) {

        echo $path . ' -- ' . 'OK
';
        echo 'CHMOD ' . $ftp_chmod . '  ' . $value . '
';

        if (ftp_site($conn_id, 'CHMOD ' . $ftp_chmod . $value)) {
            echo 'CHMOD ' . $ftp_chmod . ' IS SUCCESSFULL

';
        }
        else {
            echo 'CHMOD FAILED!

';
        }
    }
    else {
        echo $path . ' -- ' . 'NOT EXIST
';
    } // end if ( is_dir($path) == true ) else

} // end foreach ( $folder_path as $key => $value )

ftp_close($conn_id);
?>

Please note that the actual script is much larger due to the many folders that need to be changed. The folders shown in $folder_path = array() are just an example
When I execute the script on my server i get the folowind output:
chmod=0777
/var/www/example/data/www/example.com
FTP CONNECTION IS SUCCESSFULL

/var/www/example/data/www/example.com/modules/ -- OK
CHMOD 0777 /var/www/example/data/www/example.com/modules/
CHMOD FAILED!

/var/www/example/data/www/example.com/plugins/ -- OK
CHMOD 0777 /var/www/example/data/www/example.com/plugins/
CHMOD FAILED!

/var/www/example/data/www/example.com/tmp/ -- OK
CHMOD 0777 /var/www/example/data/www/example.com/tmp/
CHMOD FAILED!

/var/www/example/data/www/example.com/cache/ -- OK
CHMOD 0777 /var/www/example/data/www/example.com/cache/
CHMOD FAILED!

DOES ANYONE HAVE ANY IDEA ON HOW TO CHANGE THE CHMOD VALUE ON SO MANY FOLDERS?

UPDATE:
I also have to mention that I have tried to change the CHMOD value on each folder individually via FTP client and it is successfull. The problem comes when i have to change them through the script. The same acc with root privilege access is used from the FTP client and the script to change the files!

A: I have found a solution to the problem. What I did was a small modification to the foreach part of the script which made it work. Basically I just subtracted the required number of characters from the path returned from the getcwd() and that solved my problem.
Here is the change that i did:
---- REST OF THE SCRIPT OMITED -----

foreach ( $folder_path as $key => $value )
{
    $path = trim($value); // The leading space must be trimed fo is_dis() function to work

    if ( is_dir($path) == true ) {

        $value_short = substr($value, 19); // <------------- Subtruct the required number od chars in order to create a relative path

        echo $path . ' -- ' . 'OK
';
        echo 'CHMOD ' . $ftp_chmod . '  ' . $value_short . '
';

        if (ftp_site($conn_id, "CHMOD $ftp_chmod $value_short")) { // <-------------- Use the relative path in the function
            echo 'CHMOD ' . $ftp_chmod . ' IS SUCCESSFULL

';
        }
        else {
            echo 'CHMOD FAILED!

';
        }
    }
    else {
        echo $path . ' -- ' . 'NOT EXIST
';
    } // end if ( is_dir($path) == true ) else

} // end foreach ( $folder_path as $key => $value )

---- REST OF THE SCRIPT OMITED -----

A: Did you try just enabling Joomla's FTP layer before installing components/plugins etc?


text:
Q: C Programming: Redefine a macro defined in the shared library(.so) I want to override the macro defined in the shared library.
For example:
libxyz.so (a shared library) has
#define ADDRESS 0

int some_func()
{
   ...
   func_use_addr(ADDRESS);
}

Now I write a code where the ADDRESS that I want "some_func()" to use is (say) 0xabc36000.
Can I redefine the ADDRESS macro in my.c file so that it'll be used as the 0xabc36000 and not 0 in the some_func()?
I understand that macros are replaced during pre-processing stage, and linking with shared library happens later. I'm wondering if there's a way to do this with out modifying the shared library code.

A: Yes, you can redefine a macro.
#ifdef ADDRESS
#undef ADDRESS
#endif

#define ADDRESS 0xabc36000


text:
Q: jQuery code not works I want to corrected next jQuery code but i don't know how.
jQuery('#jud').change(function(){
    if (jQuery("#jud").val() == "0") {
        jQuery(".loc").hide();
       } else {
        jQuery(".loc").show();
    }
jQuery("#loc").find("option").hide();
jQuery("#loc").find("option[name =" + jQuery(this).attr("name") + "]").show();
});

This code display corresponding options in second select which has the same name options in the first select and hides the rest
<select id="jud">
<option name="0">Select</option>
<option name="1">Jud1</option>
<option name="2">Jud2</option>
</select>

<select id="loc">
<option name="0">Select</option>
<option name="1">Loc1</option>
<option name="1">loc2</option>
<option name="2">loc3</option>
<option name="2">loc3</option>
</select>

i think the problem is here if (jQuery("#jud").val() == "0")
can you help me?

A: try taking selected option value (edited, as haven't seen you are using names instead of values for option tag):
$("#jud option:selected").attr('name');

A: Your HTML is not correct. You should use value attributes instead of names.
jQuery('#jud').change(function () {
    if (jQuery(this).val() == "0") {
        jQuery(".loc").hide();
    } else {
        jQuery(".loc").show();
    }
    jQuery("#loc").find("option").hide();
    jQuery("#loc").find("option[value=" + jQuery(this).val() + "]").show();
});

Javascript also can be simplified:
$('#jud').change(function () {
    $(".loc").toggle($(this).val() != "0");
    $("#loc option").hide().filter("[value =" + $(this).val() + "]").show();
});

Demo: http://jsfiddle.net/Dam6v/

A: Working Solution: http://jsfiddle.net/Y7UZU/
Also posting the code below:
HTML:
<select id="jud">
<option name="0">Select</option>
<option name="1">Jud1</option>
<option name="2">Jud2</option>
</select>

<select id="loc">
<option name="0" >Select</option>
<option name="1" style="display:none;">Loc1</option>
<option name="1" style="display:none;">loc2</option>
<option name="2" style="display:none;">loc3</option>
<option name="2" style="display:none;">loc4</option>
</select>

JS:
jQuery('#jud').change(function(){

    var secN = $(this).find(':selected').attr('name');

    $('#loc option').hide();
    $('#loc option[name='+secN+']').show();

});


text:
Q: What is the maximum value of a numeric bash shell variable? I'm curious as to what happens when a numeric variable in bash is incremented up without purposely stopping it. How large can the number get? Will it overflow and become negative and just continue to increment forever? Will it break and skid to a stop at some point?
I am using an x86_64 AMD processor, but I would be happy to hear 32bit answers as well, just specify which you are talking about.
I am running Fedora21 64bit.
I've googled far and wide but haven't found this specific tidbit for some odd reason. It seems like it would be a basic piece of info in all the manuals and such.

A: It may come down to your version of bash, your OS, and your CPU architecture. Why don't you try it yourself? Set a variable to (2^31)-1, then increment it, set it to 2^32, then increment it, set it to 2^64, then increment it, etc.
Here, I just tried it myself on my Core i7 Mac running OS X "El Capitan" v10.11.3, and it looks like bash is using signed 64-bit integers.

$ uname -a
Darwin Spiff.local 15.3.0 Darwin Kernel Version 15.3.0: Thu Dec 10 18:40:58 PST 2015; root:xnu-3248.30.4~1/RELEASE_X86_64 x86_64
$ bash --version
bash --version
GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin15)
Copyright (C) 2007 Free Software Foundation, Inc.
$
$ ((X=2**16)); echo $X
65536                        <-- okay, at least UInt16
$ ((X=2**32)); echo $X
4294967296                   <-- okay, at least UInt32
$ ((X=2**64)); echo $X
0                            <-- oops, not UInt64
$ ((X=(2**63)-1)); echo $X
9223372036854775807          <-- okay, at least SInt64
$ ((X++)); echo $X
-9223372036854775808         <-- overflowed and wrapped negative. Must be SInt64

A: I set up a loop. while return status is 0 increment a variable with addition and print the variable to stdout
I started it just under 2^31, I let it pass both 2^31 and 2^32 with no issue, stopped it, then set the initial value to just under 2^63.
The result was that it seamlessly rolled over from 9.22e18 to -9.22e18 and continued to increment positively. (toward zero)
Just to check that my while [ $? -eq 0 ] was actually using the exit status of the commands within the while loop, not using the exit status of the previous script or some oddity, I also ran it with an extra command inside the loop designed to create a non zero exit status at particular increments.
So it is signed, it will roll over rather than stop at max value, and it does so without any error message. So it is possible to end up in a truly infinite loop. It does not limit the 64bit hardware and 64bit linux OS to an old 16 or 32bit standard.

A: I improved and automated @Spiff 's answer:
MAX_INT=0
for ((x=1,y=1; x<<=y; y<<=1))
do
    if ((x>0))
    then
        MAX_INT=$x
        continue
    fi

    if (((x=~x)>0))
    then
        MAX_INT=$x
    fi
    break
done
echo $MAX_INT

A: bash use 64-bit integer. So if you increase after variable reaching its max number, variable will overflow. Below is my test with unsigned int and signed integer.
MAX_UINT = 18446744073709551615
MAX_INT = 9223372036854775807

$ printf "%llu\n" $((2**64))
0
$ printf "%llu\n" $((2**64-1))
18446744073709551615

$ printf "%lld\n" $((2**63-1))
9223372036854775807
$ printf "%lld\n" $((2**63))
-9223372036854775808
$ printf "%lld\n" $((2**64-1))
-1

A: commands to get maximum bash integer (maxI), and minimum bash integer (minI):
$ maxI=$( echo `printf "%u" -1` / 2  | bc )
$ echo $maxI
9223372036854775807
$ minI=$(($maxI + 1))
$ echo $minI
-9223372036854775808

The results in different machines may be different, but the command should be the same.
-- Update --
Shorter maxI (remove the redundant "echo"), and more "exact" one:
$ maxI=$( printf "%u/2\n" -2  | bc )
$ echo $maxI
9223372036854775807

Use -2 than -1 is a bit more exact, where, printf "%u" -1 gives me 18446744073709551615 on my machine which is not divisible by 2, although bc gives the correct answer 9223372036854775807, since bc truncate anything after the decimal point. (since the default 'scale' variable is zero).  Using -2, it would be now 18446744073709551614, which is divisible by 2, and gives the correct answer when divided.


text:
Q: Generate unique ID of an object that stays the same across instances I am generating an object from the database using the following:
$game = $this->game_model->get_by('slug', 'some-title');

I am also using a cache library in Codeigniter where I write to a cache file by:
$this->cache->write($game, $cache);

where $game is the object and $cache is an identifier for that object.
I would like to generate a unique ID for this object to use as the cache name. Something like spl_object_hash but that will stay the same across subsequent instances.
For example if I do:
$cache = spl_object_hash($game);

// Cache object
$this->cache->write($game, $cache);

It will generate 000000006c5ce27300000000564a8706.cache as the unique ID, but if I reload the page, I get a different ID, which defeats the purpose of the cache.
How can I get a consistent unique ID for an object?

A: You can use serialize() and then hash it.
$cache = hash('sha1', serialize($game));


text:
Q: Plotting with a custom dataset recharts I had such a dataset.
const chartData = {
  data: [
    {
      name:           'Page A',
      analyticsCount: 4000,
      analyticsPrice: 2400,
    },
    {
      name:           'Page B',
      analyticsCount: 3000,
      analyticsPrice: 1398,
    },
  ],
  keys: ['analyticsCount', 'analyticsPrice'],
};

I was plotting using the Recharts library.
const renderBar = (keys) => {
    return keys.map((keyName, index) => (
      <Bar
        key={index}
        dataKey={keyName}
        yAxisId={keyName}
      >
        {index === 0 && (<LabelList content={renderLabel} />)}
      </Bar>
    ));
  };

now the data comes in a different format.
const charData2 = [
  {
    name:   'Page A',
    params: [
      {key: 'Count', label: 'Count', value: 12},
      {key: 'Price', label: 'Price', value: 41},
    ],
  },
  {
    name:   'Page B',
    params: [
      {key: 'analyticsCount', label: 'analyticsCount', value: 12},
      {key: 'analyticsPrice', label: 'analyticsPrice', value: 79},
    ],
  },
];

How do I build a graph with such a dataset. Moreover, the number of keys can be completely different.
My attempt
const renderTestBar = () => {
    return  chartData.map((series, key) => (
      Object.keys(series).filter(obj => obj !== 'name').map((bar, index) => (
        <Bar
          key={index}
          dataKey={bar}
          yAxisId={bar}
        />
      ))
    ));
  };

But in this case, the data is repeated