text:
Q: Using JSON for Android Maps API: Markers not Showing up I am attempting to use JSON in order to create markers on my Google map for my app, but, for some reason, they are not showing up.  The logcat has no errors or warnings, but the markers aren't showing up.
My JSON is hosted here: https://api.myjson.com/bins/4jb09
Here's my Java:
package com.example.toshiba.jsonmap;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author saxman
 */
public class MainActivity extends FragmentActivity {
    private static final String LOG_TAG = "ExampleApp";

    private static final String SERVICE_URL = "https://api.myjson.com/bins/4jb09";

    protected GoogleMap map;

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

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
    }

    private void setUpMapIfNeeded() {
        if (map == null) {
            MapFragment mapFragment = (MapFragment) getFragmentManager()
                    .findFragmentById(R.id.map);
            mapFragment.getMap();
            if (map != null) {
                setUpMap();
            }
        }
    }

    private void setUpMap() {
        // Retrieve the city data from the web service
        // In a worker thread since it's a network operation.
        new Thread(new Runnable() {
            public void run() {
                try {
                    retrieveAndAddCities();
                } catch (IOException e) {
                    Log.e(LOG_TAG, "Cannot retrive cities", e);
                    return;
                }
            }
        }).start();
    }

    protected void retrieveAndAddCities() throws IOException {
        HttpURLConnection conn = null;
        final StringBuilder json = new StringBuilder();
        try {
            // Connect to the web service
            URL url = new URL(SERVICE_URL);
            conn = (HttpURLConnection) url.openConnection();
            InputStreamReader in = new InputStreamReader(conn.getInputStream());

            // Read the JSON data into the StringBuilder
            int read;
            char[] buff = new char[1024];
            while ((read = in.read(buff)) != -1) {
                json.append(buff, 0, read);
            }
        } catch (IOException e) {
            Log.e(LOG_TAG, "Error connecting to service", e);
            throw new IOException("Error connecting to service", e);
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }

        // Create markers for the city data.
        // Must run this on the UI thread since it's a UI operation.
        runOnUiThread(new Runnable() {
            public void run() {
                try {
                    createMarkersFromJson(json.toString());
                } catch (JSONException e) {
                    Log.e(LOG_TAG, "Error processing JSON", e);
                }
            }
        });
    }

    void createMarkersFromJson(String json) throws JSONException {
        // De-serialize the JSON string into an array of city objects
        JSONArray jsonArray = new JSONArray(json);
        for (int i = 0; i < jsonArray.length(); i++) {
            // Create a marker for each city in the JSON data.
            JSONObject jsonObj = jsonArray.getJSONObject(i);
            map.addMarker(new MarkerOptions()
                            .title(jsonObj.getString("name"))
                            .snippet(Integer.toString(jsonObj.getInt("population")))
                            .position(new LatLng(
                                    jsonObj.getJSONArray("latlng").getDouble(0),
                                    jsonObj.getJSONArray("latlng").getDouble(1)
                            ))
            );
        }
    }
}

A: I went ahead and got your code working using an AsyncTask.
Here is how you invoke it in onCreate():
private void setUpMapIfNeeded() {
    if (map == null) {
        MapFragment mapFragment = (MapFragment) getFragmentManager()
                .findFragmentById(R.id.map);
        map = mapFragment.getMap();
        if (map != null) {
            //setUpMap();
            new MarkerTask().execute();
        }
    }
}

Here is the AsyncTask, note that I went ahead and made the markers blue just as an example:
private class MarkerTask extends AsyncTask<Void, Void, String> {

        private static final String LOG_TAG = "ExampleApp";

        private static final String SERVICE_URL = "https://api.myjson.com/bins/4jb09";

        // Invoked by execute() method of this object
        @Override
        protected String doInBackground(Void... args) {

            HttpURLConnection conn = null;
            final StringBuilder json = new StringBuilder();
            try {
                // Connect to the web service
                URL url = new URL(SERVICE_URL);
                conn = (HttpURLConnection) url.openConnection();
                InputStreamReader in = new InputStreamReader(conn.getInputStream());

                // Read the JSON data into the StringBuilder
                int read;
                char[] buff = new char[1024];
                while ((read = in.read(buff)) != -1) {
                    json.append(buff, 0, read);
                }
            } catch (IOException e) {
                Log.e(LOG_TAG, "Error connecting to service", e);
                //throw new IOException("Error connecting to service", e); //uncaught
            } finally {
                if (conn != null) {
                    conn.disconnect();
                }
            }

            return json.toString();
        }

        // Executed after the complete execution of doInBackground() method
        @Override
        protected void onPostExecute(String json) {

            try {
                // De-serialize the JSON string into an array of city objects
                JSONArray jsonArray = new JSONArray(json);
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObj = jsonArray.getJSONObject(i);

                    LatLng latLng = new LatLng(jsonObj.getJSONArray("latlng").getDouble(0),
                            jsonObj.getJSONArray("latlng").getDouble(1));

                    //move CameraPosition on first result
                    if (i == 0) {
                        CameraPosition cameraPosition = new CameraPosition.Builder()
                                .target(latLng).zoom(13).build();

                        map.animateCamera(CameraUpdateFactory
                                .newCameraPosition(cameraPosition));
                    }

                    // Create a marker for each city in the JSON data.
                    map.addMarker(new MarkerOptions()
                            .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE))
                            .title(jsonObj.getString("name"))
                            .snippet(Integer.toString(jsonObj.getInt("population")))
                            .position(latLng));
                }
            } catch (JSONException e) {
                Log.e(LOG_TAG, "Error processing JSON", e);
            }

        }
    }

Result:

Also, if you want customized info windows, you can look at the documentation here.
I went ahead and got a simple example working for this as well.
Code to set up the InfoWindowAdapter:
map.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {

            @Override
            public View getInfoWindow(Marker arg0) {
                return null;
            }

            @Override
            public View getInfoContents(Marker arg0) {

                View v = getLayoutInflater().inflate(R.layout.customlayout, null);

                TextView tLocation = (TextView) v.findViewById(R.id.location);

                TextView tSnippet = (TextView) v.findViewById(R.id.population);

                tLocation.setText(arg0.getTitle());

                tSnippet.setText(arg0.getSnippet());

                return v;

            }
        });

customlayout.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="20dp"
    android:orientation="vertical"
    android:background="#000000">

    <TextView
        android:id="@+id/location"
        android:textColor="#D3649F"
        android:textStyle="bold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/population"
        android:textColor="#D3649F"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

Result:


text:
Q: Generate unique id or class for the canvas tag eveytime a question is asked? I just wanted to know is there any chance I can dynamically generate a random id for my canvas in js/HTML?
I am appending a screenshot of my current work done until now.Current work
In this image, there is a container in which a chart is rendering also there a expand button on the top left which takes to a modal where a zoom image of the same chart shows.
My main concern is, for the first question it shows properly but when I ask second question it is not showing the chart in the second question's container. I think it is getting the same id which is why it is doing it so. I just wanted some references where I can generate new id every time a question is asked?
Is it Possible?? I am a newbie to frontend coding a help would be great

A: You could try generating a random number for the id. If you're getting your questions from an array of objects, just loop through them & set the id to the random number. Something like this should work
  for (let i = 0; i < myArr.length; i++) {
  myArr[i].id = Math.random() * (1000 - 50) + 50;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Modify an existing excel with all columns word wrap property to false I have an issue with my SSRS reports while exporting to excell. The columns are set to word wrap automatically. I searched for this and I did't get any solution and I want to alter the excel file without word wrap ad save it when it creates. Can anyone help me on this or is there any alternate method for this?
regards,
Sivajith

A: In Excel, you can manually remove the wrap by highlighting the entire table and going to the home tab. It'll be mid screen and say "wrap text." Sometimes you have to click it twice to undo the wrap, this is an updating issue that I've really only had occur in large tables. That is the simplest way to fix your problem without getting into SSRS exporting.


text:
Q: How to output everything AFTER a specific string? For example, I have a winsock application that's consistently receiving packets with "*USER" in them. Everything after "*USER" is different in each packet, so how can I output everything after "*USER"? Thanks in advance.
Also important to note that "*USER"'s position in the packet is different each time.
                    size_t start2 = rData.find("*USER");
                    size_t end2 = rData.find(";");

                    cout << rData.substr(start2, end2 - start2);


text:
Q: compiling HTML5 to .exe/.dmg I am currently beginning a project where we want to build an Interactive Whiteboard (educational activities) and deploy via CD-ROM. I want to build the project in HTML5 for it's interactivity and then somehow compile it to both .exe. and .dmg so when the CD-ROM is inserted it autoplays the 'Game'.
How is this possible? Any help/advice would be greatly appreciated. Thank you.

A: I already made a project using pure C (WinAPI) on github that can pack HTML files into single EXE using resources.
http://github.com/dns/WinAPI-Embed-Browser/releases
Use: res://programname.exe/test.html as path to access html files from your EXE file.
From here you also can hide the window border & just showing the content of your HTML app, or even running on fullscreen. This is very useful if you want to make interactive CD-ROM.
On Mac, you can use Delphi/Lazarus TWebBrowser control to load html files. However I don't know if mac program can access files from resource or not.

A: HTML 5 is a browser technology, so I think as long as the pc you are installing on has the latest browsers, installing your app should work fine.
Can you tell us why you want it as a CD-ROM based installation, where as you can easily host it online?

A: You may not need any .exe wrapping. Here is an approach.

Important: your autorun will be often disabled, [not so] quietly. Provide some instructions for running your application  manually.

So:

*

*Google for running a portable version of Firefox or Chrome from a CD. Have the browser prepared. Put it in a [sub]directory representing your CD.

*Put your content there.

*Create a .cmd file to invoke the browser with a command like,
FirefoxPortable.exe index.html

*Create autorun.inf (details googlable) to call the above batch file.

*Make a CD image from that directory. There are lots of CD burning applications that can do that.

*Test.


text:
Q: In MVC.NET project, changing .aspx HTML content does not update site while debugging I'm working on an existing MVC3 project, in VS 2010. The site is running in debug mode, using the VS development server. It's all working ok, but if I make a change to the home page, in Index.aspx, the change does not appear on the web site, unless I stop and restart the project.
I'm new to MVC.NET, so not sure if this is by design. I'm used to a normal web project, where editing an aspx file will have immediate effect if you refresh the page in the browser.
It is really necessary to restart debugging for MVC to recognise a change to an aspx file? Or am I missing something here?


text:
Q: Execution of browser default actions of simulated DOM events I have some code which triggers/simulates DOM events via the DOM API (createEvent, initEvent, dispatchEvent, etc.). For most DOM events such as click there is a browser default action like following a link.
Since JavaScript code execution is single threaded I´m not sure how the execution flow is when my code triggers multiple events in a batch. So let´s say I do this (pseudo code):
for (var i = 0; i < 10; i++) {
  var event = document.body.createEvent('MouseEvent');
  event.initMouseEvent(...);
  document.body.dispatchEvent(event);
}

What will happen? Is my loop first executed completely and after that all events are processed causing the default browser action to trigger and registered event listeners to execute? Or is the code execution interrupted every time dispatchEvent is called to trigger the default action (and the event listeners)?
Thanks

A: Because JS is not multithreaded, each time an event is dispatched it will fire immediately - implementations do not create some queue of events to be fired off at the next cycle.
This is one of the reason the old mutation events have been deprecated. For example, if you add 400 elements to a node, it will fire 400 mutation events (which propagate) slowing down the pretty much everything.
So in your code snippet, every iteration of your loop will create the mouse event, dispatch the mouse event, handle all listeners of the mouse event and then proceed to execute the next iteration of the loop.


text:
Q: Razor syntax For Each with String.Format I am new to Razor syntax in ASP.MVC4 and need to format a string within a loop to provide a run time path to the correct image file.
I am having problems in formatting the string within the For Each list item. Can you have a look at the below and let me know what I'm missing.

    @For Each item As modeltype In Model
        @

            @Code
                dim itemImage as string = String.Format("../../Images/{0}.png", @item.MajorAssembly)
            End Code

    Next

A: Take the @ off of @item.MajorAssembly.  When you are inside an @Code block, everything is considered code and additional @'s are unnecessary.

@For Each item As modeltype In Model
    @

        @Code
            dim itemImage as string = String.Format("../../Images/{0}.png", item.MajorAssembly)
        End Code

Next

Also, if you want, you could put the String.Format call directly into the src like this:

@For Each item As modeltype In Model
    @

Next


text:
Q: Windows 7 boot fails with EFI/Grub/Ubuntu My windows doesn't boot. Here is a screencast.
https://plus.google.com/104553781986069868504/posts/ddRjsxuvtUi
Initial situation
For some special cause, I had two concurrent windows 7 installations and a version of ubuntu (grub boot broken).
How I broke my boot
My computer is configured to work with UEFI (I speak here with boot) so notice that's there is NOT a story about MBR (I think), there's more interesting things about MSR, GPT and EFI on the web...
I tried to install Ubuntu with deleting one of the two windows partitions. This broke everything because Ubuntu doesn't support EFI installation yet. I used the Linux Secure Boot livecd to repair the linux boot. It worked... But I needed to modify the windows loader part to have a fully work installation.
Here is a description of what I did: http://wiki.nekland.fr/index.php/Grub_2_efi
But as you can see on the video, my windows start partition seems to be buggy. I saw two windows and no one works.
(I have an image of my disk if it can help but I can't post it right now)
Thanks for help !

A: Here is the solution for all my problems.
Remember facts :
My computer is using SecureBoot/UEFI/GPT.

*

*I installed Windows

*I installed Ubuntu (on another hdd)

*The boot was broken I restored it with boot-repair

*Ubuntu boot, not windows. Impossible to boot on Windows.

The solution : (and the why)
Ubuntu support secure boot only since the last release (the 13.04 version). When I installed it, Ubuntu made automatically a MBR partition. The part of mistery is how boot-repair came to make a boot with using "MBR for Ubuntu" and "EFI for windows" (which obviously didn't work).
So I :

*

*Removed Ubuntu (because it's more simple to re-install than upgrade to GPT format partition).

*Installed the new version of ubuntu

*Use again boot-repair, which work pretty good this time

If you want to use Ubuntu LTS (no support for secureboot) or another distribution, you have to disable the "secureboot" option from your bios and be sure the partition your distribution create is in "GPT" format.
Hope to be usefull !

A: *

*You should try to repair Windows 7 booting using Windows 7 installation/repair CD/DVD.
Try automatic repair option (should be run up to 3 times with rebooting after each run). If errors persist just run following command:

bcdboot c:\windows - where c: maps to Windows 7 installation drive.

*

*Then run Boot Repair for Linux. It should pick up Windows 7.

An UEFI capable BCD Editor can be downloaded here.


text:
Q: Making a dropdown tab using Angular2.0 and Bootstrap Following the tutorials and examples from angular.io and the static navbar from bootstrap, I have this snippet in the template for app.component

      My Company

Profile

Catalogue

Products on Sale

Contracts

However, nothing happens when you click the dropdown button. The original  had an href, which didn't work because I didn't have a path for it. I tried making another component with those inner
 just so I could add a [routerLink] to the dropdown-toggle, but it gave me an error about how children paths were not allowed.
Any ideas on how I can achieve the dropdown working like in the bootstrap link above? Thanks.

A: I had the same problem. The solution is that you need to use the right derective like that:
import {DROPDOWN_DIRECTIVES} from 'ng2-bs-dropdown/dropdown';
and don't forget to use this in component like :
directives: [ROUTER_DIRECTIVES, DROPDOWN_DIRECTIVES]
That's all. I hope this works for you.


text:
Q: jQuery .on('click) after form submission not assigned any more I am using Gravity Forms in combination with a custom jquery code.
The jquery code assigns a validation to the form before it is submitted and fires a sweetalert if something is missing.
After clicking the submit button of the form the first time, the jquery validations work and the alert is fired.
Because there are submission errors, gravity forms now shows the validation errors too.
When filling out all required fields and clicking on the same submit button again, the jquery validation is not assigned to the button any more and no alert is fired. Why is that? The id of the button is still the same.
The JS code, it works fine, the only problem is, that its not assigned anymore to the submit button of the gravity form when the form is in the validation erros state.
jQuery( "#gform_submit_button_3" ).on('click', (function() {
    //alert ("test");
    var jugend = jQuery("#input_3_5").val();
    var trainer_vorname = jQuery("#input_3_6_3").val();

Solution:
Prevent the Form to be submitted by the following code:
jQuery(document).on( 'click', '#gform_submit_button_3', function (e) {
    e.preventDefault();
    //do what you want with jquery/JS with the form

A: Ok, i found the solution by myself.
With the following JS (added to the wp themes JS section) i can prevent the Gravity Form to be submitted.
jQuery(document).on( 'click', '#gform_submit_button_3', function (e) {
    e.preventDefault();

After that, i use JS to do some form validations. If the form is OK, i am sending the form data with a ajax post request to the server.
Keep in mind that the normal submission hooks are not working when preventing the form submission.


text:
Q: Angular patchValue not working with JsonConverter I have a angular form with a select control which receives it's values from an enum on the server.
<select name="" id="" [formControl]="form.get('myType')">
  <option *ngFor="let type of types"  [value]="+type['key']">
    {{ type['value'] }} ({{  type['key']}})
  </option>
</select>

I've created an example here with the response hard coded in the types variable : stackblitz
I'm now trying to populate the form using the form patchValue method (see setValues button and method).
  setValues() {
    this.form.patchValue({
      myType: 0
    });
  }

In real life this response comes form the server.
The model from the server is as follows:
public class TestModel
{
    public MyType Type { get; set; }
}

So far this works.
If I change the model on the server to include the Json StringEnumConverter attribute:
public class TestModel
{
    [JsonConverter(typeof(StringEnumConverter))]
    public MyType Type { get; set; }
}

The patchValue method is now like this (see setValues2 button and method):
  setValues2() {
    this.form.patchValue({
      myType: 'Type1'
    });
  }

However my value is no longer loaded into the select control.
How can I get around this?
I started creating a directive but I don't know how to intercept the bindings to change the value to the enums key equivalent.
Please help

A: You have set option value as key property from types array
<option *ngFor="let type of types"  [value]="+type['key']">

But in setValues2 method you set form value as type['value'], that's why this method doesn't work. As it expects values 1 or 2, but gets Type2.
I think you can try to set option's value as object from types array
<option *ngFor="let type of types"  [value]="type">

then your methods should set these objects as form value
setValues() {
    this.form.patchValue({
      myType: this.types[0]
    });
  }

  setValues2() {
    this.form.patchValue({
      myType: this.types[1]
    });
  }

A: As your selected item is based on key, however, there is no key with value Type1. So your [value] is null. You can find its key by value and set [value]:
setValues2() {
   this.form.patchValue({
      myType: this.getKey('Type1')
   });
}

getKey(typeName:string) {
    let key = this.types.find(f => f.value === typeName).key;
    return key ? key : 0;
}


text:
Q: How to prove that maximal independent set is equal to maximum independent set in an interval graph? Introduction:
An interval graph $IG$ is a set of intervals on the line, the corresponding interval graph represents each interval with a vertex. if they overlap then the intersection between the corresponding nodes is not null.
The Question:
If:- $IG$ is an interval graph: which contains a set of intervals {$i_1$,$i_2$,$i_3$,$i_4$,$i_5$} as shown in the diagram bellow.

How we can show that maximal independent set of this graph is also a maximum independent set at same time?

My suggestion: since I can find |IS| = 5 because there are no intersection between any intervals; and this is IS can't be extended as I draw them in the second graph:
Now How can I show that it is also maximum ? is it because no way to increase the maximal IS, so does this mean it must be Maximum IS ? I am still confusing to argue on my point view?

A: A "Maximum Independent Set" is a "Maximal Independent Set" with the largest possible cardinality of vertices. Since the intervals are all disjoint, the resulting graph is also disjoint. Clearly the set of all vertices is a maximal independent set due to the disjointness. Clearly it is maximum because its cardinality is equal to the total number of vertices in the graph.


text:
Q: React and fetch requests I have this component which is wired up to a custom hook. Being new to this stuff my best guess is it has to do with useCallback somwhere (or lack thereof) but it's confusing the bejesus out of me because the request for picks never does it. When this gets sent to the Picks component it maps over the picks and the scores to render them. But loadedScores throws a cannot read properties of null error on page reload. To my knowledge that has something to do with the promise not being resolved yet, but if I hard code the score values, the loadedPicks object sends perfectly fine every time no matter how many times I reload the page. Why are the scores passing null but not the picks? Aren't both requests doing the exact same thing? Everything here works absolutely how I want it to as shown with the scores hard coded, but as soon as I try to use the values from the request it blows up.
Here's the main component:
import { useEffect } from "react";

import useHttp from "../hooks/use-http";
import { getScores } from "../lib/api";
import { getPicks } from "../lib/api";
import Picks from "./Picks";

const UserPicks = () => {
  const { sendRequest: scoreRequest, data: loadedScores } = useHttp(getScores);
  const {
    sendRequest: pickRequest,
    status,
    data: loadedPicks,
    error,
  } = useHttp(getPicks, true);

  useEffect(() => {
    pickRequest();
    scoreRequest();
  }, [pickRequest, scoreRequest]);

  if (status === "pending") {
    return
Loading games...
;
  }

  if (error) {
    return
{error}
;
  }

  if (status === "completed" && (!loadedPicks || loadedPicks.length === 0)) {
    return
No Games Found
;
  }

  return (

      <Picks picks={loadedPicks} scores={loadedScores} />

  );
};

export default UserPicks;

the hook:
import { useReducer, useCallback } from "react";

function httpReducer(state, action) {
  if (action.type === "SEND") {
    return {
      data: null,
      error: null,
      status: "pending",
    };
  }

  if (action.type === "SUCCESS") {
    return {
      data: action.responseData,
      error: null,
      status: "completed",
    };
  }

  if (action.type === "ERROR") {
    return {
      data: null,
      error: action.errorMessage,
      status: "completed",
    };
  }

  return state;
}

function useHttp(requestFunction, startWithPending = false) {
  const [httpState, dispatch] = useReducer(httpReducer, {
    status: startWithPending ? "pending" : null,
    data: null,
    error: null,
  });

  const sendRequest = useCallback(
    async function (requestData) {
      dispatch({ type: "SEND" });
      try {
        const responseData = await requestFunction(requestData);
        dispatch({ type: "SUCCESS", responseData });
      } catch (error) {
        dispatch({
          type: "ERROR",
          errorMessage: error.message || "Something went wrong!",
        });
      }
    },
    [requestFunction]
  );

  return {
    sendRequest,
    ...httpState,
  };
}

export default useHttp;

the request file:
const liveUrl = "https://nfl-schedule.p.rapidapi.com/v1/schedules";
const fireUrl =
  "https://office-pool-bc15f-default-rtdb.firebaseio.com/games.json";
const headers = {
  method: "GET",
  headers: {
    "x-rapidapi-host": "nfl-schedule.p.rapidapi.com",
    "x-rapidapi-key": "35cba34c56msh4bdc15a4ca34516p11f9f6jsnb3c53161c895",
  },
};

export async function getGames() {
  const response = await fetch(liveUrl, headers);
  const data = await response.json();
  const games = data.data;

  if (!response.ok) {
    throw new Error("Cannot retrieve games");
  }

  const currentGames = [];
  console.log(games);
  const days = [
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
  ];

  for (const game in games) {
    currentGames.push({
      key: games[game].shortName,
      id: games[game].shortName,
      name: games[game].name,
      visitor: games[game].awayTeam.name,
      host: games[game].homeTeam.name,
      date:
        days[new Date(games[game].date).getDay()] +
        " " +
        new Date(games[game].date).toLocaleDateString() +
        " " +
        new Date(games[game].date).toLocaleTimeString([], {
          timeStyle: "short",
        }),
    });
  }

  return currentGames;
}

export async function getScores() {
  const response = await fetch(liveUrl, headers);
  const data = await response.json();
  const scores = data.data;

  if (!response.ok) {
    throw new Error("Cannot retrieve games");
  }

  const currentScores = [];
  console.log(currentScores);
  for (const score in scores) {
    currentScores.push({
      homeScore: scores[score].homeTeam.score,
      awayScore: scores[score].awayTeam.score,
    });
  }
  return currentScores;
}

export async function getPicks() {
  const response = await fetch(fireUrl);
  const data = await response.json();

  if (!response.ok) {
    throw new Error("Cannot retrieve games");
  }

  const currentPicks = [];

  for (const game in data) {
    currentPicks.push({
      games: data[game].games,
      picks: data[game].picks,
      user: data[game].user,
    });
  }
  console.log(currentPicks);
  return currentPicks;
}


text:
Q: How to highlight an item in selectable without clicking on it (By code)? How to select(highlight) an item in selectable without clicking on it (By code)?
Such that I give it the index of which box to select/higlight
I create them dynamically like that

and
var div = document.getElementById("selectable");
for(i=0; i<list.size; i++)
{
    // It should look like that
    //
Item 1

    var properties = list[i].getProperties();
    var aTag = document.createElement("li");
    //file name or something as ID
    aTag.setAttribute('class',"ui-widget-content");
    aTag.setAttribute('id',i);
    aTag.innerHTML = properties.fileName;
    //file name
    div.appendChild(aTag);
}

A: $('youritem').trigger('click'); will do the job! Easy solution.

A: You can select an index by using eq(). 0 being the first item.
$('item').eq(0).css('background-color','yellow'); //give the first item a yellow background.

Check working example at http://jsfiddle.net/FKvhG/

A: You can use focus(): $('#element').focus();

A: You can use
$("#id").val("example value")

to select an item given its value. You can find the value by index using
$("#id").find("option").eq(index).val()

so putting them together we have
$("#id").val($("#id").find("option").eq(index).val());

which does what you want.

A: If you're select list has the id 'dropdown' and you want to select the first element, then this will work.
The eq() function will select whatever element you want, its zero based.
$('#dropdown').eq(0).attr("selected", true);


text:
Q: Upgrade from older Wix project won't uninstall older instance I've upgraded an old Wix based installer that has both an MSI generating project and a bootstrapper project (in Visual Studio). The bootstrapper sequences the MSI with a check for .Net pre-requisite/download. The new Wix# project just produces an MSI and it is installing and working just fine other than I cannot get it to replace the older installs. I've set the new project UpgradeCode to match what I see in the old MSI project (and which is in the windows registry in the uninstall list). I see the UpgradeCode being generated into the WXF file. But when I couldn't get that to work I tried setting it to match the UpgradeCode from the self-installing bootstrapper (which is what the end user runs). That didn't help.
I've read about similar experiences here and here. I've also set the upgrade strategy a few different ways including:
            project.MajorUpgrade = MajorUpgrade.Default;

And:
            project.MajorUpgrade = new MajorUpgrade
            {
                Schedule = UpgradeSchedule.afterInstallInitialize,
                AllowDowngrades = true,
                IgnoreRemoveFailure = true,
                AllowSameVersionUpgrades = false
            };

And:
            project.MajorUpgradeStrategy = new MajorUpgradeStrategy
            {
                RemoveExistingProductAfter = Step.InstallInitialize,
                UpgradeVersions = new VersionRange
                {
                    Maximum = project.Version.ToString(),
                    IncludeMaximum = false,
                    MigrateFeatures = false
                },
                PreventDowngradingVersions = new VersionRange
                {
                    Minimum = project.Version.ToString(),
                    IncludeMinimum = false
                },
                NewerProductInstalledErrorMessage = "A newer version of [ProductName] is already installed. Setup will now exit."
            };

And various variations on those themes. Nothing I've done has impacted behavior, which is to say after installing, both the old and the new version of the application is listed in the add/remove Windows list. Is there some missing secret sauce to this migration path?
UPDATE:
I've realized my last snippet attempt there is actually working*. It's triggering the removal of everything except the entry in the Windows add/remove programs! Can this be due to a name change for the application in the new installer? Or maybe it's remaining around due to the old bootstrapper somehow, since I'm using the UpgradeCode from the old MSI and not doing anything specific with the bootstrapper?
UPDATE2:
The "old" installer has both an MSI and EXE (bootstrapper) version of the setup. If I just install using the old MSI, then run the new MSI, all works perfectly. So it seems that it is something related to running the bootstrapper EXE that is not getting removed.


text:
Q: objective c XMLWriter I am wanting to know how to add text from a variable into an xml writer.
This is what I am trying to do below
NSString *testString = [[NSString alloc] initWithString:@"TEST TEST TEST"];
    //allocate serializer
        id <XMLStreamWriter> xmlWriter = [[XMLWriter alloc] init];
        //add root element
        [xmlWriter writeStartElement:@"Rows"];
            [xmlWriter writeStartElement:@"Row"];
                [xmlWriter writeCharacters:@"request: %@ can go in here", testString]; //this line here
            [xmlWriter writeEndElement];
        //close rows element
        [xmlWriter writeEndElement];

so pretty much how you do an nslog.. but i would like to know how i can do this with xmlwriter.. or if its even possible?
otherwise i guess the other option would be to create the whole string outside of the xmlwriter? what do you think?

A: Try this:
[xmlWriter writeCharacters:[NSString stringWithFormat:@"request: %@ can go in here", testString]]; //this line here


text:
Q: create aws user with s3 permissions with aws cdk I am trying to convert this CF template to AWS CDK:
Resources:
  S3User:
    Type: AWS::IAM::User
    Properties:
      Policies:
      - PolicyName: UserS3Access
        PolicyDocument:
          Version: '2012-10-17'
          Statement:
          - Sid: AllowUserToSeeBucketListInTheConsole
            Action:
            - s3:ListAllMyBuckets
            - s3:GetBucketLocation
            Effect: Allow
            Resource:
            - arn:aws:s3:::*
          - Sid: AllowRootAndUploadsBucket
            Action:
            - s3:ListBucket
            Effect: Allow
            Resource:
            - Fn::Join:
              - ''
              - - 'arn:aws:s3:::'
                - Ref: UploadBucket
            Condition:
              StringEquals:
                s3:prefix:
                - ''
                - uploads/
                s3:delimiter:
                - "/"
          - Sid: AllowListingOfUploadsFolder
            Action:
            - s3:ListBucket
            Effect: Allow
            Resource:
            - Fn::Join:
              - ''
              - - 'arn:aws:s3:::'
                - Ref: UploadBucket
            Condition:
              StringLike:
                s3:prefix:
                - uploads/*
          - Sid: AllowAllS3ActionsInUploadsFolder
            Effect: Allow
            Action:
            - s3:PutObject
            - s3:GetObject
            - s3:GetObjectVersion
            Resource:
            - Fn::Join:
              - ''
              - - 'arn:aws:s3:::'
                - Ref: UploadBucket
                - "/uploads"
                - "/*"
      Tags:
        - Key: CloudFormationArn
          Value: '#{AWS::StackId}'
  UserAccessKey:
    DependsOn: S3User
    Type: AWS::IAM::AccessKey
    Properties:
      UserName:
        Ref: S3User

Outputs:
  UserAccessKeyID:
    Description: The Access Key for S3 bucket access
    Value:
      Ref: UserAccessKey
  UserAccessKeySecret:
    Description: The Access Key Secret for S3 bucket access
    Value:
      Fn::GetAtt:
        - "UserAccessKey"
        - "SecretAccessKey"

Here is what I have so far:
import { Construct, Stack, StackProps, CfnOutput }  from '@aws-cdk/core';
import { Group, Policy, PolicyStatement, ManagedPolicy, User } from '@aws-cdk/aws-iam';
// import { Bucket } from '@aws-cdk/aws-s3';

const S3AccessGroup = 'S3AccessGroup';
const S3Users = [
  'firstname.lastname@domain.tld',
];

export class CdkIamStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);
    // const bucket = Bucket.fromBucketAttributes(this, 'ImportedBucket', {
    //   bucketArn: 'arn:aws:s3:::my-bucket'
    // });

    const AllowUserToSeeBucketListInTheConsole = new PolicyStatement({
      resources: ["arn:aws:s3:::*"],
      actions: [
        "s3:ListAllMyBuckets",
        "s3:GetBucketLocation"
        ],
    });
    const AllowRootAndUploadsBucket = new PolicyStatement({
      resources: ['arn:aws:s3:::my-bucket'],
      actions: [
        "s3:ListBucket"
        ],
      conditions: {'StringEquals': {
        's3:prefix': [
          'uploads',
          ],
        's3:delimiter': [
          '/',
          ]
        }
      }
    });
    const AllowListingOfUploadsFolder = new PolicyStatement({
      resources: ['arn:aws:s3:::my-bucket'],
      actions: [
        "s3:ListBucket"
        ],
      conditions: {'StringEquals': {
        's3:prefix': [
          'uploads/*',
          ]
        }
      }
    });
    const AllowAllS3ActionsInUploadsFolder = new PolicyStatement({
      resources: ['arn:aws:s3:::my-bucket/uploads/*'],
      actions: [
        "s3:PutObject",
        "s3:GetObject",
        "s3:GetObjectVersion"
        ],
    });

    const UserS3Access = new Policy(this, 'UserS3Access', {
      policyName: "UserS3Access",
      statements: [
        AllowUserToSeeBucketListInTheConsole,
        AllowRootAndUploadsBucket,
        AllowListingOfUploadsFolder,
        AllowAllS3ActionsInUploadsFolder
      ],
    });

    const S3Group = new Group(this, S3AccessGroup, { groupName: S3AccessGroup });
    S3Group.attachInlinePolicy(UserS3Access);

    S3Users.forEach((S3User) => {
      const user = new User(this, S3User, {
        userName: S3User,
        groups: [S3Group]
      });
    });
    // new CfnOutput(this, 'accessKeyId', { value: accessKey.ref });
    // new CfnOutput(this, 'secretAccessKey', { value: accessKey.attrSecretAccessKey });
  }
}

How do I output the accessKeyId and secretAccessKey for each user created?
Is this the correct way to generate users using AWS CDK?
Any advice is much appreciated

A: After creating the user, you need to create the key as well:
    S3Users.forEach((S3User) => {
      const user = new User(this, S3User, {
        userName: S3User,
        groups: [S3Group]
      });
      const accessKey = new CfnAccessKey(this, `${S3User}AccessKey`, {
        userName: user.userName,
      });
      new CfnOutput(this, `${S3User}AccessKeyId`, { value: accessKey.ref });
      new CfnOutput(this, `${S3User}SecretAccessKey`, { value: accessKey.attrSecretAccessKey });
    });

A: Your Users have been created and can be viewed in IAM console. Similar to how you generate your access keys in the console. You have to do the same in the CDK code.
Following code snippets might help you:
AWS CDK v2(2.37.1)
S3Users.forEach((S3User) => {
    // create user
    const user = new User(this, S3User, {
      userName: S3User,
      groups: [S3Group]
    });

    // create access key
    const accessKey = new iam.AccessKey(this, 'AccessKey', { user });

    // display access key and secret access key
    new CfnOutput(this, `${S3User}AccessKeyId`, { value: accessKey.accessKeyId});
    new CfnOutput(this, `${S3User}SecretAccessKey`, { value: accessKey.secretAccessKey });
})


text:
Q: How to install Hp laser jet 1020 plus printer? I'm new to Ubuntu (14.04). I have to print some documents, but I can't set up my printer (Hp laser jet 1020 plus). Please tell me the proper way to set-up and install it.

A: Connect your computer to the printer.  Open a terminal (Ctrl+Alt+T) and enter the command
hp-setup

The program will guide you through the steps of setting up the printer.


text:
Q: fig.canvas.draw() changes axis limits I was stumbled by this crazy matplotlib behavior.
I am using an axis with fixed aspect ratio and the xlimits I'm imposing apparently are not respected by matplotlib.
the snippet of code goes like;
self.ax.axes.set_aspect('equal', 'datalim')

print("setting lower limit to : {}".format(self.lower_xlim))
self.ax.set_xlim(*self.lower_xlim)

self.fig.canvas.draw()
print("current limits are {}".format(self.an_ax.get_xlim()))

And this is the surprising result before and after fig.canvas.draw()
setting upper limit to : (27.308915605285073, 5.034483990001178)
current limits are (34.67169979764313, -2.328300202356875)

Is there a way to fix this ?


text:
Q: How to get OpenVino toolkit to work with Anaconda Environment on Windows 10 I am trying to get the Intel OpenVino toolkit to work on an Anaconda environment. I know Anaconda has a package to get the Openvino tool kit. However, I have already installed the pre-requisite installation for Windows 10. How do I go about setting up the Openvino toolkit to work with the already existing Anaconda Environment?
Any advice would be appreciated.
Thanks in advance!

A: I recommend you to get the pre-requisite in your system first:

*

*Microsoft Visual Studio* with C++ 2019 or 2017 with MSBuild ( I recommend 2019)

*CMake 2.8.12 or higher 64-bit (ensure that this added to your system's path)

*Python 3.5 - 3.7 64-bit ( I recommend 3.6)

*Intel® Distribution of OpenVINO™ toolkit core components (2020.4 is the latest)

Since you already done that, you can proceed to next steps.
create a virtual env : conda create --name
conda activate
(then proceed the next steps of installation here, as in official Openvino documentation provided below)
conda cheat sheet: https://docs.conda.io/projects/conda/en/4.6.0/_downloads/52a95608c49671267e40c689e0bc00ca/conda-chea...
This is Openvino official documentation that shows step by step installation process: https://docs.openvinotoolkit.org/latest/openvino_docs_install_guides_installing_openvino_windows.htm...


text:
Q: Why can't I update the 11th angular to the 12th? at update.angular.io it says enter the following command
npx @angular/cli@12 update @angular/core@12 @angular/cli@12

but I get the following error
npm ERR! cb.apply is not a function
npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\acer\AppData\Roaming\npm-cache\_logs\2021-11-11T08_51_54_023Z-debug.log
Install for [ '@angular/cli@12' ] failed with code 1

after searching the internet I found a solution to remove npm from .. \ AppData \ Roaming
this solution did not help, what could be the cause of the error? I tried to update the packages separately as well, but it also didn't help, could it be that I have yarn and not npn?
help pls.
from logs
0 info it worked if it ends with ok
1 verbose cli [
1 verbose cli   'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\work\\crm\\node_modules\\npx\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'install',
1 verbose cli   '@angular/cli@12',
1 verbose cli   '--global',
1 verbose cli   '--prefix',
1 verbose cli   'C:\\Users\\acer\\AppData\\Roaming\\npm-cache\\_npx\\12492',
1 verbose cli   '--loglevel',
1 verbose cli   'error',
1 verbose cli   '--json'
1 verbose cli ]
2 info using npm@5.1.0
3 info using node@v14.15.0
4 verbose npm-session 931aa2830483b7e5
5 silly install loadCurrentTree
6 silly install readGlobalPackageData
7 http fetch GET 200 http://npm.my-site.com:2222/@angular%2fcli 781ms
8 silly pacote range manifest for @angular/cli@12 fetched in 905ms
9 verbose stack TypeError: cb.apply is not a function
9 verbose stack     at C:\work\crm\node_modules\npx\node_modules\npm\node_modules\graceful-fs\polyfills.js:287:18
9 verbose stack     at FSReqCallback.oncomplete (fs.js:184:5)
10 verbose cwd C:\work\crm
11 verbose Windows_NT 10.0.19041
12 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\work\\crm\\node_modules\\npx\\node_modules\\npm\\bin\\npm-cli.js" "install" "@angular/cli@12" "--global" "--prefix" "C:\\Users\\acer\\AppData\\Roaming\\npm-cache\\_npx\\12492" "--loglevel" "error" "--json"
13 verbose node v14.15.0
14 verbose npm  v5.1.0
15 error cb.apply is not a function
16 verbose exit [ 1, true ]

A: I solved it by downgrading node from 16.x to 14.15 and deleting package-lock.json per the documentation here:
https://gist.github.com/LayZeeDK/c822cc812f75bb07b7c55d07ba2719b3


text:
Q: Number of monomial symmetric polynomials in three variables I am trying to find a reference for a formula regarding the number of monomial symmetric polynomials of degree $m$, in three variables. I believe that this number is given by
$1+\left \lfloor{\frac{m^2+6m}{12}}\right \rfloor $, where $\lfloor{..}\rfloor$ denotes the integer part.
This problem is equivalent, I think, to the number of ways one can select three non-negative integers such that their sum is equal to $m$, ignoring permutations.
Any help appreciated.

A: The number of monomial symmetric polynomials of degree $m$ in $3$ variables
equals the number of partitions of $m$ into at most $3$ parts; the parts stand for the nonzero exponents. Transposing the partition, this also equals the number of partitions of $m$ into parts that are at most $3$ each,
in other words, the coefficient of $X^m$ in the power series expansion of
$$\frac{1}{(1-X)(1-X^2)(1-X^3)}$$
which, according to OEIS A001399, is $\left\lfloor\frac{(m+3)^2+6}{12}\right\rfloor$ whereas your formula equals $\left\lfloor\frac{(m+3)^2+3}{12}\right\rfloor$. These are equal because the square in the numerator is congruent to one of $0,1\pmod{4}$ and to one of $0,1\pmod{3}$, so is never one of $6,7,8\pmod{12}$ where the truncations would differ. In fact, the Maple example there uses your version.
Regarding references: The above OEIS entry refers to

*

*L. Comtet, Advanced Combinatorics, Reidel 1974, p. 110, $D(n)$

Indeed there we find formula [6g'] for $D(n;1,2,3)$,
the number of partitions of $n$ where each part is in $\{1,2,3\}$,
as a corollary of more general theorems.

A: Another expression for these  numbers is
$$
\frac{1}{12}\,{m}^{2}+\frac 1 2\,m+ \frac 1 8\,\cos \left( \pi \,m \right) +\frac 2 9\,\cos \left( \frac 2 3\,\pi \,m \right) +{\frac {47}{72}}.
$$


text:
Q: Total max value with for multiple dependent jQuery-UI Slider I'm trying to make a skills-maker-like interface with 4 jQuery-UI sliders (first time I use this UI library).
Sliders are limited to a total amount (here 10) and I'm trying to stop the increase slide when this limit is reached.
I readed this, this and this but the result is not very usable. The user needs to much time understand how the slider group works. That's why I test to don't change the slider "size" but just bloc the slider increase.
I success to stop the slider. But the linked number continue increseasing.
Here my attempt: http://jsfiddle.net/PXEG2/
I tried that :
function total(){
    var value = parseInt($('#item1').val()) + parseInt($('#item2').val()) + parseInt($('#item3').val()) + parseInt($('#item4').val());
    if(value > 10){
        $('.slider').slider({max: $(this).slider(max)});
    }
}

May be, I don't use the good way ?
Thanks for your help.


text:
Q: Canonical example of a cosheaf Sheaves can, like all modern mathematical constructions and abstractions, be counterintuitive beasts but, like all such constructions, a few examples can allow one to visualise them simply as a generalisation of a natural object (ie. the sets of local functions on a topological space).
I have recently become rather interested in cosheaves- a sort of natural iteration of the sheaf concept- apply the sheaf functor once, and it's contravariant, twice (being terribly careful about covers being preserved in a sensible way) and one gets a covariant construction.
My problem is that this is rather hard to anchor to anything really natural as 'sheaves over sheaves' seems rather difficult to visualise without tying ones brain in knots. So my question, in its broadest terms is 'what do cosheaves look like?' (are they for example, just $\mathcal{F}^{op}$ to some sheaf $\mathcal{F}$ by analogy with various other 'co-constructions'), but more realistically (assuming that I am making assumptions) it is "Can one find a canonical example of a cosheaf that is 'visualisable' in some sense?"

A: So you are probably requiring a more general sort of cosheaf -- I don't really know what you mean by "running the sheaf functor twice" -- but let me maybe provide a simpler description of cosheaves that might answer your question.
One definition of a cosheaf is simply a functor
$F:\mathrm{Open}(X)\to\mathcal{C}$
that sends colimits (unions) to colimits. By formality, we can say this is a sheaf valued in the opposite category
$F:\mathrm{Open}(X)^{op}\to\mathcal{C}^{op}.$
There are a couple of "canonical" examples of cosheaves. One is the cosheaf of compactly supported real valued functions on a space:
$U\rightsquigarrow \{f:U\to\mathbb{R}|\mathrm{supp}(f) \, \mathrm{cpt}\}$
Where the extension function is to extend by zero and partitions of unity should force the cosheaf axiom to hold.
More abstractly, using the colimit-preserving definition, any continuous map of spaces:
$f:X\to Y$
we can build a cosheaf of spaces on $Y$, by assigning to each open set $U\subset Y$
$U\rightsquigarrow f^{-1}(U) \qquad U\cup V \rightsquigarrow f^{-1}(U)\cup f^{-1}(V).$
Another, very closely related canonical example of a cosheaf, is to take $\pi_0(f^{-1}(U))$ and as long as $Y$ is locally connected, this will be a cosheaf. See Jon Woolf's paper The Fundamental Category of a Stratified Space and appendix B in there.
Finally, due to an observation of Bob MacPherson, if we think of a cell complex $X$ as a category with objects the cells $\sigma\in X$ with morphisms given by the face relation $\sigma\subseteq \bar{\tau}$, then a constructible sheaf is equivalent to a functor $F:X\to\mathrm{Vect}$ and a constructible cosheaf $F:X^{op}\to\mathrm{Vect}$. These gadgets are bona fide sheaves and cosheaves in the Alexandrov topology on the associated face relation poset, i.e. open sets are $U\subset X$ such that $x\in U$ $x\leq y$ implies $y\in U$.
Finally, I should say that some of my thesis work applies cosheaves to Morse theory, persistent homology and sensor networks, which should provide some more intuitive examples.


text:
Q: Using emacs org-mode, how to publish the unchanged files in a project? I am running Emacs 24.3 and org-mode 8.25f. When I use M-x org-publish command, the org-mode only convert the new .org files to .html and skip all the others which have not been modified since last publish operation.
However, usually I have some changes in the publish setup and some CSS code changes. I want them to take effect to all the files, not just the recently modified ones.
So, can I tell org-mode not to skip these unchanged files?

A: This should work:
M-: (org-publish "project name" t)

This runs org-publish with FORCE set to t. From the docs:
When optional argument FORCE is non-nil, force publishing all
files in PROJECT.  With a non-nil optional argument ASYNC,
publishing will be done asynchronously, in another process.

As you discovered yourself, a prefix argument will also force Org to publish all files:
C-u M-x org-publish

A: The export dispatcher, which you can summon with C-c C-e in the Org mode, provides the relevant "Force publishing" option under C-f.  Thus, to force-publish the current file, type C-c C-e C-f P f.


text:
Q: Stretch the last element in UIStackView I have vertical UIStackView which has two horizontal UIStackViews, if bottom UIStackView has larger width than UIStackView on the top then UIStackView on the top will be stretched to the width of the bottom UIStackView.
And now I have first element in the top UIStackView stretched, but I want to stretch last element.
Current:

Expected:

How can I achieve this?

A: Assuming your labels have the default Horizontal Content Hugging Priority set to 251 each, change the Green Label to 252

Everything else you should be able to leave as you have it.


text:
Q: Skipping lines and splitting them into columns in python text parser I am attempting to parse a space delimited text file in python 2.7.5 which looks kind of like:
variable         description      useless data
a1                asdfsdf           2342354
            Sometimes it goes into further detail about the
            variable/description here
a2                asdsfda           32123

EDIT:Sorry about the spaces added in the beginning, i did not see them
I want to be able to split the text file into an array with variable and description in 2 separate columns, and cut all the useless data and skip any lines that do not start with a string. The way I have set up my code to start is:
import os
import pandas
import numpy
os.chdir('C:\folderwithfiles')
f = open('Myfile.txt', 'r')
lines = f.readlines()
for line in lines:
    if not line.strip():
        continue
    else:
        print(line)
print(lines)

As of right now, this code skips most of the descriptive lines between variable lines, however some still pop up in the parsing. If I could get any help with either troubleshooting my line skips or help me to get started on the column forming part that would be great! I also do not have a lot of expirience in python. Thanks!
EDIT: A part of the file before code
CASEID            (id) Case Identification                   1   15   AN

MIDX              (id) Index to Birth History                16   1  No
                           1:6

After:
CASEID            (id) Case Identification                   1   15   AN

MIDX              (id) Index to Birth History                16   1  No
                           1:6

A: You want to filter out lines that start with spaces, and split all other lines to get the first two columns.
Translating those two rules into code:
with open('Myfile.txt') as f:
    for line in f:
        if not line.startswith(' '):
            variable, description, _ = line.split(None, 2)
            print(variable, description)

That's all there is to it.

Or, translating even more directly:
with open('Myfile.txt') as f:
    non_descriptions = filter(lambda line: not line.startswith(' '), f)
    values = (line.split(None, 2) for line in non_descriptions)

Now values is an iterator over (variable, description) tuples. And it's nice and declarative. The first line means "filter out lines that start with space". The second means "split each line to get the first two columns". (You could write the first as a genexpr instead of filter, or the second as map instead of a genexpr, but I think this is the closest to the English description.)

A: Assuming no spaces in your variables or descriptions, this will work
with open('path/to/file') as infile:
    answer = []
    for line in file:
        if not line.strip():
            continue
        if line.startswith(' '): # skipping descriptions
            continue
        splits = line.split()
        var, desc = splits[:2]
        answer.append([var, desc])

A: If you are using pandas try this:
from pandas import read_csv
data = read_csv('file.txt', error_bad_lines=False).drop(['useless data'])

If your file is fixed-width (as opposed to comma-separated-values) then use pandas.read_fwf


text:
Q: Bypassing functions that do not exist how would it be possible to bypass functions that are not existing in DM
such that the main code would still run? Try/catch does not seem to work, e..g
image doSomething(number a,number b)
{
    try
    {
    whateverfunction(a,b)
    }
    catch
    {
    continue
    }
}

number a,b
doSomething(a,b)

Also conditioning wont work, e.g..
image doSomething(number a,number b)
{

    if(doesfunctionexist("whateverfunction"))
    {
    whateverfunction(a,b)
    }
}

number a,b
doSomething(a,b)

thanks in advance!

A: As "unknown" commands are caught by the script-interpreter, there is no easy way to do this. However, you can construct a workaround by using ExecuteScriptCommand().
There is an example tutorial to be found in this e-book, but in short, you want to do something like the following:
String scriptCallStr = "beep();\n"
scriptCallStr = "MyUnsaveFunctionCall();\n"

number exitVal
Try { exitVal = ExecuteScriptString(scriptCallStr ); }
Catch { exitVal = -1; break; }

if ( -1 == exitVal )
{
    OKDialog("Sorry, couldn't do:\n" + scriptCallStr )
}
else
{
    OKDialog( "All worked. Exit value: " + exitVal )
}

This works nicely and easy for simple commands and if your task is only to "verify" that a script could run.
It becomes clumsy, when you need to pass around parameters. But even then there are ways to do so. (The 'outer' script could create an object and pass the object-ID per string. Similarly, the 'inner' script can do the same and return the script-object ID as exit-value.)
Note: You can of course also put doesfunctionexist inside the test-script, if you do only want to have a "safe test", but don't actually want to execute the command.

A: Depending on what you need there might also be another workaround solution: Wrapper-functions in a library. This can be useful if you want to run the same script on different PCs with some of which having the functionality - most likely some microscope - while others don't.
You can make your main-script use wrapper methods and then you install different versions of the wrapper method script scripts as libraries.
void My_SpecialFunction( )
{
   SpecialFunction()    // use this line on PCs which have the SpecialFunction()
   DoNothing()          // use alternative line on PCs which don't have the SpecialFunction()
}

My_SpecialFunction( )

I have used this in the past where the same functionality (-stage movement-) required different commands on different machines.


text:
Q: using where statement with a sequence of ids In my table, I have a column that it has a set of users id. its name is users_id.
each id separated with a comma(,).
ex : users_id = '1,2,3,4,5';
if I passed $id=1 to my function, how can I using where statement ?
function($id){
$sql = "select * from content_noti
        where  ??????"
}

A: You can add a leading and a trailing , in the field value in DB.
e.g.
Change
1,2,3,4,5
to
,1,2,3,4,5,

So that every Id has leading and trailing comma ,
Now, update the function body:
function($id){
  $sql = "select * from content_noti
        where  users_id LIKE '%,$id,%'"
}

In this case you don't have any possibility of mistake as if you search user id 1 then you will get only 1 and not 11 or 111 or 1343.
Working Demo

A: if you have multiple ids than it would be better to use IN with query
$sql = "select * from content_noti where id IN  (?)"

if you are looking for reverse than use find_in_set
 $sql = "select * from content_noti where FIND_IN_SET(?, id)";

A: You can use regular expressions in mysql:
function($id){
  $sql = "SELECT * FROM content_noti WHERE users_id REGEXP '(^|,)" . $i . "($|,)'";
}

A: SELECT * from content_noti where users_id = "1" OR users_id = LIKE '%1,%' OR users_id = LIKE '%,1%'

Storing multiple chunks of data as a single comma seperated colum is really poor design for databases and if at all possible you should look into normalizing this by making a coupling table and joining on that.
The performance of the above query will be terrible and it'll be hard to maintain.


text:
Q: PostgreSQL Partitioned table update trigger I have a date-partitioned table (inheritance partitioninng just like the one pg_partman does) which is referenced by quite a few tables in my database. To resolve the FKs checking for referenced field only in the main table (not the partitions) I created a so-called shadow table which holds the primary key and is referenced by the main table. Here's the before and after just to make it clear:
Structure without the shadow table:

Structure with the shadow table:

The table is partitioned on main_part timestamp field.
Here's the DDL for the second ERD:
create table main (
  main_id   int8 not null,
  main_part timestamp,
  primary key (main_id));

create table main_shadow (
  main_id bigserial not null,
  primary key (main_id));

create table sub_one (
  main_id            int8 not null,
  sub_one_data_field text);

alter table main add constraint test_cnstrnt_main_main_shadow_main_id foreign key (main_id) references main_shadow (main_id) on update Cascade on delete Cascade;

alter table sub_one add constraint test_cnstrnt_sub_one_main_shadow_main_id foreign key (main_id) references main_shadow (main_id) on update Cascade on delete Cascade;

Notice the on update/delete cascade statement on sub_one FK constraints. We want all the related rows deleted when the main (referenced) row is.
Inserts are handled in the same fashion the official documentation suggests.
To make deletes work properly a trigger function is created and assigned to the parent and to each child table as follows:
create or replace function test_tfnc_main_delete()
    returns trigger as
$body$
begin
    --'on delete cascade' takes care of the related rows
    delete from main_shadow where main_id = old.main_id;
    return old;
end;
$body$
    language plpgsql volatile;

create trigger test_tg_ad_main_delete
    after delete
    on main
    for each row
    execute procedure test_tfnc_main_delete();

create trigger test_tg_ad_main_p1_delete
    after delete
    on main_p1
    for each row
    execute procedure test_tfnc_main_delete();

create trigger test_tg_ad_main_p2_delete
    after delete
    on main_p2
    for each row
    execute procedure test_tfnc_main_delete();

-- and so on for each partition

However for updates it gets a bit more complicated, since an update can cause a partition change. It is fairly easy to detect if a partition will change just by analyzing the partition field (main_part in this case) and knowing the partitioning rules (e.g. monthly).
The easiest way to move a row from one partition to another (if that is required by an update) is to delete it from the current table and insert it into the parent table (with explicitly set main_id field) and let the insert trigger to take care of the rest. The only problem is that the delete will fire the test_tg_ad_main_delete after delete trigger, removing all the related rows.
The question is:
How can I prevent the said trigger from firing? Or can I use a completely different approach here?
Possible solutions I came up with but I feel like they are far from perfect:

*

*Using alter table [table_name] disable trigger [tg_name], see documentation. Locks the table and thus is not really of any use.

*Adding an update-flag to the shadow-table and changing delete trigger so that it checks the flag before removing any rows: if the flag is set the trigger does nothing (keeps the shadow table record and thus all the related rows in other tables). The flag should be set by the update trigger before deleting the said row a removed right after.

*Change delete trigger so that it deletes from shadow table only if the row is not referenced by any rows in main table or its child-tables. Insert an updated row (this won't cause unique violation on the primary key since each child table has its own unique constraint and no insert is issued on the shadow-table), then delete the old one (thus the delete won't cause shadow-row being removed since its already referenced by the new copy).

Edit 1:
Since there's not much attention I'm going to elaborate on the proposed solutions.
So far the best solution performance vise was the 3rd one. The only flaw I was able to detect is related to the case when an external app orders an insert with explicitly set main_id and it is a duplicate. There's no good way that I can think of to deal with it. However the 2nd solution allows to work this problem around by checking if the update-flag is set (since its the only situation when duplicates are allowed) and raise an UV-exception if its not.
That being said, I guess I'm gonna wait until the end of the week and if no comments or answers are proposed I'm gonna post these proposals as an answer (edit: I never did nor am I willing to).
In any case I'll be glad to hear any thoughts on the topic.


text:
Q: What to do when an API has no documentation I'm currently trying to use a REST API to insert data from Powershell into a Jira custom field made by a certain plugin (Easy links for JIRA). Unfortunately there's no documentation on the required syntax. Does anyone who's run into this plugin know the commands/syntax I'll need to use the REST API (It's quite a small plugin so I'll be surprised if anyone else has seen it)? Failing that, does anyone have any advice on discovering how to use APIs with no/bad documentation i.e. some standard method of making an API return a list of commands and syntax (preferably by using powershell)?
I've tried contacting the developer but haven't heard back from them.
The code I'm using is here, if that's helpful:
function Test-Upload(){
    Param()

        Process{
    $data=@"
    {
    "fields":
    {
        "project":
        {
            "key": "CCWASSET"
        },

        "summary": "Testing Linked Field",
        "issuetype":
        {
            "name": "Asset"
        },
        "description" : "Testing Linked Field"
    },
   "update":{
      "customfield_10500":[
         {
            "set":{
               "type":{
                  "name":"Asset PO",
                  "inward":"Asset",
                  "outward":"Purchase Order"
               },
               "outwardIssue":{
                  "key":""
               }
            }
         }
      ]
   }
}
"@
        return Jira-WebRequest -data $data

    }
}

function Jira-WebRequest(){
    Param(
        [Parameter(mandatory=$false)]$data,
        [Parameter(mandatory=$false)]$requesttype="issue",
        [Parameter(mandatory=$false)]$method="POST",
        [Parameter(mandatory=$false)]$ContentType='application/json'
    )
    Process{
        $path = $("/rest/api/2/$requesttype/")
        $Uri = ""
        [URI]::TryCreate([URI]::new($Settings.Jira.URL),"$path",$([ref]$Uri))

        $Params = @{
            ContentType =  $ContentType
            Body = $data #$(@{"vlan_id"=$vlanID;"port_id"="$portID";"port_mode"="$portMode"} | ConvertTo-JSON)
            Method = $method
            URI = $uri.AbsoluteUri
            Headers =  $JiraHeaders
            #WebSession = $Session
        }

        try{
            $result = Invoke-RestMethod @Params -Verbose
            return $result
        } Catch [System.Net.WebException] {
          $exception = $_.Exception
          $respstream = $exception.Response.GetResponseStream()
          $sr = new-object System.IO.StreamReader $respstream
          $ErrorResult = $sr.ReadToEnd()
          return $ErrorResult
        }
    }
}

A: It doesn't matter if the custom field made by a plugin or by you. At the end it's custom field so since the plugin doesn't have a good documentation, I would recommend you to stay with Atlassian Documentation and update / edit your issues base on official REST API. You can see Atlassian examples with Custom Fields here
What you need to do is you just need to figure out what's the custom field ID and that would be easy by going towards admin panel and clicking on the custom field and check it from URL if you don't want to go to database.
I know it's pain to see API without documents but at least you can workaround it this way.

A: Managed to get it working for this particular plugin. Had to include the ID field as well as the Key of the issue that I want to link to. I'd still be interested to hear if anyone has some tips for working with API's that have no/bad documentation.
  "update":{
      "customfield_10500":[
         {
            "set":{
               "type":{
                  "name":"Asset PO",
                  "inward":"Asset",
                  "outward":"Purchase Order"
               },
               "outwardIssue":{
                  "key":""
                  "ID":""
               }
            }
         }
      ]
   }
}


text:
Q: Android showing multiple views I am relatively new to android programming.I however have basic knowledge of the language and am also good in java.I am developing an app which will have an activity containing a graph,some information about the plotted info and a button.I want to implement it in such a way that i will have two layouts in my activity.In one layout(labeled as number 1 below),i want to plot a graph first.i also want to enable the user to swipe that layout so that the graph disappears and the plotted graph info is displayed.I also want to display screen indicators as illustrated belowIn the lower layout(shaded in my sketch),i want to have a button throughout.Now i don't know how to implement that.Is it through view flipper??I will appreciate your input.

A: I dont have time to explain and write a simple example so
i m posting a copy of simple code i m using in my project
first create like this
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/billboard_ll"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:background="#eeeeee"
    >
    <android.support.v4.view.ViewPager
     android:id="@+id/intro_viewpager"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:layout_margin="15dp"
    >
    </android.support.v4.view.ViewPager>
</LinearLayout>

in your activity-----
IntroWindowAdapter adapter = new IntroWindowAdapter(this, imageUrls);
        ViewPager myPager = (ViewPager) findViewById(R.id.intro_viewpager);
        myPager.setAdapter(adapter);
        myPager.setCurrentItem(0);

this one is adapter
public class IntroWindowAdapter extends PagerAdapter {

    Activity activity;
    String imageUrls[];
    private int lptMargin = 25;

    public IntroWindowAdapter(Activity activity, String[] imageArr) {
        this.imageUrls = imageArr;
        this.activity = activity;
    }

    @Override
    public int getCount() {
        return imageUrls.length;
    }

    @Override
    public void destroyItem(View arg0, int arg1, Object arg2) {
        ((ViewPager) arg0).removeView((View) arg2);
    }

    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
        return arg0 == ((View) arg1);
    }

    @Override
    public Parcelable saveState() {
        return null;
    }

    public Object instantiateItem(View collection, int position) {
        ImageView view = new ImageView(activity);
        view.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
        view.setScaleType(ScaleType.FIT_XY);
        new ImageLoader(activity).loadAndDisplayImage(imageUrls[position], view, Constants.ImageSize.NORMAL);
        ((ViewPager) collection).addView(view, 0);
        return view;

    }
}


text:
Q: WSA com.android.gallery3d Camera Button Does Not Open Camera com.android.gallery3d
command used to start application:
monkey -p com.android.gallery3d -v 500
no crash observed but no camera UI launched
but some shell command executes
logcat monitor
System Info


text:
Q: Login and submit form with web-crawler So in web-crawler I pass and submit data like this
$client = new Client();
$crawler = $client->request('GET', 'link');
$form = $crawler->filter('.default')->form();
$crawler = $client->submit($form, array(
            'login'=>'ud',
            'password'=>'pw'

));

But if I use var_dump($crawler); I realise that I never get data from the website after login because it redirects me and var_dump takes data from the page where I submited.
I want after login to move to the new link to submit a form
$client->followRedirects(true);

redirects me to the new page but I can't find a way to submit there because I can't select the form nth-child but doesn't work
I use Goutte and php 7


text:
Q: Click Listener from jQuery to Javascript I work on a site that recently changed, I track certain clicks on the site through GTM and push it into the dataLayer for Google Analytics.
With the changes to the site I can't use jQuery any more so I'm having to change the following jQuery to Javascript, but I just can't get it to work. The script used to collect the h3 text within the div class 'grid_4' when the div was clicked on. The whole structure has changed now, but the old jQuery one looked like this;
<script>
var h3Tile = $("div[class*='grid_4'] a").find('h3').text();
$("div[class*='grid_4'] a").click(function() {
  dataLayer.push({
    'h3Value' : h3Tile,
    'event' : 'tileClick'
  });
});
</script>

The js I have so far is;
<script>
var outerElement = document.getElementsByClassName('ContentTeaser');
var childElems = outerElement.getElementsByTagName('h1').innerHTML;

var myFunction = function() {
  dataLayer.push({
    'h1Value' : childElems,
    'event' : 'tileClick'
  });
};

for(var i=0;i<childElems.length;i++)
   childElems[i].addEventListener('click', myFunction(), false);

</script>

The only problem is that GTM refuses to accept this, saying;
'Uncaught TypeError: outerElement.getElementsByTagName is not a function'
Which I understand is related to the fact that I am creating an array rather than selecting an individual element, but I was hoping my for loop would handle this? or am I mistaken?
Thank you for any help anyone can offer.
Matt

A: getElementsByTagName is a method found on HTML Elements.
It and (more to the point) getElementsByClassName return an (array-like) HTML Collection, not a single HTML element.
You need to loop over outerElement and call getElementsByTagName on each element in turn instead of trying to call it on the collection itself.

Which I understand is related to the fact that I am creating an array rather than selecting an individual element, but I was hoping my for loop would handle this?

You have two collections. You are looping over the second one, but are trying to treat the first one as a single element.

It would probably be easier to simply use query selector instead:
var childElems = document.querySelectorAll(".ContentTeaser h1");

You then have a couple more problems:

for(var i=0;i<childElems.length;i++)

Since childElems is the value of innerHTML, it is undefined (if you'd called it on an element instead of an html collection then it would be a string instead) so that will throw an error.
Don't use innerHTML (which I already fixed in the query selector example).

childElems[i].addEventListener('click', myFunction(), false);

You are calling myFunction immediately and trying to assign its return value (undefined) as an event handler. Remove the ().


text:
Q: How to add a prefix to all actions with ASP.Net MVC URL Routing? I'm trying to write a MapRoute call that will make any route that is prefixed with "json/" prepend "json" to the action's name.
For instance, a route something like this:
"json/{controller}/{action}"

with "json/Foo/Bar", it should result in:
controller = "Foo"
action = "jsonBar"

Any ideas?

A: I wonder if it wouldn't be better to include json in the route-data and look it up in the action? i.e. when mapping your route, use something like (for the defaults):
new { mode="json", controller = "Home", action = "Index", id = "" }

or map the route as:
"{mode}/{controller}/{action}"

then access this in the controller:
string mode = (string) RouteData.Values["mode"];

(or pass it in as an argument)
Other than that, you could potentially write your own route-handler, but that is a lot of work.


text:
Q: Is it possible to list my uploaded files? Is there any way to check what files I have uploaded (through my questions or answers)?

A: Not really; we use a global app-level key at http://imgur.com for all images uploaded from our network.


text:
Q: Javascript / Google Analytics - Simplify Javascript code We are trying to reduce the javascript load and cleanup a page to improve the pagespeed score and generally make the page faster.
We have some Google Analytics code that looks like this:
    var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-374943-1']);
  _gaq.push(['_trackPageview'<?php echo $trackpage_variable; ?>]);

   (function() {
     var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
     ga.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'stats.g.doubleclick.net/dc.js';
     var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
   })();

</script>

Someone cleaned up the code and removed the entire function, so the code looks like this:
<script type="text/javascript">
    var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-374943-1']);
  _gaq.push(['_trackPageview'<?php echo $trackpage_variable; ?>]);
</script>

However, our Google Analytics stopped reporting as a result.
Is there a better way to clean this code up and get rid of the g.doubleclick.net/dc.js reference?
Thanks in advance

A: You can't use Google Analytics without loading Google Analytics.

ga.async = true;

It's already designed to load asynchronously, so it doesn't block rendering.
Leave it alone.


text:
Q: How to get mini games Can someone please help me figure out how to get to mini games I don't understand it.
I want to play minigames just like TheDiamondMinecart.

A: If you want to know where to play a mini-game, join a server like Mineplex (us.mineplex.com:25565) or Hypixel (play.hypixel.net:25565).
If you want to know how to add a mini-game to your server, look at plugins like CTF if you have a Bukkit server, and many other options are available for many other types of servers.


text:
Q: Проблема со scroll в JS Есть задача: сделать блок с новостями и их прокруткой скроллом. Как только скролл оказывается в самом низу - подгружать новые новости.
У меня есть:
 в котором находятся пока 2 div'а следующей структуры:

Заголовок новости 1

                Lorem ipsum dolor, sit amet consectetur adipisicing elit. Exercitationem sequi repellendus obcaecati necessitatibus maxime? Quisquam quos dolorum nihil corporis obcaecati libero, temporibus, omnis quae rem placeat perferendis ullam numquam. Animi?

Скрипт делает следующее:
const isScrollbarAtBottom = (element) => element.offsetHeight + element.scrollTop == element.scrollHeight ? true : false;

function LoadNews(element) {

    if (isScrollbarAtBottom(element)) {

        let newDiv = document.createElement("div");
        let newPHeader = document.createElement("p");
        let newPText = document.createElement("p");

        newPHeader.textContent = keysIter.next().value;
        newPHeader.style.fontWeight = "bold";

        newPText.textContent = valuesIter.next().value;
        newDiv.appendChild(newPText);
        newDiv.appendChild(newPHeader);
        element.appendChild(newDiv);
    }
}

valuesIter и keysIter указывают на Map, в котором уже заготовлены новости.
И вот чертов парадокс, который я не понимаю, почему отслеживание позиции скролла в конечной позиции успешно происходит только тогда, когда я нажимаю F12, чтобы перейти к отладке и т.д., но не работает при стартовом виде странице?

A: Вместо == в стрелочной функции isScrollbarAtBottom  необходимо использовать >=.
Рабочий вариант:
const isScrollbarAtBottom = (element) => element.offsetHeight + element.scrollTop >= element.scrollHeight ? true : false;


text:
Q: Element implicitly has an any type because expression of type '0'can't be used to index type 'Object' - angular error Property '0' does not exist on type'Object'.ts(7053)
I am getting error where i have written data[0]. I was trying to retrieve data from php database
import { Component,OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-adashboard',
  templateUrl: './adashboard.component.html',
  styleUrls: ['./adashboard.component.css']
})
export class AdashboardComponent {
  title = 'angulardatatables';
  dtOptions: DataTables.Settings = {};

  data = []  ;
  constructor(private http: HttpClient) {
    this.http.get('http://localhost/angular_admin/php/user.php').subscribe(data => {
    this.data = data[0];

    }, error => console.error(error));
  }

  ngOnInit() {
    this.dtOptions = {
      pagingType: 'full_numbers',
      pageLength: 5,
      processing: true
    };
}

}

Can anyone help me here ?


text:
Q: mootools and sprite menu i have a sprite tab menu that i would like to change the image when the user clicks, the problem is that i cant figure out how to do it properly, this is what i have:

and this is the javascript:
var getCategory = $('addCategoryList').getChildren();
getCategory.each(function(li){
    li.addEvent('click', function(){
        this.removeClass('menu-'+this.id+'-inactive').addClass('menu-'+this.id);
    });
});

the problem is that when i click it shows two categories as active as oppose to just the one that was clicked. i named them like that because they all share a common sprite and the only difference between the "menu-id-inactive" and 'menu-id" is the background position which makes the image appear as highlighted when the user clicks/

A: this is not ideal as it does not render itself well to patterns. you really want to reverse it so you .addClass('active') rather than take away an inactive class that is not generic.
if your inactive class was generic, it could still work. as it stands, you need to keep state over what is active and before swapping the classes on the new active, you need to do undo the old active first.
http://jsfiddle.net/dimitar/z3nuq/

one

two

three

four

and then state:
(function() {
    var cList = $('addCategoryList'),
        active = cList.getElement('li.active');

    cList.getElements('li').each(function(li){
        li.addEvent('click', function(){
            active && active.removeClass('active')
            active = this.addClass('active');
        });
    });

})();

though strictly speaking - you can just do in the click cList.getElements('.active').removeClass('active') before you add the active class to the clicked el.

A: Dimitar I agree with most everything, but I feel this approach is better:
http://jsfiddle.net/z3nuq/2/
Basic differences? No need to test for class active, just toggle it.
2nd uses event delegation. attach one event not potentially dozens
3rd feel free to dynamically add items to your list! Event will already be there
4th less code and I hate typing despite what this long winded post might suggest
:)
CODE Difference is only in JS
var cList = $$('#addCategoryList');
cList.addEvent('click:relay(li)', function(e,el){
    el.toggleClass('active');
});


text:
Q: Изменить масштаб изображения Задача состоит в том, чтобы изменять градус поворота и масштаб изображения в Windows Forms с помощью TrackBar'a. С поворотом разобрался, но вот с масштабом все никак.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp5
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }
        private float Ang = 0;
        private float Ang1 = 0;
        Bitmap g = new Bitmap(Imame.Value);

        protected override void OnPaint(PaintEventArgs e)
        {
            e.Graphics.TranslateTransform(g.Width / 2, g.Height / 2);
            e.Graphics.RotateTransform(Ang);
            e.Graphics.DrawImage(g, new Point(-g.Width / 2, -g.Height / 2));
        }

        private void ScaleTransformFloat(PaintEventArgs e)
        {
            e.Graphics.ScaleTransform(Ang1, 1.0F);
            e.Graphics.DrawImage(g, new Point(-g.Width / 2, -g.Height / 2));
        }

        private void numericUpDown1_ValueChanged(object sender, EventArgs e)
        {
            Ang = (float)numericUpDown1.Value;
            Invalidate();
        }

        private void trackBar1_Scroll(object sender, EventArgs e)
        {
            Ang1 = (float)trackBar1.Value;
            Invalidate();
        }
    }
}

A: Можете попробовать после каждого вызова события заново переопределять Bitmap.


text:
Q: Requirement of the Second part of PDL Filtration Lemma I was reading this filtration lemma of PDL in David Harel's book Dynamic Logic.
The Filtration Lemma:
Let $\kappa = \langle W, \mathcal{R}, V\rangle$ be a Kripke model of PDL and let $u, v\in W$:
(i) For all $\psi\in FL(\varphi)$, $u\in V(\psi)$ iff $[u]\in V_{\sim_{FL(\varphi)}}(\psi)$.
(ii) For all $[\alpha]\psi\in FL(\varphi)$,
(a) if $(u,v)\in \mathcal{R}(\alpha)$ then $([u],[v])\in\mathcal{R}_{\sim_{FL(\varphi)}}(\alpha)$;
(b) if $([u], [v])\in\mathcal{R}_{\sim_{FL(\varphi)}}(\alpha)$ and $u\in V([\alpha]\psi)$, then $v\in V(\psi)$.
Here $FL(\varphi)$ is the Fischer-Ladner closure of $\varphi$. $\kappa_{\sim_{FL(\varphi)}} = \langle W_{\sim_{FL(\varphi)}}, \mathcal{R}_{\sim_{FL(\varphi)}}, V_{\sim_{FL(\varphi)}}\rangle$ is the quotient model created wrt $FL(\varphi)$ in a similar way quotient model were created in filtration of modal logic wrt $SF(\varphi)$.
My question is:
What is the requirement of the second part of the lemma (point (ii)) in order to prove decidability? In usual modal logic, the first statement suffices since it shows the new quotient model built is preserving the truth with respect to the closure.


text:
Q: Lightest hardware accelerated desktop system I need a list of lightweight desktop environment that uses hardware acceleration either natively or from being on top of another library like Xlib, GTK+, etc.
What I'm actually looking for is a replacement for the Openbox Desktop System that comes with my CrunchBang Linux. The distro is light enough, but it irks me that moving around the windows and interacting with all the widgets are noticeably slower than my old Windows 7 installation.
I know there are different systems out there with one being lighter on CPU overall or another having a better GPU acceleration support (maybe not from itself, but from better library it sits on top on). Hence my request above for a list of choices.


text:
Q: Assigning custom roles on user creation in Azure AD Azure lets you define custom roles for an AD tenant by modifying the manifest:
 "appRoles": [
{
  "allowedMemberTypes": [
    "User"
  ],
  "description": "Admins can manage roles and perform all actions.",
  "displayName": "Global Admin",
  "id": "some GUID",
  "isEnabled": true,
  "value": "Admin"
}, ... ],

and, according to the msdn azure graph api reference, you can use the graph api to programmatically assign a user to a custom role. But I'm having trouble getting this to work where I'm creating a new user and trying to assign a role using AppRoleAssignment. I think the problem is that I need to define the user's ID, but that is defined by Azure once the user is created, so does that mean it's impossible to assign a user to a role at the point of creation and it can only be done once the user has been added to the directory ? Below is a snippet of the code I'm using to assign the role.
var appRoleAssignment = new AppRoleAssignment();
            appRoleAssignment.Id = Guid.Parse("some-guid-here");
            appRoleAssignment.ResourceId = Guid.Parse(clientId);
            appRoleAssignment.PrincipalId = ??? // what should go here for a user that hasn't been created yet ?

A: Clear appRoleAssignments,appRoleAssignedTo will let us understand the relationships of user role, app role, user, application.
1) an application can be assigned to an User as app role. Open the
User option of an application named "ADlinglitest":

Call:https://graph.windows.net/Tenantid/users/lingliad01@lingliad.onmicrosoft.com/appRoleAssignments?api-version=1.5 get the result:

Call:https://graph.windows.net/tenantid/servicePrincipals/servicePrincipalsobjectid/appRoleAssignedTo?api-version=1.5, you will see 3 user which are assigned.

2)an user can be assigned to an application as user role, group, application also can be assigned to application as a role.
"appRoles": [
{
"allowedMemberTypes": [
    "User"
  ],
  "description": "Admins can manage roles and perform all actions.",
  "displayName": "Global Admin",
  "id": "7c93906c-71fa-4e5b-b1da-21b073d298fd",
  "isEnabled": true,
  "value": "Admin"
}
]

Call:https://graph.windows.net/tanantid/servicePrincipals/serviceprincipalobjectid/appRoles?api-version=1.5 get the result:

if you dont know objectid, call https://graph.windows.net/tanantid/servicePrincipals?api-version=1.5 to get the SP objectid of your application.
3) as you mentioned "User role assignment", actually it lacks a method userRoleAssignedTo, if the user is assigned to an application as user role, we could query the application infor through userRoleAssignedTo.
It is indeed easily let people feel confused.

A: Without the identifier the role cannot be assigned. Objects and identifiers get created when user is created.

A: I dont find the C# code about assign a user to application role in azure official documents. I only can see the Powershell and Rest api method.
Powershell:
New-AzureRmRoleAssignment -ObjectId <application id> -RoleDefinitionName <role name in quotes> -Scope <subscription id>
REST API:
PATCH -- https://graph.windows.net/tenantid/application/clientid?api-version=1.5
BODY should like this,the id is the objectid of the user:
{
  "appRoles": [

    {

  "allowedMemberTypes": [
  "User", "Application"
  ],
  "description": "Dentists may create, update and delete patient's health records",
  "displayName": "Dentist",
  "id": "31952ade-a03c-414c-8340-2f11e9099106″,
  "isEnabled": true,
  "value": "dentist"

     }
]

Rest api in C# example:
    AuthenticationContext ac =
                    new AuthenticationContext("https://login.microsoftonline.com/tenantid");
                AuthenticationResult ar =
                    ac.AcquireToken("https://graph.windows.net",
                                    new ClientCredential(Constants.ClientId, Constants.ClientSecret));

                string result = string.Empty;
                HttpClient httpClient = new HttpClient();
                httpClient.DefaultRequestHeaders.Authorization =
                    new AuthenticationHeaderValue("Bearer", ar.AccessToken);
                HttpResponseMessage response =
                    httpClient.PostAsync("https://graph.windows.net/tenantid/application/clientid?api-version=1.5","json/body").Result;
if (response.IsSuccessStatusCode)
                {
                    result = response.Content.ReadAsStringAsync().Result;
                }
                Console.WriteLine(result);
                Console.ReadLine();


text:
Q: Laravel controllers and routes in packages? I'm having trouble registering controllers to routes in my package.
As far as I understand from the official documentation I just need to simply prefix it and use my namespace though I always get the error of xyzclass not found.
Anyone could explain to me how can I make this work?

-- Vendor
    -- Package
        |-- composer.json
        |-- composer.lock
        |-- public
        |-- src
        |   |-- Vendor
        |   |   -- Package
        |   |       -- PackageServiceProvider.php
        |   |-- config
        |   |-- controllers
        |   |   -- MyController.php
        |   |-- lang
        |   |-- migrations
        |   |-- routes.php
        |    -- views
        |-- tests

I loaded my routes.php in my serviceprovider file.
I created and index function in MyController.php and assigned it in my routes.php.
Route::contorller('myctrl', 'Vendor\Package\MyController');

And in theory I should be able to access mydomain.com/myctrl and it should give me back
what I defined in MyController's index function. But in reality I get an error saying  Class Vendor\Package\MyController does not exists. Any advice or help how should this work or how it's working?

A: Guess I'm dumb, forgot some little details.
I should use a proper namespace next time, and adding the controllers folder to my composer.json helped too.
I found a nice and detailed description on how to do this here:
https://stackoverflow.com/a/18137352/1397967

A: Route::contorller('myctrl', 'MyController');

This is linked to src/controllers/ not to vendor


text:
Q: Variable de PHP funciona al hacer echo pero no en query Tengo un problema y es que estoy intentando ejecutar un código php para obtener información de la base de datos. El problema es que tengo una variable llamada $user_id que si le hago echo, si me muestra el id, pero cuando lo meto en el query no funciona. Es un id numérico.
$user_id = "{{ proposal_seller_id }}";
echo $user_id; //esto si lo muestra
$seleccionar = $db->query("SELECT * FROM users WHERE user_id='" . $user_id . "'"); //aquí el user_id es 0
$row = $seleccionar->fetch();
$user_name = $row->user_name;
echo $user_name; // y aquí no muestra nada ya que el query no funciona

Muchas gracias y espero que alguien pueda ayudarme.


text:
Q: GetLegendGraphic with Filtered Range Rules I have a style with several rules that include range filters. I'm having a hard time getting the appropriate legend graphic for a specific record.
For example, a soil depth of 3 should return the legend icon for "Shallow", but when passed as a rule, I get "Specified style does not contains a rule named 3", an accurate error, the rule's name for that value is "Shallow". If I try to pass it as a featuretype, I get the full legend and not just the icon for that rule.
Surely there's a way to do this in Geoserver, is my style simply configured in a round about way?
Style w/ 1 rule for simplicity
<?xml version="1.0" encoding="UTF-8"?><sld:StyledLayerDescriptor xmlns="http://www.opengis.net/sld" xmlns:sld="http://www.opengis.net/sld" xmlns:gml="http://www.opengis.net/gml" xmlns:ogc="http://www.opengis.net/ogc" version="1.0.0">
<sld:NamedLayer>
  <sld:Name>soil_depth</sld:Name>
  <sld:UserStyle>
    <sld:Name>soil_depth</sld:Name>
    <sld:FeatureTypeStyle>
      <sld:Name>soil_depth</sld:Name>
      <sld:Rule>
        <sld:Name>Shallow</sld:Name>
        <sld:Title>Shallow</sld:Title>
        <ogc:Filter>
          <ogc:And>
            <ogc:PropertyIsGreaterThanOrEqualTo>
              <ogc:PropertyName>depth</ogc:PropertyName>
              <ogc:Literal>0</ogc:Literal>
            </ogc:PropertyIsGreaterThanOrEqualTo>
            <ogc:PropertyIsLessThan>
              <ogc:PropertyName>depth</ogc:PropertyName>
              <ogc:Literal>5</ogc:Literal>
            </ogc:PropertyIsLessThan>
          </ogc:And>
        </ogc:Filter>
        <sld:MaxScaleDenominator>512000.0</sld:MaxScaleDenominator>
        <sld:PolygonSymbolizer>
          <sld:Fill>
            <sld:CssParameter name="fill">#68B7FF</sld:CssParameter>
            <sld:CssParameter name="fill-opacity">.4</sld:CssParameter>
          </sld:Fill>
        </sld:PolygonSymbolizer>
      </sld:Rule>
    </sld:FeatureTypeStyle>
  </sld:UserStyle>
</sld:NamedLayer>
</sld:StyledLayerDescriptor>

Request w/ rule

https://domain.com/geoserver/workspace/wms?REQUEST=GetLegendGraphic&services=WMS&version=1.1.1&format=image%2Fpng&layer=soil_depth&transparent=true&legend_options=forceLabels%3Aoff&height=20&width=20&rule=3

Response w/ rule -- this makes sense
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE ServiceExceptionReport SYSTEM "https://gsdev.pivvot.com/geoserver/schemas/wms/1.1.1/WMS_exception_1_1_1.dtd">
<ServiceExceptionReport version="1.1.1" >
    <ServiceException>
      Specified style does not contains a rule named 3
</ServiceException>
</ServiceExceptionReport>

Request w/ featuretype

https://domain.com/geoserver/workspace/wms?REQUEST=GetLegendGraphic&services=WMS&version=1.1.1&format=image%2Fpng&layer=soil_depth&transparent=true&legend_options=forceLabels%3Aoff&height=20&width=20&featuretype=3

Response w/ featuretype -- does not make sense

Desired response