text:
Q: Installing MAVEN build dependencies [OSGi bundles] with Maven in to Adobe CQ We have an CQ REST API project to share content with our consumers. The bundle is created with osgi jax-rs connector. We are still in incubation state, but it seems the integration is working fine.
The issue we are facing is the "osgi jax-rs connector" project requires some bundles (osgified ones, provided by the project) to be installed in CQ. Currently we are doing this manually, using the felix console.
Can we automate the process using MAVEN (we can install the bundle which we created using MAVEN).
Any pointers to this would be helpful.
San

A: If you also have a UI package, e.g. a ZIP that gets installed with the maven-vault-plugin you can place JAR files in any folder. I usually call it install:
/apps/myproject/install

There is a handler in CQ that recognizes JAR files in a content package and installs them to OSGi.

A: If you are building a zip package to install you can have the bundles installed with maven and not include the dependencies in your project adding additional space to your SCM.
To do this you can use the maven-assembly-plugin plugin.
For example include this in your pom.xml:
    <plugins>
        <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
            <configuration>
                <appendAssemblyId>false</appendAssemblyId>
                <descriptors>
                    <descriptor>src/main/assembly/zip.xml</descriptor>
                </descriptors>
            </configuration>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>single</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>

And then in you zip.xml you would create an assembly file like this:
<?xml version='1.0' encoding='UTF-8'?>
<assembly
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">
    <id>zip</id>
    <formats>
    <format>zip</format>
    </formats>
    <includeBaseDirectory>false</includeBaseDirectory>
    <fileSets>
    <fileSet>
        <directory>${basedir}/src/main/content/jcr_root</directory>
        <outputDirectory>jcr_root</outputDirectory>
        <excludes>
            <exclude>**/.DS_Store</exclude>
        </excludes>
        <filtered>false</filtered>
    </fileSet>
    </fileSets>
    <dependencySets>
    <dependencySet>
        <outputDirectory>jcr_root/apps/myapp/install</outputDirectory>
        <useProjectArtifact>false</useProjectArtifact>
        <scope>compile</scope>
        <includes>
            <include>com.my.groupid:my-maven-artifact-id</include>
        </includes>
        <useStrictFiltering>true</useStrictFiltering>
    </dependencySet>
    </dependencySets>
</assembly>

You can adjust the dependency set and file set settings as needed.  Obviously I made up an AEM app name and maven artifact.


text:
Q: sql select,get most recent entry for each car My database (MySql) has 2 tables
Table 1 - contains a record for each car
cars= id(int), reg(int), type(int)
Table 2 - contains jobs for each car
jobs = id(int),date(date)
I need a SELECT command which will get me the most recent job for all id's
Thanks in advance.

A: You don't have a shared field, you cant do this.  You need to store the associated car_id with each job, or have a jobs_to_cars table.
Then you'd use:
SELECT C.*, J.id, MAX(J.date)
FROM cars C
INNER JOIN jobs J on J.car_id = C.id
GROUP BY C.id

If job's id IS the same as car's id then change j.car_id to j.id, but then you'd be lacking primary key on Jobs, which i suggest youd start making.

A: You could use something like this
SELECT c.*, MAX(j.date) date
FROM cars c
   LEFT JOIN jobs j ON j.id = c.id
GROUP BY c.id
ORDER BY c.id

because you don't have other fields in [jobs]. If a car don't have any jobs, date will be NULL.

A:     SELECT *
      FROM cars c
INNER JOIN (SELECT MAX(id) AS j_id
              FROM jobs
          GROUP BY car_id) x ON x.j_id = c.id

*

*You forgot the jobs.car_id field, that specifies which car job belongs to

*More elegant way will be to create the field car.last_job_id and maintain it with trigger on jobs table.

Since your question is not clear, this query also can be an answer:
    SELECT j.*
      FROM jobs j
INNER JOIN (SELECT MAX(id) id
              FROM jobs
          GROUP BY car_id) x ON x.id = j.id

A: You can try
ORDER BY date DESC

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use / run Matlab .m file in Eclipse? I have create .m file or .mat file i.e Matlab file and I am using Eclipse december 2017 version JDK 10 , what all are the steps to use these already created .m files / .mat files in Eclipse to run and get the output as it is giving my running .m files in Matlab software.
I want to know, how I can run my .m file (Matlab function files ) in Eclipse using Java?

A: You should run your code by command line. So use a command line like this in a java command executor.
"C:\<matlab path>\matlab.exe" -nodisplay -nosplash -nodesktop -r "run('C:\<program path>\mfile.m');exit;"


text:
Q: how to solve incopmatabllity in php project I'm trying to use 'yield' in my algorithm and my PHP version is 5.4.
I'm looking for any guidance on using 'yield'.

this an FP-algorithim it works fine with php 5.5 but the rest of the project use php 5.4

    public function find_frequent_itemsets($transactions, $minimum_support){
    $processedTransactions = array();
    $items = array();
    //var_dump($transactions);
    foreach($transactions as $transaction){
      // if(!is_array($transaction))
      //continue;
        $processed = array();

        foreach($transaction as $item){

            // check if this item exists ?
            if(array_key_exists($item, $items)){
                $items[$item] += 1;
            }else{
                // not found
                $items[$item] = 1;
            }
            array_push($processed, $item);

        }// every transaction.

        array_push($processedTransactions, $processed);
    }// end first for each (transaction).

    // Remove infrequent items from the item support dictionary.
    foreach(array_keys($items) as $index){
        if($items[$index] < $minimum_support){
            unset($items[$index]);
        }
    }// end loop

    //var_dump($items);
    // sort Transaction in $processedTransactions.
    $sortedTransactions = array();
    //var_dump($processedTransactions);
    foreach($processedTransactions as $currentTransactions){
        $tmp = array();

        foreach($currentTransactions as $item){
            if(array_key_exists($item, $items)){
                // key exits = frequent item.
                //array_push($tmp, array($item, $items[$item]));
                $tmp[$item] = $items[$item];
            }
        }

        // sort based on most frequent item.
        arsort($tmp);
        //var_dump($tmp);
        array_push($sortedTransactions, array_keys($tmp));
    }

    $tree = new FPTree();

    // Add all Transactions.
    foreach($sortedTransactions as $currentTransactions){
        $tree->add($currentTransactions);
    }foreach(find_with_suffix($tree, array(), $minimum_support) as $itemset){
        yield $itemset;
    }

}}
   function find_with_suffix($tree, $suffix, $minimum_support){
    foreach($tree->getItems() as $element){
    $item = $element[0];
    $nodes = $element[1];
    $support = 0;
    foreach($nodes as $n){
        $support += $n->getCount();
    }
      if($support >= $minimum_support && !array_key_exists($item, $suffix)){
        $found_set = array_merge(array($item), $suffix);
        $wanted=array();
        $foo= implode(", ", $found_set) ;
        $wanted[$foo]=$support;
        yield $wanted;                          $condTree=conditional_tree_from_paths($tree->prefixPaths($item),$minimum_support);
      foreach(find_with_suffix($condTree, $found_set, $minimum_support) as s){
            yield $s;
        }
    }
}

A: As this post on stackoverflow tells us, it is rather "costly" to change your algorithm not to use yield and thus make it compatible with a version of php <= 5.4.
On the other side an upgrade to php 5.5 or even better 5.6 is relatively easy. Unfortunately you didn't provide details why you are still with 5.4 and if there are reasons beyond your control that keep you from updating.
I recommend you update your php version because being up to date with software is a matter of security too. Unless you are limited to Windows XP and Windows Server 2003 (which themselves are out of support) you should go for the update.


text:
Q: Reporting Services: make room for long value in a field I'm struggling with Reporting Services to get this done.
I have several reports with a common header which contains some contact info, including e-mail address and web address. If those get too long, they right now just overwrite the data in the next cell below them - which is really really ugly...
So I have a report header something like this:
+-------------------------------------------------------------+
|                         T I T L E                           |
|                                                             |
| Name                            E-Mail:  (value of e-mail)  |
| Address                         Web Url: (value of web url) |
| Zip City                                                    |
|                                                             |
+-------------------------------------------------------------+

Those fixed texts ("E-Mail" and "Web Url") are standard Textfields, as are the value field, bound to a set of data that my reports gets from my ASP.NET application. These values (on the right of the header) are contained inside a single "Rectangle" that basically groups everything on the right together.
But if the e-mail is really long, what I'd like to do is "slide" the "Web Url:" label and value down one line, if the e-mail is really long - like this:
+-------------------------------------------------------------+
|                         T I T L E                           |
|                                                             |
| Name                            E-Mail:  (really really long|
| Address                                   value of e-mail)  |
| Zip City                        Web Url: (value of web url) |
|                                                             |
+-------------------------------------------------------------+

But somehow, no matter what I try, I can't get this behavior :-( The Textfield for the e-mail value has its CanGrow property set to true and the contents of the e-mail does extend down into the next line - but there it just overwrites the string value in the "web url" value field....
Any ideas?
Thanks!

A: @benni_mac_b was right - if the output fields are properly aligned and separated, Reporting Services itself will handle this situation just fine.
In my case, I had ever so slightly overlapping output fields, and for some reason, that seems to have prevented the usual growth of a line and caused the line below to be "overprinted".
I carefully separated those output fields - made sure their height was less than their distance in position, and now it works just fine.


text:
Q: Insert NULL or Empty in a Database? There is a topic here in which is discussed the impacts of inserting a NULL value or an empty value. However, the answers involved both programming and query impacts, and the storage system was not mentioned.
Do the DBMSs (more specifically MySQL and PostgreSQL) make some assumptions whether a value is null or is empty? What is the impact on storage and efficiency?


text:
Q: When I double click my tab I cannot edit it's name Context
I have to create a new tab always when the user clicks on the plus button and then they should be able to edit it on double click. My tabs have onclick and onDoubleClick events.
On the onclick I've assigned a function to get the tabs' index. I'm doing this because I'm working with the Carbon Design System Tabs component, so to get the blue mark on the bottom of the tab I need to pass the index : <Tabs selectedIndex={tabSelected}> . The new tab should have a blue mark as well.

const handleTabs = (id) => {
    const myTabSelected = tabs?.filter((tab) => tab.id === id);
    if (tabs?.length >= 1) {
      /* I'm subtracting 1 because I need the index.  */
      if (myTabSelected[0]?.id - 1 === id - 1) {
      /* [{id: 3, name: 'Tab 3'}][0]?.id -1 ===  3 - 1 */
        let myTabIndx = myTabSelected[0]?.id - 1

        setTabSelected(myTabIndx);
      } else {
        setTabSelected(tabs.length - 1);
      }
    } else {
      setTabSelected(0)
    }
  }

Here is my Tab component :
<Tabs selectedIndex={tabSelected}>
     <TabList activation="manual" aria-label="List of tabs">
         {tabs?.map((tab) => {
            return (
               <div key={tab.id}>
                   <Tab
                      onDoubleClick={() => handleEditOnDoubleClick(tab.id)}
                      onClick={() => handleTabs(tab.id)}
                   >
                   {editing ? <input
                               /* onChange={(e) => setEditTabsName(e.target.value)} */
                                  type="text"
                                  onKeyPress={finishEditOnHittingEnter}
                                  ref={ref}
                                  defaultValue={tab.name}
                                  className="input"/>
                            : tab.name}
                               <Close onClick={() => removetabs(tab.id)} size="18px" />
                   </Tab>
                </div>
                )
              })}

    </TabList>
 </Tabs>

I'm calling this function on  onDoubleClick event:
  const [editing, setEditing] = useState(false);
  const [editTabsName, setEditTabsName] = useState("");
  const ref = useRef(null);

  const handleEditOnDoubleClick = (id) => {
    setEditing(true);

    const newTabs = tabs?.map((tab) => {
      if(tab.id === id){
        return {...tab, name: ref.current.value}
      }
      return tab;
    });

    setTabs(newTabs);
  };

Problem
When I double click to edit the name it only changes if I double click it again. I don't know what's causing it and even after the tab is edited I'm getting bugs. For example, if I try to edit another tab the last value is assigned to that tab, which is not what I'm looking for.
After editing, I want the input to close, so I'm setting false to editing state when I hit enter.
const finishEditOnHittingEnter = (e) => {
    if (e.key === 'Enter') {
      setEditing(false);
    }
  }


text:
Q: Generate hierarchical structure in sql server I have a table employees

id
name
manager

1
susan
null

2
john
1

3
mary
1

4
josh
3

5
mathew
4

6
leo
2

7
peter
5

I want an output like:

id
name
hierarchy

1
susan
null

2
john
susan->john

3
mary
susan->mary

4
josh
susan->mary->josh

5
mathew
susan->mary->josh->mathew

6
leo
susan->john->leo

7
peter
susan->mary->josh->mathew->peter

DDL:
create table employees(id int,name varchar(10), manager int);
insert into employees
values(1,'susan',null)
,(2,'john',1)
,(3,'mary',1)
,(4,'josh',3)
,(5,'mathew',4)
,(6,'leo',2)
,(7,'peter',5)

A: You can use a recursive CTE for this.
WITH cte
AS (SELECT
          e.id,
          e.name,
          CAST(e.name AS VARCHAR(MAX)) AS hierarchy,
          e.manager
    FROM  dbo.employees AS e
    WHERE e.manager IS NULL
    UNION ALL
    SELECT
         e.id,
         e.name,
         CAST(ISNULL(c.hierarchy, '') + '->' + ISNULL(e.name, '') AS VARCHAR(MAX)),
         e.manager
    FROM cte AS c
         JOIN dbo.employees AS e ON e.manager = c.id)
SELECT cte.id,
       cte.name,
       CASE WHEN cte.manager IS NOT NULL THEN cte.hierarchy ELSE NULL END AS hierarchy
FROM   cte
OPTION(MAXRECURSION 0)

When you have more then 100 iterations, which your example has not, you need to provide an option: OPTION(MAXRECURSION 0)


text:
Q: Cannot remove some folders in \Library\Updates I'm trying to remove some folders in /Library/Updates as they are taking up too much space on my hard disk using Terminal.
Even with sudo, I cannot remove the folders. Here are the error messages:
sudo rm -rf 001-26311
Password:
rm: 001-26311/001-26311.en_GB.dist: Operation not permitted
rm: 001-26311/EmbeddedOSFirmware.pkg: Operation not permitted
rm: 001-26311/001-26311.en_GB.extraInfo: Operation not permitted
rm: 001-26311/FullBundleUpdate.pkg: Operation not permitted
rm: 001-26311/SecUpd2020-004Mojave.RecoveryHDUpdate.pkg: Operation not permitted
rm: 001-26311/SecureBoot.pkg: Operation not permitted
rm: 001-26311/FirmwareUpdate.pkg: Operation not permitted
rm: 001-26311/SecUpd2020-004Mojave.pkg: Operation not permitted
rm: 001-26311/macOSBrain.pkg: Operation not permitted
rm: 001-26311: Operation not permitted

I am using MacOS Mojave 10.14.6.
How do you solve this problem?


text:
Q: Injecting emails into Kafka or any other message queue So my requirement is :
I have alert emails coming into my email address ( outlook ); I want to move those ( forward ) email to a linux machine so that I can use them to push into a DB.
--> Is there a way to get emails from my outlook box to a folder in Linux machine ( I have looked into apache james but i feel its a overhead )
Any help would be much appreciated
Was following this :
https://dzone.com/articles/how-to-ingest-email-into-apache-hadoop-in-real-tim
Thanks.

A: If your Outlook account supports IMAP (which it may!!) then just use a gem like https://github.com/seattlerb/imap_processor to process and send these messages off. (As far as sending to Kafka, last time I looked https://github.com/zendesk/ruby-kafka looked awesome).
The imap processor gem has some standalone apps you can use, to check to see if your servers are compatible.
If you are in a corporate environment and running Outlook < 2013?? then IMAP might not work. I'd try and set up a filter rule server side that formwarded certain messages to a Gmail account. ?? Or try to set this up client side?


text:
Q: grep not finding name in text file text file:
Annemie;014588529
Stefaan;011802367
Jan;032569874
Hans;015253694

Trying to find the phonenumber by name but it doesn't display anything
echo -n ""
read name
number=`grep '$name' numbers.txt | awk -F';' '{print $2}'`
echo "$number"

A: Single quotes avoid expansion of variables.
You are searching the string $name inside numbers.txt.
Try this instead:
echo -n ""
read name
number=$(grep "$name" numbers.txt | awk -F';' '{print $2}')
echo "$number"

or even better to reduce the pipe (awk can perform the grep directly):
echo -n ""
read name
number=$(awk -F';' -v name="$name" '$1 ~ name {print $2}' numbers.txt)
echo "$number"

A: Single quotes prevent the shell variable name to expand.
Try like this:
#!/bin/sh
read -p "Enter name: " name
number=$(grep -F "$name" numbers.txt | awk -F';' '{print $2}')
echo "$name => $number"

Also, you should use -F for fixed string grepping, avoid old-style backtick command substitution, and use $(..) instead. If you wish, you can use -p for read prompt (in POSIX shells, sh/bash included).


text:
Q: How to convert dictionary to custom type in Swift? I am trying to convert this dictionary to a custom class but am getting a SIGABRT at let comment = aComment as! messageComments how can I convert the dictionary to the custom class messageComments
["comment1": {
    color = grape;
    content = "a comment ";
    date = 563954564;
    "icon " = referee;
    userName = "anotherUser ";
}, "comment2": {
    color = grape;
    content = "another comment ";
    date = 563954564;
    icon = referee;
    userName = "user";
}]

let comments = messages.childSnapshot(forPath: "comments").value as?[String: Any] ?? [:]

            for aComment in comments.values {
                let comment = aComment as! messageComments
                let theComment = messageComments(content: comment.content, color: comment.color, icon: comment.icon, date: comment.date, userName: comment.userName)
                commentArray.append(theComment)
            }

A: This was the solution
let comments = messages.childSnapshot(forPath: "comments").value as? [String: Any] ?? [:]

                for comment in comments {

                    let theComment = comment.value as? [String: Any]

                    let theContent = theComment?["content"] as? String ?? ""
                    let theIcon = theComment?["icon"] as? String ?? ""
                    let theColor = theComment?["color"] as? String ?? ""
                    let theDate = theComment?["date"] as? String ?? ""
                    let theName = theComment?["userName"] as? String ?? ""

                    let aComment = messageComments(content: theContent, color: theColor, icon: theIcon, date: theDate, userName: theName)
                    commentArray.append(aComment)

                }


text:
Q: Oracle SERIAL# changing for the same SID I'm using Oracle19c with a thin client and I'd like to set traces on the 5 application connections with
EXEC DBMS_SYSTEM.set_sql_trace_in_session(sid, serial#, true ) so I created a stored procedure.
When I select the SID and SERIAL# with:
select sid, serial#, osuser, machine, program, module, username
from v$session WHERE username IS NOT NULL  ORDER BY username ASC;
I noticed that the SERIAL# keeps changing every minute or so, but I don't have any connection timeout set for the user: it's using the DEFAULT profile and LIMIT='UNLIMITED'.
Is there a way to "extend the life" of those connections?

A: A new serial# is a new session. This probably means the application doing the connecting is diconnecting/reconnecting, possibly by design at regular intervals, or possibly by error and its dropping the connection and recovering by commencing a new one.
But you'll need to look inside the app to see that, not the database.
If you want to trace such an app, you could create a LOGON trigger to turn on trace as soon as they connect, rather than trying to catch it with a query to v$session, eg
create or replace
trigger TRACE_ALL_LOGINS
after logon on MY_DB_ACCOUNT.schema
begin
    execute immediate 'alter session set tracefile_identifier = BLAH';
    execute immediate 'alter session set events = ''10046 trace name context forever, level 12''';
exception
  when others then null;
end;
/

I keep the when-others-then-null in this special case to ensure that if the trigger fails for some reason, we don't block the ability to connect at all.


text:
Q: Github actions share data between different worflow runs How can I share data e.g. some id to a different worklow run which will be run at a later time?
I tried using artifacts but they seem to work only within same workflow run between jobs

A: An official action actions/download-artifact doesn't support sharing artifacts between pipeline but you can use this one dawidd6/action-download-artifact@v2
- name: Download artifact
  uses: dawidd6/action-download-artifact@v2
  with:
    # Optional, GitHub token
    github_token: ${{secrets.GITHUB_TOKEN}}
    # Required, workflow file name or ID
    workflow: workflow_name.yml
    # Optional, will get head commit SHA
    pr: ${{github.event.pull_request.number}}
    # Optional, no need to specify if PR is
    commit: ${{github.event.pull_request.head.sha}}
    # Optional, will use the branch
    branch: master
    # Optional, will use specified workflow run
    run_id: 1122334455
    # Optional, uploaded artifact name,
    # will download all artifacts if not specified
    # and extract them in respective subdirectories
    # https://github.com/actions/download-artifact#download-all-artifacts
    name: artifact_name
    # Optional, directory where to extract artifact
    path: extract_here
    # Optional, defaults to current repo
    repo: ${{github.repository}}


text:
Q: Get data of todays and 2 days before added from database I am currently working on a Laravel project. Now I need to fetch some data from the database within a period of days. I need to pass a parameter from the front end, like day =1 or day =2. If day = 1, then I need to fetch today's post. If day = 2 I need to fetch yesterdays and today's posts. I am tried with CURDATE() and NOW() and INTERVAL but I didn't get any solution.
Please help me to do this.
Code to fetch the data
Table used to fetch data

A:

If you pass day = 1 then you can get today's post by whereDate laravel function.
e.g. pass day = 1
$today = date('Y-m-d');
$post = DB::table('post')->whereDate('post_date', $today)->get();
If you pass day = 2 then first of all you have to get previous date and get current date by date function and using whereBetween laravel function you can get yesterday and today's post.
e.g. pass day = 2
$from = Yesterday date
$to   = today date
$post = POST::whereBetween('post_date', [$from, $to])->get();


text:
Q: Computing the similarity between two matrices / Monte Carlo analysis I am studying the article at the following link,
http://www-stat.stanford.edu/~cgates/PERSI/papers/MCMCRev.pdf
Which applies Monte Carlo analysis to a decryption problem. The math is admittedly over my head at this point but I believe I understand the basics.
The goal is to compute a 'plausibility' (scalar) value, I think, that represents how close a decoded message is to making sense in English. The benchmark is defined by a 2-dimensional matrix that represents the frequency that characters occur together in a string of english language.
Is there a method using the dot-product of two matrices that produces a measurement of similarity between those two matrices on a scale of 0 - 1?
(The relevant function is on the first page of the pdf I linked).
Thanks.

A: So in the equation there, $M$ is a 26x26 (say) matrix.  For letters $\ell_1$ and $\ell_2$, $M(\ell_1, \ell_2)$ is the conditional probability that the next letter is going to be $\ell_2$ given that the current letter is $\ell_1$.  For instance:
We take a book, and count the number of times the letter 'e' occurs in that book -- say 15,000.  Then we count the number of times the next letter is 'f' -- say, 200.  With this in hand, we put
$M(\text{'e'}, \text{'f'}) = 200/15000 = 1.33%$.
Now the plausibility score,
$\text{Pl}(f) = \Pi_i M(f(s_i), f(s_{i+1}))$,
is just the associated probability of picking $f(s)$ among all possible strings of text of that length, based on our model that says that the only thing that influences what letter appears at a particular position is the letter before it.  So it's nothing as complicated as you were imagining.


text:
Q: Django model property with parameter I've the following models in Django.
class User(models.Model):
    name = models.CharField(max_length=50)
    ...
    ...

    @property
    def get_info(self, key=None):
        value = self.name if key else 'Hello World'
        return value

But when I try to execute the code in Django shell, I'm getting the following error.
n [4]: user = User.objects.get(id=1)
n [5]: user.get_info(key='test_key')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-f7b917070aee> in <module>()
----> 1 user.get_info(key='test_key')

TypeError: _get_info() takes exactly 2 arguments (1 given)

A: Just remove the @property decorator.  If you need to accept arguments, it's not a property.


text:
Q: Threaded vs Thread I can't understand what is different between Thread and Threaded.
So I can understand that Threaded is a wrapper of pthread API.
And Thread extends it, and it gives more methods.
Yeah I know it, but I want to know.
Why did the developer make Thread though there is Threaded?
Where is the Threaded used?
What is the fundamental differences between those?


text:
Q: Calling Multiple functions simultaneously I'm trying to call two different functions for two different HTML elements at the same time, but the second function isn't being read at all.  I'm also trying to use the id to specify which corresponding elements to grab data from.  Here's what I have:
function changeImage(id)
 {
  var s = document.getElementById('showcase');
  var simg = s.getElementsByTagName('img');
  var slen = simg.length;

  for(i=0; i < slen; i++)
  {
   simg[i].style.display = 'none';
  }
  $('#' + id).fadeIn('slow', 0);

  function createComment(jim)
 {
  //alert('hello?');
  var d = document.getElementById('description');
  var dh = document.getElementsByTagName('p');
  var dlen = dh.length;

  //alert(dh);

  for(i=0; i < dlen; i++)
  {
   alert(dh);
   dh[i].style.display = 'none';
  }
  $('#' + jim).fadeIn('slow', 0);

 }

A: It appears you are missing the closing bracket} at the end of your changeImage function.
Also you could shorten your script substantially using jQuery:
function changeImage(id)
 {
  $('#showcase img').hide();
  $('#' + id).fadeIn('slow');
 }
function createComment(jim)
 {
  $('#description p').hide();
  $('#' + jim).fadeIn('slow');
 }

Also, I'm not sure why you have a zero inside the fadeIn() function? If you want the img/p to show instantly, just use .show()


text:
Q: webpack dll configuration not working I'm trying to create dll configuration with webpack 4, but i keep getting:
Uncaught ReferenceError: React is not defined

My configuration is very simple:
module.exports = {
  entry: {
    vendor: ["react", "react-dom"]
  },
  output: {
    filename: "[name]-manifest.dll.js",
    path: base.path.project("build"),
    library: "[name]",
    libraryTarget: "umd"
  },
  plugins: [
    new webpack.DllPlugin({
      name: "[name]",
      path: base.path.project("build/[name]-manifest.json"),
      context: base.path.src("app")
    })
  ]
};

In my development configuration I use the dllreferenceplugin.
new webpack.DllReferencePlugin({
  context: base.path.src("app"),
  manifest: require("../build/vendor-manifest.json")
})

and of course i define externals in development configuration, because I don't want to include them again when building my development js file:
  externals: {
    react: "React",
    "react-dom": "ReactDOM"
  }

In my code I import React.
import * as React from "react";

But in the browser I keep getting React is not defined.
I have googled everything and have not found any solution to this problem?
Thank you for any help!

A: Use import React, { Component } from 'react'; myself. JSX wants react to be in scope.
Largely only see externals being used when making a library, like a npm module that other folks consume that uses React. React would be marked as an external in that package to avoid double including React in the local application and inside the module.
If this is your app build process, and not an npm module then should not be marking react as externals. Your bundle needs to include react. Marking react as externals excludes it from the bundle and makes it your responsibility to manually load React before the bundle is loaded.

The externals configuration option provides a way of excluding
  dependencies from the output bundles.

See the docs on webpack externals here.

A: Just Remove the external property from your app webpack config file.Also, Include the dll file in your index.html file.
I was also facing the same issue, because I was using both dllReference plugin and external at the same time.


text:
Q: Do the photon and surface electron fields in the double slit interact even if there is no absorption This was a question on PSE "Do the photon and electron fields interact even if there is no absorption?"

I am talking to a friend about why light travels more slowly through glass. We came to the understanding that it is a purely quantum mechanical effect caused by the electromagnetic field inducing vibrations in the electron field which in turn creates new electromagnetic vibrations. These new vibrations then interfere with the original electromagnetic wave which produces a net effect of the overall wave being slower…
This seems to imply that the balance of "electron energy" to "electromagnetic energy" is always changing slightly, even if nothing is being absorbed.

And an answer, containing:

Electrons will exchange their kinetic energy with the electric field potential energy as they are accelerated and decelerated during a cycle of the wave.

Shouldn't this also be applied to the passage of photons through a double slit?


text:
Q: Show that if $G$ is a finite group and $H_i$ are subgroups of $G$ with $[G:H_i]=2$ then $[G:\cap H_i]=$ some power of $2$
Show that if $G$ is a finite group and $H_i$ are subgroups of $G$ with $[G:H_i]=2$ then $[G:\cap H_i]=$ some power of $2$.

My try:
Let the number of subgroups of $G$ be $H_1,H_2,\ldots ,H_m$
Its clear that each $H_i$ is a normal subgroup of $G$
and every $H_i$ has exactly two left/right cosets.
Let the left cosets of $H_1$ in $G$  be $H_1,g_1H_1$ ,that of $H_i$ in $G$ be $H_i,g_iH_i$ and so on.
Let $H=\cap H_i$
Now we know that
$[G:H\cap K]\le [G:H][G:K]$ for any two subgroups $H,K$ of $G$.
Thus we have
$[G:H]\le 2^m$
Now I need to show only that $[G:H]\ge 2^m$
Now I understand that since $g_i\notin H_i\implies g_i\notin H$
hence we have at least $m$ cosets of $H$ in $G$ given by $g_1H,g_2H,\ldots g_mH$
But I need to find at least $2^m$
How can I do it?
Please give some hints

A:
If $\vert G/H_i \vert =2$, then $\forall x \in G (x^2 \in H_i)$.

As you've noted, $\forall i H_i \lhd G$, so the quotient group $G/H_i$ has size two, and any representative $x$ of the quotient group's non-trivial element must satisfy $H_ix^2=H_i$, so $x^2 \in H_i$.  (Of course, if $x \in H_i$, it's trivial that $x^2 \in H_i$.)
Since each $H_i \lhd G$, it follows that $\bigcap H_i \lhd G$.

Thus, every non-identity element of $G/ \bigcap H_i$ has order $2$.

If $p|~|G/ \bigcap H_i|$ for some odd prime $p$, then $G/ \bigcap H_i$ has a $p$-Sylow subgroup which has elements of odd order.  We just finished proving that doesn't happen, so no odd prime divides $|G/ \bigcap H_i|$

Thus, $\vert G/ \bigcap H_i \vert = [G: \bigcap H_i] = 2^k$ for some $k$.


text:
Q: swift package manager 'cannot find target' error message I am very new to package manager and can't seem to import a library correctly.  I am using the following code:
import PackageDescription

let package = Package(
    name: "MyAppName",
    products: [
        .executable(name: "MyAppName", targets: ["MyAppName"])
    ],
    dependencies: [
        .package(url: "https://github.com/socketio/socket.io-client-swift", .upToNextMinor(from: "13.1.0"))
    ],
    targets: [
        .target(name: "MyAppName", dependencies: ["SocketIO"], path: "./Source Files")
    ]
)

After creating this file and placing it in my project main directory, I open a terminal window and type swift build.  The files are fetched however I get the following error message:

could not find target(s): MyAppName; use the 'path' property in the Swift 4 manifest to set a custom target path

I really don't understand the products and targets section of the package file and what I am doing wrong.  I just put my app "MyAppName" for the executable and target but don't quite understand if that is correct.  Also, not sure the path is correct.  I want the libraries to be added to a folder titled Source Files in my main project directory.

A: Everything in your Package.swift looks fine, you only need to put MyAppName directory with the source files in one of the directories Sources, Source, src, srcs in the top-level directory.
So the top-level directory (the one where Package.swift is located) should have the following structure:
TopLevelDirectory
  |- Package.swift
  |- Sources
       |- MyAppName
             |- MyAppNameSource1.swift
             |- MyAppNameSource2.swift
Alternatively, you can add the 'path' property to the definition of the target "MyAppName" and to specify where the directory with the sources resides.
Reference: https://github.com/apple/swift-package-manager/blob/master/Documentation/PackageDescriptionV4.md#target-format-reference


text:
Q: Why my script at the bottom of body blocks the page? I read that if I put the script at the bottom of the body the page would not block because will first render the html above. But it dose not happens to me, even if it is at the end is blocked.
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Some document</title>

Title

blah blah

Why??
Update:
doesn't work in chrome.
Works in firefox.
Why?

A: Since


text:
Q: Why would outputting a [PSCustomObject] change execution order Why, in the second pair of commands, is Read-Host processed before the object is output?
PS > (1..3).ForEach{ @{ a=$_ } }; Read-Host 'pause1'
Name                           Value
----                           -----
a                              1
a                              2
a                              3
pause1:

PS > (1..3).ForEach{ [PSCustomObject]@{ a=$_ } }; Read-Host 'pause2'
pause2:
a
-
1
2
3

I would have affirmed that this just started happening. A script that output a [PSCustomObject] must now complete before the output is seen. Entering the debugger after the loop but before the script's completion means the output is not seen.

A: The execution order isn't changed but the items in the pipeline are hold till the command sequence is finished before they being released to the default output (which is the display).
Prove

*

*Enter a response to Read-Host 'pause2' cmdlet and note that the response is added at the end of the pipeline:

pause2: Test
a
-
1
2
3
Test

*Add some timestamps to the testing:

(1..3).ForEach{ [PSCustomObject]@{ a=(Get-Date).ToString('HH:mm:ss.fffffff') } } ; Read-Host (Get-Date).ToString('HH:mm:ss.fffffff')
15:41:29.1931049:
a
-
15:41:29.1916159
15:41:29.1918194
15:41:29.1919053

Solution
Explicitly force the pipeline items to be immediately displayed by using the specific Write-Host cmdlet:
(1..3).ForEach{ [PSCustomObject]@{ a=$_ } } |Write-Host; Read-Host 'pause2'
@{a=1}
@{a=2}
@{a=3}
pause2:


text:
Q: gcc/ld - create a new libc.so with __isoc99_sscanf@@GLIBC_2.7 symbol from glibc.2.6 I have an application, which does a error when I try to run it:
/lib/libc.so.6: version `GLIBC_2.7' not found

But the only symbol it needs from glibc 2.7 is
__isoc99_sscanf@@GLIBC_2.7

I want to write a small single function "library" with this symbol as alias to __sscanf()
How can I do this with gcc/ld?
My variant is not accepted because "@@" symbols
 int __isoc99_sscanf@@GLIBC_2.7(const char *, const char *, ...) __attribute__((alias("__sscanf")));

second my variant is
#include <stdarg.h>
int __isoc99_sscanf1(const char *a, const char *b, va_list args)
{
   int i;
   va_list ap;
   va_copy(ap,args);
   i=sscanf(a,b,ap);
   va_end(ap);
   return i;
}

   // __asm__(".symver __isoc99_sscanf,__isoc99_sscanf@@GLIBC_2.7");
    __asm__(".symver __isoc99_sscanf1,__isoc99_sscanf@@GLIBC_2.7");

but it ends with "version node not found for symbol __isoc99_sscanf@@GLIBC_2.7" error from linker.

A: Your second version works with this script:
GLIBC_2.7 {
 global: __isoc99_sscanf;
 local: *;
};

Using -Wl,--version-script=script.txt, however, I don't know how to access the original sscanf@GLIBC_2.4.
Anyway, perhaps you would want to use -D_GNU_SOURCE instead; to avoid __isoc99_sscanf altogether.

A: I found @felipecs answer very helpful.  In addition our application had to do some dynamic linking using ocaml, and we found that the given script doesn't work for this scenario, since it makes the application only export the __isoc99_sscanf symbol as a global.
GLIBC_2.7 {
 global: *;
};

the above script resolves this issue and allows ocaml's dynamic linker to work properly.  using the -D_GNU_SOURCE option alone wasn't enough to avoid this issue since the dependency on GLIBC_2.7 came from a prebuilt binary we were statically linking with.


text:
Q: width of sampler2D must be the multiple of 16 As the topic say, the sampler2D binding to a texture which is storage to 125x94, 125 is width, 94 is height,when I use texelFetch(sampler2D, ivec2(0, 1), 0),the 128th number is token, seems like width is 128 not 125,why?
Is there some docs to prove that,thanks.


text:
Q: How do I pass arguments by nodeJS express app route Currently I have two files:
service.js
const routes = (app) => {
  app.route('/produce')
    .get((req, res) => res.send(`GET Method from /produce`))
    .post((req, res) => res.send(req.body))
};

module.exports = routes;

app.js
const service = require('./service.js');
service(app);

After that, when I try to 'GET', it returns the text "GET Method from /produce" as expected
However, when I try to 'POST' some message, it cannot return my request message.
Anyone can help on this? Many thanks.

A: The exact code you pasted doesn't work because it fails to stringify the req object. Check the express API and decide what exactly information you want to get from the req object.
For example:
.post((req, res) => res.send(req.body))

To get req.body working you need to set up a body-parsing middleware such as express.json() or express.urlencoded().
For example, if you are working with application/json, try something like
app.use(express.json())


text:
Q: Sending ordered broadcast to a specific receiver? How can I send an orderedBroadcast to a specific receiver? I am broadcasting the ACTION_MEDIA_BUTTON and only want a specific app (Winamp for example) to receive it. I don't want Pandora to steal it. Is there a way to explicitly define who the receiver will be?
void sendBroadcast() {

        Intent i = new Intent(Intent.ACTION_MEDIA_BUTTON);
        synchronized (this) {
            i.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, theKeyEvent));
            ctx.sendOrderedBroadcast(i, null);

            i.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_UP, theKeyEvent));
            ctx.sendOrderedBroadcast(i, null);
        }
    }

A: If you know the package of the Winamp application, you can use setPackage to restrict Intent resolution to only a specific package.


text:
Q: on duplicate key update with a condition? I have something like:
INSERT INTO tbl (count,otherID) VALUES (2,'a') ON DUPLICATE KEY UPDATE count = 2

I would like to update count only if the new value is greater than the current value. So let's say there is already a record with count: 4 and otherID: 'a' that ON DUPLICATE KEY UPDATE count = 3 should not be triggered
How can i achive this?
can i use if? ... UPDATE count = IF (NEWVALUE > count) NEWVALUE else count

A: Another option:
INSERT INTO tbl (count, otherID)
  VALUES (2, 'a')
ON DUPLICATE KEY UPDATE
  count = GREATEST(VALUES(count), count) ;

Warning: This will fail if the passed value for count is NULL (instead of 2). It will update the column with NULL. So, it's better to use the IF() or a CASE clause.
Unless you prefer the (there goes the elegance ...):
ON DUPLICATE KEY UPDATE
  count = GREATEST(COALESCE(VALUES(count), count), count) ;

A: Haven't tested it, but I think this should work.
INSERT INTO tbl (count, otherID) VALUES(2,'a')
ON DUPLICATE KEY
UPDATE count = IF(VALUES(count) > count, VALUES(count), count)


text:
Q: unclear caching in browser I do changes in my php-file and refresh the page in browser, changes are applied first, then I do some other changes, refresh again(ctrl+R, many times) and see it UNchanged, like it's cached. About 1-2 min pass(approximatly) and changes do get applied, although I didn't edit the file. This scenario repeats many times. I do not understand what is going on, please help. I've tried this btw:
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

but it didn't help

A: i have that same issue on i'm using free web hosting when i edit php files you need to wait couple of seconds before accessing it or else i receive blank page or the completely unedited version of it also i thought PHP tries to prevent browser caching by default?
anyway if you want to prevent user input staying "entered" when user get redirected and decided to use "back button" on browser just add autocomplete="off"
<form action="#" method="post" accept-charset="utf-8" autocomplete="off">

also if you want the prevent the form getting resubmit if user decided to refresh the page when they submitted the form i used this  https://stackoverflow.com/a/38768140/17939597


text:
Q: before_create - Ruby on Rails
Possible Duplicate:
Ruby on Rails Callback, what is difference between :before_save and :before_create?

I'm looking to replace Ruby on Rails current id from /1, /2, /3, etc to a randomly generated URL, for example /csd8dsv68dvs.
After looking into creating it, I found this in the post model
before_create { self.code = SecureRandom.hex(5) }

What does the before_create do and how can I implement the random id?
Update
It seems I got one part wrong. I'm not looking to change the ID, I just want to change the URL to a random string that a user won't be able to guess.

A: A great gem to help you with alternatives to a resource :id as the identfier through a route is friendly_id. There is even a RailsCast on it.
before_create is an ActiveRecord callback and is well explained both here on SO (as others have commented) and in the API.
If you chose to use the raw
before_create { self.code = SecureRandom.hex(5) }

You could modify your controller action to find the resource using this code instead of the id.
def some_action
  @resource = ModelClass.find_by_code!(params[:id])
end

You'd pass the :code attribute to routes for the resource in your views
resource_path(@resource.code)

where resource_path is the route method for your resource.

A: I would strongly advise against replacing the Rails id, but if you mean that you want to change the URL to something less predictable, then you're on the right path.
This is a very similar problem to one solved by creating "pretty URLs" which has been solved many times, for example with the Friendly ID gem.  Perhaps you'll want to fork the gem and call it "Unfriendly ID" :-)
Whether the gem works out of the box or not, the method is straightforward -- read the code and learn from the guy who wrote it!

A: I agree with the other two posters; you probably don't want to do this, and FriendlyID provides a nice way to work with alternate IDs for records.  That said, if you really do want to replace the id, you can just change it:
thing = Thing.new
thing.id = some_random_number_generator()
thing.save!

This was already covered in Overriding id on create in ActiveRecord.  Seriously consider not doing it unless you have a good reason.


text:
Q: mcrypt_decrypt doesn't work after encrypt I want to decrypt an encrypted response using mcrypt_decrypt but this doesn't work, so I'm using this snippet of code for test and the response should be "This is a test":
// Encryption Algorithm
// the $shared_key and $init_vector are not real
$cipher_alg = MCRYPT_RIJNDAEL_128;
$shared_key = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF";
$key = pack("H*", $shared_key);
$init_vector = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF";
$iv = pack("H*", $init_vector);

echo mcrypt_decrypt($cipher_alg, $key, utf8_encode(mcrypt_encrypt(
        $cipher_alg, $key, utf8_encode('This is a test'), MCRYPT_MODE_CBC, $iv)),     MCRYPT_MODE_CBC, $iv);

And the response is:
æ †,?7÷q†Ý³'¢gTô1ò'ù'Ü"®mÀ{ëQS

What I'm doing wrong?

A: You are utf8 encoding the encrypted stuff. That way it is modified and can not be decrypted anymore.
echo mcrypt_decrypt($cipher_alg, $key, mcrypt_encrypt(
        $cipher_alg, $key, 'This is a test'), MCRYPT_MODE_CBC, $iv), MCRYPT_MODE_CBC, $iv);


text:
Q: Can I change the Ansible target in-flight? I run KVM virtual machines on bare metal hosts. To spin up new VMs, I would:

*

*virt-clone a template

*virt-sysprep the clone to make some basic changes

*Start the cloned VM

*Use Ansible for further configuration

Currently, the first 3 steps are done using 1 Ansible script, and the last step is done with another. The first script acts on the bare metal host and the second script acts on the VM.
My question is, can this be performed in 1 script? One possibility is to change the inventory_hostname in-flight in a playbook to target the VM after Step 3. However, I believe this isn't possible.
Is there a better way to do this? Thanks in advance!

A: The solution is simpler than I thought - use delegate_to. In my Ansible role, some of the tasks were directed to the physical host that runs the VM. The rest were targeted at the virtual host.
In this example, a single script creates the VM on bare metal, and then provisions the VM itself. delegate_to executes the virt-clone command on the VM's metal host.
- name: Clone template's KVM definition
  command: virt-clone -o {{ template_name }} -n {{ clone_name }} -f {{ clone_lvm }}
  delegate_to: "{{ metal_host }}"

- name: "Wait for VM to bootup"
  local_action: wait_for host="{{ ansible_host }}" port=22 timeout=60

- name: Gather facts for first time
  setup:

- name: Install packages
  apt:
    name: auditd,ntp,apache2
    state: present


text:
Q: Можно ли сделать в MySQL CREATE TABLE LIKE с триггерами? Возможно ли  перенести триггеры в другую(точно такую же) таблицу в MySQL?
У меня есть таблица test, со временем я её архивирую и на ее месте создаю такую же
CREATE TABLE test_new LIKE test;
RENAME TABLE test to test_old;
RENAME TABLE test_new to test;

После такого кода мне нужны триггеры из test_old, они были созданы автоматически.


text:
Q: What is/How to do Unification I'm reviewing for a final exam on Monday, and I have a question I was unable to answer on a previous test. The professor's notes were horrendous, and I can't find anything better online. They all seem to talk way over my head.
For each of the following pairs of literals, determine whether or not they are unifiable. If they do, show the unifiers.

*

*P(a), Q(g(x))

*P(x), Q(g(a))

I have a feeling that it's insanely easy, as the prof (despite teaching horribly, gives easy enough questions) but I still have no idea what to do.

A: There is no unification in either case, since whatever you substitute for $x$ (and perhaps $a$; you didn't state which symbols are variables to be substituted), the first expression of the pair will have $P$ as its outermost symbol and the second one will have $Q$.


text:
Q: Handlebars: How to reuse template after dynamically updating array of objects Okay so here is the the template I'm using

And then I'm adding my objects in the array to the DOM with handlebars.
var template = Handlebars.compile($('#goalNavTemplate').html());
$('#selectGoalModal .modal-body').append(template(goals));

This works how I like, yet what I would like to do next is be able to update the DOM when a new object is added to the array (through user input). Yet if I call:
$('#selectGoalModal .modal-body').append(template(goals));

again it will add all the objects to the DOM and not just the last one. My current workaround is to remove the previously added elements and then use the above line of code after the array is updated. I was wondering if there is a more efficient way of doing this using handlebars? Like is there some way to bypass #each and just append the last object in the array? Would you use a helper? If so, how? Any insight into this would be awesome.

A: You can add some flags to goals item, e.g. datatime and check it by HB:
{{#each this.items}}
    {{#ifCond this.dt '>=' ../options.dt }}

            {{id}} - {{name}}

    {{/ifCond}}
    {{#updateDOM "#bub-" id dt}}{{/updateDOM}}
{{/each}}

http://jsfiddle.net/2jvndb0L/5/


text:
Q: Declaring interface in the same file as the base class, is it a good practice? To be interchangable and testable, normally services with logic needs to have interface, e.g.
public class FooService: IFooService
{ ... }

Design-wise, I agree with this, but one of the things that bothers me with this approach is that for one service you will need to declare two things (the class and the interface), and in our team, normally two files (one for the class and one for the interface). Another discomfort is the difficulty in navigation because using "Go to definition" in IDE (VS2010) will point to the interface (since other classes refer to the interface), not the actual class.
I was thinking that writing IFooService in the same file as FooService will reduce the above weirdness. After all, IFooService and FooService are very related. Is this a good practice? Is there a good reason that IFooService must be located in its own file?

A: Why is having separate files a discomfort? For me, it's much neater and cleaner. It's common to create a subfolder named "Interfaces" and stick your IFooServer.cs files there, if you want to see fewer files in your Solution Explorer.
The reason the interface is defined in its own file is for the same reason that classes are usually defined in their own file: project management is simpler when your logical structure and file structure are identical, so you always know which file a given class is defined in. This can make your life easier when debugging (exception stack traces usually give you file and line numbers) or when merging source code in a source control repository.

A: It is often a good practice to let your code files contain only a single class, or a single interface. But these coding practices are a means to an end - to better structure your code making it easier to work with. If you, and your team, find it easier to work with if the classes are kept together with their interfaces, by all means do so.
Personally I prefer to have the interface and class in the same file when there is just one class that implements the interface, such as in your case.
In regards to the problems you have with navigation, I can highly recommend ReSharper. It contains some highly useful shortcuts for jumping directly to the method implementing a specific interface method.

A: Interfaces belong to their clients not to their implementations, as defined in Agile Principles, Practices and Patterns by Robert C. Martin. Thus, combining interface and implementation in the same place is against it's principle.
Client code depends on the interface. This allows the possibility of compiling and deploying the client code and the interface without the implementation. Than you can have different implementations working like plugins to the client code.
UPDATE:
This is not an agile-only principle here. The Gang of Four in Design Patterns, back in '94, are already talking about clients adhering to interfaces and programming to interfaces. Their view is similar.

A: There are many times where you want your interface to be not only in a separate file to the class, but even in a separate assembly altogether.
For example, a WCF Service Contract interface can be shared by both client and service if you have control over both ends of the wire. By moving the interface into its own assembly, it will have fewer assembly dependencies of its own. This makes it much easier for the client to consume, loosening the coupling with its implementation.

A: It doesn't have to be in its own file, but your team should decide on a standard and stick to it.
Also, you're right that "Go to definition" takes you to the interface, but if you have Resharper installed, it's only one click to open a list of derived classes/interfaces from that interface, so it's not a big deal.  That's why I keep the interface in a separate file.

A: It rarely, if ever, makes sense to have a single implementation of an interface1. If you put a public interface and a public class implementing that interface into the same file, good chances are that you do not need an interface.
When the class that you co-locate with the interface is abstract, and you know that all implementations of your interface should inherit that abstract class, locating the two in the same file makes sense. You should still scrutinize your decision to use an interface: ask yourself if an abstract class by itself would be fine, and drop the interface if the answer is affirmative.
Generally, though, you should stick to the "one public class/interface corresponds to one file" strategy: it is easy to follow, and it makes your source tree easier to navigate.

1 One notable exception is when you need to have an interface for testing purposes, because your choice of mocking framework placed this additional requirement on your code.

A: I think you should keep them separate files. As you said, the idea is to remain testable and interchangeable. By placing the interface in the same file as your implementation, you are associating the interface with the specific implementation. Should you decide to create a mock object or another implementation, the interface will not be logically separate from FooService.

A: According to SOLID, not only should you create the interface, and not only should it be in a different file, it should be in a different assembly.
Why? Because any change to a source file that compiles into an assembly requires recompilation of the assembly, and any change to an assembly requires recompilation of any dependent assembly. So, if your aim, based on SOLID, is to be able to replace an implementation A with an implementation B, while the class C dependent on interface I doesn't have to know the difference, you have to make sure the assembly with I in it doesn't change, thus protecting the usages.
"But it's just a recompile" I hear you protest. Well that may be, but in your smartphone app, which is easier on your users' data bandwidth; downloading one binary that changed, or downloading that binary and five others with code that depends on it? Not every program is written to be consumed by desktop computers on a LAN. Even in that case, where bandwidth and memory are cheap, smaller patch releases can have value because they're trivial to push out to the entire LAN through Active Directory or similar domain management layers; your users will wait only a few seconds for it to be applied the next time they log in instead of a few minutes for the whole thing to be reinstalled. Not to mention that, the fewer assemblies that must be recompiled when building a project, the faster it will build, making you more productive because you spend less time sitting around waiting for 50 assemblies to build for each change you make.
Now, the disclaimer: This is not always possible or feasible to do. The easiest way to do this is to create a centralized "interfaces" project. This has its own downsides; code becomes less reusable because the interface project AND the implementation project have to be referenced in other apps reusing the persistence layer or other key components of your app. You can overcome that problem by splitting the interfaces into more tightly coupled assemblies, but then you have more projects in your app which makes a full build very painful. The key is balance, and maintaining the loosely-coupled design; you can usually move files around as necessary, so when you see that a class will need many changes, or that new implementations of an interface will be needed regularly (perhaps to interface with newly-supported versions of other software, or file types, etc) you can sever it from its interface and protect usages from knowledge of those changes.

A: I personally don't like the "I" in front of an interface. As a user of such a type I'don't want to see that this is a interface or not. The type is the interesting thing. In terms of dependencies your FooService is ONE possible implementation of IFooService. The interface should be near of the place where it is used. On the other hand the implementation should be at a place where it can be easily changed without effecting the client. So, I would prefer two files - normally.

A: Coding to interfaces can be bad, is in fact treated as an anti-pattern for certain contexts, and is not a law. Usually a good example of coding to interfaces anti-pattern is when you have an interface that only has one implementation in your application. Another would be if the interface file becomes so bothersome that you have to hide its declaration in the implemented class's file.

A: Putting a class and an interface into the same file puts no limits on how either can be used. An interface can still be used for mocks etc in just the same way, even if it is in the same file as a class which implements it.
The question could be perceived purely as one of organisational convenience, in which case I would say do whatever makes your life easier!
Of course, one could argue that having the two in the same file might lead the unwary to consider them to be more programmatically coupled than they really are, which is a risk.
Personally, if I came across a codebase which used one convention over the other I wouldn't be too concerned either way.


text:
Q: Kinds of bugs that are more likely/prone in Haskell programs than in other languages? One of the highly-touted features is that if a program compiles, it highly likely to be mostly correct, more so than a program written in a language with a less sophisticated or strict type system.
That is, Haskell is a system for translating runtime errors to compiler errors :-)
I wonder, does programming in Haskell give rise to situations where a programmer could introduce a runtime bug that doesn't have an obvious analog (in appearance and frequency) in a less strongly-typed language?
Some basic examples that pop into my head: (not great, I am looking for advice on what to be wary of)

*

*asymptotic performance bugs due to laziness

*infinite loop due to wrongly structured recursion

*fundeps/type-families pushing logic to type level, where code is more "arcane" and errors are harder to spot?

Other/better examples of gotchas?

A: It doesn't have to be asymptotic, but space leaks due to lazyness are a problem in real-world applications of Haskell. I know of Haskell-using companies that completely switched to strict datatypes (while still using the laziness of function parameters).
For sources on that view, see:

*

*E. Hesselink. Silk: making the sematic web functional. Functional Programming Exchange 2012, London, March 2012.

*C. J. Sampson. Experience report: Haskell in the 'real world': writing a commercial application in a lazy functional lanuage. In ICFP '09, pages 185–190, 2009.

*S. Wehr. Kommerzielle Softwareentwicklung mit Haskell. Hal6, Leipzig, Oct 2011. Slides (in German).

A: Laziness, especially lazy I/O where pure functions can force IO actions or closing a file Handle prior to reading.  The Haskell course by Stanford University has good information on this in the Iteratee lecture.  Imho, this lecture series is very well written and covers a lot of ground.

A: Consider the following dataype:
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveTraversable #-}

import Data.Foldable
import qualified Data.Traversable as T
import Control.Monad.Random

data U a = U [a] a deriving (Show,Functor,Foldable,T.Traversable)

I want to create a U Int with random values. It's easy using the Traversable instance:
ri :: Rand StdGen Int
ri = getRandomR (0,3)

randomU :: U Int
randomU =  flip evalRand (mkStdGen 7)
         . T.sequence
         $ U (replicate 3 ri) ri

putStrLn . show $ randomU -- works

Now I create a random infinite U Int and print the first three values of the list:
randomInfiniteU :: U Int
randomInfiniteU =  flip evalRand (mkStdGen 7)
                 . T.sequence
                 $ U (repeat ri) ri

putStrLn . show $ take 3 $ (\(U l _) -> l) $ randomInfiniteU

Works fine as well. As a last test, let's print the single value to the right:
putStrLn . show $ (\(U _ i) -> i) $ randomInfiniteU

Ugh. This hangs.


text:
Q: Apache redirecting to removed virtual host I have a strange issue with my Apache. I added a new virtual host and I noticed if I browse to it it redirects to another hosts home directory. I have host1, host2 and newly created host3. If I browse to address for host 3 it would take me to host1 site.
I removed host1 now but it still trying to take me to host1 (Apache log has"
[Thu Jul 24 16:31:33 2014] [error] [client 127.0.0.1] File does not exist: C:/WWW/htdocs/public/host1/index.html  "  which is home directory for host1 site which is removed from httpd.conf. Apache service restarted, all other .conf files checked - no mentioning of host1.
here how its configured:
################# host2 ############################
<VirtualHost host2.net:80>

DocumentRoot "C:/WWW/htdocs/host2/public/"
ServerName host2
ServerAlias host2.local

<Directory "C:/WWW/htdocs/host2/public/">
        Options Indexes FollowSymLinks
        DirectoryIndex index.php index.html
    AllowOverride all
    Order allow,deny
    Allow from all
</Directory>

</VirtualHost>

################# host3 ############################
<VirtualHost host3.net:80>

DocumentRoot "C:/WWW/htdocs/host3/public/"
ServerName host3
ServerAlias host3.local

<Directory "C:/WWW/htdocs/host3/public/">
        Options Indexes FollowSymLinks
        DirectoryIndex index.php index.html
    AllowOverride all
    Order allow,deny
    Allow from all
</Directory>

</VirtualHost>

Thanks

A: In case anybody have the same issue - I just found one software on my PC that has been messing with port 80. Once that software removed - my apache works fine


text:
Q: scroll en web: al cambiar de página y volver a la principal no ubica bien el target Estoy trabajando en una página web de estilo similar a una OnePage. Tiene un index en el que se muestra toda la información pero en la sección de servicios, en vez de usar acordeones o modals, la empresa quiere que lleve a una página diferente por cada servicio. Es decir, son 10 páginas en total.
El scroll (es una animación que sube y baja la web en función de los targets del menú), en el index, funciona perfectamente... pero en el momento que cambio de página a una de servicios y después quiero volver al index (para ver mas servicios, contactar con ellos etc) en vez de colocarse bien el target y verse el div que contiene el nombre de cada sección, lo ubica justo debajo del mismo.
El menú está fijado siempre al principio de la página, por lo que es fácil navegar por la web y acceder a las secciones.
El enlace al jquery es este:
https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js

Y este es el código que estoy usando para el scroll actual:
   $(function() {
     $('a[href*="#"]:not([href="#"])').click(function() {

      if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
        if (target.length) {
          $('html, body').animate({
            scrollTop: target.offset().top-80
          }, 1000);
          return false;
        }
      }
     });
     });

El problema está en que cuando estoy en la página de servicios, me entra a la función y también a la zona del href pero no entra al if del pathname.replace y tras varios intentos y pruebas no he conseguido que salga bien. ¿Alguien puede ayudarme con esto?

A: Por lo que veo en la descripción de tu problema, este ocurre cuando estás en otra página distinta al "home", en este caso servicios.
Voy a asumir que tienes las siguientes url:
Home: http://misitio.com/
Servicios: http://misitio.com/servicios.html
Cuando estás en la página de servicios y haces clic en tu botón o enlace que te lleva al home, dices que no es verdadero el resultado del siguiente if:
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {..}

Evaluando la primera condición (en la página de servicios), obtendríamos estos resultados:
location.pathname = /servicios.html
this.pathname = /#

Asumo que en alguna parte de la url debe haber un # teniendo en cuenta el selector de la segunda línea: a[href*="#"]:not([href="#"])
En todo caso, luego haces un replace, el cual simplemente elimina la barra oblicua inicial /.
Por consiguiente al final tendríamos como resultado que estás comparando servicios.html con #, lo cual no es igual y por ese motivo el resultado es falso (no entra al if).
La segunda condición location.hostname == this.hostname no debería tener mayor problema, a menos que estés en un subdominio distinto o similar.

Teniendo en cuenta que la idea es que el scroll funcione al regresar a la página Home, lo que necesitas es que esto lo haga una vez el contenido esté listo y detecte si hay un hash, de ser así, hacer el scroll respectivo. Te pongo una idea de como sería la solución, aunque deberías mejorarle algunas cosas:
$(function() {
  ...
  if(window.location.hash) {
    var seccion = $(window.location.hash);
    if (seccion.length) {
      $('html, body').animate({
        scrollTop: seccion.offset().top-80
      }, 1000);
      return false;
    }
  }
  ...
}


text:
Q: vs2010 build error with BOOST_MOVABLE_BUT_NOT_COPYABLE The following is the simplified code:
--------------class foo-----------------------
class foo : private boost::noncopyable      //--- mark 1---
{
    BOOST_MOVABLE_BUT_NOT_COPYABLE(foo)     //--- mark 2---

public:

    /**
     * Move constructor.
     */
    foo(BOOST_RV_REF(foo) other);

    /**
     * Move-assignment.
     */
    foo& operator=(BOOST_RV_REF(foo) other);

    /**
     * Releases
     */
    ~foo();
    ......
private:
    fool_impl*  m_pimpl;
}

foo::foo(foo_impl* pimpl)
:m_pimpl(pimpl)
{}

foo::foo(
    BOOST_RV_REF(foo) other) : m_pimpl(other.m_pimpl)
{
    other.m_pimpl = NULL;
}

foo& foo::operator=(
    BOOST_RV_REF(foo) other)
{
    if (&other != this)
    {
        delete m_pimpl;
        m_pimpl = other.m_pimpl;
        other.m_pimpl = NULL;
    }

    return *this;
}

foo::~foo()
{
    delete m_pimpl;
}

---------------class bar-----------
class bar
{
public:

    explicit bar(BOOST_RV_REF(foo) other);

    ......

private:

    foo m_foo;
};

bar::bar(BOOST_RV_REF(foo) other)
:
m_foo(other)                        //--- mark 3----
{}

when build with VS2010, mark 3 reports errors:

error C2248: 'foo' : cannot access private member declared in class 'foo'
1>   mark 1:  see declaration of 'foo'
1>   mark 2:  see declaration of 'foo'

I tried to modified some code, but useless.
Can anyone give any advice? Thanks.

@Piotr S.
Thanks for your answer, I tried, the error disappeared, but another error appeared:
class test
{
public:

    explicit test(
        BOOST_RV_REF(foo) other);

private:
    boost::shared_ptr<aClass> m_class;
};

test::test(BOOST_RV_REF(foo) other)
{
    m_class = boost::make_shared<aClass>(boost::ref(other));
}

error LNK2019: unresolved external symbol "private: __cdecl foo(class foo const &)" referenced in function "class boost::shared_ptr __cdecl boost::make_shared const >(class boost::reference_wrapper const &&)"
can you give any advice? Thanks!

A: You need to use boost::move():
bar::bar(BOOST_RV_REF(foo) other)
:
    m_foo(boost::move(other)) // move it !
{}

otherwise, the compiler is trying to access copy constructor foo(const foo&), which is inaccessible as this type is noncopyable. boost::move casts the value back to r-value reference (or whatever is hidden behind BOOST_RV_REF(foo) that emulates r-value references in C++03), making the proper call to foo(BOOST_RV_REF(foo) other).


text:
Q: Error with big number calculations: Why is this happening? I have created a small Python program in repl.it to illustrate the Collatz Conjecture, which says that if you start with any positive integer number n and you apply the following operations recursively: n/2 if n is even, 3n+1 if n is odd, you will always reach 1.
This is the code:
invalid_input = 0

while(invalid_input == 0):
  n = input("Give me a positive integer: ")

  try: #check for positive integer. If it cannot do int(n) it means a string was entered, and it goes to except.
    if(int(n)>0):
      invalid_input = 1 #this is to tell the while loop above that the right input was entered
      print("Thank you.")
      print("Now loading:")

    else: #an integer was entered, but it was negative
      print("Please enter a positive integer")
  except: #a string was entered
    print("Please enter a positive integer")

n=int(n)
nentered = n #this will keep track of the initial n
npeak = n #this will keep track of the highest n reached
iteration = 1 #this will keep track of the number of iterations
iterationmax = 1 #this will keep tack of the iteration at which npeak was reached

while(n != 1):
  print("%5i:    %5i" % (iteration,n))
  if(n % 2 == 0): #divide by 2 if even
    n=n/2
  else: #if it is odd, multiply by 3 and add 1
    n=3*n+1
  iteration = iteration + 1
  if(n>npeak): #record the higher n and its iteration
    npeak = n
    iterationmax = iteration

It works. But there is a problem: if the entered number is big enough, for example 6666666666666666666666666, then it does something really strange. This is what I get:
Give me a positive integer: 6666666666666666666666666
Thank you.
Now loading:
    1:    6666666666666666666666666
    2:    3333333333333333277409280
    3:    1666666666666666638704640
    4:    833333333333333319352320
    5:    416666666666666659676160
    6:    208333333333333329838080
    7:    104166666666666664919040
    8:    52083333333333332459520
    9:    26041666666666666229760
   10:    13020833333333333114880
etc

As you can see, I am expecting the second number to be exactly 3333333333333333333333333, but instead I am getting different numbers at the end.
As another example, entering 1000000000000000000000000 returns 499999999999999991611392 in the second iteration.
What could be the reason for this?

A: Change your / operation to be //, so that they don't result in (inaccurate) floating point values.
So this:
if(n % 2 == 0): #divide by 2 if even
  n=n/2

Should be:
if(n % 2 == 0): #divide by 2 if even
  n=n//2

Or as properly formatted by Python conventions:
if n % 2 == 0:
    n //= 2

A: The reason of why what @ruohola said is true, is because when you use floating-point division with a single /, what happens is that a floating-point number is created. However, it cannot be represented as the number is so large, so it is rounded to the closest most accurate representation. So you will have to use // instead of /.
However, using //, is integer division. This results in an integer which can be represented much easier than a high float.
A very similar question can be found here, it contains some more explanation.


text:
Q: Deserialize is not implemented So I'm learning how to build a REST API with Rust. I keep getting an error when trying to implement the following line:
 #[derive(Deserialize, Debug)]
  pub struct Config {
      pub pg: deadpool_postgres::Config,
      pub server: ServerConfig,
}

And this is the error code I'm getting:
 error[E0277]: the trait bound `deadpool_postgres::Config:
 config::_::_serde::Deserialize<'_>` is not satisfied

Here are my dependencies in Cargo.toml:
[dependencies]
actix-rt = "2.3.0"
actix-web = "3.3.2"
serde = "1.0.130"
dotenv = "0.15.0"
config = "0.11.0"
tokio-pg-mapper = "0.2.0"
tokio-pg-mapper-derive = "0.2.0"
deadpool-postgres = "0.10.0"
tokio-postgres = "0.7.3"

I'm new to Rust and I'm not exactly sure what the error means or what to do to fix it. I'm implementing deadpool_postgres just like how it is in the docs, except in my file I'm trying to pull the database variables from a dotenv file. Here's the complete file:
use::config::ConfigError;
use serde::Deserialize;

#[derive(Deserialize, Debug)]
pub struct Config {
    pub pg: deadpool_postgres::Config,
    pub server: ServerConfig,
}

#[derive(Deserialize, Debug)]
pub struct ServerConfig {
    pub host: String,
    pub port: i32
}

impl Config {
    pub fn from_env() -> Result<Self, ConfigError> {
        let mut cfg = config::Config::new();
        cfg.merge(config::Environment::new())?;
        cfg.try_into()
    }
}

A: The compiler tells you the deadpool_postgres::Config struct doesn't implement Deserialize.
You need to enable the "serde" feature in your Cargo.toml to get this implementation (see list of features).
This can be done like this:
[dependencies]
deadpool-postgres = { version = "0.10.0", features = ["serde"] }


text:
Q: Discord.NET audit log based invite tracker not sending desired message I apologize to those of you that saw my last post reguarding. I see that it was too vague I was just not in the right headspace but hopefully this post sustains enough information about the issue. I have been trying to debug this auditlog based invite tracker for an absurd amount of time and have lost sanity. The idea behind this is that using a onmemberjoin event the bot can use the audit logs to fetch the invite that the user used to join the guild and will send a log with information about that to a specified log channel. I can see in the debugging that the auditlog is being collected but the message is not being sent. it seems from the information I gained trying to debug that it is somehow getting stopped between the foreach and the if statement the line under it somehow of which I have no clue on how that could be possible. If anyone could help me find the issue I would be extremely grateful.
private async Task OnMemberJoin(SocketGuildUser arg)
        {
            var g = arg.Guild;
            var channelId = await _servers.GetLogsAsync(g.Id);
            var chnlIdInt = Convert.ToInt64(channelId);
            if (chnlIdInt == 0) return;
            if (!g.CurrentUser.GuildPermissions.ViewAuditLog)
            {
                await _serverHelper.SendLogAsync(g, "Bot Does Not Have Sufficient Permissions",
                    "A event logger has failed its task because I do\nnot have `View Audit Log` permissions. To solve this error please\ngive me that permission");
                return;
            }

            var auditlogs = await g.GetAuditLogsAsync(1, null, null, null, ActionType.InviteUpdated)
                .FlattenAsync();

            foreach (var audit in auditlogs)
                if (audit.User is IUser && audit.Data is InviteUpdateAuditLogData d1)

                {
                    var inv3 = _client.Guilds
                        .OfType<InviteUpdateAuditLogData>()
                        .FirstOrDefault(x => x.After.Code.ToString().IndexOf(
                                                 d1.After.Code,
                                                 StringComparison.OrdinalIgnoreCase) !=
                                             -1);
                    if (inv3 == null) return;

                    if (inv3 is IInvite iInvite)

                    {
                        var uses = d1.Before.MaxUses.Value - d1.After.MaxUses.Value;
                        await _serverHelper.SendLogAsync(g, "Invite Used",
                            $"An invite has been used.\nInvite: {iInvite.Url}\nTotal invite uses: `{uses.ToString()}`\nInvite created by: {iInvite.Inviter.Mention}");
                        return;
                    }
                }


text:
Q: File not found: Beautiful Soup I am trying to run a program that I downloaded in Ubuntu latest version, but I continue getting an error everytime I try to run the program. It says:
File Not Found: BeautifulSoup

So in order to attempt to fix this, I've downloaded the bs4 beautiful soup  package through the command line. I've tried running python, and then importing it by doing, from bs4 import BeautifulSoup.
I have tried many different variations of this and downloading and redownloading it. I've tried running the from bs4 import BeautifulSoup directly from the terminal, but that did not work and returned an error.
Does anyone know anyway to fix this issue or what I need to do?

A: You can install the package python-beautifulsoup in a Ubuntu system running the command below as root:
apt-get install python-beautifulsoup

This will install the package under /usr/share/pyshared and importing it should work.


text:
Q: javascript detect if user left the site or just refreshed/clicked link I am using a nodejs server to display online users, but it activates the disconnected function even when the user clicks a link or refreshes the page, I am trying to bypass this, by sending a message to the server only if the user closes the tab/window with the following code:
var socket = io.connect('http://example.com:8000');

socket.emit('started', { username: "TestUser", });

var clicked = false;

$(document).ready(function() {
    $("a[href]").click(function() {
        clicked = true;
    });

    $(document).bind('keypress keydown keyup', function(e) {
        if(e.which === 116) {
            clicked = true;
        }
        if(e.which === 82 && e.ctrlKey) {
            clicked = true;
        }
    });
});

window.onbeforeunload = function(e){
    if(!clicked) {
        socket.emit('userDisconnected', { user: "TestUser" });
    }
};

this works for if a user clicked a link and also when a user presses F5, but how can I detect if they clicked the browsers refresh button
I basically want the userDisconnected message to be sent ONLY when the user leaves my website
thanks

A: Not possible, and if it were it would probably be considered a bug. But what you did here is clever, looking for key events.
Depending on what you actually want to accomplish, you can approach it another way. Send a notification through your socket on every window unload. Put that socket on standby by setting a timeout event on that socket. Have your page also emit a reconnect signal on refresh or navigation within your site (something saying I'm back). If a socket on standby does not receive this signal within 5 (or some other number) seconds, close the connection on the server. If it does, cancel the timeout.


text:
Q: How to make a dataframe of windows? Suppose I have a pandas series:
0 x[0]
1 x[1]
...
n x[n]
...

and I want to create a pandas.Dataframe whose rows are the windows of size k in the dataframe. So, for k=2, we have
  1     0
0 x[0]  x[1]
1 x[1]  x[2]
2 x[2]  x[3]
...
n-1 x[n-1] x[n]

There are some obvious clunky ways of doing it, but it seems like there should be a one-line way.

A: Not ideal, but likely better than a raw for loop would be:
Code:
def shift_to_columns(vector, k):
    return pd.DataFrame({i: vector.slice_shift(-i)[:len(vector)-k+1]
                         for i in range(k)})

Test Code:
import pandas as pd
data = pd.Series(range(10))
print(data)
print(shift_to_columns(data, 3))

Results:
0    0
1    1
2    2
3    3
4    4
5    5
6    6
7    7
8    8
9    9

dtype: int64
   0  1  2
0  0  1  2
1  1  2  3
2  2  3  4
3  3  4  5
4  4  5  6
5  5  6  7
6  6  7  8
7  7  8  9


text:
Q: Getting "containers with unready status: []" error in Kubernetes I'm trying to deploy a Kubernetes Pod in AKS (I'm new to Kubernetes, so at this stage, I just want to create a container, deploy to Kubernetes and connect to it).
My Yaml file is as follows:
apiVersion: v1
kind: Pod
spec:
  containers:
    - name: dockertest20190205080020
      image: dockertest20190205080020.azurecr.io
      ports:
      - containerPort: 443
metadata:
  name: my-test

I've created the image in Azure Container Registry and, according to the CLI, successfully deployed it to Kubernetes.
After deploying, I used the following command:
kubectl get service

And it tells me there is no External IP to connect to.  I then tried:
kubectl describe pod my-test

Which gave the following errors:
 Events:
   Warning  Failed   4m (x2221 over 8h)  kubelet, aks-nodepool1-27401563-2  Error: ImagePullBackOff
   Normal   BackOff  0s (x2242 over 8h)  kubelet, aks-nodepool1-27401563-2  Back-off pulling image "dockertest20190205080020.azurecr.io"

I then tried editing the deployment:
kubectl edit pods my-test

Which game me the error:
message: 'containers with unready status: [dockertest20190205080020]'

I'm not a little unsure what my next diagnostic step would be.  I get the impression there's an issue with the container or the container registry, but I'm unsure how to determine what that may be.

A: What happens here (most likely) - your AKS doesnt have permissions to pull images frmo you ACR (that's the default behaviour). You need to grant those (link):
#!/bin/bash

AKS_RESOURCE_GROUP=myAKSResourceGroup
AKS_CLUSTER_NAME=myAKSCluster
ACR_RESOURCE_GROUP=myACRResourceGroup
ACR_NAME=myACRRegistry

# Get the id of the service principal configured for AKS
CLIENT_ID=$(az aks show --resource-group $AKS_RESOURCE_GROUP --name $AKS_CLUSTER_NAME --query "servicePrincipalProfile.clientId" --output tsv)

# Get the ACR registry resource id
ACR_ID=$(az acr show --name $ACR_NAME --resource-group $ACR_RESOURCE_GROUP --query "id" --output tsv)

# Create role assignment
az role assignment create --assignee $CLIENT_ID --role acrpull --scope $ACR_ID

Alternative is to just use a docker login secret (that article mentions that as well).
Example image in ACR:

image name would be
clrtacr.azurecr.io/dns:tag (or without tag for latest)

A: I'm not sure if you know there is something wrong in your yaml file, or it just shows as you want for security. But I would show you here:
apiVersion: v1
kind: Pod
spec:
  containers:
    - name: dockertest20190205080020
      image: dockertest20190205080020.azurecr.io/image_name_and_version
      ports:
      - containerPort: 443
metadata:
  name: my-test

Also, as the error that you got shows, you don't have the permission to pull the image from your ACR.
On my side, I would be better to use a secret for pulling all the image from the ACR. You can create a service principal to achieve it. The steps would be like here:
#!/bin/bash

ACR_NAME=myacrinstance
SERVICE_PRINCIPAL_NAME=acr-service-principal

# Populate the ACR login server and resource id.
ACR_LOGIN_SERVER=$(az acr show --name $ACR_NAME --query loginServer --output tsv)
ACR_REGISTRY_ID=$(az acr show --name $ACR_NAME --query id --output tsv)

# Create acrpull role assignment with a scope of the ACR resource.
SP_PASSWD=$(az ad sp create-for-rbac --name $SERVICE_PRINCIPAL_NAME --role acrpull --scopes $ACR_REGISTRY_ID --query password --output tsv)

# Get the service principal client id.
CLIENT_ID=$(az ad sp show --id http://$SERVICE_PRINCIPAL_NAME --query appId --output tsv)

# Output used when creating Kubernetes secret.
echo "Service principal ID: $CLIENT_ID"
echo "Service principal password: $SP_PASSWD"

# Create the secret
kubectl create secret docker-registry acr-auth --docker-server <acr-login-server> --docker-username <service-principal-ID> --docker-password <service-principal-password>

Then you can change your yaml file like this:
apiVersion: v1
kind: Pod
spec:
  containers:
    - name: dockertest20190205080020
      image: dockertest20190205080020.azurecr.io/image_name_and_version
      ports:
      - containerPort: 443
  imagePullSecrets:
  - name: acr-auth
metadata:
  name: my-test


text:
Q: Django loaddata error doesn't show message I have Mezzanine app and my purpose is to move data from sqlite3 to prostgres.
I found this solution which solved some erors.
But now I have something wrong again and can't understand what actually happend because I got just name of error django.db.utils.DataError.
Here is full Traceback:
manage.py loaddata dump.json
Traceback (most recent call last):
  File "D:\GitRepos\newbesturfu\manage.py", line 14, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 338, in execute_from_command_line
    utility.execute()
  File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 330, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Python27\lib\site-packages\django\core\management\base.py", line 393, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Python27\lib\site-packages\django\core\management\base.py", line 444, in execute
    output = self.handle(*args, **options)
  File "C:\Python27\lib\site-packages\django\core\management\commands\loaddata.py", line 60, in handle
    self.loaddata(fixture_labels)
  File "C:\Python27\lib\site-packages\django\core\management\commands\loaddata.py", line 90, in loaddata
    self.load_label(fixture_label)
  File "C:\Python27\lib\site-packages\django\core\management\commands\loaddata.py", line 147, in load_label
    obj.save(using=self.using)
  File "C:\Python27\lib\site-packages\django\core\serializers\base.py", line 173, in save
    models.Model.save_base(self.object, using=using, raw=True)
  File "C:\Python27\lib\site-packages\django\db\models\base.py", line 738, in save_base
    updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  File "C:\Python27\lib\site-packages\django\db\models\base.py", line 803, in _save_table
    forced_update)
  File "C:\Python27\lib\site-packages\django\db\models\base.py", line 853, in _do_update
    return filtered._update(values) > 0
  File "C:\Python27\lib\site-packages\django\db\models\query.py", line 580, in _update
    return query.get_compiler(self.db).execute_sql(CURSOR)
  File "C:\Python27\lib\site-packages\django\db\models\sql\compiler.py", line 1062, in execute_sql
    cursor = super(SQLUpdateCompiler, self).execute_sql(result_type)
  File "C:\Python27\lib\site-packages\django\db\models\sql\compiler.py", line 840, in execute_sql
    cursor.execute(sql, params)
  File "C:\Python27\lib\site-packages\django\db\backends\utils.py", line 79, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "C:\Python27\lib\site-packages\django\db\backends\utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "C:\Python27\lib\site-packages\django\db\utils.py", line 97, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "C:\Python27\lib\site-packages\django\db\backends\utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
django.db.utils.DataError

I use Windows 10, Django 1.8.3 and PostgreSQL 9.4.
Does anyone know how to show full error message or may be know how to get rid of this issue?


text: Q: Formula or code to map cross-quadrilateral to square I'm building an image warping tool. Photoshop's free transform tool not only supports mapping an rectangular image to a quadrilateral, but also supports cross-quadrilaterals. I'm looking for a formula or piece of code which allows mapping between square and cross-quadrilateral. For normal quadrilateral mappings there is a publication by Heckbert (http://graphics.cs.cmu.edu/courses/15-463/2006_fall/www/Papers/proj.pdf) which fits my needs. Any pointers are appreciated!


text:
Q: The truth value of an array with more than one element is ambiguous when calculating similarity measure between 2 vectors I have a list of source vector and a list of target vector :
I would like to calculate for each source vector its similarity measure with every target vector .
For this I did this function :
def calculate_similarity2(source_doc, target_docs, threshold=0):
        """Calculates & returns similarity scores between given source document & all the target documents."""
        results = []
        for doc1 in source_doc:
            source_vec = vectorize(doc1)
            #print(source_vec)
            for doc in target_docs:
                target_vec = vectorize(doc)
                #print(target_vec)
                sim_score = np.dot(source_vec, target_vec) / (np.linalg.norm(source_vec) * np.linalg.norm(target_vec))
                print(sim_score)
                if sim_score > threshold:
                    results.append({
                        'score' : sim_score,
                        'source sentence' : doc1,
                        'target sentence' : doc

                    })
            # Sort results by score in desc order
            results.sort(key=lambda k : k['score'] , reverse=True)

        return results

But I get an error :
ValueError                                Traceback (most recent call last)
<ipython-input-186-c025176ea126> in <module>()
----> 1 sim_scores = calculate_similarity2(source_doc, target_docs)

<ipython-input-185-5c04abb8d5ed> in calculate_similarity2(source_doc, target_docs, threshold)
     10                 sim_score = np.dot(source_vec, target_vec) / (np.linalg.norm(source_vec) * np.linalg.norm(target_vec))
     11                 print(sim_score)
---> 12                 if sim_score > threshold:
     13                     results.append({
     14                         'score' : sim_score,

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Can you help me to resolve this error please?
Thanks


text:
Q: Vue.set two different object properties with the same reference I'm trying to add an object into an array using Vue.set function, but it adds the item to another object with the same array property.
data() {
    return {
      ...
      form: {
        ...
        client_a: {
           ...
           items: []
        },
        client_b: {
           ...
           items: []
        },
      }
    };
  },

When I do: (note that I'm adding an item to client_a.items)
this.$set(this.form.client_a.items, 'key', { prop1: '', prop2: '' })

Then client_b.items var has the same value of client_a
console.log(this.form.client_b.items)

Outputs
[
   'key': { prop1: '', prop2: '' }
]

The expected result of this.form.client_b.items is
[]

as I don't added anything into it
Code example: https://codesandbox.io/s/proud-fast-bjvyr

A: As @skirtle points out, the base_client.functions-property is the same array.
A simple fix in beforeMount():
beforeMount() {
  this.form.client_a = {
    ...this.base_client,
    functions: []
  }
  this.form.client_b = {
    ...this.base_client,
    functions: []
  }
  this.form.functions = [
    {
      key: "key-1",
      name: "Test"
    }
  ];
}

Not too elegant, but should work. Another way to do it is to make base_client a method with a return value, where you generate a new returns-array every time.


text:
Q: How to write data one by one from tmp files to the final output file using for loop? I have two tmp files named tmp1 and tmp2 which contains some lines.
tmp1 file,
1c\
datafile no. 23
2c\
datafile is ok

tmp2 file,
3c\
datafile no. 24
4c\
datafile is ok

I have a file (named wrong_file) which entries I want to correct from tmp files
datafile no. 32
datafile is ok
datafile no. 42
datafile is ok

My output file (modified_file) will be like,
datafile no. 23
datafile is ok
datafile no. 24
datafile is ok

I want use for loop which will run until the last tmp file and write data from tmp files to final file (Output) instead doing it manually.
I have tried,
sed -f tmp1 wrong_file > file1
sed -f tmp2 file1 > modified_file

A: I'm pretty sure you can just do:
cat ./tmp[12] | sed -f - ./wrong_file >outfile

At least, that will not cause any issues if all of sed's script instructions are specific to line number. There's no need to apply the scripts separately - you can chain them all together and run the script at once.
That you have to do this at all, though, is indicative of duplicated work. Here is a copy of a sed script which would avoid writing any of those tempfiles in the first place and simply scan input for the lines which need changing before passing all of the script in a stream to the final sed in one go:
{   sed '/^#\.tid\.setnr/!d;=;g;G' |
    paste  -d'c\\\n' - - - ./addfile
}   <./mainfile | sed -f - ./mainfile

Its output is not identical to your sample data here because it is tailored to the samples you provided in the other question. But it avoids writing out the modification scripts at all and sends all editing commands to a sed process which can take action immediately.
In general you can consider that a sed process is just as ready to handle its script input in all of the ways it might also be ready to handle its edit content input.-


text:
Q: How to add custom framework in a project? I am making an app in which I am using BMSocialShare.framework for Facebook sharing. I have add this framework in my project by this step - Add File to "My_project"  -> select framework -> add. But when I deploy this project in another system them I have got this framework
missing and got this type of warning -
warning: Could not find object file

"/Users/vinzenzweber/Library/Developer/Xcode/DerivedData/BMSocialShare-gedvbinixmfywidbwutkdxrdvdzo/Build/Intermediates/BMSocialShare.build/Release-iphonesimulator/BMSocialShareFramework.build/Objects-normal/i386/BMSocialShare.o"
  - no debug information available for "/Users/vinzenzweber/Documents/xcodeworkspace/blockhaus-git/BMSocialShare/iOS/BMSocialShare/BMSocialShare/BMSocialShare.m".

and app get crashed. So can you suggest me that what is the proper way to add an framework if framework is not present in our existing list.

A: You can follow below steps:
1) Create sub-folder in your project and add framework into that folder.
2) Now, open Build Phases -> Link Binary With Libraries. And click on '+' button.
3) Then click on "Add Other" instead of adding default framework.
Now, you have added framework successfully.
That's it.
Cheers!

A: First copy and paste your frame work in where ever your project location and then do the same task that you have been done this is working
and another thing when ever you deploy this in another system make sure send the project with compress means zip file


text:
Q: how to use HTML tags to format text in an EditText in android my code looks like this
txtData=(EditText)findViewById(R.id.textbox);
txtData.setText(Html.fromHtml(""));

as you can see i am trying to make HTML code appear in an EditText box. I am trying to use HTML tags using the Html.fromHtml() method to format the HTML code that appears in the box.
i need to find a way to escape the '<' and '>' tags around the word html from being processed by the fromHtml method. any suggestions on how to do this ?

A: Try this:
txtData.setText(Html.fromHtml("<html>"));

A: try this:
txtData=(EditText)findViewById(R.id.textbox);
txtData.setText(Html.fromHtml("<html>"));

or
txtData=(EditText)findViewById(R.id.textbox);
txtData.setText(Html.fromHtml("<html>"));

A: You should use
 <

and
 >

as in this example
txtData.setText(Html.fromHtml("<html>"));