text:
Q: Room Database entries in RecyclerView I want to show Room Database entries in a RecyclerView. So far I have the Room skeleton and I can show some dummy content (not from Room) in the RecyclerView:

However I have struggles showing Room DB entries instead of the dummy content. In Arduino the EEPROM I/O stuff used to be almost a oneliner but within Android Room this conceptually easy task seems to be a code-intense and not-so-forward challenge. This brings me to my first question:
1) As in my case the database is pretty slim and simple, is there any simpler approach than Room using less overhead and classes?
Regarding the Room approach, I believe that I am pretty close. I have difficulties implementing the following:
2) How can I substitute the for-loop in init DummyContent by the Room-DB entries (allJumps from ViewModel)?
Here is what I got so far (I didn't post anything below the ViewModel such as Repository and DAO's as it should not of interest right now):
DummyItems (dummy contents to be replaced by Room DB entries)
object DummyContent {

    // An array of sample (dummy) items.
    val ITEMS: MutableList<DummyItem> = ArrayList()

    // A map of sample (dummy) items, by ID.
    val ITEM_MAP: MutableMap<String, DummyItem> = HashMap()

    private val COUNT = 25

    init {
        // Add some sample items.
        // TO BE REPLACED BY ROOM DB ENTRIES <----------------------------------------------------
        for (i in 1..COUNT) {
            addItem(createDummyItem(i))
        }
    }

    private fun addItem(item: DummyItem) {
        ITEMS.add(item)
        ITEM_MAP.put(item.id, item)
    }

    private fun createDummyItem(position: Int): DummyItem {
        return DummyItem(position.toString(), "Item " + position, makeDetails(position))
    }

    private fun makeDetails(position: Int): String {
        val builder = StringBuilder()
        builder.append("Details about Item: ").append(position)
        for (i in 0..position - 1) {
            builder.append("\nMore details information here.")
        }
        return builder.toString()
    }

    // A dummy item representing a piece of content.
    data class DummyItem(val id: String, val content: String, val details: String) {
        override fun toString(): String = content
    }
}

allJumps / JumpData
// allJumps is of type LiveData<List<JumpData>>

@Entity
data class JumpData (
    @PrimaryKey var jumpNumber: Int,
    var location: String?
}

ViewModel
class JumpViewModel(application: Application) : AndroidViewModel(application) {

    // The ViewModel maintains a reference to the repository to get data.
    private val repository: JumpRepository
    // LiveData gives us updated words when they change.
    val allJumps: LiveData<List<JumpData>>

    init {
        // Gets reference to WordDao from WordRoomDatabase to construct
        // the correct WordRepository.
        val jumpsDao = JumpRoomDatabase.getDatabase(application, viewModelScope).jumpDao()
        repository = JumpRepository(jumpsDao)
        allJumps = repository.allJumps // OF INTEREST <----------------------------------------------------
    }

    fun insert(jump: JumpData) = viewModelScope.launch {
        repository.insert(jump)
    }

    fun getJumps() : LiveData<List<JumpData>> {
        return allJumps
    }
}

A: You can try to add this to object DummyContent
object DummyContent {
    val jumpsLiveData = MutableLiveData<List<JumpData>>()

    private val observedLiveData: LiveData<List<JumpData>>? = null
    private val dataObserver = object : Observer<List<JumpData>> {
        override fun onChanged(newList: List<JumpData>) {
            // Do something with new data set
        }
    }
    fun observeJumpsData(jumpsLiveData: LiveData<List<JumpData>>) {
        observedLiveData?.removeObserver(dataObserver)
        observedLiveData = jumpsLiveData.apply {
            observeForever(dataObserver)
        }
    }
}

And this to viewModel's init block:
init {
        val jumpsDao = JumpRoomDatabase.getDatabase(application, viewModelScope).jumpDao()
        repository = JumpRepository(jumpsDao)
        allJumps = repository.allJumps
        DummyContent.observeJumpsData(getJumps())
    }

By this code, DummyContent will automatically subscribe to new data after ViewModel creation
And in 'Activity', where you created RecyclerView, add this text to end of onCreate:
override fun onCreate(savedState: Bundle?) {
  DummyContent.jumpsLiveData.observe(this, Observer {
    recyclerAdapter.changeItemsList(it)
  }
}

changeItemsList - method that changes your recycler's data, i believe, you already created it


text:
Q: Sublime Text 2 doesn't render text properly if I start the application with my Acer display attached I'm using a Macbook Air. If I start Sublime Text with no external displays and then attach the display everything looks fine.
But, if I attach the display first and then start Sublime Text the text is less vivid and sharp on both the external display and the Macbook display.
Left is what the text looks like when I plug in the display after starting Sublime Text. Right is what it looks like when I plug in the display first.

Details:
Macbook Air w/ OSX 10.7.2
Sublime Text 2 Beta 2165
Acer 24 inch display model X233HZ

A: I found the answer in the Sublime text forums here:
http://www.sublimetext.com/forum/viewtopic.php?f=2&t=4342&p=20036#p20036
This fix worked for me.

I did some more digging on this and it turns out it has something to do with how OSX renders fonts for certain LCD monitors. I was experiencing this with my MacBook Air when attached to a Samsung LCD monitor. However, there was no issue when just using the Macbook Air on it's own or with my Apple Cinema Display.
Here is what I did to fix it. Run the following code in Terminal:
defaults -currentHost write -globalDomain AppleFontSmoothing -int 2
Then restart your system. Once OSX booted up again, the problem was gone. You can read more about this here:

A: I've tested this for you on my iMac with both external monitor and no external monitor and I could not replicate the problem. I would possibly say that it has something to do with the graphics chip on the air struggling to render the application correctly. As you Macbook air needs to render your laptop screen plus the 24inch screen.
Also Sublime uses hardware rendering as opposed to software rendering as shown on their website. http://www.sublimetext.com/x
Software rendering. Sublime Text uses hardware rendering, while X uses software rendering. This eliminates the single biggest source of user problems with Sublime Text, and preserves full functionality when running under a virtual machine.
Hope this helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: EBike Controller - Does 'current' affect driving speed? I wanted to ask if a brushless controller Current actually affects electric bicycle speed.
At the moment I have a 48V 250W brushless controller, rated current of 5A and maximum current of 10A. protection voltage is 42V.
Here is a more detailed picture about my controller plugs, etc:

So my main question is: if I switch to a same brushless controller but just this time with lets say a maximum Current of 17A, will it make any difference in any way?
I also tried talking with the manufacturer and I didn't get a flat answer; they said it won't affect on the speed but I read in a few places that it might.
My Battery: 48V 13Ah
My Motor: 48V 250W ( model: bafang swx02 )
Also another question, is there any way to make my ebike drive faster than 25 km/h without switching the motor?

A: To a first approximation (a flat, level road), increasing the current capability (not the current) will have no effect on your speed.
A BLDC motor is effectively driven at a certain AC frequency, and the motor turns at one revolution per cycle of the drive. As long as the motor gets enough current to produce the force necessary to overcome friction and drag, increasing the current available won't change anything. And you should note that, from a power perspective, it's clear that your battery and motor are well-matched. The motor is rated for 5 amps @ 48 volts (peak 10 amps), for a total of 240 watts (480 peak). The motor is rated for 250 watts, so the motor is the limiting factor.
So the first thing you would need to do is replace the motor. However, you would also probably need to replace the controller as well. I suspect there is a speed limiter somewhere in there.

A: The motor will draw whatever current it wants to unless the speed controller limits current for torque control or to protect itself. If your motor would normally draw less than 5A at top speed then using a higher rated controller won't make a significant difference (it might be very slightly faster due to lower voltage drop across the FETs in the controller).
Motor speed is proportional to voltage. If you want more speed (and can't gear it up) then use a higher voltage battery. Just realize that it will draw more power, which may damage the motor or controller if their ratings are exceeded. You will need a higher voltage controller as well as extra batteries, so you might consider replacing the entire drive chain.

A: Voltage correlates to raw (unloaded) speed, current correlates to torque and overall power (loaded speed). The current handling of your motor is going to limit your speed. There won't really be a way to go faster without changing out your motor.

A: open the controller, find the shunt and add a bit of solder it will increase amps output allowing more torque, as well as speed if the current was limited down low enough (which 5A sounds a little low to me) this would cost a bit off of the battery range.


text:
Q: Spring boot data hibernate different datasources I am playing with spring-boot and spring-boot-data-jpa. I need that @Entity class A {...} uses hsqlDatasource and @Entity class B {...} use mssqlDatasource. How can I achieve that?
I would like to do something like this:
@Repository
@UseDatasource("hsql")
interface A extends CrudRepository....

A: Spring Data supports this pattern through @EnableJpaRepositories(entityManagerFactoryRef=...). To make it work with Spring Boot you could create your 2 DataSources, mark one of them @Primary and it will be used by the auto-configured entityManagerFactory bean. Then you add another and refer to them both individually in your 2 @EnableJpaRepositories annotations.
I suppose you could even create a custom annotation for each of the two repository types and use it in @EnableJpaRepositories(includeFilters=...), but if I were you I would get it working with a package scan first (i.e. just put the repositries for the 2 data source targets in different packages).


text:
Q: Create constructor of DataBase class within Activity Please don't throw stones at me, but I can't really get and find the answer Why I can't call a method from class DB inside of MainActivity...
Seems like I didn't do anything wrong, but...
NullPointerException everytime I'm trying, what I'm doing wrong?
Thanksfull to any answer!
public class MainActivity extends ActionBarActivity{

        SQLiteDatabase db;
    DBHelper dbHelper;
    DB mDB;

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

            dbHelper = new DBHelper(this);
            db = dbHelper.getReadableDatabase();

            mDB = new DB();
            mDB.fillListView();

        }

and second class with the method
public class DB {

    final String LOG = "phonebookLogs";
    private static final String TABLE_NAME = "contacts";
    private static final String COL_NAME = "name";
    private static final String COL_SURNAME = "surname";
    private static final String COL_BIRTHDAY = "birthday";
    private static final String COL_SEX = "sex";
    private static final String COL_ADRESS = "adress";
    private static final String COL_LINK = "link";
    private static final String ID = "_id";

    Cursor c;

    public void fillListView(){
        c = db.query(TABLE_NAME, null, null, null, null, null, null);
        if(c != null){
            if(c.moveToFirst()){
                do{
                    String[] names = {c.getString(c.getColumnIndex(COL_SURNAME)) + " "
                            + c.getString(c.getColumnIndex(COL_NAME))};
                    int[] links = {c.getInt(c.getColumnIndex(COL_LINK))};
                    if(links[0] == 0){
                        links[0] = R.drawable.default_contact;
                    }

                    Log.d(LOG, "\n" + links[0] + " " + names[0]);
                }while(c.moveToNext());
            }
        }else{
            Log.d(LOG, "Cursor is null!");
        }

    }
}

Log
07-06 23:37:09.929: E/AndroidRuntime(10952): FATAL EXCEPTION: main
07-06 23:37:09.929: E/AndroidRuntime(10952): Process: com.nixsolutions.phonebook, PID: 10952
07-06 23:37:09.929: E/AndroidRuntime(10952): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nixsolutions.phonebook/com.nixsolutions.phonebook.MainActivity}: java.lang.NullPointerException
07-06 23:37:09.929: E/AndroidRuntime(10952):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2202)
07-06 23:37:09.929: E/AndroidRuntime(10952):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2252)
07-06 23:37:09.929: E/AndroidRuntime(10952):    at android.app.ActivityThread.access$800(ActivityThread.java:139)
07-06 23:37:09.929: E/AndroidRuntime(10952):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1200)
07-06 23:37:09.929: E/AndroidRuntime(10952):    at android.os.Handler.dispatchMessage(Handler.java:102)
07-06 23:37:09.929: E/AndroidRuntime(10952):    at android.os.Looper.loop(Looper.java:136)
07-06 23:37:09.929: E/AndroidRuntime(10952):    at android.app.ActivityThread.main(ActivityThread.java:5103)
07-06 23:37:09.929: E/AndroidRuntime(10952):    at java.lang.reflect.Method.invokeNative(Native Method)
07-06 23:37:09.929: E/AndroidRuntime(10952):    at java.lang.reflect.Method.invoke(Method.java:515)
07-06 23:37:09.929: E/AndroidRuntime(10952):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
07-06 23:37:09.929: E/AndroidRuntime(10952):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:606)
07-06 23:37:09.929: E/AndroidRuntime(10952):    at dalvik.system.NativeStart.main(Native Method)
07-06 23:37:09.929: E/AndroidRuntime(10952): Caused by: java.lang.NullPointerException
07-06 23:37:09.929: E/AndroidRuntime(10952):    at com.nixsolutions.phonebook.DB.fillListView(DB.java:26)
07-06 23:37:09.929: E/AndroidRuntime(10952):    at com.nixsolutions.phonebook.MainActivity.onCreate(MainActivity.java:63)
07-06 23:37:09.929: E/AndroidRuntime(10952):    at android.app.Activity.performCreate(Activity.java:5275)
07-06 23:37:09.929: E/AndroidRuntime(10952):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
07-06 23:37:09.929: E/AndroidRuntime(10952):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2166)
07-06 23:37:09.929: E/AndroidRuntime(10952):    ... 11 more

A: Make dbHelper and db members of DB class
Change fillListView
public void fillListView(Context context){
    dbHelper = new DBHelper(context);
    db = dbHelper.getReadableDatabase();
    c = db.query(TABLE_NAME, null, null, null, null, null, null);

Call it as
mDB.fillListView(this)


text:
Q: Send string to php server and use it Im trying to send a string to a php server, but for some reason, Im not able to read the string on the server... I tried many ways to type it well but it seems like I never got the correct syntax. Anyone have clues?
var command="";
if(document.getElementById("Text_1").value != "" && document.getElementById("Text_2").value != "")
        {
            command += " " + document.getElementById("Text_1").value + " " + document.getElementById("Text_2").value;
        }

        alert(command);

        xmlhttp.open("POST", "server.php", false);
        xmlhttp.setRequestHeader('info', command)
                     //TRIED xmlhttp.setRequestHeader("info, command")
                     //TRIED xmlhttp.setRequestHeader('info', 'command')
                     //TRIED many others sketchy things...
        xmlhttp.send();
        //TRIED xmlhttp.send(command);
        var output = xmlhttp.responseText;

On php server :
<?php

$parameter = $_POST['command'];

$output = exec("someexecutable.exe $parameter");

echo json_encode($parameter);
?>

For them wondering, if I hardcode $parameter with a right string, it works, so the executable isn't the problem. The server just cant get the value of the string in $_POST.

A: setRequestHeader is used to set headers on the request.  Things like Content-type and Content-length.
You need to pass the data to send().  For $_POST to work, they need to be in key=val&vey2=val2 format.  Actually, in newer browsers, you can use FormData.
xmlhttp.open("POST", "server.php", false);

// To emulate a `<form>` POST
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

// To get the response, you need to set a callback
xmlhttp.onreadystatechange = function(){
    // readyState 4 = complete
    // status = 200 OK
    if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
        var output = xmlhttp.responseText;
    }
};

// Create the Form Data
var params = new FormData;
params.append('command', command);

xmlhttp.send(params);

P.S. You should run escapeshellarg() before running your command.  This could be worse than just SQL injection if people can run arbitrary commands on your server.
<?php
$parameter = escapeshellarg($_POST['command']);
$output = exec("someexecutable.exe $parameter");
?>

P.P.S. escapeshellarg() will make your command treat the entire $_POST['command'] string as one parameter.  If you don't want that, then you'll need to POST an array from your JavaScript.
// Create the Form Data
var params = new FormData;
params.append('command[]', document.getElementById("Text_1").value);
params.append('command[]', document.getElementById("Text_2").value);

xmlhttp.send(params);

Now $_POST['command'] will be an array, so you'll have to run the command like so:
<?php
$parameters = array_map('escapeshellarg', $_POST['command']);
$output = exec("someexecutable.exe ".implode(' ', $parameters));
?>


text:
Q: How to get a working DOCUMENT_ROOT value on IIS server? I've been working with Linux servers I think about 98% of my development time. And for more or less the first time I'm putting code onto some IIS server.
I work on a Linux Env so everything works as I'd expect it to, however getting to the IIS server and everything falls apart. I'll save everyone a massive rant about why IIS and Windows sucks and get to the issue in hand.
Use of $_SERVER['DOCUMENT_ROOT'] on my env outputs a value like:

/var/www/project

Which is good for including files e.g.
require_once $_SERVER['DOCUMENT_ROOT']. '/app/connect.php';

However, on IIS this errors with the message:

No such file or directory

This made me prefix the code with this:
echo '
'. print_r($_SERVER['DOCUMENT_ROOT'], 1) .'
';

which outputs this:

C:\inetpub\wwwroot

100% unrelated to the actual site.
Is there an IIS-specific variable I should be using to include my scripts? It seems to have a huge knock-on affect for all of my code when including files which isn't ideal at all. In a dream world, my code wouldn't touch IIS with a 10-foot pole but unfortunately it has to run on it.
How do I set the root for the site in my code?

A: Unfortunately for me, the IIS server isn't in my control so I couldn't really look to solutions that tamper with the server settings. However I did manage to find a solution:
I placed in my header.php template file:
echo '
'. print_r(exec('CHDIR'), 1) .'
';

this gave me a value that looked like this:

C:\www\mysite

Which is a lot different to the output of $_SERVER['DOCUMENT_ROOT'].
I created a conditional to tell the server OS apart and set a new variable based on the value:
if (strpos(PHP_OS, 'Linux') > -1) {
    $root = $_SERVER['DOCUMENT_ROOT'];
    $feRoot = '/';
} else {
    $root = 'C:\\www\\mysite';
    $feRoot = 'http://mysite';
}

Now I can call my scripts like this ($DS = DIRECTORY_SEPRARTOR):
require_once $root. $DS .'app'. $DS .'connect.php';

And call my frontend assets like this:
<link rel="stylesheet" href="<?php echo $feRoot; ?>/css/file.css" />

So the key to IIS is deal in absolutes rather than relative to the DOCUMENT_ROOT


text:
Q: Make color scale for numbers in dictionary [Python] I have a dictionary with different values, like this:
  colormap_coms=
  {0.10208554259455638: rgb(179, 56, 79), 0.0: rgb(121, 28, 149),
  0.10870219813309245: rgb(44, 147, 200), 0.12623481073520415: rgb(78, 170,
  98), 0.10298102981029811: rgb(150, 87, 91), 0.044263775971093045: rgb(223,
  39, 33), 0.13340724316334074: rgb(194, 205, 92), 0.10034049058439304:
  rgb(99, 41, 106), 0.08040984519434236: rgb(97, 51, 26),
  0.008130081300813009: rgb(106, 148, 70), 0.07158437438032918: rgb(54, 159,
  37)}

I used this function:
 colormap_coms = {x :
 RGB(random.randrange(0,256),random.randrange(0,256),random.randrange(0,256))
                 for x in list(set(communities))}

Here I have random color assignment, but i want to assign color scale (for ex. from dark to light) based on values(from smaller to bigher).
Is there a simple way to do this?
Thanks

A: RGB is ill suited to create smooth color transitions, google HSV color space.
You pick a Hue, a Saturation and make the Value variable to create different shades of one base color.
You can get RGB values from HSV values like this:

import colorsys

rgbs = []
for v in range(10000):
    val = v/10000.0
    # http://colorizer.org/   some light blue base color
    rgbs.append( colorsys.hsv_to_rgb(170/256.0,0.7,val))

print (rgbs)

(modified from CoryKramers answer here )
You can map this list of RGBs to your values, or simply put your values into the Value of the HSV - you might need some scaling/normalisation on your raw values to spread them over the available color space.

You can also fix any of the other 2: H or V in that case hue or value are changing.
Create a similar mapping as you do for rbg and you should be set:
coms= sorted([0.10208554259455638, 0.0, 0.10870219813309245,0.12623481073520415, 0.10298102981029811,0.44263775971093045,0.13340724316334074,0.10034049058439304,0.08040984519434236,0.008130081300813009,0.07158437438032918])

mycols = {}
part = 1.0 / len(coms)
for k in range(len(coms)):
    mycols[colormap_coms[k]] = colorsys.hsv_to_rgb(170/256.0,0.7,k*part)

print(mycols)

Output:
    {0.0: (0.0, 0.0, 0.0),
     0.008130081300813009: (0.02727272727272728, 0.028267045454545465, 0.09090909090909091),
     0.07158437438032918: (0.05454545454545456, 0.05653409090909093, 0.18181818181818182),
     0.08040984519434236: (0.08181818181818182, 0.08480113636363638, 0.2727272727272727),
     0.10034049058439304: (0.10909090909090911, 0.11306818181818186, 0.36363636363636365),
     0.10208554259455638: (0.1363636363636364, 0.14133522727272732, 0.4545454545454546),
     0.10298102981029811: (0.16363636363636364, 0.16960227272727277, 0.5454545454545454),
     0.10870219813309245: (0.19090909090909094, 0.19786931818181824, 0.6363636363636364),
     0.12623481073520415: (0.21818181818181823, 0.22613636363636372, 0.7272727272727273),
     0.13340724316334074: (0.2454545454545455, 0.2544034090909092, 0.8181818181818182),
     0.44263775971093045: (0.2727272727272728, 0.28267045454545464, 0.9090909090909092)}


text:
Q: Where to parse a large txt file ASP.NET I have a large txt file thar I want to parse in my web application. Earlier, I had the same application as a kind of desktop application, and I did the parsing one time during the Load, and briong the contents of file into memory.
Here in ASP.NET website, I am not sure if I should be doing this in Page_Load() since parsing a 13Mb text file would make this slow for the user everytime. What should I do to bring this one time into memory and then for all the users, the same in-memory parsed contents can be looked up?

A: I would load it in global.asax in the Application_Start event handler.  Then add it to the cache and retrieve as needed.
To decrease the likelihood of your data being dropped from the cache, you can specify that it is not removable:
HttpContext.Current.Cache.Add(
    "mydatakey",        // key for retrieval
     MyDataObject,
     null,              // cache dependencies
     DateTime.Now.AddDays(1),      // absolute expiration
     TimeSpan.FromDays(1),         // sliding expiration
     System.Web.Caching.CacheItemPriority.NotRemovable,       // priority
     new CacheItemRemovedCallback(MyHandleRemovedCallback)
);

For more detail this caching method data, see here on MSDN (Caching Application Data):  http://msdn.microsoft.com/en-us/library/6hbbsfk6(v=vs.71).aspx

A: If your file is same for all the users you can put in cache provided by asp.net. If it is specific to user then session could be a place for it but that will acquire a lot of memory and make it almost devastating. This is how you can Cache file in asp.net
string fileContent = Cache["SampleFile"] as string;
if (string.IsNullOrEmpty(fileContent))
{
    using (StreamReader sr = File.OpenText(Server.MapPath("~/SampleFile.txt")))
   {
       fileContent = sr.ReadToEnd();
       Cache.Insert("SampleFile", fileContent, new System.Web.Caching.CacheDependency(Server.MapPath("~/SampleFile.txt")));
   }
}

A: Well if you MUST load a 13 mb text file into memory for a website then I would suggest using an Application variable you can set this in the Global.asax file, this will be available to all the users within the site.
Once the file is there it will remain until the application pool is unloaded from memory.

A: Use Application["key"] = value. You need to cache this in the server and Application should do it like saving things in Session like Session["userid"] = something.


text:
Q: Making a basic GUI for a Java 'Connect Four' game This might be either a too basic and a too huge question to ask.
Although I study business management as my discipline, by some chance I am taking a Java module this year and am currently working on building a 'Connect Four' game. So far, I have succeeded making the game work in the console, however, I have utterly no idea about how to present the game through GUI. I mean, I could build a GUI window in a separate class but could you help me extending the class methods I created before to the GUI class that I don't have to write the whole programme again? Many thanks.
All of the codes I wrote are here: https://github.com/aca16kd/java-connect-four/tree/master/Assignment/src. The classes live in assignment2017 folder as well as the main class, PlayConnect4, and the EasyReader class which could be used as exactly same as java.util.Scanner lives in sheffield folder.

A: The simplest way (I can think of) is having a separate GUI class which extends Jframe and implements Action Listeners. This way you could have a simple text box in a frame with a couple of buttons.


text:
Q: How to get negative value of a boolean Android Manifest PlaceHolder variable? Let's say I have this in my Gradle file:
manifestPlaceholders = [releaseBuild: "false"]

Now in my Android Manifest file, I want to have this:
<profileable android:shell="${!releaseBuild}" />

I am getting this error:
Cannot convert string ${!releaseBuild} to target class boolean.
Any ideas?


text:
Q: Lock axis in ZedGraph I've used ZedGraph to plot data from several sources with a single click. I need the Y-axes to always have the same max and min-values for each plot. I need this to be able to see changes between datasets as I flip through them. In my case, it would not make sense to plot data from several sources in one graph.
I've tried to set axis properties like this:
    myPane.Y2Axis.Scale.Max = 40;
    myPane.Y2Axis.Scale.MaxAuto = false;
    myPane.Y2Axis.Scale.Min = -40;
    myPane.Y2Axis.Scale.MinAuto = false;

I still see the axes beeing auto scaled. Please give me a hint if this is possible or not. I probably only miss a small thing...
(by the way: I hope someone picks this project up, it's great!)

A: Well, solved like this:
        zGC.AxisChange();
        zGC.RestoreScale(myPane);
        zGC.ZoomOut(myPane);

Added a ZoomOut(), since I realized that RestoreScale() actually always autozooms...
-rb

A: Is your intention to synchronize the scales of all panes that you use?
If so, have you seen this tutorial?
The second thing is that the Y2Axis is not visible by default. ZG uses by default first Y axis (YAxis). Have you enabled Y2Axis manually?


text:
Q: curl ignore --data starting with @ sign: don't read from file In slack you can script slackbot to post messages to a channel like this:
curl --data "$msg" $'https://<yourteam>.slack.com/services/hooks/slackbot?token=<yourtoken>&channel=#random'

Now i'd like to mention a username as the first part of the message like msg="@joernhees hello self".
The problem with this is that if the --data argument of curl starts with an @ sign it will interpret the string after the @ as filename and post its content. Is there a way to make curl ignore the @ sign and to send a literal @ as the first char of a post request?

A: If you are on a new version of cURL you can also use the --data-raw option:
http://curl.haxx.se/docs/manpage.html#--data-raw
A word of warning is that looking my laptop it appears Yosemite ships with an older version of cURL.
In general if you're creating tools to post to Slack I'd recommend using an HTTP library in your script rather than calling out to a shell and invoking the curl command.

A: Actually i just found out i can do this (not sure it's the best option though):
curl --data '@-' $'https://<yourteam>.slack.com/services/hooks/slackbot?token=<yourtoken>&channel=#random' <<< "$msg"

The trick is to tell curl to read from stdin @- and then pass the message in via that.


text:
Q: Reducer in deeply nested state I've been trying to come up with a useReducer for a deeply nested state for a while.
const initialState = {
  typeOfMeal: "breakfast",
  protein: "",
  carbs: "",
  fat: "",
  mainPhoto: "",
  platePhoto: "",
  ingredients: [
    {
      ingredientName: "",
      ingredientQuantity: "",
      ingredientUnit: "g",
      ingredientId: 0,
    },
  ],
};

the objects in ingredients are dynamically generated, and that works fine, but I can't update them.
This is the case responsible for updating these objects:
case "GET_INGREDIENT_BOX_VALUE":
      return {
        ...state,
        ingredients: [
          ...state.ingredients,
          { ...state.ingredients[action.index], [action.name]: action.value },
        ],
      };

And an example of an object fragment that I want to update:
name="ingredientName"
value={state.ingredients[box.ingredientId].ingredientName}
 onChange={(e) =>
   dispatch({
   type: "GET_INGREDIENT_BOX_VALUE",
   value: e.target.value,
   index: box.ingredientId,
   name: e.target.name,
   })
  }

How to get to such an object? I've been looking for a solution for a while and can't find anything. Thank you for your help :)

A: Hope this could be helpful.
case "GET_INGREDIENT_BOX_VALUE":
  const { ingredients } = state;
  ingredients[action.index] = {
    ...ingredients[action.index],
    [action.name]: action.value
  };
  return {
    ...state,
    ingredients: [...ingredients],
  };


text:
Q: Using jQuery each to display images I'm trying to display three images each in a row. For example, I am trying to get the page to look like this (I manually went ahead and typed out all the html I'm trying to get): http://imgur.com/AsizGyy
But when I try to use jQuery to append the images to try and make it appear like how it is in the previous screenshot, it displays like this: http://imgur.com/Vkt4ljH
Obviously that is different than how I want it to be.
Here is my code (both the html and jQuery)

$('#album-name').on('change', function() {
    // retrieve the images from the photo album selected
    $.ajax({
        type: "POST",
        url: "/members/profile/get-photos-from-album",
        dataType: "json",
        data:  {
            album_name: $('#album-name option:selected').val()
        }
    }).done(function(msg) {
        if (msg.photos == undefined) {
            $('#no-album-photos .w3-col m12').attr('style', 'display: initial;');
            $('#no-album-photos .w3-col m12 ').html("
No photos were found in the album
");

            return false;
        } else {
            $('#album-header').attr('style', 'display: initial;');

            $('#album-header h4').html("Photos in " + $('#album-name option:selected').text().split("_")[0] + ":");

            $('.w3-row-padding .w3-margin-top').attr('style', 'display: initial;');

            $.each(msg.photos, function(i, item) {
                $('div.w3-third').find('.w3-card-2').append('<img src="<?php echo $this->basePath() . '/images/profile/' . $this->identity() . '/albums/'; ?>' + $('#album-name option:selected').val() + '/' + msg.photos[i] + '" style="width: 100%;">');
            });
        }
    }).fail(function(msg) {
        alert(msg);
    });
});

I know the issue is within the $.each function but I am at a loss on how to fix this (after searching for any issues or tutorials on how to accomplish this but to no luck unfortunately).
The html I am trying to get for this would be like this:

Any help would be appreciated. If more information is needed, I can try and post more.
Thanks!

A: You are stacking your DIV's which will create columns so your code is working fine, it's your HTML that's wrong. You could use float: left to do this

           Image1

           Image2

           Image3

FIDDLE
OR stylesheet it
.w3-third {
    float: left;
    max-height: 200px;
}
img {
    max-height: 150px;
    padding-bottom: 10px;
}

A:
Try updating the line with the $.each function. Looks like you are
  looping within the div.w3-third instead of the div.w3-row.

$(this).append('

<img src="<?php echo $this->basePath() . '/images/profile/' . $this->identity() . '/albums/'; ?>' + $('#album-name option:selected').val() + '/' + msg.photos[i] + '" style="width: 100%;">

');

Though this is not the best implementation of building html with jQuery.
You don't need a new row each time. If your css class .w3-third which i assume is one-third of your row. You'll have something like this
CSS
.w3-third {
     width: 33.3%;
     float: left;
 }

Set the height of the image wrapper
    .w3-card-2 {
       height: 240px;
       margin-bottom: 15px;
    }

OR
.w3-card-2, .w3-card-2 img {
       height: 240px;
}

Hope this helps.

A: .w3-third {
float: left;
width:30%;
max-height: 200px;
pading:0;
}
img {
width:100%;
margin-left:0;
margin-right:0;
max-height: 150px;
padding-bottom: 10px;
}


text:
Q: Communicate changes between sibling components in AngularJS 1.6 I have an AngularJS 1.6 app that looks like this:
angular.module('app').component('parent', {
    template: '
      <parent>
         <display options="ctl.options"></display>
         <controls options="ctl.options"></controls>
      </parent>',
    controller: function() {
      this.options = { x: 100, y: 0.2 };
    },
    controllerAs: 'ctl',
    bindToController: true
});

I'd like to use inputs in controls component to modify properties of the options object, so that changes are reflected in display (but without rewriting entire object each time one property has been changed).
How can I do it? Even if I set options to two-way binding in controls, display is not updated and $onChanges does not fire.
It can be easily accomplished with $watch or messages, but I can't figure out a proper component-centric way to do it.

A: The $onChanges life-cycle hook only fires when the identity of an object changes. If you want to check for changes to the contents of an object, use the $doCheck life cycle hook.
From the Docs:

Life-Cycle Hooks

*

*$doCheck() - Called on each turn of the digest cycle. Provides an opportunity to detect and act on changes. Any actions that you wish to take in response to the changes that you detect must be invoked from this hook; implementing this has no effect on when $onChanges is called. For example, this hook could be useful if you wish to perform a deep equality check, or to check a Date object, changes to which would not be detected by AngularJS's change detector and thus not trigger $onChanges. This hook is invoked with no arguments; if detecting changes, you must store the previous value(s) for comparison to the current values.

  -— AngularJS $compile Service API Reference - Life-cycle hooks

See also AngularJs 1.5 - Component does not support Watchers, what is the work around?

A: A declarative way to do it would be to have a factory store the data, and pass the factory in to each controller. When either controller/component updates the state, it'll be reflected in the other controller/component.

var app = angular.module('app', []);

app.factory('Options', function(){
  return {
    data: {
      x: 100,
      y: 0.2
    }
  };
});

app.controller('DisplayCtrl', function($scope, Options){
  $scope.options = Options.data;
});

app.controller('ControlsCtrl', function($scope, Options){
   $scope.options = Options.data;
});

x: {{ options.x }}

y: {{ options.y }}

        x: <input type="number" ng-model="options.x">

        y: <input type="number" ng-model="options.y">

See Share data between AngularJS controllers for more thoughts. I think https://stackoverflow.com/a/25145593/1927876 is the best answer because it is so declarative and easy to reason about, and is what I base my answer here on.


text:
Q: Spring Boot Hystrix fallback method not being invoked after timeout limit I want a fallback method to be invoked after a service takes more than 350 milliseconds to complete. Even after 10,000 milliseconds, the method is still not invoked.
I'm running a JUnit test that uses Mockito.
UnitTesting.java
...
@Test
public void test1() {

    when(service.getId()).thenAnswer(new Answer<Integer>() {
               public Integer answer(InvocationOnMock invocation){
                 try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                 return -1;
    }});
    LateralService latService= new LateralService(service);
    ArrayList<IdService> returnedIdServices = latService.getIdServices(); //getId() is invoked in this method
    ...
}

LateralService.java
...
@HystrixCommand(groupKey = "fallback",
                commandKey = "fallback",
                fallbackMethod = "idServiceFallBack",
                commandProperties = {
                   @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "350")})
public ArrayList<IdService> getIdServices() {
    int id = service.getId();

    ...
}

public ArrayList<IdService> idServiceFallBack(){
    return new ArrayList<IdService>() { add(new IdService(1)) }
}


text:
Q: Split SPAN when Inserting HTML Inside of it I have a setup where I have a large amount of text that is formatted HTML (containing headings and paragraphs)–all inside of a contenteditable div. I've setup a function to insert a custom html entity: <newnote> into the editable div upon clicking a button. This works great except that when inserting the note inside of a span I need to split the span in two and place the <newnote> in between them.
I've looked at lots of functions around the web for inserting text into a DIV, and since it is a requirement that I be inserting HTML it seems like document.createTextNode() is my only choice.
So here is what I've setup thus far, it checks if the parent is a SPAN and then places different content based on that if statement.
function insertNodeAtRange() {
  var newRange = rangy.getSelection().getRangeAt(0);
  var parentElement = newRange.commonAncestorContainer;
  if (parentElement.nodeType == 3) {
      parentElement = parentElement.parentNode;
  }
  var el = document.createElement('newnote');
  el.className = "bold";
  if (parentElement.tagName == 'SPAN') {
      el.appendChild(document.createTextNode(" </span>Test<span> "));
  } else {
      el.appendChild(document.createTextNode(" Test "));
  }
  newRange.insertNode(el);
}

Here is what I have sofar
Thanks in advance for any help...

A: The main problem with your code is that you were trying to make/modify html by creating a text node. Text nodes do not get parsed as dom.
This should work for you:
JSFiddle
function insertNodeAtRange() {
    var newRange = rangy.getSelection().getRangeAt(0);
    var parentElement = newRange.commonAncestorContainer;
    if (parentElement.nodeType == 3) {
        parentElement = parentElement.parentNode;
    }
    var el = document.createElement('newnote');
    el.className = "bold";
    el.appendChild(document.createTextNode(" Test "));
    newRange.insertNode(el);
    if (parentElement.tagName == 'SPAN') {
        var $newnote = $(el);
        var $span1 = $("<span>");
        var $span2 = $("<span>");
        var left = true;
        $parentElement = $(parentElement);
        $parentElement.contents().each(function (i, node) {
            if (node.isSameNode(el)) {
                left = false;
            } else if (left) {
                $span1.append(node);
            } else {
                $span2.append(node);
            }
        });
        $parentElement.replaceWith($newnote);
        $span1.insertBefore($newnote);
        $span2.insertAfter($newnote);
    }
}

I just went ahead and inserted the newnote element right away, then got the stuff before that and put it into span1, got the stuff after it and put it into span2, replaced the existing span with newnote and positioned the new spans around newnote.


text:
Q: How to style responsive table to make table like list? I have my aspx code here:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SearchCustomer.aspx.cs" Inherits="WebApplication1.eyeofheaven.SearchCustomer" %>

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<link rel="stylesheet" type="text/css" href="StyleSheets/SearchCustomerStyle.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">

<title>Search Customer</title>

<form id="form1" runat="server">

                        <button type="button" data-target="#navbarCollapse" data-toggle="collapse" class="navbar-toggle">
                            Toggle navigation

                        </button>

Home

                                Search

Search Form(Customer)

Search Form(Vehicle)

Search Customer

        <input type="text" runat="server" id="search" size="20" class="form-control" placeholder="Customer ID">

        <select class="form-control" runat="server" id="Country">
            <option value="select" selected disabled>Search by Country</option>
            <option value="A:C ESTUDIO">A:C ESTUDIO</option>
            <option value="Aaron McEwen-194712">Aaron McEwen-194712</option>
        </select>

        <select class="form-control" runat="server" id="Currency">
            <option value="selected" selected disabled>Search by Currency</option>
            <option value="AUD">AUD (Australian Dollar)</option>
            <option value="EUR">EUR (Euro)</option>
            <option value="GBP">GBP (United Kingdom Pounds)</option>
            <option value="JPY">JPY (Japan Yen)</option>
            <option value="NZD">NZD (New Zealand Dollar)</option>
            <option value="USD">USD (United States Dollar)</option>
        </select>

<button type="button" runat="server" onserverclick="Button1_Click" id="searchinfo" class="btn btn-primary"> Search Info</button>
<button type="button" runat="server" onserverclick="Button2_Click" id="Button2" class="btn btn-danger">Reset</button>

    <asp:GridView runat="Server" id="data" CssClass="table table-striped table-bordered table-responsive">
    </asp:GridView>

</form>

And my css style here:
#searchcustomer{
    margin-top:51px;
    text-align:center;
    background-color:#3399FF;
}
#gridview {
    margin: 20px;
}
#data {
    display: block;
    height:400px;
    overflow-y: scroll;
}
/* Zebra striping */
    tr:nth-of-type(odd) {
        background: #eee;
    }
    th {
        background: #333;
        color: white;
        font-weight: bold;
    }
    td, th {
        padding: 6px;
        border: 1px solid #ccc;
        text-align: left;
    }

 @media only screen and (max-width: 800px) {

    /* Force table to not be like tables anymore */
    #data table,
    #data thead,
    #data tbody,
    #data th,
    #data td,
    #data tr {
        display: block;
    }

    /* Hide table headers (but not display: none;, for accessibility) */
    #data thead tr {
        position: absolute;
        top: -9999px;
        left: -9999px;
    }

    #data tr { border: 1px solid #ccc; }

    #data td {
        /* Behave  like a "row" */
        border: none;
        border-bottom: 1px solid #eee;
        position: relative;
        padding-left: 50%;
        white-space: normal;
        text-align:left;
    }

    #data td:before {
        /* Now like a table header */
        position: absolute;
        /* Top/left values mimic padding */
        top: 6px;
        left: 6px;
        width: 45%;
        padding-right: 10px;
        white-space: nowrap;
        text-align:left;
        font-weight: bold;
    }
}

The output is okay when viewed on website:

But when viewed on mobile the output is like this:

All of my "th" seems to display before my all my "td"
How do I revised my css to make an output not like this. I want to make my table when viewed on mobile (It will get the th and td display)
Example:
When viewed on mobile:
The output is:
(First it will display the th tag "IDCustomer" and next to it is the td which is "253433")
(Image below)
Note:(I just edited this image on paint to further explain my question.)

How Do I design a css style like this?

A: You have to use responsive solution for this :
solutions here


text:
Q: Is there any way to mark existing clustered index as primary key in SQL Server? I have table with about 60 000 000 rows in it and having size near 60 GB.
It has 2 indexes: clustered index and primary key on same id identity column.
Primary key index has size near 1GB. It looks excessive. I have several such tables.
Question is, is there any way to effectively mark existing clustered index as primary key also without dropping both indexes and creating one single new index?
Sub question is does it worth it to do such operations, maybe only drop primary keys? What's the real practical advantage of having primary key except descriptive usage for 3rd party tools? maybe sql server optimizer uses this metadata to optimize queries or any other advantages that I am missing?
Small sample of what I want to achieve, but other way (if it exists), without dropping and creating indexes.
I assume that it looks like there's no other way really, but who knows maybe there's some trick.
create table a
(
    id int identity,
    col1 varchar(50)
)

create unique clustered index cix_id on a(id)
alter table a add constraint pk_a primary key nonclustered(id)

select t.name,i.name,i.is_primary_key,i.type_desc from
sys.tables t
inner join sys.indexes i on i.object_id=t.object_id
where t.name='a'

drop index cix_id on a
alter table a drop constraint pk_a
alter table a add constraint pk_a primary key clustered(id)

select t.name,i.name,i.is_primary_key,i.type_desc from
sys.tables t
inner join sys.indexes i on i.object_id=t.object_id
where t.name='a'


text:
Q: Realm query returning wrong result sporadically I have been noticing that when I have updated an object recently of a certain class and I try to fetch a list of those objects, the most recently updated object is returned with wrong values.
It is not happening every time but it happens every once in a while.
The data gets correctly inserted in the RealmDB.
I am using the following code snippet to fetch from realm.
public static <T extends RealmModel> ArrayList<T> fetchAllForKey(Class<T> clazz, String key, boolean value) {
    Realm realm = Realm.getInstance(new RealmConfiguration.Builder().build());
    RealmQuery query = realm.where(clazz);
    query.equalTo(key, value);
    RealmResults<T> results = query.findAll();
    ArrayList<T> list = realm.copyFromRealm(realmResults);
    realm.close;
    return list;
}

I have 5 Objects in the RealmDB and when I fetch using the above function I get a list of size 5 but sometimes it returns a list of 4 size even when I have the data in DB and on the subsequent fetch it returns list of size 5.
I am trying to figure out why realm is returning wrong values and a way to mitigate this.


text:
Q: Cordova build android fails after upgrading to cordova-android 11 I'm currently upgrading cordova (and its platforms) in an existing project.
After upgrading from cordova-android from 9.x to 11.x I get some build errors:
FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:processDebugResources'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
   > Android resource linking failed
     C:\Users\OBurger\.gradle\caches\transforms-3\5c55b34766402f38a5e46b43ac71f280\transformed\jetified-core-splashscreen-1.0.0\res\values-v31\values-v31.xml:3:5-9:13: AAPT: error: style attribute 'android:attr/windowSplashScreenAnimatedIcon' not found.

     C:\Users\OBurger\.gradle\caches\transforms-3\5c55b34766402f38a5e46b43ac71f280\transformed\jetified-core-splashscreen-1.0.0\res\values-v31\values-v31.xml:3:5-9:13: AAPT: error: style attribute 'android:attr/windowSplashScreenBackground' not found.

     C:\Users\OBurger\.gradle\caches\transforms-3\5c55b34766402f38a5e46b43ac71f280\transformed\jetified-core-splashscreen-1.0.0\res\values-v31\values-v31.xml:3:5-9:13: AAPT: error: style attribute 'android:attr/windowSplashScreenAnimationDuration' not found.

     C:\Users\OBurger\.gradle\caches\transforms-3\5c55b34766402f38a5e46b43ac71f280\transformed\jetified-core-splashscreen-1.0.0\res\values-v31\values-v31.xml:10:5-14:13: AAPT: error: style attribute 'android:attr/windowSplashScreenIconBackgroundColor' not found.

     C:\Users\OBurger\.gradle\caches\transforms-3\4e55571a2aca20a3df79838283759989\transformed\core-1.7.0\res\values\values.xml:105:5-114:25: AAPT: error: resource android:attr/lStar not found.

I already followed the steps for the cordova-android upgrade described here: https://ionic.zendesk.com/hc/en-us/articles/7891143965975-Migrating-to-Cordova-Android-11
I also added a dependency for "androidx.core:core-splashscreen:1.0.0" in build.gradle


text:
Q: How to write to (/var/lib/mysql-files) with apache? I get the Permission denied error every time I try to write a file to (/var/lib/mysql-files) directory with http, but if I restart apache and/or MySQL I can write to that directory with no errors, but only one time, so if I try to write a second file I will get that error, and I have to restart apache again and so on.
This is the ownership and the permissions that i gave that directory:
  groupadd mysql_apache
  usermod -a -G mysql_apache mysql
  usermod -a -G mysql_apache apache
  chown -R :mysql_apache /var/lib/mysql-files
  chmod -R 770 /var/lib/mysql-files

I want to give the rights to read; write; execute on this dir (/var/lib/mysql-files) only to MySQL and apache, What did I do wrong here?
PS: This is on CentOs 8.

A: We moved to Ubuntu 20.04 since CentOs 8 EOL changed to 2021, and I didn't have this problem in Ubuntu.


text:
Q: Difference in application between orthonormal basis vs orthogonal basis I am trying to understand what ortonormal and orthogonal means, and also how to visualize them.
If I understand correctly: lets say we have three vectors $u_1,u_2,u_3$ that make up the third dimension $R^3$, we can simplify this to make calculations more easily. The simplification is finding the orthogonal basis of the newly created three dimensional space. Simply put, we take one of these vectors, lets say $u_1$, and create another vector $w_1$ that is 90 degrees in respect to $u_1$. When added to the first vector $u_1$ we get the second vector $u_2$: $\lambda u_1+\mu w_1= \gamma u_2, $ where $\lambda, \mu, \gamma \in \mathbb{R}$ in exactly one way (say $\gamma = 5$ then there is exactly one combination of $\lambda u_1 + \mu w_1 = 5u_2$.) Then we do the same for $u_2$ (now expressed in $u_1$ and $w_1$, in order to calculate $u_3$. The combination of $u_1,w_1,w_2$ the same as one vector with two orthogonal components that we now can use to express any vector in $R^3$ created by $u_1,u_2,u_3$. We get the orthonormal basis of this space instead of the orthogonal basis by dividing all the vectors by their length, e.g $\frac{u_1}{|u_1|}$.
What is the point (geometric implication) of the orthonormal basis?
Why the orthonormal basis so superior to the orthogonal basis?
When would you choose the orthonormal over the orthogonal basis? Also when would you choose to keep the original vectors (when would it be easier)?
All I can find is that using the orthogonal basis for any $R^n, n \in \mathbb{R}$ is better than what we had first because we can more easily express any vector using vectors that are connected rather than three distinct vectors combined. Or something. Which I find to not make any sense because we could perfectly well describe $R^3$ with the orthogonal vectors, right?


text:
Q: Storing longitude and latitude data in android I have to store longitude and latitude of all cities of a country in android application
when user will select a city i have to return the longitude and latitude of selected city.
what will be the most efficient way to do this?
or is there any resources where i enter a country and it will show all cities with their longitude and latitude..?

A: You can use Google Geocoding API : https://developers.google.com/maps/documentation/geocoding/
For example :
https://maps.googleapis.com/maps/api/geocode/json?address=Berlin&sensor=true
And parse output using GSON
{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "Berlin",
               "short_name" : "Berlin",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Berlin",
               "short_name" : "Berlin",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "Niemcy",
               "short_name" : "DE",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "Berlin, Niemcy",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 52.6754542,
                  "lng" : 13.7611176
               },
               "southwest" : {
                  "lat" : 52.33962959999999,
                  "lng" : 13.0911663
               }
            },
            "location" : {
               "lat" : 52.52000659999999,
               "lng" : 13.404954
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 52.6754542,
                  "lng" : 13.7611176
               },
               "southwest" : {
                  "lat" : 52.33962959999999,
                  "lng" : 13.0911663
               }
            }
         },
         "types" : [ "locality", "political" ]
      }
   ],
   "status" : "OK"
}


text:
Q: Branch Deep Linking not working in Google Analytics hitCallback I'm using both Google Analytics and branch.io in this website.
The website is designed for mobile.
The problem is that when clicking the banner with text "OPEN", the app cannot be opened.
Here is the code for the click:
$scope.openApp = () => {
  let appOpened = false;
  const open = () => {
    if (!appOpened) {
      appOpened = true;
      branch.deepviewCta();
    }
  };

  $timeout(open, 1000);

  ga('send', 'event', 'homepage', 'download', {
    hitCallback() {
      open();
    }
  });
};

If I get rid of the GA code, it works fine:
$scope.openApp = () => {
  let appOpened = false;
  const open = () => {
    if (!appOpened) {
      appOpened = true;
      branch.deepviewCta();
    }
  };

  $timeout(open, 1000);

  open();

};

The reason I put open() in hitCallback is to make sure GA sends out the hit because open() will redirect to another page.
Can you help me?

A: Alex from Branch.io here:
The Branch deepviewCta() function works on iOS 9+ by triggering an automatic redirect to a Universal Link URL (which opens the app) and then going to a fallback URL if that fails. But Apple is very specific about the situations in which a Universal Link is allowed to launch the app (including things like how long of a pause is allowed before redirection). Of course these restrictions are not public, so all we can do is guess. My suspicion is that putting the deepviewCta() function inside a GA callback is falling outside of Apple's rules, so the app never opens and you are instead being sent to the fallback URL.
I can think of two options here:

*

*You can build some way to trigger the GA and Branch functions separately so that they don't conflict with Apple's requirements.

*We actually have a brand new, one-click integration with Google Analytics, which you can read about here and here. If you set that up, you'll get all Branch-related events automatically instead of needing to manually collect link click data.

Hopefully that helps!


text:
Q: "No 'Access-Control-Allow-Origin' header" when no response data is expected I want to post the contents of a form using ajax to an URL in a different domain. I don't have control over the remote site response headers.
I can issue the POST request and the data goes through but get an error (using Chrome here):
No 'Access-Control-Allow-Origin' header

I don't expect to get any data from the remote site, except for a 200 status code.
When using jQuery, if I set the dataType to 'jsonp', I get the 200 OK status code but I also get a warning:
Resource interpreted as Script but transferred with MIME type text/html

How can I still post the data to the remote server and simply ignore whatever response I might get (or not) with the exception of the status codes (200, 404, etc...)?
Thanks in advance.


text:
Q: Mutating one field while iterating over another immutable field Given the following program:
struct Data {
    pub items: Vec<&'static str>,
}

trait Generator {
    fn append(&mut self, s: &str) {
        self.output().push_str(s);
    }

    fn data(&self) -> &Data;

    fn generate_items(&mut self) {
        for item in self.data().items.iter() {
            match *item {
                "foo" => self.append("it was foo\n"),
                _ => self.append("it was something else\n"),
            }
        }
    }

    fn output(&mut self) -> &mut String;
}

struct MyGenerator<'a> {
    data: &'a Data,
    output: String,
}

impl<'a> MyGenerator<'a> {
    fn generate(mut self) -> String {
        self.generate_items();

        self.output
    }
}

impl<'a> Generator for MyGenerator<'a> {
    fn data(&self) -> &Data {
        self.data
    }

    fn output(&mut self) -> &mut String {
        &mut self.output
    }
}

fn main() {
    let data = Data {
        items: vec!["foo", "bar", "baz"],
    };

    let generator = MyGenerator {
        data: &data,
        output: String::new(),
    };

    let output = generator.generate();

    println!("{}", output);
}

The following errors are produced trying to compile it:
error[E0502]: cannot borrow `*self` as mutable because it is also borrowed as immutable
  --> src/main.rs:15:26
   |
13 |         for item in self.data().items.iter() {
   |                     ----                   - immutable borrow ends here
   |                     |
   |                     immutable borrow occurs here
14 |             match *item {
15 |                 "foo" => self.append("it was foo\n"),
   |                          ^^^^ mutable borrow occurs here

error[E0502]: cannot borrow `*self` as mutable because it is also borrowed as immutable
  --> src/main.rs:16:22
   |
13 |         for item in self.data().items.iter() {
   |                     ----                   - immutable borrow ends here
   |                     |
   |                     immutable borrow occurs here
...
16 |                 _ => self.append("it was something else\n"),
   |                      ^^^^ mutable borrow occurs here

What is the proper way to structure the code so that the mutable field output can be written to while iterating over the immutable field data? Assume the indirection through the Generator trait is being used to share similar logic with other structs, so accessing MyStruct's fields from the trait's default method implementations need to be done through accessor methods like this.

A:
Assume the indirection through the Generator trait is being used to share similar logic with other structs, so accessing MyStruct's fields from the trait's default method implementations need to be done through accessor methods like this.

Then it's impossible.

The compiler recognizes access to different fields when it sees such fields directly; it does not break abstraction boundaries to peek inside the functions called.
There have been discussions about adding attributes on the methods to specifically mention which field is accessed by which method:

*

*the compiler would enforce that a method does not touch any field NOT mentioned in the attribute

*the compiler could then use the knowledge that said method only operates on a subset of the fields

however... this is for non-virtual methods.
For a trait this gets significantly more complicated because a trait does not have fields, and each implementer may have a different set of fields!

So now what?
You will need to change your code:

*

*you can split the trait in two, and require two objects (one to iterate, one to mutate)

*you can "hide" the mutability of the append method, forcing users to use interior mutability

*...

A: You can use RefCell:

RefCell uses Rust's lifetimes to implement 'dynamic borrowing', a
  process whereby one can claim temporary, exclusive, mutable access to
  the inner value. Borrows for RefCells are tracked 'at runtime',
  unlike Rust's native reference types which are entirely tracked
  statically, at compile time. Because RefCell borrows are dynamic it
  is possible to attempt to borrow a value that is already mutably
  borrowed; when this happens it results in thread panic.

use std::cell::{RefCell, RefMut};

struct Data {
    pub items: Vec<&'static str>,
}

trait Generator {
    fn append(&self, s: &str) {
        self.output().push_str(s);
    }

    fn data(&self) -> &Data;

    fn generate_items(&self) {
        for item in self.data().items.iter() {
            match *item {
                "foo" => self.append("it was foo\n"),
                _ => self.append("it was something else\n"),
            }
        }
    }

    fn output(&self) -> RefMut<String>;
}

struct MyGenerator<'a> {
    data: &'a Data,
    output: RefCell<String>,
}

impl<'a> MyGenerator<'a> {
    fn generate(self) -> String {
        self.generate_items();

        self.output.into_inner()
    }
}

impl<'a> Generator for MyGenerator<'a> {
    fn data(&self) -> &Data {
        self.data
    }

    fn output(&self) -> RefMut<String> {
        self.output.borrow_mut()
    }
}

fn main() {
    let data = Data {
        items: vec!["foo", "bar", "baz"],
    };

    let generator = MyGenerator {
        data: &data,
        output: RefCell::new(String::new()),
    };

    let output = generator.generate();

    println!("{}", output);
}

Rust playground

A: This is a common issue in Rust; the typical way of solving it is the replace dance. This involves making more of the data and methods use mutable references:
struct Data {
    pub items: Vec<&'static str>,
}

trait Generator {
    fn append(&mut self, s: &str) {
        self.output().push_str(s);
    }

    fn data(&mut self) -> &mut Data;

    fn generate_items(&mut self) {
        // Take the data. The borrow on self ends after this statement.
        let data = std::mem::replace(self.data(), Data { items: vec![] });
        // Iterate over the local version. Now append can borrow all it wants.
        for item in data.items.iter() {
            match *item {
                "foo" => self.append("it was foo\n"),
                _ => self.append("it was something else\n"),
            }
        }
        // Put the data back where it belongs.
        std::mem::replace(self.data(), data);
    }
    fn output(&mut self) -> &mut String;
}

struct MyGenerator<'a> {
    data: &'a mut Data,
    output: String,
}

impl<'a> MyGenerator<'a> {
    fn generate(mut self) -> String {
        self.generate_items();

        self.output
    }
}

impl<'a> Generator for MyGenerator<'a> {
    fn data(&mut self) -> &mut Data {
        self.data
    }

    fn output(&mut self) -> &mut String {
        &mut self.output
    }
}

fn main() {
    let mut data = Data {
        items: vec!["foo", "bar", "baz"],
    };

    let generator = MyGenerator {
        data: &mut data,
        output: String::new(),
    };

    let output = generator.generate();

    println!("{}", output);
}

The thing to realize is that the compiler is right to complain. Imagine if calling output() had the side effect of mutating the thing that is referenced by the return value of data()  Then the iterator you're using in the loop could get invalidated. Your trait functions have the implicit contract that they don't do anything like that, but there is no way of checking this. So the only thing you can do is temporarily assume full control over the data, by taking it out.
Of course, this pattern breaks unwind safety; a panic in the loop will leave the data moved out.


text:
Q: React.js and JSON: Dynamic Styles? I'm building a site with React.js, and I'm having trouble using a hex value stored in a json file as the background color of an object. Somehow, the data isn't making its way over to the javascript file (this is my first time using JSON), as it is having no effect on the rendered style or content. This goes for the color, text, etc. Assistance would be much appreciated. Thanks in advance!
The Javascript (ListItem.js):
import data from './data.json';

class ListItem extends Component {

  render() {

    var listItems = data.listItems;
    var color = listItems.color;
    var text = listItems.text;

    var listItemStyle = {

      width: '100px',
      minHeight: '100px',
      backgroundColor: color,
      color: '#FFFFFF'
    }

    return (

{text}

      </listItemStyle>
    );
  }
}

export default listItem

The JSON (data.json):
{ "listItems" : [

  { "color" : "#000000",
    "text" : "hello world"
}]}

A: You listItems in data.json is an array.
{
  "listItems": [ <--- array
    {
      "color": "#000000",
      "text": "hello world"
    }
  ]
}

So when you access listItems.color you get undefined. Use listItems[0].color or update your data.json to
{
  "listItems" {
    "color": "#000000",
    "text:": "hello world"
  }
}

A: You had some syntax error. and as CodinCat said you need an array for reading the Json file. here is the complete code and JSON file.
JS Code:
import data from './testJson2.json';
import React, {Component} from 'react';

class ListItem extends Component {
        render() {
            let listItems = data.listItems;
            let listItemStyle = {
                width: '300px',
                minHeight: '300px',
                backgroundColor: listItems[0].color,
                color: '#ff571a'
            };
            return (

                {listItems[0].text}

            );
        }
    }

    export default ListItem

Json file:
{
  "listItems": [
    {
      "color": "#FFF51E",
      "text": "Rendered Json"
    }
  ]
}

Output => render style/css from JSON file in React JS:


text:
Q: How do you assign a storage file to a ByteArray? How can I assign a storage file to a ByteArray?
var file = await openPicker.PickSingleFileAsync();

A: here a sample using a file picker, getting a storage file and convert it to a byte array.
private async void Button_Click_2(object sender, RoutedEventArgs e)
{
    var picker = new FileOpenPicker();
    picker.ViewMode = PickerViewMode.Thumbnail;
    picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
    picker.FileTypeFilter.Add(".jpeg");
    picker.FileTypeFilter.Add(".jpg");
    picker.FileTypeFilter.Add(".png");
    var file = await picker.PickSingleFileAsync();
    if (file != null)
    {
        var stream = await file.OpenStreamForReadAsync();
        var bytes = new byte[(int)stream.Length];
        stream.Read(bytes, 0, (int)stream.Length);
    }
}


text:
Q: Visual Studio 2015 shortcut for publishing web.config How can I publish the web.config file only and not the entire project?

A: Select your web.config file in solution explorer and press Alt + ¨, Alt + P.
This actually works for any selected file(s) in solution explorer.


text:
Q: How to make apps that depend on communities to grow
*

*What do we call an app that depends on its users for information ?
Example include the Google translate ( or map at a certain extend).

*Imagine for instance I wanted to create an app that help people find the way (or bus stops) in a local scale( quarter), what will I need ?
Any valuable help will be highly appreciated


text:
Q: Test Open vSwitch vs Linux bridge vs Open vSwitch with DPDK I have one quick question - how to test data flow in that environment? I have connection which look like this:
topology:

I want to test data flow from server1 to server2 through server3 which is Virtual Switch. All these servers are physical.
I want to test this in different environments, like OvS, OvS with DPDK then Linux bridge and I want to see any differences between them - but which traffic generator would be the best? I know only one - iperf.
I have seen some comparisons in Mpps between OvS and OvS with DPDK - but I only have seen end result, I haven't seen how looked like the tests.

A: Hi and thanks for the drawing, that helps a lot.
I need to clarify - is it a mistake or really just one device in Server 2 as both sides are called "eth2"? I haven't seen bridging between to e.g. vlans with DPDK as that is at a higher level.
For now I'm assuming your Server 2 has two DPDK capable network devices (actually three to have one remaining for control).
You would then on server 2 dedicate both network devices to DPDK and add them to openvswitch. See the Serverguide for some examples. There is an update pending to integrate how this is done for the OVS/DPDK versions available in Yakkety.
OVS will naturally bridge traffic between those two ports without further configuration.
Warning: make sure those two ports are not part of the same physical network. Doing so would re-reflect all traffic and self amplify itself - finally killing the whole network segment with this being a self made DOS attack.
Once you have set this up, you can run any sort of traffic from server 1 <-> server 3. Iperf is fine for simple streaming workloads. Other common simple tests are netperf and uperf. Configuring all three can be found in the test examples linked here.
For some simplified testing on Ubuntu which can be done on just one machine with two DPDK capable ports feel free to take a look at simple dpdk tests. Some day I intend to set up something similar to your drawing in that with virtual machines to then modify flow rules in between and check the impact of number and complexity of them, but had no time yet.
Finally if you want to go bigger you could consider using server 1 (if enough interfaces are available) with a DPDK based traffic generator like for example Moongen or TRex.

A: Thank you for your response.
Yes, my mistake, here you are new topology:
new_topology:
new
In server3 I have one NIC (with eth1 and eth2 ports) and then I have connection from server1 to the eth2 on that NIC and from server2 to the eth1 on the same NIC.
I have only one Network interface card (NIC) on server3.
I found some examples of comparisons, for example Open vSwitch vs Linux bridge vs Open vSwitch with DPDK and here you are some example of result:
results
I want to achieve sth like that, but I don't know which traffic generator I should use..


text:
Q: Seeing duplicate requests handled with Unicorn Recently I upgraded our EC2 instances to c3.large in order to boost more unicorn workers to handle increased traffic to our site. (6xworkers per machine - 2 ec2 instances).
When I did this, I started seeing duplicate records being created! It looks like somehow, that maybe 2 unicorn workers are attempting to process the same request?
In my nginx logs I see ONE [POST] request to a particular rails controller - yet two records are being created in the database. Obviously I'm hitting some kind of race condition issue - but have no idea how to debug this. It doesn't happen all the time, but when it does it's frustrating as well. I also noticed that the two database records are within 5 seconds of each other. (And yes I disable the button when the user clicks the submit button).
Unicorn 4.8.2
Ruby 1.9.3
Rails 3.2.14
Any help would be great! Thanks!

A: Although it may not fix your problem, upgrade to Ruby 2.0.0.  There are some blog mentioning that is a good idea to upgrade to Ruby 2.0.0 if you are using Unicorn.
For example: https://www.digitalocean.com/community/articles/how-to-optimize-unicorn-workers-in-a-ruby-on-rails-app
Specifically:

If you are using Ruby 1.9, you should seriously consider
  switching to Ruby 2.0. To understand why, we need to understand a
  little bit about forking.

Forking and Copy-on-Write (CoW)

When a child process is forked, it is
  the exact same copy as the parent process. However, the actual
  physical memory copied need not be made. Since they are exact copies,
  both child and parent processes can share the same physical memory.
  Only when a write is made-- then we copy the child process into
  physical memory.

So how does this relate to Ruby 1.9/2.0 and Unicorn?

Recall the Unicorn uses forking. In theory, the operating system would
  be able to take advantage of CoW. Unfortunately, Ruby 1.9 does not
  make this possible. More accurately, the garbage collection
  implementation of Ruby 1.9 does not make this possible. An extremely
  simplified version is this — when the garbage collector of Ruby 1.9
  kicks in, a write would have been made, thus rendering CoW useless.
Without going into too much detail, it suffices to say that the
  garbage collector of Ruby 2.0 fixes this, and we can now exploit CoW.


text:
Q: Debugging a custom Gradle plugin started from the tooling API I am implementing a custom plugin, which I want to run via the Gradle tooling API. We can take this project as exact baseline for my problem.
I essentially want to be able to put a breakpoint inside of the plugin code (in that case the https://github.com/melix/gradle-tapi-demo-artifacts/blob/master/plugin/src/main/java/org/gradle/demo/plugin/OutgoingArtifactsModelBuilder.java.)
The actual Gradle plugin is called from a Java file located in another Gradle module. In that case App.java.
public class App {
    public static void main(String... args) throws Exception {
        GradleConnector connector = GradleConnector.newConnector();
        connector.forProjectDirectory(findProjectPath(args));
        ProjectConnection connection = null;
        try {
            connection = connector.connect();
            ModelBuilder<OutgoingArtifactsModel> customModelBuilder = connection.model(OutgoingArtifactsModel.class);
            customModelBuilder.withArguments("--init-script", copyInitScript().getAbsolutePath());
            OutgoingArtifactsModel model = customModelBuilder.get();
            for (File artifact : model.getArtifacts()) {
                System.out.println("artifact = " + artifact);
            }
        } finally {
            if (connection != null) {
                connection.close();
            }
        }
    }

I cannot find a way to run that Java file and have the breakpoint be hit in the plugin. I understand that I somehow should be launching a remote debug session against the created Gradle deamon but no luck so far.
The -Dorg.gradle.debug=true is not supported when running the Java file directly. I also tried to set those flags inside my ~/.gradle/gradle.properties but without success either (The gradle daemon then refuses to run).
The project is a composite build, I am not sure whether that is relevant.
There are a few too many moving pieces over here for me apparently, if someone has some pointers that would be great!

A: I was able to make a breakpoint in the plugin's source code being hit when runnning the inspector app by adding -Dorg.gradle.debug=true to withArguments and reducing the Gradle daemon's idle timeout to 1 second to effectively disable it. In total, this works for me.


text:
Q: Common Lisp auto completion in emacs Update
Apparently, the auto-complete package is not the culprit.
Emacs fails to download melpa archive.
A quick google search indicates that this is a reappearing problem both on windows and unix machines.
As there are already threads concerning failed to download 'melpa' archive (none of which helped unfortunately) this thread may or may not be closed.
Inital Question
I'm trying to set up emacs for Common Lisp.
I installed sbcl and the slime package.
Some time ago I used to have auto completion for Common Lisp keywords in emacs such that - while typing - it suggested a word via a greyed out completion (TAB for acceptance) or via drop down or both. (I can't remember exactly.)
I'm struggling to get this working again.
At https://github.com/purcell/ac-slime it is suggested to first install auto-complete but when I type package-list-packages there is no such package. (But there are plenty named auto-complete-*).
(I set up Melpa with:
(require 'package)
(add-to-list 'package-archives
    '("melpa" . "http://melpa.org/packages/")))

The provided link http://cx4a.org/software/auto-complete/ is dead as well.M-x install-package [RET] auto-complete [RET] also fails. Emacs says: [No match]
So my question is:
If there is no auto-complete package anymore, what is a good way to set up Common Lisp auto completion in emacs in the way mentioned above (greyed out word or dropdown)?

A: The current home-page for auto-complete is https://github.com/auto-complete/auto-complete
Installing it should be enough to allow you to use ac-slime (there is also a completion version using company).

A: Here is how I got it to work.

*

*Download the .ZIP archive with repository here.

*Unzip

*Run M-x package-install-file

*On the prompt, specify the path to the downloaded repository and the file named auto-complete.el.

*Make sure that installation returns something along the lines of "Successful"

*Add this line to your Emacs initialization file (.emacs):
(ac-config-default)

*To auto-complete in SLIME, follow similar step to install ac-slime (requires SLIME and Auto-complete)
P.S. There is another package called company (stands for Complete Anything), which is quite good as an alternative. I am trying it out now. Getting it to work was very simple.


text:
Q: jQuery plot has percentage symbol on hover I am using jQuery Flot plugin to draw some graphs. On my local environment everything works fine, but on a test server when i hover over a dot from the graph it yields My_text_label: %y.
In place of %y I expect the y-coordinates of that point.
Here is my code sample:
data = [{
    label: label,
    data: d1,
    color: "#48CFAD"
}];

Options = {
    xaxis: {
        mode: "time"
    },
    yaxis: {

    },
    series: {
        lines: {
            show: true,
            fill: false,
            lineWidth: 2
        },
        points: {
            show: true,
            radius: 4.5,
            fill: true,
            fillColor: "#ffffff",
            lineWidth: 2
        }
    },
    grid: {
        hoverable: true,
        clickable: false,
        borderWidth: 0
    },
    legend: {
        container: legend,
        show: true
    },

    tooltip: true,
    tooltipOpts: {
        content: '%s: %y'
    }

};

$.plot(holder, data, Options );

A: When you hover over the dot the tooltipOpts: is called and it displays the content: '%s: %y'
%s reads as My_text_label
: is read as :
%y is read as %y
As you stated, it doesn't work on the test server but works fine locally.  The problem could be that your version of JQuery on your local machine is different to the version on the test server.

A: I have had issues with Flot graphs behaving differently in two different environments.  My issue was that, in the production environment, jQuery was getting reloaded after my Flot script tag was being called.  Since the Flot plugins were "attached" to the jQuery variable, the Flot functionality was getting overwritten.  For example, I could no longer call $.plot since the jQuery variable had been redefined.
I ended up having to use the $.getScript function to reload all the Flot code(including plugins) before calling $.plot after the page renders(and the Flot functionality has been overwritten).
In your case, since you are using a plugin, I am not sure how you could solve this effectively.  I have not tested it, but try using something like
$(window).on('load', function () {
    // add $.getScript calls here
});

to load your Flot js files and plugins.


text:
Q: Python signal handler weird behavior As far as I know, the signal handler in Python is executed in main thread, so I try the following script:
import signal, time
from threading import Event

def main():
        running = True
        event = Event()

        def handler(signal, frame):
                print("Value of event: %s" % event.is_set())
                print("Value of running: %s" % running)
                event.set()
                running = False

        signal.signal(signal.SIGINT, handler)
        while running:
                time.sleep(10)

if __name__ == '__main__':
        main()

After starting the program, I type Ctrl+C then the program raises the exception:

UnboundLocalError: local variable 'running' referenced before
assignment

As soon as I remove the line:
running = False

the program works fine. The value of event is False for the first Ctr-C then True for next times as expected.
So what is the problem of the code and the underlining mechanism of the handler when procesing basic type vs object?


text:
Q: How can I find an optimal point on a scatter graph? Suppose I am going to locate an emergency point on a field having 100 houses.
If we see this as a scatter graph with 100 points on it, I need to find a point (or let's call it an optimal point) which is the optimal choice for the emergency point. In other words, the SUM of travelling from the emergency point to all the houses (i.e. Emgncy point to Hous.No1 + Emgncy point to Hous.No2 + ... Emgncy point to Hous.No100) is the lowest possible value.

A: I'll attempt to explain the algorithm given at Wikipedia. Notice, though, that it isn't a formula for the answer, but an algorithm for getting better and better approximations of the answer. Given a starting point, call it $y_0$, the algorithm produces a sequence of points $y_0,y_1,y_2,\dots$ converging (most of the time) to the answer.
So, call the points on your scatter graph $x_1,x_2,\dots,x_m$. Given two points $x$ and $y$, write $\|x-y\|$ for the distance between $x$ and $y$. Pick a starting point, $y_0$. [In principle, this could be anything. I suppose it might be a good idea to choose $y_0$ to be the average of the $x_j$, $y_0=(1/m)\sum_{j=1}^mx_j$. Or maybe choose $y_0$ so its first component is the median of the first components of the $x_j$, and its second component is the median of the second components of the $x_j$. I don't know what's best, and I don't know how much difference it makes.]
Now if you have already computed the approximation $y_i$, you compute the next approximation, $y_{i+1}$, from the formula, $$y_{i+1}=\sum_{j=1}^m{x_j\over\|x_j-y_i\|}\div\sum_{j=1}^m{1\over\|x_j-y_i\|}$$ You keep computing better and better approximations, until they seem to converge to something, and then you're done.


text:
Q: How to use weight of a deep neural network which is trained in tensorflow-python api in a c++ project? I have trained some classification models with tensorflow 2.4 and now I want to use these trained models in a c++ project. I did similar work by tkDNN library(which is used to increase frame per second (fps)) but in this case I don't want to use tkDNN because I don't care about fps.
In the below code I used weight of trained yolo-tiny which is fixed point by tkDNN. Is there any library for feeding weights like this code to use dnn in c++?
int main()
{

int n_classes=3;

const char * net = "/home/tkDNN/build/yolo_tiny_3l_fp16.rt";

// instantiate detector
tk::dnn::Yolo3Detection yolo;
tk::dnn::DetectionNN *detNN;
detNN = &yolo;
int n_batch = 2;
detNN->init(net, n_classes, n_batch);

bool g;
g = true;
cv::VideoCapture cap(0);
if(!cap.isOpened())
    g = false;
else
    std::cout<<"camera started\n";

...


text:
Q: angularjs xeditable - show preselected value in editable-select with dynamic data from $http.get Why is the Group-Row empty, when i push the Edit Button?
I want to have the same value there from the list, when the Edit Mode is on an the Dropdown is visible.
How can i resolve this?
click for image
Please check this Working Code:
Here is my plnkr

var app = angular.module("employment", ["xeditable"]);

 app.run(function(editableOptions) {
   editableOptions.theme = 'bs3'; // bootstrap3 theme. Can be also 'bs2', 'default'
 });

 app.controller('EditableRowCtrl', function($scope, $filter, $http)
 {

    $scope.users = [];
    $http.get('userdata.json').success(function(data){
     $scope.users = data;
    });

    $scope.statuses = [
        {value: 1, text: 'aktiv'},
        {value: 2, text: 'inaktiv'}
    ];

    $scope.groups = [
        {id: 1, text: 'Administrator'},
        {id: 2, text: 'SuperUSer'},
        {id: 3, text: 'Mitglied'},
    ];

    $scope.showGroup = function(user) {
      if(user.group && $scope.groups.length) {
        var selected = $filter('filter')($scope.groups, {id: user.group});
        return selected.length ? selected[0].text : 'Not set';
      } else {
        return user.groupName || 'Not set';
      }
    };

    $scope.showStatus = function(user) {
      var selected = [];
      if(user.status) {
        selected = $filter('filter')($scope.statuses, {value: user.status});
      }
      return selected.length ? selected[0].text : 'Not set';
    };

    // remove user
    $scope.removeUser = function(index) {
      $scope.users.splice(index, 1);
    };

    // add user
    $scope.addUser = function() {
      $scope.inserted = {
        id: $scope.users.length+1,
        name: '',
        status: null,
        group: null
      };
      $scope.users.push($scope.inserted);
    };
 });

A: @M1ke, I don't know if you're still working on this.  I just saw this question.  The problem is that your status and group codes are defined as strings in  userdata.json and integers in the statuses and groups objects.  I just changed them to integers in the userdata and it worked like a charm.


text:
Q: SRF and Operating frequency for inductor As a rule of thumb the SRF(self resonant frequency) of an inductor should be higher than the operating frequency. I need to know why this inductor has lower SRF and why the operating frequency is much higher than SRF.
As I know the inductor and a chock are the same for using them with the same inductance and SRF. How is it possible the WA8514-AE(SRF<250Mhz) inductor is used as a RF chock for this application which frequency can be up to 2.7Ghz.

A: The data in the link says it can be operated to 3 GHz yet it has a self-resonant frequency (SRF) of 250 MHz. So, the answer lies in what applications might benefit from this part at frequencies higher than the SRF. Here's its impedance graph vs frequency: -

And this pretty much tells me that it would make a good ferrite bead at frequencies between about 30 MHz and 2 GHz. The peak shown in the graph will be mainly dissipative resistance and that is precisely what ferrite beads do and what applications they are targeted at: -

Image from here. And here's another from this site: -

How is it possible the WA8514-AE(SRF<250Mhz) inductor is used as a RF
chock for this application which frequency can be up to 2.7Ghz

Look at the impedance graph and ask yourself at what point does this drop close to anything like 50 ohm across the frequency range you need. Between 10 MHz and 3 GHz it has an impedance greater than 500 ohm. That makes it very usable as a bias setter for the PHA-202+.


text:
Q: Serverless Framework, setting up rest api lambda I wanted to make a lambda available at dev-api.example.com/auth/*.
The lambda will act like an auth service. So it will have urls like

*

*dev-api.example.com/auth/register

*dev-api.example.com/auth/login

*and more ...

Like wise more lambdas will be hooked to single ApiGateway.
With that design decision, I wrote following serverless.yml file.
// serverless.yml
...
custom:
  customDomain:
    domainName: dev-api.example.com
    stage: prod
    basePath: ''
...

functions:
  auth:
    handler: src/index.handler
    events:
      - http:
          method: ANY
          path: /{auth+}

It does not seem to work. Whenever I visit dev-api.example.com/auth/register it returns Not Found error.

A: AWS API Gateway only accepts {proxy+} syntax (Link), then I think serverless fw just support {proxy+} and {any+}.
If you want to just create a function to handle 2 api endpoint, in this case, the endpoints are
POST /auth/register (I think so)
POST /auth/login
Then you have setting in serverless.yml like
...
functions:
  auth:
    handler: src/index.handler
    events:
      - http:
          method: ANY
          path: auth/{any+} # this matches any path, the token 'any' doesn't mean anything special
...

A: Thanks @hoangdv , your suggestion almost fixed the problem.
The issue was with path. It should have been path: auth/{proxy+} instead of path: /{auth+}
functions:
  auth:
    handler: src/index.handler
    events:
      - http:
          method: ANY
          path: auth/{proxy+}