text:
Q: Initializing Hashtables in Java? In C# you can initialize Hashtables (and many other types of objects) using code like this -
Hashtable table = new Hashtable {{1, 1}, {2, 2}};

Is there anything like this in Java or do you have to just declare the Hashtable first and then manually put items in it one by one?

A: In Google Guava, if you want an immutable map you can use:
Map<K,V> m = ImmutableMap.of(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5);

up to 5 Key/Value pairs.
Beyond that, you can use their ImmutableMap.Builder class:
ImmutableMap<String, Integer> WORD_TO_INT = ImmutableMap.builder()
       .put("one", 1)
       .put("two", 2)
       .put("three", 3)
       .build();

Still not nearly as nice as in C#, but the fluent API is a bit helpful.

A: This is answered elsewhere but you can use an anonymous subclass:
new HashMap<Integer, Integer>() {{ put(1, 1); put(2, 2); }};

Lot's of boiler plate, but still a one-liner :).  This will, unfortunately, also complain about the missing serialVersionUID constant which you can either add or ignore the warning on.
This is called an instance initializer block, more information here.

A: Try this:
Hashtable<Integer, String> ht = new Hashtable<Integer, String>(){
    {
        put(1,"One");
        put(2,"Two");
        put(3,"Three");
    }
};

A: If you need to initialize a HashMap (HashTable is obsolete) you can use an static initialization block.
Example:
private static Map<String, String> map;

static {
    map = new HashMap<String, String>();
    map.put("name1", "value1");
    map.put("name2", "value2");
    ....
}

Hope this helped, have Fun!

A: Another answer (besides the obvious "no -- no native language way to do this"):
Create a Tuple class with a static factory method with a fancy-pants "_" name for brevity:
import java.util.Map;
import java.util.HashMap;

class Tuple<T1,T2> {
    private T1 t1;
    private T2 t2;
    public Tuple(T1 t1, T2 t2) {
         this.t1 = t1; this.t2 = t2;
    }
    public T1 getT1() {return t1;}
    public T2 getT2() {return t2;}

    static public <X,Y> Tuple<X,Y> _(X t1, Y t2) { return new Tuple<X,Y>(t1,t2); }
    static public <X,Y> Map<X,Y> mapFor(Tuple<X,Y>... tuples) {
        Map<X,Y> map = new HashMap<X,Y>();
        for( Tuple<X,Y> tuple: tuples ) {
           map.put(tuple.getT1(), tuple.getT2());
        }
        return map;
    }

    public static void main(String[] args) {
        Map<String,Integer> map = Tuple.mapFor( _("A", 1), _("B", 2), _("C",3));
    }
}

If you want to allow variations on what kind of backing map is produced, you can just pass that in instead:
    static public <X,Y> Map<X,Y> mapFor(Map<X,Y> map, Tuple<X,Y>... tuples) {
        for( Tuple<X,Y> tuple: tuples ) {
           map.put(tuple.getT1(), tuple.getT2());
        }
        return map;
    }

A: There's a thing called double brace initialization, which isn't as nice...
Hashtable table = new Hashtable() {
    {
        table.put(1, 1);
        table.put(2, 2);
    }
};

You could even specify using anonymous array notation, and then iterate over it yourself, like this:
Hashtable table = new Hashtable() {
    {
        for (int[] entry : new int[][] { { 1, 1 }, { 2, 2 } }) {
            table.put(entry[0], entry[1]);
        }
    }
};

Perhaps make a utility function if you're really missing python :)

A: One of C#'s features which I quite like is its ability to initialize inline like that. Unfortunately, Java doesn't have this feature.
The Java Hashtable does not have any constructors which allow for this either. See a list of its constructors in the Java API documentation:
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Hashtable.html

A: A safe approach is to use ImmutableMap.of from Guava and optionally wrapped with newHashSet if mutability is needed:
Maps.newHashMap(ImmutableMap.of(k1, v1, ...));

Here's a self-written map builder for inline use, e.g. newMap(1, "one", 2, "two", 3, "three").
public static <K, V> Map<K, V> newMap(final K key, final V value, final Object... elements) {
    Preconditions.checkNotNull(key);
    Preconditions.checkArgument(elements.length % 2 == 0, "Array length can't be " + elements.length);

    final HashMap<Object, Object> map = Maps.newHashMap();
    map.put(key, value);
    for (int i = 0; i < elements.length; i += 2) {
        map.put(elements[i], elements[i + 1]);
    }
    return (Map<K, V>) map;
}

A: i suggest something like this:
String[] names={"albert","john","michel"};
int[] id={1234,2345,3456};
Hashtable<int,String> persons = new Hashtable<int,String>();

for(int i=0;i<3;i++)
{
 persons.put(id[i],names[i]);
}

A: This is not possible in Java. We all suffer from that.


text:
Q: Change element position inside MovieClip in Event.RESIZE OK I have some little listener.
stage.addEventListener(Event.RESIZE,rozmiar1);
            function rozmiar1(e:Event):void
            {
            ofertaBTN.oCenter.width=(14.59*stage.stageWidth)/100;
            ofertaBTN.oRight.x = ofertaBTN.x+ofertaBTN.oLeft.width +ofertaBTN.Ocenter.width;
            }

But only ofertaBTN.oCenter.width is changing. oRight is not responding and I get error #1010. Could you give me any clue?

A: I think you have written variable name badly: Ocenter instead of oCenter in your second statement

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to tell TS compiler that returned value is not null via custom function not sure if this is available in TS but i am willing to bet there is a way to make this work.
this code:

const someArray: foo[] | null | undefined = [...]

// TS fail: someArray possibly undefined
<MyComponent data={someArray} />

// TS OK
if (someArray) return <MyComponent data={someArray} />

// TS fail: someArray possibly undefined
if (any(someArray)) return <MyComponent data={someArray} />

my func:
export function any(arr: any[] | null | undefined): boolean {
  if (arr && arr.length > 0) {
    return true
  }
  return false
}

question:
is it possible to construct any() (maybe using generic hints) to signal to TS that the checked array is not null/undefined?

A: You're looking for a "type predicate" / type guard.
You can use the is keyword in a function return value to cast the type of the argument in the positive condition.
export function any<T>(arr: any[] | null | undefined): arr is T[] {
  if (arr && arr.length > 0) {
    return true  // if func returns true, then the arg is of type T[]
  }
  return false
}


text:
Q: read one value from read_csv error tst = pd.read_csv('/Users/me/Desktop/stuff/Et2Load.csv', header=0,delimiter="\t", quoting=3)
    print(tst.head(2))  # ok
    #print(tst['date'][0])

I made up this file, one line header 2 lines
3 columns, 2 lines
                               id,date,coldata
0  1,August 18 2016,"With all this stuff going do...
1  2,August 19 2016,this is a great movie. The mu...
i cannot access a specific "cell"
print(tst['date'][0]) error
return self._engine.get_loc(self._maybe_cast_indexer(key))
  File "pandas/index.pyx", line 137, in pandas.index.IndexEngine.get_loc (pandas/index.c:4154)
  File "pandas/index.pyx", line 159, in pandas.index.IndexEngine.get_loc (pandas/index.c:4018)
  File "pandas/hashtable.pyx", line 675, in pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:12368)
  File "pandas/hashtable.pyx", line 683, in pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:12322)
KeyError: 'date'

A: well this is the big secret:
set_index('name the column that going to be used as 'id'')

It was difficult to find this one.


text:
Q: Goroutines not Using Max CPU and Cores I'm realizing my very first Golang application and I'm having some issues on using MAX CPU & Cores when using GoRoutines and I don't really know why.
When using a tool such as htop, CPU isn't used at its max power and only 1..4 threads are active at time. Also, all cores are active but they are around 25%-40% utilization.
I used:
func MaxParallelism() int {
    maxProcs := runtime.GOMAXPROCS(0)
    numCPU := runtime.NumCPU()
    if maxProcs < numCPU {
        return maxProcs
    }
    return numCPU
}

In order to get the number of goroutines to be instantiated.
Here's How I set up the application:
//Common Channel for the goroutines
tasks := make(chan *exec.Cmd, 64)

    //Spawning Max Cores Number goroutines (8)
    var wg sync.WaitGroup
    cores := MaxParallelism()
    for i := 0; i < cores; i++ {
        wg.Add(1)
        go func(num int, w *sync.WaitGroup) {
            defer w.Done()
            var (
                out []byte
                err error
            )
            for cmd := range tasks {
                out, err = cmd.Output()
                if err != nil {
                    fmt.Printf("Can't get stdout:", err)
                }
                . . .
            }
        }(i, &wg)
    }

    //Generate Tasks
    for i := 0; i < 100000; i++ {
      tasks <- exec.Command(cmd1, args...)
      tasks <- exec.Command(cmd2, args...)
    }

close(tasks)
// wait for the workers to finish
wg.Wait()

I share two screenshots of htop while executing the application

I don't know If it May help but I'm launching it through Intellij Idea.
How do I use Max CPU properly and Cores?
Thanks in advance.

A: Goroutines and threads are not the same. Ergo you should not expect any CPU affinity. See more for details here http://tleyden.github.io/blog/2014/10/30/goroutines-vs-threads/.

Here are some of the advantages of Goroutines over threads:

*

*You can run more goroutines on a typical system than you can threads.

*Goroutines have growable segmented stacks.

*Goroutines have a faster startup time than threads.

*Goroutines come with built-in primitives to communicate safely between themselves (channels).

*Goroutines allow you to avoid having to resort to mutex locking when sharing data structures.

*Goroutines are multiplexed onto a small number of OS threads, rather than a 1:1 mapping.

*You can write massively concurrent servers without having to resort to evented programming.

EDIT:
Answer to your question in the comments. There is no definitive answer. As others mentioned, it depends on what your code does. You may never end up using 100% CPU if you, for example, do I/O, which is slow. So no matter how many routines you start, I/O is slow. Contrarily, if your goroutine has a very tight loop doing just some computation then it's likely that 8 goroutines will consume your 8 CPUs completely.

A: After reading around, getting some hints and trying some stuff, it came out that the code was written just fine and there were not real problems caused by it.
Essentially, Go scales pretty good and, the more tasks you generate, the more CPU resources are used.
For instance, setting an higher range on the for, e.g. 1.000.000, makes Go use all the cores available at ~55% of their possibilities.
I hope it will help someone.

A: For the record, here's a code which will likely max out your CPU. I run concurrently 256 routines (#1 routine + those spawned within the for loop).
package main

func main() {
  for i := 0; i < 255; i++ {
    go func() {
      for {}
    }()
  }

  for {}
}

If you execute only one routine (the #1 routine), you'll see only one CPU core is used:
package main

func main() {
  for {}
}

If you execute 2 routines (the #1 routine + the spawned one), you'll see 2 CPU cores are used:
package main

func main() {
  go func(){
    for {}
  }()

  for {}
}

Go scales routines across CPU cores automatically.
Worth noting that go routines are not the same as functions.


text:
Q: F# call .Net Function with generic params - wont compile F# Beginner here, I want to draw a Polygon using ImageSharp. The build fails with:

No overloads match for method 'DrawPolygon'. The available overloads are shown below. error FS0001: This expression was expected to have type 'Image' but here has type 'a * 'b'.

    let renderRect(img:Image<Rgba32>) =

        let points: PointF list = [
            new PointF(float32 2.0, float32 8.0);
            new PointF(float32 4.0, float32 1.0);
            new PointF(float32 1.0, float32 7.0);
            new PointF(float32 5.0, float32 2.0);
        ]

        img.Mutate (fun x -> x.DrawPolygon(Rgba32.White, 1.0, points))
        img

The signature of the method i want to call:
static IImageProcessingContext<TPixel> DrawPolygon<TPixel>(this IImageProcessingContext<TPixel> source, TPixel color, float thickness, params PointF[] points) where TPixel : struct, IPixel<TPixel>

A: I see several issues:

*

*As Aaron said, you're passing a list where an array is required.

*The second argument to DrawPolygon should be a float32, not a float.  Note that rather than calling the float32 function, you can just use a literal of the correct type by adding a suffix: 1.0f.

*The second argument to Mutate needs to be an Action<_>, so it shouldn't return anything; this means you should ignore the result of the DrawPolygon call rather than returning it.  You can achieve this by putting |> ignore after the call.

Here's a version of your code with these issues addressed:
let renderRect(img:Image<Rgba32>) =

    let points = [|
        PointF(2.0f, 8.0f);
        PointF(4.0f, 1.0f);
        PointF(1.0f, 7.0f);
        PointF(5.0f, 2.0f);
    |]

    img.Mutate (fun x -> x.DrawPolygon(Rgba32.White, 1.0f, points) |> ignore)
    img

Since you didn't include a full repro (or even the list of suggested overloads from the error message!) it's hard to know if there's anything else that needs to be changed.

A: You are passing a list of points, but the signature of the method expects an array of points.  I would suggest either passing the points in-line as params, or defining points as an array:
let points =
    [|
        new PointF(float32 2.0, float32 8.0)
        new PointF(float32 4.0, float32 1.0)
        new PointF(float32 1.0, float32 7.0)
        new PointF(float32 5.0, float32 2.0)
    |]


text:
Q: Multiple Domain names, Multiple Certificates, one IIS 7 server I have 1 IIS server that is hosting 3 domains, for example, example1.com, example2.com and example3.com. Each has it's own certificate. How can I install a separate certificate for each of these sites on IIS 7.5 ?
Currently using a UUC certificate with multiple domains on it is not an option.

A: Just install them and select "SNI" (Server Name Indication) and enter the hostname.
Edit: SNI is an IIS8 feature. For 7.5 see:
Setup IIS 7.5 with multiple website bindings and SSL?


text:
Q: Getting first element of an IEnumerable item I am returning an IEnumerable<object[]> element from a function that uses yield return in a loop.
public static IEnumerable<object[]> GetData()
{
        ...

        connection.Open();

        using (OleDbDataReader dr = command.ExecuteReader())
        {
            while (dr.Read())
            {
            object[] array = new object[dr.FieldCount];
                dr.GetValues(array);
            yield return array;
            }
        }

        connection.Close();
}

What's the best way to retrieve the first element without using a loop preferably?
var result = Adapter.GetData();

A: In short:
enumerator=result.GetEnumerator();
enumerator.MoveNext();
enumerator.Current;

This is what a foreach does in a loop to iterate through all the elements.
Proper way:
using (IEnumerator<object[]> enumerator = result.GetEnumerator()) {
    if (enumerator.MoveNext()) e = enumerator.Current;

}
With LINQ:
var e = result.First();

or
var e = result.FirstOrDefault(default);

Also:
var e = result.ElementAt(0);

A: If your .Net 3.5 or higher
Adapter.GetData().First()

A: Can't you use result.First()?

A: enumerator=result.GetEnumerator();
enumerator.MoveNext();
enumerator.Current;

A:     public static T FirstOrDefault<T>(this IEnumerable items) where T : class {
        var list = items.OfType<T>();
        if (list!= null) {
            return list.FirstOrDefault();
        }

        return default(T);
    }


text:
Q: How to enable a UIBarItem after checking a TextField is not empty This is my first question in this forum. I would like to know how to enable a UIBarButtonItem only if a UITextField has text in it. I have seen many examples of how to do this in Swift 2 but not Swift 3. This is for a simple app to save some data to core data. I do not have any code to show other then the UIOutlets etc as I am unsure how to check the UITextField for text on the fly.

A: You need to check length of textField.
//MARK: - UITextFieldDelegate

func textFieldDidEndEditing(_ textField: UITextField) {

    if let text = exampleTextFiled.text {
        exampleBarButtonItem.isEnabled = text.characters.count > 0
    }
}

At the top of you controller you need to add UITextFieldDelegate
class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet var exampleTextField: UITextField!
    @IBOutlet var exampleBarButtonItem: UIBarButtonItem!

    // Your code
}

And in the storyboard you can ctrl-drag from textField to controller to add delegate.

A: That's why I don't recommend using Interface Builder and Storyboards, the developer gets "dumbed down".
Anyhow, the algorithm is something like this:
1) Text fields have callback methods or "delegate" methods for text field events like user tapping on the return/done key.
So firstly, you need to tell your text field the delegate is your view controller.
2) You define the necessary UITextField delegate methods (https://developer.apple.com/reference/uikit/uitextfielddelegate)
3) There is a hasText method (newly available for iOS 10+) for UITextField to tell if your text field has any text. If there is, enable the bar button item, otherwise disable it.
You could alternatively use if let optional binding to unwrap your textField.text? property, then check the text.characters.count is greater than 0 like so:
if let text = textField.text {
    navigationItem.rightBarButtonItem?.isEnabled = text.characters.count > 0
}

This is the conventional way of doing it (before iOS 10 if you want to support older iOS version) :D
The code in full is below:
class ViewController: UIViewController, UITextFieldDelegate {
    @IBOutlet var myTextField:UITextField!

    ...

    override func viewDidLoad() {
        super.viewDidLoad()

        // self is referring to this view controller
        ...
        myTextField.returnKeyType = UIReturnKeyType.done
        myTextField.delegate = self
    }

    // UITextField Delegate Methods
    func textFieldDidEndEditing(_ textField: UITextField) {

        // get the navigation bar button (right bar button in my case)
        // and set its "isEnabled" property depending on whether
        // the textField has any text using "hasText" of UITextField
        navigationItem.rightBarButtonItem?.isEnabled = textField.hasText
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {

        hideKeybaord()

        return false
    }

    // UITouches delegate methods for extra user experience polish
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        // hides keyboard when user taps on the background
        hideKeybaord()
    }

    // resusable hideKeyboard method
    func hideKeybaord() {
        myTextField.resignFirstResponder()

        // in case you need to hide all other text fields in the future
        // textField2.resignFirstResponder()
        // textField3.resignFirstResponder()
    }
}

A: Below is the code I implemented to resolve my problem. It does not take into consideration the iOS keyboard. The last function is the @IBAction (Editing Changed) added to the controller (ViewController.swift) from the TextField in the Scene. I right clicked the TextField in the scene selected the Action, Editing Changed and dragged it to the View Controller. Thanks to all for your iuput and code!!
import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

   // Add Outlet
   @IBOutlet weak var tvShowName: UITextField!
   @IBOutlet weak var saveButton: UIBarButtonItem!

   // Add functions

   @IBAction private func saveButton(_ sender: UIBarButtonItem) {

      let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
      let newTVShow = TVShows(context: context)

      newTVShow.name = tvShowName.text

      do {
         try context.save()
         navigationController!.popViewController(animated: true)
      } catch {
         let alert = UIAlertController(title: "Oops!", message: "Failed to save the TV Show", preferredStyle: UIAlertControllerStyle.alert)
         alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
         self.present(alert, animated: true, completion: nil)
      }
   }

   @IBAction private func cancelButton(_ sender: UIBarButtonItem) {
      // Code for cancel
      navigationController!.popViewController(animated: true)
   }

   override func viewDidLoad() {
      super.viewDidLoad()
      saveButton.isEnabled = false
   }

   @IBAction func tvShowTextFieldEditChanged(_ sender: UITextField) {
      if let text = tvShowName.text{
          saveButton.isEnabled = text.characters.count > 0
      }
   }
}


text:
Q: how to save output of for loop in cmd? I am trying to extract packages information from directory .\sam and iterate through all sub directories, some of them is returning packages reference but some is not:
C:\Users\mac\Desktop\sample\sam>for /R /D %s in (*) do \users\mac\desktop\jclassinfo\jclassinfo --packages %s\*.class

I want to add folder names within the loop, then I try:
C:\Users\mac\Desktop\sample\sam>for /R /D %s in (*) do (dir %s /b /s /a:d & \users\mac\desktop\jclassinfo\jclassinfo --packages %s\*.class) >> pack.txt

But the pack.txt looks miserable.
My question is any code can do:

*

*Save output of packages reference by * folder names? (*.txt)

or

*better way printing folder names when jclassinfo returning packages? (if?)


text:
Q: Get video object (or video id) from Facebook timeline post I'm trying to get a Facebook video object from a timeline post :

*

*I'm getting the posts from graph api /me/home

*I can easily get the photo object via the returned object_id

*The problem is there is no object_id value for video post type
{
   "id": "750834774_10152138100019775",
   "from": {
      "id": "750834774",
      "name": "Emilie Volpi"
   },
   "message": "haha le monde qui fait une analyse geopolitique de games of thrones^^ une bonne manière de se remettre à jour pour la nouvelle saison demain !!!!!",
   "picture": "https://fbexternal-a.akamaihd.net/safe_image.php?d=AQCclQTe2bPMIcrY&w=130&h=130&url=http%3A%2F%2Fs2.dmcdn.net%2FEHFV4%2F526x297-mO8.jpg",
   "link": "http://www.dailymotion.com/video/x1lu3ke_game-of-thrones-comprendre-la-crise-a-westeros-en-4-minutes_news",
   "source": "http://www.dailymotion.com/swf/video/x1lu3ke?autoPlay=1",
   "name": "« Game of Thrones » : comprendre la crise à Westeros en 4 minutes",
   "caption": "www.dailymotion.com",
   "description": "Guerre des cinq rois, pression des marcheurs blancs et des sauvageons au nord, retour des dragons à l'est… le Royaume des Sept couronnes est plongée dans une crise politique sanglante depuis plus d'un an. Le Monde vous propose un décryptage de la crise en quatre minutes mais attention… spoilers !",
   "icon": "https://fbstatic-a.akamaihd.net/rsrc.php/v2/yj/r/v2OnaTyTQZE.gif",
   "actions": [
      {
         "name": "Comment",
         "link": "https://www.facebook.com/750834774/posts/10152138100019775"
      },
      {
         "name": "Like",
         "link": "https://www.facebook.com/750834774/posts/10152138100019775"
      }
   ],
   "privacy": {
      "value": ""
   },
   "type": "video",
   "status_type": "shared_story",
   "application": {
   "name": "Links",
   "id": "2309869772"
 },
 "created_time": "2014-04-06T09:39:57+0000",
 "updated_time": "2014-04-06T09:39:57+0000",
 "likes": {
    "data": [
      {
        "id": "1283687218",
        "name": "Max Imus"
      }
    ],
    "paging": {
       "cursors": {
          "after": "MTI4MzY4NzIxOA==",
          "before": "MTI4MzY4NzIxOA=="
       }
    }
  }
},

As you can see there is no video id so I can't get the video
My goal is to retrieve the embed_html from the video object
Please tell me how to do that (graph api or FQL query)

A: I think you can only get the embed_html for videos which are actually hosted on Facebook. The example you're using is hosted on dailymotion and only referenced in the post. That's the main difference.
I guess you could use the following FQL to get the embeddable video url:
select attachment.media.video.source_url from stream where post_id='750834774_10152138100019775'

You can then include it dynmically in your page if you pass the source_url content to an iFrame as src attribute for example


text:
Q: Invoking DAGs in different Amazon (MWAA)Managed workflow for Apache AIrflow environments giving reponse-code 400 Case: trying to invoke dag using another dag.
steps followed as per instructions given on >>
site
my code section:
client = boto3.client('mwaa', region_name='us-east-1')
print('client ',client)
token = client.create_cli_token(Name='s3bucket_name')
print('token ', token)
url = f"https://{token['WebServerHostname']}/aws_mwaa/cli"
print('url  ', url)

headers = {'Authorization': 'Bearer ' + token['CliToken'],
          'Content-Type':'text/plain'}

body = 'trigger_dag tag_dag'
response = requests.post(url, headers=headers, data=body)
print('response: ', response )

the generated url when clicked gives>> following error>
Forbidden
You don't have the permission to access the requested resource. It is either read-protected or not readable by the server.
*
and getting reponse-code 400 in dag's logs:
dags log details:
[2022-04-01, 13:29:07 UTC] {{logging_mixin.py:109}} INFO - yes3
[2022-04-01, 13:29:07 UTC] {{scheduler_dag.py:92}} INFO - 6246fe23e08cc15f124bf737 contains the details of the report
[2022-04-01, 13:29:08 UTC] {{logging_mixin.py:109}} INFO - client  <botocore.client.MWAA object at 0x7fd1ddb5b210>
[2022-04-01, 13:29:08 UTC] {{logging_mixin.py:109}} INFO - token  {'ResponseMetadata': {'RequestId': '6c2185b3-a7ae-45ff-...', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Fri, 01 Apr 2022 13:29:08 GMT', 'content-type': 'application/json', 'content-length': '626', 'connection': 'keep-alive', 'x-amzn-requestid': '6c2185b3-a7ae-...', 'access-control-allow-origin': '', 'access-control-allow-headers': 'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token', 'x-amz-apigw-id': 'P5yl.....MFULw=', 'access-control-allow-methods': 'GET,OPTIONS,POST', 'access-control-expose-headers': 'x-amzn-RequestId,x-amzn-ErrorType', 'x-amzn-trace-id': 'Root=1-62fe24-33837d3'}, 'RetryAttempts': 0}, 'CliToken': 'eyJ0eXAiObzItVktoQ0NaL0FtYXpvbk1XQUEtYWlyZmxvdyJ9.YSqwqR5UPtR42RJLLrfNOAuGB0-ZkkGJkB2sLu_Zyk9YasiSWmAIj_DeHQ2UEYfTIG4lZfrRXvE64JenWTKYGyOV41ji4RmjSPBuShw35eL45UbZb5ugn8xuuaHoaWTHOIzK65VDe0ItP4uPhNpOokNosRqr-vY9XJCPQuJqIw8ntUu3XULwfyVDg7MCj5HeZl0A57JQGBvXP4axQdyVL9KvgM2Iz2cHq9dduG5cTmCjTUKg6yTzms8mcgECXNgucQIAeBlKWG1_PBlh8T8rfCvPOQWGfjTY0NuFlDHOeyjdSOFKYWSrA', 'WebServerHostname': '3f1d37fd90db2f2.c75.us-east-1.airflow.amazonaws.com'}
[2022-04-01, 13:29:08 UTC] {{logging_mixin.py:109}} INFO - url   ``https://3f1d32-3a7fd90db2f2.c75.us-west-1.airflow.amazonaws.com/aws_mwaa/cli
[2022-04-01, 13:29:08 UTC] {{scheduler_dag.py:149}} INFO - starting dag with run_id 6246fe23e08cc15f124bf737
[2022-04-01, 13:29:09 UTC] {{logging_mixin.py:109}} INFO - response:  <Response [400]>
[2022-04-01, 13:29:09 UTC] {{scheduler_dag.py:156}} INFO - requests status 400
[2022-04-01, 13:29:09 UTC] {{python.py:152}} INFO - Done. Returned value was: None
[2022-04-01, 13:29:09 UTC] {{taskinstance.py:1280}} INFO - Marking task as SUCCESS. dag_id=scheduler_dag, task_id=create_runtime_dag, execution_date=20220401T132853, start_date=20220401T132855, end_date=20220401T132909
[2022-04-01, 13:29:09 UTC] {{local_task_job.py:154}} INFO - Task exited with return code 0
[2022-04-01, 13:29:09 UTC] {{local_task_job.py:264}} INFO - 0 downstream tasks scheduled from follow-on schedule check

My Dag is successfully completed but cant send request to another dag as it is giving 400 code
Also refered for error checking :
https://docs.aws.amazon.com/ja_jp/mwaa/latest/API/CommonErrors.html .. but unable to get exact result

locally when I run using >>url = f"http://{config.IPS['AIRFLOW_HOST_IP']}:8080/api/v1/dags/dag_ticket_workflow_new_tests/dagRuns"
this runs perfectly fine.
one dag triggers another dag. as procedure in mwaa is slightly different ,it gettng difficult to reach the results
dag should send successfull request to another dag named: tag_dag
tag_dag should start and run independently.
can someone please help me find solution for this , so I cound send request to another dag.
Thankyou.


text:
Q: how to simplify the following geometric series? so I have the following series:
$$\sum_{i=3}^n 2^{i-1} $$
since it's $2^{i-1}$, I brought down the $2$ and move $1/2$ in front of series. Then
I assumed that I solved the problem with a formula for finite geometric series
so I had it set up as follows: $$\frac{1}{2}\sum_{i=3}^n 2^i = \frac{8(1-2^n)}{1-2} = \frac{1}{2}(2^{n+3} - 8) = 2^{n+2} - 4$$
When I checked the answer it says $2^n - 4$. What did I do wrong?

A: The first two equalities in your displayed expression are incorrect.  That is,
$$\frac{1}{2}\sum_{i=3}^n 2^i \not= \frac{8(1-2^n)}{1-2} \not= \frac{1}{2}(2^{n+3} - 8) = 2^{n+2} - 4$$
The second mistake is a little easier to see because it should have been
$${8(1-2^n)\over1-2}={8(2^n-1)\over2-1}=2^{n+3}-8$$
(which of course is still the wrong answer because of the first mistake).  A better way to proceed would be
$$\begin{align}
{1\over2}\sum_{i=3}^n2^i&={1\over2}(2^3+2^4+\cdots+2^n)\\
&={2^3\over2}(1+2+\cdots+2^{n-3})\\
&=2^2\left({1-2^{n-2}\over1-2}\right)\\
&=2^2(2^{n-2}-1)\\
&=2^n-4
\end{align}$$


text:
Q: Concatenation of Array at Output Verilog Total noob here, just to be clear. Only about a month in to learning Verilog.
So I have some user-defined parameters, and I want to put out a concatenation of all items in an array. For instance, if the array length were static (in this case, an array of 10 12-bit items), I could certainly do something like:
    reg [11:0] array [9:0];
    output <= {array[9],...,array[0]};

But what if the array length is user-defined and therefore not a static value? For instance, if I wanted two outputs like so, with length being a parameter:
    output1 <= array[0];
    output2 <= {array[length-1],...,array[1]};

Been banging my head against this for a minute or two and haven't found anything in my internet searches... Hope I'm being clear enough...

A: Let's say you have the following:
parameter NUM_ITEMS = 10;
parameter LOWER = 1;
parameter UPPER = 9;
reg [11:0] array [NUM_ITEMS-1:0];
reg [12*(NUM_ITEMS-1)-1:0] output;

The following could work:
integer i;
always@(*) begin
    for (i=0; i <= UPPER; i=i+1)
        output[i*12+:12] = array[LOWER+i];
        //alternatively output [12*i+11:12*i] = array[LOWER+i];
end

Your array elements would need to be sequential, though.

A: you could try assigning the array in a loop to the variable output2. You will move across the bits of the output2 variable and assign the value from each element of array into output2. WIDTH_ARRAY is the width of array and has to be a constant.
parameter SZ = 10;
parameter WIDTH_ARRAY = 8;

reg [WIDTH_ARRAY-1:0] a[SZ] = {1,1,1,1,1,1,1,1,1,1}  ;
reg [SZ*WIDTH_ARRAY:0] output2;

output1 <= array[0];
for ( int i = 0 ; i<SZ-1;i++)
   begin
        output2[(i*WIDTH_ARRAY)+:WIDTH_ARRAY] = array[i+1];
   end

You cannot assign array to output2 directly as one is unpacked and other is a packed structure .
+: is called the bit slice operator.  Indexing vectors and arrays with +:


text:
Q: She took the job at her friend's expense - what does this mean? "She took the job at her friend's expense."

*

*Her friend was replaced by her. (It was her friend's job)

*Her friend helped her to get the job.
Which one is correct? Thank you.

A: To answer your question,

Mary took the job at her friend's expense.

could mean your #1 choice, but more likely

1a. Mary and her friend John applied for the same job,
  and they were the top two (or the last two, or the only two)
  candidates (applicants) —
  and there was only one opening (i.e., one position or one job).
  Mary was the employer's first choice, and John was their second.
  Mary took the job, and therefore John was not hired.

It could possibly be some other (but similar) scenario.
No English speaker would use the sentence to mean your #2 choice.

A: at the expense of TFD

Fig. to the detriment of someone or something; to the harm of someone
  or something.

From the sentence: "She took the job at her friend's expense," all one can assume is that her friend was harmed or offended and the action did not benefit the friend. It would go against this idiom to state the friend was helping her to get said job.  More context would shed light on the nature of the harm and the nuances of their relationship.
As in:  "He had a good laugh at the expense of his brother", at best we know that the brother was the part of the 'laugh'.  The extent of harm and detriment are determined by the context of the event.


text:
Q: Replacing an object with an empty prototype I am trying to flush some data by replacing it entirely with an object that has a set of keys with empty values.
e.g.
const sportPrototype = {
  name: '',
  players: '',
  displacement: '',
  points: '',
  leagues: []
}

var profileScratchpadOne = {
  sportScratchpad: {
    name: 'Soccer',
    players: '16',
    displacement: 'Foot',
    points: 'unlimited',
    leagues: ["Fifa"]
  }
}

profileScratchpadOne.sportScratchpad = sportPrototype
profileScratchpadTwo.sportScratchpad = sportPrototype

Whenever a value in either sportScratchpads gets changed, it does in both profileScratchpadOne and profileScratchpadTwo.
I figure a reference is being passed.
I have investigated spread operator, prototypes, constructors, and have yet to find a bulletproof, concise approach.
What is the most succinct way of getting around this, and passing a fresh object every time?

A: Although Object.assign would work here, the objects would still share the same leagues array. Only primitive-typed properties will live a separate life. You could find a function that performs a  deep copy, but I think in this case you could use the constructor pattern:
function SportPrototype() {
  this.name = '';
  this.players = '';
  this.displacement = '';
  this.points = '';
  this.leagues = [];
}

var profileScratchpadOne = {};
var profileScratchpadTwo = {};

var o = new SportPrototype();
o.name = 'Soccer';
o.players = '16';
o.displacement = 'Foot';
o.points = 'unlimited';
o.leagues = ["Fifa"];
profileScratchpadOne.sportScratchpad = o;

profileScratchpadOne.sportScratchpad = new SportPrototype();
profileScratchpadTwo.sportScratchpad = new SportPrototype();

Now the last two assignments will produce objects which are completely independent.

A: Edit : Since there is at least an object (array) on sportPrototype, shallow copy is not the right choice here. Simplest deep copy can be chosen :
function deepCopy(o) {
  return JSON.parse(JSON.stringify(o));
}

const sportPrototype = {
  name: '',
  players: '',
  displacement: '',
  points: '',
  leagues: []
}

var profileScratchpadOne = {
  sportScratchpad: {
    name: 'Soccer',
    players: '16',
    displacement: 'Foot',
    points: 'unlimited',
    leagues: ["Fifa"]
  }
}

profileScratchpadOne.sportScratchpad = deepCopy(sportPrototype);
profileScratchpadTwo.sportScratchpad = deepCopy(sportPrototype);

A: As others have mentioned, Object.assign() is one way to create a shallow copy of an object. Another option is to use Object.create(), which "wraps" the object so that assigning values to the properties of the new object will not overwrite the properties of the prototype:

const sportPrototype = {
  name: '',
  players: '',
  displacement: '',
  points: '',
  leagues: []
}

var profileScratchpadOne = {
  sportScratchpad: {
    name: 'Soccer',
    players: '16',
    displacement: 'Foot',
    points: 'unlimited',
    leagues: ["Fifa"]
  }
}

var profileScratchpadTwo = {}

profileScratchpadOne.sportScratchpad = Object.create(sportPrototype)
profileScratchpadTwo.sportScratchpad = Object.create(sportPrototype)

console.log(sportPrototype.name);
console.log(profileScratchpadOne.sportScratchpad.name);
console.log(profileScratchpadTwo.sportScratchpad.name);

profileScratchpadOne.sportScratchpad.name = 'Jai Alai'
profileScratchpadTwo.sportScratchpad.name = 'Curling'

console.log(sportPrototype.name);
console.log(profileScratchpadOne.sportScratchpad.name);
console.log(profileScratchpadTwo.sportScratchpad.name);

However, both Object.create and Object.assign will have a problem with the leagues property because it is a reference type and will therefore be shared between all copies if you mutate it (by adding elements, etc.). For that reason, you'll essentially need to create a new, empty array for leagues (and any other reference-type properties) when you want to copy the prototype.
You could take care of this with a factory function, like:
function sportDefaults() {
    var newObj = Object.create(sportPrototype);
    newObj.leagues = [];

    return newObj;
}

profileScratchpadOne.sportScratchpad = sportDefaults()

Edit: The benefit of Object.create is that there is only one copy of your original prototype and new properties are created as needed, which saves on memory. If you're not all that concerned about memory, you could just create a function that returns a brand new copy of your prototype every time. This would sidestep the above-mentioned issues with reference types:

function sportDefaults() {
  return {
    name: '',
    players: '',
    displacement: '',
    points: '',
    leagues: []
  }
}

var profileScratchpadOne = {}
var profileScratchpadTwo = {}

profileScratchpadOne.sportScratchpad = sportDefaults()
profileScratchpadTwo.sportScratchpad = sportDefaults()

console.log('- before assignment')
console.log(profileScratchpadOne.sportScratchpad.name)
console.log(profileScratchpadTwo.sportScratchpad.name)

profileScratchpadOne.sportScratchpad.name = 'Jai Alai'
profileScratchpadTwo.sportScratchpad.name = 'Curling'

console.log('- after assignment')
console.log(profileScratchpadOne.sportScratchpad.name)
console.log(profileScratchpadTwo.sportScratchpad.name)


text:
Q: How to find an equivalent of $\int_{1}^{+\infty}\exp{(-x^n)}dx$? It's an exercise, I need to find an equivalent of :
$$\int_{1}^{+\infty}\exp{(-x^n)}dx$$
I tried this :
Let $x=u^{1/n}.$ Then $dx=\frac{1}{n}u^{1/n-1}\,du,$ so :
\begin{align}
\int_1^{+\infty} e^{-x^n}\,dx & =\int_0^{+\infty} e^{-x^n}\,dx-\int_0^1 e^{-x^n}\,dx=\frac{1}{n}\int_0^{+\infty} u^{1/n-1}e^{-u}\,du-\int_0^1 e^{-x^n}\,dx\\
& = \frac{1}{n}\Gamma(1/n)-\int_0^1 e^{-x^n}\,dx = \frac{1}{n}(n+o(n))-1+o(1)\\
& = o(1)
\end{align}
I try to multiply by $n$ but I am stuck here. One person told me that there will be a euler constant after that (I doubt it). Yet I don't know how to show it.
I would like first prove that there is a constant $c\neq 0$ such that this integral multiply by $n$ equals to $c$. Then try to find it.

A: Using the incomplete gamma function and the exponential integral function
$$I_n=\int\exp{(-x^n)}\,dx=-\frac{x }{n}E_{\frac{n-1}{n}}\left(x^n\right)$$
$$J_n=\int_{1}^{\infty}\exp{(-x^n)}\,dx=\frac{1}{n}\Gamma \left(\frac{1}{n},1\right)$$
If we  expand $\Gamma \left(\frac{1}{n},1\right)$ as a series for large value of $n$, the constant term is $c_0=-\text{Ei}(-1)$ as already given by @Sangchul Lee in comments.
What is difficult is to simplify the next since they involve more and more complex Meijer G-functions such as
$$c_1=G_{2,3}^{3,0}\left(1\left|
\begin{array}{c}
 1,1 \\
 0,0,0
\end{array}
\right.\right)$$
$$c_2=G_{3,4}^{4,0}\left(1\left|
\begin{array}{c}
 1,1,1 \\
 0,0,0,0
\end{array}
\right.\right)$$ and so on. Less compact forms involve hypergeometric functions.
Making their decimal values rational
$$n\,J_n=-\text{Ei}(-1)+\frac{59}{603\,n}+\frac{23}{646\,n^2}+\frac{3}{271\,n^3}+O\left(\frac{1}{n^4}\right)$$
For $n=10$, the above would give $J_{10}=0.0229524$ while the exact value is $0.0229536$


text:
Q: SSH from Linux to Windows does not execute commands in windows environment(only as background process) I am somewhat out of my dept here, so please go easy on me. I installed Openssh on both linux vm and Windows vm in vmware. As far as I can tell this implements some form of cygwin on windows. I can ssh to the user folder:
C:\Program Files\OpenSSH\home\ATV>

, like this:
ssh -p22 -t ATV@DESKTOP-CGHF9HU bash

or like this:
ssh -p22 -t ATV@DESKTOP-CGHF9HU cmd OpenExcelFile.vbs

or similar with cmd or sh. I can cd and DIR to my hearts content, and I can run .exe's, scripts you name it. It is just that they all start as background processes.
I want to be able to trigger ACTUAL execution of applications in the foreground.
The basics of it, I can access the command line and my windows os system through my linux terminal. I can dir file system and cd everything there. But I cannot run anything as foreground application, only as background processes, and I would like to trigger the actual opening of Microsoft Excel in the windows vm gui?
EDIT:
The problem is the display.... I can start Microsoft Excel, and see it running in background processes. So I guess the question would be how to be able to :

*

*Either start an application in the foreground over ssh.

*Or trigger a script that would open Excel in a "window".

Right now I am transferring the "file" via scp from python
os.system('scp CalculatedOutput/Opera.csv ATV@DESKTOP-CM5F9HU:')
os.system('ssh -t ATV@DESKTOP-CGHF9HU  RunIf.vbs')

, trying to open the script through ssh.
I also managed to find version 1.1 of winexe, but there seem to be a lot of problems with this client. I have scoured the net, but no combinations of the syntax seems to work:
os.system('./winexe --user=\DESKTOP-CGHF9HU/ATV%Mypassword   //windows.domain.local --interactive=1 --uninstall --system  OpenExcelFile.vbs')

My guess would be that some people know how to do(hack) this. Why you would want to ? Unless you are a unix purist I would think it obvious...
I didn't have the opportunity to give up on this, so I continued digging. As mentioned in the comments below there are indeed access restrictions, and I guess microsoft wouldn't want to allow access to their os. Nevertheless, seeing as your other windows settings allow sharing and your syntax is correct:
./winexe -U ATV%password //DESKTOP-CGHF9HU 'cmd.exe'

, you can edit your registry as per https://tommynation.com/enable-remote-access-administrative-shares-windows-10/
, and the winexe1.1 will indeed allow you access. Now I know this isn't safe, but all my vm's are physically under my control so I DO NOT CARE.
Moving on the problem still persists though, as my code above actually gives you access to the windows command line, but still opens applications in the background. I can not bring them to the foreground( as in -fg), and the purpose is defeated. Question remains, how do I get them to display ?
I can do the same thing with openssh and cygwin so what is then the purpose of the winexe application ?
Edit2:
Well, I'm not going to call it quits here, but The best way for me to do this at the moment, is transferring the file in question, then running the "if(file exists)" script at the same time over ssh(From python):
os.system('scp CalculatedOutput/Opera.csv ATV@DESKTOP-CGHF9HU:')
os.system('ssh -p22 -t ATV@DESKTOP-CGHF9HU "cscript RunIf.vbs"')

The vbscript for automating Excel is automatically run in the background with Excel, and I guess the fact that I manually have to open Excel for visualization is something I will have to live with for the time being. That WAS my original question though, so I will still leave this unanswered.

A: Not sure if it will work for all combinations of windows/linux
I wanted for logged windows user to see what ssh-ed user is doing, and vice versa, I needed for ssh linux session to "see" programs that it started in foreground.
So only way i got it to work was for that logged windows user and linux ssh user are the same, and that windows user started its own ssh with command
C:\OpenSSH\sshd.exe -f C:\wherever\sshd_config
If sshd was started as a service, or as a scheduled task, it didn't work.
Hope it helps someone

A: When you login as an ssh client to cygwin ssh server it seems like ssh session does not have access to all of the windows commands.
But there is a workaround, the idea is

*

*create service to execute windows command and launch it from startup script

*use this service by adding command to execute at file at cygwinhome.

Here is the implementation.
Service reads commands from ~/winexec.bat file one line single time and passes this line to cmd.exe:
tail -f ~/winexec.bat|xargs -l cmd /c

Here is how to setup it in simple way (you can copy and paste following commands to cygwin terminal)
Use cygwin shell to setup service at windows:
# findout dos path of bash
bash=`which bash|xargs cygpath -d`
# findout full path to startup folder - works for windows 10
startup_dir="$APPDATA/Microsoft/Windows/Start Menu/Programs/Startup/"
# create batch which launch cygwin service
# to execute windows commands
cmd=">~/winexec.bat;tail -f ~/winexec.bat|xargs -l cmd /c"
# and put it to startup folder
service_fn="$startup_dir/winexec-service.bat"
echo $bash -l -c '"$cmd"'>"$service_fn"

This service will start at Windows startup or you can start it immediately by double click $startup_dir/winexec-service.bat
Now to execute some troubled command using ssh from linux just add new line with command to ~/winexec.bat like this:
ssh 192.168.2.107 'echo troubled-command>>~/winexec.bat'

Voilà, you have just launched full blown windows command at cygwin host from linux shell prompt!


text:
Q: Spring Advisor in Java using @Bean I'm wondering if it's okay to create my own Spring Advisor via Java configuration, similar to what's proposed here. I too wanted to have annotated methods intercepted.
I had such an Advisor defined in our application, but after removing a completely unrelated @Configuration class, the whole thing collapsed and the advice no longer worked. After a lot of debugging, I figured that this could work
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public Advisor sessionContextAdvisor(OpenSessionInterceptor openSessionInterceptor)
{
    AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
    pointcut.setExpression("@annotation(my.app.SessionContext)");
    return new DefaultPointcutAdvisor(pointcut, openSessionInterceptor);
}

and indeed, that worked. I needed to declare the bean as an infrastructure bean @Role(BeanDefinition.ROLE_INFRASTRUCTURE) for Spring. I gotta say, this feels even more hackey now.
On the other hand, there is a way to add custom Advisors via XML, using <aop:advisor> ..., as documented in the Spring docs. But I couldn't find a Spring-documented way to register an Advisor via Java configuration.
Also, Spring JavaDoc has to say this about the Advisor interface:

This interface is not for use by Spring users, but to allow for commonality in support for different types of advice.

That doesn't sound like you're supposed to create instances of this interface.
But if there's an XML-way, is there really no Java configuration way to achieve the same thing? Is my solution not so bad after all?

A: Any aop-specific Java configuration for Advisor beans is not required (except @EnableAspectJAutoProxy) cause spring-aop discovers such beans via BeanFactory, please check org.springframework.aop.framework.autoproxy.BeanFactoryAdvisorRetrievalHelper
As regards to the question whether is it legitimate to use custom Advisor beans or not - just think about why @Transactional and @Cacheable are not implemented via @Aspect or check the example below:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
@Inherited
public @interface DemoAnnotation {
}

public interface DemoAnnotationApi {

    @DemoAnnotation
    default void method1() {

    }

    @DemoAnnotation
    void method2();

    void method3();

}

@Component
public class DemoAnnotationImpl implements DemoAnnotationApi {

    @Override
    public void method2() {

    }

    @DemoAnnotation
    @Override
    public void method3() {

    }
}

@Aspect
@Component
public class DemoAnnotationAspect {

    @Pointcut("@annotation(DemoAnnotation)")
    public void annotated() {
        // nop - pointcut
    }

    @Around("annotated()")
    public Object invoke(ProceedingJoinPoint pjp) {
        return doProceed(pjp);
    }

    @SneakyThrows
    protected Object doProceed(ProceedingJoinPoint pjp) {
        System.out.println("\tDemoAnnotationAspect: " + pjp.getSignature().getName());
        return pjp.proceed();
    }

}

@Component
public class DemoAnnotationAdvisor extends AbstractPointcutAdvisor {

    private final Advice advice;

    private final Pointcut pointcut;

    public DemoAnnotationAdvisor() {
        this.advice = new MethodInterceptor() {
            @Nullable
            @Override
            public Object invoke(@Nonnull MethodInvocation invocation) throws Throwable {
                System.out.println("\tDemoAnnotationAdvisor: " + invocation.getMethod().getName());
                return invocation.proceed();
            }
        };
        this.pointcut = new AnnotationMatchingPointcut(null, DemoAnnotation.class, true);
    }

    @Override
    public Pointcut getPointcut() {
        return pointcut;
    }

    @Override
    public Advice getAdvice() {
        return advice;
    }
}

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class DemoAnnotationTestIT {

    @Autowired
    DemoAnnotationApi api;

    @Test
    void test() {
        System.out.println("Calling method1");
        api.method1();
        System.out.println("Calling method2");
        api.method2();
        System.out.println("Calling method3");
        api.method3();
    }

}

output:
Calling method1
    DemoAnnotationAdvisor: method1
    DemoAnnotationAspect: method1
Calling method2
    DemoAnnotationAdvisor: method2
Calling method3
    DemoAnnotationAdvisor: method3
    DemoAnnotationAspect: method3


text:
Q: How to solve two REST problems: the interface document; loss of privacy in descriptive URLs Coming from a lot of frustrating times with WSDL/Soap, I very much like the REST paradigm, but am trying to solve two basic problems in our application, before moving over to REST.  The first problem relates to the lack of an interface document.  I think I finally see how to handle this situation:  One can query his way down from a top-level "/resources" resource using various requests of GET, HEAD, and OPTIONS to find the one needed resource in the correct hypermedia format.  Is this the idea?  If so, the client need only be provided with a top-level resource URI:  http://www.mywebservicesite.com/mywebservice/resources.  He will then have to do some searching and possible keep track of what he is discovering, so that he can use the URIs again efficiently in future to do GETs, POSTs, PUTs, and DELETEs.  Are there any thoughts on what should happen here?
The other problem is that we cannot use descriptive URLs like /resources/../customer/Madonna/phonenumber.  We do have an implementation of opaque URLs we use in the context of a session, and I'm wondering how opaque URLs might be applied to REST.  The general problem is how to keep domain-specific details out of URLs, and still benefit from what REST has to offer.

A:
The other problem is that we cannot use descriptive URLs like /resources/../customer/Madonna/phonenumber.

I think you've misunderstood the point of opaque URIs.  The notion of opaque URIs is with respect to clients: A client shall not decipher a URI to guess anything of semantic meaning from it.  So a service may well have URIs like /resources/.../customer/Madonna/phonenumber, and that's quite a good idea.  The URIs should be treated as opaque by clients:  not infer from the URI that it represents Madonna's phone number, and that Madonna is a customer of some sort.  That knowledge can only be obtained by looking inside the URI itself, or perhaps by remembering where the URI was discovered.
Edit:
A consequence of this is that navigation should happen by links, not by deconstructing the URI.  So if you see /resouces/customer/Madonna/phonenumber (and it actually represents Customer Madonna's phone number) you should have links in that resource to point to the Madonna resource: e.g.
{
  "phone_number" : "01-234-56",
  "customer_URI": "/resources/customer/Madonna"
}

That's the only way to navigate from a phone number resource to a customer resource.  An important aspect is that the server implementation might or might not have domain specific information in the URI, The Madonna record might just as well live somewhere else: /resources/customers/byid/81496237.  This is why clients should treat URIs as opaque.
Edit 2:
Another question you have (in the comments) is then how a client, with the required no knowledge of the server's URIs is supposed to be able to find anything.  Clients have the following possibilities to find resources:

*

*Provide a search interface.  This could be done by providing an OpenSearch description document, which tells clients how to search for items.  An OpenSearch template can include several variables, and several endpoints, depending on what you're looking for.  So if you have a "customer ID" that's unique, you could have the following template: /customers/byid/{proprietary:customerid}", the customerid element needs to be documented somewhere, inside the proprietary namespace.  A client can then know how to use such a template.

*Provide a custom form. This implies making a custom media type in which you explicitly define how (based on an instance of the document) a URI to a customer can be forged.  <customers template="/customers/byid/{id}"/>.  The documentation (for the media type) would have to state that the template attribute must be interpreted as a relative URI after the string substitution "{id}" to an actual customer ID.

*Provide links to all resources.  Some resources aren't innumerable, so you can simply make a link to each and every one of them, optionally including identifying information along with the links.  This could also be done in a custom media type: <customer id="12345" href="/customer/byid/12345"/>.
It should be noted that #1 and #2 are two ways of saying the same thing: Clients are allowed to create URIs if they

*

*haven't got the URI structure a priori

*a media type exists for which the documentation states that URIs should be created

This is much the same way as a web browser has no idea of any URI structure on the web, except for the rules laid out in the definition of HTML forms, to add a ? and then all the query parameters separated by &.
In theory, if you have a customer with id 12345, then you could actually dispense with the href, since you could plug the customer id 12345 into #1 or #2.  It's more common to actually provide real links between resources, rather than always relying on lookup or search techniques.

A: I haven't really used web RPC systems (WSDL/Soap), but i think the 'interface document' is there mostly to allow client libraries to create the service API, right?  if so, REST shouldn't need it, because the verbs are already defined and don't really need to be documented again.
AFAIUI, the REST way is to document the structure of each resource (usually encoded in XML or JSON).  In that document, you'll also have to document the relationship between those resources.  In my case, a resource is often a container of other resources (sometimes more than one type), therefore the structure doc specifies what field holds a list of URLs pointing to the contained resources.  Ideally, only one unique resource will need a single, fixed (documented) URL.  everithing else follows from there.
The URL 'style' is meaningless to the client, since it shouldn't 'construct' an URL.  Every URL it needs should be already constructed on a resource field.  That let's you change the URL structure without changing the client (that has saved tons of time to me).  Your URLs can be as opaque or as descriptive as you like.  (personally, i don't like text keys or slugs; my keys are all BIGINTs or UUIDs)

A: I am currently building a REST "agent" that addresses the first part of your question.  The agent offers a temporary bookmarking service.  The client code that is interacting with the agent can request that an URL be bookmarked using some identifier.  If the client code needs to retrieve that representation again, it simply asks the agent for the url that corresponds to the saved bookmark and then navigates to that bookmark.  Currently those bookmarks are not persisted so they only last for the lifetime of the client application, but I have found it a useful mechanism for accessing commonly used resources.  E.g.  The root representation provides a login link.  I bookmark that link and if the client ever receives a 401 then I can redirect to the "login" bookmark.
To address an issue you mentioned in a comment, the agent also has the ability to store retrieved representations in a dictionary.  If it becomes necessary to aggregate and manipulate multiple representations at the same time then I can simply request that the agent store the current representation in a dictionary associated to a key and then continue navigating to the next resource.  Once the client has accumulated all the necessary representation it can do what it needs to do.


text:
Q: RelativeLayout.LayoutParams AND addRule method not working I'm new here so be gentle with me :).
Im trying to generate a new TextView every button click and place it BELOW another View in the activity.
my XML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.mylifeinformationsharedsocial.HairCutsActivity"
    android:id="@+id/relative_layout_id">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:id="@+id/header1"
        android:text="@string/header1_text"
        android:textSize="20sp"

        />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:id="@+id/editText1"
        android:layout_below="@id/header1"
        android:text="@string/date_text"
        android:inputType="date"
         />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/addButton"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:text="@string/add_button_text"

        />

</RelativeLayout>

My Java:
package com.example.mylifeinformationsharedsocial;

import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import com.example.mylifeinformationsharedsocial.R.id;

import android.support.v7.app.ActionBarActivity;
import android.text.Layout;
import android.R.bool;
import android.R.integer;
import android.R.layout;
import android.R.string;
import android.app.ActionBar.LayoutParams;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class HairCutsActivity extends ActionBarActivity
{
    TextView header1;
    EditText editText; // Where you insert your new dates
    Button addButton;
    String hairCutDateString;
    TextView dateText;
    public static ArrayList<TextView> datesUploadedList = new ArrayList<TextView>();
    int datesUploadedCounter = 0;
    RelativeLayout relativeLayout;
    boolean firstInsertFlag = true; // True - first insert

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hair_cuts);

        getWindow().getDecorView().setBackgroundColor(Color.WHITE); // Setting the window color to white

        header1 = (TextView) findViewById(R.id.header1);
        header1.setTextColor(Color.rgb(32,178,170));

        editText = (EditText) findViewById(R.id.editText1);
        relativeLayout = (RelativeLayout) findViewById(R.id.relative_layout_id);
        addButton = (Button) findViewById(R.id.addButton);

        addButton.setOnClickListener(new View.OnClickListener() // Click on add button
        {
            @Override
            public void onClick(View v)
            {
                SimpleDateFormat simpleDateFromat = new SimpleDateFormat("MM/dd/yyyy");
                java.util.Date date;
                try
                {
                    date = simpleDateFromat.parse(editText.getText().toString());
                    hairCutDateString = date.getMonth() + 1 + "/" + (date.getDate()) + "/" + (1900 + date.getYear()); // The date string
                }
                catch (ParseException e)
                {
                    e.printStackTrace();
                }
                dateText = new TextView(HairCutsActivity.this);
                dateText.setText(hairCutDateString);
                dateText.setId(datesUploadedCounter);
                datesUploadedCounter++;

                datesUploadedList.add(dateText);
                if (firstInsertFlag) // First insert
                {
                    RelativeLayout.LayoutParams layoutParams  = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
                    // Setting the new date below the header
                    layoutParams .addRule(RelativeLayout.BELOW, header1.getId());
                    dateText.setLayoutParams(layoutParams);
                    relativeLayout.addView(dateText);
                    layoutParams.addRule(RelativeLayout.BELOW,datesUploadedList.get(datesUploadedCounter - 1).getId());
                    editText.setLayoutParams(layoutParams);
                    firstInsertFlag = false;
                }
                else
                {

                }
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.hair_cuts, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings)
        {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

Now the thing is the BELOW alignment of the EditText is working (BELOW the new TextView) but the alignment of the new TextView to bew BELOW the header1 TextView is not working.
pictures:
Before the click on the button:
http://www.siz.co.il/my.php?i=fmigy2wimnkz.png
After the click on the button:
http://www.siz.co.il/my.php?i=ijyg0ytz4nty.png
Anyone know what is the problem? Thanks

A: just change
 layoutParams.addRule(RelativeLayout.BELOW,datesUploadedList.get(datesUploadedCounter - 1).getId());

to
 layoutParams.addRule(RelativeLayout.BELOW,datesUploadedList.get(dateText.getId());

Also you might want to set some margin.
And you don't need handle first add and others so differently.
Take a global TextView
 TextView lastTextView = null;

and just use (change margins according to your taste)
    onclick(){
    .........

            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            if(lastTextView == null) {
                layoutParams.addRule(RelativeLayout.BELOW, header1.getId());
            }else{
                layoutParams.addRule(RelativeLayout.BELOW,lastTextView.getId());
            }
           layoutParams.setMargins(100,100,100,100);
            dateText.setLayoutParams(layoutParams);
            relativeLayout.addView(dateText);

            RelativeLayout.LayoutParams newLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            newLayoutParams.addRule(RelativeLayout.BELOW, dateText.getId());
            newLayoutParams.setMargins(200,200,200,200);
            editText.setLayoutParams(newLayoutParams);
            lastTextView =dateText;
    }


text:
Q: Return one element array or empty array best practice in JavaScript Is there any better way to implement this?
const a = _.get(obj, 'property');
const b = a ? [a] : [];

obj is an object, may or may not have property. If it does, return an array of one element of property, else return an empty array.

A:

let obj = {}
console.log("when property is not present: ", obj["property"] || [])

obj = {property: ["hello"]}

console.log("when property is present: ", obj["property"] || [])

A: You could wrap it into array an filter non-nil value
const a = _.get(obj, 'property');
const b = [a].filter(Boolean);

const a1 = null
const a2 = 1

const res1 = [a1].filter(Boolean)
const res2 = [a2].filter(Boolean)

console.log(res1)
console.log(res2)

A: const obj = {
  prop: "hello"
}

const b = obj.hasOwnProperty("prop") ? [obj.prop] : [];


text:
Q: How to get Grunt UnCss to compile based on the homepage I am trying to get UnCss to produce a cut down version of my master CSS file, for now I only want to get this working on the homepage as a test.
I am using the following code:
uncss: {
  dist: {
    options: {
      stylesheets  : ['localhost/assets/css/master-2014.css'],
      urls         : ['localhost/en-gb/']
    },
    files: {
      'css/app.clean.css': ['localhost/en-gb/']
    }
  }
}

What I am trying to do here is read master-2014.css from my local server (and eventually a remote url e.g. google.com), then look at the page that I have got the stylesheet from (my homepage localhost) and determine which style is needed. I finally want to then produce this into app.clean.css.
Currently I cannot get this to work for the life of me I have tried other variations like:
    files: {
      'css/app.clean.css': ['**/*.Master', '**/*.ascx']
    }

This does not work.
I have also seen people try something like this:
    files: {
      'css/app.clean.css': ['index.html']
    }

Where index.html is a blank html file. This is the only one that succeeds but it just creates me a css file which only contains css for html and body. The rest all throw the following error:
Running "uncss:dist" (uncss) task
Warning: Destination (css/app.clean.css) not written because src files were empty. Use --force to continue.

Aborted due to warnings.

All other examples that I can find are for WordPress which is PHP and this is a .Net site.
I would be very grateful for any help.


text:
Q: Is there any way to speed up array initialization? I have a function that stores values inside some arrays. Every time the function is called, the arrays have to be cleared before putting items in them.
public static void UpdateAttackedPieces()
    {
        attackedSquares = new List<int>[2][];

        for (int color = 0; color < 2; color++) attackedSquares[color] = new List<int>[64];

        for (int color = 0; color < 2; color++) for (int i = 0; i < 64; i++) attackedSquares[color][i] = new List<int>();

        checkAttackersRays = new List<int>[2][];

        for (int color = 0; color < 2; color++) checkAttackersRays[color] = new List<int>[64];

        for (int color = 0; color < 2; color++) for (int i = 0; i < 64; i++) checkAttackersRays[color][i] = new List<int>();

        // Update arrays
    }

(It is a chess program and the function is for updating pieces under attack).
attackedSquares is an array (one per color) of the 64 squares on the board which holds information about its attackers (so attackedSquares[0][4][2] is the third attacker on the fifth square for white, for example)
I've done some testing and about 35% of the time it takes to run the function is spent initializing the jagged arrays. Is there a faster way to do this?

A: Thanks to @Matthey Watson's comment, I was able to bring the time down from 6.5 seconds to less than 1 second with this change in the code:
public static void UpdateAttackedPieces()
    {
        for (int color = 0; color < 2; color++) for (int i = 0; i < 64; i++) attackedSquares[color][i].Clear();

        for (int color = 0; color < 2; color++) for (int i = 0; i < 64; i++) checkAttackersRays[color][i].Clear();

        // Update arrays
    }


text:
Q: Changing Atmel IO pins from input to output to tristate on the fly I'm Google-d out.  So, dear friends at StackOverflow,  is it possible to change an IO pin on at Atmel family microprocessor (say an Atmel 165) from input to output, or from output to tristate, or from output to tristate to input and any or all of those in reverse?
Parallel question:  Are there Atmel programmers/languages that do or don't support the "tools" to switch the IO pins?  If I were to search Google for related information, does this subject (changing pin directions) have a name that is more searchable than "change input pin to output pin" +Atmel?

A: The I/O direction of the pins is configured by changing the values of individual bits in 3 control registers.  The documentation for this is in section 12.2 (starting on page 61) of this doc.
For example, to set PA1 to a tri-state input, you need to clear the corresponding bits in DDRA and PORTA.  In C:
PORTA &= !(1<<PA1)
DDRA &= !(1<<DDA1)

A: Yes, you can change the pin configuration at any time. I've never heard of a language that didn't let you switch the pin configuration.
Just follow the procedures outlined in the chip documentation for how to change the pin configuration. You basically just write a value to the corresponding data direction register for that port. See section 12.4 of the data sheet. In C, it's usually as simple as DDRC = 0; to set all port C pins to inputs.
The data sheet goes over the capabilities of each port and how to get them in sections 12.4.2 through 12.4.22.


text:
Q: What methods could/should I use for identifying sub-groups in a customer segmentation? I am working on a segmentation model that has been fed into the company by an external agency which created the segmentation based on surveys. I have a number of 6 attitudinal segments and after ascribing them to our database via proxy variables, I wish to test if it makes sense from a statistical point of view to further split (or combine for that matter) the segments.
What kind of methods should I consider applying to tackle this? I have limited experience with clustering (k-means), and not so much from a statistical point of view, but more from a perspective where I'd only care about measures of predictive accuracy and not so much about exploratory modelling, so any directions would be helpful.
Many thanks!
P.S. The original segmentation will have to stay unchanged (business requirements...)

A: There have been many 'tests' proposed in literature. But if you apply them to the business-given clusters it will likely not consider them to be good either...
Popular tests include AIC and BIC that trade point approximation vs. model size. So of you need just a few more parameters (clusters) to get a much better model of your data, then these clusters are good to keep.
You could try an ANOVA test, but as k-means optimizes this, the significance values will be way too extreme. Beware of multiple testing and "data snooping" when trying to judge the significance of cllusterings.


text:
Q: Google Charts How to redraw Charts based on its Type been provide as a list? I am using the following code to make my chart   initially. But I want to provide users with set of Charts options list like 'SteppedAreaChart', 'LineChart', 'ColumnChart'
 var barChart = new google.visualization.ChartWrapper({
              'chartType': 'BarChart',
              'containerId': 'chart1',
              'options': {
                'width': '100%',
                'height': 800,
                'chartArea': {top: 0, right: 0, bottom: 0}
              }
            });

I am looking a workaround for
1. ControlWrapper to accept Chart Type
2. Then redraw the below chart accordingly
I tried using statechange  no luck still.
barChart.setView({chartType: 'LineChart'});
            barChart.draw();

A: There is currently no control that will let you change the chart type of a chart, so your (1) is not possible.  However, you should be able to make that change yourself outside of controls.  What you tried could potentially work, but I don't see where you specified the data.  E.g.
barChart.setDataTable(myTable);

The view_spec that you provide to setView() must contain the entire view, since you are replacing whatever had been specified previously.
Alternatively, you can just call setChartType() to change the type of the chart in the chart wrapper, like this:
barChart.setChartType('LineChart');
barChart.draw()

The docs for ChartWrapper are at: https://google-developers.appspot.com/chart/interactive/docs/reference#chartwrapperobject


text:
Q: How to do a SQL "Where Exists" in LINQ to Entities? I really want to do something like this:
Select *
from A join B on A.key = B.key join C on B.key = C.key -- propagated keys
where exists (select null from B where A.key = B.key and B.Name = "Joe") and
      exists (select null from C where B.key = C.key and C.Name = "Kim")

What would the linq statement look like using Entity Framework 4 and C#?
Update:
Apparently .Contains() will produce "Where Exists" results.  So, another attempt (I don't know if this will even compile LOL):
var inner1 = from recordB in B
             where recordB.Name = "Joe"
             select recordB.key;

var inner2 = from recordC in C
             where recordC.Name = "Kim"
             select recordC.key;

var result = from recordA in A
             where inner1.Contains( recordA.key) &&
                   inner2.Contains( recordA.key)
             select recordA;

EDIT: WOW this is what actually worked:
var result = from A in Products
             where A.kfield1 == 1 && A.kfield2 == 2 &&
                   ( from B in Btable
                     where B.otherid == "Joe" &&  // field I want to select by
                           B.kfield1 == A.kfield1 &&
                           B.kfield2 == A.kfield2 // Can keep adding keys here
                     select A.identifier  // unique identity field
                   ).Contains(A.identifier) &&
                   ( from C in Ctable
                     where C.otherid == "Kim" &&  // field I want to select by
                           C.kfield1 == A.kfield1 &&
                           C.kfield2 == A.kfield2 // Can keep adding keys here
                     select A.identifier  // unique identity field
                   ).Contains(A.identifier)
             select A;

This produced this SQL:
SELECT [t0].[identifier], [t0].*
FROM [A] AS [t0]
WHERE ([t0].[kfield1] = @p0) AND ([t0].[kfield2] = @p1) AND (EXISTS(
    SELECT NULL AS [EMPTY]
    FROM [B] AS [t1]
    WHERE ([t0].[identifier] = [t0].[identifier]) AND ([t1].[otherid] = @p2) AND
          ([t1].[kfield1] = [t0].[kfield1]) AND
          ([t1].[kfield2] = [t0].[kfield2]))) AND (EXISTS(
    SELECT NULL AS [EMPTY]
    FROM [C] AS [t2]
    WHERE ([t0].[identifier] = [t0].[identifier]) AND ([t2].[otherid] = @p3) AND
          ([t2].[kfield1] = [t0].[kfield1]) AND
          ([t2].[kfiekd2] = [t0].[kfield2]) ))

Which is what I wanted.  Notice the [t0].[identifier] = [t0].[identifier], which filters out null values because null doesn't compare equal to anything including itself (in SQL)

A: The .Any() extension method typically maps to exists.

A: Have you tried adding your exists conditioning to your joins?
from a in context.AEntity
Join B in context.BEntity on A.Key equals B.Key && B.Name == "Joe"
Join C in context.CEntity on B.Key equals C.Key && C.Name == "Kim";

Not sure if that will work, but worth a shot.


text: Q: Getting issue with push notification image randomly We have implemented firebase push notification in our react-native application, but randomly we are facing that image issue. When we are sending push notification to all users in that case some of our users are not getting image in notification which is very weird because when we try to send it on individually then it's working fine.


text:
Q: dbdelta failing with error: "WordPress database error Table 'wp_2_myPlugin' already exists I'm upgrading a plugin and having issues with dbdelta.
Here's the original db creation function:
global $jal_db_version;
$jal_db_version = "0.1";

function jal_install() {

   global $jal_db_version;

   global $wpdb;
   $table_name = $wpdb->prefix . "jalPlugin";
   $sql = "CREATE TABLE " . $table_name . " (
      id mediumint(9) NOT NULL AUTO_INCREMENT,
      timestamp datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
      hash text NOT NULL,
      uname tinytext NOT NULL,
      UNIQUE KEY id (id)
    );";

   require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
   dbDelta($sql);

   update_option("jal_db_version", $jal_db_version);
}

// Installs db on plugin activation
register_activation_hook(__FILE__,'jal_install');

You'll probably recognize it from the WordPress Codex on Using Tables -- it works beautifully. (I obviously modified the function name so as not to conflict with other plugins).
I'm trying to upgrade my db used for the plugin and having some issues. I thought dbdelta was supposed to be able to see the differences between what you have and what you want and modify a table accordingly. So here's my upgrade script:
global $jal_db_version;
$jal_db_version = "0.2";
function jal_install() {

   global $wpdb;
   $table_name = $wpdb->prefix . "jalPlugin";
   $sql = "CREATE TABLE " . $table_name . " (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        timestamp datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
        hash text NOT NULL,
        uIP VARCHAR(55) DEFAULT '' NOT NULL,
        uname tinytext NOT NULL,
        UNIQUE KEY id (id)
    );";

   require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
   dbDelta($sql);

   update_option("jal_db_version", $jal_db_version);

}

function jal_install_update_check() {
    global $jal_db_version;
    if (get_site_option('jal_db_version') != $jal_db_version) {
        jal_install();
    }
}
add_action('plugins_loaded', 'jal_install_update_check');

I got this code from the same codex page.
The db is not updating and I'm getting an error in the error log:
[05-Feb-2012 20:33:18] WordPress database error Table 'wp_2_jalPlugin' already exists for query CREATE TABLE wp_2_jalPlugin (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        timestamp datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
        hash text NOT NULL,
        uIP VARCHAR(55) DEFAULT '' NOT NULL,
        uname tinytext NOT NULL,
        UNIQUE KEY id (id)
    ) made by require, require_once, require_once, require_once, do_action, call_user_func_array, qrLogin_update_db_check, qrLoginDB_install, dbDelta

It would appear to me that dbdelta is not understanding that it has a job to do...
Any ideas?
...and thanks for your time!

A: I've never had any luck with dbdelta, it has worked spottily at best, and when I code, that's just not good enough. My method for handling DB changes is to use database versions. So when I create a plugin, I also set the database version, then if I want to update the database, I do a check against the current dbversion (almost always stored in the wp_options table), if it's less than the new DB version, I'll run a series of updates. I'll repeat the process if I release another update that requires database structure changes. This allows users to update the plugin, even from a very old version, and still be assured that the database format will be correct. This method also holds up if the data needs to be transformed and re-entered into the database, as it will update through every structural change as though the plugin were being updated incrementally.


text:
Q: How to use Button to switch fragments in a ViewPager? I have 3 main fragments inside viewpager and they have couple of buttons. I want each button to navigate to another fragment and back button to get back to main fragment. I tried to add fragment transaction but it does not work. What am I doing wrong here?
this is one of the main fragments
public class OneFragment extends Fragment implements View.OnClickListener{

    public OneFragment() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        return inflater.inflate(R.layout.fragment_one, container, false);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.aButton:
                FragmentManager manager = getFragmentManager();
                FragmentTransaction transaction = manager.beginTransaction();
                transaction.replace(R.id.fragment_one, AFragment.newInstance());
                transaction.commit();
                break;
        }
    }
}

this is the fragment I want to navigate
public class AFragment extends Fragment{

    public AFragment() {

    }
    public static AFragment newInstance() {
        AFragment fragment = new AFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        return inflater.inflate(R.layout.a_fragment, container, false);
    }

}

A: First, define a public method in your Activity to switch tabs in the ViewPager, and also define the onBackPressed() override, which will select the first index when the back button is pressed:
public void selectIndex(int newIndex) {
  mViewPager.setCurrentItem(newIndex);
}

@Override
public void onBackPressed() {
  int currentPosition = mViewPager.getCurrentItem();
  if (currentPosition != 0) {
        mViewPager.setCurrentItem(0);
  } else {
    super.onBackPressed();
  }
}

Then, modify the click listener in the Fragment in order to call the selectIndex() method:
@Override
public void onClick(View v) {
    switch (v.getId()){
        case R.id.aButton:
            //select the index of AFragment:
            ((MainActivity)getActivity()).selectIndex(1);
            break;
    }
}


text:
Q: Was Grima the only one who knew about the weak spot in Helm's Deep? In the movie at least of The Two Towers, Grima Wormtongue mentioned to Saruman a nasty weak spot in the outer foundations of Helm's Deep - a small tunnel which allows a wee stream to flow to and fro.
Now even if nobody knew at the time that Saruman was capable of making bombs, they could have assumed that the enemy could try and break their way through the tunnel by chiseling or pulling out the tiny grate inside the tunnel.
Was this possibility not considered?

A: As far as I can recall, the books don't make any reference to Grima informing Saruman and his army of the culvert in the wall.  It was obviously a weakness, but it was also necessary, as we see in the slightly different version of events in the books.
The Culvert as Described in the Books:
In the book, there don't seem to be bars across the culvert, so it is easier to access than in the movie.  Fairly early in the battle, Orcs begin to crawl through the culvert, but they are forced to pass through it one at a time, so they are easily dealt with.  The men of Rohan ask Gimli to help them block the culvert, and he does so.  However, this causes new problems.
It is pouring rain by now, and with the culvert (which was intended to allow the Deeping-stream to pass out of the fortress by running under the walls) blocked, the water has nowhere to go.  As a result, the fortress begins to fill with water, making it difficult to move around, let alone fight.  Only a page later, the point becomes moot, as the Orcs place explosives in the culvert and blow the wall apart.
In this light, it appears that the culvert was an obvious weakness, but it was necessary to allow water to drain from the fortress.  Whether or not Grima told anyone about the culvert, it would have been visible to the attackers as soon as they arrived at the scene.  The Orcs in the films are much bigger than they are in the books (generally speaking, Orcs in the books are barely taller than hobbits, perhaps 3 1/2 to 4 1/2 feet tall, and Uruks are somewhat bigger, but no Orcs are as tall as the average man), so the culvert probably would have been at eye level to them, and trying to crawl through it would have been a natural choice.
Did Anyone Know that Saruman Had Explosives?
As to the issue of whether the defenders knew that Saruman had access to explosives:  The defenders are surprised by the explosion, and clearly weren't expecting anything like that, but Aragorn immediately realized what had happened.  However, his reaction suggests that he didn't know that explosives existed, and simply realized that whatever had caused the blast must have been the work of Saruman.

Then there was a crash and a flash of flame and smoke.  The waters of the Deeping-stream poured out hissing and foaming:  they were choked no longer, a gaping hole was blasted in the wall.  A host of dark shapes poured in.
"Devilry of Saruman!" cried Aragorn.  "They have crept in the culvert again, while we talked, and they have lit the fire of Orthanc beneath our feet."
  - The Two Towers, Helm's Deep

Two pages later:

"But the Orcs have brought a devilry from Orthanc," said Aragorn.  "They have a blasting fire, and with it they took the wall."
  - ibid

It took Aragorn a few seconds to realize that the Orcs had some sort of explosives, but the words he uses to describe it imply that he doesn't understand what explosives are or how they work.
The Answer:
Anyone who had been to Helm's Deep would have known about the culvert, because a stream passed through the fortress and exited through it.  You could only fail to notice the culvert if you also failed to notice the stream, which would be almost impossible.  All it would take for you to notice the culvert was for you to see the stream and look at the spot where it passed through the outer wall.
But the men of Rohan probably didn't know that Saruman had explosives, and therefore, they could not have imagined that the culvert would become such a liability.  In their minds, they probably anticipated that Orcs could crawl through the culvert one at a time, but this wasn't a serious threat - Orcs are barely taller than hobbits, and a handful of them would be incredibly easy to kill.  Leave a couple of guys near the entrance to the culvert and they can kill any Orcs who crawl through, before they even have a chance to stand up and defend themselves.  The men of Rohan were reluctant to block the culvert because they didn't want to have to fight in a pool of knee deep water.
So they definitely knew about the culvert, but they probably didn't realize how much of a problem it would become, because they almost certainly didn't expect Saruman to use explosives (if they even knew that explosives existed, which is unlikely).  And in any case, they couldn't have done anything about the culvert (like blocking it up, for instance) without flooding the fortress.  They basically had to cross their fingers and hope for the best.


text:
Q: Question about controllers, dependent models, and controller functions I'm new to ruby on rails and I'm thoroughly confused from all the documentation online. I'm creating a database program that keeps track of orders. I've already setup the has_one, belongs_to, and has_many associations in the model and I can verify their relationship with my sqlbrowswer.
Here's an rough illustration of the models.
Models
Each order has only one product, one service, one bill, and each bill can have many charges. The same product may appear in different orders, but each order would be unique.
I also have an order_observer model to create dependent models of the product
class OrderObserver < ActiveRecord::Observer
    observe :order
    def after_create(order)
        Product.create! :order_id => order.id
        Service.create! :order_id => order.id
        Bill.create! :order_id => order.id
    end
end
Here's what my product class and order class look like:
class Product < ApplicationRecord
belongs_to :order
end

class Order < ApplicationRecord
has_one :product, dependent: :destroy
has_one :bill, dependent: :destroy
has_one :service, dependent: :destroy
accepts_nested_attributes_for :product
accepts_nested_attributes_for :bill
accepts_nested_attributes_for :service
end

Now, what I'm confused on is how to update the dependent models. Should I implement multiple controllers for each model or just one controller to handle the whole thing?
Right now all I have in my main controller is:
 def create
    @order = Order.new(order_params)
 end
 def edit
    @order = Order.find(params[:id])
 end
 def update
 end

I would appreciate any tips or guidance.
Thanks!

A:
Now, what I'm confused on is how to update the dependent models. Should I implement multiple controllers for each model or just one controller to handle the whole thing?

You can do this whatever you want, but you should always remember the idea 'resources', In this case, each model represents a resource, so you should do it separately.
The Rails program is based on resources, as you can see that in 'routes.rb'.


text:
Q: How to generate a series of bisection points of a given line segment? I want to get the coordinates of the bisection points for a given line segment to a specified resolution. For example, when the line is given by {0,0} and {1,0}, the output coordinates should be {0.5,0} for the first iteration, and then {0.25,0} and {0.75,0} for the second iteration, and so on, until the distances between those points are less than some resolution, say 1/16. Is there a convenient way?

A: Here's a cute method based on the way Mathematica reduces fractions. Suppose you want to divide the line into 16ths:
n = 16;
x = Reverse @ GatherBy[Range[n - 1]/n, Denominator]

(* {{1/2}, {1/4, 3/4}, {1/8, 3/8, 5/8, 7/8},
  {1/16, 3/16, 5/16, 7/16, 9/16, 11/16, 13/16, 15/16}} *)

The actual coordinates can be obtained with:
line = {{0, 0}, {1, 0}};
Map[{1 - #, #}.line &, x, {-1}]

(* {{{1/2, 0}}, {{1/4, 0}, {3/4, 0}}, {{1/8, 0}, {3/8, 0}, {5/8, 0}, {7/8, 0}}, ... *)

A: Here is an apporach:
fun[p_, q_, n_] :=
 Nest[DeleteDuplicates[
    Join @@ Map[
      Function[u, u /. {x_List, y_List} -> {x, Mean[{x, y}], y}],
      Partition[#, 2, 1]]] &, {p, q}, n]

Testing (by plotting):
Table[ListPlot[fun[{0, 0}, {1, 0}, j], PlotStyle -> Red,
PlotMarkers -> {Automatic, 10}], {j, 0, 5}]

Or
Table[ListPlot[fun[{0, 0}, {1, 1}, j], PlotStyle -> Red,
  PlotMarkers -> {Automatic, 10}], {j, 0, 5}]

And for line not through origin:
Table[ListPlot[fun[{3, 0}, {1, 1}, j], PlotStyle -> Red,
  PlotMarkers -> {Automatic, 10}], {j, 0, 5}]

UPDATE
Same code works for 3D:
tab = Table[fun[{1, 6, 5}, {10, 2, 2}, j], {j, 0, 5}];
Export["e:/mse/msebisect3d.gif",
 Table[Graphics3D[{{Red, PointSize[0.04], Point[j]}, Line[j]}], {j,
   tab}], "DisplayDurations" -> Table[2, {6}]]

A: f[i_, j_, lim_] := Table[k, {k, i, j, 2 ^Floor@Log[2, lim] (j - i)}]
g[a_, b_, lim_] := (a (1 - #) + b #) & /@ f[0, 1, lim/Norm[b - a]]

So;
g[{0, 0}, {1, 1}, 1/4]

(* {{0, 0}, {1/8, 1/8}, {1/4, 1/4}, {3/8, 3/8}, {1/2, 1/2}, {5/8, 5/8},
    {3/4, 3/4}, {7/8, 7/8}, {1, 1}} *)


text:
Q: how to access a server in a VPN from a home computer via a separate notebook with the vpn connection For my local work environment I would like to access all my companies server directly from my workstation elsewhere.
To make this really fun the only access possible is via the VPN on the company managed notebook and the notebook does not allow connections to the local network.
Obviously, no IT department is helping you with such a problem.

A: If you can SSH to the company notebook from your home computer then you can use SSH Tunnelling or SSH Jump Hosts

A: There is a lot of ssh tunnneling documentation, but they dont cover this specific scenario.
So to get from
     Workstation <-> Notebook <-> Company Network
we need an extra system on N which plays the router to connect the separate networks.
We need an additional VM on the Notebook with 2 network ports.
One is connected to the host network via NAT,
the other connected to the LAN via a bridged connection.
So we can get a connection as
 W <-> VM1 <-> VM2 <-> N1 <-> N2 <-> CN
This can be configured via ssh config.
An example with some bogus IPs.
W =   192.0.0.3   <LAN>      VM1 = 192.0.0.2
VM1 = 192.0.0.2   <route>    VM2 = 10.0.0.3
VM2 = 10.0.0.3    <NAT>      NATRouter = 10.0.0.1
NR =  10.0.0.1    <nat2host> N1 = 20.0.0.4
N2 = 20.0.0.4     <vpnroute> CN 0.0.0.0/0

This is the description of the network hops between the system.
So to connect to a server in the CN we need to solve 2 separate steps.
We need to setup ssh configurations for the intermediate hops.
.ssh/config entries:
# reaching the VM
Host VM
    User            vmuser
    IdentityFile    ~/.ssh/vm_id_rsa
    ForwardX11      yes

# reaching a host inside the CN
Host CNhost
    User            companyuser
    IdentityFile    ~/.ssh/cnhost_id_rsa
    ForwardX11      yes
    ProxyCommand    ssh -A vm nc %h %p 2>  /dev/null

Another important issue is the correct routing within the VM.
The route to the bridged LAN 192.0.0.0/24 needs to have a lower metric than the default route to the NAT 10.0.0.1.
vm$ ip route
default via 10.0.0.1 metric 100
10.0.0.0/24 dev nat1 metric 100
192.0.0.0/24 dev bridge1 metric 99

Now the interesting case is when we want to also access a server on an internal network which is accessible only from a server already inside the company network.
A classical jumphost configuration.
For that we need another .ssh/config entry
# reaching a host on a CN internal network
Host CNInternalhost
    User            cnInternalUser
    IdentityFile    ~/.ssh/cninternalhost_id_rsa
    ForwardX11      yes
    ProxyCommand    ssh -A CNhost nc %h %p 2>  /dev/null

Now we should be able to simply ssh into the CNInternalhost.
If not the routeing tables need to be checked. (e.g. missing routes or wrong metrics)

But we also want to access a service on this internalhost directly from our local workstation!
For this we  now create the tunnel using the hops preconfigured in the .ssh/config
ssh -L <portOnLocalhost>:CNInternalhost:<portOnCNInternalHost> CNhost

Now we can access CNInternalhost: < portOnCNInternalHost > on localhost:< portOnLocalhost >
If we want to reuse an additional network name (ServerX) in our local setup, we can add a host alias on our local host for our LAN ip and create an additional tunnel for it.
echo 192.0.0.3 ServerX >> /etc/hosts

This also requires an additonal .ssh/config entry:
# configuring another host on the CN internal network
Host serverX
    User            cnInternalUser
    IdentityFile    ~/.ssh/serverX_id_rsa
    ForwardX11      yes
    ProxyCommand    ssh -A CNhost nc %h %p 2>  /dev/null

with this ssh config we can now create a  tunnel like this
ssh -L serverX:<portOnLocalhost>:serverX:<portOnLocalhost> CNhost

as long as serverX is accessible from CNhost.
And we can do a:
$ wget serverX:<portOnLocalhost>


text:
Q: StitchServiceError {message: "insert not permitted"} mongodb I'm using mongodb stitch for backend with

Users can read all data, but only write their own data

template. Logging in with email/password is working. However when I tried to insert data, I'm getting this error:
StitchServiceError {message: "insert not permitted", name: "StitchServiceError", errorCode: 12, errorCodeName: "ArgumentsNotAllowed", stack: "StitchServiceError: insert not permitted↵    at St…tp://localhost:3000/static/js/0.chunk.js:18077:14"}
message: "insert not permitted"
name: "StitchServiceError"
errorCode: 12
errorCodeName: "ArgumentsNotAllowed"}

What is causing this error?

A: In my case, I was receiving the error while trying to do an insert from within a Realm function. The function was being executed from the realm sdk.
I was able to fix this issue by adding/specifying the field name in the read/write rules within the specific realm app (auth is required)