text:
Q: xhr upload progress event only firing once I want to update a progress bar using the xhr progress event.
I have the following code:
  xhr: function() {
    var xhr = Ember.$.ajaxSettings.xhr();
    xhr.upload.addEventListener("progress", function(e){
      if (e.lengthComputable) {
        self.didProgress(e);
      }
    }, false);
    return xhr;
  },

The problem is that the event only happens once and I believe this happening because the server call is cross domain.
Does anybody know what I have to set on the server by way of headers to let this work correctly?

A: As far as I know, this has nothing to do with being a cross-domain request. Normally, on Apache, you wouldn't get a progress event to fire more then once because (I assume) you upload the whole file in one chunk. This is the normal behavior without using a module like apache-upload-progress-module
The way I achieved this without modules in the past is to split the file into chunks on the client-side (using the File API and Blobs). The first chunk gets sent, waits for the server response, sends the second chunk from where it left off, and so on until there are no more chunks to upload.
There are a few examples of this around the web. You might want to take a look at how JQuery File Upload does it.
I hope this helps.


text:
Q: MySQL 5.1.69 at CentOS 6.4 doesn't know enable-named-pipe? Trying to install MySQL (for WordPress) on a CentOS 6.4 /64 bit server.
I have installed the mysql-server-5.1.69-1.el6_4.x86_64 package and executed the following commands:
# chkconfig mysqld on
# service mysqld start
# /usr/bin/mysqladmin -u root password 'xxxxx'
# /usr/bin/mysql_secure_installation

Then I've noticed that mysqld_safe process
is listening at 0.0.0.0 and decided to change that -
so that my WordPress installation only uses
domain sockets (or unix pipes? not sure about the correct term).
So I've modified the /etc/my.cnf to:
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
user=mysql
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
bind-address = localhost
skip-networking
enable-named-pipe

[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid

But now MySQL refuses to start:
# service mysqld restart
Stopping mysqld:                                           [  OK  ]
MySQL Daemon failed to start.
Starting mysqld:                                           [FAILED]

The  /var/log/mysqld.log contains:
 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
  InnoDB: Initializing buffer pool, size = 8.0M
  InnoDB: Completed initialization of buffer pool
  InnoDB: Started; log sequence number 0 44233
 [ERROR] /usr/libexec/mysqld: unknown option '--enable-named-pipe'
 [ERROR] Aborting
  InnoDB: Starting shutdown...
  InnoDB: Shutdown completed; log sequence number 0 44233
 [Note] /usr/libexec/mysqld: Shutdown complete
 mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid ended

I've searched Google and grepped
/usr/share/mysql/*.cnf for that directive,
but haven't found any hints there.

A: No hints?
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
user=mysql
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
bind-address = localhost
skip-networking
enable-named-pipe <-------------------

[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid

According the online documentation for that version of MySQL:
--enable-named-pipe
Command-Line Format --enable-named-pipe
Option-File Format  enable-named-pipe
Platform Specific   windows  <--------------------

Enable support for named pipes. This option can be used only with the mysqld-nt and mysqld-debug servers that support named-pipe connections.

Remove that setting from your /etc/my.cnf and restart the process.

redpajama_set_name: RedPajamaStackExchange


text:
Q: MendesPavlisModel in Orekit python: 'MendesPavlisModel' object has no attribute 'getParameters' I used the Python version of Orekit's MP model for atmospheric refraction correction
Here is my code:
import orekit
vm = orekit.initVM()
from org.orekit.models.earth.troposphere import MendesPavlisModel

latitude=FastMath.toRadians(30.67166667)
longitude=FastMath.toRadians(-104.0250)
height=2010.344
pressure=798.4188
temperature=300.15
humidity=0.4
lambdad=0.532
point=GeodeticPoint(latitude, longitude, height)
date=AbsoluteDate(2009,8,12, TimeScalesFactory.getUTC())
elevation=15.0

MP_Model=MendesPavlisModel(temperature, pressure,humidity, lambda)

computedDelay = model.computeZenithDelay(point, model.getParameters(), date)

It gives:
 'MendesPavlisModel' object has no attribute 'getParameters'

Can anyone help?


text:
Q: Exclude EurekaClient Bean from Application Context in SpringBootApplicationTest I'm trying to write a integration test against my Spring Data API with the following test configuration.
eureka:
  client:
    enabled: false
[..] # No other configuration part that affects discovery/eureka client

This is my test class
@SpringBootTest
@AutoConfigureMockMvc(addFilters = false)
@Transactional
class FooAPITest {

  @Test
  void contextLoads() {
  }

}

However I have a component which injects the EurekaClient to get a service instance from it
@Component
public class ServiceClient {

  @Autowired
  public ServiceClient(@Qualifier("eurekaClient") EurekaClient eurekaClient) {
    URI serviceUri = URI.create(eurekaClient.getNextServerFromEureka("service", false).getHomePageUrl());
  }

}

So as of this service my application is not able to load the ApplicationContext.
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.netflix.discovery.EurekaClient' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Qualifier(value="eurekaClient")}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1695)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1253)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1207)
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:885)
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:789)
    ... 81 more

What I've tried so far
I thought about setting up a custom ContextConfiguration to exclude the ServiceClient as it is not needed in the test class. However I need to include a Configuration File which autowires the EntityManager but when I use @SpringBootApplication(classes = {Configuration.class}) the EntityManager can not be injected. This Configuration looks like that:
@Configuration
class Configuration {
  @Autowired
  EntityManager entityManager;
}

This produces the same error but with EntityManager Bean:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.persistence.EntityManager' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1695)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1253)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1207)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640)
    ... 81 more

Current Workaround
Currently I'm avoiding the problem by mocking the ServiceClient but I want to get rid of that code smell.
@MockBean
ServiceClient serviceClient;

@BeforeEach
void setUp() {
  MockitoAnnotations.initMocks(FooAPITest.class);
}

Another workaround would be to mark the Injected Beans as not required but I don't find that practicable only to make the tests work.
What is a proper way to solve this problem?

A: You can try mocking the EurekaClient in your test:
@SpringBootTest
@AutoConfigureMockMvc(addFilters = false)
@Transactional
class FooAPITest {

  @MockBean
  private EurekaClient eurekaClient;

  @Test
  void contextLoads() {
  }

}

This will create the EurekaClient as a mocked bean in the ApplicationContext to be injected into your service.
If you have other tests that initialize the Spring ApplicationContext, you can create a separate configuration class within the application package to be scanned (using @ConditionalOnMissingBean annotation to cover all bases):
@Configuration
public class MockEurekaConfiguration {

  @Bean
  @ConditionalOnMissingBean
  public EurekaClient eurekaClient() {
    return Mockito.mock(EurekaClient.class);
  }

}


text:
Q: Changing the UI of the longlistSelector Is it possible to change the UI of the LongListSelector in windows phone applications?
If so how can I do that if not why it is not possible?

A: It is possible. You change the UI by providing custom UI definition/style for ItemTemplate, GroupHeaderTemplate, JumpListStyle, ListHeaderTemplate, ListFooterTemplate, and some other properties of LongListSelector.
Find details on how to that in this post from geekchamp.com and see 3 sample projects that demonstrates possible usage of LongListSelector from blogs.windows.com


text:
Q: sendmail: Cannot open mailhub:25 but my config specifies port 587 I'm using Sendmail on Linux via the command line, to attempt to send email as described here - https://blog.edmdesigner.com/send-email-from-linux-command-line/
I've updated my /etc/ssmtp/ssmtp.conf as follows, which specifies port 587 to be used for the mailhub:
UseSTARTTLS=YES
    root=my.address@gmail.com
    mailhub=smtp.gmail.com:587
    AuthUser=my.address@gmail.com
    AuthPass=xxxxxxxxxxx

When I try to send an email via the command line as follows, I get the error Sendmail: Cannot open mailhub:25:
echo "Subject: Hi" | sendmail my.otheraddress@somewhereelse.com
Is there something I need to do to ensure that the current version of ssmtp.conf is used?
I've also added this to /etc/ssmtp/revaliases:
root:my.address@gmail.com:smtp.gmail.com:587


text:
Q: Firefly Cartesian Conversion I'm trying to use the algorithm of firefly, is based of the next source:
https://github.com/firefly-cpp/Firefly-algorithm--FFA-
I have the problem that it's  is giving me the highest point of a firefly and  I need to modify the code, to make the firefly give  me back  a point on a Cartesian plane. Could you give me a advice of how to start doing this


text:
Q: Is $ \forall x \in \emptyset. (P(x) \land \lnot P(x)) $ true? I have searched the forums but haven't found any answers to this question, so I thought I'd ask it myself.
Let $P(x)$ be an arbitrary predicate. Does the following statement evaluate to true or false?
$ \forall x \in \emptyset. (P(x) \land \lnot P(x)) $
It should evaluate to true because there is no element, hence it is true for all elements.
But it should evaluate to false because $ P(x) \land \lnot P(x) $ is always false.
Does anyone have any ideas on how to answer this question?

A: It's a true statement.
Your statement is a universal statement, so to verify it, you can think of it as 'lining up' all objects to which the statement pertains, and checking whether they have the indicated property. So, for example, if your domain consists of two objects $a$ and $b$, then verifying the claim that all objects have property $P$ amounts to verifying that both $a$ and $b$ have property $P$.
Ok, but what if your domain is empty (as in your case)? Well, then the verification is trivial: Yes, 'all' (zero!) objects have the property $P$.
Here is another way to think about it: what would make a universal claim false? Well, the claim is false when you find some object that does not have property $P$ ... but if you find no such counterexamples, then the claim is true. Having no objects in your domain, however, means that there can be no counterexamples, so no matter what $P$ is, even if (as in your case) it expresses something impossible.
Consider this somewhat more concrete example:
"Every time I played the lottery, I won the jackpot!"
Huh! Am I a very lucky person? Well, consider the fact that actually I have never played the lottery ...  does that make the statement true? Yes! All zero times that I played the lottery, I won the jackpot! Again, think of it as 'lining up' all points in time when I played the lottery and verifying that at all those times I won the jackpot. Well, given that there are no such points in time where I played the lottery, this verification is trivial: yes, it checks out!
Or, in terms of counterexamples: there is no point in time where i played the lottery and did not win the jackpot. So, the claim checks out and is therefore true.
Of course, it is also true that all zero times I played the lottery, I did not win the jackpot. So, all zero times that I played the lottery, I did win the jackpot as well as did not win the jackpot ... which is just like your statement.

A: The formula is equivalent to :

$\forall x \ (x \in \emptyset \to (P(x) \land \lnot P(x)))$.

Thus, it is TRUE,because $x \in \emptyset$ is always FALSE and the truth table for the conditional has that :

FALSE $\to$ FALSE is TRUE.

See also Vacuous truth :

a statement that asserts that all members of the empty set have a certain property.

A: $$\forall x \in \emptyset. (P(x) \land \lnot P(x))$$
is true as you mentioned.
$$(P(x) \land \lnot P(x))$$ is also true for all $x$ in the empty set.
Thus there is no conflict.

A: Make use of the fact that for any propositions $A$ and $B$, we have $A \implies [\neg A \implies B]$ regardless of whether $B$ is true or false. This tautology is the so-called principle of explosion.
Definition: $\forall a: \neg [a\in \emptyset]$
Suppose $x\in \emptyset$ (the initial premise).
From the definition of $\emptyset$, we obtain $\neg [x\in \emptyset]$.
Applying the principle of explosion to the initial premise, we have $\neg [x\in \emptyset] \implies P(x) \land \neg P(x)$.
Applying the rule of detachment, we have $P(x) \land \neg P(x)$.
Discharging the initial premise and generalizing on $x$, we obtain, as required:
$\forall a:[a\in \emptyset \implies P(a)\land \neg P(a)] $


text:
Q: i cannot get my javascript number-sorter to work i am making a number sorter that alerts the number of different numbers (e.g. 11223 would be returned as number of ones = 2, number of twos = 2, number of threes = 1 ect. ect.)
here is the code
<html>
<body>
<textarea width="100" height="50" id="text" onBlur="sort();"></textarea>
<script>
var text = document.getElementById("text").value;
var no1 = 0
var no2 = 0
var no3 = 0
var no4 = 0
var no5 = 0
var no6 = 0
var no7 = 0
var no8 = 0
var no9 = 0
var no0 = 0
var other = 0
var split = text.split("");
function sort() {
    for (i = 1; i < split; i++) {
        if (string[i]===1) {
            no1++;
            return no1;
        }
        else if (string[i]===2) {
            no2++;
            return no2;
        }
        else if (string[i]===3) {
            no3++;
            return no3;
        }
        else if (string[i]===4) {
            no4++;
            return no4;
        }
        else if (string[i]===5) {
            no5++;
            return no5;
        }
        else if (string[i]===6) {
            no6++;
            return no6;
        }
        else if (string[i]===7) {
            no7++;
            return no7;
        }
        else if (string[i]===8) {
            no8++;
            return no8;
        }
        else if (string[i]===9) {
            no9++;
            return no9;
        }
        else if (string[i]===0) {
            no0++;
            return no0;
        }
        else {
            other++;
            return other;
        }
    }
    alert("number of ones = " + no1 + ", number of twos = " + no2 + ", number of threes = " + no3 + ", number of fours = " + no4 + ", number of fives = " + no5 + ", number of sixes = " + no6 + ", number of sevens = " + no7 + ", number of eights = " + no8 + ", number of nines = " + no9 + ", number of zeros = " + no0 + ", number of other characters = " + other + ".");
}
</script>
</body>
</html>

when i enter a value and click away from the text field it returns 0 for all the variables
please help

A: Your code was not very easy to maintain, so I made my own version, try it out:
function sort() {
    var text = document.getElementById("text").value;
    // will contain a list of chars with their associated count
    var charCounter = {};
    for (var i = 0, l=text.length; i < l; i++) {
        var char = text[i];
        // if char is a number
        if(!isNaN(parseInt(char))){
            if(charCounter[char]){ charCounter[char]++; }
            else { charCounter[char] = 1; }
        // if char is not a number
        } else {
            if(charCounter['other characters']){ charCounter['other characters']++; }
            else { charCounter['other characters'] = 1; }
        }
    }
    outputList(charCounter);
}

function outputList(obj){
    var keys = Object.keys(obj);
    var output = '';
    for(var i=0, l=keys.length; i<l; i++){
        output += 'Number of ' + keys[i] + ' : ' + obj[keys[i]] + '.\n';
    }
    alert(output);
}

JS Fiddle Demo

A: A simpler solution is to use an array of words for the number names and use it for keys on an object that accumulates the count of occurrences of each digit, e.g.
function countDigits(n) {

  // Array of number names
  var words = ['zeros','ones','twos','threes','fours',
               'fives','sixes','sevens','eights','nines'];

  // Split number into digits
  var nums = String(n).split('');
  var counts = {};

  // Count how many of each digit
  nums.forEach(function(n){
    if (!(counts.hasOwnProperty(words[n]))) counts[words[n]] = 0;
    ++counts[words[n]];
  });

  // Write to output
  words.forEach(function(w){
    console.log('Number of ' + w + ' = ' + (counts[w] || 0) + '\n');
  });
}

countDigits(1012023405);

/*
  Number of zeros = 3
  Number of ones = 2
  Number of twos = 2
  Number of threes = 1
  Number of fours = 1
  Number of fives = 1
  Number of sixes = 0
  Number of sevens = 0
  Number of eights = 0
  Number of nines = 0
*/

Or a slightly different formulation:
function countDigits(n) {

  // Array of number names
  var words = ['zeros','ones','twos','threes','fours',
               'fives','sixes','sevens','eights','nines'];
  var counts = [];

  // Split number into digits and count
  String(n).split('').forEach(function(n) {
    counts[n] = counts[n]? counts[n] + 1 : 1;
  });

  // Write to output
  for (var i=0; i<10; i++) {
    console.log('Number of ' + words[i] + ' = ' + (counts[i] || 0) + '\n');
  }
}


text:
Q: Debugger: show data of opencv Mat of type CV_16UC1 I have an opencv Mat variable img of type CV_16UC1 (16 bit memory with 12 bit usable data) and want to display its data member in the debugger, e.g. gdb. When I try to do print img.data I get:
print img
$2 = {flags = 1124024322, dims = 2, rows = 480, cols = 640,
data = 0xa1b48042 <error: Cannot access memory at address 0xa1b48042>,
datastart = 0xa1b48042 <error: Cannot access memory at address 0xa1b48042>,
dataend = 0xa1bde042 <error: Cannot access memory at address 0xa1bde042>,
datalimit = 0xa1bde042 <error: Cannot access memory at address 0xa1bde042>,
allocator = 0x0, u = 0x0, size = {p = 0xbeffeaa8}, step = {p = 0xbeffead0, buf = {1280, 2}}}

Trying to print values with print *(ushort *)img.data@2 results in:

Cannot access memory at address 0xa1b48042

How is it possible to display the values of img without converting to another type (e.g. CV_8UC1)?
img was create from a custom buffer class:
cv::Mat img = cv::Mat(height, width, CV_16UC1, (void *)(static_cast<char*>(buffer->Data()))

When I shift img by 4 bit and converting to CV_8UC1:
cv::Mat img8 = img * 16.0;
img8.convertTo(img8, CV_8UC1);

I am able to display the data with:
(gdb) print *(ushort *)img8.data@2
$5 = {513, 2052}


text:
Q: JQuery: Combining animate CSS and fadeIn This is my script:
$("#headerimage").animate({marginLeft:"0"},300);

I want to add "fadeIn" as well to start simultaneously and at the exact same speed. How is this done?

A: By animating the opacity:
$("#headerimage").animate({
    marginLeft: 0,
    opacity   : 1
}, 300);

If it's hidden with display:none, show it first:
$("#headerimage").css({
    opacity : 0,
    display : 'block' // or whatever
}).animate({
    marginLeft: 0,
    opacity   : 1
}, 300);

A: $("#headerimage").animate({
    marginLeft:"0",
    opacity: 1
},300);


text:
Q: Is it possible to Generate new keystore with correct signature using original certificate files Our old developer "lost" the password for the keystore.  We have tried using a brute force attack on the keystore but it has been running for over a week so we are giving up on that option.
We still have the pk8 and pem files which were used to create the keystore.
Is it possible to create a new keystore with the certificate so that the signature matches?
We are at our whit's end on this one. Any help is greatly appreciated.


text:
Q: What line of code could I use in C++ to disable energy saver? I want to prevent the monitor from going to sleep (the windows setting, not the monitor setting). I am using c++. What call do I make?

A: A simpler way that doesn't modify global system state like the first response does:
In your window procedure, add a handler for WM_SYSCOMMAND. When wParam is SC_MONITORPOWER, return 0 instead of deferring to DefWindowProc. (When wParam is any other value, make sure you either handle the message or pass it to DefWindowProc. Otherwise the user will have difficulty adjusting your window at runtime.)

A: SetThreadExecutionState(ES_DISPLAY_REQUIRED|ES_CONTINUOUS);

A: class KeepDisplayOn
{
public:
    KeepDisplayOn()
    {
        mPrevExecState = ::SetThreadExecutionState(ES_DISPLAY_REQUIRED | ES_SYSTEM_REQUIRED | ES_CONTINUOUS);
        ::SystemParametersInfo(SPI_GETSCREENSAVETIMEOUT, 0, &mPrevScreenSaver, 0);
        ::SystemParametersInfo(SPI_SETSCREENSAVETIMEOUT, FALSE, NULL, 0);
    }

    ~KeepDisplayOn()
    {
        ::SystemParametersInfo(SPI_SETSCREENSAVETIMEOUT, mPrevScreenSaver, NULL, 0);
        ::SetThreadExecutionState(mPrevExecState);
    }

private:
    UINT                mPrevScreenSaver;
    EXECUTION_STATE     mPrevExecState;
};

A: Wiggle the mouse every minute or so.
mouse_event(MOUSEEVENTF_MOVE,1,0,0,0);
mouse_event(MOUSEEVENTF_MOVE,-1,0,0,0);
Sleep(60000);


text:
Q: Prisma create empty model object How can I create an empty model object in prisma without typing every atribute?
I I have the following model:
model Compra {
  id          Int       @id @default(autoincrement())
  createdAt   DateTime  @default(now())
  anoMes      String
  fecha       DateTime
  ccf         String
  neto        Decimal   @default(0)
  iva         Decimal   @default(0)
  excento     Decimal   @default(0)
  total       Decimal   @default(0)
  proveedor   Proveedor @relation(fields: [proveedorId], references: [id])
  proveedorId Int
}

I want to create something like this:
let empty = {
    id: 0,
    createdAt: '',
    anoMes: '',
    fecha: '',
    ccf: '',
    neto: '',
    excento: '',
    iva: '',
    total: ''
    proveedor: { id: 0, nombre: '', registo: '' },
    proveedorId: 0,
};

Is there a shorthand o do I have to create one for every model I have?

A: Every property in the model of a Prisma schema must have a type.
Documentation: https://www.prisma.io/docs/concepts/components/prisma-schema/data-model#defining-fields
Declaring the type is part of declaring the field - you must have both. A field can be nullable (if not an array type you can add a ? to the end of it), and you can use types native to the kind of database you're using (https://www.prisma.io/docs/concepts/components/prisma-schema/data-model#native-types-mapping), but there's no way to completely omit a field's type.
When Prisma interacts with your underlying database, it NEEDS to know the type of data it's working with when constructing tables/columns/queries. The types are also crucial to the emitted TypeScript client, which provides super helpful type-hinting when performing CRUD operations.


text:
Q: Range selectors in enlive I'm trying to create a range selector, and can't seem to get off the ground.
I'm trying things like:
(sniptest "

Hi

There

"
      [{[:.start] [:.end]}] (content "Hello"))

And that just returns the supplied html. I'd expect it to return a div with the body "Hello".
How do I do this?
EDIT
Just to be more concise, this is what I've done with deftemplate and a real html file:
HTML

  <title></title>

Not hello

 foo

    bar

CLJ
(ns compojure-blog-test.views.landing-page
  (:require [net.cgrand.enlive-html :as html]))

(html/deftemplate landing-page "compojure_blog_test/views/landing_page.html"
  [blogs]
  {[:.start] [:.end]} (html/content "Blah blah"))

I'm following along with this tutorial, but it uses a snippet to match ranges. Is this neccesary?
Is it possible to test these out with just sniptest?

A: These are called "fragment selectors" in enlive parlance and unfortunatly for your purposes they don't support content directly, though if you wrap them in a clone-for you can get the same effect.
user> (require '[net.cgrand.enlive-html :as html])
nil
user> (html/sniptest "

before

Hi

There

after

last

"
                     {[:.start] [:.end]} (html/clone-for [m ["Hello"]]
                                            [:p] (html/content m)))
"

before

Hello

Hello

after

last

"

This allows you to do more interesting things based on the position in the fragment
user> (html/sniptest "

before

Hi

There

after

last

"
    {[:.start] [:.end]} (html/clone-for [m [["Hello" "Sir"]]]
                           [:p.start] (html/content (first m))
                           [:p.end]   (html/content (last m))))
"

before

Hello

Sir

after

last

"

You can also use do-> instead of clone-for:
user> (html/sniptest "

before

Hi

There

after

last

"
    {[:.start] [:.end]} (html/do-> (html/content "Hello")))
"

before

Hello

Hello

after

last

"


text:
Q: Sensible solutions to the removal of the offline_access permission Am coming back to building a FB app after some time away from the FB Platform and I see that the old offline_access permission has been removed and replaced with long(ish)-expiry tokens[1].
So, it now seems like any external app that needs to push data to Facebook based on, say, a schedule or some activity in the external app will need to cope with that long-access token having expired. This is made more frustrating because now a user logging out of FB will also kill any long-expiry token[2], whereas before, offline_access lived on even when the user was logged out.
I'm still in the pondering-a-solution stage, but two ideas spring to mind:
1) Whenever my app contacts a user who has FB integration, they are requested to click a link that will trigger re-auth with FB to get a new long-access token. My users are generally contacted several times within the lifespan of a long-access token, so this should effectively keep renewing the long-access token for as long as they need (even if it does add some annoying friction to my app)
2) Because I can't guarantee that 1) will always work (due to users not clicking the re-auth link in my app's email notification or them logging out of Facebook, for example) I'll also have to handle failed FB interactions by placing them in a holding queue and emailing the user to explicitly ask them to grant a long-access token again. Not cool, but I see no other option. If they don't respond to the request after X attempts to ask them to re-grant permission, I'll just have to bin the task and email them to explain that it's due to an FB limitation, not my app. Again, not cool.
Has anyone had to come up with any better solutions to maintain the ability to interact with a user's account with authentication/explicit permissions? I'd be keen to hear what you did.
(This is all pending me re-reading the FB ToS, of course - it's entirely possible that this is against the rules, which would be even more frustrating)
EDIT/UPDATE: the data I need to push is images to a photo album which will arrive at my server from various sources and will then be pushed into an appropriate user's album (with their pre-granted permission, of course). I won't be able to guarantee having any web-based end-user interaction at the point in time the images hit my server in order to get the end user to grant me a new short-lifespan token. Basically, offline_access really would have been ideal for this IMO.
UPDATE 2: NB: it's really key to my use case that the user won't necessarily be using my app or Facebook when the token needs to be granted or extended.
[1] https://developers.facebook.com/roadmap/offline-access-removal/
[2] http://developers.facebook.com/blog/post/2011/05/13/how-to--handle-expired-access-tokens/

A: You've got the right two options, but I will point out a third option and a little-known-fact that may or may not be relevant for your specific scenario of "needs to push data to Facebook"
First, another option available assuming you either have mobile web or canvas implemented for your app is app to user requests or notifications.  The user will get a little notification counter indicator next to your app name in the list of bookmarks.  If they respond to the request or the bookmark/notification counter gets them to hit your app, you can trigger your server-side token renewal/extension process.  This process is transparent to the user -- assuming they still have your app installed they see nothing.
Secondly, what a lot of people use offline_access for today is simply posting to the user's stream.  If that is all you need and you don't need to do a bunch of FQL queries or hit other actions on the graph API, then you don't actually need offline_access or a current user token if you get the publish_stream permission.  With publish_stream you can post while the user is offline by using your app access token.

A: For the specific "need to push data" scenario, facebook announced new Page object connections that allow you to create post's with a specific publication time. With these in theory you can get rid of the problem by authenticating the users when creating these and let Facebook post them instead of scheduled jobs on your side.

A: here comes 3rd option as a suggestion.
For each authenticated user, you have access_token and expires_in (assume that you have stored them in your db already)
1) Write a scheduled task, that checks existing tokens with their expires_in value
when you find any token close to expiration time,
2) you can renew this token from the server side by HTTP GET call (sample code below)
requestUrl = "https://graph.facebook.com" + "/oauth/access_token"
            + "?" + "client_id="+facebook_appId
            + "&"+"client_secret="+facebook_appSecret
            + "&" + "grant_type=fb_exchange_token"
            + "&" + "fb_exchange_token="+currentToken;

            req = WS.url( requestUrl );
            Logger.info("renew token, req.url : %s", req.url);
            req.timeout = 20;
            resp = req.get();

            // access_token=....&expires=5181096
            Map<String, String> respMap = LocoUtils.decodeUrl( resp.getString() );
            token = respMap.containsKey("access_token")? respMap.get("access_token") : "";

            facebookToken.access_token = token;
            facebookToken.expires_in = respMap.containsKey("expires")?LocoUtils.stringToLong(respMap.get("expires")) : 0L;


text:
Q: Overriding deprecated UIKit methods -- Can I get a warning? Apple sometimes deprecates methods in UIKit that you are expected to override (e.g. [UIViewController shouldAutorotateToInterfaceOrientation:] in iOS 6).
Unfortunately, once you change your deployment target to the version where it's fully deprecated, there is no warning/error produced even though the method is deprecated and will never be called...ever.
If you CALL a deprecated method, you get a warning, but not if you override one.
I'd like to be able to find all my deprecated methods I'm overriding so I can clean them out over time.
Is there any easy way to do this?
Thanks,
-Vince

A: You should have build warnings about using deprecated functions.
There's an article here on making sure they are enabled in Xcode, but it is quite old:
http://blog.mro.name/2010/06/xcode-missing-deprecated-warnings/
Here's an Xcode 4.5 screen shot:


text:
Q: Gallery Position After scrolling I have a gallery with 7 images.
How can I get the position when stop the scrolling of a Gallery?

A: For reference you can handle the setOnItemSelectedListenerof the Galley component to do this.
    // Gallery On Item Selected
    mGallery.setOnItemSelectedListener(new OnItemSelectedListener() {

        // On Item Selected
        public void onItemSelected(CustomAdapterView<?> parent, View view,
                int position, long id) {

            // Do some custom action here!

        }
        //>

        // On Nothing Selected
        public void onNothingSelected(CustomAdapterView<?> parent) {
            // TODO Auto-generated method stub

        }
        //>
    });
    //-->

A: Are you using an Adapter with the Gallery? If so, then AdapterView has a getSelectedItemPosition() function that returns an int.
You can subclass the ImageAdapter class and add a function that returns a private int which is always updated to the index of the last 'clicked' image; thus giving you the position of the current image.


text:
Q: squeryl date to long conversion I want to store java.util.Date (or Timestamp) as an int (or Long) in my db using Squeryl.
I'd like to control how the date is transformed to the number and vice versa.
How can I achieve this?
I'm pretty new to scala/squeryl, coming from java/hibernate.
Back in java/hibernate I could create user types and either register them globaly or use them localy on a field with an annotation. This user type defined methods for how to persist the object type to db and how to load it from the db.
I read some of the squeryl and scala docs, noticed two things:

*

*there are custom types

*there is a implicit function mechanism that is called for conversions
I know one of these can help me but I didn't find any good full examples to understand how.
Any help is appreciated!

A: Please see this example :
https://github.com/max-l/squeryl-extended-field-types-example/blob/master/src/main/scala/example/MyCustomTypes.scala
in your case, you subsitute TTimestamp for TLong (the backing JDBC type) and DateTime for Date (you might want consider using the joda date though).
implicit val dateAsLongTEF = new NonPrimitiveJdbcMapper[Long, Date, TLong](longTEF, this) {
  def convertFromJdbc(v: Long) = new Date(v)
  def convertToJdbc(v: Date) = v.getTime
}

implicit val optionDateAsLongTEF =
new TypedExpressionFactory[Option[Date], TOptionLong]
  with DeOptionizer[Long, Date, TLong, Option[Date], TOptionLong]  {

    val deOptionizer = dateAsLongTEF
}

Note: the fact that you use TLong and TOptionLong means that you'll be able to
compare a number column to a long backed column in the DSL.
Update: there is a limitation that prevents re registering a primitive type,
so you'll need to have a wrapper type, I updated the example in the github project...


text:
Q: How to Generate Halide Function with float argument I'm trying to create a (C++) helper function that transforms a lookup table that's computed in my C++ code into a Halide Func which takes a float as an argument and lerps between samples in the LUT.
The use-case here is that the user has generated a tone curve using a spline with a bunch of control points that we want to apply with Halide. So I sample this spline at a bunch of points, and I want to write a Halide function that lets me linearly interpolate between these samples. Here's my current attempt at this:
#include <Halide.h>

using namespace Halide;
using namespace std;

static Func LutFunc(const vector<float> &lut) {
    Func result;
    Var val;

    // Copy the LUT into a Halide Buffer.
    int lutSize = (int) lut.size();
    Buffer<float> lutbuf(lutSize);
    for(int i = 0; i < lut.size(); i++) {
        lutbuf(i) = lut[i];
    }

    // Compute the offset into the LUT along with the blending factor
    // for the 2 samples we'll take.
    auto y = val * ((float) lutSize - 1);
    auto index = clamp(cast<int>(y), 0, lutSize - 2);
    auto fract = y - cast<float>(index);

    // interpolate between the 2 nearest samples
    result(val) = (lutbuf(index) * (1.0f - fract)) + (lutbuf(index + 1) * fract);

    return result;
}

The problem is that if I then try to include this function into my Halide pipeline, I get this error:
Implicit cast from float32 to int in argument 1 in call to "f" is not allowed. Use an explicit cast.

How can I explain to Halide that the argument to this function should be a float, rather than an int?
Here's a short test program for the above, in case it's helpful:
int main(int argc, char *argv[]) {
    vector<float> lut = { 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0 };
    auto f = LutFunc(lut);

    Buffer<float> testData(4);
    testData(0) = 0.05;
    testData(1) = 0.15;
    testData(2) = 0.25;
    testData(3) = 0.35;

    Func testFn;
    Var x;

    testFn(x) = f(testData(x));

    Buffer<float> resultBuf(4);
    testFn.realize(resultBuf);

    for(int i = 0; i < 4; i++) {
        cout << i << " = " << resultBuf(i) << endl;
    }

    return 0;
}

(if there's an easier way to generate these lerping LUT functions (esp if it's able to take advantage of the sampler hardware on GPUs), I'd be interested to know about that too)

A: As you already found, the arguments to Halide::Func are always integer types (int32 by default); this is intrinsic to Halide.
Re: a better way to do lerping, Halide has a built-in lerp() helper: see http://halide-lang.org/docs/namespace_halide.html#a55158f5f229510194c425dfae256d530

A: Ok, so it seems it's not possible to do this with a Func(): Funcs seem like their intended use-case is to encapsulate a transformation on the source data -- they have a constraint that their arguments be integers, and the intended use case is to specify the pixel coordinates of the input.
I think the way to achieve this is to break it up into two parts: a method to transform my LUT into a Halide Buffer, and a second method that takes an Expr as an argument and returns an Expr, implementing the calculation inline, to which we pass the generated buffer.
Here's a revised version of my function that does what I want:
#include <Halide.h>

using namespace Halide;
using namespace std;

static Expr LutInterp(const Buffer<float> &lutbuf, Expr val) {
    // Interpolate the two values nearest the specified input.
    int lutSize = lutbuf.dim(0).extent();
    auto y = val * ((float) lutSize - 1);
    auto index = clamp(cast<int>(y), 0, lutSize - 2);
    auto fract = y - cast<float>(index);
    return (lutbuf(index) * (1.0f - fract)) + (lutbuf(index + 1) * fract);
}

static Buffer<float> LutToBuff(const vector<float> &lut) {
    int lutSize = (int) lut.size();
    Buffer<float> lutbuf(lutSize);
    for(int i = 0; i < lut.size(); i++) {
        lutbuf(i) = lut[i];
    }
    return lutbuf;
}

int main(int argc, char *argv[]) {
    vector<float> lut = { 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0 };
    auto lutbuf = LutToBuff(lut);

    Buffer<float> testData(4);
    testData(0) = 0.05;
    testData(1) = 0.15;
    testData(2) = 0.25;
    testData(3) = 0.35;

    Func testFn;
    Var x;

    testFn(x) = LutInterp(lutbuf, testData(x));

    Buffer<float> resultBuf(4);
    testFn.realize(resultBuf);

    for(int i = 0; i < 4; i++) {
        cout << i << " = " << resultBuf(i) << endl;
    }

    return 0;
}

I'll proceed with this for the time being, and swap it out if I happen upon a better solution in the future.


text:
Q: How can i open excel file by using pandas? File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\util_decorators.py", line 311, in wrapper
return func(*args, **kwargs)
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\excel_base.py", line 457, in read_excel
io = ExcelFile(io, storage_options=storage_options, engine=engine)
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\excel_base.py", line 1419, in init
self._reader = self._engines[engine](self._io, storage_options=storage_options)
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\excel_openpyxl.py", line 525, in init
super().init(filepath_or_buffer, storage_options=storage_options)
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\excel_base.py", line 518, in init
self.book = self.load_workbook(self.handles.handle)
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\excel_openpyxl.py", line 536, in load_workbook
return load_workbook(
File "C:\ProgramData\Anaconda3\lib\site-packages\openpyxl\reader\excel.py", line 317, in load_workbook
reader.read()
File "C:\ProgramData\Anaconda3\lib\site-packages\openpyxl\reader\excel.py", line 281, in read
apply_stylesheet(self.archive, self.wb)
File "C:\ProgramData\Anaconda3\lib\site-packages\openpyxl\styles\stylesheet.py", line 198, in apply_stylesheet
stylesheet = Stylesheet.from_tree(node)
File "C:\ProgramData\Anaconda3\lib\site-packages\openpyxl\styles\stylesheet.py", line 103, in from_tree
return super(Stylesheet, cls).from_tree(node)
File "C:\ProgramData\Anaconda3\lib\site-packages\openpyxl\descriptors\serialisable.py", line 103, in from_tree
return cls(**attrib)
File "C:\ProgramData\Anaconda3\lib\site-packages\openpyxl\styles\stylesheet.py", line 94, in init
self.named_styles = self._merge_named_styles()
File "C:\ProgramData\Anaconda3\lib\site-packages\openpyxl\styles\stylesheet.py", line 114, in _merge_named_styles
self._expand_named_style(style)
File "C:\ProgramData\Anaconda3\lib\site-packages\openpyxl\styles\stylesheet.py", line 124, in _expand_named_style
xf = self.cellStyleXfs[named_style.xfId]
File "C:\ProgramData\Anaconda3\lib\site-packages\openpyxl\styles\cell_style.py", line 185, in getitem
return self.xf[idx]
I wanted to read excel file but it is not working


text:
Q: Regular glyphicons usage in html I'm trying to use glyphicons from glyphicons(dot)com but I couldn't find out how to use them in my code... Should I make some kind of css file (like it's done in bootstrap) or should I link it somehow into my html?
I hope someone knows the answer :) Thanks!

 Clans

If it helps, this is e.g one of my code where I want to use glyphicon (with glyphicon code).
Btw, path is "glyph/glyph/glyph/png"

A: The icons you downloaded are PNGs, I think you should try this:

 Clans

A: For GLYPHICONS use. You need to buy License or use free. If you want to free then you will get small

GLYPHICONS Basic set

.png icons.
Examples of use

All License

GLYPHICONS Basic set
GLYPHICONS Halflings
GLYPHICONS Filetypes
GLYPHICONS Social
All sets in raster files*
Commercial use**

Examples of use

PRO License

GLYPHICONS Basic set
GLYPHICONS Halflings
GLYPHICONS Filetypes
GLYPHICONS Social
All sets in raster files*
All sets in vector files
All sets as a web font
All sets in live HTML/CSS
Future updates for free
Commercial use**

Examples of use

/* Note: You can use @2x and @3x size. */

 /* This is for example */

Only free use GLYPHICONS icon using HTML/CSS from Twitter-Bootstrap file.
Examples of use
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

That's all know about the GLYPHICON.

A: If you are using Boostrap then Glyphicons are already included, so there is no need to link them (providing you already have Bootstrap linked). However, if you are not using Bootstrap you can call just the Glyphicons like Troyer commented:
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css" rel="stylesheet">

You can then display Glyphicons on the page, like so:

Notice the extra glyphicon class before the class for the specific icon.
If you need any more help, check out this page.

A: First you want to give reference to same glyph library which you are using on your page than use span tag to put your glyph
Include this cdn link inside your head tag
 <link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css" rel="stylesheet">

then use your span tag to use glyphicon


text:
Q: Acquire::By-Hash apt option does not work I'm trying to make apt-get use Acquire::By-Hash option, so it will download packages identifying them by cryptographic hash, not by package version. This should prevent race conditions and "Hash Sum Mismatch" errors happening sometimes while trying to apt-get install something.
I can't make apt-get use this method. I tried

*

*Putting Acquire::By-Hash "force"; to /etc/apt/apt.conf.d/51acquire_by_hash

*Changing sources.list:
deb [by-hash=force] http://ftp.us.debian.org/debian/ buster main contrib non-free

*Using -o Acquire::by-hash=force apt-get option
Neither works. apt-get still uses the old method (see the URLs it's requesting)

# apt-get -o Acquire::by-hash=force -o Debug::Acquire::http=true install fortunes
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following NEW packages will be installed:
  fortunes
0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded.
Need to get 1,117 kB of archives.
After this operation, 2,611 kB of additional disk space will be used.
0% [Working]GET /debian/pool/main/f/fortune-mod/fortunes_1.99.1-7_all.deb HTTP/1.1
Host: ftp.us.debian.org
User-Agent: Debian APT-HTTP/1.3 (1.8.2.1)

0% [Waiting for headers]Answer for: http://ftp.us.debian.org/debian/pool/main/f/fortune-mod/fortunes_1.99.1-7_all.deb
HTTP/1.1 200 OK
Date: Sun, 09 Aug 2020 05:28:00 GMT
Server: Apache
Last-Modified: Thu, 15 Aug 2013 03:54:21 GMT
ETag: "110cf4-4e3f46de0807d"
Accept-Ranges: bytes
Content-Length: 1117428

Get:1 http://ftp.us.debian.org/debian buster/main amd64 fortunes all 1:1.99.1-7 [1,117 kB]
Fetched 1,117 kB in 18s (60.6 kB/s)
Selecting previously unselected package fortunes.
(Reading database ... 159825 files and directories currently installed.)
Preparing to unpack .../fortunes_1%3a1.99.1-7_all.deb ...
Unpacking fortunes (1:1.99.1-7) ...
Setting up fortunes (1:1.99.1-7) ...

The mirror supports By-Hash:
$ wget http://ftp.us.debian.org/debian/dists/buster/InRelease 2>/dev/null -O - | grep By-Hash
Acquire-By-Hash: yes

Any ideas how to make apt-get use that options? Thank you.

A: The manual for apt.conf(5) says, for Acquire::By-Hash:

Try to download indexes via an URI constructed from a hashsum of the expected file

(my emphasis)
In my testing the following worked as expected (after cleaning out /var/lib/apt/lists, which apt clean didn't seem to do a good job of). Since I have a local mirror I could verify the requested indexes from its log too:
apt{,-get} update -o Acquire::By-Hash="force" -o Debug::Acquire::http=true

so the manual is correct and accurate. Acquiring the packages themselves by hash is not supported, only the indexes.


text:
Q: How do I solve old selected is not working in Laravel 7 I have a "select" and I need to keep selected the "option" after a request.
But after send a request the old value is not retrieved.
I'm using laravel 7.
The code is:
<select name="select1" id="select1">
<option value="">Select an option...</option>
@foreach($sites as $s)
    <option value="{{ $s->id }}" {{ old('select1') == $s->id ? 'selected' : '' }} >{{$s->nome </option>
@endforeach
</select>

A: You need to use the ->with() function in your controller after the redirect:
return redirect('Your redirection')->with('select1', $request->select1);

Then replace {{ old('select1') == $s->id ? 'selected' : '' }} with:
@if(Session::get('select1') == $s->id) selected @endif

The option should look like
<option value="{{ $s->id }}" @if(Session::get('select1') == $s->id) selected @endif>{{$s->nome}} </option>


text:
Q: How to implement 'reverse application function' in C++? I am writing the C++ part of my project which has OCaml as the main language. I much more experienced with OCaml then C++.
I use name binding (in OCaml, variable in C++) when this name is a conceptual point of the logic (to highlight it) or when this name is expected as an argument by more than one function (Possibly, I use it in other cases too, but it isn't important for current context). The following 4 variables look for me more than redundant. As for me they make information noise and decrease code readability.
auto caml_level = Caml::Value::of_int(level);
auto caml_api_state = Core::Api::File::open_new(caml_level);
auto polimorpic_variant_hash_status =
  _api -> extract_and_save_state(caml_api_state);
auto status = statuses.at(polimorpic_variant_hash_status);

That's why I had written code that computes status without using any additional variables.
auto status =
  statuses.at(
    _api -> extract_and_save_state(
      Core::Api::File::open_new(
        Caml::Value::of_int(
          level
        )
      )
    )
  );

As for me, the second sample looks better but still unsatisfiable because it is necessary to read this code from down to up. Can I reverse the order of functions to provide the ability to read it up to down? Is it possible to write it as in the 3rd sample where we imagine that C++ has OCaml |> operator?
auto status =
  level |> Caml::Value::of_int
        |> Core::Api::File::open_new
        |> _api -> extract_and_save_state
        |> statuses.at

How to implement a reverse application function in C++?
(These examples are from my trying to implement a bridge between OCaml and C++ with good readability. The bridge contains a lot of conversions like from C int to OCaml int and vise versa, so, potentially it has a lot of variables. And these variables are results of low-level operations, not conceptual points. So, it is not easy to give them good names).

A: C++ doesn't let you define new infix operators, so you will have to use identifiers.
Let's assume you are happy to have | rap > (spaces optional) instead of |>.
struct rap_t {
    template <typename F>
    struct wrapper_t { F f; };

    template <typename F>
    friend wrapper_t<F> operator>(rap_t, F&& f) { return { std::forward<F>(f) }; }

    template <typename T, typename F>
    friend std::invoke_result_t<F, T> operator|(T&& t, wrapper_t<F> w)
    { return std::invoke(std::forward<F>(w.f), std::forward<T>(t)); }
} rap;

That allows you to
auto reuslt =
  level |rap> &Caml::Value::of_int
        |rap> &Core::Api::File::open_new
        |rap> std::bind_front(&Api::extract_and_save_state, _api)
        |rap> &results.at


text:
Q: How to Read Remote Registry Keys? I need to be able to read the values in a specific Registry Key from a list of Remote Computers.
I can do this locally with the following code
   using Microsoft.Win32;

        RegistryKey rkey = Registry.LocalMachine;
        RegistryKey rkeySoftware=rkey.OpenSubKey("Software");
        RegistryKey rkeyVendor = rkeySoftware.OpenSubKey("VendorName");
        RegistryKey rkeyVersions = rkeyVendor.OpenSubKey("Versions");

        String[] ValueNames = rkeyVersions.GetValueNames();
        foreach (string name in ValueNames)
        {
          MessageBox.Show(name + ": " + rkeyVersions.GetValue(name).ToString());
        }

but I don't know how to get the same info for a Remote Computer. Am I even using the right approach or should I be looking at WMI or something else?

A: This is the solution I went with in the end:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

// add a reference to Cassia (MIT license)
// https://code.google.com/p/cassia/

using Microsoft.Win32;

namespace RemoteRegistryRead2
{
    class Program
    {
        static void Main(string[] args)
        {
            String domain = "theDomain";
            String user = "theUserName";
            String password = "thePassword";
            String host = "machine-x11";

            using (Cassia.UserImpersonationContext userContext = new Cassia.UserImpersonationContext(domain + "\\" + user, password))
            {
                string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
                System.Console.WriteLine("userName: " + userName);

                RegistryKey baseKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, host);
                RegistryKey key = baseKey.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName");

                String computerName = key.GetValue("ComputerName").ToString();
                Console.WriteLine(computerName);
            }
        }
    }
}

Works like a charm :]

A: You can achieve this through WMI, although I think you can also achieve it via the same mechanism (i.e. Microsoft.Win32 namespace classes) that you're currently using.
You need to look into the:
OpenRemoteBaseKey Method
The link above gives examples.  It's should be as simple as something like:
// Open HKEY_CURRENT_USER\Environment
// on a remote computer.
environmentKey = RegistryKey.OpenRemoteBaseKey(
                   RegistryHive.CurrentUser, remoteName).OpenSubKey(
                   "Environment");

Note, though, that'll there will be security implications in opening remote registry keys, so you may need to ensure that you have the relevant security permissions to do this.  For that, you'll want to look into the:
SecurityPermission
and
RegistryPermission
classes in the System.Security.Permissions namespace.

A: I found that I could as CraigTP showed use the OpenRemoteBaseKey() method however it required me to change the permissions in the registry on the dest computers.
Here is the code I wrote that worked once I changed the permissions.
RegistryKey rkey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, "RemoteComputer");
RegistryKey rkeySoftware = rkey.OpenSubKey("Software");
RegistryKey rkeyVendor = rkeySoftware.OpenSubKey("VendorName");
RegistryKey rkeyVersions = rkeyVendor.OpenSubKey("Versions");

String[] ValueNames = rkeyVersions.GetValueNames();
foreach (string name in ValueNames)
{
    MessageBox.Show(name + ": " + rkeyVersions.GetValue(name).ToString());
}

I also found that I could get the same info using WMI without having to modify the permissions. Here is the code with WMI.
ManagementScope ms = new ManagementScope();
ms.Path.Server = "flebbe";
ms.Path.NamespacePath = "root\\default";
ms.Options.EnablePrivileges = true;
ms.Connect();

ManagementClass mc = new ManagementClass("stdRegProv");
mc.Scope = ms;

ManagementBaseObject mbo;
mbo = mc.GetMethodParameters("EnumValues");

mbo.SetPropertyValue("sSubKeyName", "SOFTWARE\\VendorName\\Versions");

string[] subkeys = (string[])mc.InvokeMethod("EnumValues", mbo, null).Properties["sNames"].Value;

ManagementBaseObject mboS;
string keyValue;

foreach (string strKey in subkeys)
{
    mboS = mc.GetMethodParameters("GetStringValue");
    mboS.SetPropertyValue("sSubKeyName", "SOFTWARE\\VendorName\\Versions");
    mboS.SetPropertyValue("sValueName", strKey);

    keyValue = mc.InvokeMethod("GetStringValue", mboS, null).Properties["sValue"].Value.ToString();
    MessageBox.Show(strKey + " : " + keyValue);
}

P.S.
I am calling the GetStringValue() method in the loop as I know all the values are strings. If there are multiple data types you would need to read the datatype from the Types output parameter of the EnumValues method.

A: The win32 API allows you to specify a computer name through RegConnectRegistry. I'm not sure that the .NET wrappers exposes this. You can also use WMI as you mentioned.

A: Look up OpenRemoteBaseKey().

A: A commenter on my blog asked me to post my solution on stack overflow, so here it is.
How to authenticate and access the registry remotely using C#
It is basically the same as CraigTP's answer, but it includes a nice class for authenticating to the remote device.
And the code is in production and tested.

A: Easy example in c# installed programs via windows registry (remote: OpenRemoteBaseKey)
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace SoftwareInventory
{
    class Program
    {
        static void Main(string[] args)
        {
            //!!!!! Must be launched with a domain administrator user!!!!!
            Console.ForegroundColor = ConsoleColor.Green;
            StringBuilder sbOutFile = new StringBuilder();
            Console.WriteLine("DisplayName;IdentifyingNumber");
            sbOutFile.AppendLine("Machine;DisplayName;Version");

            //Retrieve machine name from the file :File_In/collectionMachines.txt
            //string[] lines = new string[] { "NameMachine" };
            string[] lines = File.ReadAllLines(@"File_In/collectionMachines.txt");
            foreach (var machine in lines)
            {
                //Retrieve the list of installed programs for each extrapolated machine name
                var registry_key = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
                using (Microsoft.Win32.RegistryKey key = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, machine).OpenSubKey(registry_key))
                {
                    foreach (string subkey_name in key.GetSubKeyNames())
                    {
                        using (RegistryKey subkey = key.OpenSubKey(subkey_name))
                        {
                            //Console.WriteLine(subkey.GetValue("DisplayName"));
                            //Console.WriteLine(subkey.GetValue("IdentifyingNumber"));
                            if (subkey.GetValue("DisplayName") != null)
                            {
                                Console.WriteLine(string.Format("{0};{1};{2}", machine, subkey.GetValue("DisplayName"), subkey.GetValue("Version")));
                                sbOutFile.AppendLine(string.Format("{0};{1};{2}", machine, subkey.GetValue("DisplayName"), subkey.GetValue("Version")));
                            }
                        }
                    }
                }
            }
            //CSV file creation
            var fileOutName = string.Format(@"File_Out\{0}_{1}.csv", "Software_Inventory", DateTime.Now.ToString("yyyy_MM_dd_HH_mmssfff"));
            using (var file = new System.IO.StreamWriter(fileOutName))
            {

                file.WriteLine(sbOutFile.ToString());
            }
            //Press enter to continue
            Console.WriteLine("Press enter to continue !");
            Console.ReadLine();
        }

    }
}


text:
Q: CardView elevation not working on Android 5.1.1 I am using CardView inside a RecyclerView.
After reading a lot I ended up with following 'NOT WORKING' code only on Android 5.1.1. On Android Version prior to this one its working nice.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#11ffffff"
    android:orientation="vertical"
    android:paddingBottom="10dp">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#11ffffff">
        <android.support.v7.widget.CardView
            android:id="@+id/card_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:background="@color/primary_bg_light"
            card_view:cardCornerRadius="2dp">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="@color/primary_bg_light">

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_alignParentBottom="true"
                        android:paddingBottom="15dp"
                        android:paddingLeft="15dp"
                        android:textColor="@color/background_floating_material_light"
                        android:textSize="24sp"
                        android:textStyle="bold" />

                </RelativeLayout>
        </android.support.v7.widget.CardView>
    </RelativeLayout>
</LinearLayout>

I did try setting elevation using code also but same result.

A: Just simply add this code to your Card View in xml file!
    card_view:cardUseCompatPadding="true"

You have to import card_view with Alt+Enter !
And code below will be import in top !.
  xmlns:card_view="http://schemas.android.com/apk/res-auto"

You'll see elevation is working on android 5 or 5+ .

A: Remove below line if you used in AndroidManifest.xml
android:hardwareAccelerated="false"

A: remove this line from <application ...> </application> in AndroidManifest.xml file
android:hardwareAccelerated="false"

change to
android:hardwareAccelerated="true"

for more details Hardware acceleration

A: To make it both compatible above or below api 21, you need to specify  app:cardUseCompatPadding="true" in your support CardView.
<android.support.v7.widget.CardView
        app:cardElevation="4dp"
        app:cardUseCompatPadding="true"
        app:cardMaxElevation="6dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
</android.support.v7.widget.CardView>

A: set in card view
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="6dp"
card_view:cardUseCompatPadding="true"
card_view:cardElevation="4dp"
card_view:cardCornerRadius="3dp">


text:
Q: How to port code using Windows conio.h to Linux? I wrote this C program for Win32/c compiler but while i'm trying run this  using gcc in Linux  machine or codepad.org it shows 'conio.h: No such file or directory compilation terminated' What are modification to be done to execute this program without including any other new includes like curses.h
#include<stdio.h>
#include<conio.h>
void main()
  {
   int i=0,j=0,k=0,n,u=0;
   char s[100],c2,c[10];
   char c1[3]={'a','b','c'};
   clrscr();
   printf("no of test cases:");
   scanf("%d",&n);
  for(u=0;u<n;u++)
    {
 printf("Enter the string:");
 scanf("%s",s);
  i=0;
 while(s[i]!='\0')
  {
     if(s[i+1]=='\0')
         break;
     if(s[i]!=s[i+1])
     {
      for(j=0;j<3;j++)
       {
    if((s[i]!=c1[j])&&(s[i+1]!=c1[j]))
    {
      c2=c1[j];
     }
}
    s[i]=c2;

  for(k=i+1;k<100;k++)
    {
 s[k]=s[k+1];
}
  i=0;
  }
  else
  i++;
}
c[u]=strlen(s);

}
for(u=0;u<n;u++)
printf("%d\n",c[u]);
 getch();
}

A: It looks like the only functions you're using from conio.h are clrscr() and getch().  Just take those out and you should be fine - they don't appear to affect the operation of the program.  They're being used here more like workarounds for windows terminal behaviour.
A couple of notes:

*

*main() should return int.

*strlen() is defined in string.h - you'll probably want to include that.

A: Reviewing your question I can see that for clrscr() and getch() you are using conio.h But this header is not available in gcc. So for clrscr use
system("clear");

and as you have mentioned for getch() use the curses library
Cheers !!

A: I did not look at your code to see if it needs the three functions. But this is the simplist way to get them.  There is normaly a better way than using getch(). clrscr() is also no fun when you clear my screen !
#include<stdio.h>
#include <stdlib.h>  // system
#include <string.h>  // strlen
#include <termios.h> // getch
#include <unistd.h>  // getch

void clrscr()
{
  // Works on systems that have clear installed in PATH
  // I don't like people clearing my screen though
  system("clear");
}

int getch( )
{
  struct termios oldt, newt;
  int ch;

  tcgetattr( STDIN_FILENO, &oldt );
  newt = oldt;
  newt.c_lflag &= ~( ICANON | ECHO );
  tcsetattr( STDIN_FILENO, TCSANOW, &newt );
  ch = getchar();
  tcsetattr( STDIN_FILENO, TCSANOW, &oldt );
  return ch;
}

getch()


text:
Q: Ruby 2D arrays need some explanation please I have recently started working with 2D arrays in Ruby. Can someone explain why total is set to 0 in this case and also what function has "do" and "double pipes" in this case?
Thank you! See below.
def two_d_sum(arr)
 total = 0

 arr.each do |sub_array|
    sub_array.each do |num|
      total += num
    end
  end
  return total
end

A: Total is being set to 0 so that you can add to it using the += operator inside of the block.
The do || ...end syntax is a block of code that is being passed to the each method. each runs the block of code for each item inside of the array. So here you are looping through each outer array then you are looping through the inner array and adding the value to total.
In ruby most people don't use return at the end of the method because the last value is always returned.
Here are a few other ways this same method could be implemented.
# flatten the 2D array into a normal array then sum
def two_d_sum(arr)
  arr.flatten.sum
end

# inject 0 with the sum of the arrays
def two_d_sum(arr)
  arr.inject(0) do |memo, array|
    memo + array.sum
  end
end

The inject example might be a bit confusing while you are learning, but the idea is that the block is run for each item in array and the return value of the block is passed as 'memo' for the next loop, and at the end the 'memo' is returned.


text:
Q: Processing Data After Linq to SQL Call I've been using LINQ to SQL for a while, and most of the time I end up creating a complex linq expressions using SQLFunctions and DbEntities classes to mimic functions such as toString or DateTime formating (e.g. Linq to SQL Format Date time in One Take) not available in Linq to SQL.
I always thought that this is much cleaner than forcing query execution using ToList() and then using linq again but this time with objects with all the available functions. My questions is, which is a better approach, try to stuff everything in one Linq to SQL expression with efforts to format the data and everything, or go the easy way and just extract the data in one step and then process it using ForEach on the resulting list from the first query.


text:
Q: How can I push the derivative through the following sum? Let $f$ be a probability density and $F$ the corresponding distribution function. In other words $f$ is non-negative, integrates to 1, and $F' = f$. I'm interested in the following:
$$
\frac{d}{dx}\sum_{i\in\mathbb{Z}}F(i+x)-F(i)\stackrel{?}{=}\sum_{i\in\mathbb{Z}}f(i+x)
$$
I'm doubtful that this result holds in general. But what if I add assumptions such as that $f$ be Lipschitz-continuous?

A: It suffices to show that $\sum_{i\in\mathbb{Z}}F(i+x)-F(i)$ is a primitive function of $\sum_{i\in\mathbb{Z}}f(i+x)$.
\begin{align}
& \int_0^x \sum_{i\in\mathbb{Z}}f(i+t) dt \\
=& \sum_{i\in\mathbb{Z}} \int_0^x f(i+t) dt \tag{Fubini-Tonelli Theorem} \\
=& \sum_{i\in\mathbb{Z}} (F(x+i)-F(i))
\end{align}
The result follows from the Fundamental Theorem of Calculus.


text:
Q: what do you call it when you suddenly remember something? Suppose, you and your friends are hanging out. One of your friends brings up a topic. Suddenly, a funny thing that has happened in the past, comes to your mind. what do you say? Do you say:
"I just remembered a funny thing...."
That sounds odd to me. That is why I'm asking the question. Which verb would you use?

A: In American English it's common to start that kind of response with "It's funny, [...]". For example, if someone told you they found a hundred dollars on the street last week, you might say, "It's funny, me too!" A few other ways of opening stories are "This one time, ..." or "I remember this once, ..." These are all very colloquial examples but seem appropriate for the situation you described.


text:
Q: Multiple attribute symbology in ArcMap I have a layer I need to symbolise with graduated colours based on one field and graduated symbols based on another field.
Sizes are based on a field that stores a count (range 1 to 50).  Colours are based on a field that stores cost (range 0 to 7500).
I set up Symbology by selecting Multiple Attributes, choosing my Count field and manually setting the sizes, then selecting Variation by Colour Ramp and choosing my Cost field for the ramp.
It has mostly worked, except it's not using quite the same colour ramp as I selected.  The two highest values are using the same colour, and I can't find a way to update it.
Symbology > Multiple Attributes:

Colour Ramp:

End result (note the high values are still yellow, not red):

The largest point on the map in my screenshot above should be coloured red, as the value for this point is over $4000.
Has anyone had success in setting symbology this way?  What do I need to do/change to get this to work?

A: This is a bug.  It is using the color ramp, but only a small portion of it.  It doesn't matter how you change the settings, you're not going to get the full color ramp for your points.  You will only get a small section of the color ramp.  You may be able to improve the color range by increasing the number of classes, changing the class break values, or adjusting the range.  Please post a comment if any of those tests work for you.


text:
Q: How do you automatically set the foreign key on a new object from an ActiveRecord relationship if the class names don't match? The following class is a subclass of Quote using single table inheritance.
class BuyQuote < Quote
  has_many :shipment_quotes, foreign_key: :quote_id
  has_many :shipments, through: :shipment_quotes
end

I'd like to create a shipment using the standard ActiveRecord new method.
quote = BuyQuote.create
shipment = quote.shipments.new

But, the relationship is not being set between the shipment and the quote. I assume that this is due to the class name being different than expected, but I'm not sure.
How can I modify the ActiveRecord relationship so that this will work?

A: Looks like you have some syntax errors in your posted code and potentially an incorrect table name.  If the lookup table doesn't need any additional attributes (other than relating the Shipment to the Quote), I would just use the simplistic has_and_belongs_to_many relationship.  This depends on if you plan to have a shipment associated with more than one quote.
class BuyQuote < Quote
  has_many :shipments_quotes, :foreign_key => :quote_id
  has_many :shipments, :through => :shipments_quotes
end

or with habtm relationship:
class BuyQuote < Quote
  has_and_belongs_to_many :shipments, :foreign_key => :quote_id
end

Another issue could be because you are instantiating a Quote class, which you aren't showing the definition for.  You seem to be defining the "shipments" relationship for the BuyQuote class, but not for the parent class Quote.
Maybe try:
quote = BuyQuote.create
shipment = quote.shipments.new


text:
Q: Does "find" return nodes in order? Do XML::LibXML::Node::find and related methods guarantee that the list of nodes will always be ordered as in the XML document?
This is important for me because my document corresponds to a big array in which I want to be able to delete series of items in certain circumstances, and I must make sure something like this works consistently:
my @nodes = $dom->find('//MyElement[@attr=something]/descendant::Token/@id')
                ->get_nodelist;
for my $token ( reverse map { $_->value } @nodes ) {
    splice @my_big_array, $token, 1;
}

The difficulty is that this is not documented in XML::LibXML, and I don't know whether this depends on libxml2 implementation, whose documentation I don't really understand, or on the DOM standard or some other W3C standard, which were clearly not written to be read my mere mortals.

A: To my best knowledge the current XML standard does care about the order of the nodes and the current implementaion of XML::LibXML will give you back the same order every time.
See more: In XML, is order important?, Does XML care about the order of elements?
Good reading about this: http://www.ibm.com/developerworks/xml/library/x-eleord/index.html
1: Its needs to be ordered some way so each run of the same parser should return the same result. 99% of parsers uses the order in xml file the remaining ones orders by the order in the schema

The XML Information Set (InfoSet -- see Resources), the core XML data
  model defined by the W3C, characterizes element children as: An
  ordered list of child information items, in document order.

2: The ordering could enforced or removed

The ampersand (&) characters between the sibling element subpatterns
  indicate that any order is acceptable.

element memo {
  element title { text } &
  element date { text } &
  element from { text } &
  element to { text } &
  element body { text }
}

A: I essentially answered this in a related question. XML::LibXML calls xmlXPathCompile from libxml2 which makes sure that the resulting node-set will be sorted in document order.


text:
Q: Odd merge on git hub Our git hub is showing a wierd merge.  I had made a couple small changes to our master branch on git hub and then merged the branch into our develop branch.  However at the same time as the merge from master to develop Master is showing a merge from develop into master, however the associated pull request is for the merge from master into develop.
Is this just a bug in the reporting?
Here are screen shots of the merges.


text:
Q: Android HttpURLConnection, HttpClient coexistence and connections limits I have taken over maintaining an Android app that has been built to use both HttpURLConnection and HttpClient from threads. A new instance is used each time, rather than reusing a shared instance (I know that this is not good practice, at least for HttpClient, and I intend to change it). Most of the connections are made to the same server; I find that when some connections are busy, other threads are blocked.
I understand from Android HttpClient performance that  HttpClient per default allows only two concurrent connections to the same target host.
I also see from the answer in URLConnection or HTTPClient : Which offers better functionality and more efficiency? that with HttpUrlConnection concurrent connections to the same host get serialized.
How do I change the concurrent connections limit for HttpClient and HttpUrlConnection?
Can HttpURLConnection and HttpClient coexist in the same app without problems, or would it be better to use just one of them?
Thanks.

A: Google has stated that HttpClient is no longer being maintained in Android, which basically means, that it may stick around, but they are not going to enhance it.  They prefer that people use HttpUrlConnection, HttpUrlConnection has some bugs depending on the version of Androind :(  (you can read more about both choices on the Android Developer Blog http://android-developers.blogspot.ca/2011/09/androids-http-clients.html)
Personally, I'd take a look at OkHttp (by Square) since it provides an almost drop in replacement for HttpUrlConnection but it offers connection pooling and SPDY support.
http://square.github.io/okhttp/


text:
Q: Can I set the parameters in a matlab function in simulink to be tunable? I want to tune some parameters of a matlab function block in simulink with Dashboard Blocks like knobs. But when i click on the matlab function with the parameter I want to tune, it says that this block has no tunable parameters. How can I change this?

A: To my knowledge there is no way to get a tunable parameter in such a block. To get the functionality, I recommend make an input port out of the parameter you want to tune. Then connect it to a constant block and tune the constant instead.


text:
Q: tcl : error when execute grep with option w I execute the following command under tclsh
exec sh -c "grep -w $string $file"

when the $string is not matched in the $file I got the following error :
child process exited abnormally
how to avoid this errror

A: If the pattern is not found, grep would return 1, which exec interprets as an error and shows you the above message.
you should test the return of the grep command or add the '-q' parameter, if you want to avoid that message:
http://www.gnu.org/software/grep/manual/html_node/Exit-Status.html

A: When a subprocess exits with a non-zero exit code, exec generates an error. When you're dealing with a command such as grep where the non-zero code is also generated when things are simply not found at all.
The simplest way of dealing with this is listed in the Tcl 8.6 exec manual page:
try {
    set results [exec grep foo bar.txt]
    set status 0
} trap CHILDSTATUS {results options} {
    set status [lindex [dict get $options -errorcode] 2]
}

(The manual page also describes how to handle the problem in earlier versions. The code is quite a lot uglier.)
Note that you can get the same error when you close a pipeline containing a failing grep. It's the same mechanism.


text:
Q: azure App registration using powershell does not create a service principal when we create an azure ad app registration from the azure portal  the service principal is automatically created, and given a contributors role, how do we achieve the same using PowerShell ?
I tried running the following the command the app is created but no service principal is created, and there are no  parameters for configuring a service principle
New-AzADApplication -DisplayName "NewApplication" -HomePage "http://www.microsoft.com" -IdentifierUris "http://NewApplication"

what i am looking for is to create the following using powershell, is this possible ?

*

*AzureADAppregistration + ServicePrincipal

*Create and get the client secret

Thanks

A: Try this:
#set your secret here.
$secretTextValue = "abcdefg1234567890"

$secret = ConvertTo-SecureString -String $secretTextValue -AsPlainText

$app = New-AzADApplication -DisplayName "NewApplication" -HomePage "http://www.microsoft.com" -IdentifierUris "http://NewApplication"

New-AzADAppCredential -ObjectId $app.ObjectId -Password $secret -EndDate (Get-Date).AddMonths(6)

#azure will assign contributor role of current subscription to this SP
New-AzADServicePrincipal -ApplicationId $app.ApplicationId

Result:


text:
Q: Is it possible to only use lock and condition to get ABCABC result I try to get the result like this, ABCABCABCABCABC. I have already implemented it by using a flag to indict the current print state. However, I think I can remove the flag to implement the same function. But after my modification, the code is blocked in the construct of AlternateDemo. I could not find the root cause. Could anyone tell me the reason?
My code is below.
NOTE: thread-A is like A, thread-B is like B, and thread-C is like C
package edu.seu.juc.problem;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TestABCAlternateOnlyCondition {
    public static void main(String[] args) {
        AlternateDemo demo = new AlternateDemo();

        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                demo.loopA(i);
            }
        }, "thread-A").start();

        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                demo.loopB(i);
            }
        }, "thread-B").start();

        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                demo.loopC(i);
            }

            System.out.println("-------------------------------------");
        }, "thread-C").start();
    }

    private static class AlternateDemo {
        private Lock lock = new ReentrantLock();
        private Condition conditionA = lock.newCondition();
        private Condition conditionB = lock.newCondition();
        private Condition conditionC = lock.newCondition();

        public AlternateDemo() {
            lock.lock();

            try {
                conditionB.await();
                conditionC.await();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }

        public void loopA(int totalLoop) {
            lock.lock();

            try {
                conditionA.await();
                for (int i = 0; i < 1; i++) {
                    System.out.println(Thread.currentThread().getName() + "\t" + i + "\t" + totalLoop);
                }

                conditionB.signalAll();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }

        public void loopB(int totalLoop) {
            lock.lock();

            try {

                conditionB.await();

                for (int i = 0; i < 1; i++) {
                    System.out.println(Thread.currentThread().getName() + "\t" + i + "\t" + totalLoop);
                }

                conditionC.signalAll();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }

        public void loopC(int totalLoop) {
            lock.lock();

            try {
                conditionC.await();

                for (int i = 0; i < 1; i++) {
                    System.out.println(Thread.currentThread().getName() + "\t" + i + "\t" + totalLoop);
                }

                conditionA.signalAll();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
}

A: You can also add a flag to control thread to be awaited.
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TestABCAlternateOnlyCondition {
    public static void main(String[] args) {
        AlternateDemo demo = new AlternateDemo();

        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                demo.loopA(i);
            }
        }, "thread-A").start();

        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                demo.loopB(i);
            }
        }, "thread-B").start();

        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                demo.loopC(i);
            }

            System.out.println("-------------------------------------");
        }, "thread-C").start();
    }

    private static class AlternateDemo {
        private Lock lock = new ReentrantLock();
        private Condition conditionA = lock.newCondition();
        private Condition conditionB = lock.newCondition();
        private Condition conditionC = lock.newCondition();
        private static int nextThread = 1; // control thread to await

        public void loopA(int totalLoop) {
            lock.lock();

            try {
                while (nextThread != 1) {
                    conditionA.await();
                }
                for (int i = 0; i < 1; i++) {
                    System.out.println(Thread.currentThread().getName() + "\t" + i + "\t" + totalLoop);
                }
                nextThread = 2;
                conditionB.signalAll();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }

        public void loopB(int totalLoop) {
            lock.lock();

            try {

                while (nextThread != 2) {
                    conditionB.await();
                }

                for (int i = 0; i < 1; i++) {
                    System.out.println(Thread.currentThread().getName() + "\t" + i + "\t" + totalLoop);
                }
                nextThread = 3;
                conditionC.signalAll();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }

        public void loopC(int totalLoop) {
            lock.lock();

            try {
                while (nextThread != 3) {
                    conditionC.await();
                }

                for (int i = 0; i < 1; i++) {
                    System.out.println(Thread.currentThread().getName() + "\t" + i + "\t" + totalLoop);
                }
                nextThread = 1;
                conditionA.signalAll();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
}

A: Thank you for the hints from @root. Now, I can solve the problem by only using the semaphore.
The code is below,
package edu.seu.juc.problem;

import java.util.concurrent.Semaphore;

/**
 * @author: zs.sun
 * Create at: 2020/5/25 8:59
 * @Package: edu.seu.juc.problem
 * @ProjectName: af-study
 * @Description:
 */
public class TestABCAlternateOnlyCondition {
    public static void main(String[] args) {
        AlternateDemo demo = new AlternateDemo();

        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                demo.loopA(i);
            }
        }, "thread-A").start();

        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                demo.loopB(i);
            }
        }, "thread-B").start();

        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                demo.loopC(i);
            }

            System.out.println("-------------------------------------");
        }, "thread-C").start();
    }

    private static class AlternateDemo {
        private Semaphore semaphoreA = new Semaphore(1);
        private Semaphore semaphoreB = new Semaphore(1);
        private Semaphore semaphoreC = new Semaphore(1);

        public AlternateDemo() {
            try {
                // NOTE: init the status at the beginning
                semaphoreB.acquire();
                semaphoreC.acquire();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public void loopA(int totalLoop) {

            try {
                semaphoreA.acquire();
                for (int i = 0; i < 1; i++) {
                    System.out.println(Thread.currentThread().getName() + "\t" + i + "\t" + totalLoop);
                }

                semaphoreB.release();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public void loopB(int totalLoop) {
            try {

                semaphoreB.acquire();

                for (int i = 0; i < 1; i++) {
                    System.out.println(Thread.currentThread().getName() + "\t" + i + "\t" + totalLoop);
                }

                semaphoreC.release();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public void loopC(int totalLoop) {

            try {
                semaphoreC.acquire();

                for (int i = 0; i < 1; i++) {
                    System.out.println(Thread.currentThread().getName() + "\t" + i + "\t" + totalLoop);
                }

                semaphoreA.release();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}


text:
Q: "Bad Request Exception" when trying to use AWS Transcribe using Python to transcribe a voice data sent as JSON dump using websocket I am trying to use AWS transcribe using Python. Please do not suggest boto.
Please do look into this and suggest me what I should do to fix the error.
The response I receive is:

b'\x00\x00\x00\xa3\x00\x00\x00ah\x10k\xe1\x0f:exception-type\x07\x00\x13BadRequestException\r:content-type\x07\x00\x10application/json\r:message-type\x07\x00\texception{"Message":"Unexpected
  WebSocket frame received."}\xbd\xceK\x8a'

This goes on till I terminate it myself.
The code to transcribe. Please fill in your AWS key and secret to replicate.
Thanks in advance.
import asyncio
import websockets
import json
import sys, os, base64, datetime, hashlib, hmac, urllib
import pyaudio
import struct
import numpy as np

audio = pyaudio.PyAudio()
text = ""
voice_data = {}

def createPresignedUrl(data):
    method = 'GET'
    service = 'transcribe'
    region = data['region']
    host = 'transcribestreaming.' + region + '.amazonaws.com:8443'
    endpoint = "wss://" + host

    def sign(key, msg):
        return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()

    def getSignatureKey(key, dateStamp, regionName, serviceName):
        kDate = sign(('AWS4' + key).encode('utf-8'), dateStamp)
        kRegion = sign(kDate, regionName)
        kService = sign(kRegion, serviceName)
        kSigning = sign(kService, 'aws4_request')
        return kSigning

    access_key = data['key']
    secret_key = data['secret']
    if access_key == '' or secret_key == '':
        print('No access key is available.')
        sys.exit()

    # Create a date for headers and the credential string
    t = datetime.datetime.utcnow()
    amz_date = t.strftime('%Y%m%dT%H%M%SZ') # Format date as YYYYMMDD'T'HHMMSS'Z'
    datestamp = t.strftime('%Y%m%d') # Date w/o time, used in credential scope

    canonical_uri = '/stream-transcription-websocket'

    canonical_headers = 'host:' + host + '\n'
    signed_headers = 'host'

    algorithm = 'AWS4-HMAC-SHA256'
    credential_scope = datestamp + '/' + region + '/' + service + '/' + 'aws4_request'

    canonical_querystring  = 'X-Amz-Algorithm=AWS4-HMAC-SHA256'
    canonical_querystring += '&X-Amz-Credential=' + urllib.parse.quote_plus(access_key + '/' + credential_scope)
    canonical_querystring += '&X-Amz-Date=' + amz_date
    canonical_querystring += '&X-Amz-Expires=300'
    canonical_querystring += '&X-Amz-SignedHeaders=' + signed_headers
    canonical_querystring += '&language-code=' + data['languageCode']
    canonical_querystring += '&media-encoding=pcm'
    canonical_querystring += '&sample-rate=' + str(data['sampleRate'])

    payload_hash = hashlib.sha256(('').encode('utf-8')).hexdigest()

    # Step 6: Combine elements to create canonical request
    canonical_request = method + '\n' + canonical_uri + '\n' + canonical_querystring + '\n' + canonical_headers + '\n' + signed_headers + '\n' + payload_hash

    string_to_sign = algorithm + '\n' +  amz_date + '\n' +  credential_scope + '\n' +  hashlib.sha256(canonical_request.encode('utf-8')).hexdigest()

    # Create the signing key
    signing_key = getSignatureKey(secret_key, datestamp, region, service)

    # Sign the string_to_sign using the signing_key
    signature = hmac.new(signing_key, (string_to_sign).encode("utf-8"), hashlib.sha256).hexdigest()

    canonical_querystring += '&X-Amz-Signature=' + signature

    request_url = endpoint + canonical_uri + "?" + canonical_querystring

    return request_url

data = {
    'key': '',
    'secret': '',
    'region': 'us-east-1',
    'languageCode': 'en-US',
    'sampleRate': 44100
}

url = createPresignedUrl(data)

FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
CHUNK = 4096

stream = audio.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK)

def pcmEncode(in_data):
    offset = 0
    input_len = len(in_data)
    buffer = []

    for i in range(input_len):
        offset += 2
        s = max(-1, min(1, in_data[i]))
        b = (s * 32768) if (s < 0) else (s * 32767)
        buffer.insert(offset, b)

    return buffer

def downsampleBuffer(buffer, outputSampleRate = 16000) :
    if outputSampleRate == RATE :
        return buffer

    sampleRateRatio = RATE / outputSampleRate
    newLength = round( len(buffer) / sampleRateRatio )
    result = []
    offsetResult = 0
    offsetBuffer = 0

    while offsetResult < newLength :
        nextOffsetBuffer = round((offsetResult + 1) * sampleRateRatio)
        accum = 0
        count = 0

        len_buffer = nextOffsetBuffer if nextOffsetBuffer < len(buffer) else len(buffer)

        for i in range( offsetBuffer, len_buffer):
            accum += buffer[i]
            count += 1

        result.append(accum / count)
        offsetResult += 1
        offsetBuffer = nextOffsetBuffer

    return result

async def start_stream():
    try:
        connection = websockets.connect(url)
        while True:
            voice_data = stream.read(CHUNK)

            async with connection as ws:
                sent_data = {
                    "headers": {
                        ":message-type": {"type": "string", "value": "event"},
                        ":event-type": {"type": "string", "value": "AudioEvent"},
                        ":content-type": {"type": "string", "value": "application/octet-stream"}
                    },
                    "body": str(voice_data)
                }
                await ws.send(json.dumps(sent_data))

                response = await ws.recv()

                print(response)

    except KeyboardInterrupt:
        pass

asyncio.get_event_loop().run_until_complete(start_stream())

stream.stop_stream()
stream.close()
audio.terminate()


text:
Q: Find by two columns where one contains null Following documentation of spring-data that is available here there is possibility of creating custom queries using naming convention of methods.
I can find record by some value in column1 using findByColumn1 and find objects that contains NULL in column2 by using findByColumn2IsNull, but when I try to do something like
MyResult result = findByColumn1AndColumn2IsNull("expectedValueOfColumn1");

it returns results that contains column2 property that is set to non-null value.
Can somebody tell me if I'm using the query method wrong, or there is some other issue here?


text:
Q: grunt karma getting error .... Loading "grunt-karma.js" tasks...ERROR Loading "grunt-karma.js" tasks...ERROR

TypeError: Cannot read property 'prototype' of undefined
    Warning: Task "karma" not found. Use --force to continue.

Aborted due to warnings.
I'm experiencing this issue too.
I'm using node 7.5.0 and npm 4.1.2.

A: I faced a similar problem. The following correction helped me
"grunt-karma": "^0.12.2",
"karma": "^1.6.0",

Read more here

A: Doing npm install on karma helped me fix this problem.

A: I was also getting the same error.
First make sure grunt installed locally? otherwise you may see the following message:
Fatal error: Unable to find local grunt.
If you're seeing this message, grunt hasn't been installed locally to
your project. For more information about installing and configuring grunt,
please see the Getting Started guide:
The whole workaround consists of the following steps, even though not all of these steps are necessary but just to be on the safe side:
Optionally, you can uninstall and re-install grunt. That applies to your entire PC and not just to the local installation. Once you uninstall grunt, it won't be accessible from other local folders.
npm uninstall -g grunt

then install the grunt command line by calling:
npm install -g grunt-cli

Installing a local instance of grunt:
npm install grunt --save-dev

Now you can recreate package.json by calling:
npm init

Then fill (or confirm) all details and it will create a new package.json file.
Then, for the grunt dependencies, call:
npm install

If there are errors or warnings, fix them by calling:
npm audit fix

or in severe cases:
npm audit fix --force


text:
Q: List index out of range - python array error File "C:\Users\Tom\Desktop\Tetris!\tetris.py", line 206, in typeSet
    Globals.blockArray[i].x.append(7)
IndexError: list index out of range
I get the above error for the 4th line in typeSet
At initialization:
def main():
    initialize()

def initialize():
    Globals.running = True
    addBlock()

class Globals:
    running = True
    blockArray = []
    blockNum = 0

And then later on:
def addBlock():
    Globals.blockArray.append(block())

class block:
    def __init__(self):
        self.id = Globals.blockNum
        Globals.blockNum += 1
        self.x = []
        self.y = []
        self.landed = False
        self.blockType = 1#random.randint(1,6)
        self.typeSet()

    def typeSet(self):
        i = self.id
        if self.blockType == 1:
            #square(i)
            Globals.blockArray[i].x.append(7)
            Globals.blockArray[i].y.append(0)
            Globals.blockArray[i].x.append(7)
            Globals.blockArray[i].y.append(1)
            Globals.blockArray[i].x.append(8)
            Globals.blockArray[i].y.append(0)
            Globals.blockArray[i].x.append(8)
            Globals.blockArray[i].y.append(1)

Edit: added more code and switched it so the id should start at 0.  Error code hasn't changed

A: Not enough code. The error tells you the exact problem. Globals.blockArray does not have a member at position i. That's why you shouldn't work with global variables when you can avoid them, since it can be a hard time making sure your global variables have the expected values in them.

A: While nothing immediate comes to mind looking at your code above, the first thing I would try would be to print the contents of Globals.blockArray, and Globals.blockArray[i].

A: I'm not sure but maybe you want to do
Globals.blockArray.append(self)

in the init function, and also increase Globals.blockNum after the assignment to self.id.

A: Every time an instance of block is created, Globals.blockNum is incremented by 1 and self.id is set to the current value of Globals.blockNum.
Later (in typeSet) self.id is used to index into Globals.blockArray.
The error occurs when Globals.blockArray doesn't have at least self.id + 1 items in it.
If Globals.blockNum keeps increasing and its value is used (indirectly) to index into Globals.blockArray, this will likely cause the error (unless something causes Globals.blockArray to keep growing too.