text:
Q: Icon works fine, expect on launcher itself I'm trying to build an app, but the main problem i'm having is that my icon isn't displaying like it should. When I install the app, the icon is the right one. but on my launcher screen its the default Phonegap one. Does anyone know how this could be possible?
these are my configs;
Phonegap config.xml
    <?xml version='1.0' encoding='utf-8'?>
<widget id="com.phonegap.helloworld" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:gap="http://phonegap.com/ns/1.0">
    <name>HelloWorld</name>
    <description>
        Hello World sample application that responds to the deviceready event.
    </description>
    <author email="support@phonegap.com" href="http://phonegap.com">
        PhoneGap Team
    </author>
    <feature name="http://api.phonegap.com/1.0/device" />
    <preference name="permissions" value="none" />
    <preference name="orientation" value="default" />
    <preference name="target-device" value="universal" />
    <preference name="fullscreen" value="true" />
    <preference name="webviewbounce" value="true" />
    <preference name="prerendered-icon" value="true" />
    <preference name="stay-in-webview" value="false" />
    <preference name="ios-statusbarstyle" value="black-opaque" />
    <preference name="detect-data-types" value="true" />
    <preference name="exit-on-suspend" value="false" />
    <preference name="show-splash-screen-spinner" value="false" />
    <preference name="auto-hide-splash-screen" value="true" />
    <preference name="disable-cursor" value="false" />
    <preference name="android-minSdkVersion" value="12" />
    <preference name="android-installLocation" value="auto" />
    <icon src="icon.png"/>
    <icon gap:density="ldpi" gap:platform="android" src="res/icon/android/icon-36-ldpi.png" />
    <icon gap:density="mdpi" gap:platform="android" src="res/icon/android/icon-48-mdpi.png" />
    <icon gap:density="hdpi" gap:platform="android" src="res/icon/android/icon-72-hdpi.png" />
    <icon gap:density="xhdpi" gap:platform="android" src="res/icon/android/icon-96-xhdpi.png" />
    <icon gap:platform="blackberry" src="res/icon/blackberry/icon-80.png" />
    <icon gap:platform="blackberry" gap:state="hover" src="res/icon/blackberry/icon-80.png" />
    <icon gap:platform="ios" height="57" src="res/icon/ios/icon-57.png" width="57" />
    <icon gap:platform="ios" height="72" src="res/icon/ios/icon-72.png" width="72" />
    <icon gap:platform="ios" height="114" src="res/icon/ios/icon-57-2x.png" width="114" />
    <icon gap:platform="ios" height="144" src="res/icon/ios/icon-72-2x.png" width="144" />
    <icon gap:platform="webos" src="res/icon/webos/icon-64.png" />
    <icon gap:platform="winphone" src="res/icon/windows-phone/icon-48.png" />
    <icon gap:platform="winphone" gap:role="background" src="res/icon/windows-phone/icon-173.png" />
    <gap:splash gap:density="ldpi" gap:platform="android" src="res/screen/android/screen-ldpi-portrait.png" />
    <gap:splash gap:density="mdpi" gap:platform="android" src="res/screen/android/screen-mdpi-portrait.png" />
    <gap:splash gap:density="hdpi" gap:platform="android" src="res/screen/android/screen-hdpi-portrait.png" />
    <gap:splash gap:density="xhdpi" gap:platform="android" src="res/screen/android/screen-xhdpi-portrait.png" />
    <gap:splash gap:platform="blackberry" src="res/screen/blackberry/screen-225.png" />
    <gap:splash gap:platform="ios" height="480" src="res/screen/ios/screen-iphone-portrait.png" width="320" />
    <gap:splash gap:platform="ios" height="960" src="res/screen/ios/screen-iphone-portrait-2x.png" width="640" />
    <gap:splash gap:platform="ios" height="1024" src="res/screen/ios/screen-ipad-portrait.png" width="768" />
    <gap:splash gap:platform="ios" height="768" src="res/screen/ios/screen-ipad-landscape.png" width="1024" />
    <gap:splash gap:platform="winphone" src="res/screen/windows-phone/screen-portrait.jpg" />
    <access origin="http://127.0.0.1*" />
</widget>

Cordova config.xml
<?xml version='1.0' encoding='utf-8'?>
<widget id="com.phonegap.helloworld" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:gap="http://phonegap.com/ns/1.0">
    <name>Hello Cordova</name>
    <description>
        A sample Apache Cordova application that responds to the deviceready event.
    </description>
    <access origin="*" />
    <content src="index.html" />
    <preference name="loglevel" value="DEBUG" />
    <feature name="App">
        <param name="android-package" value="org.apache.cordova.App" />
    </feature>
    <name>HelloWorld</name>
    <description>
        Hello World sample application that responds to the deviceready event.
    </description>
    <author email="support@phonegap.com" href="http://phonegap.com">
        PhoneGap Team
    </author>
    <feature name="http://api.phonegap.com/1.0/device" />
    <preference name="permissions" value="none" />
    <preference name="orientation" value="default" />
    <preference name="target-device" value="universal" />
    <preference name="fullscreen" value="true" />
    <preference name="webviewbounce" value="true" />
    <preference name="prerendered-icon" value="true" />
    <preference name="stay-in-webview" value="false" />
    <preference name="ios-statusbarstyle" value="black-opaque" />
    <preference name="detect-data-types" value="true" />
    <preference name="exit-on-suspend" value="false" />
    <preference name="show-splash-screen-spinner" value="true" />
    <preference name="auto-hide-splash-screen" value="true" />
    <preference name="disable-cursor" value="false" />
    <preference name="android-minSdkVersion" value="7" />
    <preference name="android-installLocation" value="auto" />
    <icon src="icon.png"/>
    <icon gap:density="ldpi" gap:platform="android" src="res/icon/android/icon-36-ldpi.png" />
    <icon gap:density="mdpi" gap:platform="android" src="res/icon/android/icon-48-mdpi.png" />
    <icon gap:density="hdpi" gap:platform="android" src="res/icon/android/icon-72-hdpi.png" />
    <icon gap:density="xhdpi" gap:platform="android" src="res/icon/android/icon-96-xhdpi.png" />
    <icon gap:platform="blackberry" src="res/icon/blackberry/icon-80.png" />
    <icon gap:platform="blackberry" gap:state="hover" src="res/icon/blackberry/icon-80.png" />
    <icon gap:platform="ios" height="57" src="res/icon/ios/icon-57.png" width="57" />
    <icon gap:platform="ios" height="72" src="res/icon/ios/icon-72.png" width="72" />
    <icon gap:platform="ios" height="114" src="res/icon/ios/icon-57-2x.png" width="114" />
    <icon gap:platform="ios" height="144" src="res/icon/ios/icon-72-2x.png" width="144" />
    <icon gap:platform="webos" src="res/icon/webos/icon-64.png" />
    <icon gap:platform="winphone" src="res/icon/windows-phone/icon-48.png" />
    <icon gap:platform="winphone" gap:role="background" src="res/icon/windows-phone/icon-173.png" />
    <gap:splash gap:density="ldpi" gap:platform="android" src="res/screen/android/screen-ldpi-portrait.png" />
    <gap:splash gap:density="mdpi" gap:platform="android" src="res/screen/android/screen-mdpi-portrait.png" />
    <gap:splash gap:density="hdpi" gap:platform="android" src="res/screen/android/screen-hdpi-portrait.png" />
    <gap:splash gap:density="xhdpi" gap:platform="android" src="res/screen/android/screen-xhdpi-portrait.png" />
    <gap:splash gap:platform="blackberry" src="res/screen/blackberry/screen-225.png" />
    <gap:splash gap:platform="ios" height="480" src="res/screen/ios/screen-iphone-portrait.png" width="320" />
    <gap:splash gap:platform="ios" height="960" src="res/screen/ios/screen-iphone-portrait-2x.png" width="640" />
    <gap:splash gap:platform="ios" height="1024" src="res/screen/ios/screen-ipad-portrait.png" width="768" />
    <gap:splash gap:platform="ios" height="768" src="res/screen/ios/screen-ipad-landscape.png" width="1024" />
    <gap:splash gap:platform="winphone" src="res/screen/windows-phone/screen-portrait.jpg" />
    <access origin="http://127.0.0.1*" />
</widget>

Android Manifext
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.phonegap.helloworld.androidsplashscreentimer"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:theme="@android:style/Theme.Holo.NoActionBar"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:logo="@drawable/ic_launcher">
        <!-- Main activity -->
        <activity
            android:name="com.phonegap.helloworld.HelloWorld"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"></action>
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.LAUNCHER"></category>
            </intent-filter>
        </activity>
    </application>

</manifest>

I've replaced all the default phonegap icons and splashscreens with my own..

A: On the left side you see res/drawable/ic_launcher.jpg. Add your ic_launcher.png or whatever, and it's done.
In Android Manifest:
android:icon="@drawable/ic_launcher"
android:logo="@drawable/ic_launcher"

change them.


text:
Q: Without using OOPS concept I am building apps in iOS  , can I build mobile apps in   iOS  using only structs to parse data from the web?

A: Essentially, no, you can't. And iOS app is built on many required frameworks such as UIKit. Things like view, label, view controller, table views, etc. are all using object oriented classes.
Even the basics of Swift start off with classes. Use a string, you've created an instance of a class. Use an integer, you've created an instance of a class. OK, technically both of those are actually structures but it is still object oriented.
You simply can't avoid OOP when writing an iOS app in a language like Swift or Objective-C. Accept the fact that you need to become familiar and comfortable with those concepts.
Start with the The Swift Programming Language book and you will be introduced to the concepts as you learn.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Textformfiled flutter: prefix and suffix not in line with the content The textformfiled i want

and My textformfield now

I'm trying create a search field like this.(attach this link) but the suffix, prefix icon not align with content
I am also attaching the code that I am using for this TextFormfield:
 Container(
            height: 35,
            width: Get.width - 40,
            decoration: BoxDecoration(
              color: backgroundColor.withOpacity(.8),
              borderRadius: BorderRadius.circular(20),
            ),
            child: TextFormField(
              textAlignVertical: TextAlignVertical.center,
              decoration: InputDecoration(
                contentPadding: const EdgeInsets.only(
                    left: 15, bottom: 10, top: 10, right: 15),
                border: InputBorder.none,
                focusedBorder: InputBorder.none,
                enabledBorder: InputBorder.none,
                errorBorder: InputBorder.none,
                disabledBorder: InputBorder.none,
                hintText: 'Search',
                prefix: IconButton(
                  constraints: const BoxConstraints(),
                  icon: Image.asset(
                    'assets/icons/back.png',
                    width: 20,
                    height: 20,
                    fit: BoxFit.scaleDown,
                  ),
                  onPressed: () => toast(content: 'back action'),
                  padding: EdgeInsets.zero,
                ),
                suffix: IconButton(
                  constraints: const BoxConstraints(),
                  icon: Image.asset(
                    'assets/icons/plus_circle.png',
                    width: 20,
                    height: 20,
                    fit: BoxFit.scaleDown,
                  ),
                  onPressed: () => toast(content: 'clear action'),
                  padding: EdgeInsets.zero,
                ),
              ),
            ),
          ),

A: You can use CupertinoSearchTextField and modify the way it as you like. If it doesnt satisfy, you can choose row over prefix and suffix alignment. Here are three looks and code.

CupertinoSearchTextField
child: CupertinoSearchTextField(
  padding: EdgeInsets.all(8),
  borderRadius: BorderRadius.circular(20),
  // decoration: BoxDecoration(
  //   color: Colors.grey,
  //   borderRadius: BorderRadius.circular(20),
  // ),
  prefixIcon: Icon(Icons.arrow_back_ios),
),

Using Row
Container(
  width: 400,
  decoration: BoxDecoration(
    color: Colors.grey,
    borderRadius: BorderRadius.circular(20),
  ),
  child: Row(
    crossAxisAlignment: CrossAxisAlignment.center,
    children: [
      IconButton(
        iconSize: 16,
        icon: Icon(
          Icons.ads_click,
        ),
        onPressed: () {},
        padding: EdgeInsets.zero,
      ),
      Expanded(
          child: TextFormField(
        decoration: InputDecoration(
          border: InputBorder.none,
          focusedBorder: InputBorder.none,
          enabledBorder: InputBorder.none,
          errorBorder: InputBorder.none,
          disabledBorder: InputBorder.none,
          hintText: 'Search',
          isDense: true,
        ),
      )),
      IconButton(
        iconSize: 16,
        icon: Icon(
          Icons.ads_click,
        ),
        onPressed: () {},
        padding: EdgeInsets.zero,
      ),
    ],
  ),
),

Using Prefix and suffix
Container(
width: 400,
decoration: BoxDecoration(
  color: Colors.grey,
  borderRadius: BorderRadius.circular(20),
),
child: TextFormField(
  decoration: InputDecoration(
    border: InputBorder.none,
    focusedBorder: InputBorder.none,
    enabledBorder: InputBorder.none,
    errorBorder: InputBorder.none,
    disabledBorder: InputBorder.none,
    hintText: 'Search',
    isDense: true,
    prefix: IconButton(
      iconSize: 16,
      icon: Icon(
        Icons.ads_click,
      ),
      onPressed: () {},
      padding: EdgeInsets.zero,
    ),
    suffix: IconButton(
      iconSize: 16,
      constraints: const BoxConstraints(),
      icon: Icon(Icons.ads_click),
      onPressed: () {},
      padding: EdgeInsets.only(right: 16),
    ),
  ),
),
),

IF you need to change size, provide height and width(if needed wrapped with SizedBox)

A: Wrap the icon in a column widget and give mainAxisAlignment center
Column(
  mainAxisAlignment: MainAxisAlignment.center,
   children:[ Icon(),]
  )

This will bring the icon to the center of the text field


text:
Q: Populate hidden field with post data from checkbox (multiselect) in JSP (or JSTL) I have a checkbox on page1.jsp that has more values:
<input type="checkbox" name="contactID" value="1" />
<input type="checkbox" name="contactID" value="2" />
<input type="checkbox" name="contactID" value="3" /> etc.

I do post through a form, and on the next page2.jsp i have:
    // below line fails
    <input type="hidden" name="contactID" value="${param.contactID}" />
    You have selected 2 people:
    - Name1
    - Name2

    Select a newsletter for them:
    {select}

    <button>Subscribe</>

Then on the third page, i want the same thing as i got here, because i like to subscribe all selected contacts to the newsletter. I cant use one page, because i also have other operations to the selected contacts (send email, send sms, subscribe to this and that etc).


text:
Q: How to Instantiate object of private class from .DLL? I'm either googling the wrong thing or trying to head down the completely wrong path (most likely)... but now I'm curious so I thought I'd ask.
Long story short, I'm trying to tap into the underlying "API" framework of Microsoft's Message Analyzer tool for a custom application.  I say "API" because there is no formal support for an API, no documentation, and there won't be any in the near future, if ever (so says Paul at Microsoft anyway).  So instead I've been using the IL DASM tool to poke around some of the Message Analyzer and PowerShell .dlls to try to get an understanding of how this stuff works; the ultimate goal of course is to use MA's .dlls and drivers to do what I want for the custom app.  I'm looking at Microsoft.Protocols.Tools.PowerShell.dll, which has a class (Microsoft.Protocols.Tools.PowerShell.PpkTraceSession) that I'm trying to instantiate:

However, if you look right below it, it says something about the class being private (it's cut off in the picture, but the class does implement IPpkTraceSession and IPpkTraceSessionEx).  Sure enough, when I reference this .dll in some C# code and try to instantiate an object, I get a compile error saying its inaccessible due to its protection level:

Windows PowerShell has no problem at all creating one of these objects.  It just so happens the printout seen below matches all the properties (not seen in the first picture) of the PpkTraceSession class, so I know Windows PowerShell is working some magic to create an object of that class,, I just can't figure out how since apparently this class is private.

So my question,, what's going on here?  I've poked around in a lot of the classes shown in the IL DASM output, and there are a surprising number of them that appear to be private.  Maybe it's just my bad practice, but I've rarely if ever used or seen many private classes.  It's my understanding they have to be nested in other classes to be of any particular use.  If PpkTraceSession is nested in another class, that's not clear from the IL DASM output at all.  You may see the IPpkTraceSession(Ex) interfaces above,, if there's a way to access the class properties using those I haven't figured it out yet.  Is there anyway to instantiate an object of this class, or am I going about this all wrong?
This might be close to a duplicate, but not quite I don't think.  Any help is much appreciated!  I clearly don't know much about Windows programming.
yano
EDIT:::::
Just to tie off all the loose ends (in case somebody else makes my mistake), I discovered the source of my confusion a couple of days ago.  All the classes indicated as "private" by the IL DASM tool are actually "internal" classes, meaning that they're meant to be visible only within their own assembly.  That was my missing piece, I couldn't understand where all these private classes were coming from when C# won't even let you compile a standalone private class (it must be nested within another class).  I should've done some more research on IL DASM before I posted a question, but it didn't even occur to me; I thought private meant private.  It's my observation that IL DASM does make a distinction between private/internal classes and nested private classes.  This issue has also already been addressed here: When I declare a class as internal, why does the IL show it as private? .  Thanks for the help everyone!

A: I suspect that what you are seeing is that other classes, probably deep inside the PowerShell plumbing, might expose some of the properties of the PpkTraceSession class. You might be able to find them by inspecting the intermediate language of the public classes exposed by the same dll THAT contains the private PpkTraceSession class. However, I suspect that you are wasting your time, and will not find a way to use those classes in your own code.
They are marked private because Microsoft has no intention of supporting them, and their behavior might change without notice. That isn't a problem within the PowerShell team, which has access to them, most likely through other private classes. So, if they need to change the way one of those classes behaves, they can do it, and the affected audience is small and easily reachable.
Speaking as a developer, I can think of a host of reasons that Microsoft might not want to support it, such as that it is very fussy, or that doing so would involve disclosing proprietary or patented technology that they have a legal right to keep secret.
Perhaps you could start a campaign to make them public, but you'll need to make a really good case, and convince a lot of other people, preferably people who already pay Microsoft a lot of money, to get behind you.


text:
Q: Can't upload files larger than 10MB via axios I am trying to send a file larger than 10MB (which is the default maximum) via axios.
This is my code:
let formData = new FormData();
                formData.append('files', this.file_xcode_ios);

                axios.post('/xcode_ios.php?timestamp=<?=$get_id;?>', formData, {
                headers: {'Content-Type': 'multipart/form-data'}
                  })

I am using this axios script (last version of axios 0.19.2)
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

I have read about:
maxContentLength: Infinity,
maxBodyLength: Infinity

But I can't make it work.
I get this error:
413 Request Entity Too Large

I would really appreciate if someone can help me fix this.

A: In some of the forums I came across using
maxContentLength: 10000000,
maxBodyLength: 10000000

instead of
maxContentLength: Infinity,
maxBodyLength: Infinity

A: maxContentLength: 10000000,
maxBodyLength: 10000000

I implemented on axios but don't can make http request with successfully , continue with error
Error [ERR_FR_MAX_BODY_LENGTH_EXCEEDED]: Request body larger than maxBodyLength limit
this is my code

axios.post(url, bodyFormData,{
                headers: {'Content-Type': 'multipart/form-data'},
                maxBodyLength: 10000000,
                maxContentLength: 10000000,
                emulateJSON: true

            })


text:
Q: How to create a button that runs a javascript function multiple times? Basically I want to be able to rotate the numbers clockwise when I click the rotate button. I think I've attached all of the associated code. I created a button. It links back to the javascript function. It even runs the function. The issue is I can only get it to run the function and rotate one time.

var value1 = "1";
var value2 = "2";
var value4 = "3";
var value3 = "4";

document.getElementById("value1").innerHTML = value1;
document.getElementById("value2").innerHTML = value2;
document.getElementById("value3").innerHTML = value3;
document.getElementById("value4").innerHTML = value4;

var btn = document.querySelector('#bt1');

btn.addEventListener('click', rotate)

function rotate() {
  var Value1 = value1;
  var Value2 = value2;
  var Value3 = value3;
  var Value4 = value4;
  document.getElementById("value1").innerHTML = Value4;
  document.getElementById("value2").innerHTML = Value1;
  document.getElementById("value3").innerHTML = Value2;
  document.getElementById("value4").innerHTML = Value3;
}
body {
  font-family: sans-serif;
  margin-left: auto;
  margin-right: auto;
  width: 20%;
}

.import {
  padding-bottom: 0.3em;
}

.import input[type=text] {
  width: 630px;
}

.valid {
  background-color: limegreen;
}

.invalid {
  background-color: red;
}

.imported_square {
  background-color: lightgray;
}

.puzzle {
  border: 4px solid black;
  border-collapse: collapse;
}

.puzzle tr {
  padding: 0;
}

.puzzle td {
  padding: 0;
  border: 1px solid black;
  width: 2em;
  font-size: 50pt;
  text-align: center;
}

.puzzle .thick_right {
  border-right: 4px solid black;
}

.puzzle .thick_bottom {
  border-bottom: 4px solid black;
}

  <button id="bt1">Rotate</button>

I've spent a long time scouring threads on here and also trying to create my own roundabout ways but nothing seems to work. I can get it to rotate once but I just can't find a way to make it rotate more than once. I want to be able to click the rotate button as many times as I want and the numbers keep rotating in a clockwise direction.

A: You can use a function to modify each number upon each round of rotation:

    var value1 = 1;
    var value2 = 2;
    var value4 = 3;
    var value3 = 4;

    document.getElementById("value1").innerHTML = value1;
    document.getElementById("value2").innerHTML = value2;
    document.getElementById("value3").innerHTML = value3;
    document.getElementById("value4").innerHTML = value4;

    var btn = document.querySelector('#bt1');

    btn.addEventListener('click', rotate)

    function nextNum(currentNum) {
      // upon each rotate, minus the current number by 1 or reset to 4
      return currentNum - 1 < 1 ? 4 : currentNum - 1
    }

    function rotate(){

        value1 = nextNum(value1)
        value2 = nextNum(value2)
        value3 = nextNum(value3)
        value4 = nextNum(value4)

        document.getElementById("value1").innerHTML = value1;
        document.getElementById("value2").innerHTML = value2;
        document.getElementById("value3").innerHTML = value3;
        document.getElementById("value4").innerHTML = value4;
    }
 body {
  font-family:sans-serif;
  margin-left: auto;
  margin-right: auto;
  width: 20%;
          }
.import {padding-bottom:0.3em;}
.import input[type=text] {width:630px;}

.valid {background-color:limegreen;}
.invalid {background-color:red;}
.imported_square {background-color:lightgray;}

.puzzle {border:4px solid black; border-collapse: collapse;}
.puzzle tr {padding:0;}
.puzzle td {padding:0; border:1px solid black; width:2em; font-size:50pt; text-align:center;}
.puzzle .thick_right {border-right:4px solid black;}
.puzzle .thick_bottom {border-bottom:4px solid black;}

  <button id="bt1">Rotate</button>

A: add in the rotate button values (next to id) onclick='rotate(element)' and add a parameter in rotate() function that says which element to rotate.

A: You keep rotating the same numbers so it seems the button isn't working. I've arranged the code so that the function would work. Pay attention to what variables is exchanged with another. This is counterclockwise rotation.

var value1 = "1";
var value2 = "2";
var value4 = "3";
var value3 = "4";

document.getElementById("value1").innerHTML = value1;
document.getElementById("value2").innerHTML = value2;
document.getElementById("value3").innerHTML = value3;
document.getElementById("value4").innerHTML = value4;

var btn = document.querySelector('#bt1');

btn.addEventListener('click', rotate)

function rotate() {
  var old_value1 = value1
  value1 = value2;
  value2 = value4;
  value4 = value3;
  value3 = old_value1;
  document.getElementById("value1").innerHTML = value1;
  document.getElementById("value2").innerHTML = value2;
  document.getElementById("value3").innerHTML = value3;
  document.getElementById("value4").innerHTML = value4;
}
body {
  font-family: sans-serif;
  margin-left: auto;
  margin-right: auto;
  width: 20%;
}

.import {
  padding-bottom: 0.3em;
}

.import input[type=text] {
  width: 630px;
}

.valid {
  background-color: limegreen;
}

.invalid {
  background-color: red;
}

.imported_square {
  background-color: lightgray;
}

.puzzle {
  border: 4px solid black;
  border-collapse: collapse;
}

.puzzle tr {
  padding: 0;
}

.puzzle td {
  padding: 0;
  border: 1px solid black;
  width: 2em;
  font-size: 50pt;
  text-align: center;
}

.puzzle .thick_right {
  border-right: 4px solid black;
}

.puzzle .thick_bottom {
  border-bottom: 4px solid black;
}

  <button id="bt1">Rotate</button>

A: You have to use array.

  <button id="bt1">Rotate</button>

A:

   var value1 = 1;
    var value2 = 2;
    var value4 = 3;
    var value3 = 4;

    document.getElementById("value1").innerHTML = value1;
    document.getElementById("value2").innerHTML = value2;
    document.getElementById("value3").innerHTML = value3;
    document.getElementById("value4").innerHTML = value4;

    var btn = document.querySelector('#bt1');

    btn.addEventListener('click', rotate)

    function rotate() {
        if(value1 === 1) {
            value1 = 4
        }else {
            value1--
        }

        if(value2 === 1) {
            value2 = 4
        }else {
            value2--
        }

        if(value3 === 1) {
            value3 = 4
        }else {
            value3--
        }

        if(value4 === 1) {
            value4 = 4
        }else {
            value4--
        }

        document.getElementById("value1").innerHTML = value1;
        document.getElementById("value2").innerHTML = value2;
        document.getElementById("value3").innerHTML = value3;
        document.getElementById("value4").innerHTML = value4;

    }
body {
  font-family: sans-serif;
  margin-left: auto;
  margin-right: auto;
  width: 20%;
}

.import {
  padding-bottom: 0.3em;
}

.import input[type=text] {
  width: 630px;
}

.valid {
  background-color: limegreen;
}

.invalid {
  background-color: red;
}

.imported_square {
  background-color: lightgray;
}

.puzzle {
  border: 4px solid black;
  border-collapse: collapse;
}

.puzzle tr {
  padding: 0;
}

.puzzle td {
  padding: 0;
  border: 1px solid black;
  width: 2em;
  font-size: 50pt;
  text-align: center;
}

.puzzle .thick_right {
  border-right: 4px solid black;
}

.puzzle .thick_bottom {
  border-bottom: 4px solid black;
}

  <button id="bt1">Rotate</button>

A: Use loops and arrays in this case.
I didn't focus much on design. But this Javascript code will work on your script too.

function rotate() {

 var array = []

  document.querySelectorAll('td').forEach((element) => {
    array.push(element.innerText)
  })

  array.push(array.shift())

  document.querySelectorAll('td').forEach((element, index) => {
    element.innerText = array[index]
  })

}
table{
  border-collapse: collapse;
}

table td{
  border: 2px solid #111;
  padding: 20px;
}

button{
  margin-top: 20px;
  border: none;
  outline: none;
  padding: 10px 16px;
  background: #111;
  color: #FFF;
}

    1
    2
    3
    4

<button onclick='rotate()'>Rotate</button>


text:
Q: Angular 2 with client side typescript compiler I'm learning Angular 2 with typescript.
My first step is a simple hello world with client side typescript compilation.
I'm also using wamp 3.0.4.
So I have
index.html
<!DOCTYPE html>

    <title>Hello Angular</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

Angular 2 with TypeScript

    <my-app>Loading AppComponent content here ...</my-app>

config.js
System.config({
  transpiler: 'typescript',
  typescriptOptions: {
    emitDecoratorMetadata: true
  },
  paths: {
    'npm:': 'https://unpkg.com/'
  },
  map: {
    'app': './app',
    '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
    '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
    '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
    '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
    '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
    '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
    '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
    '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
    'rxjs': 'npm:rxjs',
    'typescript': 'npm:typescript@2.0.2/lib/typescript.js'
  },
  packages: {
    app: {
      main: './main.ts',
      defaultExtension: 'ts'
  }
});

main.ts
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';
platformBrowserDynamic().bootstrapModule(AppModule)

and app.module.ts
import {Component,NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
@Component({
  selector: 'my-app',
  template: `

Hello {{name}}

  `,
})
export class App {
  name:string;
  constructor() {
    this.name = 'Angular2'
  }
}
@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

I don't know if everything is necessary but ... it is working.
The problem is that if I now modify app.module.ts, let say
Hello my name is {{name}}
 the modifications are not shown when I refresh the web page.  To have it working I have to close the browser and open the page again.  It is like the compilation was done only once and cached.
Is it a problem with wamp ?  with my application ?

A: While I don't use System js it seems like you didn't activate hot reloading. Webpack is simpler if you are a beginner I'd advise to take a look at angular-cli.
Anyway here it says that you have to use the hot reloader. I think that's what it is, I never used systemjs so... It could also be because of wamp, maybe go for a standard setup (hint: angular-cli, or do like the angular 2 doc does), serving your files should be a one liner in the cmd, no need for wamp or anything weird when you are just starting.

A: After you modify app.module.ts, it is recompiled, since you can see the change after you reopen. The modification only works when you close and open the page, I think the reason is about the browser cache. You can try to clear the cache and refresh. And, the recompilation will take some time, like several seconds.
The auto-compilation is done by the tool you use. I think you have some watch in you script of starting test server. Maybe you use webpack, or the script (which is used in official getting started tutorial).
If you want to compile the typeScript code by yourself, you can use tsc, which is command tool of npm package TypeScript.


text:
Q: Tcl: Interpreter creates copy of traced object whet it goes changed #include <tcl.h>
#include <iostream>
using namespace std;

char* myTraceProc(ClientData clientData, Tcl_Interp* interp, const char* name1, const char* name2, int flags) {
    cout << "myTraceProc" << endl;
    //changing the object
    return NULL;
}

int main(int argc, char* argv[]) {
    Tcl_FindExecutable(argv[0]);
    Tcl_Interp *interp = Tcl_CreateInterp();

    Tcl_TraceVar(interp, "database", TCL_TRACE_WRITES, myTraceProc, 0);

    return 0;
}

This is a part of my c++/tcl program. In fact it doesn't show the problem but I'll try to explain it.
The variable database has custom type. It is registrated using Tcl_RegisterObjType proc. The problem is that when I do a change with traced object in the myTraceProc proc, interpreter duplicates the object (Tcl_DupInternalRepProc is called). This is not desired behavior of the program. It would be great if clone doesn't be created and all charges be done with the exact object. I have looked Tcl_TraceVar documentation but didn't find an way to disable it.

A: First off, Tcl's type system is very different to that used in C++ (and many other languages besides) in that:

*

*Types attach explicitly to values, not to variables.

*Values can be mutated between types. (This can be done by serialisation to a string and then parsing that string, or it can be done via a more efficient mechanism; the details are very specific to the exact example.)

Secondly, Tcl_RegisterObjType() has no special relationship to any other API except for Tcl_GetObjType(), which does the lookup in the table that T_RegisterObjType makes an entry in. Tcl itself does not call Tcl_GetObjType anywhere; you gain no advantage from registering the type other than to allow another extension package to get hold of the type if it wishes. We also don't document what types there are. Not all of Tcl's internal types are registered — the set of types is not even guaranteed between patch versions — and there's no public guarantee of what the effect of operations are on the types of arguments (though some are currently pretty easy to guess, such as with list and dictionary operations).
Because of these points, you need to change the approach you are using. Instead of putting a database handle directly in the value, instead put a human-readable string that you can use to look up the real handle in a hash table. This is pretty easy to get right, and requires significantly less tricky coding. The only downside is that you end up having to use manual disposal of the handle; typically you'd do this by having a closeDatabase $handle operation, or by setting an unset trace on a variable such that you can just do unset handle (or just to from a procedure, in the case of a local variable) to have the deletion happen. This is a classic approach that has been written about a lot, so I won't go into all the details here. (You might also find this code interesting which I wrote rather a long time ago.)
A more sophisticated approach is to bind the handle into a TclOO object. The TclOO C API has a mechanism to allow you to register the handle as a hidden internal value on the instance object which you can retrieve easily from your TclOO methods (provided they're using the TclOO C API, instead of being scripted) and you then get to benefit from the lifetime management code used in TclOO (well-defined constructors and destructors, callbacks when the containing entity is deleted, etc.). This is how many of TDBC's database drivers work (e.g., tdbc::odbc does exactly this under the hood).
Finally, if this is a real database you're talking to, use an existing database extension (TDBC-compliant is recommended). Why? Because then you're not having to maintain a large body of code to do the connection management; you can delegate that all to scripts (easy to write) and extensions maintained by other people. Your calls to access the database from C++ can then just become invocations of (self-provided) Tcl commands, probably via Tcl_EvalObjv as that is the most efficient public command invocation function.


text:
Q: docker build shows: failed sandbox add: failed to set gateway while updating gateway: invalid argument I am running docker on a linux system.
The linux uname -a shows: Linux TENCENT64.site 3.10.94-1-tlinux2-0036.tl2
The docker version is: 1.8.3
when I try to build a image, docker return the error message: failed sandbox add: failed to set gateway while updating gateway: invalid argument
My Dockerfile is:
# centos 7

FROM centos:7
MAINTAINER a b

# make work dirs
RUN mkdir /workspace

# add passport files
COPY ./output.tar.gz /workspace/

# add start script
COPY ./resources/start.sh /workspace/

EXPOSE 22
EXPOSE 8082

CMD ["/usr/sbin/sshd", "-D"]

the full error message is:
Sending build context to Docker daemon 3.284 MB
Step 0 : FROM centos:7
 ---> eeb3a076a0be
Step 1 : MAINTAINER AlphaCloud wangziyi <wangziyi@didichuxing.com>
 ---> Using cache
 ---> dc3d3f638d8d
Step 2 : RUN mkdir /workspace
 ---> Running in 53a34c6d1731
failed sandbox add: failed to set gateway while updating gateway: invalid argument

My docker process is:
/usr/bin/docker daemon --ip-forward=false --iptables=false --insecure-registry=10.10.10.39

help me

A: Yes, we read some source code of docker, this error is because docker can't find a gateway to access network. our kernel is cut some network models, so we have to run docker in host network mode.
add --bridge=none to your docker daemon start command.
the full start command is docker daemon --bridge=none --ip-forward=false --iptables=false
but, there is some effect on docker build
you can't build image using like yum or else network needed way.
detail see: https://github.com/docker/docker/issues/22064


text:
Q: Trying to call class method from a Trigger So my class has
global class SendQueue{
@InvocableMethod
public static void send(List<ListRequests> requests)
{...}
global class ListRequests{
@InvocableVariable(required=True)
public Id ownerID;
 }
}

My Trigger
trigger CallBack on Task (before insert) {
SendQueue.ListRequests listVars = new SendQueue.ListRequests();
List<listVars> requests = new listVars();
....
SendQueue.send(); //trying to call the send function in the class
}

When trying to compile the trigger, there is an error of Invalid type:listVars.

A: There is compile error because you are trying to declare variable requests of incorrect type. List is container and this container should have some type. For example, List<String>, List<SObject> etc. List<listVars> is icorrect if you don't have listVars class in your namespace.


text:
Q: Problem with PlanarGraphPlot And ConvexHull I'm getting a lot of strange errors when using PlanarGraphPlot with a simple list of 11 points.  This is using Mma 9.0.1 64-bit Mac OS X.
<< ComputationalGeometry`;
x = {{184978.59580704456`, 77909.66948289984`},
     {184978.27815712072`,77909.76595227784`},
     {184978.27082673783`, 77909.74177736834`},
     {184977.5543690799`, 77909.95958192856`},
     {184977.65873976916`, 77910.2913545858`},
     {184977.87393886593`, 77910.32174601014`},
     {184978.3127146399`, 77911.75682671613`},
     {184979.13720817852`, 77911.37094455786`},
     {184979.40459261995`, 77911.34308556134`},
     {184979.6157774594`, 77912.04232488069`},
     {184980.40222282038`, 77911.69604330455`}};
PlanarGraphPlot[x]

Errors I get are
Mod::indet: Indeterminate expression Mod[-1,0] encountered. >>

Part::partw: Part 1 of {} does not exist. >>

Part::pspec: Part specification Indeterminate is neither a machine-sized integer nor a list of machine-sized integers. >>

Part::pspec: Part specification {{4,2},{1,4,6},{6},{7,2,1},{6,6},{2,5,6,3,5},{11,10,9,4},{},{7,10},{9,7,11},{10,7}}[[8,1]] is neither a machine-sized integer nor a list of machine-sized integers. >>

Part::pspec: Part specification {{4,2},{1,4,6},{6},{7,2,1},{6,6},{2,5,6,3,5},{11,10,9,4},{},{7,10},{9,7,11},{10,7}}[[8,1]] is neither a machine-sized integer nor a list of machine-sized integers. >>

General::stop: Further output of Part::pspec will be suppressed during this calculation. >>

Part::partw: Part 1 of {} does not exist. >>

Set::shape: Lists {ComputationalGeometry`Private`merge$30945[[ComputationalGeometry`Private`l0$30945]],ComputationalGeometry`Private`merge$30945[[ComputationalGeometry`Private`r0$30945]]} and ComputationalGeometry`Private`insert[{{4,2},{1,4,6},{6},{7,2,1},{6,6},{2,5,6,3,5},{11,10,9,4},{},{7,10},{9,7,11},{10,7}}[[{6,{{4,2},{1,4,6},{6},{7,2,1},{6,6},{2,5,6,3,5},{11,10,9,4},{},{7,10},{9,7,11},{10,7}}[[8,1]]}]],6,{{4,2},{1,4,6},{6},{7,2,1},{6,6},{2,<<3>>,5},<<1>>,{},{7,10},{9,7,11},{10,7}}[[<<1>>]],2,3] are not the same shape. >>

Mod::indet: Indeterminate expression Mod[-1,0] encountered. >>

Part::partw: Part 1 of {} does not exist. >>

General::stop: Further output of Part::partw will be suppressed during this calculation. >>

Set::shape: Lists {ComputationalGeometry`Private`merge$33935[[ComputationalGeometry`Private`l0$33935]],ComputationalGeometry`Private`merge$33935[[ComputationalGeometry`Private`r0$33935]]} and ComputationalGeometry`Private`insert[{{4,2},{1,4,6},{6},{7,2,1},{6,6},{2,5,6,3,5},{11,10,9,4},{},{7,10},{9,7,11},{10,7}}[[{6,{{4,2},{1,4,6},{6},{7,2,1},{6,6},{2,5,6,3,5},{11,10,9,4},{},{7,10},{9,7,11},{10,7}}[[8,1]]}]],6,{{4,2},{1,4,6},{6},{7,2,1},{6,6},{2,<<3>>,5},<<1>>,{},{7,10},{9,7,11},{10,7}}[[<<1>>]],2,3] are not the same shape. >>

Mod::indet: Indeterminate expression Mod[-1,0] encountered. >>

General::stop: Further output of Mod::indet will be suppressed during this calculation. >>

Set::shape: Lists {ComputationalGeometry`Private`merge$35305[[ComputationalGeometry`Private`l0$35305]],ComputationalGeometry`Private`merge$35305[[ComputationalGeometry`Private`r0$35305]]} and ComputationalGeometry`Private`insert[{{4,2},{1,4,6},{6},{7,2,1},{6,6},{2,5,6,3,5},{11,10,9,4},{},{7,10},{9,7,11},{10,7}}[[{6,{{4,2},{1,4,6},{6},{7,2,1},{6,6},{2,5,6,3,5},{11,10,9,4},{},{7,10},{9,7,11},{10,7}}[[8,1]]}]],6,{{4,2},{1,4,6},{6},{7,2,1},{6,6},{2,<<3>>,5},<<1>>,{},{7,10},{9,7,11},{10,7}}[[<<1>>]],2,3] are not the same shape. >>

General::stop: Further output of Set::shape will be suppressed during this calculation. >>

Removing certain points from the list (like the last one) causes the plot to succeed.
Also this set of points fails to give proper ConvexHull
y = {{1.8497859580704457`, 0.7790966948289985`},
    {1.8497827815712071`, 0.7790976595227784`},
    {1.8497827082673783`, 0.7790974177736835`},
    {1.849775543690799`, 0.7790995958192857`},
    {1.8497765873976917`, 0.779102913545858`},
    {1.8497787393886593`, 0.7791032174601015`},
    {1.849783127146399`, 0.7791175682671613`},
    {1.8497913720817853`, 0.7791137094455786`},
    {1.8497940459261994`, 0.7791134308556135`},
    {1.849796157774594`, 0.7791204232488069`},
    {1.849804022228204`, 0.7791169604330455`},
    {1.849803552734635`, 0.7791159289575218`},
    {1.8498057134522492`, 0.7791151852825192`},
    {1.8498006729413692`, 0.7790991813917657`},
    {1.8498002121744468`, 0.7790984699581178`},
    {1.8497995890919037`, 0.7790977401058187`},
    {1.8497986151981813`, 0.7790973602143807`},
    {1.8497975924352397`, 0.7790973993547065`},
    {1.8497955957785752`, 0.77909842160827`},
    {1.8497951821355425`, 0.7790997823117062`},
    {1.8497944840038416`, 0.779101624213374`},
    {1.8497934996381435`, 0.7791037516125543`},
    {1.8497920021456453`, 0.779106194441444`},
    {1.849792775326504`, 0.7791094914607818`},
    {1.8497897908134828`, 0.7791098506337076`}}
Graphics@Point@y[[ ConvexHull[y] ]]

Thanks

A: Numbers are too big and too close  ... a recipe for numeric disaster. Just translate them to the origin:
<< ComputationalGeometry`
PlanarGraphPlot[Transpose[Transpose@x - Mean[x]]]

A: Also
PlanarGraphPlot[TranslationTransform[- Mean @ x] @ x]


text:
Q: Call controller method from outside the controller I have an implementation of the RenderTone method for sound playback and from that method I want to call controller methods. I'm able to acces controller members fine like this:
InstrumentGridViewController *viewController = (InstrumentGridViewController *)inRefCon;
viewController->count = 7;

But what I want to do is call a method the same way. I tried this but it's not working:
viewController->stopToneUnit;

My method implementation looks like this:
- (void) stopToneUnit{
    AudioOutputUnitStop(toneUnit);
    AudioUnitUninitialize(toneUnit);
    AudioComponentInstanceDispose(toneUnit);
    toneUnit = nil;
}

How should I call this method?

A: In Objective-C the syntax for sending messages is:
[viewController stopToneUnit];


text:
Q: AngularJS animating prepended $scope data I have an array named $scope.data with some objects in it, and then I make a call and get older data and I prepend the data to the array.
  TestQuery.query({start:0, end: Date.now()}, function(response){

    if (response.length > 0) {
      response.reverse();
      $scope.data.reverse();
      $scope.data = $scope.data.concat(response).reverse();
    };

  });

How would you go about animating this change in scope? I want to move the text down and animate the new data coming in. Simple is fine and preferable. Very new to Angular, help is very much appreciated. I would like to remain in Angular world and not use any jQuery is possible.


text:
Q: Parsing a book or article pdf to get metadata I want to extract metadata (title, authors, publication date etc.) from the pdf files which I know they are books or articles. Is there any template for books and articles? While parsing, how can I know that I found the right thing? Which tools or libraries can I use?
There is a question partly about my question: Libraries for parsing PDF, PostScript and/or DjVu

A: As far as I know there is now standard for a layout of PDF books and  layout is always specific to the particular publisher. But I think that if you want to automate the classification of books stored in PDF format then you might consider the following scenario:

*

*take 2 to 5 major publishers (that 80% from 80/20 Paretto principle) and check first pages of PDF book for their specific headers or footers, like "published by PublisherName"

*compare the structure of the source PDF with patterns you have created on the previous step. You may extract structure of the visual layout working with low-level libraries like iTextSharp or with high-level libraries like commercial PDF Extractor SDK that provides API to access by column/row.

*sort out input books by these filters to find out which publisher made the book.

*apply the pre-coded extraction for the selected publisher to the book and the layout this or that publisher uses.

This way you may try to cover major publishers and leave non-major publishers to for the manual categorization. Please also note that PDF files includes Producer, Author, Title fields as standard header that you may use for the additional source of information about books.
Disclosure: I'm related to ByteScout, maker of PDF Extractor SDK and free PDF Multitool


text:
Q: How to use content negotation format parameter in Spring WebFlux? spring.mvc.contentnegotiation.favor-parameter=true
spring.mvc.contentnegotiation.parameter-name=format

How can I use the content negotiation feature in spring webflux?
So that /request?format=json is possible beside Accept header.

A: It works as follows, but don't know it that's the correct way:
@Configuration(proxyBeanMethods = false)
public class ReactiveWebFluxConfigurer {
    @Value("${spring.mvc.contentnegotiation.parameter-name}")
    private String formatName;

    @Bean
    public WebFluxConfigurer webFluxConfigurer() {
        return new WebFluxConfigurer() {
            @Override
            public void configureContentTypeResolver(RequestedContentTypeResolverBuilder builder) {
                builder.parameterResolver().parameterName(formatName);

                //if you want, add additional fallback to Accept header if format param is missing
                builder.headerResolver();
            }
        };
    }
}


text:
Q: Determine MySql mode from PHP Is there any way to find if mysql server is in strict mode or not from PHP?
I need to find out this at runtime(in installation script), so I can inform user if his system satisfy script requirements.

A: SELECT @@sql_mode; will give what you want.

A: I think you can run a simple query like
SELECT @@sql_mode;

This should be able to get you your SQL mode. There is more information at http://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html about how you can manage the mode if need be.


text:
Q: ActiveMQ Artemis Jolokia returns Status "404" I want to get the amount of messages I have in my ActiveMQ Artemis queue, but when I execute this command:
curl -v -H "Origin:http://IP:port" -u user:pass http://IP:Port/console/jolokia/read/org.apache.activemq.artemis:broker=0.0.0.0,component=addresses,address=123456,subcomponent=queues,routing-type=anycast,queue=123456/MessageCount

I get this error
"error":"javax.management.InstanceNotFoundException : org.apache.activemq.artemis:broker=0.0.0.0,component=addresses,address=123456,subcomponent=queues,routing-type=anycast,queue=123456","status":404

Do you know why? If I put this URL
http://IP:Port/console/jolokia/read/org.apache.activemq.artemis:broker=0.0.0.0,component=addresses,address=123456,subcomponent=queues,routing-type=anycast,queue=123456/MessageCount

in a browser like Chrome it works but with curl it doesn't work.

A: The name of an queue's MBean follows this pattern:
org.apache.activemq.artemis:broker="brokerName",component=addresses,address="addressName",subcomponent=queues,routing-type="routingType",queue="queueName"

Note that the quotation marks are part of the MBean's name. Therefore you need to specify them in your curl command. Here's an example that works for me with the default broker:
curl -v -H "Origin: http://localhost" -u myUser:myPass http://localhost:8161/console/jolokia/read/org.apache.activemq.artemis:broker=\"0.0.0.0\",component=addresses,address=\"DLQ\",subcomponent=queues,routing-type=\"anycast\",queue=\"DLQ\"/MessageCount

Notice the quotation marks along with the proper escaping so it executes on the command-line. There is a similar (although simpler) example in the documentation.


text:
Q: Shopify - Making an API request to update user's email Using the Shopify Admin API - I've been able to update a user's email address.
I've tested it with Postman, passing in a private app secret key.
Now I want to have this functionality on an actual page however have some questions:

*

*I can't exactly store those private app keys on the JS code of the page itself as anyone would see. Neither can I make send a request with it as again anyone would have visbility.

*Is it possible to create some sort of intermediary where I could make some sort of endpoint like POST /update/useremail sending across a customer ID

*If the above is possible - I'm not sure how I could avoid any random person hitting that endpoint and updating other user's email addresses.

Has anyone had any experience/ideas/suggestions for a simply way to do this?
Any help appreciated.
Thanks.

A: Issue: Your issue is here that you want to verify if the email change request is a valid call or not? Then if you find it valid then you make the API call to update it.
My Solution
Create a page in Shopify with your form to update email. Show the page only to logged in users. When a user lands in the page show them the form to pass the new email they want. This where you need to add a few things so as to validate the requests. When the page loads create a hashed string from the Shopify Backend like below.
{% if customer != nil %}
  {% assign timestamp = 'now' | date: "%s" %} //epoch time stamp
  token = {{ customer.email | append: '<random_string>' | append: timestamp | sha256 }}
{% endif %}

Whenever a request is made for a change of email validate the SHA256 code at your end by creating a hash at your server. If the hash is valid update the email. Make sure you pass the timestamp and old email in the request you make.
Security issues you need to take care of -

*

*You need to validate timestamp always For eg. It should not be 10 secs in the future or 10 secs in the past.

*Your random string can also be brute forced. So keep updating the random string regularly using Assets API. It is very unlikely but why take the risk.


text:
Q: Solving Simultaneous Modulus Equations I'm trying to figure out how to solve multiple simultaneous modulus equations.  The problem I'm hitting is that I get to a point where there's too many unknowns or degrees of freedom for how many equations I have and I'm not sure what to do about it.
For instance, let's say I have these 4 equations:
$A mod K_0 = 0$
$A mod K_1 = 1$
$B mod K_0 = 0$
$B mod K_1 = 0$
I'm trying to find any values of $A$,$B$,$K_0$ and $K_1$ that satisfy the above.
I know that I can transform each of those into the four following equations:
$A = K_0N_0$
$A = K_1N_1+1$
$B = K_0N_2$
$B = K_1N_3$
Where $N_i \epsilon \mathbb Z$.
That then seems to leave me with 4 unknowns ($A$,$B$,$K_0$,$K_1$) and four values that can be any integer value ($N_0$, $N_1$, $N_2$, $N_3$), and four equations.
Four equations with four unknowns sounds like I'm basically there, but what do i do about the $N_i$ values?
How do I go about finding values for $A$,$B$,$K_0$ and $K_1$ that fit the original 4 equations?
EDIT: Since posting this question i've learned a number of things, but am still stuck.
I know modular multiplicative inverse, the chinese remainder theorem, and the extended euclidean algorithm.
I can solve modulus equations of the form: $x \% 10 = 2$
$x \equiv 2 + 10 \mathbb Z$
This form: $((x\%7)\%5)\%2=1$$x \equiv (1 + 7 \mathbb Z) \cup (3 + 7 \mathbb Z) \cup (6 + 7 \mathbb Z)$
$x \in${…, -6, -4, -1, 1, 3, 6, 8, 10, 13, 15, 17, 20, …}
and This form: $3\%x=1$
$x | 2$


text:
Q: Using the same activity for different buttons but different action using xml resource I am doing a project in Android Studio. I will have 2/3 activities at most. On main activity I will have some buttons. There will be a second activity. So for each button that second activity will pop up and show some more buttons or imageButton but they will be different. The buttons on the second activity will also be meant for different actions but all of it will be on a third activity. The third activity will have some images and a text view. So image view and text view will show different data from the "XML resource" for different buttons. Any ideas how I can do it?I am using Android Studio.
Can it be done using base Adapter?
Also when all the data are stored on sql database, what different thing do I need to do?
Thank You!

A: When you go from main activity to the second activity, you must be using intent.
You can add extra info in your intent to to modify accordingly using putExtra()
Then in your second activity, you can simply retrieve the extra info and make changes accordingly.
in main activity,
//your first button
    Button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        Intent newintent= new Intent(MainActivity.this, SecondActivity.class);
        newintent.putExtra("details", "load first set of images");
        startActivity(newintent);
        }
    });
//your second button
    Button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        Intent newintent= new Intent(MainActivity.this, SecondActivity.class);
        newintent.putExtra("details", "load second set of images");
        startActivity(newintent);
        }
    });

in second activity,
 String extrainfo=getIntent().getStringExtra("details");
 if(extrainfo.equals("load first set of images"))
{
//make your changes accordingly
}
else if(extrainfo.equals("load second set of images"))
{
//make your changes accordingly
}
else
{
//make according changes
}

This is how you can achieve it.
Hope this helps!


text:
Q: Why code in OnNewIntent() is executed twice? I am using singleTop mode in my main Activity. I am using SearchWidget
This is manifest for my MainAcivity:
<activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:launchMode="singleTop" >

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <action android:name="android.intent.action.SEARCH" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

        <meta-data
            android:name="android.app.searchable"
            android:resource="@xml/searchable" />
</activity>

onNewIntent  is called twice:
protected void onNewIntent(Intent intent) {

    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {

     // here is my code

    }

}

Why does it happen?

A: Are you using Hardware keyboard to perform search? If yes, the double-execution is a known but never fixed Android bug.
You might want to try using an integer lock variable to avoid double-execution.
I have an Android 4.2.2 device with the same issue. Similar behavior was observed in Android Emulator.


text:
Q: Problem with perl signal INT I have the following perl code on windows activestate perl 5.8
  $SIG{INT}=\&clean;

  ...
  sub clean {

  print 'cleaning...';
  ...
  ...
  exit 0;

  }

but when i try to close my program by Ctrl^c it didn't enter the sub clean at all could someone help why did i miss something ?

A: It seems that Windows doesn't provide signals as in Unix.
From man perlwin32:

Signal handling may not behave as on Unix platforms (where it doesn't
      exactly "behave", either :).  For instance, calling "die()" or "exit()"
      from signal handlers will cause an exception, since most implementations
      of "signal()" on Win32 are severely crippled.  Thus, signals may
      work only for simple things like setting a flag variable in the handler.
      Using signals under this port should currently be considered
      unsupported.

A: I'd say no.  I can't see anything wrong with what you're doing.  I wrote a test program that actually runs:
#!/usr/bin/perl

use strict;
use warnings;

$SIG{INT}=\&clean;

sub clean {
    print 'caught';
}
sleep 10;

Tested on Linux, this works as expected, but I don't have AS perl handy to try it.  Try it yourself on your machine.
Also, print to STDERR to ensure it's not something very odd going on with print buffering.

A: I found that the script given by @ijw (modified to be what it is below) does not work under Active State Perl version v5.10.1:
This is perl, v5.10.1 built for MSWin32-x86-multi-thread
(with 2 registered patches, see perl -V for more detail)

My modification below adds the autoflush calls (as otherwise the sleep
below would not show the print statement output at all while
sleeping):
#!/usr/bin/perl

use IO;
use strict;
use warnings;

# Set autoflushing on to stdout and stderr.  Otherwise, system() call and stdout output does not show up in proper sequence,
# especially on Windows:
STDOUT->autoflush(1);
STDERR->autoflush(1);

$SIG{INT}=\&clean;

sub clean {
    print "caught\n";
    exit (0);
}

print "before sleep\n";
sleep 100;
print "after sleep and then exiting\n";
exit (0);

When I commented out the following lines in that script above:
$SIG{INT}=\&clean;

sub clean {
    print "caught\n";
    exit (0);
}

And then hitting CTRL-C during the sleep, the script does terminate and show this message:
Terminating on signal SIGINT(2)

Hence it must actually still be true (well, for ActiveState Perl v5.10.1) what man perlwin32 states:

... most implementations of "signal()" on Win32 are severely crippled. ...

For future reference:

*

*perlmonks refers to the use of Win32::API to setup a call to the SetConsoleCtrlHandler Win32 function.

*All about SetConsoleCtrlHandler.


text:
Q: Discord.py | How to assign someone a role? I am trying to mute someone using a role Muted
The Code:
@bot.command()
async def mute(ctx, member:commands.MemberConverter):
    role = discord.utils.find(lambda r: r.name == 'Muted', ctx.guild.roles)
    await member.edit(roles=[role])

But I get this weird error:
Ignoring exception in command mute:
Traceback (most recent call last):
  File "C:\Users\gathi\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\gathi\Vscode\Discord_Bot\tutorial.py", line 61, in mute
    await member.edit(roles=[role]) # 848410518154117130
  File "C:\Users\gathi\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\member.py", line 681, in edit
    await http.edit_member(guild_id, self.id, reason=reason, **payload)
  File "C:\Users\gathi\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\http.py", line 248, in request
    raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\gathi\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\gathi\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\gathi\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions

I don't understand what to do.
Here is the perms of the bot:
The bots perms

A: The answer is within the bot Forbidden: 403 Forbidden (error code: 50013): Missing Permissions should instantly tell you it's a permissions issue.
The bot fails on await member.edit(roles=[role]) # 848410518154117130 which tells you the code works but it can't assign the role.
Make sure the bot:

*

*Is higher than you in the role hierarchy

*Has Manage Roles or the Administrator permission

If this continues to not work then consider going to my previous answer about intents.

A: You can use discord.Member.add_roles to assign a role.
@bot.command()
async def mute(ctx, member: commands.MemberConverter):
    role = discord.utils.find(lambda r: r.name == 'Muted', ctx.guild.roles)
    await member.add_roles(role)

And this is the unmute command.
@bot.command()
async def unmute(ctx, member: commands.MemberConverter):
    role = discord.utils.find(lambda r: r.name == 'Muted', ctx.guild.roles)
    await member.remove_roles(role)


text:
Q: How to use the Intel AVX in Java? How do I use the Intel AVX vector instruction set from Java? It's a simple question but the answer seems to be hard to find.

A: Depending on the work, you may not have to do much. AVX2 is used automatically by JVM on some operations on Arrays and String, on  supporting platforms like Haswell onwards and Xeon v3 onwards.
https://software.intel.com/en-us/articles/java-application-performance-improvement-with-intel-xeon-processor-e7-v3
https://en.wikipedia.org/wiki/Advanced_Vector_Extensions#CPUs_with_AVX2
From Ryzen 3 / Epyc Rome, you'll also have single cycle AVX2 on AMD processors:
https://www.anandtech.com/print/14525/amd-zen-2-microarchitecture-analysis-ryzen-3000-and-epyc-rome
Direct use of the instructions and intrinsics are not easily available though.

A: Java 19 now supports SIMD with new Vector Intrinsics API , this API much faster then JNI implementations.
Its directly converting your java method calls to inline assembly instructions.
Checkout : https://vksegfault.github.io/posts/java-simd/

A: As I know, most current Java JVM JITters don't support automatic vectorization or just do that for very simple loops, so you're out of luck.
In Mono's .NET implementation there's Mono.Simd for manual vector code emission and then later MS introduced the System.Numeric.Vectors. Unfortunately there's nothing similar in Java. I don't know if Java's vector class is vectorized using SIMD or not but I don't think it is.
If you want to use CPU-specific features like AVX then your only choice is JNI. Write your bottle neck part in C or C++ and call it from Java
There's another solution by Scala to use vectorized code without modifying the JVM that you can read in How we made the JVM 40x faster

Update:
Now there's a new Vector API being developed for writing vector code manually

Provide an initial iteration of an incubator module, jdk.incubator.vector, to express vector computations that reliably compile at runtime to optimal vector hardware instructions on supported CPU architectures and thus achieve superior performance to equivalent scalar computations.
https://openjdk.java.net/jeps/338

*

*Vector API Developer Program for Java* Software

*Oracle and Intel seek to build a Java API for SIMD support

Read more:

*

*Do any JVM's JIT compilers generate code that uses vectorized floating point instructions?

*SIMD Vectors/Matrices in Java?

*What is the state of auto-vectorization in OpenJDK?

*Vectorized Algorithms in Java

A: To use these operations from Java you need a library like JavaCV  This library enables vector operations for both Intel Processors and GPUs like NVIDIA.

A: One option is to use Aparapi and install the Intel OpenCL driver. (Your code will be vectorized to work on both CPUs and GPUs, as long as an appropriate OpenCL driver is installed.)
Another option is to use JNI and call a C++ function that uses AVX intrinsics or was auto-vectorized by a compiler.

A: Check for yeppp library.
It has java binding and its very fast cross platform SIMD Library.
http://www.yeppp.info


text:
Q: Alternative for form Action to call a payment service Is there any working alternative or replacement using jquery or webservice for form action to call payment service like this :
<form name="ipg" action="https://pay.doku.com/DokuSuite/Channel" method="post" data-ajax="false">

A: You can use ajax to call your service (this service can be written in any server language):
In javascript you can create a function to cal your service through ajax with JQuery:
btnExecute_onclick = function() {

    $.ajax({
        url: "https://pay.doku.com/DokuSuite/Channel",
        type: "POST",
        data: {
            //parameters here
            anyParameterName: 'foo'
        },
        success: function( data ) {
            // do anything you want with data received from server
            // here I'm just showing the result in a div
            $( "#anyDiv" ).html( "Server return here: " + data + "" );
        }
    });

}

In the html you can have a button like this:
<input type="button" id="btnExecute" onclick="btnExecute_onclick()">

You can take input from the user by form tags like input type text and send as parameters in your ajax call.
You can receive in the success function, the return from the server.
Look at the ajax JQuery function api here


text:
Q: RF Receiver Q/Q_N and I/I_N What is the point of inverted Q and inverted I on a receiver? Specifically on FMCW radar applications?

A: You have to consider what is at the heart of most modern receiver chips and that is a mixer not dissimilar to the LT5512: -

Generalising a bit, the silicon inside will usually produce a balanced output (IF) and require at least the RF input or local oscillator to also be balanced (sometimes both).
The output stage is usually a differential pair of BJTs and only when you take the differential voltage from the collectors will you get the best quality signal.
Why is it a differential output stage you might ask?
Because it's a balanced modulator and the simplest and (usually) most cost effective solution uses a differential pair to perform analogue multiplication of local oscillator and RF input. The bases are antiphase fed the RF input and the local oscillator can be fed to the shared emitter as a single ended input. More complex arrangements use a gilbert cell and these use diff signals on all three ports. There are also arrangements like below that only require two ports to be differential: -

This has a fair chance of matching the LT5512 and, although it only shows one collector as an output, for reasons given above both collectors will be used as outputs.
If you try and use only one collector single-ended you will get mixer artifacts that you don't want and you will seriously degrade receiver performance.
So why doesn't a chip like the LT5512 have a differential to single ended output converter you might ask.
The answer is quite simply that if you are down converting to baseband with a baseband spectrum of several tens of MHz you would (or could) use an op-amp but, if you are not down converting to baseband and still have a seriously high IF frequency then an op-amp won't do the job and you are into balun territory then an amplifier.
So the chip (like the above) provides differential outputs.


text:
Q: Junit fail following tutorial MongoDB, Springboot I am following this tutorial:
https://www.baeldung.com/spring-boot-embedded-mongodb
Only dot 1,2,3
I need insert and check new registers in my mongoDB embebed.
this is my pom:
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-mongodb</artifactId>
        <version>2.1.1.RELEASE</version><!--$NO-MVN-MAN-VER$ -->
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-log4j2</artifactId>
    </dependency>
    <dependency>
        <groupId>de.flapdoodle.embed</groupId>
        <artifactId>de.flapdoodle.embed.mongo</artifactId>
        <scope>test</scope>
    </dependency>

</dependencies>

It is my test.java:
import static org.assertj.core.api.Assertions.assertThat;

import java.util.List;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;
import org.springframework.data.mongodb.core.MongoTemplate;

import com.batch.DesarrolloBatch.model.Documento;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DBObject;

@DataMongoTest
public class TestApplicationConfiguration {

            @Test
            public void test(@Autowired MongoTemplate mongoTemplate) {
                // given
                DBObject objectToSave = BasicDBObjectBuilder.start()
                    .add("_id", "999999999999")
                    .get();

                // when
                mongoTemplate.save(objectToSave, "collection");

                List<Documento> list =  mongoTemplate.findAll(Documento.class, "collection");

               System.out.println("size " + list.size());

                // then
                assertThat(mongoTemplate.findAll(Documento.class, "collection")).extracting("_id")
                    .containsOnly("999999999999");
            }
}

I am trying insert a new Documento with attribute _id value= 99999999
But this code failed, so, I am trying see the size my List for know if I insert success...
I get this error:
java.lang.Exception: Method test should have no parameters
    at org.junit.runners.model.FrameworkMethod.validatePublicVoidNoArg(FrameworkMethod.java:76)
    at org.junit.runners.ParentRunner.validatePublicVoidNoArgMethods(ParentRunner.java:155)
    at org.junit.runners.BlockJUnit4ClassRunner.validateTestMethods(BlockJUnit4ClassRunner.java:208)
    at org.junit.runners.BlockJUnit4ClassRunner.validateInstanceMethods(BlockJUnit4ClassRunner.java:188)
    at org.junit.runners.BlockJUnit4ClassRunner.collectInitializationErrors(BlockJUnit4ClassRunner.java:128)
    at org.junit.runners.ParentRunner.validate(ParentRunner.java:416)
    at org.junit.runners.ParentRunner.<init>(ParentRunner.java:84)
    at org.junit.runners.BlockJUnit4ClassRunner.<init>(BlockJUnit4ClassRunner.java:65)
    at org.junit.internal.builders.JUnit4Builder.runnerForClass(JUnit4Builder.java:10)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createUnfilteredTest(JUnit4TestLoader.java:87)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:73)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:46)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:522)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)

I am new in Junit, mongodb ... I only want use mongoDB embebed and insert and check my bbdd .... thanks...

A: You forgot an annotation on the class level: @ExtendWith(SpringExtension.class)
@DataMongoTest
@ExtendWith(SpringExtension.class)
public class TestApplicationConfiguration {

        @Test
        public void test(@Autowired MongoTemplate mongoTemplate) {
            // your test code
        }
}

Please read the tutorial carefully.
Here is the link to the GitHub Repo where you can find the pom.xml and all the source code as well:
https://github.com/eugenp/tutorials/tree/master/persistence-modules/spring-boot-persistence-mongodb


text:
Q: Python C API Boolean Objects I am using Python C API 2.7.2 with my C++ console application. There is one doubt regarding Python C API Boolean Objects
I am using:
PyObject* myVariable = Py_True;

Do I need to deference myVariable with Py_DECREF(myVariable)?
The Python C API documentation says:-

The Python True object. This object has no methods. It needs to be
  treated just like any other object with respect to reference counts.

I searched the questions but could not find a clear answer for it.
Thanks.

A: Although it isn't dynamically created, it must be reference counted because PyObject variables can hold ANY Python object. Otherwise there would need to be checks for Py_True and other special cases scattered throughout the Python runtime as well as any C/C++ code that uses the API. That would be messy and error prone.

A:
It needs to be treated just like any other object with respect to reference counts.

This means that you must incref it when you take its reference
{
  Py_INCREF(Py_True);
  PyObject* myVariable = Py_True;

and you must decref it when you dispose of it.
  Py_DECREF(myVariable);
}


text:
Q: Zurb Foundation 5 and Jquery 3 incompatible? I am trying to use Zurb Foundation 5 with JQuery 3.0.0.1 and seem to be having some compatibility issues. When I initialize Foundation $(document).foundation(); a javascript error is thrown

Object doesn't support property or method 'indexOf' on line 9612

If I roll back to 2.2.4 everything works fine.
Has anyone else run into this?
Browser: MS Edge(IE 11)

A: Yes, Zurb Foundation 5 and jQuery 3 are incompatible. Foundation still uses the load function, which was deprecated 4 years ago in jQuery 1.8 and finally removed in jQuery 3.0. Since there is another jQuery Function called load, which is called instead, you get this rather cryptic error message.
Even the current relased Version of Zurb Foundation 6.2.3 and jQuery 3 are incompatible. The fix for your problem is already merged and should be released with version 6.2.4 which was to be released about 2 months ago, but still isn't. (Its 78% complete according to the GitHub page)
So I guess the only solution is to a) ignore the error or b) patch the code yourself as described in this answer.
Update: Foundation 6.2.4 was released October 21, 2016 and now supports jQuery 3.

A: You can work around that with a snippet like this:
// XXX Hack for foundation for jQuery upgrade from 2.x to 3.x
jQuery.fn.load = function (callback) {
    this.on('load', callback);
    return this;
};

Typescript:
import jQuery from 'jquery';

// XXX Hack for foundation for jQuery upgrade from 2.x to 3.x
var jQueryAny = (jQuery as any).fn;
jQueryAny.load = function(cb:any) {
    this.on('load', cb);
    return this;
}


text:
Q: How to extract data from the points closer to required location in R? I have two data.frame. FakeData has the Long & Lat along with data while ExCor has Long & Lat of the points that I would like to have the data extracted from FakeData. ExCor should only extract data from the closest points.
Here is some sample data to start with
rm(list = ls())

DF1 = data.frame(t(data.frame(Grids = 1:5, Long = runif(5, min = 5, max = 10), Lat = runif(5, min = 2, max = 3))))
DF2 = data.frame(X1 = runif(1095, 0.5,1), X2 = runif(1095, 1.5,2), X3 = runif(1095, 0.5,1.5), X4 = runif(1095, 0.5,6), X5 = runif(1095, 0.5,15))
FakeData = rbind(DF1, DF2)

ExCor = data.frame(t(data.frame(Long = runif(3, 7, 9), Lat = runif(3, 2,3))))

Any thoughts are welcome.

A: One of many ways to achieve this is to use the st_nearest_feature predicate within sf::st_join. First, though, you need to rejig your data structure so that it is more compatible with the packages that work with spatial geometries.
library(sf)

# Reshape datasets so that coords and attributes are columns, not rows
ExCor <- setNames(do.call(rbind.data.frame, ExCor), row.names(ExCor))
FakeData <- setNames(do.call(rbind.data.frame, FakeData), row.names(FakeData))

# Convert to sf objects
FakeData_sf <- st_as_sf(FakeData, coords=c('Long', 'Lat'))
ExCor_sf <- st_as_sf(ExCor, coords=c('Long', 'Lat'))

# Spatial join nearest feature
newdat <- st_join(ExCor_sf, FakeData_sf, join=st_nearest_feature)

You can then write out to a .csv again if you want...
st_write(newdat, 'newdat.csv', layer_options='GEOMETRY=AS_XY')


text:
Q: Make [if-then] a synonym of [if-statement] The if-then tag seems a bit pointless, but is being used. Could we please either:

*

*Burninate it; or

*Make it a synonym for if-statement?
(This came to my attention through https://stackoverflow.com/review/suggested-edits/2285785 where user Dariusz was giving the tag if-then the tag excerpt "do not use this tag; use if-statement which is more general". This seems sensible to me.)


text:
Q: Indexing a custom Stack Class I am currently doing some C# Unit-Testing using an Udemy Course. In this course, the current Stack class is implemented:
namespace Testing
{
    public class Stack<T>
    {
        public readonly List<T> _list = new List<T>();

        public int Count => _list.Count;

        public void Push(T obj)
        {
            if (obj == null)
                throw new ArgumentNullException();

            _list.Add(obj);
        }

        public T Pop()
        {
            if (_list.Count == 0)
                throw new InvalidOperationException();

            var result = _list[_list.Count - 1];
            _list.RemoveAt(_list.Count - 1);

            return result;
        }

        public T Peek()
        {
            if (_list.Count == 0)
                throw new InvalidOperationException();

            return _list[_list.Count - 1];
        }
    }
}

Now, I do not understand why the Peek function can use:
return _list[_list.Count - 1];

As far as I know, a list object cannot be indexed, if such functionality is not explicitly implemented (which does not seem to be the case here). Furthermore, if I create an instance of that object:
Stack<int> newStack = new Stack<int>();
newStack.Push(5);
var lastElement = newStack[0];

I get a squiggly error message:
cannot apply indexing with to an expression of 'Testing.Stack<int>'

...which supports my assumption that this instance cannot be indexed. Can someone please explain me this behavior?

A:
As far as I know, A List object cannot be indexed

This is incorrect. A c# list is a type of dynamic array, similar to the c++ std::vector. You are probably thinking of linked list, a completely different type, and one I would rarely recommend using.

cannot apply indexing with to an expression of 'Testing.Stack'

This is because you have not implemented an indexer. Assuming you want zero to be the most recently added item:
public T this[int i] => _list[Count  - i - 1];

While writing your own stack can be useful as an exercise, for real work I would recommend using the built in stack. There is also source code available.


text:
Q: mvvm binding is updating intermittently I have a counter on a a page just below a datagrid and I am trying to use it to notify the user of how many rows are in the datagrid and how many rows are expected ("1 of 900"). The textbox that is in question is being updated but on when the count is being changed for each row. It is updating after 400+ rows have been inserted into the datagrid.
The model property:
    public string CountText
    {
        get
        {
            return countText;
        }
        set
        {
            countText = value;
            OnPropertyChanged("CountText");
        }
    }

The wpf textbox:
    // wpf textbox
    <TextBox
         Margin="10,0,0,0"
         x:Name="CountText"
         Style="{StaticResource EtchedTextBoxWhiteOnBlack}"
         Background="Transparent"
         Height="50" Width="200"
         FontSize="22" FontWeight="ExtraBold"
         Text="{Binding EventLogModel.CountText}"
         TextAlignment="Center"
         HorizontalAlignment="Center" VerticalAlignment="Center"
         HorizontalContentAlignment="Center" VerticalContentAlignment="Center" />

The code updating the CountText property in the model:
    // model property to which the textbox is bound
    public string CountText
    {
        get
        {
            return countText;
        }
        set
        {
            countText = value;
            OnPropertyChanged("CountText");
        }
    }

    // code snippet that is updating the datagrid and the string property to which the textbox is bound
    bool bContinue = true;
    int startIndex = 0;
    int chunkSize = 50;
    bool breset = EventLogSignalingEvent.Reset();
    ThreadPool.QueueUserWorkItem(GetNumberOfLogEntries, lp);
    bool bwait = EventLogSignalingEvent.WaitOne();

    count = 0;

    if (maxItems > 0)
                {
                    UpdateStatusDialog("Loading log data", string.Format("{0} items total found", maxItems));
                    CountText = string.Format("{0} of {1}", count.ToString(), maxItems);
                }
                else
                {
                    statusOpen = false;
                    UpdateStatusDialog("No log data found", "");
                    StatusDlgHideEllipse();
                    CountText = string.Format("{0} items found", maxItems);
                }

                while (bContinue && !bStopped)
                {
                    EventLogSignalingEvent.Reset();
                    lp = new LogParams();
                    lp.chunkSize = chunkSize;
                    lp.eDate = eDate;
                    lp.sDate = sDate;
                    lp.startIndex = startIndex;
                    lp.UTCOffset = UTCOffset;
                    ThreadPool.QueueUserWorkItem(GetEventLogChunk, lp);
                    EventLogSignalingEvent.WaitOne();

                    if (chunk != null && chunk.Count > 0)
                    {
                        foreach (LogRecordDbMVVM db in chunk)
                        {
                            MainWindow.MainWinDispatcher.Invoke(DispatcherPriority.Send, new ThreadStart(() =>
                            {
                                try
                                {
                                    EventLog.Add(LogRecordGUI.LogRecord_DBtoGUI(db));
                                    Thread.Sleep(10);
                                }
                                catch
                                {
                                }
                            }));

                            if (statusOpen == true)
                            {
                                CloseStatusDialog();
                                statusOpen = false;
                            }

                            if (count < maxItems)
                            {
                                count++;
                                ThreadPool.QueueUserWorkItem(UpdateCount, count);
                                //CountText = string.Format("{0} of {1}", count.ToString(), maxItems);
                            }
                        }
                    }
                    else if (chunk == null)
                    {
                        log.Info("############################################### ERROR: chunk == null");
                        log.InfoFormat("Start date = {0} End date = {1} Start index = {2} chunkSize = {3} maxItems = {4}", sDate, eDate, startIndex, chunkSize, maxItems);
                    }

                    startIndex += chunkSize;
                    bContinue = (startIndex >= maxItems) ? false : true;

                }

                EventLogViewCount = (EventLog.Count - NumberOfEventLogItemsInView) >= 0 ? EventLog.Count - NumberOfEventLogItemsInView : 0;
            }
            catch (Exception ex)
            {
                log.ErrorFormat("{0} {1}", ex.Message, ex.StackTrace);
            }
        }
        catch (Exception ex)
        {
            log.ErrorFormat("{0} {1}", ex.Message, ex.StackTrace);
        }
    }

    private void UpdateCount(object context)
    {
        int count = (int)context;

        CountText = string.Format("{0} of {1}", count.ToString(), maxItems);
    }

    private void GetNumberOfLogEntries(object context)
    {
        LogParams lp = (LogParams)context;
        maxItems = BT220.ManagementService.GetEventLogCountChunk(lp.sDate, lp.eDate, lp.UTCOffset, lp.startIndex, lp.chunkSize);
        EventLogSignalingEvent.Set();
    }


text:
Q: React-router route props not passed I am using componentDidMount to fetch data from firebase and set the components state with fetched data
  componentDidMount() {
  this.state.firebase.database().ref().on("value", function(snapshot) {
  let data = snapshot.val()

  // Authors
  this.setState({authors: data.Author})

then in render method I have this
{
    console.log(this.state.authors)
}
<Route path="/author/:authorId" component={AuthorPage} authors={this.state.authors} />

Inside AuthorPage component I have this
render() {
    console.log(this.props.route)
    return (....

The console output is
Object {authorId: Object} // This is for this.state.authors
Object {path: "/author/:authorId", authors: undefined, component: function} // this is for this.props.route

As you can see, this.state.authors has a value, but becomes undefined when passed to component as route props. This has never happened to me before, even in the same app with other routes.

A: For some reason this solves the problem
  let authorsArray = data.Author
  let aths = this.state.authors
  for(var j in authorsArray) {
    aths[j] = authorsArray[j]
  }
  this.setState({authors: aths})

Anybody know why?


text:
Q: Create DOMNode to pass to google maps API using React or jQuery The Google Maps Info Window API accepts either a string or a DOMNode as an argument. I can use document.createElement() to generate a DOMNode, but that quickly explodes into many lines of code as the information I want to include there increases.
This is my createInfoWindow method for example:
  _createInfoWindow(id, location) {
    ...
    let button = document.createElement('button')
    button.appendChild(document.createTextNode('Add to Itenerary'))
    google.maps.event.addDomListener(button, 'click', myFunction())
    let content = document.createElement('div')
    ...
    content.appendChild(button)
    return new google.maps.InfoWindow({ content })
  }

It would be nice to be able to generate a DOMNode that I can pass as an argument to the google maps api that is less verbose. I'm writing this app in React, so React is ideal, but whatever works - if there's a way to generate a DOMNode in jQuery, I'd like to know that as well. The above example is missing several lines of code that create a bunch of DOMElements and append them to content.

A: It'd probably be best to write your own React component that contains your content, captures a ref to its DOM element, instantiate the google.maps.InfoWindow in componentDidMount(), and pass it the reference to the DOM element. Something like this:
import React, {Component} from 'react'

class InfoWindow extends Component {
    componentDidMount() {
        this.infoWindowApi = new google.maps.InfoWindow({ content: this.infoDiv })
    }

    componentWillUnmount() {
        this.infoWindowApi && this.infoWindowApi.close();
    }

    render () {
        const { id, location, onButtonClick } = this.props;

        return (

 (this.infoDiv = ref)}>

Info

${location}

                <button onClick={onButtonClick}>Add to Itenerary</button>

        );
    }
}

export default InfoWindow;

...elsewhere in some container component:
<InfoWindow
  id={someId}
  location={theLocation}
  onButtonClick={() => this.onInfoWindowClicked(location)}
/>

...or if you must resort to jQuery, simply create a quick content DIV and pass to InfoWindow:
var contentDiv = $('

Info
<button>Add to Itinerary</button>
').click(myFunction);

// [0] to extract first (and only) DOM element inside the jQuery selector
var infoWin = new google.maps.InfoWindow({ content: contentDiv[0] });


text:
Q: Merge strings in javascript I want to merge two variable with stings alternately using javascript. What would be an algorithm to accomplish this task?
For example:
var a = "abc"
var b = "def"

result = "adbecf"

A: The best way to do this is to perform the following algorithm:

*

*Iterate through string 1

*For each character, if there is a character in the same position in string 2, replace the original character with both

This can be achieved with the following code:
function merge(s, t) {
  return s.split("")
          .map(function(v,i) {
              return t[i] ? v + t[i] : v
          })
          .join("")
}

or the more Codegolf type answer:
s=>t=>[...s].map((v,i)=>t[i]?v+t[i]:v).join``

A: I would use Array.from to generate an array from the strings (unicode conscious).
After that, just add a letter from each string until there's no letters left in each. Please note this solution will combine strings of uneven length (aa+bbbb=ababbb)

var a = "abc"
var b = "def"
var d = "foo  bar mañana mañana"

function combineStrings(a,b){
  var c = "";
  a = Array.from(a);
  b = Array.from(b);
  while(a.length > 0 || b.length > 0){
    if(a.length > 0)
      c += a.splice(0,1);
    if(b.length > 0)
      c += b.splice(0,1);
  }
  return c;
}

var test = combineStrings(a,b);
console.log(test);

var test2 = combineStrings(a,d);
console.log(test2);

A: The simple way would be define the longest string and assigned to for loop. Also you have to add if statments for strings of uneven length, because you want to ignore undefined values of shorter string.

function mergeStrings(s1, s2){

  var n = s1.length;

  if(s1.length < s2.length){
    n = s2.length;
  }

  var string = '';
  for(var i = 0; i < n; i++){
    if(s1[i]){
      string += s1[i];
    }
    if(s2[i]){
      string += s2[i];
    }
  }

  return string;
}

console.log(mergeStrings('ab','lmnap'));
console.log(mergeStrings('abc','def'));

A: If your strings are the same length, this will work. If not you'll have to append the rest of the longer string after the loop. You can declare i outside of the loop and then use substr() to get the end of the longer string.

const a = "abc"
const b = "def"

var res = "";
for (var i = 0;i < Math.min(a.length, b.length); i++) {
  res += a.charAt(i) + b.charAt(i)
}

console.log(res)

A: Regex or array processing and joining do the job:

let a = 'abc';
let b = 'def';
console.log(a.replace(/./g, (c, i) => c + b[i]));        // 'adbecf'
console.log(Array.from(a, (c, i) => c + b[i]).join('')); // 'adbecf'

A:
You can solve this using array spread and reduce. Split each string into an array and merge into one array and then use reduce to generate the merged string.

function mergeStrings(a, b) {
    const mergedValues = [
     ...a.split(''),
     ...b.split('')
     ].reduce((values, currentValue) => {
         if (!values.includes(currentValue)) {
             values.push(currentValue);
         }
         return values;
       }, []);

    return Array.from(mergedValues).join('');
}


text:
Q: Generate and then save an image I just wrote this code to generate an image
<?php

$canvas = imagecreatetruecolor(800, 350);

$pink = imagecolorallocate($canvas, 255, 105, 180);
$white = imagecolorallocate($canvas, 255, 255, 255);
$green = imagecolorallocate($canvas, 132, 135, 28);

imagefill($canvas, 0, 0, $white); // BACKGROUND

function drawlinebox($x1, $y1, $x2, $y2, $height, $color){
    global $canvas;
    imagesetthickness ( $canvas, 1 );
    for ($i=1; $i < $height; $i++){
        imageline( $canvas, $x1, $y1, $x2, $y2, $color );
        $y1++; $y2++;
    }
}

drawlinebox(20, 20, 780, 300, 30, $green);

drawlinebox(20, 300, 780, 20, 30, $pink);

// Output and free from memory
header('Content-Type: image/png');

imagepng($canvas, NULL, 9);

imagedestroy($canvas);

?>

but I also want this image to saved automatically on the server.
Think of it as a cron job. Which creates images, then saves the image on the sever for later use and inserts the saved image location in the DB.

A: As stated in the manual, imagepng()'s second parameter is $filename which allows you to store the result in a file.


text:
Q: Android/iOS trigger action after connecting to USB I'm going to create a mobile phone charger, that is accessible in public (like in bars or restaurants). Now I'm looking for a method to show to my "clients" an information about the device (about the sponsor).
Is it possible to trigger opening a webpage, after connecting the mobile phone to a USB port? Or ask the user to install an app? The port can be in a PC (not a charge-only port). I've read about "universal accessories", which can do a lot, but it looks quite complicated to create a charging "accessory" only to display a web-page.
Has anyone an better idea? Any other actions (other than opening a web page / asking to install an app) are possible?

A: Open it on a PC? Probably. On Android not without installing an app to do that or using Tasker.
Read up on Intents and specifically how to listen for Intent.ACTION_BATTERY_CHANGED if you want to have people install an app in order to use the charger.


text:
Q: How to add a column of data to existing data frames with a loop I need to add a column of data to several data frames which represents a chromosome from which the data were derived. I've read many posts about adding a column to a data frame and they are all either too specific of answers or switch to using apply functions, which are quite opaque in how they operate. Can someone help me out here and show me the proper for loop and apply techniques, so I can start to unpack the apply + function(x) style?
I tried using paste0 to create a vector of objects to insert into the loop, but that fails. Here is the basic syntax of how I think the looping should works (but fails):
library(dplyr)

df.1 <- data.frame(V1=rnorm(100), V2=rnorm(100))
df.2 <- data.frame(V1=rnorm(100), V2=rnorm(100))
df.3 <- data.frame(V1=rnorm(100), V2=rnorm(100))

for(i in 1:3){
  df.i <- df.i %>% mutate(CHR = i)
}

This is the error I get with this code: Error in eval(lhs, parent, parent) : object 'df.i' not found.
The output should look like this:
head(df.1)
          V1         v2 CHR
1 -1.3545128  0.8267013   1
2  0.3758215 -0.4475770   1
3  0.5209901 -1.1342161   1
4  0.7207743 -1.4273951   1
5 -0.3867220  0.2681198   1
6  1.3279556  0.6116999   1

Thanks for the help.

A: You can add column names:
column_names= ["Id", "Name", "Age", "Weight", 'mreading1', 'mreading2', 'mreading3', 'freading1', 'freading2', 'freading3']
df = pd.read_csv("defo.csv", names = column_names)

A: You could try putting the data in a list and loop over as follows.
df.1 <- data.frame(V1=rnorm(100), V2=rnorm(100))
df.2 <- data.frame(V1=rnorm(100), V2=rnorm(100))
df.3 <- data.frame(V1=rnorm(100), V2=rnorm(100))
df_list <- list(df.1,df.2, df.3)
for(i in 1:length(df_list)){
  df_list[[i]] <- df_list[[i]] %>% mutate(CHR = i)
}