Q:

How to assign grid row and column index dynamically

I am trying to add user controls to the Grid and I am trying to set the Grid.Column and Grid.Row property in the DataTemplate but it does not have any effect on the rendering. Can someone help to point out what could be wrong in the code below.
I have the main window with the following code:
<ItemsControl ItemsSource="{Binding Controls}">
    <ItemsControl.ItemsPanel >
        <ItemsPanelTemplate>
            <Grid Name="MainGrid">
                <Grid.RowDefinitions>
                    <RowDefinition/>
                    <RowDefinition/>
                    <RowDefinition/>
                    <RowDefinition/>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition/>
                    <ColumnDefinition/>
                    <ColumnDefinition/>
                    <ColumnDefinition/>
                </Grid.ColumnDefinitions>
            </Grid>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>

    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <AppControls:TagInfo Grid.Row="{Binding RowIndex}"
                                 Grid.Column="{Binding ColumnIndex}"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

TagInfo.xaml.cs
public partial class TagInfo : UserControl
{
    public TagInfo()
    {
        InitializeComponent();
    }

    public int RowIndex { get; set; }

    public int ColumnIndex { get; set; }
}

TagInfo.xaml
<UserControl x:Class="DataSimulator.WPF.Controls.TagInfo"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d" Height="258" Width="302"
             DataContext="{Binding Main, Source={StaticResource Locator}}">
    <Grid Margin="2,2,2,2">
        <Grid.RowDefinitions>
            <RowDefinition Height="40"/>
            <RowDefinition Height="30"/>
            <RowDefinition Height="30"/>
            <RowDefinition Height="30"/>
            <RowDefinition Height="30"/>
            <RowDefinition Height="30"/>
            <RowDefinition Height="30"/>
            <RowDefinition Height="30"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="100"/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>

        <TextBlock Grid.Row="0" Grid.Column="0" Text="Tag"/>
        <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding TagInfo.TagName}"/>

        <TextBlock Grid.Row="1" Grid.Column="0" Text="High High"/>
        <TextBox Grid.Row="1" Grid.Column="1" Text="{Binding TagInfo.HighHigh}"/>

        <TextBlock Grid.Row="2" Grid.Column="0" Text="High"/>
        <TextBox Grid.Row="2" Grid.Column="1" Text="{Binding TagInfo.High}"/>

        <TextBlock Grid.Row="3" Grid.Column="0" Text="Low Low"/>
        <TextBox Grid.Row="3" Grid.Column="1" Text="{Binding TagInfo.LowLow}"/>

        <TextBlock Grid.Row="4" Grid.Column="0" Text="Low"/>
        <TextBox Grid.Row="4" Grid.Column="1" Text="{Binding TagInfo.Low}"/>

        <TextBlock Grid.Row="5" Grid.Column="0" Text="Range Start"/>
        <TextBox Grid.Row="5" Grid.Column="1" Text="{Binding TagInfo.RangeStart}"/>

        <TextBlock Grid.Row="6" Grid.Column="0" Text="Range End"/>
        <TextBox Grid.Row="6" Grid.Column="1" Text="{Binding TagInfo.RangeEnd}"/>

        <Button Grid.Row="7" Grid.Column="0" Grid.ColumnSpan="2" Content="Save"/>
    </Grid>
</UserControl>

ViewModel
private ObservableCollection<Controls.TagInfo> _controls
        = new ObservableCollection<Controls.TagInfo>();

public ObservableCollection<Controls.TagInfo> Controls
{
    get { return _controls; }
    set { _controls = value; }
}

private void AddControl()
{
    if(currentRow == 3)
    {
        currentRow = 0;
    }

    if(currentColumn == 3)
    {
        currentColumn = 0;
        currentRow++;
    }

    var tagInfoUserControl = new Controls.TagInfo();
    tagInfoUserControl.RowIndex = currentRow;
    tagInfoUserControl.ColumnIndex = currentColumn++;
    _controls.Add(tagInfoUserControl);
}

A:

I am trying to add user controls to the grid and I am trying to set the Grid.Column and Grid.Row property in the data template but it does not have any effect on the rendering

We can't do the attached property binding in a DataTemplate, creating a style for your UserControl in ItemsControl.ItemContainerStyle can make it work:
<ItemsControl ItemsSource="{Binding Controls}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Grid Name="MainGrid">
                <Grid.RowDefinitions>
                    <RowDefinition/>
                    <RowDefinition/>
                    <RowDefinition/>
                    <RowDefinition/>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition/>
                    <ColumnDefinition/>
                    <ColumnDefinition/>
                    <ColumnDefinition/>
                </Grid.ColumnDefinitions>
            </Grid>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemContainerStyle>
        <Style TargetType="AppControls:TagInfo">
            <Setter Property="Grid.Row" Value="{Binding RowIndex}"/>
            <Setter Property="Grid.Column" Value="{Binding ColumnIndex}"/>
        </Style>
    </ItemsControl.ItemContainerStyle>
</ItemsControl>

Screenshot:


Q:

get output volume with AppleScript

I'm writing an AppleScript which should show the value for the output volume. With get volume settings I'm getting 4 values, but I need just the output volume value. The integer should be shown in a display dialog.

A:

use this:
display alert output volume of (get volume settings)


Q:

Problem with Redisson Hibernate 2L cache config in Spring MVC

I am trying to configure Redisson Hibernate 2L cache in Spring MVC project.
I had follow tutorials, although most of them is devoted to Spring Boot.
I have added dependencies in pom.xml file:
<dependency>
  <groupId>org.redisson</groupId>
  <artifactId>redisson</artifactId>
  <version>3.12.0</version>
</dependency>
<dependency>
  <groupId>org.redisson</groupId>
  <artifactId>redisson-hibernate-53</artifactId>
  <version>3.11.6</version>
</dependency>

In persistance.xml (second level cache is set to false for now, because I only try to make it start the application):
<property name="hibernate.cache.region.factory_class" value="org.redisson.hibernate.RedissonRegionFactory"/>
  <property name="hibernate.cache.use_second_level_cache" value="false"/>
  <property name="hibernate.cache.use_query_cache" value="false"/>

And in my Configuration file:
    @Bean(destroyMethod="shutdown")
  RedissonClient redisson() {
    Config config = new Config();
    config.useClusterServers()
            .addNodeAddress("redis://127.0.0.1:6379");
    return Redisson.create(config);
  }

  @Bean
  CacheManager cacheManager(RedissonClient redissonClient) throws IOException {
    Map<String, CacheConfig> config = new HashMap<>();
    config.put("testMap",
            new CacheConfig(120000, 180000)); //2min TTL and 3min max idle time
    return new RedissonSpringCacheManager(redissonClient, config);
  }

Project is building correctly, but when I try to run it, I recieve an error:
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.cache.spi.CacheImplementor]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:275)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
    at org.hibernate.service.internal.SessionFactoryServiceRegistryImpl.getService(SessionFactoryServiceRegistryImpl.java:97)
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:238)
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:462)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:938)
    at org.hibernate.jpa.HibernatePersistenceProvider.createContainerEntityManagerFactory(HibernatePersistenceProvider.java:141)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:390)
    ... 63 more
Caused by: java.lang.IllegalStateException: Cache provider not started
    at org.hibernate.cache.spi.AbstractRegionFactory.verifyStarted(AbstractRegionFactory.java:65)
    at org.hibernate.cache.spi.support.RegionFactoryTemplate.buildTimestampsRegion(RegionFactoryTemplate.java:66)
    at org.hibernate.cache.internal.EnabledCaching.<init>(EnabledCaching.java:80)
    at org.hibernate.engine.spi.CacheInitiator.initiateService(CacheInitiator.java:33)
    at org.hibernate.engine.spi.CacheInitiator.initiateService(CacheInitiator.java:24)
    at org.hibernate.service.spi.SessionFactoryServiceInitiator.initiateService(SessionFactoryServiceInitiator.java:30)
    at org.hibernate.service.internal.SessionFactoryServiceRegistryImpl.initiateService(SessionFactoryServiceRegistryImpl.java:61)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263)
    ... 72 more
Caused by: org.hibernate.cache.CacheException: Unable to locate Redisson configuration
    at org.redisson.hibernate.RedissonRegionFactory.createRedissonClient(RedissonRegionFactory.java:107)
    at org.redisson.hibernate.RedissonRegionFactory.prepareForUse(RedissonRegionFactory.java:83)
    at org.hibernate.cache.spi.AbstractRegionFactory.start(AbstractRegionFactory.java:91)
    at org.hibernate.cache.internal.EnabledCaching.<init>(EnabledCaching.java:77)

I do not know what I'm missing in order to locate Redisson configuration..?
I would appreciate any help!

A:

You forgot to define path to Redisson config:
<property name="hibernate.cache.redisson.config" value="/redisson.yaml" />


Q:

To stuck or to be stuck

While buying a ticket from one of the main low-fare flight operators in Europe I've encountered a pop-up with this message:

Select a seat if you don`t want to stuck in the middle row!

Is this the correct grammar? I always thought that the correct form is "to be stuck" but it is hard to imagine to me that such a big company would make a grammar error on their website.

A:

No, it's a mistake. Probably simply left out the word "be" or "get".


Q:

Using mutual recursion to do a binary comparison of two files; would prefer to use one method, calling itself. How?

I've made a crossword (and similar) puzzle helper, which enables searching a dictionary for matches to a pattern such as pa??ern, pa*, pa??ern*, etc., where ? and * have the same meaning as wildcards in Windows (? matches any letter; * matches any number of letters [including 0]).
I found two text dictionaries online, one with 108,000+ words, the other with 80,000+. I assumed that the smaller would be a subset of the larger. Not even close.
So I wrote a Java program to compare and to print any word that is in one dictionary but not in the other. (Turned out there were 24,000+ words in the smaller than in the larger; 52,000+ in larger but not in smaller. So I now, via another program, have a dictionary with 132,000+ words.)
I used mutual recursion to accomplish this:
-When current words match, continue; nothing to print here.
-When current word from dictionary A is "<" than current word in B, then...
     * print and read A until finding word ">=" current word in B.
       --If '=', they match; continue without printing.
       --If '>', then reverse the process:
       * print and read B until finding word ">=" current word in A.
...

This is all there is to the logic. I really like recursion because it's how we think, though it's often very hard to get those thoughts into code.
And some things about the nature of programmatic recursion are very hard.
In particular, I had to use "dual" methods: one for reading A until >= B; one for reading B until >= A.
I tried to make one routine that would call itself in the same way the different routines call each other, as described above in pseudocode.
I'm asking for someone to show me how to use ONE method to call itself to accomplish the goal.
Here's the code that works but is inefficient, as described:
package filecomparison;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;

public class ShorterBinaryCompare {
  static int      kta = 0, exa = 0,     ktb = 0, exb = 0;
  static Scanner  sca,                  scb;
  static String   reca,                 recb;
  static Path a = Paths.get("C:\\newdic.txt");
  static Path b = Paths.get("C:\\WordHelp.dick");

  private static int read_a_untilGE_b(){
    while(sca.hasNext()){
      if(reca.equals(recb))        return 0; // 0 => a = b
      if(reca.compareTo(recb) > 0) break;         // a > b
      System.out.println(reca); exa++; kta++;
      reca = sca.next();
    }
    read_b_untilGE_a();
    return 0;
  }

  private static int read_b_untilGE_a(){
    while(scb.hasNext()){
      if(recb.equals(reca))        return 0;  // a = b
      if(recb.compareTo(reca) > 0) break;     // b > a
      System.out.println("\t\t" + recb); exb++; ktb++;
      recb = scb.next();
    }
    read_a_untilGE_b();
    return 0;
  }

  private static void drain(String msg, Scanner sc){
    int k = 0;
    System.out.println("\n\nDraining " + msg);
    String s;
      while(sc.hasNext()){
        s = sc.next();
        System.out.println(s);
        ++k;
      }
      System.out.println("\nExtras at end: " + k);
  }

  public static void main(String[] args) throws IOException {

    System.out.println("Compare:\n" + a + " vs. \n" + b + "\n");

    sca = new Scanner(a);   scb = new Scanner(b);

    while(sca.hasNext() && scb.hasNext()){

        reca = sca.next(); kta++;
        recb = scb.next(); ktb++;

        int compareResult = reca.compareTo(recb);

        if(     compareResult < 0) read_a_untilGE_b();   // a < b
        else if(compareResult > 0) read_b_untilGE_a() ;  // a > b
                   // mutually-recursive read...untils make a = b at this point
    }
    System.out.println("\n\nRecords in " + a.toString() + ": " + kta);
    System.out.println("Extras in " + a.toString() + ": " + exa);
    System.out.println("Records in " + b.toString() + ": " + ktb);
    System.out.println("Extras in " + b.toString() + ": " + exb);
    if(sca.hasNext()){ drain(a.toFile().toString(), sca); }
    if(scb.hasNext()){ drain(b.toFile().toString(), scb); }
  }
}

Here's the last version I tried of one method calling itself. It worked as long as it was the "left" file with the extra words, but when it changed so that the "right" file had the extras, it didn't take long to get stack overflow. Maybe I'm closer than I thought; but I'm out of gas for the day.
Can you modify the method below, which calls itself, to do what mutual recursion does in the code above?
  private static int read_untilGE_(Scanner a, Scanner b){
    String sa, sb;
    if(b.hasNext())
      sb = b.next();
    else
      return -1;
    System.out.println("Extra in " + a.toString());
    while(sca.hasNext()){
      sa = sca.next();
      if(sa.equals(sb))        return 0;  // a = b
      if(sa.compareTo(sb) > 0) break;     // a > b
      System.out.println(sa); exb++; ktb++;
    }
    read_untilGE_(b, a);
    return 0;
  }

A:

You got off to the right start by passing your two Scanners as parameters to your method, so that you call your method recursively by switching the parameters.  Then you erred by using a Scanner (sca) that wasn't one of the parameters.


Q:

Declaring an object when type is "unknown"

Here is my problem:
I have the function
public static void fillObject(object [] obs, DataTable dt)
{
    for (int j = 0; j < dt.Rows.Count; j++)
    {
        DataRow dr = dt.Rows[j];
        fillObject(obs[j], dr);
    }
}

obs is an array of some type of class (let say for the example "sheep") when I debug I get that obs[j] is a null and not an object type of sheep so I need to do something like
obs[j] = new sheep();

any ideas?

A:

If you want to strongly type your solution, you can use generics
public static void FillObject<T>(T [] obs, DataTable dt) where T: new
{
    //...

    obs[j] = new T();
}

You would then call the function like
FillObject<Sheep>(mySheep, dt);


Q:

Send a raw ethernet packet from inside a kernel module

I found out that I need to build a new sk_buff struct in the kernel module and pass it to my network device, but what I can't figure out is how to set the struct variables for a simple raw ethernet packet.
This has to be easy, but I would really appreciate it, if someone could give me a sample code of how to put the sk_buff together.

A:

Take a look at the function packet_sendmsg_spkt in net/packet/af_packet.c for inspiration.  The hard part is getting a struct sock if you don't have a socket...
Edit: Added a basic code shell:
int sendpacket(struct socket *sock, struct net_device *dev, __be16 proto, void *data, size_t len)
{
    struct sock *sk = sock->sk;
    struct sk_buff *skb;

    if (!(dev->flags & IFF_UP))
        return -ENETDOWN;

    if (len > dev->mtu + dev->hard_header_len)
        return -EMSGSIZE;

    skb = sock_wmalloc(sk, len + LL_RESERVED_SPACE(dev), 0, GFP_KERNEL);

    if (skb == NULL)
        return -ENOBUFS;

    /* FIXME: Save some space for broken drivers that write a
     * hard header at transmission time by themselves. PPP is the
     * notable one here. This should really be fixed at the driver level.
     */
    skb_reserve(skb, LL_RESERVED_SPACE(dev));
    skb_reset_network_header(skb);

    /* Try to align data part correctly */
    if (dev->header_ops) {
        skb->data -= dev->hard_header_len;
        skb->tail -= dev->hard_header_len;
        if (len < dev->hard_header_len)
            skb_reset_network_header(skb);
    }

    memcpy(skb_put(skb, len), data, len);
    skb->protocol = proto;
    skb->dev = dev;
    skb->priority = sk->sk_priority;

    dev_queue_xmit(skb);

    return len;
}


Q:

how to get functionName from a javascriptCode which is in string format

this is my code
var javascriptCode="function adding(a,b){ return a+b}"

and i want to pick functionName adding from that string how to do that?
i have tried by finding its index as
var indexStart=javascriptCode.indexOf("function ");
var indexEnd=javascriptCode.indexOf("(");
var res = javascriptCode.substring(indexStart, indexEnd);

but i am getting the output as
function adding, is their any other way to do this

A:

You could use regular expression.
var javascriptCode="function adding(a,b){ return a+b}"
var regex = /function\s*([^\(]*)\(/
var matchResult = javascriptCode.match(regex)
var funcName = null;
if (matchResult && matchResult.length) {
    funcName = matchResult[1];
}
console.log(funcName);


Q:

Gmail blocking pixel tracking / 1x1 pixel since today morning

I was implementing pixel tracking for a gmail web service, but since today google has changed the gmail client to proxy linked images !

Is there any work around, as the proxy is giving my server a fake/masked ip and location?

A:

This is true. gmail has been proxying all user content via it thus showing Mountain View,CA as its REMOTE_ADDR. This is true only for gmail clients. The same logic has not been working on Gmail via outlook or any other mail client.
Most email tracking companies rely on these details to differentiate the recepients of the mail.
I dont think there is a work around. But if there is one we would find out soon given that these companies have a lot to lose.
Meanwhile, you could try using HTTP_X_FORWARDED_FOR or disposition notification headers. But given that this can be messed with, there isnt much option left but just go back to making people click on links!!!


Q:

IntelliJ, PhpStorm: Debugging with xdebug ignores XDEBUG_SESSION cookie

I am trying to debug a Drupal website with the PHP plugin in Intellij (would be the same in PhpStorm).
I have the following setup:
Chrome Browser pointing to a localhost alias mydomain.local and the XDebug Helper extension is installed and set to Debug. In the Developer Tools under Cookies I can see that the XDEBUG_SESSION cookie is set to PHPSTORM.
I have configured php with the xdebug plugin using the following settings:
xdebug.extended_info = 1
xdebug.idekey = "PHPSTORM"
xdebug.max_nesting_level = 500
xdebug.remote_autostart = 1
xdebug.remote_connect_back = 0
xdebug.remote_enable = 1
xdebug.remote_handler = dbgp
xdebug.remote_host = 127.0.0.1
xdebug.remote_mode = req
xdebug.remote_port = 9000

In IntelliJ I have setup a Server pointing to mydomain.local and in the run configuration I am using that server and have set the Ide Key to PHPSTORM.
Now the issue is this:
If I enable Break at first line in PHP scripts, then the debugger immediately breaks at the first breakable location inside the index.php. If I disable that option, I get a warning that no breakpoint was hit, even though I have a break point set and I am certain that the code is being executed. The warning that I see looks like this:
Debug session was finished without being paused
It may be caused by path mappings misconfiguration or not synchronized
local and remote projects.
To figure out the problem check path mappings configuration for
'mydomain.local' server at PHP|Servers or enable Break at first line in
PHP scripts option (from Run menu).

Now if I explicitly use a URL with the following query parameter appended: ?XDEBUG_SESSION_START=PHPSTORM then all my breakpoints are properly being breaked in IntelliJ.
Question: Why is the XDEBUG_SESSION cookie being ignored?
Update: Added my PHP and XDebug version output from php -v:
PHP 7.0.8-0ubuntu0.16.04.3 (cli) ( NTS )
Copyright (c) 1997-2016 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologies
    with Zend OPcache v7.0.8-0ubuntu0.16.04.3, Copyright (c) 1999-2016,
    by Zend Technologies
    with Xdebug v2.4.0, Copyright (c) 2002-2016, by Derick Rethans

and my Apache virtual host configuration:
<VirtualHost *:80>
    DocumentRoot /var/www/html/mydomain
    ServerName mydomain.local
    <Directory /var/www/html/mydomain>
        Options Indexes FollowSymLinks
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>

    ErrorLog /var/log/apache2/mydomain.log
</VirtualHost>

Update 2:
I have a php extension installed that is called fpm. I am not quite sure why its installed or if I need it. I think it was automatically installed with php. Could this be interfering?

A:

I used to have this issue when I've "overconfigured" my setup.

You might want to try adding the XDebug helper extension to chrome
After adding that go to the plugin's settings and select PhpStorm:

Try striping down your xdebug config to these values only:

(works on my box)
zend_extension=xdebug.so
xdebug.remote_enable=1
xdebug.remote_port=9000

The PhpStorm config should contain debug port 9000 and [X] Can accept external connections:

Then you should have listening to debug connections in PhpStorm on:

Also enable debugging in your browser (via the xdebug helper):

If the bug icon is green , then if you refresh the page, you should be good to go, and PhpStorm should stop at the first breakpoint.

A:

As it turned out the problem was not in IntelliJ or PhpStorm, but rather Drupal specific. In particular I needed to disable all caching.
The article Disable Drupal 8 caching during development explains in detail the steps to do that.
After I had disabled the caching Drupal everything worked as expected.


Q:

Boolean variable initialization used in several components

I realize an instant messenger. When I click on a thread, a window should open with the desired discussion. I do not want the user to open two identical discussions. This is why I added a boolean 'isOpen' variable to each thread :
export class Thread {

id: string;
messages: Observable<Message[]>;
lastMessage: Message = null;
participants: User[];
isOpen: boolean;
isReduce: boolean;
isFlash: boolean;

constructor(id?: string,
          participants?: User[],
          messages?: Observable<Message[]>,
          obj?: any) {
this.id             = id                       || uuid();
this.participants   = participants;
this.messages       = messages;
this.isOpen         = obj && obj.isOpen        || false;
this.isReduce       = obj && obj.isReduce      || false;
this.isFlash        = obj && obj.isFlash       || true;
 }
}

When I click on a thread, the variable 'thread.isOpen' changes to true.
And when I close this thread, the variable 'thread.isOpen' goes to false :
export class ListItemComponent implements OnInit {

 @Input() thread: Thread;
      ............................
clicked(thread: Thread): void {
this.newWindow = true;
if (!thread.isOpen) {
  thread = this.chatService.openThread(thread);
  this.chatService.setCurrentThread(thread);
  thread.isOpen = true;
 }
}

export class WindowItemComponent implements OnInit {

@Input() thread: Thread;
      ..............................
closeThread(thread?: Thread): void {
document.getElementById('chat-window-' + this.thread.id).style.display = 'none';
thread.isOpen = false;
this.newUser = false;
this.newWindow = false;
}

I do not understand why it does not work. When I test my variable this does not keep the initialization set to true. My two functions are in two different components.
/////////////////////////////////////////////////
EDIT
@Injectable()
  export class ChatService {
openThread(thread: Thread): Thread {
const newThread: Thread = new Thread(thread.id, thread.participants, thread.messages);
this.threadService.windows.push(newThread);
return newThread;
}

setCurrentThread(newThread: Thread): void {
  this.threadService.currentThread.next(newThread);
}

A:

I am going to paste and example and I hope that will help.
Imagine you have a parent component with some fake threads which might be comming from a rest call in real live:
export class ParentComponent implements OnInit {
  private threads: any[] = [{isOpen: false, id: '1'}, {isOpen: false, id: '2'}];
}

with its html that is spreading the objects to its childdren:

  <child *ngFor="let thread of threads"  [thread]="thread"></child>
  <child *ngFor="let thread of threads"  [thread]="thread"></child>

{{t.isOpen}}

When you do this and you change the thread object within its childdren. The thread object will change everywhere, in the parent and in all other childdren.
The child component is something like (It is a very simple child displaying the isOpen attribute and with a change method to change it from false to true):
export class child implements OnInit {
  @Input()
  public thread: any;

  public change(){
    this.thread.isOpen = true;
  }
}

with the html :

{{thread.isOpen}}

Hope that helps. As you can see I am trying to prove that it doesnt't matter where you change the isOpen property it will effect everywhere in the application


Q:

System.Runtime.Remoting.RemotingException [4484] Designer process terminated unexpectedly?

I created a class to monitor properties for changes and trigger the INotifyPropertyChanged event
however when a class using its added to a WPF control the designer crashes with an unhandled exception of

System.Runtime.Remoting.RemotingException [4484] Designer process
  terminated unexpectedly!

anyone know why?
public interface IObservableValue<T>:INotifyPropertyChanged, INotifyPropertyChanging
{
    T Value { get; }
}

public class ObservableProperty<T> : IObservableValue<T>
{
    public static implicit operator T(ObservableProperty<T> obj)
    {
        return obj.Value;
    }

    public ObservableProperty()
        :this(default(T))
    {
    }
    public ObservableProperty(T value)
    {
        val = value;
        CheckInterface(val, true);
    }

    T val;

    public T Value
    {
        get { return val; }
        set
        {
            if (!val.Equals(value))
            {
                OnPropertyChanging(changingArgs);

                CheckInterface( val, false);
                val = value;
                CheckInterface( val, true);

                OnPropertyChanged(changedArgs);
            }
        }
    }

    public bool HasValue
    {
        get { return val!=null; }
    }

    protected void CheckInterface<TValue>(TValue value, bool add)
    {
        INotifyPropertyChanging inc = value as INotifyPropertyChanging;
        if (inc != null)
        {
            if (add)
                inc.PropertyChanging += new PropertyChangingEventHandler(val_PropertyChanging);
            else
                inc.PropertyChanging -= new PropertyChangingEventHandler(val_PropertyChanging);
        }

        INotifyPropertyChanged inpc = value as INotifyPropertyChanged;
        if (inpc != null)
        {
            if (add)
                inpc.PropertyChanged += new PropertyChangedEventHandler(val_PropertyChanged);
            else
                inpc.PropertyChanged -= new PropertyChangedEventHandler(val_PropertyChanged);
        }
        INotifyCollectionChanged incc = value as INotifyCollectionChanged;
        if (incc != null)
        {
            if (add)
                incc.CollectionChanged += new NotifyCollectionChangedEventHandler(val_CollectionChanged);
            else
                incc.CollectionChanged -= new NotifyCollectionChangedEventHandler(val_CollectionChanged);
        }
    }

    void val_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        OnPropertyChanged(changedArgs);
    }
    void val_PropertyChanging(object sender, PropertyChangingEventArgs e)
    {
        OnPropertyChanging(changingArgs);
    }
    void val_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        OnPropertyChanged(changedArgs);
    }
    void OnPropertyChanged(PropertyChangedEventArgs changed)
    {
        var handler = PropertyChanged;
        if (handler != null) handler(this, changed);
    }
    void OnPropertyChanging(PropertyChangingEventArgs changed)
    {
        var handler = PropertyChanging;
        if (handler != null) handler(this, changed);
    }

    private static PropertyChangedEventArgs changedArgs = new PropertyChangedEventArgs("Value");
    private static PropertyChangingEventArgs changingArgs = new PropertyChangingEventArgs("Value");

    public event PropertyChangedEventHandler PropertyChanged;
    public event PropertyChangingEventHandler PropertyChanging;

}

A:

Very Odd but restarting VS2012 Fixed it


Q:

Python - couldn't open image

IMAGE WITH ERROR IN MY PYTHON GAME:

I want to run my application, but see this error, how to fix it?
Image with a correctly format is not a possible to open, this is a simple game make in a Python
import random
from livewires  import games
games.init(screen_width=640,screen_height=480,fps=50)
class Ship(games.Sprite):
def update(self):

    if games.keyboard.is_pressed(games.K_RIGHT):
        self.angle+=1
    if games.keyboard.is_pressed(games.K_LEFT):
        self.angle-=1

    if games.keyboard.is_pressed(games.K_1):
        self.angle=0
    if games.keyboard.is_pressed(games.K_2):
        self.angle=90
    if games.keyboard.is_pressed(games.K_3):
        self.angle=180
    if games.keyboard.is_pressed(games.K_4):
        self.angle=270
class Asteroid(games.Sprite):
    SMALL = 1
    MEDIUM = 2
    LARGE = 3
    images={SMALL : games.load_image("asteroida_s.bmp"),
            MEDIUM : games.load_image('asteroida_m.bmp'),
            LARGE : games.load_image('asteroida_l.bmp')   }
    SPEED=2
def main():
nebula_image=games.load_image("mglawica.jpg")
games.screen.background=nebula_image

for i in range(8):
    x=random.randrange(games.screen.width)
    y=random.randrange(games.screen.height)
    size-random.choice([Asteroid.SMALL,Asteroid.MEDIUM,Asteroid.LARGE,])
    new_asteroid=Asteroid(x=x,y=y,size=size)
    game.screen.add(new_asteroid)
games.screen.mainloop()
def main():
nebula_image=games.load_image("mglawica.jpg",transparent=false)
games.screen.background=nebula_image

ship_image=games.load_image("statek.bmp")
the_ship=Ship(image=ship_image,
    x=games.scren.width/2,
    y=games.scren.height/2)
games.scren.add(the_ship)
games.screen.mainloop()
def play(self):
nebula_image=games.load_image("mglawica.jpg")
games.screen.background=nebula_image
self.advance()
games.screen.mainloop()
def advanced(self):
self.level+=1
BUFFER=150
for i in range(self.level):
    x_min=random.randrage(BUFFER)
    y_min=BUFFER-x_min
    x=self.ship.x+x_distance
    y=self.ship.y+y_distance
    x%=games.screen.width
    y%=games.screen.height
    new_asteroid=Asteroid(game=self,x=x,y=y,size=Asteroid.LARGE)
    game.screen.add(new_asteroid)
def end():
end_message=games.Message(value="Koniec gry",
                          size=90,
                          color=color.red,
                          x=games.screen.width/2,
                          y=games.screen.height/2,
                          lifetime=10*games.scren.fps,after_death=games.screen.quit,
                          is_sollideable=False)
games.scren.add(end_message)
def die(self):
    if self.size !=Asteroid.SMALL:
        for i in range(Asteroid.SMALL):
            new_asteroid=Asteroid(x=self.x,
                                  y=self.y,
                                  size=self.size-1)
            game.screen.add(new_asteroid)
    self.destroy()

A:

While your code is very messy (no indentation), I think I have a way to fix it. First, I question your need to import livewire, and also wonder why you marked this question as pygame. You never imported pygame. So my solution will be written in pygame.
First, you have to load the images (and if you want assign it to a variable):
 image = pygame.image.load(filename)

Then, you have to convert the Surface, or basically just the image.
 image = pygame.image.load(filename).convert()


Q:

What are the best ways to deal with headphone cords while exercising?

I'm looking to buy a new set of headphones; I don't care much about audio quality, so I use the same pair of headphones for running and normal use, and prefer the kind of earbuds that slip over the ear (even for normal use).
In considering which kind of headphones to buy this time around, I realized that, although I don't mind headphone cords in normal usage, I find them extremely frustrating during running and weight-lifting. So, while browsing Amazon's headphones section, I thought there would be at least some overlap between the Sports & Exercise and Wireless feature categories; turns out there isn't. After doing some digging, there do seem to be bulky wireless headphones marketed for exercise, but most of their reviews make such headphones seem pretty terrible.
Since getting rid of the cords doesn't seem feasible at this point, what are the best ways to deal with headphone cords while exercising?

A:

I'm a long time jogger and just hated corded headphones, plus having to constantly replace them because the cable would wear near the plug.
All the reviews of wireless headphones were less than convincing, as you've seen.
I did however take the plunge and bought a Motorola S9. I returned it immediately because it was counterfeit. Then I got a real one.

As far as stability and comfort, I couldn't fault it, but maybe I just had the right shaped head. The problem was losing reception when jogging near a interference source, like overhead wires. Nonetheless, I it rarely affected me where I jogged so the only time I'd go back to wired headphones was when I'd forgot to charge the Motorolas. The Motorolas completely eliminated that enormous frustration I had with wires and buds falling out.
Caveat: I only listen to audiobooks, not music, so can't comment on their sound reproduction.
Just recently I bought a friend some Plantronics Backbeat GOs, telling her to give me them back if she didn't like them, knowing wireless is really a hit and miss affair.

She gave them back.
So I now use them along with the Motorolas. Their wireless reception is brilliant, I use them when cleaning the house as I don't have to carry the phone. I use them when walking the dog as power lines don't affect them. I use them at the gym. I use them where I may later have to take them off and carry them in a pocket, as the Motorolas are too bulky for pocketing. The Motorolas however do not feel bulky when wearing them.
I don't use the Plantronics GOs for jogging, they simply are not secure enough to handle the bouncing. Another massive design fault of them is the rubber connecting cord between the buds--high friction rubber catches on the back of your neck when turning your head and can pull the buds out. That could have been so easily eliminated with smooth plastic. Sometimes I wonder if any companies actually use their products. Having the cord across the front instead of the back helps this a lot, but now gets in the way of activities more.
These two devices together would make the perfect device. Maybe the later version of the Motorola, the S10, is much better, but the reviews still seem poor.
A problem with headphones is, because of hygiene, I never found a place that would let me return them if they were no good. One may have better luck in the States, but you may have to just take the gamble, try them, because it seems like people either love them or hate them. Wireless headphones have a long way to come, but are definitely feasible at the moment.

A:

I've got a pair of these Philips ActionFit Sports earhook headphones.
They're in-ear, they go over-ear and are adjustable for snug fit, and they're washable. I've had them about a year and they've been great.
I run with a waist pouch. I have the pouch behind me, and I run the headphone cables down the back of my neck, under my shirt and into the pouch. It works really well, I'm never bothered by my headphones.

A:

Mine is the simple earphones, the ones which you put inside the ear hole. My problem with that was during running the earphones are falling off my ears.
So what i came up with is to have the cord tied around my each ear haha, and now it doesn't fall off! It might look weird/odd though but it suits me as I have hair covering it anyways. It does save me from buying new ones or even buying a headset which definitely will not fall off. I also put the cord inside my shirt to prevent it from swaying back and forth on a run.


Q:

Изменение констант базовых типов

Хотелось бы понять, как С++ обрабатывает константы базовых типов.
Что будет, если при помощи плясок с бубном и указателями изменить значение, находящееся в ячейке памяти, где, по идее, и должна содержаться константа?
Есть следующий код:
#include <iostream>

using namespace std;

int main(int argc, char** argv) {
    const int number = 45;
    const int * constPoint = &number;
    cout << "constPoint " << constPoint << endl;
    int * point = (int *) constPoint;
    cout << "     point " << point << endl;
    * point = 54;
    cout << "&number " << &number << "; number " << number << endl;
    cout << "  point " << point   << "; *point " << *point << endl;
}

Вывод у меня получается следующий:
constPoint 0x7fff1b73a6ec
     point 0x7fff1b73a6ec
&number 0x7fff1b73a6ec; number 45
  point 0x7fff1b73a6ec; *point 54

Таким образом, значение константы не изменилось, хотя число, которое содержится в ячейке по адресу этой константы, уже другое.
Как объяснить подобное поведение?
Я не собираюсь такой код никогда использовать на практике, просто хочу понять, где хранятся константы.

A:

Для начала: по стандарту, изменение при помощи трюков с указателями констант есть undefined behaviour. Может случится всё, что угодно в любой точке программы.
Компилятор имеет право не хранить константу вообще нигде, если вы к ней не обращаетесь. Или имеет право хранить, если ему покажется так лучше. Или хранить в памяти только для чтения. Или хранить по общему адресу с какой-нибудь инструкцией кода, которая численно равна этой же константе.
Например, если компилятор видит обращение к константе, он может встроить её в точку вызова (он ведь знает значение на этапе компиляции), может обратиться к этой константе по адресу в любой момент, может даже выразить другие константы через эту (например, если у вас есть константа 1024, то обращение к 2048 он имеет право представить как 1024 << 1 из соображений эффективности).
Хуже того, если где-то компилятор выяснил для себя, что константа чётная, и её младший бит равен 0, и на основании этой информации смог исключить какие-нибудь проверки из кода, то теперь проверки не пройдут, и код может крешнуться в любой момент.
На UB обычно основаны дыры в безопасности программ. Например, если компилятор обоснованно считает, что длина строки 45, и под неё достаточно выделить буфер такой длины, в то время как вы, обманув компилятор, подсунете ему строку длиной 54, получится классический срыв стека.

Резюме: У компилятора нет никаких «обязательств» или «принципов» по работе с константами. Он имеет право делать что угодно. Наоборот, это программист, если уж обещал, что какое-то значение есть константа, не имеет права его менять.

A:

Согласно стандарту C++ (7.1.6.1 The cv-qualifiers)

4 Except that any class member declared mutable (7.1.1) can be
  modified, any attempt to modify a const object during its lifetime
  (3.8) results in undefined behavior

Есть один анахронизм в C, когда даже попытка изменить неконстантный объект приводит к неопределенному поведению программы. Речь идет о строковых литералах в языке C.
В C++ строковые литералы имеют типы константных символьных массивов. Например, строковый литерал "Hello" имеет тип const char[6]. Однако в C строковые литералы имеют типы неконстантных символьных массивов. Поэтому этот же самый строковый литерал "Hello" в C имеет тип char[6]. Тем не менее вы не можете изменить строковый литерал в C, также как вы не можете изменить строковый литерал в C++.
Из стандарта C (6.4.5 String literals)

7 It is unspecified whether these arrays are distinct provided their
  elements have the appropriate values. If the program attempts to
  modify such an array, the behavior is undefined.

То, что в C строковые литералы имеют типы неконстантных символьных массивов, очевидно связано с поддержкой уже существующей кодовой базы на момент введения квалификатора const в стандарт языка C.

A:

Компилятор умный и знает, что константу можно заинлайнить. Но есть возможность убедить его, что эта константа не слишком константная:
volatile const int number = 45;

Полный код: http://codepad.org/tNlZoNkE
Вариант с кастом в void* для вывода: http://codepad.org/EoqOgd6t
PS: Насколько я помню, volatile const это корректная ситуация, которая не должна приводить к undefined behavior.

он имеет полное право предполагать, что свой код точно не меняет const-объекты.

Для volatile это неважно. Представим, что есть нечто внешнее, что "совершенно случайно" меняет ту же константу на те же значения, что мы написали. А в самой программе вместо изменяющего кода стоят nop'ы. Такой вариант абсолютно точно корректен и не вызывает UB.
Значит, если UB есть, то его вызывает не изменившееся значение, а сама операция записи. Есть ли какой-то случай, в котором это возможно? Приходит в голову только read-only страница в памяти, но может ли компилятор так поступить? Локальную переменную он поместит в стек, который однозначно не readonly. Остаются глобальные. (Поля объектов попадают в одну из этих категорий.) Или есть ещё ситуации, когда операция записи может что-то испортить?


Q:

Calling a method from WS, parameter input type issue

I have the following operation in a webservice interface:
[OperationContract]
  List<vCard> getVCards(int[] vCardIDs);

And I get this error when trying to write the code for calling it:

What am I doing wrong?
Thanks

A:

You have a type missmatch just wrap your cardList into new ObservableCollection() where it is needed.
For e.g. just before call the service, 'course if it's following your program semantic
service.getVCardsAsync(new ObservableCollection<int>(cardList))


Q:

How to Use corrplot with method="number" and Drop Leading Zero?

How does one plot a correlation matrix in R using the package corrplot and drop the leading zero when using 'method="number"'?
For example, if a correlation is '0.78', I would like it to display '.78' or '78' in order to save space.
Regards,
Scott

A:

Using an example from the corrplot documentation:
data(mtcars)
M <- cor(mtcars)

corrplot(round(100*M), method="number", col="black", cl.pos="n",is.corr=F)

The key here is that we actually are plotting a correlation matrix, but we're multiplying by 100 and rounding, so we have to set is.corr=F.


Q:

TeamCity show branch in artifact zip name

I have a build in TeamCity where I want to build an artifact zip file.
I can use Edit Configuration Settings => General Settings => Artifact Paths to set up the files to zip and the zip file name.
I want to make the name more descriptive, and TeamCity lets me use parameters, e.g. :
out/mypackagedfiles/** => MyBuild_%build.number%.zip

will give me a zip file like MyBuild_46.zip.
I'd also like to include the branch that the build was built from. This is also available as a TeamCity parameter, but it contains a forward slash (e.g. feature/my_great_feature).  So if I use this in the Artifact Paths configuration, I get a directory containing a zip file:
out/mypackagedfiles/** => MyBuild_%build.number%_%vcsroot.branch%.zip

which gives my_great_feature.zip in a directory called MyBuild_46_feature.
What I'd like to do is somehow remove/replace the forward slash from the branch name to get one zip file, such as MyBuild_46_feature_my_great_feature.zip.
I'm not to worried about the exact format - as long as the branch name is identifiable.
Ideas for what might exist - but I can't find yet:

create a new parameter that derives the sanitised branch name from vcsroot.branch
some kind of string manipulation within the Artifact Paths configuration

== EDIT ==
Based on oryades answer below (which looks like linux bash command line), I converted this to PowerShell for Windows as follows:

Set up artifacts to use %env.branch_name% (this also requires setting a temporary/dummy value in the Parameters tab for the build to run)
Create a build step with runner type = PowerShell
Set script to Source Code and paste in the following:
$branch_name="%vcsroot.branch%".replace('/','_')
echo "Sanitised branch for Artifact zip = " $branch_name
echo "##teamcity[setParameter name='env.branch_name' value='$branch_name']"

Note that TeamCity lets you do substitution of %vcsroot.branch% - this is a substitution that happens before PowerShell runs. Thanks to Team City and Power Shell for this tip

A:

You can create env variable during build, just create a build step with the following content:
branch_name=$(echo %vcsroot.branch% | sed 's/\//_/')
echo "##teamcity[setParameter name='env.branch_name' value='$branch_name']"

On next build steps you can use %env.branch_name% as a variable with required value.
https://confluence.jetbrains.com/display/TCD10/Build+Script+Interaction+with+TeamCity


Q:

How do I format a date in a string variable to year date month in vb.net

I have a date in string variable strOrderEndDate which looks like this 8/14/2015.
I would like to convert it to 2015-08-14.
How do I do this in vb.net?
I tried strOrderEndDate.ToString(yyyy mmmm dd) but its not working

A:

As the comments indicate, you first need to convert the string to a date using CDate.  Then you can use the .ToString method on the new date type variable to format the output as desired:
 Dim strOrderEndDate As String = "8/14/2015"
 Dim datOrderEndDate As Date = CDate(strOrderEndDate)
 MsgBox(datOrderEndDate.ToString("yyyy-MM-dd"))

...or as Plutonix recommends, you can use DateTime.Parse to perform the conversion.  He's pretty smart so if he says it's better, then it's better.
 Dim datOrderEndDate As Date = DateTime.Parse(strOrderEndDate)


Q:

No appropriate default constructor available templates

I have a problem when i created an template object, i have a constructor but the program said that doesn't exists a correct constructor.
What is wrong?
Error c2512 ... no appropriate default constructor available appear in VS 2015
template <class T>
class CNODO_D
{private:
    T element;
    CNODO_D<T>* next;
    CNODO_D<T>* back;

public:
    CNODO_D(T e)
    {
        element = e;
        next = nullptr;
        back = nullptr;
    }
}

template <class T>
class CLista_S
{
private:
    CNODO<T>* begin;
    int _size;

public:CLista_S()
    {
        begin = nullptr;
        _size = 0;
    }
        void push_back(T e)
    {
        _size++;
        if (begin == nullptr)
        {
            CNODO_D<T>* n = new CNODO_D<T>(e);
            begin = n;
        }
        else
            //some other code
    }
}
    class CVida
{
private:
int vidas,x,y,ancho,alto;
int pos_inicial;
public:
CVida(int px, int py, int vid)
{
x = px;
y = py;
pos_inicial = px;
vidas = vid;
alto = 47;
ancho = 48;
}
    CLista_D<CVida>* lista_vidas= new CLista_D<CVida>();
lista_vidas->push_back(CVida, 12, 6, 9));

A:

You’re using CVida as a value in the last line of your example. Perhaps you meant lista_vidas->push_back(CVida{12, 6, 9})? That’s not the real problem though.
The problem is that CVida doesn’t have a default constructor but you’re calling the CVidadefault constructor in the CNODO_D<CVida> constructor. You should be using a member init list.
template <class T>
class CNODO_D
{private:
    T element;
    CNODO_D<T>* next;
    CNODO_D<T>* back;

public:
    CNODO_D(T e)
        : element(e), next(), back() {}
}


Q:

Sorting values of a list inside a dataframe's column

I have a dataframe as df :
   info      task                                               timestamp
0  foo       ABC                                           ['2016-04-30']
1  bar       DEF ['2016-01-31', '2015-06-30', '2016-06-30', '2016-08-31']
2  bar       GHI               ['2015-12-31', '2016-08-31', '2016-05-31']
3  foo       JKL                                           ['2017-03-31']
4  foo       XYZ               ['2016-02-29', '2015-10-31', '2016-01-31']

i want to sort the dates inside the timestamp column. Please note the values within the timestamp column are in a list and of string types.
Desired output:
   info      task                                               timestamp
0  foo       ABC                                           ['2016-04-30']
1  bar       DEF ['2015-06-30', '2016-01-31', '2016-06-30', '2016-08-31']
2  bar       GHI               ['2015-12-31', '2016-05-31', '2016-08-31']
3  foo       JKL                                           ['2017-03-31']
4  foo       XYZ               ['2015-10-31', '2016-01-31', '2016-02-29']

A:

So, the obvious answer is to call apply(sorted) here, but I'm going to go on a tangent, because there's a fundamental flaw in how your data is structured.
Let's flatten your data first.
df

  info task                                         timestamp
0  foo  ABC                                      [2016-04-30]
1  bar  DEF  [2016-01-31, 2015-06-30, 2016-06-30, 2016-08-31]
2  bar  GHI              [2015-12-31, 2016-08-31, 2016-05-31]
3  foo  JKL                                      [2017-03-31]
4  foo  XYZ              [2016-02-29, 2015-10-31, 2016-01-31]

v = df.values
i = v[:, :-1].repeat(df.timestamp.str.len(), axis=0)
j = np.concatenate(v[:, -1]).reshape(-1, 1)

df = pd.DataFrame(np.hstack((i, j)), columns=df.columns)

   info task   timestamp
0   foo  ABC  2016-04-30
1   bar  DEF  2016-01-31
2   bar  DEF  2015-06-30
3   bar  DEF  2016-06-30
4   bar  DEF  2016-08-31
5   bar  GHI  2015-12-31
6   bar  GHI  2016-08-31
7   bar  GHI  2016-05-31
8   foo  JKL  2017-03-31
9   foo  XYZ  2016-02-29
10  foo  XYZ  2015-10-31
11  foo  XYZ  2016-01-31

Now, groupby the first two columns and call sort_values -
df.groupby(['info', 'task'], sort=False)\
  .timestamp\
  .apply(pd.Series.sort_values)\
  .reset_index(level=[0, 1])

   info task   timestamp
0   foo  ABC  2016-04-30
2   bar  DEF  2015-06-30
1   bar  DEF  2016-01-31
3   bar  DEF  2016-06-30
4   bar  DEF  2016-08-31
5   bar  GHI  2015-12-31
7   bar  GHI  2016-05-31
6   bar  GHI  2016-08-31
8   foo  JKL  2017-03-31
10  foo  XYZ  2015-10-31
11  foo  XYZ  2016-01-31
9   foo  XYZ  2016-02-29

Which still needs an apply, but I'm willing to bet will be significantly faster, especially considering your other operations may not require an apply anymore.


Q:

How to remove upload button in Bootstrap File Input

I have this Bootstrap file input plugin which can be found here: http://plugins.krajee.com/file-basic-usage-demo
This plugin looks like as below:

Now what I want to do is to remove this upload button of this plugin. Does anybody know how to do this? Or does anyone already tried?

A:

You can just use these following snippets
$("#your-input-type-file-ID").fileinput({
    'showUpload': false
});

A:

Finally found the answer, by simply editing this code here from fileinput.js:
$.fn.fileinput.defaults = {
    language: 'en',
    showCaption: true,
    showPreview: true,
    showRemove: true,
    showUpload: false, // <------ just set this from true to false
    showCancel: true,
    showUploadedThumbs: true,
    // many more below
};

A:

You can do it in a simple way also simply write in an attribute data-show-upload="false" and it I'll work too!!


Q:

jQuery - how to detect an option being selected in a select, when it doesn't change the selection

I have a bunch of selects listing PDF files.  When the user chooses a PDF from the select, I display the pdf in the screen.  This is triggered from an event listener on "change blur".
If they then close the div with the pdf in it, and want to open it again, they must select it again from the dropdown.
However, I'm finding that in order to show the pdf again, they need to select a different pdf, then open the select again and choose the one they do want:  in other words, if you open the select, then click "Done" (on mobile) or click on the already-selected option (desktop), then because it hasn't changed, it doesn't trigger showing the PDF.
I thought that adding "blur" to the events being listened for would do it - wouldn't the select closing trigger it's blur event?  But it doesn't seem to help.
This is my code:
$("body").on("change blur", ".pdf-file-select", function(e){
  //get the pdf uri from the selection and show the pdf
});

thanks.
EDIT - on investigation, blur only fires when I click outside the select - it doesn't fire when I close the select.

A:

use the click event instead
$("body").on("click", ".pdf-file-select", function(e){
  //get the pdf uri from the selection and show the pdf
});


Q:

Get Abbrevation From a string

How would I get the accroyn  letter of the string
for example i have a string
"Location1 Location2 Wall21" or may have "loc loc wal2012";
I need Output looks like
loc1loc2wal21 and loclocwal2012
means to say first 3 letter of a word and all numeric words with that string
I used this
echo preg_replace('~\b(\w{3})|.~', '$1', $s);

But it gives only 3 words not all numeric charcter.
AnyBody have idea how to resolve this
Thanks

A:

Then only include letters, and take out that |.:
echo preg_replace('~\b(\p{L}{3})\p{L}*|\s~', '$1', $s);

Here's a demo.


Q:

How to solve Apple Mach-o linker error? (_OBJC_CLASS_$_Connection", referenced from..)

I get this error and people says it about missing frameworks but i can't see I'm missing any.
Undefined symbols for architecture armv7:
"_OBJC_CLASS_$_Connection", referenced from:
objc-class-ref in SocketServer.o
ld: symbol(s) not found for architecture armv7
collect2: ld returned 1 exit status

It happens when i add this:
theServer = [[SocketServer alloc]init];
theServer.serverName = [NSString stringWithFormat:@"%@", username];
theServer.delegate = self;

What is there to try?
SocketServer is a class from a project from the book Apress Beginning iPhone Games Development

A:

I can see from the book's source code, that there is a related Connection class that you are forgetting to link with:
Beginning iPhone Games Development Source Code/chapter 15 - PartyTime - Peter Bakhirev/TwentyFour final/Classes/Connection.m

Add that class to your project and it should then link.


Q:

"Server error. Upload directory isn't writable."

I use FineUpload script to upload images on server. This is the code I use from localhost
<?php
require 'FineUpload.php';

$uploadDir = 'http://www.naukaplywaniakrakow.pl/gallery/';
$allowed   = explode(',', 'pdf');
$sizeLimit = 5000 * 1024;

$fineUpload = new FineUpload($allowed, $sizeLimit);
$response   = $fineUpload->handleUpload($uploadDir);

if (@$response['success']) {
    $uploadName = $fineUpload->getUploadName();

    list($width, $height) = getimagesize($uploadDir . $uploadName);

    $response['fileName'] = $uploadName;
}

echo json_encode($response);

I have created a gallery directory in public_html directory, but still gets the error:

{"error":"Server error. Upload directory isn't writable."}

A:

Your upload directory must be a local folder relative to your current dir and not a web url.
Try getcwd() to know which folder you are in and then use a relative path to your gallery folder.


Q:

Rolling Mean on pandas on a specific column

I have a data frame like this which is imported from a CSV.
              stock  pop
Date
2016-01-04  325.316   82
2016-01-11  320.036   83
2016-01-18  299.169   79
2016-01-25  296.579   84
2016-02-01  295.334   82
2016-02-08  309.777   81
2016-02-15  317.397   75
2016-02-22  328.005   80
2016-02-29  315.504   81
2016-03-07  328.802   81
2016-03-14  339.559   86
2016-03-21  352.160   82
2016-03-28  348.773   84
2016-04-04  346.482   83
2016-04-11  346.980   80
2016-04-18  357.140   75
2016-04-25  357.439   77
2016-05-02  356.443   78
2016-05-09  365.158   78
2016-05-16  352.160   72
2016-05-23  344.540   74
2016-05-30  354.998   81
2016-06-06  347.428   77
2016-06-13  341.053   78
2016-06-20  363.515   80
2016-06-27  349.669   80
2016-07-04  371.583   82
2016-07-11  358.335   81
2016-07-18  362.021   79
2016-07-25  368.844   77
...             ...  ...

I wanted to add a new column MA which calculates Rolling mean for the column pop. I tried the following
df['MA']=data.rolling(5,on='pop').mean()

I get an error
ValueError: Wrong number of items passed 2, placement implies 1

So I thought let me try if it just works without adding a column. I used
 data.rolling(5,on='pop').mean()

I got the output
               stock  pop
Date
2016-01-04       NaN   82
2016-01-11       NaN   83
2016-01-18       NaN   79
2016-01-25       NaN   84
2016-02-01  307.2868   82
2016-02-08  304.1790   81
2016-02-15  303.6512   75
2016-02-22  309.4184   80
2016-02-29  313.2034   81
2016-03-07  319.8970   81
2016-03-14  325.8534   86
2016-03-21  332.8060   82
2016-03-28  336.9596   84
2016-04-04  343.1552   83
2016-04-11  346.7908   80
2016-04-18  350.3070   75
2016-04-25  351.3628   77
2016-05-02  352.8968   78
2016-05-09  356.6320   78
2016-05-16  357.6680   72
2016-05-23  355.1480   74
2016-05-30  354.6598   81
2016-06-06  352.8568   77
2016-06-13  348.0358   78
2016-06-20  350.3068   80
2016-06-27  351.3326   80
2016-07-04  354.6496   82
2016-07-11  356.8310   81
2016-07-18  361.0246   79
2016-07-25  362.0904   77
...              ...  ...

I can't seem to apply Rolling mean on the column pop. What am I doing wrong?

A:

To assign a column, you can create a rolling object based on your Series:
df['new_col'] = data['column'].rolling(5).mean()

The answer posted by ac2001 is not the most performant way of doing this. He is calculating a rolling mean on every column in the dataframe, then he is assigning the "ma" column using the "pop" column. The first method of the following is much more efficient:
%timeit df['ma'] = data['pop'].rolling(5).mean()
%timeit df['ma_2'] = data.rolling(5).mean()['pop']

1000 loops, best of 3: 497 µs per loop
100 loops, best of 3: 2.6 ms per loop

I would not recommend using the second method unless you need to store computed rolling means on all other columns.

A:

Edit: pd.rolling_mean is deprecated in pandas and will be removed in future. Instead: Using pd.rolling you can do:
df['MA'] = df['pop'].rolling(window=5,center=False).mean()

for a dataframe df:
          Date    stock  pop
0   2016-01-04  325.316   82
1   2016-01-11  320.036   83
2   2016-01-18  299.169   79
3   2016-01-25  296.579   84
4   2016-02-01  295.334   82
5   2016-02-08  309.777   81
6   2016-02-15  317.397   75
7   2016-02-22  328.005   80
8   2016-02-29  315.504   81
9   2016-03-07  328.802   81

To get:
          Date    stock  pop    MA
0   2016-01-04  325.316   82   NaN
1   2016-01-11  320.036   83   NaN
2   2016-01-18  299.169   79   NaN
3   2016-01-25  296.579   84   NaN
4   2016-02-01  295.334   82  82.0
5   2016-02-08  309.777   81  81.8
6   2016-02-15  317.397   75  80.2
7   2016-02-22  328.005   80  80.4
8   2016-02-29  315.504   81  79.8
9   2016-03-07  328.802   81  79.6

Documentation: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rolling.html
Old: Although it is deprecated you can use:
df['MA']=pd.rolling_mean(df['pop'], window=5)

to get:
          Date    stock  pop    MA
0   2016-01-04  325.316   82   NaN
1   2016-01-11  320.036   83   NaN
2   2016-01-18  299.169   79   NaN
3   2016-01-25  296.579   84   NaN
4   2016-02-01  295.334   82  82.0
5   2016-02-08  309.777   81  81.8
6   2016-02-15  317.397   75  80.2
7   2016-02-22  328.005   80  80.4
8   2016-02-29  315.504   81  79.8
9   2016-03-07  328.802   81  79.6

Documentation: http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.rolling_mean.html

A:

This solution worked for me.
data['MA'] = data.rolling(5).mean()['pop']

I think the issue may be that the on='pop' is just changing the column to perform the rolling window from the index.
From the doc string: " For a DataFrame, column on which to calculate the rolling window, rather than the index"


Q:

What is "Task scanning" in NetBeans and how to turn it off?

Sometimes when opening projects, NetBeans will display a "Task scanning" progress bar on the status bar. What exactly is it scanning for? Is it possible to turn it off as I noticed that sometimes it takes a while and maybe it's just my installation but sometimes I have to force it to stop when closing NetBeans.

A:

It is a "Task List" plugin working. It does this:

Provides the Task List window, which lists places of interest in your project, such as lines that contain "TODO", "XXX", "PENDING", Java compilation errors, and so on. You can click an entry in the list to navigate to the corresponding place in your code.

You can remove it by going to "Tools > Plugins" menu, "Installed" tab, selecting "Task List" from the installed plugin list and clicking "Uninstall" button. (These instructions are for NetBeans 6.5, but should be somewhat alike for all the other versions).
But I would advise against removing it - I find it pretty useful. There are times when I forget about several TODO's, and Tasks window is a great way to look 'em up.
If you can't see that window, you can access it through "Window > Task" menu, or by pressing Ctrl+6 (again, these instructions are for NetBeans 6.5)


Q:

Where can I find AWS RDS snapshot hostname?

I have a MySQL instance running on RDS and I have created a snapshot and I read I can connect to snapshot. But I can't find snapshot specific hostname there on RDS management console. Can I really connect to AWS RDS snapshot using mysql client like I connect to instances?

A:

There was an implication in the linked answer that you would need to restore the snapshot to an RDS instance. A snapshot isn't a live MySQL database -- you can't connect to it and use that state until you restore a new RDS instance from that snapshot. Here's how snapshots are defined in the documentation, if it helps:

DB snapshots are user-initiated and enable you to back up your DB
  instance in a known state as frequently as you wish, and then restore
  to that specific state at any time. DB snapshots can be created with
  the Amazon RDS console or the CreateDBSnapshot action in the Amazon
  RDS API. DB snapshots are kept until you explicitly delete them with
  the Amazon RDS console or the DeleteDBSnapshot action in the Amazon
  RDS API.

You can restore from a snapshot from the AWS console, or programmatically through the:

CLI: restore-db-instance-from-db-snapshot
API: RestoreDBInstanceFromDBSnapshot


Q:

How to get a list of all collections with mongoskin

The goal is to get a list of all the collections in the database using mongoskin.
I know you can enter the db.getCollectionNames() method in mongo shell to do this, but I haven't found a way to achieve the same in my app.
I have already looked at a similar post on SO (Is there a way to list collections with mongoskin?) and tried the posted solution without success.

A:

It's collectionNames().  It returns databasename.collectionname (ex. "test.user") though... but you can do some string manipulations to get rid of that if you need.
db.collectionNames(function(err, items) {
  items.forEach(function(item) {
    console.log(item.name);
  });
});


Q:

overall effects of categorical variables

I'm doing a Poisson regression in Stata, so the dependent variable is a count variable and I have some categorical predictors. If A is a categorical variable with, for example, 4 levels, in the parameter estimates table I get results for the 3 levels of the variable compared to the level I have set as the reference category. Similarly for an interaction term. However, I would also like to have an estimate of the overall effect of variable A and also an estimate of the overall effect of the interaction. How do I do this in Stata?
Ie. I need the test of the effect of A in the model on the dependent variable D, which tests the joint hypothesis that every one of the four levels of A has the same effect on D, and therefore A does not explain any of the variation in D, and so it is not a significant predictor of D in the model.
I do not need a test which tests the hypothesis that the effects on D of e.g. A2 , A3, or A4, respectively, are all equal to each other in this model, but not necessarily equal to the effect of A1.
Thank you
UPDATE:  Well, prompted by the comments from all of you, and after hours of trying out different things, I found that what I was looking for was
"constrast A",
described in http://www.stata.com/manuals13/u25.pdf
However, I am now wondering why "contrast A" does not give me the same results as
"test A4=A3=A2=A1". I'm told I shouldn't make stata-specific questions, however I'm trying to see how stata corresponds to other packages and this is what prompted my question. I also think that if someone can answer this question for me i.e. why constrast is not the same as a joint test on whether all levels have the same effect, then this would be of general interest as it obviously translates to a general statistical question.

A:

Given your comments I will assume that you do not want an estimate of the size of the effect but instead a statistical test whether the expected (possibly adjusted) count for each of the categories are the same. This may or may not be wise depending on your circumstances, but this is an example of how you do it in Stata:
webuse dollhill3
poisson deaths smokes i.agecat, exposure(pyears)
testparm i.agecat

If you want something like a single effect size you could look into sheaf coefficients. In case of interaction terms this generalizes to a model with parametrically weighted covariates. A brief discussion on how to do those in Stata can be found here.


Q:

How to access watson assistant using python?

I want to implement a particular chatbot which has been created and trained using IBM Watson Assistant on a website, which is using Django/flask at the backend so how can I integrate that particular chatbot on my website?
Please help me by providing any link or video guide

A:

The answer depends on whether you just want to embed the chatbot or deeply integrate it with additional logic.
For embedding the chatbot with a website (like yours build with Flask or Django), you could use the integrations offered by Watson Assistant. It is either customized or IBM-branded.
Another option is to utilize the Python SDK for the IBM Watson services. Here, you would build the UI on your own and drive the dialog. I have built a simple text-based command line tool with that SDK and am able to converse with Watson Assistant.


Q:

Casablanca Linker Errors on Android

I built casablanca for Android per the instructions here: How to build and setup for Android on Linux (2.3+).
I moved the compiled libraries to my Android project and linked the module that depends on casablanca per the instructions here: How to use the C++ REST SDK on Android (2.3+).
However, I get multiple linker errors.
For example, when trying to use
json::value::string( "some value" );

I get,
error: undefined reference to 'web::json::value::string(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >)'

And when trying to use
json::value version;
version[someValue] = something;

I get,
error: undefined reference to 'web::json::value::operator[](std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)'

I am compiling my Android project with clang.
I built on a Linux-64 VM and my Android project is on a Windows-64 machine. However, when trying to build a shared library of casablanca for Android on Linux, I also got multiple linker errors.
I suspect that there is some code being compiled with libstdc++ and some with libc++. From looking at the build scripts, I can see that clang is being used for both boost and casablanca but I also see include paths pointing to gcc headers. I'm also curious as to why I see on the linker output (on Windows) references to /sources/cxx-stl/gnu-libstdc++/4.8/include/ with my Linux VM path.
Any insights on how to get casablanca to link properly on Android will be appreciated.
Thanks.
(I posted this same question here.)

A:

Actually ended up compiling the project code with libstdc++ (gnustl_shared).


Q:

Do sneak attacks stack with crits?

I am playing an assassin character. I focus on silenced pistols and eventually develop melee weapons as well.
My question is if any of you know if the sneak attacks stack with critical hits?
example: Let's say my silenced pistol does 50 damage and I have a 4x sneak attack multiplier (due to the Ninja perk). If I apply the critical hit to the sneak attack in VATS, what will the resulting damage be?
For the sake of argument lets assume I have a couple perks points invested which increase the critical damage by an extra 100% - raising the critical damage multiplier to 3x effectively.
I can see three scenarios but I am not sure which one applies to Fallout 4:

SNEAK BONUS and CRIT are added => 4x + 3x = 7x total damage amplification
SNEAK BONUS and CRIT are multiplied => 4x x 3x = 12x total damage amplification
SNEAK BONUS and CRIT are not stacked => resulting in either the 4x SNEAK BONUS or the 3x CRIT

How does Fallout 4 handle this?

A:

I got sick of waiting for an answer to my broader question regarding how the damage multiplys in general,  so I did a bunch of testing myself.
Method:
All tests were done by shooting a friendly setler in the back of the torso at close range.
The NPC was wearing nothing but a Minuteman outfit and had their HP set to 5000 with the console. I did not check what their Damage resistance was nor did I modify it, though I probably should have.
A single shot was taken, NPCs HP remaining checked with the console, then the game was reloaded. This was done 5 times.
Due to perks etc, my Sneak attack bonus was at 4.2
Not sure what my exact critical bonus is, I had 4 ranks of Tesla Science (+20% crit damage) and no other perks or mods which would increase it.
Tests performed with a Laser Rifle, instigating tests performed with Old Faithful with the same mods. Both showed a base damage of 144 in the Pip-Boy interface.

Results:
Normal Shot
111.81, 214.99, 213.32, 214.57, 212.48
Average: 204.72 damage (Average may be low? First shot did much less damage)
Critical Hit:
350.93, 349.86, 350.63, 350.34, 351.00
Average: 350.552
Sneak Attack:
905.80, 905.97, 906.70, 906.38, 905.46
Average: 906.062
Sneak Attack + Critical Hit:
1040.25, 1042.20, 1040.83, 1038.45, 1040.27
Average: 1040.40
Normal Shot + Instigating Weapon
425.43, 430.58, 431.57, 430.70, 352.29
Average: 414.114 damage (Average may be low? Last shot did much less damage)
Critical Hit + Instigating Weapon:
565.44, 559.52, 566.39, 565.26, 566.12
Average: 564.546
Sneak Attack + Instigating Weapon:
1810.25, 1812.87, 1813.63, 1813.38, 1812.00
Average: 1812.426
Sneak Attack + Critical Hit + Instigating Weapon:
1944.69, 1946.42, 1947.35, 1947.74, 1947.11
Average: 1946.662

Discussion:
The above results show some variance, with some shots noted as being much lower than others. It is not clear if this was due to poor accuracy causing some bullets to hit the wrong location (though injuries on target suggested all shots hit the back), natural RNG spread of damage, or damage resistance of the target.
When roughly comparing Sneak attacks performed with both Instigating and normal weapons, the stated Sneak Attack bonus does appear to be multiplicative with Instigating ( [Weapon Damage x2] x4.2) or at least close enough to satisfy me that this is the case.
Interestingly, Critical Hits do not appear to be multiplicative with Sneak and Instigating. In all situations the additional damage inflicted was close to the weapons stated base damage (144, give and take some variance). This suggests to me that critical strikes are seperate damage which is calculated and then added after sneak attacks and instigating are multiplied ( {[Weapon Damage x2] x4.2} + [Weapon Damage xCrit Modifier])
The Wiki suggests that Critical Hits use the following formula:
Ranged: Critical Hit Damage = DamagePaper + DamageBase x CriticalMultiplier
Melee/Unarmed: Critical Hit Damage = DamagePaper x 1.5 + DamageBase x CriticalMultiplier
DamageBase = Weapon damage, including workshop mods, but excluding perks and other bonuses.
DamagePaper = Damage displayed in PipBoy (PipBoy cuts off decimal places)
Conclusion:
Sneak Attack and Instigating are multiplicative with each other.
Critical Hits are not multiplicative with Sneak or Instigating
This suggests:
([Weapon Damage x Instigating] x Sneak Modifier) + (Weapon Damage x Crit Modifier)

A:

From personal experience they do stack together. I had a critical sneak attack on a Mirelurk Queen which dropped her HP by just under half (I also have the Instigating weapon perk which doubles damage to full hp targets) , it then took another 21-28 shots (3-4 mags) to finish her off. That's with having +50% crit damage and 3x sneak bonus.


Q:

Exception in Pom.xml SPring Starter project

I created a project with Spring Starter Project, but my pom.xml gives me this exception:
org.apache.maven.archiver.MavenArchiver.getManifest(
    org.apache.maven.project.MavenProject, org.apache.maven.archiver.MavenArchiveConfiguration)

A:

Update your eclipse m2e connectors by
Help -> Install New Software -> paste this link and install http://repo1.maven.org/maven2/.m2e/connectors/m2eclipse-mavenarchiver/0.17.2/N/LATEST/


Q:

How can I join several plots a single figure using a Table?

It is possible to joint different kind of plot using a Table, The idea is to have a single plot. I have been trying using Show function y. But I can not get it.  So It is possible also to add independently captions for each figure.
Here it is the code
L = 15; pp = 100; uv1 = {y -> 0 , k -> 1}; uv2 = { k -> 0.5} ;

Bb[x_, y_, n_] = BesselJ[n, k Sqrt[x^2 + y^2]];

graf1 =Table[ Plot[Bb[x, y, n] /. uv1, {x, -L, L}, PlotRange -> Full, PlotLabel -> {tit, tit1, tit2 }], {n, 0, 2}];

graf2 = Table[Plot3D[Bb[x, y, n] /. uv2 , {x, -L, L}, {y, -L, L}, AxesLabel -> {x, y, "Bessel"}, ColorFunction -> "Rainbow",PlotRange -> Full, ViewPoint -> {1.5, -2, 1.3}], {n, 0, 2}];

graf3 = Table[DensityPlot[Bb[x, y, n] /. uv2, {x, -L, L}, {y, -L, L}, ColorFunction -> "Rainbow", PlotRange -> Full, PlotPoints -> pp,    PerformanceGoal -> "Quality"], {n, 0, 2}];

I try using
Show[{graf1,graf2,graf3}]

A:

How about this?
GraphicsGrid[{graf1, graf2, graf3}, ImageSize -> Large]


Q:

Querying SQL NodeJS + Tedious: request.on('done', cb) not being called and nested queries

I am trying to make a request, add the returned data to an object on the cb in the "row" event on the request, and then do something in the "done" cb. Pretty simple; however, the "done" event is apparently not being triggered. Here is my current code:
var connection = new Connection(config);
var executeTest = function (connection) {
 var result = [];
 var statement = "select val1, val2 from table;"

 var request = new Request(statement, function (err, rowCount) {
   if (err) {
    console.log(err);
   }
   console.log(rowCount);
   connection.close();
 });

 request.on('row', function(columns) {
  var thisRow = {};
  columns.forEach(function(column) {
    thisRow[column.metadata.colName] = column.value;
    result.push(thisRow);
  });
  console.log(result); //not empty
  //tried making request2 here, no dice
  //tried making a second connection here, no dice
  //got error:
  //'requests can only be made in the LoggedIn state,
  //not the SentClientRequest state' :(
 })

 request.on('done', function (rC, more, row) { //never called
   console.log(rC, more, row);
   //other things to do
 })
 connection.execSql(request);

}

function test () {
 var connection = new Connection(configure);
 connection.on('connect', function(err) {
   if (err) {console.log(err);}
   console.log("Connected");
   executeTest(connection);
 })
}

test();
console.log(result); // []
//make second request using values from result

Also if anyone could explain how to use the results from a query as parameters in another, that would be great. After I call test, obv result is empty, but when it isn't empty in the request.on('row', cb), I have not been able to make a second request in that cb with the current thisRow obj. Would I need to use transactions? If so would someone please give an example of how to do nested queries with transaction in tedious where the results of the first query are fed to the second query as parameters? Thanks.

A:

To make the second request, you need to pass a callback into the function wrapping the tedious request. I dumbed down the code a bit for simplicity sake:
var statement = "select val1, val2 from table";

function executeTest(connection, callback) {

    var results = [];

    var request = new Request(statement, function(error) {

        if (error) {
            return callback(error);
        }
        // pass the results array on through the callback
        callback(null, results);
    });

    request.on("row", function(rowObject) {
        // populate the results array
        results.push(rowObject);
    });
    connection.execSql(request);
}

function test() {
    /*
    create connection code
     */
    executeTest(connection, function(error, results) {
        // here is the results array from the first query
        console.log(results);
    });
}

test();

The key point is that the request is asynchronous, so the results must be passed to a callback. That means if you want the code somewhere else, you need to pass a callback parameter into executeTest .


Q:

What is the Average Big-Ο complexity of Gnome sort?

There is nothing about it in wikipedia.
Anyone knows that?
I only want to know the average Big-O Complexity of that algorithm.

A:

The performance of the gnome sort algorithm is at least O(f(n)) where f(n) is the sum for each element in the input list of the distance to where that element should end up.  For a "random" list of length L, an element at the beginning of the list is expected to be an average of L / 2 distance away from its sorted location.  An element in the middle of the list is expected to be an average of L / 4 distance away from its sorted location.  Since there are L total elements, f(n) is at least L * L / 4.  Therefore, on average, gnome sort is O(n * n).
Sorry if this is hard to follow.


Q:

Linking HTML element with onscroll, onchange doesn't work

I am trying to make a div .progress container change its width once the div #myContact reaches 100% height on scroll
I've tried linking the HTML element with onscroll, onchange or anything else but I don't seem to know what works.

 //this containter needs to change width

 //when this one reaches 100% height

#containter {
  width: 100%;
  height: 3000px; // original setting is 100vh, this value is just for scrolling without me pasting all the other elemnts
  scroll-behavior: smooth;
  overflow: scroll;
  scroll-snap-type: y mandatory;
}

.progress-container {
  position: fixed;
  width: 20%;
  height: 100%;
}

/* The progress bar (scroll indicator) */
.progress-bar {
  width: auto;
  background: #000;
  height: 0%;
  max-height: 100%
}

// Scroll function
  function scrollProgress() {
      var elem = document.getElementById('containter');
      var winScroll = elem.scrollTop;
      var height = elem.scrollHeight - document.documentElement.clientHeight;
      var scrolled = (winScroll / height) * 100;
      document.getElementById("myContact").style.height = scrolled + "%";
};
    // Expand function

    /* When 'myContact' reaches 100% height then 'progres-container' expands left, and cover the entire screen*/

  function expandMe() {
    let trigger = document.getElementById('myContact').style.height;
    if (trigger = 100) {
      document.getElementById('progress').style.width = trigger + "%";
    }
  };
/* When 'myContact' reaches 100% height then 'progres-container' expands left,
 and cover the entire screen*/

Nothing really happens and also I have no errors.
Thank you so much!

A:

It's not a pixel-perfect solution, but since you've got some mistakes in your code, an event listener should be bound to window object, then it will render as you need.
I added some visual effect to the width changing style.

window.addEventListener('scroll', function () {
      var winScroll = window.pageYOffset;
      var height = document.getElementById('container').scrollHeight - document.documentElement.clientHeight;
      var scrolled = (winScroll / height) * 100;
      document.getElementById("myContact").style.height = scrolled + "%";
      document.getElementById("myContact").parentElement.style.width =(scrolled >= 100) ? scrolled + "%" : "20%";
});
#container {
  width: 100%;
  height: 3000px;
  scroll-behavior: smooth;
  overflow: scroll;
  scroll-snap-type: y mandatory;
}

.progress-container {
  position: fixed;
  background: #0f0;
  width: 20%;
  height: 100%;
  transition: width 1s;
}

/* The progress bar (scroll indicator) */
.progress-bar {
  width: auto;
  background: #f00;
  height: 0%;
  max-height: 100%
}


Q:

Changing object/path filling's opacity without changing the stroke's opacity

I would like to reduce the opacity of the filling colour of an object/path and keep the stroke of such object/path unchanged.
Is there a way of impeding this relationship so I can only reduce the opacity of one?

A:

Color selector has alpha slider. In the next image both circles have black stroke and cyan fill. The rightmost circle has 50% transparent fill color (alpha=128)

Unfortunately there's a thing you maybe didn't expect. The stroke is half-way covered by the fill and the covered half become visible.
A fast workaround is to have 2 separate shapes (=edge & the fill) or to make a white stroke + grey fill copy on the top and use it as opacity mask. An example:

The opacity mask is set by selecting both layered objects and applying Object > Mask > Set
The 2 shape approach needs the stroke as a filled area which has a hole. It can be made easily by subtracting the fill area from the stroke which is converted to path. I do not recommend it because exactly fitting seam has 1 pixel wide transparent zone which needs a narrow stroke to be covered => more complex that the opacity mask version and not easily editable.


Q:

UIView drawRect: is it possible to stroke inside a path?

With core graphics, is it possible to stroke the inside of a path? As opposed to the line weight being drawn half on the outside and half on the inside of a stroked path?
The reason being it would be easier to control the visible thickness of the stroke if say part of a view is on the screen edge and part is not. The part on the screen edge gets cut off, while the view edge that is fully on screen looks thicker (as both sides if the stroke are visible).

A:

Clip to the path before you stroke it.

A:

This draws no stroke:
- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetStrokeColorWithColor(context, [UIColor darkGrayColor].CGColor);
    CGContextSetLineWidth(context, 14);
    CGRect rrect = CGRectMake(CGRectGetMinX(rect), CGRectGetMinY(rect), CGRectGetWidth(rect), CGRectGetHeight(rect));
    CGFloat radius = 30;
    CGFloat minx = CGRectGetMinX(rrect), midx = CGRectGetMidX(rrect), maxx = CGRectGetMaxX(rrect);
    CGFloat miny = CGRectGetMinY(rrect), midy = CGRectGetMidY(rrect), maxy = CGRectGetMaxY(rrect);
    CGContextMoveToPoint(context, minx, midy);
    CGContextAddArcToPoint(context, minx, miny, midx, miny, radius);
    CGContextAddArcToPoint(context, maxx, miny, maxx, midy, radius);
    CGContextAddArcToPoint(context, maxx, maxy, midx, maxy, radius);
    CGContextAddArcToPoint(context, minx, maxy, minx, midy, radius);
    CGContextClosePath(context);
    CGContextClip(context);
    CGContextDrawPath(context, kCGPathStroke);
}

EDIT: This is what worked (according to the correct answer):
- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetStrokeColorWithColor(context, [UIColor darkGrayColor].CGColor);
    CGContextSetFillColorWithColor(context, [UIColor blackColor].CGColor);
    CGContextSetLineWidth(context, 14);
    CGRect pathRect = CGRectMake(10, 10, rect.size.width -20, rect.size.height -20);
    CGPathRef path = [UIBezierPath bezierPathWithRoundedRect:pathRect cornerRadius:20].CGPath;
    CGContextAddPath(context, path);
    CGContextClip(context);
    CGContextAddPath(context, path);
    CGContextDrawPath(context, kCGPathEOFillStroke);

}


Q:

Jackson, Hibernate Validator, and Spring MVC: combining them together

I hope you're fine:
public class UserDTO extends AbstractDTO implements Serializable {

    private static final long serialVersionUID = -2724997313065531109L;

    @NotNull
    @Pattern(regexp = "^[a-zA-Z0-9_\\.]+$")
    @Length(min = 3, max = 30)
    private String userName;

    @NotNull
    @Email
    @Length(min = 3, max = 30)
    private String email;

    @NotNull
    @Length(min = 6, max = 30)
    private String password;

    private String gender;

    @Digits(fraction = 0, integer = 13)
    @Length(min = 8, max = 20)
    private String mobile;

    @Length(min = 6, max = 30)
    private String confirmPassword;

    @NotNull
    @Past
    private Date birthDate;

I'm using Jackson to submit JSON object in Spring MVC, moreover I'm using Hibernate Validator.
For the above DTO, when I'm trying to submit a json object with username length is less than the minimum length in the class @Length(min = 3, max = 30), I got http 400 bad request.
Why the annotation of hibernate validation  is tightly coupled with Jackson? and How can I get rid of this error?
Thank you in advance :D

A:

In the following link:
http://ppettitau.wordpress.com/tag/requestbody/
,You will find how to combine Hibernate Validator, Jacson, and Spring MVC.
The link is providing a complete request life cycle, the client sends request and receive a response in AJAX way.
The response contains the error messages that you want to show for the user.


Q:

Is there a point of wearing a talis that does not require tzitzis?

There is a din in the gemorah (Chullin 110a/110b and likely elsewhere)

ואמר רב יהודה טלית שאולה כל שלשים יום פטורה מן הציצית
A borrowed tallis does not require tzitzis for 30 days (my paraphrase)

(and therefore many have a custom not to recite a blessing on a borrowed tallis). If, say, I am praying shacharis with a borrowed tallis and tfilin, is there any point in wearing the tallis?

A:

The Shulchan Aruch rules (OC 14:3) that even though a man is exempt from attaching tzitzit to a borrowed four-cornered garment, if he borrowed it with tzitzit already attached, then he may say a blessing on it, implying that there is a mitzva that happens when he wears (at least a reshut--voluntary mitzva). So it would seem like there is good reason to wear that kind of tallit during prayers.

A:

A טלית is not necessarily a "prayer shawl" as commonly associated today. The word refers to a four-cornered wrap, like a toga, or a cape. Although it previously mentioned Tefillin the Gemara could talking about a generic cape/wrap/shawl, not a "prayer shawl" as often thought of today.
On the other hand, it seems like (ahem) "Hahu Gavra" was being sort of a trouble-maker, so it's possible he didn't care about anything other than making a point.


Q:

Breaking the HNQ feedback loop on bad questions

The Hot Network Questions sidebar is a bit of a contentious issue, because it tends to promote questions that are often perceived as 'cheap', of relatively low quality, or on the fringes of topicality for the site that hosts them.
One reason for this is that they're subject to a feedback loop: they're promoted widely, a bunch of people with no previous experience of the site click through, upvote it (because they bring their association bonus) but don't downvote it even if they recognize it as bad (because the association bonus doesn't let you downvote), and then the question score increases, and the system thinks it's really Hot and worthy of further promotion.
This has frustrated a lot of people, to the extent that people have asked that outsiders with just the association bonus be barred from voting on those questions (or, for that matter, asking how to get rid of the sidebar entirely). That, however, is a bit extreme, and makes understandable that the dev and community teams have given that proposal a wide berth over the two years since it was first proposed.
So, here's something a bit less extreme:
Let association-bonus users vote on HNQs, but don't count those votes and views into whatever algorithm does the decision that a question is Hot.
That is, separate all the votes and views on questions and answers into two categories,

those by users with 100+ rep earned on the site in question, and
those by everyone else, even if they have 100 rep from the association bonus,

and discard the second category when feeding it into the HNQ algorithm (possibly still this one?). (If you want to, you can change that 100 to some given threshold, no smaller than the earned ability to upvote at 15 rep.)
I think this is a good mix of not being too disruptive on the normal mechanisms while also allowing more room for the organic quality measures of the individual sites to decide what gets promoted more widely, instead of the current junk-food driven algorithm.
That said, I would at least like to know from the dev team whether there are insurmountable scaling and feasibility barriers to implementing this sort of separation.

A:

In my opinion, this proposal is treating the symptom rather than the cause of the issue.  The sites themselves pretty much don't have any input on whether a question makes it to HNQ, since especially on smaller sites a few quick answers and votes can quickly put the question on the HNQ regardless of quality and how well it fits the site. Once it's there, the only thing the site can do to guarantee the question gets off the list is closing it, which in the typical case doesn't make any sense.
The HNQ is great especially for telling other SE users about smaller sites they may not know about, but the site should have some way of influencing whether a question makes it to the list. The HNQ should be for high quality questions that reflect the site and attract new users. As of now, we don't have have any feedback on the quality or that it reflects the site only if it is "hot" or not.
A simple suggestion is once a question reaches a certain threshold instead of just going directly to the HNQ bar, it is instead put into a queue to check the quality of the questions similar to the triage. Based on its score there the question will get a multiplier to its HNQ score which won't influence it's overall position on the HNQ, but determine if the site wants it there over other questions that have similar scores.

A:

What's proposed in the question is a good, easy, actionable improvement that would make an immediate positive difference and is worth doing.
It can be done, and should be done (and probably should have been done 2 years ago when it was first proposed).
It should be rolled out as soon as possible.

Of course it's one improvement among many needed and not the mythical, magical one-fix-that-will-make-HNQs-perfect. We should, did, and probably will continue to spend large amounts of time discussing other, deeper, more fundamental improvements to the mechanisms around HNQ. That is important and needs doing. It is not a reason to not act on good, simple, quick improvements that will have an immediate positive effect.
If someone is bleeding heavily from the arm, you can and should spend time talking about why they're bleeding, how to prevent similar such bleeding, what the best bandaging technique is, etc etc. But that's not a good reason to dither and delay on treating the immediate symptom, bandaging the bleeding arm.
We should continue to discuss things like how to give sites more control over their HNQs, and discuss the details in posts like, for example:

Allow mods or gold tag badge holders to prevent question from being on hot network questions list
Let mods (and 10k?) know when questions go “hot”

...but that's not a good reason to delay taking a simple, easy to spec, easy to schedule and easy to implement action that will clearly reduce how often curious-looking but low-quality questions get stuck in the HNQ list because they're (often inadvertently) clickbait-y to people who don't know the topic.

See also this related even-more-popular proposal, from 2014, Prevent questions on Hot List from being upvoted by casual visitors (only rep is from association bonus). I think that's maybe an even better solution - but the most important thing is that either this proposal or that one gets done, and another two years aren't spent ignoring the problem.


Q:

Batch converting .eps to .jpg in imagemagick and making .mkv

I am trying to convert multiple .eps files into .jpg ones. By looking at answers here in SO, I was able to do it for single separate files.
The problem is that, when I'm trying to do it for all the files, they don't show any .jpg file.
I am currently using Imagemagick with the command

convert -density 300 outputs-000.eps -flatten outputs-000.jpg

I believe the problem is because my files are written as

outputs-000.eps
outputs-001.eps
outputs-002.eps
outputs-003.eps
...
outputs-145.eps
...

and so on. I tried putting %d (as in outputs-%d.eps and outputs-%d.jpg), but with no success.
Apart from that, I intent to get all those files and "convert" them into an .mkv or .gif or similar type (they are images of the time configuration of a particle collision system, so each image is a frame, so the goal is to make it into a 10sec movie). If there is a way to do that directly from the .eps, even better. Any help is welcome, since I've been trying to do this for several hours now. Thank you.

A:

You should be able to make an animated GIF in one go like this:
convert -density 300 outputs-*eps -delay 200 animated.gif

Failing that, you should be able to convert all your eps files to, say PNG with:
mogrify -density 300 -format png outputs-*eps

Be careful with mogrify - it overwrites your input files unless you specify -path for an output directory, or you change format - like I just did to PNG.


Q:

Possible to insert request headers into SSL/HTTPS Request using proxy?

I am currently using the apaches mod_proxy/mod_proxy_http/mod_headers as a forward proxy to add (overwrite) cookie request headers to a request like this:
<Proxy *>
Order deny,allow
Allow from all
RequestHeader set Cookie "mycookie=1234"
</Proxy>

(Of course i don't have allow from all and * but to simplify and reproduce this is just fine)
Now I want to do the same for an ssl connection. I loaded mod_proxy_connect which makes ssl work fine, but the header injection doesn't work.
This makes sense because SSL is end2end and shouldnt be modified on the way.
However I want to do it. I think the server would need to be a man in the middle. It would need its own SSL certificate which will be invalid for the domain, but this can be added as an exception. Can this somehow be done with a reverse proxy?
Another thing which i would be cool with to (which I would prefer) would be to map the ssl connection to a usual http connection.
Any suggestions welcome!

A:

It is possible, but that is a breach of SSL security, so you won't find feature for this in white-hat software.
SSLStrip can proxy HTTPS to HTTP and transform links and redirects on the fly.