text:
Q: Understanding deadlocks in java Given below is an example I found about deadlocks and it works. My question is how does currentThread() work? And also A and B are not created as threads specifically, i.e like:
Deadlock d=new Deadlock();
Thread A=new Thread(d)

How does the code still work?
class A {
    synchronized void foo(B b) {
        String name = Thread.currentThread().getName();
        System.out.println(name + " entered A.foo");
        try {
            Thread.sleep(1000);
        } catch (Exception e) {System.out.println("A Interrupted");
        }
        System.out.println(name + " trying to call B.last()");
        b.last();
    }

    synchronized void last() {
        System.out.println("Inside A.last");
    }
}

class B {
    synchronized void bar(A a) {
        String name = Thread.currentThread().getName();
        System.out.println(name + " entered B.bar");
        try {
            Thread.sleep(1000);
        } catch (Exception e) {System.out.println("B Interrupted");
        }
        System.out.println(name + " trying to call A.last()");
        a.last();
    }
    synchronized void last() {
        System.out.println("Inside A.last");
    }
}

public class Deadlock implements Runnable {
    A a = new A();
    B b = new B();

    Deadlock() {
        Thread.currentThread().setName("MainThread");
        Thread t = new Thread(this, "RacingThread");
        t.start();
        a.foo(b); // get lock on a in this thread.
        System.out.println("Back in main thread");
    }

    public void run() {
        b.bar(a); // get lock on b in other thread.
        System.out.println("Back in other thread");
    }

    public static void main(String args[]) {
        new Deadlock();
    }
}

A: I think this is a fairly confusing example of a deadlock - it adds other noise the the problem.
A very simple example can be achieved by using Lock objects like so:
public class App {

    private static final Lock LOCKA = new ReentrantLock();
    private static final Lock LOCKB = new ReentrantLock();

    private static final class Locker1 implements Runnable {

        @Override
        public void run() {
            while (true) {
                try {
                    LOCKA.lockInterruptibly();
                    Thread.sleep(100);
                    LOCKB.lockInterruptibly();
                    System.out.println("Locker 1 Got locks");
                } catch (InterruptedException ex) {
                    return;
                }
                LOCKB.unlock();
                LOCKA.unlock();
            }
        }
    }

    private static final class Locker2 implements Runnable {

        @Override
        public void run() {
            while (true) {
                try {
                    LOCKB.lockInterruptibly();
                    Thread.sleep(100);
                    LOCKA.lockInterruptibly();
                    System.out.println("Locker 2 Got locks");
                } catch (InterruptedException ex) {
                    return;
                } finally {
                    LOCKA.unlock();
                    LOCKB.unlock();
                }
            }
        }
    }

    public static void main(String[] args) throws IOException {
        final ExecutorService executorService = Executors.newFixedThreadPool(2);
        executorService.submit(new Locker1());
        executorService.submit(new Locker2());

    }
}

The application starts two threads in an executor, we then have those threads call two runnables.
These runnables try and acquire locks on the two Lock objects in the opposite order.
So Locker1 locks LOCKA then waits a few milliseconds. Locker2 locks LOCKB and waits a few milliseconds, they they try and acquire the other lock.
The situation is that Locker1 waits for LOCKB and Locker2 waits for LOCKA for ever as the other thread never releases it.
You can see this fairly clearly in the thread dump for those threads:
"pool-1-thread-1" - Thread t@8
   java.lang.Thread.State: WAITING
    at sun.misc.Unsafe.park(Native Method)
    - waiting to lock <7725204d> (a java.util.concurrent.locks.ReentrantLock$NonfairSync) owned by "pool-1-thread-2" t@9
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:186)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.parkAndCheckInterrupt(AbstractQueuedSynchronizer.java:834)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.doAcquireInterruptibly(AbstractQueuedSynchronizer.java:894)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireInterruptibly(AbstractQueuedSynchronizer.java:1221)
    at java.util.concurrent.locks.ReentrantLock.lockInterruptibly(ReentrantLock.java:340)
    at com.boris.testbench.App$Locker1.run(App.java:32)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
    at java.util.concurrent.FutureTask.run(FutureTask.java:166)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:722)

   Locked ownable synchronizers:
    - locked <7567e1fa> (a java.util.concurrent.locks.ReentrantLock$NonfairSync)

    - locked <5ad52411> (a java.util.concurrent.ThreadPoolExecutor$Worker)

"pool-1-thread-2" - Thread t@9
   java.lang.Thread.State: WAITING
    at sun.misc.Unsafe.park(Native Method)
    - waiting to lock <7567e1fa> (a java.util.concurrent.locks.ReentrantLock$NonfairSync) owned by "pool-1-thread-1" t@8
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:186)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.parkAndCheckInterrupt(AbstractQueuedSynchronizer.java:834)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.doAcquireInterruptibly(AbstractQueuedSynchronizer.java:894)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireInterruptibly(AbstractQueuedSynchronizer.java:1221)
    at java.util.concurrent.locks.ReentrantLock.lockInterruptibly(ReentrantLock.java:340)
    at com.boris.testbench.App$Locker2.run(App.java:51)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
    at java.util.concurrent.FutureTask.run(FutureTask.java:166)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:722)

   Locked ownable synchronizers:
    - locked <7725204d> (a java.util.concurrent.locks.ReentrantLock$NonfairSync)

    - locked <6856c528> (a java.util.concurrent.ThreadPoolExecutor$Worker)

We can see that pool-1-thread-1 wants a lock on the lock owned by pool-1-thread-2 and pool-1-thread-2 wants a lock on the lock owned by pool-1-thread-1.
This situation will continue forever, hence deadlock.
You code achieves the same result but instead of using two threads spawned manually it uses the application main thread (spawned by the JVM) and one thread spawned manually.
It also uses synchronized methods in two Objects rather than two Lock objects.

A: Thread#currentThread() = Thread that is currently running. Everything runs in a Thread. When you start a java app, you have only one thread that we can call the Main Thread. So, a call to a main method is nothing else but the start of a running thread.
I commented where you may be having some doubts.
// Deadlock is a Runnable. So, it can be wrapped inside a Thread Object to be started.
public class Deadlock implements Runnable {
    A a = new A();
    B b = new B();

    Deadlock() {
        // currentThread now is the one that instanciated this Deadlock object.
        Thread.currentThread().setName("MainThread");
        // here the Deadlock is wrapped inside a thread object. Notice the `this` qualifier.
        Thread t = new Thread(this, "RacingThread");
        // here the thread wrapping deadlock is started.
        t.start();

        a.foo(b); // get lock on a in this thread.
        System.out.println("Back in main thread");
    }

    public void run() {
        b.bar(a); // get lock on b in other thread.
        System.out.println("Back in other thread");
    }

    // here is the start of the Main Thread! :D
    public static void main(String args[]) {
        // the program is started inside the Deadlock Class constructor.
        new Deadlock();
    }
}

Can you understand better now?

A: Some good answers here (+1 to @Ralf and @bmorris591) but I thought I'd explain your code a bit more.
There are 2 threads here.  The "main" thread which runs main(...) and the "RacingThread" started from within the Deadlock constructor.  Btw, it is very bad form to start a thread in a object constructor.  It would be better to do something like:
  Deadlock deadlock = new Deadlock();
  new Thread(deadlock, "RacingThread").start();

Also, inside the Deadlock constructor it calls Thread.currentThread().setName("MainThread");.  This is trying to set the name of the current running thread which is (confusingly) the "main" thread since it did the new Deadlock().  Unfortunately the setName(...) call is a noop if the thread is already running so it doesn't do anything.
Next, inside the Deadlock constructor, the "RacingThread" is constructed with this as the Runnable and start() is called which forks the thread and has it call the Deadlock.run() method.  This takes some time so most likely the a.foo(b); line is reached before the run() method is called.
Your a and b objects are not threads as has been pointed out already.  They are just objects that are being used to demonstrate the locking.  The deadlock happens because the main thread is calling a.foo(b); and then the "RacingThread" calls the b.bar(a); inside of the run(); method.  a.foo(...) is synchronized on a and then tries to call b.last() which is synchronized on b.  b.bar(...) is synchronized on b and then tries to call a.last() which is synchronized on a.  That is a classic deadlock.
Hope this helps a bit.

A: I think you are assuming that the synchronized keyword is a global lock. It is not. It simply locks(serializes) access the the method to which it is applied. Given that your example does not call the same method on the same class from 2 separate threads, no reason it wouldn't work.

A: A deadlock occurs when 2 threads take two resources in different orders :

*

*T1 take r1

*T2 take r2

*T1 try to take r2 <=== blocked, waiting for resource r2

*T2 try to take r1 <=== blocked, waiting for resource r1

*system dead

This program:
public class DeadLock implements Runnable {

   String name;
   Object r1;
   Object r2;

   DeadLock( String name, Object r1, Object r2 ) {
      this.name = name;
      this.r1   = r1;
      this.r2   = r2;
   }

   @Override public void run() {
      if( name.equals( "T1" )) {
         System.out.println( name + " try to take r1" );
         synchronized( r1 ) {
            System.out.println( name + " has taken r1" );
            try{ Thread.sleep( 1000L ); }catch( InterruptedException x ){}
            System.out.println( name + " try to take r2" );
            synchronized( r2 ) {
               System.out.println( name + " has taken r2" );
            }
         }
      }
      else {
         System.out.println( name + " try to take r2" );
         synchronized( r2 ) {
            System.out.println( name + " has taken r2" );
            try{ Thread.sleep( 1000L ); }catch( InterruptedException x ){}
            System.out.println( name + " try to take r1" );
            synchronized( r1 ) {
               System.out.println( name + " has taken r1" );
            }
         }
      }
   }

   public static void main( String[] args ) {
      Object r1 = new Object();
      Object r2 = new Object();
      new Thread( new DeadLock( "T1", r1, r2 )).start();
      new Thread( new DeadLock( "T2", r1, r2 )).start();
   }
}

Outputs:
T1 try to take r1
T2 try to take r2
T1 has taken r1
T2 has taken r2
T2 try to take r1
T1 try to take r2


text:
Q: CSS3 transform difference in Firefox and Chrome and IE I think it may have something to do with a pseudo element, but I'm not sure. I am having difficulties with the effect of a transform transition using css3. In Firefox v24, the effect works as I want it to - see the CodePen here http://codepen.io/patrickwc/pen/aKEec but in Chrome and IE, the border effect of the links animate and then suddenly switch back into position. It is difficult to describe so the best way is to look at the effect in Firefox then in Chrome or IE.

body {
  background: #000;
  color: #fff;
}

p {
  text-align: center;
}

nav.footer-social-links a {
  position: relative;
  margin: 0 10px;
  text-transform: uppercase;
  letter-spacing: 1px;
  padding: 1px 12px 0 8px;
  height: 32px;
  line-height: 30px;
  outline: none;
  font-size: 0.8em;
  text-shadow: 0 0 1px rgba(255, 255, 255, 0.3);
}

nav.footer-social-links a:hover,
nav.footer-social-links a:focus {
  outline: none;
}

.footer-social-links a::before,
.footer-social-links a::after {
  position: absolute;
  width: 30px;
  height: 2px;
  background: #fff;
  content: '';
  opacity: 0.2;
  -moz-transition: all 0.3s;
  -o-transition: all 0.3s;
  -webkit-transition: all 0.3s;
  transition: all 0.3s;
  pointer-events: none;
}

.footer-social-links a::before {
  top: 0;
  left: 0;
  -webkit-transform: rotate(90deg);
  -moz-transform: rotate(90deg);
  transform: rotate(90deg);
  -webkit-transform-origin: 0 0;
  -moz-transform-origin: 0 0;
  transform-origin: 0 0;
}

.footer-social-links a::after {
  right: 0;
  bottom: 0;
  -webkit-transform: rotate(90deg);
  -moz-transform: rotate(90deg);
  transform: rotate(90deg);
  -webkit-transform-origin: 100% 0;
  -moz-transform-origin: 100% 0;
  transform-origin: 100% 0;
}

.footer-social-links a:hover::before,
.footer-social-links a:hover::after,
.footer-social-links a:focus::before,
.footer-social-links a:focus::after {
  opacity: 1;
}

.footer-social-links {
  margin: 0;
  text-align: center;
}

.footer-social-links a {
  color: white;
  -webkit-transition: all 0.3s;
  -moz-transition: all 0.3s;
  -o-transition: all 0.3s;
  transition: all 0.3s;
  display: inline-block;
  text-decoration: none;
}

.footer-social-links a:hover::before,
.footer-social-links a:focus::before {
  width: 80%;
  left: 10%;
  -webkit-transform: rotate(0deg) translateX(50%);
  -moz-transform: rotate(0deg) translateX(50%);
  transform: rotate(0deg) translateX(50%);
}

.footer-social-links a:hover::after,
.footer-social-links a:focus::after {
  width: 80%;
  right: 5%;
  -webkit-transform: rotate(0deg) translateX(50%);
  -moz-transform: rotate(0deg) translateX(50%);
  transform: rotate(0deg) translateX(50%);
}

    Gplus

    Facebook

    Twitter

    Linkedin

    Skype

    Lastfm

Fixed with help from css-tricks forum and stackoverflow here

I have a feeling messing with transform-origin might fix it, but I've been unable to get that to work. Any help or explanation as to the difference would be greatly appreciated.

A: I am not sure about why Chrome has problems with your code, but you can simplify it and then it will work ok in all the browsers.
You should change your CSS to
.footer-social-links a:hover::before,
.footer-social-links a:focus::before {
    width: 80%;
    left: 10%;
    -webkit-transform: rotate(0deg);
    -moz-transform: rotate(0deg);
    transform: rotate(0deg);
}

.footer-social-links a:hover::after,
.footer-social-links a:focus::after {
    width: 80%;
    right: 10%;
    -webkit-transform: rotate(0deg);
    -moz-transform: rotate(0deg);
    transform: rotate(0deg);
}

It is useless to do a translate  in X and at the same time modify your left value; better concentrate the changes in a single value (left) and eliminate the translateX

redpajama_set_name: RedPajamaStackExchange


text:
Q: ASP.Net mvc 5 - Save Parent and child records together I am just getting started with ASP.net mvc 5 and got stuck into one problem that I have explained below:
I have User and History models. And user can have more then one history.
User model:
public class User
{
    public int ID { get; set; }
    public string TicketType { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Gender { get; set; }

    public virtual ICollection<History> Histories { get; set; }
}

History model:
public class History
{
    public int ID { get; set; }
    public int Year { get; set; }
    public int Month { get; set; }
    public int Day { get; set; }

    public virtual User User { get; set; }
}

UserController:
public class UsersController : Controller
{
    private MyDbContext db = new MyDbContext();

    public ActionResult Create()
    {
        var user = new User();
        user.Histories = new List<History>();
        user.Histories.Add(new History { });
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "ID,TicketType,FirstName,LastName")] User user)
    {
        if (ModelState.IsValid)
        {
            db.Users.Add(user);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(user);
    }
}

Here is my form:
Create.cshtml
@model MyApp.Models.User

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    @Html.Partial("_Form")

    <input type="submit" value="Create" class="btn btn-lg btn-success" />
}

_Form.cshtml: Just to remove duplication in both Create and Edit forms
        @model MyApp.Models.User
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.TicketType, htmlAttributes: new { @class = "control-label" })
            @Html.DropDownListFor(model => model.TicketType, new List<SelectListItem>
                    {
                        new SelectListItem() {Text = "OPD", Value="opd"},
                        new SelectListItem() {Text = "Emergency", Value="emergency"},
                    }, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.TicketType, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label" })
            @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label" })
            @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })

            Year
            <input type="text" value="" class="form-control" />

            Month
            <input type="text" value="" class="form-control" />

            Day
            <input type="text" value="" class="form-control" />

A: You Have First created ViewModel.
The view model combine to user and history model
below the code
Public class userviewmodel
{

     public string TicketType { get; set; }
     public string FirstName { get; set; }
     public string LastName { get; set; }
     public string Gender { get; set; }
     public int Year { get; set; }
     public int Month { get; set; }
     public int Day { get; set; }

 }

second, your chtml view is modified :
set model userviewmodel
 @model MyApp.Models.Userviewmodel

Form design change code  in year, month and  day

          Year
          Month
          Day

        Year
        @Html.EditorFor(model => model.Year, new { htmlAttributes = new { @class = "form-control" } })

    Year
    @Html.EditorFor(model => model.month, new { htmlAttributes = new { @class = "form-control" } })

    Year
    @Html.EditorFor(model => model.day, new { htmlAttributes = new { @class = "form-control" } })

  <input type="button" value="add">

if the add button click create new Row in the table t body
every  inside textbox or HiddenField Vlaue Assied the current textbox value
For example
 jquery function
  $("#add").click(function(){
      string row="
<input type='text' value='$('#year').val(),
       name='Yearlist'>
        <input type='text' value='$('#month').val(), name='monthlist'>
       <input type='text' value='$('#day').val(), name='daylist'>

"
        $("#tbodyval").append(row);
    });

cahnge your code in controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create( Userviewmodel usermodel, string[] yearList,string[] monthList,string[] dayList())
{
    if (ModelState.IsValid)
    {

        user model=new user()
        model.TicketType=.usermodel.TicketType;
        model.FirstName=usermodel.FirstName;
        model.LastName=usermodel.LastName;
        model.Gender=usermodel.Gender;

       for(int i=0;i<yearlist.count();i++)
       {
         History child=new History()

         child.Year=yearlist[i].Year;
         child.month=montList[i].month;
         chile.day=dayList[i].day;
         model.Histories.add(child);
       }

        db.Users.Add(model);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(user);
}


text:
Q: Python 3.x - don't count carriage returns with len I'm writing the following code as part of my practice:
input_file = open('/home/me/01vshort.txt', 'r')
file_content = input_file.read()
input_file.close()
file_length_question = input("Count all characters (y/n)? ")
if file_length_question in ('y', 'Y', 'yes', 'Yes', 'YES'):
    print("\n")
    print(file_content, ("\n"), len(file_content) - file_content.count(" "))

It's counting carriage returns in the output, so for the following file (01vshort.txt), I get the following terminal output:
Count all characters (y/n)? y

0
0 0
1 1 1

 9

...or...
Count all characters (y/n)? y

0
00
111

 9

In both cases, the answer should be 6, as there are 6 characters, but I'm getting 9 as the result.
I've made sure the code is omitting whitespace, and have tested this with my input file by deliberately adding whitespace and running the code with and without the line:
 - file_content.count(" ")

Can anyone assist here as to why the result is 9 and not 6?
Perhaps it isn't carriage returns at all?
I'm also curious as to why the result of 9 is indented by 1 whitespace? The input file simply contains the following (with a blank line at the end of the file, line numbers indicated in the example):
1. 0
2. 0 0
3. 1 1 1
4.

...or...
1. 0
2. 00
3. 111
4.

Thanks.

A: If you want to ignore all whitespace characters including tabs and newlines and other control characters:
print(sum(not c.isspace() for c in file_content))

will give you the 6 you expect.
Alternatively you can take advantage of the fact the .split() method with no argument will split a string on any whitespace character. So split it into non-space chunks and then join them all back together again without the whitespace characters:
print(len(''.join(file_content.split())))

A: You're getting 9 because the content of the file could be interpreted like:
file_content = "0\n0 0\n1 1 1\n"

and you're only matching the white spaces (file_content.count(" ")).
In order to count only the characters you'd either:

*

*read line by line the file, or

*use a regexp to match white space.

For the indenting of 9: print processes the commas as outlined here


text:
Q: How to send private messages or locate a specific user? I'm a 17-year-old girl living in Mexico and dreaming of studying at a university in Romania. I speak Spanish and English and am trying my best to learn Romanian, and I can hardly find anyone to whom I can speak in Romanian. My only Romanian e-friend who's actually willing to help won't Skype with me because he lives with his family and the time difference means he'd wake them if we were to Skype at a decent time for me.
Now that you know this, you can imagine my excitement when I randomly found an active user with a totally Romanian name, Bogdan Alexandru, and even more so when I clicked his profile and found that he is indeed from București. But he has no contact links on his profile. Is there any way I can contact him and offer to trade services (like an I'll-help-you-with-Spanish-if-you-help-me-with-Romanian thing)? Or will I just have to put something on my profile, answer one of his questions and hope he looks at my page?

A: This is not possible.
Why? Because we are not a social network. And we are not interested in becoming one. We focus on questions and answers, under specific topics.
If a user has not shared any contact details publicly, it is most probably because they don't want to be contacted by strangers.

Or will I just have to put something on my profile, answer one of his questions and hope he looks at my page?

By all means, put something on your profile.
However, unless you have an actual, relevant answer to a post by this person, you shouldn't answer. Doing anything else would be rude by our standards.


text:
Q: Access values of Go struct in external function I have the following function declararion, which works and prints out correctly.
import (
    "fmt"
    "github.com/google/go-github/github"
)

func LatestTag(user, project string) {

    client := github.NewClient(nil)
    releases, _, err := client.Repositories.ListTags(user, project, nil)

    if err != nil {
        fmt.Printf("error: %v\n", err)
    } else {
        release := releases[0]
        fmt.Printf("Version: %+v\n", *release.Name)
    }

}

EDIT
I have modified the function to return a string (I don't think this is right) but hopefully it can help shed some light on what I am trying to do.
import (
    "fmt"
    "github.com/google/go-github/github"
)

func LatestTag(user, project string) string {

    client := github.NewClient(nil)
    releases, _, err := client.Repositories.ListTags(user, project, nil)
    var release string

    if err != nil {
        fmt.Printf("error: %v\n", err)
    } else {
        release := releases[0]
    }
    return *release.Name
}

I would like to return the value of *release.Name rather than just print it out so that I can access the value from another function but I don't understand how returning works in this case (very new to Go).
I was thinking I could just return the struct as a string but get errors when I run it.
release.Name undefined (type string has no field or method Name)

Which makes me think that I'm not approaching this correctly.  Can somebody point me in the right direction?

A: One problem is here:
var release string
...
if err != nil {
...
} else {
    release := releases[0]  // <-- here
}

At the line indicated you define a new variable called release equal to releases[0] which is scoped only to the else clause (use of :=). That then goes out of scope immediately. I'm surprised you don't get an unused variable warning. Looks like you also need to change the type of release to github.RepositoryTag. Try:
var release github.RepositoryTag
...
if err != nil {
...
} else {
    release = releases[0]  // note equals sign
}

However a more idiomatic way to do this would be something like (untested):
func LatestTag(user, project string) (string, error) {
    client := github.NewClient(nil)
    if releases, _, err := client.Repositories.ListTags(user, project, nil); err != nil {
        return "", err
    } else {
        release := releases[0]
        return *release.Name, nil
    }
}


text:
Q: Power Query convert of 3 byte binary date getting variable wasn't recognized Date displays as 3byte hex value example = 72, 02, 11
Converts to 72 to decimal = 114 + 1900 = 2014, 02 = 02, 11 = 17
So date is 02/17/2014
Bdate comes in as a three byte field, binary so defined
1st byte = year, 2nd byte = mth, 3rd byte = day.
Building a function to call because several dates in data base are of this format.
Secondary function to convert hex to decimal is fnhex2Dec from a library.
Here is code for FixDateBn
    let
        FixDateBn = (Bdate as binary) =>

        let
        FixDateBn = BinaryFormat.ByteOrder(
        BinaryFormat.Record ([
                Yr= BinaryFormat.Byte,       //<- the Yr variable is getting Name Yr wasn't recognized.
                Mth = BinaryFormat.Byte,
                Day = BinaryFormat.Byte ]),
            ByteOrder.LittleEndian),
                Yrnum = fnhex2Dec(Yr,16)+1900,
                Mthnum = fnhex2Dec(Mth,16),
                Daynum = fnhex2Dec(Day,16),
            Gooddate = #date(Yrnum,Mthnum,Daynum) as date
        in
            if Bdate is null then null else Gooddate
    in
        FixDateBn

Appreciate any help.
Here is the sql that converts from hex to regular date. Don't know how to do this in Power Query M language.
CREATE FUNCTION "GetDateFromWDate" (:wDate CHAR(3)) RETURNS DATE AS
BEGIN
    DECLARE :tmpdate DATE
    SET :tmpdate = '1900-01-01';
    IF (:wDate <> null) and (:wDate <> '') THEN
        SET :tmpdate = DATEFROMPARTS (ascii(substring(:wDate, 1, 1)) + 1900, ascii(substring(:wDate, 2, 1)), ascii(substring(:wDate, 3, 1)));
    END IF;
    RETURN :tmpdate;
END

Thanks
Sammy


text:
Q: How do I set a String variable equal to that of the value on a slider? I am trying to create a label that will show what the current selected value is for a particular slider. Currently, I am able to insert the labels and get them onto the window. I am not sure how to get the value of the slider to show up in the label. I am pretty sure that I need to parse the information being that it is two different value types.
Any help with where to go from here would be greatly appreciated.
Code added on edit:
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;

public class ColorSliders extends JFrame implements ChangeListener {
    ColorPanel canvas = new ColorPanel();
    JSlider red = new JSlider(0, 255, 255);
    JSlider blue = new JSlider(0, 255, 0);
    JSlider green = new JSlider(0, 255, 0);

    // Creating labels to measure output of Slider Value
    JLabel redLabelValue = new JLabel("Red Value: ");
    JLabel greenLabelValue = new JLabel("Green V: ");
    JLabel blueLabelValue = new JLabel("Blue: ");

    public ColorSliders() {
        super("Color Slide");
        setSize(350, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);

        red.setMajorTickSpacing(50);
        red.setMinorTickSpacing(10);
        red.setPaintTicks(true);
        red.setPaintLabels(true);
        red.addChangeListener(this);

        green.setMajorTickSpacing(50);
        green.setMinorTickSpacing(10);
        green.setPaintTicks(true);
        green.setPaintLabels(true);
        green.addChangeListener(this);

        blue.setMajorTickSpacing(50);
        blue.setMinorTickSpacing(10);
        blue.setPaintTicks(true);
        blue.setPaintLabels(true);
        blue.addChangeListener(this);

        JLabel redLabel = new JLabel("Red: ");
        JLabel greenLabel = new JLabel("Green: ");
        JLabel blueLabel = new JLabel("Blue: ");
        GridLayout grid = new GridLayout(4,1);
        FlowLayout right = new FlowLayout(FlowLayout.LEFT);
        setLayout(grid);

        JPanel redPanel = new JPanel();
        redPanel.setLayout(right);
        redPanel.add(redLabel);
        redPanel.add(red);
        redPanel.add(redLabelValue);
        add(redPanel);

        JPanel greenPanel = new JPanel();
        greenPanel.setLayout(right);
        greenPanel.add(greenLabel);
        greenPanel.add(green);
        greenPanel.add(greenLabelValue);
        add(greenPanel);

        JPanel bluePanel = new JPanel();
        bluePanel.setLayout(right);
        bluePanel.add(blueLabel);
        bluePanel.add(blue);
        bluePanel.add(blueLabelValue);
        add(bluePanel);
        add(canvas);

        setVisible(true);
    }

    public void stateChanged(ChangeEvent event) {
        JSlider source = (JSlider) event.getSource();
        if (source.getValueIsAdjusting() != true) {
            Color current = new Color(red.getValue(), green.getValue(),
                    blue.getValue());
            String blueVal = Integer.parseInt(blue.getValue());
            blueLabelValue.setText(blueVal);
            canvas.changeColor(current);
            canvas.repaint();
        }
    }

    public Insets getInsets() {
        Insets border = new Insets(45, 10, 10, 10);
        return border;
    }

    public static void main(String[] arguments) {
        ColorSliders cs = new ColorSliders();
    }
}

class ColorPanel extends JPanel {
    Color background;

    ColorPanel() {
        background = Color.red;
    }

    public void paintComponent(Graphics comp) {
        Graphics2D comp2D = (Graphics2D) comp;
        comp2D.setColor(background);
        comp2D.fillRect(0, 0, getSize().width, getSize().height);
    }

    void changeColor(Color newBackground) {
        background = newBackground;
    }
}

A: Change:
String blueVal = Integer.parseInt(blue.getValue());

TO
String blueVal = String.valueOf(blue.getValue());

You have to create a String vom an Integer, not an Integer from a String

A: You'd first need to get the value of the slider by using:
int value = <JSliderFieldName>.getValue();

And then set your JLabel text to:
String labelText = "JSlider Value: " + value;


text:
Q: Meteor data not updated on change I'm having an issue getting Meteor to update properly. My template is as follows:
  <template name="hello">

Hello World!

        {{#each items}}
        {{>demoRow}}
        {{/each}}

  </template>
  <template name="demoRow">

     {{order}}

          <input type="text" class="nameChanger" name="demoName-{{name}}" data-demoname="{{name}}"     style="width: 90px" value="{{name}}"/>

  </template>

The script file looks like the following:
Template.hello.items = function () {
      var entity= Entities.findOne(Session.get('entityId'));
      if(entity!=null) {
         return Entities.findOne(Session.get('entityId')).items;
      }
      return null;
   };
Template.hello.events({
      'change .nameChanger': function(evt) {
          var $tgt = $(evt.target)
          var entity=Entities.findOne(Session.get('entityId'));
          var items = entity.items;
          var tgtName = $tgt.data('demoname');
          var newName = $tgt.val();
          var found=false;
          for(var i=0;i<items.length;i++) {
              var item=items[i];
              if(item.name == tgtName) {
                  item.name =newName;
                  found=true;
              }
          }
          if(!found) {
              alert("Cannot find ",tgtName);
          }
          Entities.update({_id: entity._id}, {$set: { items: items}});
      },
    });

Finally, my initial value is set up as:
Entities.insert( { type: 'test',
                 items: [
                     {name: 'value1'},
                     {name: 'value2'},
                     {name: 'value3'}
                     ]
             }
         );

This renders a table of text inputs. When I change one of the text fields, it automatically updates the entities collection and the display shows the correct data.  However, if I try to change the same field a second time, my alert will trigger as it cannot find the value.
The really interesting part is that tgtName has the original, unchanged value. Yet, evt.target has the correct, updated data set with the new name.  I can even get the correct name via evt.target.dataset['demoname'] which is the workaround I have in place.
My question is, why id $tgt.data() not hold the updated values?
I should mention that this does update other windows appropriately and if I update it in one window and then update the same value in another, it does work appropriately, first time. After that, both windows seems to house the value they had at the first update.  It's almost like some kind of scope issue, but I can't figure out where.
Thanks

A: Just guessing, but maybe the update is doing something wrong. Maybe you could try just updating the single edited item. Try this:
Template.hello.events({
  'change .nameChanger': function(evt) {
      var $tgt = $(evt.target)
      var entity=Entities.findOne(Session.get('entityId'));
      var items = entity.items;
      var tgtName = $tgt.data('demoname');
      var newName = $tgt.val();
      var found=false;
      for(var i=0;i<items.length;i++) {
          var item=items[i];
          if(item.name == tgtName) {
              item.name =newName;
              found=true;
              break;
          }
      }
      if(!found) {
          alert("Cannot find ",tgtName);
      }
      else
        Entities.update({_id: entity._id}, {$set: { 'items.' + i.toString(): item}});
  },
});

A bit clunky, but maybe...

A: This is a limitation of jQuery with Meteor (or any other thing that tries to modify the data attribute)

The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery).

So, the option are to NOT user jQuery and access the evt.target.dataset['demoname'] as stated, or to use the jQuery.attr()
$tgt.attr("data-demoname")

Thanks to mizzao and dgreensp at meteor for help on this (https://github.com/meteor/meteor/issues/2329)


text:
Q: Can not save .cer file to keychain I can not save a .cer file to my keychain. I see them being saved under system "certificates" but not under login "my certificates". Saving them under system it does not allow for me to create .p12 files. Anyone run into this before?

A: Remove .cer certificate from keychain which installed under system certificates. Now select keys from left panel remove keys also for your certificate. Select My Certificates quit Keychain access.
Restart your system.Now again try to install .cer file.
It worked for me.


text:
Q: filter duplicates according to conditions I have the messy result of merging two data frames and want to decide according to specified criteria.
The data looks as follows (only duplicates shown):
structure(list(date = structure(c(2347, 2347, 2347, 2347, 2347, 2347, 2347, 2347, 6962, 6962, 16442, 16442, 16442, 16442), class = "Date"),
               country = c("United Kingdom", "United Kingdom", "United Kingdom", "United Kingdom", "United Kingdom", "United Kingdom", "United Kingdom",
                           "United Kingdom", "Greece", "Greece", "France", "France", "France", "France"),
               city = c("Belfast", "Belfast", "Belfast", "Belfast", "Belfast", "Belfast", "Belfast", "Belfast", "Athens",  "Athens", "Paris", "Paris", "Paris", "Paris"),
               diff_categories = c(FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE),
               diff_num1 = c(-1, -4, 0, -3, 3, 0, -1, -4, 0, 1, 0, 12, -12, 0),
               diff_num2 = c(NA, NA, NA, NA, NA, NA, NA, NA, 0, 0, 1, 11, -10, 0),
               df1_id = c("df1_197606050002", "df1_197606050002", "df1_197606050003", "df1_197606050003","df1_197606050004", "df1_197606050004", "df1_197606050006",
                          "df1_197606050006","df1_198901230001", "df1_198901230001", "df1_201501070001", "df1_201501070001","df1_201501070002", "df1_201501070002"),
               df2_id = c("df2_101", "df2_102", "df2_101", "df2_102", "df2_101", "df2_102", "df2_101", "df2_102", "df2_216", "df2_219", "df2_510",  "df2_511",  "df2_510", "df2_511")),
          row.names = c(NA, -14L), class = c("tbl_df", "tbl", "data.frame"))

I now want to only keep one row per instance of df1_id and decide which row according to the following criteria (in descending order; first is most important):

*

*diff_categories must be FALSE

*diff_num1 should be as small as possible

*diff_num2 should be as small as possible

*keep first.

Can someone point out how to best implement this logic?

A: Will this work:
library(dplyr)
df %>%
   group_by(df1_id) %>%
       filter(diff_categories == TRUE & diff_num1 == min(diff_num1) & diff_num2 == min(diff_num2))


text:
Q: Django model inheritance problem. How to solve? I have an existing app with the following model
class Contact(models.Model):
     lastname = models.CharField(max_length=200)
     firstname = models.CharField(max_length=200)
     ...

class Journalist(Contact):
     pass

I have a Contact in my database and I would like that it becomes a Journalist.
In raw sql, it seems as simple as insert into app_journalist values (25624);. In this example 25624 is the id of the existing contact. It seems to work ok and the django app seems happy.
However, I would like to make the same thing with the django ORM. I have tried several thinks like forcing the journalist id (Journalist(id=25624)) but it creates a new contact rather than linking to the existing one.
Is it possible do to that with the Django ORM? How?
Thanks in advance for your help

A: One way to solve this is (without changing your model structure) to set the contact_ptr attribute of the Journalist instance to the appropriate Contact instance. For e.g.
contact = Contact.objects.get(pk = 25624)
journalist = Journalist(contact_ptr = contact)
journalist.save()

This becomes easier to understand if you first look at the table app_journalist. It has but one column, contact_ptr_id. So when you execute insert into app_journalist values (25624) you are setting contact_ptr_id = 25624 at the SQL level. Correspondingly you should set the  contact_ptr = <instance of Contact> at the ORM level.
Update
There are other ways to solve the problem but they would require changes to your existing models. As @bugspy.net pointed out you can use a generic relationship. Alternately you can declare an additional type field to specify whether the contact is a journalist, a colleague etc.
Update 2
Also take a look at this demo snippet (and the complete code) that lets you use polymorphic inheritance (SQLAlchemy already does this).
Update 3
As @luc himself pointed out (see comment below)
journalist = Journalist(contact_ptr = contact)

alone will not suffice. This will overwrite the firstname and lastname of the contact to "". To avoid this you have to explicitly assign each field to Journalist.

A: Django's Contenttypes framework is really handy.
You could use it to represent different contact types:
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

class Contact(models.Model):
     lastname = models.CharField(max_length=200)
     firstname = models.CharField(max_length=200)
     content_object = generic.GenericForeignKey('content_type', 'object_id')

A: Inheritance at the model level is usually not such a good idea. Most ORM let you do it. Most ORM are even proud to be able to do it. At the model level, the famous "prefer composition over inheritance" is more true than ever.
In your case, instead of saying : "A journalist IS A person", you could instead say : "A person has a job, which in this case is journalist". This would be represented by a Person class composed with a Job class. One of the job could be "journalist".
The composition approach lets you have a person change job, or even have multiple jobs.
Of course, this doesnt directly answer your question, but the other answers are already pretty good !


text:
Q: Django model foreign key in the same table Before to send this kind of modification to my database, I just would like to know if what I do is OK or not.
class Comments(models.Model):
    text = models.CharField(max_length=300, null=False)
    image = models.FileField(upload_to=user_directory_path_comments, validators=[validate_file_extension], blank=True, null=True)
    articles = models.ForeignKey(Articles, verbose_name="Article", null=False)
    author = models.ForeignKey(User, verbose_name="Auteur")
    in_answer_to = models.ForeignKey(Comments, verbose_name="En réponse au commentaire", blank=True, null=True)
    date = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name="Date de création")
    update = models.DateTimeField(auto_now=True, verbose_name="Dernière modification")

    def __str__(self):
        return self.text

I have a model called Comments for listing the comments in my article's blog. I want to add the functionality to answer to a comment and so I add a field name where, if it's an answer, I add the ID of the comment.
So, is it OK if I add a foreign key field, knowing that it's is about the same table ? This is not really a foreign key ?

A: You can have a ForeignKey that references the same model, but in that case you should use 'self' as the othermodel argument.
From the documentation:

To create a recursive relationship – an object that has a many-to-one relationship with itself – use models.ForeignKey('self', on_delete=models.CASCADE).


text:
Q: How to launch Windows Scheduler by command-line? I mean to open the built-in Windows GUI from command line- not to launch by Schtasks

A: Yes, the GUI is available in XP.  I can get the list of scheduled tasks (but not the GUI) to open with the following command,
control.exe  schedtasks

Then you can use the wizard to add a new scheduled task, for example.
In XP, you can find the Scheduler GUI from within Windows Help if you search for "Scheduled Tasks" then click on "Step by Step instructions" and open the scheduler GUI.  Clicking on the last link executes the following command, which likely could be translatedinto something that would open the Scheduler GUI from the command line.  Does anyone know how?
ms-its:C:\WINDOWS\Help\mstask.chm::/EXEC=,control.exe, schedtasks CHM=ntshared.chm FILE=alt_url_windows_component.htm

A: taskschd.msc is available in Windows Vista and later.
http://technet.microsoft.com/en-us/library/cc721871.aspx
I could have sworn I'd seen a little task scheduler GUI like you're talking about prior to Vista, but maybe I was thinking of the "Add Scheduled Task" wizard.
You might have to settle for opening the scheduled tasks explorer with this command:
control schedtasks

I couldn't find any way to launch the "Add Scheduled Task" wizard from the command line, unfortunately (there has to be a way!)

A: Here is an example I just used:
at 8am /EVERY:M,T,W,Th,F,S,Su cmd /c c:\myapp.exe

The result was:
Added a new job with job ID = 1

Then, to check my work:
at

A: You might want to have look at simple command line scheduler "at":

C:\Documents and Settings\mahendra.patil>at/?

The AT command schedules commands and programs to run on a computer at
a specified time and date. The Schedule service must be running to use
the AT command.
AT [\\computername] [ [id] [/DELETE] | /DELETE [/YES]]
AT [\\computername] time [/INTERACTIVE]
    [ /EVERY:date[,...] | /NEXT:date[,...]] "command"

\computername     Specifies a remote computer. Commands are scheduled on the
                   local computer if this parameter is omitted.
id                 Is an identification number assigned to a scheduled
                   command.
/delete            Cancels a scheduled command. If id is omitted, all the
                   scheduled commands on the computer are canceled.
/yes               Used with cancel all jobs command when no further
                   confirmation is desired.
time               Specifies the time when command is to run.
/interactive       Allows the job to interact with the desktop of the user
                   who is logged on at the time the job runs.
/every:date[,...]  Runs the command on each specified day(s) of the week or
                   month. If date is omitted, the current day of the month
                   is assumed.
/next:date[,...]   Runs the specified command on the next occurrence of the
                   day (for example, next Thursday).  If date is omitted, the
                   current day of the month is assumed.
"command"          Is the Windows NT command, or batch program to be run.

A: You can make a new shortcut to:
control schedtasks

Name it something easy like "tsks.lnk" and then save it in c:\windows\system32.
You can now press Windows Key + R, then type "tsks" and press Enter and voila.  No mouse necessary at that point.
Or in Windows Vista/7/2008, just press Windows Key, then type "tsks" and press Enter.

A: I'm using Windows 2003 on the server. I'm in action with "SCHTASKS.EXE"
    SCHTASKS /parameter [arguments]

    Description:
        Enables an administrator to create, delete, query, change, run and
        end scheduled tasks on a local or remote system. Replaces AT.exe.

    Parameter List:
        /Create         Creates a new scheduled task.

        /Delete         Deletes the scheduled task(s).

        /Query          Displays all scheduled tasks.

        /Change         Changes the properties of scheduled task.

        /Run            Runs the scheduled task immediately.

        /End            Stops the currently running scheduled task.

        /?              Displays this help message.

    Examples:
        SCHTASKS
        SCHTASKS /?
        SCHTASKS /Run /?
        SCHTASKS /End /?
        SCHTASKS /Create /?
        SCHTASKS /Delete /?
        SCHTASKS /Query  /?
        SCHTASKS /Change /?

    ┌─────────────────────────────────────┐
    │ Executed Wed 02/29/2012 10:48:36.65 │
    └─────────────────────────────────────┘

It's quite interesting and makes me feel so powerful. :)

A: You can use either TASKSCHD.MSC or CONTROL SCHEDTASKS
Here are some more such commands.

A: This launches the Scheduled Tasks MMC Control Panel:
%SystemRoot%\system32\taskschd.msc /s

Older versions of windows had a splash screen for the MMC control panel and the /s switch would supress it.  It's not needed but doesn't hurt either.

A: I'm also running XP SP2, and this works perfectly (from the command line...):
start control schedtasks

A: If you're asking what I think you're asking, you can open it by executing this:
explorer.exe "C:\WINDOWS\Tasks\"


text:
Q: Joomla 2.5: You do not have access to the administrator section of this site I have trouble with my Joomla 2.5
I see this when i'm login with correct superuser username and password

I also included SQL file if you want to analyze it
here is: http://akdira.drivehq.com/akdira/u889932813_ah2.sql
Can someone give solution please?

A: I had the same issue a few days ago & was lost in finding an answer.
However, I did find this website: http://www.itoctopus.com/you-do-not-have-access-to-the-administrator-section-of-this-site-error-when-trying-to-login-to-joomlas-admin & in that had my answer.
The section that helped me was in step 3.

Step 3: Check the jos_assets table: If all else fails, then (sadly)
  the problem almost certainly lies in the jos_assets table (which is,
  by far, the scariest table in Joomla – because a simple mistake in
  that table can cause a total collapse of the website). The two most
  common causes in the jos_assets table that might lead to this problem
  are:
Missing entry for the com_admin row. (By the way, that was the reason why the system administrator at that chip maker company wasn't able to login to the website)
Wrong rules field for the com_admin row. The rules field for that row should just contain "{}". (two curly brackets)

I found in my site that the first three entries were deleted from the assets table.
I suggest you look at your assets table & compare it to a clean site & add in any that are missing. T

A: I'm not sure that this is your problem, but you can try to run the following query:
UDPATE `ah2_users` SET `password` = "d2064d358136996bd22421584a7cb33e:trd7TvKHx6dMeoMmBVxYmg0vuXEA4199"
  WHERE `username` = "akdira"

This will try to reset the password for user with username akdira.
The new password should be the wordsecret
Note to all readers: The table ah2_users is just for this site. The prefix will probably be different for other sites.

A: Make sure your #_assets table has parent_id=0 for Root Asset. If not, set parent_id=0 for root asset. It worked for me.

A: I have same problem with joomla 3.9, Checked and found #__user_usergroup_map table has the wrong mapped for admin. I have changed role_id to 8, It works!


text:
Q: Why text is not formatted with Html.fromHTML? I'm trying to display html code in text view. I want to display this:

I'm using this page to generate this code: http://tohtml.com/java/
HTML:

public class MainActivity extends Activity {

     // Called when activity is created
     @Override
     protected void onCreate(Bundle savedInstanceState)
     {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
     }
}

I'm tried this:
TextView textView; // my text view
String data = loadDataAsString("/sdcard/code.html"); // my function which loads data from file and returning it as String.
textView.setText(Html.fromHTML(data), TextView.BufferType.SPANNABLE);

And i'm getting this as result:

How can I fix it?
I don't want to use WebView.
I'm using API 19 (Android 4.4.4 - KitKat)

A: Html.fromHtml() supports only a subset of HTML tags. This list is a bit out of date, but it will give you the idea of what you can and cannot use. You would need to alter your HTML to abide by the HTML elements that fromHtml() can work with.
Alternatively:

*

*Use a WebView instead of a TextView, or

*Use a different HTML->Spanned parser, like my SpannableStringGenerator, if it works with HTML that is more to your liking


text:
Q: SQL Query Get the Next ID I am working on a problem where I need to get the next available Category for a gamer. If the gamer has reached the final Category (Shooter in below image) then I will need to go back to the start of the table and go to the next one available.
Below is a list of Category:

Below is a list of gamers and what their last Category_ID was:

Finally, below is the data I will be using to work with

Now I need to find the next Category_ID for each gamer using the data table. If a Gamer has reached the last Category_ID (ID 4 in this case and Gamer C) then it will reset back to top like 1 however Gamer C will pick Category 2 as there is no one for that Gamer.
How can I pick the next Category available using the data table for each gamer while keeping in mind of resetting back to top if reached end?
Below is a code example of the problem:
DECLARE @Category AS TABLE
(
    Category_ID INT IDENTITY(1,1) ,
    Description VARCHAR(255)
)

INSERT INTO @Category
VALUES('Sports'), ('Adventure'), ('Action'), ('Shooter')

DECLARE @Gamer AS TABLE
(
    Username VARCHAR(255) ,
    Last_Category_ID INT
)

INSERT INTO @Gamer
VALUES('Gamer A', 1), ('Gamer B', 2), ('Gamer C', 4), ('Gamer D', 3)

DECLARE @Data AS TABLE
(
    Username VARCHAR(255) ,
    Play_At DATETIME ,
    Category_ID INT
)
INSERT INTO @Data
VALUES('Gamer A', GETDATE() -1, 1), ('Gamer B', GETDATE() -1, 2), ('Gamer A', GETDATE() -1, 3), ('Gamer D', GETDATE() -1, 3), ('Gamer C', GETDATE() -1, 2)

SELECT * FROM @Category
SELECT * FROM @Gamer
SELECT * FROM @Data

A: If I understand correctly, you want the next unused category id for each gamer.  And then to start over when all are done.
Here is an approach:

*

*For each gamer, get the maximum current category.

*For each category, get the next category.

*Get the first category as well.

*When there is no next category use the first.

This is a good opportunity to use lateral joins:
select g.*, coalesce(cn.category_id, cf.category_id)
from @gamers g outer apply
     (select max(category_id) as max_category_id
      from @data d
      where d.username = g.username
     ) c outer apply
     (select top (1) cn.category_id
      from @categories cn
      where cn.categoryid > c.max_categoryid
     ) cn cross join
     (select min(cf.category_id) as categoryi_d
      from @categories cf
     ) cf;

Here is a db<>fiddle.

A: I'm not 100% clear on if your @Data table represents the starting category however this might be what you need, if not by all means please clarify with some clear expected results for the sample data.
Using an apply to determine the starting category for each user (if indeed that's what your description entails) and another to get the maximum possible category, select the username and, using a case expression, the corresponding next category name or the starting category if it's already the max category.
select
    Username,
    (   select description
        from @category c
        where c.category_Id=case when Last_Category_ID<m.Id then Last_Category_ID + 1 else startcat.Id end
    ) NextCategory
from @gamer g
outer apply (
    select min(category_id) Id
    from @data d
    where d.username=g.Username
)startcat
outer apply (
    select Max(category_Id) Id
    from @category
)m


text:
Q: Unexpected error with aggregate query to Azure Cosmos DB via MongoAPI I've noticed that aggregate query fails on my db:
{
  "aggregate" : "visitors",
  "pipeline" : [
     { "$match" : { "project" : "E2E120AF-AC50-4969-9DA1-CFA1E31D7E17", "data.lastVisit" : { "$gt" : ISODate("2018-02-07T17:00:00Z") } } },
     { "$group" : { "_id" : { "$hour" : "$data.lastVisit" }, "count" : { "$sum" : 1 } } }
   ]
}

I tried this both from MongoChef and .Net client app and everywhere I get unexpected error as a result:
{{ "_t" : "OKMongoResponse", "ok" : 0, "code" : 1, "errmsg" : "unexpected error occured while processing the request", "$err" : "unexpected error occured while processing the request" }}

If I use other date expression operator like $dayOfYear, it fails as well. If I do grouping by data.lastVisit without any date expression it works fine. Of course same query works smoothly on real MongoDB.
Documents structure in visitors collection is like this:
{
    "project" : "E2E120AF-AC50-4969-9DA1-CFA1E31D7E17",
    "data" : {
        "defaultName" : true,
        "name" : "...",
        "geo" : {
            ...
        },
        "firstVisit" : ISODate("2018-02-21T09:10:06.464+0000"),
        "ip" : "....",
        "lastVisit" : ISODate("2018-02-21T09:10:08.582+0000")
    },
    "_id" : ObjectId("5a8d376ef72db1002b9c591a"),
    "sockets" : [
    ],
    "isBlacklisted" : false,
    "online" : true
}

I believe it's an issue in Cosmos DB realization of aggregate pipeline, so any workarounds and information on how to file a Cosmos DB issue would be helpful

A: Ok, I've managed to find a workaround for that which is one have to simply add the field to grouping _id:
{ "$group" : { "_id" : { time: { "$hour" : "$data.lastVisit" } }, "count" : { "$sum" : 1 } } }

But the error is still there and it's definitely an issue.


text:
Q: Word2Vec Sentiment Classification with R and H2O I am trying to build a sentiment classification model with R and H2O.
I have a data file with the format:
  +-----------+------------------------------------------------------+
| Sentiment | Text                                                 |
+-----------+------------------------------------------------------+
| 1         | This is a sample text. This is another sentence.     |
+-----------+------------------------------------------------------+
| 0         | Another sentence. And another!                       |
+-----------+------------------------------------------------------+
| -1        | Text text and Text! Text everywhere! So much text... |
+-----------+------------------------------------------------------+

So the sentiment values a 1, 0 and -1 and the text in each row can consist of several sentences.
I know want to prepare the dataset to use it with the deeplearning function of h2o. Therefore I wanted to use the tmcn.word2vec R package. But I can not transform it row-wise with this package. I could just get the whole text column and transform it in a word2vec document, but then my sentiment information would be lost.
Is there another way to translate the text into numerical input for a deeplearning function in R? Especially for H2O?
Best regards

A: https://www.kaggle.com/c/word2vec-nlp-tutorial/details/part-3-more-fun-with-word-vectors
The above Kaggle article explains few ways to overcome this challenge (but, in Python). There are,

*

*Vector averaging (as mentioned by Avni)

*Clustering

*Paragraph Vector Check this paper
I think the ideas might help.

A: So there are a few ways you can go about accomplishing your task of using H2O for this application.
First though, you need to normalize the texts in your dataset.
I'm assuming you are doing some text cleaning / tokenization which will produce a sequence of individual word strings.  Then you are going to run your Word2Vec model on those individual word strings.  Problem is each text document can be N number of words long and so you might want to try averaging the word2vec vectors for a given string.
So in your above example on sentence2:
v(another) + v(sentence) + v(and) + v(another) / 4 (individual words)
This would produce an average vector of X features long for each individual text document.
After which you can use our h2o.cbind() function in R.
So partition your dataset into 2 data frames whereby frame 1 is just the sentiment of a document (-1, 0, 1) and the next data frame is the tweets ('Another sentence. And another').  Run the above steps on the tweet dataframe and then cbind the two.
Be sure to pass both data frames into h2o BEFORE using our h2o.cbind() command however and then you should be ready to run our h2o.deeplearning() model on your dataset!
Good luck!

A: I have used rword2vec package instead of tmcn.word2vec.
To train wordvec model, there should not be any punctuation marks and all words should be lowercase for better results
train=data$Text
train=tolower(train)
train=gsub("[[:punct:]]", "", train)
write(train,"text_data.txt")

Now train word2vec model on this text file.
Output file can be .txt or .bin.
Pro of .txt output file: you can easily change or do operations on word vectors.
Con of .txt output file: you cannot use other rword2vec functions(distance,analogy) on .txt file.
To train word2vec model:
model=word2vec(train_file = "text_data.txt",output_file ="model1.bin",layer1_size = 300,min_count = 40,num_threads = 4,window = 10,sample = 0.001,binary=1)

To get .txt file from the binary output file:
bin_to_txt("model1.bin","model1text.txt")

We need "model1text.txt" to create training dataset. There are two popular ways to create training dataset:

*

*Vector Averaging (for each row create a feature vector, by taking average of all word vectors present in that row)

*Bag of Centroids (cluster word vocabulary and then create bag of centroids as similar to bag of words)

For more info, check out this tutorial series:
I have built a sentiment classification model using above methods for kaggle's bag of words meets bag of popcorn(Github Repo link). You can use this code to get training dataset for your text data by making some necessary changes.
Finally, train this on the training dataset using h2o or any othe machine learning algorithm to get sentiment classification model.


text:
Q: Storing multiple images in mysql I'll rephrase my question.
My problem is not storing only images.. but storing multiple images alongside with text, description, etc.. I researched all over stack overflow finding for the answer but most of what I found was answers related to storing images only. I would like to find how can I insert multiple data(name, image, description) at the same time.
The only part I am having difficulty is the multiple image part.
Also, my form is dynamically generated using jquery.
my db structure would be like
id | name | image | description | price
This is my HTML:
<input type="text" class="form-control" name="item[]" placeholder="Name of Item" />
<input type="text" class="form-control" name="desc[]" placeholder="Description" />
<input type="text" class="form-control" name="price[]" placeholder="Price" />
<input type="text" class="form-control" name="brand[]" placeholder="Brand" />
<input type="file" name="images" class="form-control" />
<input type="submit" id="save-product" class="btn btn-success" name="submit" value="Submit">

This is my PHP:
if(isset($_POST['submit']) ){
$name = $_FILES['images']['name'];
$type = $_FILES['images']['type'];
$size = $_FILES['images']['size'];
$temp = $_FILES['images']['tmp_name'];
$error = $_FILES['images']['error'];
$allowed = array(
    "image/jpeg",
    "image/jpg",
    "image/png");
$con = mysqli_connect("localhost","root", "", "db_elective");
if(in_array($type, $allowed) && $size < 2000000 && !empty($_POST['item'])){
    $ext = end(explode(".", $name));
    $newFilename = sha1(date("Y-m-d h:i:s")) . "." . $ext;
    if(move_uploaded_file($temp, "../uploaded" . $newFilename)){

        $item = $_POST['item'];
        $desc = $_POST['desc'];
        $price = $_POST['price'];
        $brand = $_POST['brand'];
        $image = $newFilename;

        for($x = 0; $x < count($item); $x++){
            $vItem = $item[$x];
            $vdesc = $desc[$x];
            $vbrand = $brand[$x];
            $vImg = $image[$x];
            $vprice = $price[$x];
            mysqli_query($con, "INSERT INTO tb_items (product_name, product_desc, product_img, product_brand, price)
                VALUES('$vItem','$vdesc', '$vImg', '$vbrand', '$vprice')");
        }

    }

}else{
    echo "Wrong";
}

}

A: firstly change your form if you are taking multiple images at same time, --
<input type="file" name="images[]" class="form-control" />
<input type="file" name="images[]" class="form-control" />

and then you can take multiple images at same time --
and then process the images using foreach loop --i.e. to say just by uploading one by one and inserting a new record for each one.

A: You can use PHP's array notation as you would in regular form fields:
Image 1:  <input type="file" name="images[]" class="form-control" />
Image 2:  <input type="file" name="images[]" class="form-control" />


text:
Q: i need to implement some mouse/flash animation object interactivity, can anyone please help? Sorry if this is a bit longwinded. I need to model a couple of 3d objects in a separate 3d application, then animate them, import these animations into flash cs3 and then trigger these animations with a mouse. So, for example, a box object will open up when the mouse goes over it (the animation will be triggered by the mouse).
Also, and more complicatedly, I need another object to rotate in the direction the mouse is swiped over it. I figured I'd create about 16 different looping animations in the 3d application, and depending on what direction the cursor moves over the object in flash, it would trigger that particular animation.
As you can probably tell, I'm an animator and don't have a clue about actionscript, if anyone has any advice, I'd hugely appreciate it.
Thanks.

A: Well, I'm not sure if there is a shortcut to this question, I guess you need to lookup mouse events and function calls. I'm not sure how much you know about actionscript 3 but for the clicking part you will need something like this:
this.addEventListener(MouseEvent.CLICK, onMouseClick);

This means when you click the mouse the function "onMouseClick" will be called.
private function onMouseClick(e:MouseEvent):void
{
   theNameOfYourAnimationMovieClipInstance.gotoAndPlay("theNameOfTheLabelToPlay");
}

That might not be much but I think you need to specify your question if you want complete solutions. Hope it helps a bit.

A: I don't know that you're going to find anyone able to step you through something like this, it's kind of complex.
A good place to start might be here: http://gotoandlearn.com/play.php?id=106 Lee walks you through importing a Collada file into Flash and playing with it. You're going to need a third-party 3D library like Papervision or Away 3D. Depending on your requirements, you may want to dive into the new Molehill APIs - it's still in beta, but it'll give you hardware accelerated 3D and much better performance in flash than anything that's out there now.
Sorry, I know that's not necessarily what you're looking to hear - but this is a really complex subject with any number of ways to achieve your goals, and any number of ways to completely screw it up.
Here, we can help with specific questions or like I've tried to do we can point you into general directions - but it's very difficult to helpfully answer a question like this.
I hope I've given you enough to dive into. Good luck!


text:
Q: Authenticate and register a user by additional fields in Symfony 2 I have Symfony 2.3 project. FOS User Bundle and Sonata User Bundle installed.
Now I need to login a user not only by user name and password but by a card number and PIN code.
A user can have only one card but the card could be connected with several users.
And the algorithm is when a user has entered his user name, password, card number and PIN I should check all the data and if there are the user with the card in the DB he is logging in. But if there card info is valid but the entered user data is invalid I should register the new user with the user name and password in the DB and log in him right away.
I've created the Card Entity with the two fields and relation with User entity. The User entity was extended from Sonata User Bundle.
This is the Card entity code:
namespace Acme\BoardBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;
use Acme\UserBundle\Entity\User as User;

/**
 * @ORM\Entity
 * @ORM\Table(name="yam_card")
 */
class Card
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank()
     * @Assert\Length(min = "6")
     * @Assert\Length(max = "6")
     */
    protected $number;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank()
     * @Assert\Length(min = "4")
     * @Assert\Length(max = "4")
     */
    protected $pin;

    /**
     * @ORM\OneToMany(targetEntity="Acme\UserBundle\Entity\User", mappedBy="card", cascade={"remove"})
     */
    protected $users;

    public function __toString()
    {
      return (string)$this->number;
    }

    public function __construct()
    {
        $this->users = new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set number
     *
     * @param string $number
     */
    public function setNumber($number)
    {
        $this->number = $number;
    }

    /**
     * Get number
     *
     * @return string
     */
    public function getNumber()
    {
        return $this->number;
    }

    /**
     * Set pin
     *
     * @param string $pin
     */
    public function setPin($pin)
    {
        $this->pin = $pin;
    }

    /**
     * Get pin
     *
     * @return string
     */
    public function getPin()
    {
        return $this->pin;
    }

    /**
     * Add users
     *
     * @param \Acme\UserBundle\Entity\User $users
     * @return Card
     */
    public function addUser(\Acme\UserBundle\Entity\User $users)
    {
        $this->users[] = $users;

        return $this;
    }

    /**
     * Remove users
     *
     * @param \Acme\UserBundle\Entity\User $users
     */
    public function removeUser(\Acme\UserBundle\Entity\User $users)
    {
        $this->users->removeElement($users);
    }

    /**
     * Get users
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getUsers()
    {
        return $this->users;
    }
}

And a peace of code of the User entity with the relation:
namespace Acme\UserBundle\Entity;

use Sonata\UserBundle\Entity\BaseUser as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use \Acme\BoardBundle\Entity\Card;

/**
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks
 * @ORM\Table(name="fos_user")
 */
class User extends BaseUser
{
    ...

    protected $card;

    /**
     * Set card
     *
     * @param \Acme\BoardBundle\Entity\Card $card
     * @return Card
     */
    public function setCard(\Acme\BoardBundle\Entity\Card $card)
    {
        $this->card = $card;

        return $this;
    }

    /**
     * Get card
     *
     * @return \Acme\BoardBundle\Entity\Card
     */
    public function getCard()
    {
        return $this->card;
    }
}

User.orm.xml:
<?xml version="1.0" encoding="UTF-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
                  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                  xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping
                  http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">

    <entity name="Acme\UserBundle\Entity\User" table="fos_user">

        ...

        <many-to-one field="card" target-entity="Acme\BoardBundle\Entity\Card" inversed-by="users">
            <join-column name="card" referenced-column-name="id" />
        </many-to-one>
    </entity>
</doctrine-mapping>

The question is what class (or interface) should I redefine to add the check for the two additional parameters (card number and PIN) and how can I make it?
I've found the UserProvider class which implements UserProviderInterface. But the class has loadUserByUsername() method which loads user by user name and works with the user object already.
The class doesn't receive a responce object from where I can get the card number and PIN code from the login form.
Also I've found a solution for checking additional user status parameter by extending UserChecker class from Symfony Security Core. There checkPreAuth and checkPostAuth methods was used but there I can also work with the User object only.
So I guess that I should use some listener or something like that to check the receiving user name, password, card number and PIN code from the request on equality with the users which was registered in my DB.
But I can't find the entering point.

A: You can manually login a use once you are sure the passed Card is valid and belongs to that User. Make sure you trigger an InteractiveLoginEvent to let all listeners know the login happened:
    // 'main' is the name of the firewall to login to
    $token = new UsernamePasswordToken($validatedCard->getUser(), null, 'main', $validatedCard->getUser()->getRoles());
    $this->get('security.token_storage')->setToken($token);

    // Notify the dispatcher, so LoginListener is triggered
    $loginEvent = new InteractiveLoginEvent($request, $token);
    $this->get('event_dispatcher')->dispatch(SecurityEvents::INTERACTIVE_LOGIN, $loginEvent);


text:
Q: pip stopped working after upgrading anaconda v4.4 to v5.0 I ran the command conda update anaconda to update anaconda v4.4 to v5.0
After anaconda was successfully upgraded to v5.0, I had problems running pip.
This is the error output I see after running pip;
Traceback (most recent call last):
  File "C:\ProgramData\Anaconda3\Scripts\pip-script.py", line 6, in <module>
    from pip import main
  File "C:\ProgramData\Anaconda3\lib\site-packages\pip\__init__.py", line 28, in <module>
    from pip.vcs import git, mercurial, subversion, bazaar  # noqa
  File "C:\ProgramData\Anaconda3\lib\site-packages\pip\vcs\mercurial.py", line 9, in <module>
    from pip.download import path_to_url
  File "C:\ProgramData\Anaconda3\lib\site-packages\pip\download.py", line 41, in <module>
    from pip._vendor.requests.adapters import BaseAdapter, HTTPAdapter
ModuleNotFoundError: No module named 'pip._vendor.requests.adapters'

How can I get pip to work again? I am using Windows10, 64-bit python v3.6 anaconda v5.0

A: This occurs when broken pip. The broken pip caused by the failed upgrade can be fixed by running:
!easy_install pip

A: Had the same problem fixed by renaming the directory:
%USERPROFILE%\Anaconda3\Lib\site-packages\pip
then running conda install --force-reinstall pip
(Then I guess it's safe to remove the renamed directory)

A: I will answer my own question.
The problem was fixed by uninstalling anaconda and doing a fresh re-install from the windows installation executable.
Based on this link https://github.com/pypa/pip/issues/2345, it seems something went wrong with the installation but the problem cannot be reproduced. I do not know what exactly what wrong with conda update anaconda.


text:
Q: Tunnel into multiple servers and establish port link I have create port link in my local system for a database for accessing it.
Working Case: When I have only one server as proxy I use.
ssh -L 5433:rds-server:5432
Using this syntax I am able to connect to the rds-server:5432 from my local using: jdbc:postgresql://localhost:5433/reports
Need help Case: When I have two servers as proxy
I have to ssh into proxy-server1 and from there ssh into proxy-server2 and access the rds-server:5432. I need a command so that I can tunnel two servers and create a link to the rds-server:5432 to my localhost:5433.

A: I expect you use key authentication:
Just run
ssh -L 5433:rds-server:5432 'ssh -L 5433:rds-server2:5432'

The server you connect to firstly will automatically run the command inside ''.
See here: https://linux.die.net/man/1/ssh


text:
Q: Angular 5 - How to use HTTPRespose.blob()? In Angular 4 , I used to download any excel or pdf file as a blob by making a http get or post call via the angular 4 http library .
My code in Angular 4 used to look like this :
import { Http, Response, Headers, RequestOptions,ResponseContentType   } from '@angular/http';
...................................

getExcelOrPDF(URL: string) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json' );
    return this.http.get(URL, {headers: headers, responseType: ResponseContentType.Blob
  }).map(response => this.getData(response)) .catch(error => this.handleError(error));
}

public getData(res: Response) {
    console.log("getData()---Enter");
    let headers = res.headers;
    let contentType = headers.get('Content-Type');
    var blob;
    try {
        if(contentType === 'pdf' || contentType === 'application/pdf') {
            blob = new Blob([res.blob()], { type: "application/pdf"});
        } else {
            blob = new Blob([res.blob()], { type: "application/vnd.ms-excel"});
        }
    }
    catch (e) {
        console.debug(e);
    }
    console.log("getData()-Exit");
    return blob;
}

Now , we all know that in Angular 5 , we have support for HTTPClient Module and HTTPClient and I am trying to move away from angular 4 way of getting data . So , I have imported the HTTPClient, HTTPResponse etc.
My code in Angular 5 looks like this :
import { HttpClient, HttpResponse , HttpHeaders} from '@angular/common/http';
...................................

getExcelOrPDF(URL: string) {
    let headers = new HttpHeaders();
    headers.append('Content-Type', 'application/json' );
    return this.http.get(URL, {headers : headers, responseType: 'blob' as 'json'
 }).map(response => this.getData(response)) .catch(error => this.handleError(error));
}

public getData(res: HttpResponse<any>) {
    console.log("getData()---Enter");
    let headers = res.headers;
    let contentType = headers.get('Content-Type');
    var blob;
    try {
        if(contentType === 'pdf' || contentType === 'application/pdf') {
            blob = new Blob([res.blob()], { type: "application/pdf"});
        } else {
            blob = new Blob([res.blob()], { type: "application/vnd.ms-excel"});
        }
    }
    catch (e) {
        console.debug(e);
    }
    console.log("getData()-Exit");
    return blob;
}

However , where the angular 4 code runs flawlessly, the above code in angular 5 gives me a couple of errors :

*

*res.blob() --> Using HTTPResponse , I get the error : blob() function is not supported . This is an error that I get to see in
the editor itself .

*When the code is run , it compiles successfully , but when I try to
download the excel , I get the error: unsupported media type : 415

*I checked using console.logs , but it seems the function getData() is
not even being called as the console logs are not getting printed .

Can some one please let me know as to what I am doing wrong here ? Any help is deeply appreciated .

A: I had committed a silly mistake , due to which I was facing a lot of issues .
Firstly : When we are using HTTPClient instead of HTTP, we should create the headers like this :
let headers = new HttpHeaders();
headers  = headers.append('Content-Type', 'application/json' );

headers object is required to be assigned back to headers otherwise the actual headers object will be empty.
Secondly: make the http call like this : this.http.get(URL, {headers : headers, observe: 'response', responseType: 'blob'}
Thirdly : res.blob() is not available in HTTPResponse . Instead we should use : res.body
After going through hundreds of documentation and articles in the internet and countless trial and error  , I was able to come up with a satisfactory solution .
Hopefully this helps anybody else who is going through a similar issue .


text:
Q: Error al "pip install robotframework-selenium2library==1.8.0" para instalar la ultima versión de seleniumlibrary2 me da un error, ya segui todos los pasos de:
https://github.com/robotframework/SeleniumLibrary/
Adjunto pantallazo del error

Alguien me puede ayudar? Muchas gracias

A: El problema es de compatibilidad

Selenium2Library 1.8 supports Python 2.6-2.7.

Fuente Selenium2Library, también lo dicen en este Issue.
Y según veo en la captura de pantalla usted usa Python 3, ¡¿cierto?!
¿Por qué no intenta pip install --upgrade robotframework-selenium2library?

El comando anterior instala SeleniumLibrary, así como una
nueva versión de Selenium2Library que es solo un wrapper
para SeleniumLibrary. Eso permite importar Selenium2Library en pruebas
mientras se migra a SeleniumLibrary.

A partir de la versión 3.0, Selenium2Library pasa a llamarse
SeleniumLibrary y este proyecto (Selenium2Library) existe principalmente para ayudar con
la transición.


text:
Q: Custom Post Type Video - Online/Offline I have created a custom post type which will store posts that contain videos, i have made use of the ACF wysiwyg field to display the video content and i have a further true/false field which will enable/disable the video. Basically if it is enabled, it will display the video on the page and if it is disabled then it won't display on the page.
Now for the tricky part, when a video is disabled i need to either rename the file on the server or move it to a temporary location. If there are other options, i am open to ideas. The requirement for this is so that they can have control of when the video is viewed.
If the video is shared on Facebook, you would normally be able to still view that video regardless because it would still exist on the server, however we need to be able to control that. If i share a video today and disable it tomorrow, no one else clicking on the link for that video should be able to view it until it is enabled again.
I tried using a rename function but i don't think that is the best way of doing this, as if i enable the video again it would need to have the same name as before it was disabled. Perhaps there is another way of achieving what i need to do?
Video path comes from my ACF field. (The wysiwyg editor)
function jd_video_path($video_path) {
    global $wpdb;

    $video_id = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM " . $wpdb->posts . " WHERE guid='%s';", $video_path ) );

    $post = get_post($video_id);
    $file = get_attached_file($video_id);
    $path = pathinfo($file);

    $new_file_name = "offline";
    $new_file = $path['dirname']."/".$new_file_name.".".$path['extension'];

    rename($file, $newfile);
    update_attached_file( $video_id, $new_file );

    var_dump($path);
}


text:
Q: SKScene presented from another SKScene not able to load from SKS file I have quite a specific problem. I used to be presenting my Game Scene from a view controller with the default code. However I Added another SKScene and am now presenting my game scene from that using this code:
//In an SKScene (not Game scene)
let scene = GameScene()
let skView = self.view!
skView.ignoresSiblingOrder = true
scene.scaleMode = .aspectFit
let push = SKTransition.push(with: SKTransitionDirection.right, duration: 0.4)
skView.presentScene(scene, transition: push)

My problem is that my game scene seems to no longer recognize my SKS file as when I run the line of code:
//in gamescene
sprite = self.childNode(withName: "sprite") as! SKLabelNode

It doesn't find anything when unwrapping.
When I present my SKScene from GameViewController using the code:
if let scene = GKScene(fileNamed: "GameScene") {

        // Get the SKScene from the loaded GKScene
        if let sceneNode = scene.rootNode as! GameScene? {

            // Copy gameplay related content over to the scene
            sceneNode.entities = scene.entities
            sceneNode.graphs = scene.graphs

            // Set the scale mode to scale to fit the window
            sceneNode.scaleMode = .aspectFit

            // Present the scene
            if let view = self.view as! SKView? {
                view.presentScene(sceneNode)

                view.ignoresSiblingOrder = true
            }
        }
    }

Everything works. What am I doing wrong? Thanks in advance.

A: I think the reason that it crashes when you present from within the SKScene, and not from the UIViewController is because of 2 reasons.

*

*You are creating 2 different classes, that would probably have different code. When you present from the SKScene, you create an object of type GameScene but when you present from the UIViewController you create an object of type GKScene.

*When you create the object of type GameScene, you use an initializer that does not take into account the attached SKS File. But when you create the object of type GKScene you do.

Therefore, I would edit the first block of code to be:
//In an SKScene (not Game scene)
if let sceneContainer = GKScene(fileNamed: "GameScene") {
    let skView = self.view!
    skView.ignoresSiblingOrder = true
    //Something comparable to the following line. I don't have a project set up, but let the compiler run you through the exact syntax.
    let scene = sceneContainer.rootNode as! GameScene?
    scene?.scaleMode = .aspectFit
    let push = SKTransition.push(with: SKTransitionDirection.right, duration: 0.4)
    skView.presentScene(scene!, transition: push)
}

The doc for getting the SKScene from a GKScene can be found here.


text:
Q: Save SDL Texture to file I am trying to save a texture to a png and the only thing I'm getting
is a screenshot of a portion of the screen.
my code example:
src_texture =  SDL_CreateTextureFromSurface( renderer, some_surface );
/*.........*/

/*create target texture */
SDL_Texture *tmp_texture = SDL_CreateTexture(renderer, format, SDL_TEXTUREACCESS_TARGET , w, h);
SDL_SetTextureBlendMode(tmp_texture, SDL_BLENDMODE_NONE);
SDL_SetRenderTarget(renderer, tmp_texture);
SDL_RenderCopy(renderer, src_texture, NULL, NULL);

/*create surface and get pixels from texture*/
PixelFormat mask = GetMask(format);
s = SDL_CreateRGBSurface(0, w, h, 32, mask.Rmask, mask.Gmask, mask.Bmask, mask.Amask);
if (s) {
    SDL_SetRenderTarget(renderer, tmp_texture);
    SDL_RenderReadPixels(renderer, NULL, s->format->format, s->pixels, s->pitch);
    IMG_SavePNG(s, "image.png");

}
SDL_DestroyTexture(tmp_texture);

Any idea how to achieve this?

A: Here is my solution:
void save_texture(const char* file_name, SDL_Renderer* renderer, SDL_Texture* texture) {
    SDL_Texture* target = SDL_GetRenderTarget(renderer);
    SDL_SetRenderTarget(renderer, texture);
    int width, height;
    SDL_QueryTexture(texture, NULL, NULL, &width, &height);
    SDL_Surface* surface = SDL_CreateRGBSurface(0, width, height, 32, 0, 0, 0, 0);
    SDL_RenderReadPixels(renderer, NULL, surface->format->format, surface->pixels, surface->pitch);
    IMG_SavePNG(surface, file_name);
    SDL_FreeSurface(surface);
    SDL_SetRenderTarget(renderer, target);
}

This function has no side effects outside of the file write.  This makes it easy to insert as you don't have to worry that the render target will be clobbered.  Feel free to add error handling as you see fit.

A: I was looking for the same thing and was disappointed when I couldn't find a snippet that performed this "simple" task.
So, I went ahead and made one for the next person that wants it. I wouldn't use this in production code, it's just for debugging. Tested in SDL 2.0.7.
What it does
Saves any SDL_Texture to a .bmp file.
Technically, it converts any SDL_Texture into an SDL_Surface, to which it saves as a .bmp.
Example use cases
Particularly well suited for:

*

*Inspecting a large texture atlas that was generated during runtime

*Exploring large generated levels all at once

*Saving a screenshot

*Viewing any generated or composite textures in your favorite image editor

Usage
Pretty straightforward, just pass any SDL_Renderer along with the SDL_Texture you want to save, and a filename to save to.
Also, this will clobber whatever file is there, so be careful.
The code forces everything into an RGBA32 format, though it is simple enough to tweak to whatever format you desire. If you want to, you can load format by passing it's pointer as a parameter to SDL_QueryTexture to auto-detect the format of the input texture and use that for the output file.
Limitations
If you want to enhance this code, here are a few things to consider.

*

*Memory usage: this requires roughly 4x the memory of the texture, or 3x if you are trying to save a texture that is already a renderable target. That may be too much memory, depending on how big your textures are.

*File compression: The image data is stored in a raw format, so there is no compression. This can yield prohibitively large files. If you wanted to use this for screenshots, you probably want to use this raw format as a stepping stone to a png, jpg, or other compressed format.

*Error handling: there isn't much in the way of error handling. You probably want something more robust.

Snippet
/* Usage example */
save_texture(sdlttyDisplay->ren, sdlttyDisplay->font_tex, "image.bmp");

void save_texture(SDL_Renderer *ren, SDL_Texture *tex, const char *filename)
{
    SDL_Texture *ren_tex;
    SDL_Surface *surf;
    int st;
    int w;
    int h;
    int format;
    void *pixels;

    pixels  = NULL;
    surf    = NULL;
    ren_tex = NULL;
    format  = SDL_PIXELFORMAT_RGBA32;

    /* Get information about texture we want to save */
    st = SDL_QueryTexture(tex, NULL, NULL, &w, &h);
    if (st != 0) {
        SDL_Log("Failed querying texture: %s\n", SDL_GetError());
        goto cleanup;
    }

    ren_tex = SDL_CreateTexture(ren, format, SDL_TEXTUREACCESS_TARGET, w, h);
    if (!ren_tex) {
        SDL_Log("Failed creating render texture: %s\n", SDL_GetError());
        goto cleanup;
    }

    /*
     * Initialize our canvas, then copy texture to a target whose pixel data we
     * can access
     */
    st = SDL_SetRenderTarget(ren, ren_tex);
    if (st != 0) {
        SDL_Log("Failed setting render target: %s\n", SDL_GetError());
        goto cleanup;
    }

    SDL_SetRenderDrawColor(ren, 0x00, 0x00, 0x00, 0x00);
    SDL_RenderClear(ren);

    st = SDL_RenderCopy(ren, tex, NULL, NULL);
    if (st != 0) {
        SDL_Log("Failed copying texture data: %s\n", SDL_GetError());
        goto cleanup;
    }

    /* Create buffer to hold texture data and load it */
    pixels = malloc(w * h * SDL_BYTESPERPIXEL(format));
    if (!pixels) {
        SDL_Log("Failed allocating memory\n");
        goto cleanup;
    }

    st = SDL_RenderReadPixels(ren, NULL, format, pixels, w * SDL_BYTESPERPIXEL(format));
    if (st != 0) {
        SDL_Log("Failed reading pixel data: %s\n", SDL_GetError());
        goto cleanup;
    }

    /* Copy pixel data over to surface */
    surf = SDL_CreateRGBSurfaceWithFormatFrom(pixels, w, h, SDL_BITSPERPIXEL(format), w * SDL_BYTESPERPIXEL(format), format);
    if (!surf) {
        SDL_Log("Failed creating new surface: %s\n", SDL_GetError());
        goto cleanup;
    }

    /* Save result to an image */
    st = SDL_SaveBMP(surf, filename);
    if (st != 0) {
        SDL_Log("Failed saving image: %s\n", SDL_GetError());
        goto cleanup;
    }

    SDL_Log("Saved texture as BMP to \"%s\"\n", filename);

cleanup:
    SDL_FreeSurface(surf);
    free(pixels);
    SDL_DestroyTexture(ren_tex);
}

A: For saving part of screen into file, better create RGBSurface:
SDL_Surface *ss = SDL_CreateRGBSurface(0, w, h, 32, 0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000);

Here is SDL_CreateRGBSurface documentation
Next step is the same as in your code - use SDL_RenderReadPixels with correct color format.
When you got this, you can simply save with SDL_SaveBMP or other functions.

A: Have you managed to solve this? Using your code my program crashes on the SDL_RenderReadPixels() call.
If you change the texture to be SDL_TEXTUREACCESS_STREAMING you can capture it correctly with the above method, but note that only in the resolution of the actual renderer. If the texture is bigger, it will be cut off.


text:
Q: storing values from html to mysql via django i want to send data to my mysql db via django. When i run server i dont get any error. When i submit form from hello.html, the values arent stored in my db. in DB i got table hello_cont
hello.html
   {% block content %}
    <form action="/polls/" method="POST"> {% csrf_token %}
      <input class="form-control" id="name" name="name" placeholder="Name" type="text" required>

      <input class="form-control" id="email" name="email" placeholder="Email" type="email" required>

  <textarea class="form-control" id="comments" name="comments" placeholder="Comment" rows="5"></textarea>

      <button class="btn btn-default pull-right" type="submit">Send</button>
    </form>

{% endblock %}
models.py
from __future__ import unicode_literals
from django.db import models

class cont(models.Model):
    name = models.CharField(max_length=10)
    email = models.CharField(max_length=10)
    comments= models.CharField(max_length=250)

def __str__(self):

        return self.name

forms.py
from django import forms
from .models import cont

class PostForm(forms.ModelForm):

    class Meta:
        model = cont
        fields = ('name', 'email', 'comments')

view.py
    from django.utils import timezone
    from django.shortcuts import render
    from django.http import HttpResponseRedirect
    from .models import cont
    from .forms import PostForm

    def hello(request):
            return render(request, 'polls/hello.html')
    def post_new(request):
        if request.method == "POST":
            form = PostForm(request.POST)
            if form.is_valid():
                post = form.save(commit=False)
                post.name = request.user
                post.email = request.email
                post.comments = request.comments
                post.save()
    else:
            form = PostForm()
        return render(request, 'blog/post_edit.html', {'form': form

})

polls/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
    url(r'^$', views.post_list, name='post_list'),
    url(r'^post/(?P<pk>\d+)/$', views.post_detail, name='post_detail'),
    url(r'^post/new/$', views.post_new, name='post_new'),
]

urls.py
from django.conf.urls import include, url
from django.contrib import admin
from polls.views import hello
urlpatterns = [
    url(r'^admin/', admin.site.urls),
 url(r'', include('polls.urls')),

]


text:
Q: Is it possible to share multiple files with Web Share Target API? Is it possible to share multiple files using Web Share Target API?
I can select multiple pictures in Google Photos, hit Share, then select my PWA. But only one of the selected files is sent to the share_target URL given in the manifest.json.
This is odd. Did I missed something?
Thanks!

A: It is, yes.
In your Web App Manifest, use something like this:
"share_target": {
  "action": "/_share-target",
  "enctype": "multipart/form-data",
  "method": "POST",
  "params": {
    "files": [{
      "name": "media",
      "accept": ["image/*"]
    }]
  }
}

In your service worker that handles incoming POST requests for /_share-target/, do something like this:
const formData = await event.request.formData();
const mediaFiles = formData.getAll('media');

for (const mediaFile of mediaFiles) {
  // Do something with each mediaFile
}

There's a deployed example of this code "in action" at https://scrapbook-pwa.web.app/


text:
Q: How to convert timestamp to the number of days Supposing I have a timestamp 123456. How to convert to the number of days (day count). For example: if 123 -> 1 days, then 122 -> 0 day.
My query has this:
something_to_get_the_number_of_day(TIMESTAMP(NOW()) - TIMESTAMP('2011-12-13 14:00:00'))

A: You can use the DATEDIFF() function which will give you the difference in days.
You can use something like:
DATEDIFF(TIMESTAMP(NOW()), TIMESTAMP('2011-12-13 14:00:00')) AS DiffDate

That should give you the result you want.
Here's a w3schools link on the DATEDIFF() function
Edit: From your comment, I now see you want to include the actual time too.
You should be able to use TIMESTAMPDIFF() instead then (providing you are using mySQL 5.0.0+)
http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_timestampdiff