text:
Q: Character moves uncontrollably when grabs an object Something really weird is happening to my game. When the character grabs an object, he starts to move uncontrollably and the inputs are inverted. For example, if I press the button that makes the character to go to right, he goes to left and vice versia. I don't know what's going on. The object has a box collider. The player has a sphere collider attached to him which is triggered.
The bigger this object, the faster the character moves. I really don't know. I use this code to pick the object.
private void OnTriggerStay(Collider other)
{
    if (other.tag == "PlayerCollider")
    {
        Player.PodeLargar = false;
    }

    if (Input.GetButtonDown("Jump") && other.tag == "PlayerCollider" && !Player.Segurando && !ItemEmCima)
    {
        StartCoroutine(PegarItem());
    }

    if (Input.GetButtonDown("Jump") && other.tag == "PlayerCollider" && Player.Segurando && !ItemEmCima)
    {
        StartCoroutine(Player.PosicionarItem(this.transform));
        ItemEmCima = true;
    }

    if (Input.GetButtonDown("Jump") && other.tag == "PlayerCollider" && Player.Segurando && !ItemEmCima /*|| other.gameObject.tag != "Espaço1.1" || other.gameObject.tag != "Incisivo"*/)
    {
        Player.PodeLargar = false;
    }

    if (Input.GetButtonDown("Jump") && other.tag == "PlayerCollider" && !Player.Segurando && ItemEmCima)
    {
        EmCima = this.transform.GetChild(1).gameObject;
        LugarErrado = false;
        StartCoroutine(PegarDaBancada(EmCima));
    }
}

private void OnTriggerExit(Collider other)
{
    if (other.tag == "PlayerCollider")
    {
        Player.PodeLargar = true;
    }
}

//----Coroutines---------------------------------------------------------
IEnumerator PegarItem()
{
    //Instantiate(DenteRespectivo, ColliderTrans.position, ColliderTrans.rotation, ColliderTrans.transform);
    yield return new WaitForSeconds(0.1f);
    Player.Segurando = true;
}

IEnumerator PegarDaBancada(GameObject Objeto)
{
    Objeto.transform.parent = ColliderTrans.transform;
    Objeto.transform.position = ColliderTrans.position;
    Objeto.transform.rotation = ColliderTrans.rotation;

    yield return new WaitForSeconds(0.1f);
    Player.Segurando = true;
    ItemEmCima = false;
}


text:
Q: Code contracts - Not correctly warning about readonly members? Given this class, I"m not sure why I get the Ensure unproven Result != null warning.
public class MyClass {
  private readonly string _value;

  public MyClass(string value) {
    Contract.Requires(value != null);
    _value = value;
  }

  public string Value {
    get {
      Contract.Ensures(Contract.Result<string>() != null);
      return _value;
    }
  }
}

I can make the warning go away by adding an Invariant that _value != null, but it feels like I shouldn't have to.  Is this just a limitation of the analysis?
EDIT:  Adding a bit more to the question, as I think the point of my question is being missed.
public class Test {
    private string _value = "";

    public string Value {
        get {
            Contract.Ensures(Contract.Result<string>() != null);
            return _value;
        }
        set {
            Contract.Requires<ArgumentNullException>(value != null);
            _value = value;
        }
    }
}

The CC analysis seems perfectly happy with this class; a non-null value is assigned in the ctor, and the setter Requires non-null values to change _value thus Ensures is proven.

A: Your constructor does not promise that  _value will be non-null. It sets _value to value, which is non-null, but that's an implementation detail, not part of the contract. Even if it were part of the contract, it wouldn't be enough, because all pre- and postconditions should remain equally valid when you add another constructor that doesn't make that same promise.
You should add the invariant that _value != null. Why does it feel like you shouldn't have to?
Edit: as an alternative, you could try adding an invariant that Value != null (which would also be useful outside of MyClass), and make Value's property getter ensure that Contract.Result<string>() == _value (merely to prove the invariant), but I'm not sure that would work.

A: Not sure the option was available when the question was asked, but I ran into a similar issue today and found that by turning on the Code Contracts option "Infer Invariants for readonly" the warning went away.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to wake up the app with Eddystone in Android I want to wake up my app with Eddystone, however nothing happened when my phone get close to the signal of Eddystone. I did it with Android Beacon library. And it is as blew:
    `
onCreate(){
    mBeaconManager = BeaconManager.getInstanceForApplication(this);
    // Detect the main Eddystone-UID frame:
    mBeaconManager.getBeaconParsers().add(new BeaconParser().
            setBeaconLayout(BeaconParser.EDDYSTONE_UID_LAYOUT));
    mBeaconManager.setBackgroundBetweenScanPeriod(50);
    mBeaconManager.setBackgroundScanPeriod(50);
    mBeaconManager.setForegroundBetweenScanPeriod(50);
    mBeaconManager.setForegroundScanPeriod(50);
    mBeaconManager.setBackgroundBetweenScanPeriod(50);
    mBeaconManager.setForegroundScanPeriod(50);
    mBeaconManager.applySettings();
    mBeaconManager.bind(this);

}`
Android.xml:
<application
    android:name="com.example.MyApplicationName"
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <!-- Note:  the singleInstance below is important to keep two copies of your activity from getting launched on automatic startup -->
    <activity
        android:launchMode="singleInstance"
        android:name="com.example.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
    <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

Is there anyone did it before, please help me with it. Thanks

A: Yes, it is possible to wake up an app with Eddystone-UID using the Android Beacon Library.  It works the same way as with AltBeacon or iBeacon.
The easiest way to get this to happen is to start with the reference app here:
https://github.com/altbeacon/android-beacon-library-reference
The only modification you need to make is to add the beacon parser for Eddystone-UID:
mBeaconManager.getBeaconParsers().add(new BeaconParser().
        setBeaconLayout(BeaconParser.EDDYSTONE_UID_LAYOUT));

Looking at the code in the question, setting the scan periods to 50 is going to be a problem, as 50ms is not long enough to reliably detect a beacon.  I would remove these custom scan period configurations and use the defaults.
A few tips:

*

*Make sure you can detect beacons in the foreground before trying to make your app work in the background.

*Make sure your app is using RegionBootstrap as in the reference app as described in the "Starting an App in the Background" section here

*When testing background detection, make sure you are out of region before starting the test.  To do this, bring your app to the foreground, and have your beacon(s) turned off for 30 seconds.  This will ensure you are out of region.  Always to this before starting a background detection test.

*If you kill your app from the task switcher, wait 5 minutes to ensure it is restarted in the background before starting your testing.

*Be realistic about how long it might take to detect a beacon in the background.  Read here for more info.


text:
Q: How to query and update some record set in django models atomically? I have some records in a django Model, and each time I want to query and update some of them.
How can perform this operation atomically?
def queryAndUpdate(count):
    entries = Model.objects.filter(...)[:count]
    for entry in entries:
        entry.count = F('count') + 1
        entry.save()
    return entries

I tried QuerySet.select_for_update(), but it fails.

A: Just:
Model.objects.filter(...).update(count=F('count') + 1)

Here is the doc.
If you want to limit the size of QuerySet as 100, use Model.objects.filter(...)[:100]. It will be translated to SELECT ... LIMIT 100, so you don't need to worry about the performance, here is another question about this.
And it's return value is <class 'django.db.models.query.QuerySet'>, same as Model.objects.filter(...), so you can use Model.objects.filter(...)[:100].update(...) too.


text:
Q: Exception HResult 0x800a03ec when trying to open Excel with Microsoft.Office.Interop.Excel.Workbooks.Open() Following Exception is thrown if I try to open an excel file on a client machine:
Exception from HRESULT: 0x800A03EC

Inner Exceptions: (empty)
Stack Trace:
   at Microsoft.Office.Interop.Excel.Workbooks.Open(String Filename, Object UpdateLinks, Object ReadOnly, Object Format, Object Password, Object WriteResPassword, Object IgnoreReadOnlyRecommended, Object Origin, Object Delimiter, Object Editable, Object Notify, Object Converter, Object AddToMru, Object Local, Object CorruptLoad)
   at (own assembly)

This HResult is a very generic Error, I could not find any useful informations by it.
My Setup:
WCF Service running inside a Windows Service. The exact same Setup is working on three other machines.
Things I can rule out:

*

*Wrong Path

*File does not exists

*File is corrupt

*File is write protected

Things I've done:

*

*Created the Desktop folders as seen here (second Answer) https://social.msdn.microsoft.com/Forums/vstudio/en-US/4d6c383a-94eb-4898-9d22-aa4bb69be25b/

*Gave the Desktop Folders "Everyone" or "Jeder" Permissions ("Jeder" is the equivalent of "Everyone" in German)

*Started the Service with the currenlty active User

*Changed the DCOM Config for Excel as advised by Heidi2 (see Link above)

*Changed from Office 365 to Office Professional Plus

*Locale is set to en-US while trying to open the file

*Opened file manually which is supposed to be opened: no errors / warnings / user dialogs from excel

*Installed English - US on target machine

*Wrote an non WCF Service which starts the dll which executes the Interop request

*Wrote an Console Application which starts the dll which executes the Interop request

Some Observations:

*

*If I remove the Desktop folders (see my first "Things I've done"), I get the error as described and resolved here: Microsoft Office Excel cannot access the file 'c:\inetpub\wwwroot\Timesheet\App_Data\Template.xlsx'

*Excel is open for a short time in the task manager while the dll tries to open the excel file

*while I've had Office 365 installed, Office Click-Once Tasks opped up in Task Manager, sometimes freezing the Application. That's why I've switched to Professional Plus

*If the active language is set to English US, this error is not thrown anymore; but images, which are supposed to be rendered by Interop, are rendered blank

What am I missing here?

A: Sorry - I know this is an indirect answer, although I would recommend you follow on. I personally have very bad experiences with Excel Interop services (ASP.NET application). As I am aware Microsoft does not recommend Interop server automation.
Even if you solve this issue you might stumble into issues with memory leakage, performance etc. In my previous project we were advanced with Excel interop automation until deployment. We stumbled into so many issues (Excel Interop processes not closing properly etc.) that we had to rewrite everything to OpenXML.
If possible use the new OpenXML format. There is a ClosedXML library that makes working with very easy.
Why OpenXML vs Interop?:

*

*Efficiency (OpenXML is lightweight)

*No memory leakage risk

*Ease of use

A: Before trying this solution be sure that you read the "Things I've done" paragraph from the question (and tried what applies to you)
The Exception was thrown upon opening the Document; on the machine which generated the Excels, the files were generated invalid.
The solution was to change the Format of the numbers.
Go into System Configuration -> Time, Language and Region -> Language

Tap on the highlighted Hyperlink
Open Advanced Settings

Change the delimiter to a point "."

A: We have converted our Client / Server solution from 4GL language to C#, where embedded C# code below worked without any issue  before, and started to receive same error message.
Excel.Application excelApp = new Excel.Application();
Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(fileExcel,
    0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
    true, false, 0, true, false, false);

I have followed all the instructions in this thread, but to no avail, until I have realised that in our case at least fileExcel, which contains the full path with the name of the file and defined as  System.String fileExcel  had trailing spaces, e.g. instead of "C:\temp\MyTest.xls" it was "C:\temp\MyTest.xls[many many spaces]".
Once I have added Trim() to fileExcel as below, all went back to normal. Hope it will help to someone in the future.
Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(fileExcel.Trim(),
    0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
    true, false, 0, true, false, false);


text:
Q: Scala: Parsing Array of String to a case class I have created a case class like this:
def case_class(): Unit = {
   case class StockPrice(quarter : Byte,
                      stock : String,
                      date : String,
                      open : Double,
                      high : Double,
                      low : Double,
                      close : Double,
                      volume : Double,
                      percent_change_price : Double,
                      percent_change_volume_over_last_wk : Double,
                      previous_weeks_volume : Double,
                      next_weeks_open : Double,
                      next_weeks_close : Double,
                      percent_change_next_weeks_price : Double,
                      days_to_next_dividend : Double,
                      percent_return_next_dividend : Double
                     )

And I have thousands of line as Array of String like this:
1,AA,1/7/2011,$15.82,$16.72,$15.78,$16.42,239655616,3.79267,,,$16.71,$15.97,-4.42849,26,0.182704

1,AA,1/14/2011,$16.71,$16.71,$15.64,$15.97,242963398,-4.42849,1.380223028,239655616,$16.19,$15.79,-2.47066,19,0.187852

1,AA,1/21/2011,$16.19,$16.38,$15.60,$15.79,138428495,-2.47066,-43.02495926,242963398,$15.87,$16.13,1.63831,12,0.189994

1,AA,1/28/2011,$15.87,$16.63,$15.82,$16.13,151379173,1.63831,9.355500109,138428495,$16.18,$17.14,5.93325,5,0.185989

How Can I parse data from Array into that case class?
Thank you for your help!

A: You can proceed as below (I've taken simplified example)
Given your case class and data (lines)
// Your case-class
case class MyCaseClass(
  fieldByte: Byte,
  fieldString: String,
  fieldDouble: Double
)

// input data
val lines: List[String] = List(
  "1,AA,$1.1",
  "2,BB,$2.2",
  "3,CC,$3.3"
)

Note: you can read lines from a text file as
val lines = Source.fromFile("my_file.txt").getLines.toList

You can have some utility methods for mapping (cleaning & parsing)
// remove '$' symbols from string
def removeDollars(line: String): String = line.replaceAll("\\$", "")

// split string into tokens and
// convert into MyCaseClass object
def parseLine(line: String): MyCaseClass = {
  val tokens: Seq[String] = line.split(",")
  MyCaseClass(
    fieldByte = tokens(0).toByte,
    fieldString = tokens(1),
    fieldDouble = tokens(2).toDouble
  )
}

And then use them to convert strings into case-class objects
// conversion
val myCaseClassObjects: Seq[MyCaseClass] = lines.map(removeDollars).map(parseLine)

As a more advanced (and generalized) approach, you can generate the mapping (parsing) function for converting tokens into fields of your case-class using something like reflection, as told here

A: Here's one way of doing it. I'd recommend splitting everything you do up into lots of small, easy-to-manage functions, otherwise you will get lost trying to figure out where something is going wrong if it all starts throwing exceptions. Data setup:
val array = Array("1,AA,1/7/2011,$15.82,$16.72,$15.78,$16.42,239655616,3.79267,,,$16.71,$15.97,-4.42849,26,0.182704",
  "1,AA,1/14/2011,$16.71,$16.71,$15.64,$15.97,242963398,-4.42849,1.380223028,239655616,$16.19,$15.79,-2.47066,19,0.187852",
  "1,AA,1/21/2011,$16.19,$16.38,$15.60,$15.79,138428495,-2.47066,-43.02495926,242963398,$15.87,$16.13,1.63831,12,0.189994",
  "1,AA,1/28/2011,$15.87,$16.63,$15.82,$16.13,151379173,1.63831,9.355500109,138428495,$16.18,$17.14,5.93325,5,0.185989")

case class StockPrice(quarter: Byte, stock: String, date: String, open: Double,
  high: Double, low: Double, close: Double, volume: Double, percent_change_price: Double,
  percent_change_volume_over_last_wk: Double, previous_weeks_volume: Double,
  next_weeks_open: Double, next_weeks_close: Double, percent_change_next_weeks_price: Double,
  days_to_next_dividend: Double, percent_return_next_dividend: Double
)

Function to turn Array[String] into Array[List[String]] and handle any empty fields (I've made an assumption here that you want empty fields to be 0. Change this as necessary):
def splitArray(arr: Array[String]): Array[List[String]] = {
  arr.map(
    _.replaceAll("\\$", "")         // Remove $
      .split(",")                   // Split by ,
      .map {
        case x if x.isEmpty => "0"  // If empty
        case y => y                 // If not empty
      }
      .toList
  )
}

Function to turn a List[String] into a StockPrice. Note that this will fall over if the List isn't exactly 16 items long. I'll leave you to handle any of that. Also, the names are pretty non-descriptive so you can change that too. It will also fall over if your data doesn't map to the relevant .toDouble or toByte or whatever - you can handle this yourself too:
def toStockPrice: List[String] => StockPrice = {
  case a :: b :: c :: d :: e :: f :: g :: h :: i :: j :: k :: l :: m :: n :: o :: p :: Nil =>
    StockPrice(a.toByte, b, c, d.toDouble, e.toDouble, f.toDouble, g.toDouble, h.toDouble, i.toDouble, j.toDouble,
      k.toDouble, l.toDouble, m.toDouble, n.toDouble, o.toDouble, p.toDouble)
}

A nice function to bring this all together:
def makeCaseClass(arr: Array[String]): Seq[StockPrice] = {
  val splitArr: Array[List[String]] = splitArray(arr)
  splitArr.map(toStockPrice)
}

Output:
println(makeCaseClass(array))

//ArraySeq(
// StockPrice(1,AA,1/7/2011,15.82,16.72,15.78,16.42,2.39655616E8,3.79267,0.0,0.0,16.71,15.97,-4.42849,26.0,0.182704),
// StockPrice(1,AA,1/14/2011,16.71,16.71,15.64,15.97,2.42963398E8,-4.42849,1.380223028,2.39655616E8,16.19,15.79,-2.47066,19.0,0.187852),
// StockPrice(1,AA,1/21/2011,16.19,16.38,15.6,15.79,1.38428495E8,-2.47066,-43.02495926,2.42963398E8,15.87,16.13,1.63831,12.0,0.189994),
// StockPrice(1,AA,1/28/2011,15.87,16.63,15.82,16.13,1.51379173E8,1.63831,9.355500109,1.38428495E8,16.18,17.14,5.93325,5.0,0.185989)
//)

Edit:
To explain the a :: b :: c ..... bit - this is a way of assigning names to items in a List or Seq, given you know the List's size.
val ls = List(1, 2, 3)
val a :: b :: c :: Nil = List(1, 2, 3)
println(a == ls.head) // true
println(b == ls(1)) // true
println(c == ls(2)) // true

Note that the Nil is important because it signifies the last element of the List being Nil. Without it, c would be equal to List(3) as the rest of any List is assigned to the last value in your definition.
You can use this in pattern matching as I have in order to do something with the results:
val ls = List(1, "b", true)
ls match {
  case a :: b :: c if c == true => println("this will not be printed")
  case a :: b :: c :: Nil if c == true => println(s"this will get printed because c == $c")
} // not exhaustive but you get the point

You can also use it if you know what you want each element in the List to be, like this:
val personCharacteristics = List("James", 26, "blue", 6, 85.4, "brown")
val name :: age :: eyeColour :: otherCharacteristics = personCharacteristics
println(s"Name: $name; Age: $age; Eye colour: $eyeColour")
// Name: James; Age: 26; Eye colour: blue

Obviously these examples are pretty trivial and not exactly what you'd see as a professional Scala developer (at least I don't), but it's a handy thing to be aware of as I do still use this :: syntax at work sometimes.


text:
Q: Is there some directory walker in Haskell? Is there some recursive directory walker in Haskell so I could write something like
listing <- walkDir "/tmp"

I would not like to write my own. I can install some dependency from cabal but I want it to be cross platform (at least Linux and Windows).

A: I have a recursive definition for traversing a directory using filepath package:
import Control.Monad
import System.Directory
import System.FilePath
import System.Posix.Files

-- | Traverse from 'top' directory and return all the files by
-- filtering out the 'exclude' predicate.
traverseDir :: FilePath -> (FilePath -> Bool) -> IO [FilePath]
traverseDir top exclude = do
  ds <- getDirectoryContents top
  paths <- forM (filter (not.exclude) ds) $ \d -> do
    let path = top </> d
    s <- getFileStatus path
    if isDirectory s
      then traverseDir path exclude
      else return [path]
  return (concat paths)

A: http://hackage.haskell.org/package/FilePather has that sort of recursive directory walking functionality.

A: The filemanip package provides powerful and elegant functions for that. For example it provides a fold function that will recursively call your function down a directory tree. As an example i used it here to recursively list files in a directory starting from the oldest

A: Here is one way to list all Haskell files in a directory tree, using directory-tree that is not in a hidden directory (whose name starts with '.'):
import Data.Traversable (traverse)
import System.Directory.Tree (
    AnchoredDirTree(..), DirTree(..),
    filterDir, readDirectoryWith
    )
import System.FilePath (takeExtension)

listFilesDirFiltered = do
    _:/tree <- readDirectoryWith return "C:\\devmy\\code"
    traverse print $ filterDir myPred tree
    return ()
  where myPred (Dir ('.':_) _) = False
        myPred (File n _) = takeExtension n == ".hs"
        myPred _ = True

main = listFilesDirFiltered

Works on both Windows and Linux.


text:
Q: example using uploadDirectory from android to S3 Will someone please provide an example for uploading a bunch of photos to S3 using uploadDirectory? Say I have 300 photos in a directory named "special_photos" on my android device. And I want to upload all of these photos to Amazon S3. I figure uploadDirectory may be the best method for doing this. But being new to Amazon cloud, I don't know how I might do it. All I have gleaned so far is that the method executes asynchronously and so can be called from the main thread. I keep finding php codes on the internet. But I don't use PHP. Does anyone have a complete working example they don't mind sharing with the community? I am using the SDK via gradle on Android Studio. Also, is there some kind of callback for knowing when all the photos have been uploaded? Say for instance I want to delete the photos and the directory once they have been uploaded.

A: There is no uploadDirectory but there is Multipart Upload. This will do your large data upload to S3. As stated HERE, the Multipart Upload Docs say:

Using the list multipart uploads operation, you can obtain a list of multipart uploads in progress. An in-progress multipart upload is an upload that you have initiated, but have not yet completed or aborted. Each request returns at most 1000 multipart uploads. If there are more than 1000 multipart uploads in progress, you need to send additional requests to retrieve the remaining multipart uploads.

To address the callback, there is a completion called once all of the TransferUtility items are uploaded. This open source adds listeners applied to the upload function. I would recommend breaking up your calls to 30 at a time, then delete the corresponding photos - in case there is a failure with the upload. There is a success and fail return, so obviously only delete in case of success.
HERE is the AWS documentation for Android Multipart Uploads
HERE is an article that will help migrate & understand the differences between TransferManager and TransferUtility
HERE is a good article on getting started with the Android TransferManager
And HERE is an open source demo - under the S3_TransferManager
Hope this helps!
Update:
The below code is all taken from @awslabs references
Create client:
public static AmazonS3Client getS3Client(Context context) {
    if (sS3Client == null) {
        sS3Client = new AmazonS3Client(getCredProvider(context.getApplicationContext()));
    }
    return sS3Client;
}

Create TransferUtility:
public static TransferUtility getTransferUtility(Context context) {
    if (sTransferUtility == null) {
        sTransferUtility = new TransferUtility(getS3Client(context.getApplicationContext()),
                context.getApplicationContext());
    }
    return sTransferUtility;
}

Use TransferUtility to get all upload transfers:
observers = transferUtility.getTransfersWithType(TransferType.UPLOAD);

Add your records: - you could iterate over the file names in your directory
HashMap<String, Object> map = new HashMap<String, Object>();
Util.fillMap(map, observer, false);
transferRecordMaps.add(map);

This starts everything:
private void beginUpload(String filePath) {
    if (filePath == null) {
        Toast.makeText(this, "Could not find the filepath of the selected file",
                Toast.LENGTH_LONG).show();
        return;
    }
    File file = new File(filePath);
    TransferObserver observer = transferUtility.upload(Constants.BUCKET_NAME, file.getName(),
            file);
    observers.add(observer);
    HashMap<String, Object> map = new HashMap<String, Object>();
    Util.fillMap(map, observer, false);
    transferRecordMaps.add(map);
    observer.setTransferListener(new UploadListener());
    simpleAdapter.notifyDataSetChanged();
}

This is your completion:
private class GetFileListTask extends AsyncTask<Void, Void, Void> {
    // The list of objects we find in the S3 bucket
    private List<S3ObjectSummary> s3ObjList;
    // A dialog to let the user know we are retrieving the files
    private ProgressDialog dialog;

    @Override
    protected void onPreExecute() {
        dialog = ProgressDialog.show(DownloadSelectionActivity.this,
                getString(R.string.refreshing),
                getString(R.string.please_wait));
    }

    @Override
    protected Void doInBackground(Void... inputs) {
        // Queries files in the bucket from S3.
        s3ObjList = s3.listObjects(Constants.BUCKET_NAME).getObjectSummaries();
        transferRecordMaps.clear();
        for (S3ObjectSummary summary : s3ObjList) {
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("key", summary.getKey());
            transferRecordMaps.add(map);
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        dialog.dismiss();
        simpleAdapter.notifyDataSetChanged();
    }
}

A: You can send a List to your service that is using TransferUtility to upload multiple images. At least that is how I was able to make it work.


text:
Q: propriedade Prompt nao esta funcionando

          <%= f.label :modelo_id %>
          <%= f.select :modelo_id,
            options_for_select(
              @modelos.collect { |modelo|
              [modelo.nome.titleize, modelo.id] }, @carro.submodelo.modelo.id), {}, { id: 'modelos_select', class: 'form-control'  }, prompt: 'Selecionar disciplina' %>

Alguem saberia me dizer porque o prompt nao esta funcionando?

A: Você precisa colocar o prompt dentro do hash do html_options, tente da seguinte forma:

          <%= f.label :modelo_id %>
          <%= f.select :modelo_id,
            options_for_select(
              @modelos.collect { |modelo|
              [modelo.nome.titleize, modelo.id] }, @carro.submodelo.modelo.id), {},
              { id: 'modelos_select', class: 'form-control'  , prompt: 'Selecionar disciplina' } %>


text:
Q: Output the results of a Log Analytics Workspace query to Event Hub I'm performing a query to output logs captured in an Azure Log Analytics Workspace, for example:
Invoke-AzOperationalInsightsQuery -WorkspaceId '' -Query "AzureDiagnostics | where Category == 'AzureFirewallApplicationRule'"
However I need to send the results of this to an Event Hub for further processing.
I'm trying to use the REST API (https://learn.microsoft.com/en-us/rest/api/eventhub/send-batch-events) but struggling to dynamically generate a request body to send to the Event Hub based on the output fields of the query. This may not be the best way to do it, any suggestions?

A: I suggest you can use Send event api by sending a simple json data one by one. Because if you use send batch api, you should build a more complex source data.
You can use the following powershell code to send data to event hub using send event api.
$queryResults = Invoke-AzOperationalInsightsQuery -WorkspaceId "xxx" -Query "your query"

#generate sas token
$URI_1 = "event_hub_namespace.servicebus.windows.net/eventhub_path"
$Access_Policy_Name="RootManageSharedAccessKey"
$Access_Policy_Key="the key"

#Token expires now+3000
$Expires=([DateTimeOffset]::Now.ToUnixTimeSeconds())+3000
$SignatureString=[System.Web.HttpUtility]::UrlEncode($URI_1)+ "`n" + [string]$Expires
$HMAC = New-Object System.Security.Cryptography.HMACSHA256
$HMAC.key = [Text.Encoding]::ASCII.GetBytes($Access_Policy_Key)
$Signature = $HMAC.ComputeHash([Text.Encoding]::ASCII.GetBytes($SignatureString))
$Signature = [Convert]::ToBase64String($Signature)
$SASToken = "SharedAccessSignature sr=" + [System.Web.HttpUtility]::UrlEncode($URI_1) + "&sig=" + [System.Web.HttpUtility]::UrlEncode($Signature) + "&se=" + $Expires + "&skn=" + $Access_Policy_Name
$SASToken

$method = "POST"
$url = "https://event_hub_namespace.servicebus.windows.net/eventhub_path/messages"
$signature = $SASToken

# API headers
$headers = @{
            "Authorization"=$signature;
            "Content-Type"="application/atom+xml;type=entry;charset=utf-8";
            }

#use foreach to send data
foreach($s in $queryResults.Results){
    #Write-Output "hello"
    $json = $s | ConvertTo-Json
    #Write-Output $json

    Invoke-WebRequest -Method $method -Headers $headers -Body $json -uri $url
}

Write-Output "**completed**"

After execute the powershell, I use code to receive the data from event hub, and I can confirm that all the data are sent to event hub. The screenshot as below:


text:
Q: Not Null Terminated character array #include <stdio.h>

char s[3] = "Robert";
int main()
{
    printf("%s",s);
}

Output: Rob

How does this get printed properly? The string is not null terminated.
I saw the assembly. It used .ascii for storing "Rob" which is not null terminated.
I expected some garbage along with Rob to be printed.
Can someone explain me this behaviour?

A: Your "Rob" has been stored in an extra section of the executable. The sections in an executable are aligned, i.e. the section with the data is padded with 0 until the next section. So printf got "its" 0 from the section padding. To illustrate:
#include <stdio.h>

char dummy[] = "ocop";
char s[3] = "Robert";
char second[] = "in Hood";
int main( void )
{
    printf("%s",s);
    return 0;
}

Output (MinGW-GCC w/o optimization): Robin Hood
Output (MinGW-GCC with optimization): Robocop
Now there is no 0 from the padding but the begin of the next string which will be outputted as well.


text:
Q: Need help changing my website's name / address this might sound a bit amateur-ish but I'm in a bit of a situation here.
So I created myself a website and managed to get it working on localhost, I tried port forwarding ports 80,443 but nothing helped, So next thing I'm googling around and I read about ngrok and it actually worked. Got it working on a long randomly generated domain but the problem is that I want to use the one that I have from no-ip.com. How can I do that please? I'm very lost here.
Software being used: Xampp (Apache,MySQL)
I've reserved a DHCP ip-address for my PC in my router's settings, hopefully that helps? I don't know. Help me internet.

A: There are a whole bunch of possible reasons that this might not work. Here are a few of them.
Your ISP
Even if you have port forwarding set up properly on your router, it is still possible that you cannot do what you want.
First, many ISPs block serving websites from residential internet connections. Connections to port 80/443 will never even reach your router. You might try experimenting by forwarding a different port number (such as 8000 instead of 80) to see if the traffic can get through on that port. (However, that will not work as a practical solution since your users will not know to use an alternate port and your ISP can choose to terminate your service if you are violating the terms of your agreement.)
Second, due to the exhaustion of public IPv4 addresses, some ISPs are implementing Carrier-Grade NAT (CGNAT, a.k.a. Large-Scale NAT - LSN). Instead of giving your router a public IP address, they give your router a private IP address inside their network. Once again, connections to port 80/443 (or any other port for that matter) will never reach you. You can check if you are behind CGNAT by going to your router's setting and finding the public IP address, then going to https://whatsmyip.com/ and seeing if it is the same or different. (In theory, you should be able to tell that you have CGNAT if your router's IP address is between 100.64.0.0 - 100.127.255.255, but in practice some ISPs use other private network ranges too, such as 10.0.0.0 - 10.255.255.255.)
The reason Ngrok works for you is because Ngrok opens a tunnel from your computer to their cloud servers and sends the traffic through that tunnel.
DNS
You mentioned in the comments that you have the DNS set to resolve the private IP of your computer. That certainly will not allow users on the public internet to get to your site, because they cannot connect to your address.
However, you also mentioned in the comments that if you change the DNS to point to your public IP, it doesn't work from either inside or outside. This could mean your problem is one of the ISP issues described above. It could also mean that your router does not support Hairpin-NAT (a.k.a. NAT Reflection), which is how the router would be able to redirect local traffic back to the local server instead of trying to send it out over the internet.
Firewall
Your computer's firewall can look at the source IP address of the incoming traffic, and it might be set not to allow external access to your web server. DO NOT DISABLE YOUR FIREWALL to try to get around this. Instead, you need to add a specific exception to the firewall rules to allow the incoming traffic. How you do this will depend on your operating system.


text:
Q: How to force user to clear cache after production in Angular 6 I have an external css file (work.css) and I put this file in angular.json to be compiled
"styles": [
              "src/styles.css",
              "src/assets/css/work.css"
            ],

Now and for example, if I have margin-left: 50px and I changed it to margin-left: 10px and release a new production to users. The browser cached the 50px, and the 10px doesn't appear until I clear the cache. How can I force the user to clear cache after a new production?
EDIT
And the same problem appears in each component css.

A: Http caching is generally not an easy problem. Actually it is very easy as long as you know how it works :) Adding --prod to you ng build will generate the index.html file that will include all the static resources js, css with the unique indetyfier. So
style.css

will become
style.sdfsrregsfd32453455.css

Unfortunately this is just part of the story as index.html can and will be cached by the browser. And you can't change that. Hhere is another caching mechanism that can help us, it is called ETag (Entity Tag).
Basically the http server, that is serving your website, will add to to the index.tml GET request a header that will identify that resource. Browser will send that id with each request to fetch index.html. Server will analyze it and if the index.html has not change will send response with no body. With the 302 Not Modified code.

I have a longer blog post on the subject:
https://medium.com/12-developer-labors/http-caching-with-hazelcast-and-other-trics-how-to-make-my-angular-app-load-faster-aeaa90562e94


text:
Q: GWT Date Handing... have client respect server's timezone I've read many a post here re: GWT date handling.
One in particular that struck a cord with me was this one
Sending a date and timezone from GAE server to GWT client
Anyhow, there's a need on a project I'm working on to be able to display days, hours, minute intervals as labels in a grid.  My team has adopted an approach where all date/time instances are passed the client from the server in ISO8601 String format.  The server time zone is to be respected by the client.  The biz use case is that all date/time instances are in "market time", so that any browser that visits the app will see and work with dates in the "market time" timezone which happens to be GMT-05:00 (if Daylight Savings in effect) or GMT-06:00 (if Standard Time in effect).
I have posted some source on Github, here:
https://github.com/fastnsilver/gwt-datehandling-example
Particularly...
https://github.com/fastnsilver/gwt-datehandling-example/blob/master/src/main/java/me/fns/gwt/datehandling/client/util/CSTimeUtil.java
and the GWTTestCase
https://github.com/fastnsilver/gwt-datehandling-example/blob/master/src/test/java/me/fns/gwt/datehandling/client/util/CSTimeUtilTestGwt.java
in the hopes that someone can stare at the utility (and test) we're employing for date handling and help us see what we're not seeing.
EDIT
The basic problem is that CSTimeUtil#hoursInDay(Date) is not being calculated correctly in Production mode for "transition days"  This method is used by other methods (like CSTimeUtil#dateToHour(Date) and CSTimeUtil#labelsForDay(Date)).
I have deployed our application with the current implementation of CSTimeUtil and it appears to work, but not quite.  I'm really confused by alternate test results when e.g., mvn gwt:test is run in GWT Mode or Production Mode on Windows where the OS timezone is set to various timezones other than U.S. GMT-05:00 or GMT-06:00.

A: Based on some hints from Andrei and some serious blood, sweat and tears, I figured this out on my own.  I have updated the code in Github, so if you're curious please go have a look there.
The basics:

*

*Make sure all Strings are ISO8601 (no millis) compliant when sent from server to client and vice versa

*Use  DateTimeFormat.getFormat("yyyy-MM-ddTHH:mm:ss.SZZZZ") to format and parse dates

*Retreive GMT-prefixed time zone info from java.util.Date in "Market time" using DateTimeFormat(Date, TimeZone), where TimeZone param is set as TimeZone.createTimeZone(TZ_CONSTANTS_INSTANCE.americaChicago()) and time zone String retrieved by TimeZone.getISOTimeZoneString(Date)

*Generating days, see generateDay(Date, int) or hours generateHour(Date, int), from a source date had to take into consideration that an increment or decrement coudl trigger a change in time zone offset if occurring on a "transition day".

A: If you time zone is fixed, why would you use a string to represent date/time? You can send a standard Java Date object to the client. If you want, you can even store all dates and times as Longs and pass Longs only. You also send the GWT's TimeZone Json string for your time zone (once per session). You can find it in the GWT - there is a file with strings for all time zones.
On a client you use DateTimeFormat with many predefined formats to display whatever you need: full date, month and date, date and time, etc. Just remember to create TimeZone object from this Json string and use  it  in DateTimeFormat.getFormat(...).format(Date, TimeZone).
With this approach you don't have to worry about DST changes (they are encoded in that Json string) and locales. You only pass simple Date or Long objects.


text:
Q: Can a Firebase Security Rule check if someone has specific access rights? Can I use the keyword "in" to check if a user's authentication matches a Firebase security rule?
For example, I create a user token with:
var token = tokenGenerator.createToken({ "uid": "1234", "access": [file1, file2, file3] });

I want to check if the user can access a particular file by setting the following security rule:
{
   "rules": {
       ".read": true,
       ".write": "file3 in auth.access"
    }
}

I am not sure if this works or is there a similar pattern for Firebase security. I want to issue each user unique security tokens that allows them to access certain files.

A: What you're describing is a form of role-based security, which you can definitely build on Firebase.
This requires that you store the roles in your Firebase (and not just dynamically add them to the token):
users
    twitter:214
        files
            file1: true
            file2: true
    twitter:469
        files
            file2: true

Your rule would then be:
".write": "root.child('users/'+auth.uid+'/files/file1').exists()"


text:
Q: Why is the parent scroll event getting triggered , when scrolling inside child, From what I know scroll event doesn't get bubbled to the parent and only bubbles document itself then why parent scroll event is getting fired,
import { useEffect, useRef } from "react";
import "./styles.css";

export default function App() {
  const refParent = useRef(null);
  const refChild = useRef(null);
  useEffect(() => {
    function handleParent() {
      console.log("Parent");
    }
    function handleChild() {
      console.log("Child");
    }
    if (refParent && refChild) {
      refParent.current.addEventListener("mousewheel", handleParent);
      refChild.current.addEventListener("mousewheel", handleChild);
    }
    return () => {
      refParent.current.removeEventListener("mousewheel", handleParent);
      refChild.current.removeEventListener("mousewheel", handleChild);
    };
  });
  return (
    <div
      style={{ width: "400px", height: "200px", background: "red" }}
      ref={refParent}
    >
      <div
        style={{ width: "100px", height: "100px", overflow: "auto" }}
        ref={refChild}
      >
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Quas, dolorum
        nisi, debitis optio magnam perferendis similique delectus incidunt alias
        eum dignissimos est quis assumenda doloribus rem deserunt tempora eos
        reiciendis!Lorem ipsum dolor sit amet consectetur adipisicing elit.
        Quas, dolorum nisi, debitis optio magnam perferendis similique delectus
        incidunt alias eum dignissimos est quis assumenda doloribus rem deserunt
        tempora eos reiciendis! Lorem ipsum dolor sit amet consectetur
        adipisicing elit. Quas, dolorum nisi, debitis optio magnam perferendis
        similique delectus incidunt alias eum dignissimos est quis assumenda
        doloribus rem deserunt tempora eos reiciendis!Lorem ipsum dolor sit amet
        consectetur adipisicing elit. Quas, dolorum nisi, debitis optio magnam
        perferendis similique delectus incidunt alias eum dignissimos est quis
        assumenda doloribus rem deserunt tempora eos reiciendis!
      </div>
    </div>
  );
}

here is the live example https://codesandbox.io/s/runtime-silence-lxi1jb?file=/src/App.js
Thanks

A: It's because you are using the mousewheel event and not the scroll event. The mousewheel event will bubble and is just saying did the user issue a command to their machine to attempt a scroll. It's like onClick but for the mouse wheel.
You meant to use the scroll event which means "did this frame move scroll position".


text:
Q: Cannot find a token authenticator for the 'System.IdentityModel.Tokens.UserNameSecurityToken' token type. I am trying to get a third party Java client to communicate with a WCF service I have written.
I get the following exception when receiving the message:

Cannot find a token authenticator for the
  'System.IdentityModel.Tokens.UserNameSecurityToken' token type. Tokens
  of that type cannot be accepted according to current security
  settings.

Here is my configuration:
Binding
<customBinding>
    <binding name="TestSecureBinding">
        <security authenticationMode="MutualCertificate" />
        <textMessageEncoding messageVersion="Soap11WSAddressing10" />
        <httpsTransport requireClientCertificate="true" maxReceivedMessageSize="5242880" />
    </binding>
</customBinding>

Behaviour:
  <serviceBehaviors>
    <behavior name="TestCertificateBehavior">
      <serviceCredentials>
        <clientCertificate>
          <certificate storeLocation="LocalMachine" x509FindType="FindBySubjectName" findValue="Test 01"/>
          <authentication certificateValidationMode="PeerTrust" trustedStoreLocation="LocalMachine" revocationMode="NoCheck"/>
        </clientCertificate>
        <serviceCertificate storeLocation="LocalMachine" x509FindType="FindBySubjectName" findValue="Test 01"/>
      </serviceCredentials>
    </behavior>
  </serviceBehaviors>

Endpoint:
  <service name="TestService"
           behaviorConfiguration="TestCertificateBehavior">
    <endpoint
      name="TestEndpoint"
      address="https://localhost:443"
      contract="TestServiceContract"
      binding="customBinding"
      bindingConfiguration="TestSecureBinding">
    </endpoint>
    <host>
      <baseAddresses>
        <add baseAddress="https://localhost:443" />
      </baseAddresses>
    </host>

  </service>

Does anyone know what is causing this?

A: Its because the wrong way of referencing the cert has been used somewhere, if i remember correctly, you either directly reference the cert or use a key identifier - anyhow, to get beyond it, you should be able to add the allowSerializedSigningTokenOnReply tag to your security tag on your clients binding configuration and set it to true.
that should get beyond it for you - remember, put this client side
Sorry I cant find the references - I remember reading it somewhere and cant find it now! :( ****EDIT Here It is**** - http://webservices20.blogspot.co.uk/2010/10/wcf-cannot-find-token-authenticator.html
<customBinding>
<binding name="TestSecureBinding">
        <security allowSerializedSigningTokenOnReply="true" />
        etc
    </binding>
<customBinding>

A: I have accepted that I can't do this in the config file and have resorted to creating the service host in code.
Here is the full example of creating the binding, binding elements and creating the service host.
Please note, you may not be using WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005W - you are probably using a more recent version than I am having to use - but just substitute that for the correct version for your service.
var securityBindingElement = (AsymmetricSecurityBindingElement)SecurityBindingElement.CreateMutualCertificateBindingElement(MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10);
securityBindingElement.EndpointSupportingTokenParameters.Signed.Add(new UserNameSecurityTokenParameters());
securityBindingElement.MessageSecurityVersion = MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;
securityBindingElement.IncludeTimestamp = true;
securityBindingElement.MessageProtectionOrder = System.ServiceModel.Security.MessageProtectionOrder.EncryptBeforeSign;

var customBinding = new CustomBinding();
customBinding.Elements.Add(securityBindingElement);
customBinding.Elements.Add(new TextMessageEncodingBindingElement(MessageVersion.Soap11WSAddressing10, Encoding.UTF8));
customBinding.Elements.Add(new HttpsTransportBindingElement() { MaxReceivedMessageSize = 5242880 });

ServiceHost customServiceHost = new ServiceHost(type);
customServiceHost.AddServiceEndpoint(typeof(ITestServiceContract), customBinding, "https://localhost:443");
customServiceHost.Open();

A: Make sure to check the endpoint address your client is calling.  We wrestled with this for far too long until we realized that there was a typo in the custom binding address addendum.


text:
Q: T-test and tree don't match logically I would like some help in a machine learning homework.
First I want to make clear that I don't think this is considered cheating as I am just asking for help in understanding a result, rather than asking for the code/answer. After all the professor told us himself that he encourages to seek outside help when needed.
Regarding my question, I am using the DoctorVisits dataset from the AER package. Before making a tree I did some descriptive statistics on the data, including t-tests. After that I chose the column lchronic to make a tree.
Thing is that the tree uses the variables illness and age, while the t-tests :
t.test(illness~lchronic, data = DoctorVisits)
t.test(age~lchronic, data = DoctorVisits)

both resulted in the acceptance of the null hypotheses. Therefore, seeing as the means aren't different for these variables regardless of lchronic, shouldn't that mean that the tree can't have them as branches?
Also, another minor thing, the branch freerepat seems to be doing nothing as it results to two 'No' nodes regardless of the value of freerepat.


text:
Q: This loop to modify a arraylist of numbers based on arraylist of strings isnt working So, in my program you input employee information and the salary you input depends on what you input for designation. If temporary, yo input how much they make per hour, if permanent you input what they make per year. At the end, you have the option to sort by salary, so if they choose that then I must multiply the temporary's per-hour by a set number (1920) in order to convert it to what they make per year. I tried this but I got the messages
" The type of the expression must be an array type but it resolved to java.util.ArrayList"
and "The type of the expression must be an array type but it resolved to java.util.ArrayList", I got that second one twice.
public static void main(String[] args)
  {
    Scanner in = new Scanner(System.in);
    String Continue = "y";
int Count = 0;
int SortingChoice;
ArrayList<String> Names       = new ArrayList<String>();
ArrayList<String> Department  = new ArrayList<String>();
ArrayList<String> Designation = new ArrayList<String>();
ArrayList<Float>  Salary      = new ArrayList<Float>();

//******************************************************//

do
{
   System.out.println("Enter Employee Name: ");
   String x = in.next();
   Names.add(x);

   System.out.println("Enter Employee Designation ('temporary or permanent'): ");
   String y = in.next();
   Designation.add(y);

   System.out.println("Enter Employee Department: ");
   String z = in.next();
   Department.add(z);

   System.out.println("Enter Employee Salary: ");
   float i = in.nextFloat();
   Salary.add(i);

   System.out.println("Do you wish to add another employee? ('y'/'n'): ");
   Continue = in.next();

   Count = Count + 1;
}
while(Continue.equals("y"));

//***********************************************************************//

System.out.println("Enter sorting Criterion Number: 1. Name, 2.Department, 3. Salary. ");
SortingChoice = in.nextInt();

if(SortingChoice == 1)
{
  Collections.sort(Names);
     for(int i=0; i<Names.size(); i++)
     {
        System.out.println(Names.get(i));
     }
}

if(SortingChoice == 2)
{
  Collections.sort(Department);
     for(int i=0; i<Department.size(); i++)
     {
        System.out.println(Department.get(i));
     }
}

if(SortingChoice == 3)
{
  for(int k=0; k<Salary.size(); k++)
  {
    if(Designation[k].equals("temporary"))
      {
         Salary[k] = Salary[k]*1920;
      }
  }

  Collections.sort(Salary);
     for(int i=0; i<Salary.size(); i++)
     {
        System.out.println(Salary.get(i));
     }
}
  }

What I am most concered about if the loop under if(SortingChoice==3)


text:
Q: increase log output for SSLPeerUnverifiedException issues I am running into an javax.net.ssl.SSLPeerUnverifiedException in my current project. Even though log level is set to ALL the logs do not show what I would like to know.

Certificate for <#####.com> doesn't match any of the subject
alternative names: [.#####.com]
(org.apache.http.conn.ssl.DefaultHostnameVerifier)

I read that there is a way to enable additional logging for SSL and I lost the source for that.
Is there an environment attribute, or the like, that I could set to get more log entries for SSL?

A: MarquisofLorne gave the anser in a comment:

See the JSSE Reference Guide, 'debugging utilities'

This source has the option I was looking for -Djavax.net.debug=all.
Less agressive versions are also available there.


text:
Q: Preventing Form closure from freezing Invoke calls In my application I've created a thread which draws on a Bitmap object, and when it is done drawing it calls form.Invoke(form.Refresh) which draws the bitmap to the main form. (form being a reference to the main form of my application.)
The Problem: I've noticed that if I close the form while the other thread is waiting for the callback message from UI thread (because of the Invoke call) - the thread will wait indefinitely(?) and will essentially get stuck, preventing the application from closing.
Using BeginInvoke doesn't make sense in my program, because the time it takes to refresh the form has to be accounted for in the work of the thread.
Q: What would be the best way to prevent this from happening?
Edit: I've read in some places that its a bad idea, but it seems to me that the only way to deal with this is to call Thread.Abort(). I can't close the thread by using a flag or something similar, since its just stuck at the Invoke call.
Edit 2: To make it clear, what I'm looking for is a way to tell the worker thread that it should stop waiting for the Invoke callback and continue working.

A: The best answer is of course to use BeginInvoke. If you need the thread to wait until the UI thread has processed the result, then you'll have to add another synchronization method to the process.
An AutoResetEvent would work as a gate, something like this:
using System;
using System.Diagnostics;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

public class MainForm : Form
{
    protected override void OnLoad(EventArgs e)
    {
        new Thread(ProcessBitmap) { IsBackground = true }.Start(null);
        base.OnLoad(e);
    }

    void DoneProcessingBitmap(Bitmap bitmap)
    {
        Trace.WriteLine("Done Processing Bitmap");
        uiDoneEvent.Set();
    }

    AutoResetEvent uiDoneEvent = new AutoResetEvent(false);
    volatile bool terminate = false;

    void ProcessBitmap(object state)
    {
        while (!terminate)
        {
            Bitmap bitmap = (Bitmap)state;
            Trace.WriteLine("Processing Bitmap");
            Thread.Sleep(5000); // simulate processing
            BeginInvoke(new Action<Bitmap>(DoneProcessingBitmap), bitmap);
            Trace.WriteLine("Waiting");
            uiDoneEvent.WaitOne();
        }
    }

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new MainForm());
    }
}

A: Check if the form still exists before calling Invoke.  Something like...
if (form != null && !form.Disposed)
    form.Invoke(form.Refresh());


text:
Q: /var/run/lircd is not created when run as systemd service I'm configuring lirc in Raspbian. Here my systemd service:
[Unit]
Description=Flexible IR remote input/output application support
Wants=lircd-setup.service
After=network.target lircd-setup.service

[Service]
Type=simple
ExecStart=/usr/sbin/lircd -n -H irtoy -d /dev/serial/by-id/usb-Irdroid_USB_Infrared_Transceiver_00000002-if00

[Install]
WantedBy=multi-user.target

and here the lirc_options.conf:
[lircd]
nodaemon        = False
driver          = irtoy
device          = /dev/serial/by-id/usb-Irdroid_USB_Infrared_Transceiver_00000002-if00
output          = /var/run/lircd
pidfile         = /var/run/lircd.pid
plugindir       = /usr/lib/arm-linux-gnueabihf/lirc/plugins
permission      = 666
allow-simulate  = No
repeat-max      = 600

[lircmd]
uinput          = False
nodaemon        = False

It runs but it doesn't create the socket file /var/run/lircd.
Launching the very same command from shell:
/usr/sbin/lircd -n -H irtoy -d /dev/serial/by-id/usb-Irdroid_USB_Infrared_Transceiver_00000002-if00

leads to the correct behavior - i.e. the file is created and I can connect to the socket.
What would prevent this behavior when launched from systemd?


text:
Q: Django adding a custom field to registration I'm trying to add additional field for user's profile which can be edited only by administrator.
When I try to save a new value of city in an administration module I'm getting an error:
global name 'created' is not defined

This error comes from:
signals.py in create_profile, line 7

I described what I have done till now :)
I started a new app profil
In models.py
from django.db import models
from django.contrib.auth.models import User
from django.utils.encoding import smart_str

class UserProfile(models.Model):
    """Model przechowujący dodatkowe informacje o użytkowniku"""
    user = models.ForeignKey(User, unique=True)
    city = models.CharField(max_length=255, verbose_name=u'Miasto', blank=True, null=True)

    class Meta:
        verbose_name = 'Profil użytkownika'
        verbose_name_plural = 'Profile użytkowników'

    def __unicode__(self):
        return u'%s' self.user.username

    def __str__(self):
        return smart_str('%s' % self.user.username)

import profil.signals

In file: signals.py
from django.contrib.auth.models import User
from django.db.models.signals import post_save

from profil.models import UserProfile

def create_profile(sender, instance, **kwargs):
    if created == True:
        UserProfile.objects.get_or_create(user=instance)

post_save.connect(create_profile, sender=User)

forms.py
from django import forms
from profil.models import UserProfile

class UserProfileForm(forms.ModelForm):
    '''Formularz modelu UserProfile'''
    class Meta:
        model = UserProfile

admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User

from profil.forms import UserProfileForm
from profil.models import UserProfile

class UserProfileInline(admin.StackedInline):
    model = UserProfile
    fk_name = 'user'
    max_num = 1
    form = UserProfileForm

class UserProfileAdmin(UserAdmin):
    inlines = [UserProfileInline, ]

admin.site.unregister(User)
admin.site.register(User, UserProfileAdmin)

A: You can use:
def create_profile(sender, instance, **kwargs):
    if kwargs.get('created', False) ...

or
def create_profile(sender, instance, created, **kwargs):
    if created == True:

A: In your signals.py you are using created but is not defined yet.
So, you can get it from kwargs using this kwargs.get('created')
Fianlly, you create_profile function should looks like this.
def create_profile(sender, instance, **kwargs):
    if kwargs.get('created',None):
        UserProfile.objects.get_or_create(user=instance)


text:
Q: How to use Data Loader when parent contain IDs array? I am trying to implementing data-loader in my project-
Here is my code-
subCategory: async (parent, _, {loaders}) => {
    console.log(parent);
    // I try it but getting errors
    const subcategory = await loaders.subCategory.load(parent.subCategory.toString());
    return subcategory;
}

The above code's console result-
{
  _id: new ObjectId("61a658932c7ad474fde70893"),
  name: "Men's",
  createdAt: 2021-11-30T17:00:03.225Z,
  updatedAt: 2021-12-05T13:52:26.848Z,
  __v: 2,
  subCategory: [ // Array of IDS
    new ObjectId("61acc3f8a49c6cf3b04cf225"),
    new ObjectId("61acc41aa49c6cf3b04cf22b")
  ]
}
{
  _id: new ObjectId("61a65980890ef431bc0ecbcf"),
  name: 'Women',
  createdAt: 2021-11-30T17:04:00.530Z,
  updatedAt: 2021-12-05T13:54:00.449Z,
  __v: 3,
  subCategory: [ // Array of IDS
    new ObjectId("61acc460dba0e6083be97fb5"),
    new ObjectId("61acc471dba0e6083be97fbd"),
    new ObjectId("61acc478dba0e6083be97fc3")
  ]
}

I try it with this function--
module.exports.batchSubCategory = async (categoryIds) => {
    const subcategory = await Subcategory.find({_id: {$in: Ids}});
    return Ids.map(categoryId => subcategory.find(category => category.id === categoryId));
}

Here is context
context: async ({req}) => {
        return {
            loaders: {
                subCategory: new Dataloader(keys => loaders.categoryLoaders.batchSubCategory(keys))
            }
        }
},

I am using apollo server.

A: I have also encountered this type of problem.
The solution was to use the .loadMany() Method.
You can also refer to this URL https://medium.com/the-marcy-lab-school/how-to-use-dataloader-js-9727c527efd0.
Just try
Instead of .load() method:

const subcategory = await loaders.subCategory.load(parent.subCategory.toString());

Use the .loadMany() Method:

const subcategory = await loaders.subCategory.loadMany(parent.subCategory);


text:
Q: Interface that all properties are strings and one property is number I want to define an interface like below.
interface Foo {
   id: number,
   [x:string]: string
}

It means id is a numeric type and all other properties are strings. But I am getting and error. The error is:-
Property 'id' of type 'number' is not assignable to string index type 'string'.ts(2411)

How to solve this issue? Thanks in advance!


text:
Q: filtering input to only numbers. C Here's a basic question:
How can I take the input from a user and only accept numbers?
I know I need to use this start:
    do{
    ch=getchar();
     }while (ch != '\n');

But I know it's not enough. This will block every input, including numbers, so I need to break when input is number.
also how do I break not after the first digit of the number?
I tried looking this up with no luck.
thanks!

A: When you need to perform error checking, do different things based on the input, etc., it's best to read user input line by line and process each line as you see fit.
// Make it large enough for your needs.
#define LINE_LENGTH 200

char line[LINE_LENGTH];

// Keep reding lines of text until there is nothing to read.
while ( fgets(line, sizeof(line), stdin) != NULL )
{
   // Process contents of line.
}

If you expect to see only one number per line, you can use sscanf to extract numbers from each line.
while ( fgets(line, sizeof(line), stdin) != NULL )
{
   int num;
   if ( sscanf(line, "%d", &num) == 1 )
   {
      // Got a number. Use it.
   }
}

A: The probably easiest way to read in a number is using scanf:
int number;
if (scanf("%d",&number) == 1) {
  printf("successfully read number %d\n",number);
} else {
  printf("not a number.\n");
}

It skips leading white spaces and then takes characters from stdin as long as these match an integral number format. Note that you still might have to press "enter" before your program will proceed, because the operating system might buffer the input (beyond your control).
Note that a ch=getchar() will take also the first non-digit value from stdin, which can then not be consumed by any further access to stdin anymore. scanf, in contrast, keeps this character in the buffer for later use.

A: Just check if the input is some value between '0' and '9'
#include <stdio.h>

int main(void)
{
    size_t len = 0;
    char str[32];
    int ch;

    while (len < sizeof(str) - 1) {
        ch = getchar();
        if ((ch >= '0') && (ch <= '9')) {
            str[len++] = (char)ch;
        } else {
            break;
        }
    }
    str[len] = '\0';
    puts(str);
    return 0;
}

A: simple, nice and neat solution:), I used to solve similar questions when I started programming, this will let you only input numbers
#include <stdio.h>

int main()
{
char ch;
  do{
    ch=getchar();
   }while (!(ch>=48 && ch<=57));
printf("yay,we got a number : %c !",ch);
return 0;
}


text:
Q: How to adjust the log output level of GTK4? When developing an application based on GTK4, a log will be printed every time it is started. How can I get rid of it?
(conquerdocker:17460): Gtk-WARNING **: 09:13:21.962: Unknown key gtk-button-images in /home/aszswaz/.config/gtk-4.0/settings.ini

(conquerdocker:17460): Gtk-WARNING **: 09:13:21.962: Unknown key gtk-menu-images in /home/aszswaz/.config/gtk-4.0/settings.ini

(conquerdocker:17460): Gtk-WARNING **: 09:13:21.963: Unknown key gtk-toolbar-style in /home/aszswaz/.config/gtk-4.0/settings.ini

A: If you are not concerned about having any log output when you are executing your program, you could call your program and redirect the logging output to "/dev/null", such as:
./your_program_name > /dev/null

Alternatively, since your program is most likely a GUI program and doesn't require a terminal/console window, you could set up a desktop file similar to the following example.
[Desktop Entry]
Type=Application
Name=GtkProgramName
Icon=/home/username/.local/share/icons/hicolor/48x48/apps/GTK.png
Categories=Utilities;
StartupNotify=true
Terminal=false
Exec=/path/to/your/Programs/your_program_name

The key attribute here is the "Terminal=false" attribute which will run your program without a terminal, and therefore a user would not see spurious messages.  Desktop files usually are placed in the "~/.local/share/applications folder" and have a permission mask of "rw-rw-r--".
You might give those options a try.
Regards.


text:
Q: Android Oreo 8 unable to fetch packages I tried fetching browser packages using the below code, I have two web browser, UC Browser and Google Chrome. But this is not returning me any browsers. This is happening only for Android Oreo signed APK for Google Pixel.
Intent webIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
List<ResolveInfo> activities = activity.getPackageManager().queryIntentActivities(webIntent, 0);

A: Add
webIntent.setType("text/html");

Or try with
webIntent.setDataAndType(url,"text/html");


text:
Q: Pattern printing with arrays/tuples So I'm trying to do this
You will be given a positive integer n > 0 and you will construct a pattern that is made up of n rows:
• Row 0 contains 1 number—the number 1
• Each row is one longer than the one before and follows the pattern that ensues
So if variable n:int = 4, the output would be
[1]
[1,2]
[2,3,5]
[5,7,10,15]

The number in the current array is added to the number immediately above it in the previous array and appended at the end of the current array. Also when starting a new array the last element of the previous array is considered as the first element of the current array.
I apologize if my question is unclear, but I hope after the example and explanation I provided, the question is clearer now.
Here is my code:
def append(n: int):
    for x in range(1,n+1):
        return(x,x+1)
    print(append(n))

When I put n = 4, it doesnt seem to work, what's the problem here?

A: I don't think your code will return the pattern you want to show. Here's a little code I wrote to print that pattern but there are two loops running, if you could optimize that you could do it or else use the code just as it is.
n=4
arr=[1]
brr = [1]
print(brr)
for i in range(0,n-1):
  brr = arr[i:]
  for k in range(0,len(arr)):
    brr.append(arr[k]+brr[k])
  arr = brr
  print(brr)

A: This will do it:
def func(n):
    mylist = []
    for i in range(n):
        if i == 0:
            mylist.append([1])
        else:
            mylist.append(createnewlist(mylist[i-1]))
    return mylist

def createnewlist(a):
    newlist = []
    for i in range(len(a)+1):
        if i == 0:
            newlist.append(a[len(a)-1])
        else:
            value = a[len(a)-1]
            for m in range(i):
                value += a[m]
            newlist.append(value)
    return newlist

print(func(6))


text:
Q: Call specific method on object depending on selected enum value Let's assume we have an enum, that represents searchable fields:
enum SearchableFields {
    ALL,
    FIELD1,
    FIELD2,
    FIELD3;
}

This enum is displayed via a (combobox) selection inside a GUI. At runtime, I want to evaluate the selection of this combobox and search accordingly.
Depending on the selection, I need to retrieve the fields to search from a POJO (example below) via a getter.
class FieldPojo {
    private String field1;
    private String field2;
    private String field3;
    ...
    public String getField1() {
        return field1;
    }
    ...
}

I currently use a switch statement to evaluate the selection of SelectableFields and to then retrieve the correct field(s) to search:
private String retrieveField(FieldPojo f) {
    switch (selectedField) {
    case ALL:
        return retrieveAll(); // method that retrieves all available fields
    case FIELD1:
        return f.getField1();
    ...
}

This does work, however I feel like it's clunky.
Question:
Is there a more concise way to do this without evaluating the enum via a switch? (Java 8)

A: You can create a static map instead of the switch-case.
private static final Map<SearchableFields,Supplier<String>> searchableFieldsToFieldPojo = Map.of(
    ALL, this::retrieveAll,
    FIELD1, FieldPojo::retrieveAll
    );

And then you can access via:
searchableFieldsToFieldPojo.get(selectedField).get();

A: Given that you can modify all parts of the code, you have several options:

*

*Put the retrieveField into the class FieldPojo and modify it's parameter so it takes the enum SearchableFields as parameter.

*Put the fields of FieldPojo as values into a map with a key of type SearchableFields. You can then decide whether you want to have "ALL" as an extra entry of the map or handle it as special case in a method similar to retrieveField. You could use this to have a "default" handling if you want to update the enum but not the FieldPojo class.

*You put retrieveField into the class FieldPojo together with the SearchableFields enum - since only FieldPojo knows, which fields it actually provides as searchable fields.

*You use introspection to gather the list of possible searchable fields and also access their contents.

Depending on your real requirements (you only showed a very abstract and specific version of them) one or the other method might be "the right one" for you. I would actually prefer the "everything into FieldPojo" as the most robust one, but on the other hand if you are not able to change FieldPojo and have to handle many different classes like it, the introspection variant might be the right one. (Be aware that it is fragile in terms of security and also probably very slow.)

A: You could store a reference to the getter in your enum constants:
enum SearchableFields {
    ALL(FieldPojo::retrieveAll),
    FIELD1(FieldPojo::getField1)

    private final Function<FieldPojo, String> accessor;
    SearchableFields(Function<FieldPojo, String> acccessor) {
        this.accessor = accessor;
    }

    public String get(FieldPojo fp) {
        return accessor.apply(fp);
    }
}

A: Enums can contain method definitions, so one way is to define the method that retrieves the field name based on the enum value. I assume you have the actual field name stored as a member field also. Then you can override the method for the special ALL value:
enum SearchableFields {
    ALL("all") { // all is just a placeholder in this case
        @Override
        String retrieveField(FieldPojo f) {
            // logic for all fields
        }
    },
    FIELD1("field1"),
    FIELD2("field2"),
    FIELD3("field3");

    SearchableFields(String fieldName) {
        this.fieldName = Optional.of(fieldName);
    }
    SearchableFields() {
        fieldName = Optional.empty();
    }
    private final Optional<String> fieldName;

    String retrieveField(FieldPojo f) {
        if (fieldName.isPresent()) {
            return (String) f.getClass().getField(fieldName.get()).get(f);
        } else {
           // ...
        }
    }
}


text:
Q: how to iterate only first level node in xml with x-path? I need to iterate through an XML file. The root node has a few children and I need to either copy the child as is or to do something. So I'm working on an XSLT to do so. Here's a sample source XML:
<?xml version="1.0" encoding="utf-8"?>
<XDSDocumentEntry id="DOC01">
    <author authorRole="XDSITEST_DICOM_INSTANCE_PUBLISHER" authorPerson="XDSITEST">Author</author>
    <classCode displayName="Communication" codingScheme="Connect-a-thon classCodes">Communication</classCode>
    <confidentialityCode displayName="Celebrity" codingScheme="Connect-a-thon confidentialityCodes">
</XDSDocumentEntry>

In this XML I need to select nodes author, classCode and confidentialityCodes but I'm getting the text() nodes with this code:
        <xsl:for-each select="node()"><!--<xsl:copy-of select="."/>-->
            <!--<xsl:value-of select="local-name()"/>-->
            <xsl:choose>
                <xsl:when test="author">
                    do something
                </xsl:when>
                <xsl:otherwise>
                    <xsl:copy-of select="."/>
                </xsl:otherwise>
            </xsl:choose>
        </xsl:for-each>

My result so far is this:
author<author authorRole="XDSITEST_DICOM_INSTANCE_PUBLISHER" authorPerson="XDSITEST"
       authorInstitution="Some institution"/>
classCode<classCode displayName="Communication" codingScheme="Connect-a-thon classCodes">Communication</classCode>
confidentialityCode<confidentialityCode displayName="Celebrity" codingScheme="Connect-a-thon confidentialityCodes">
C</confidentialityCode>

Any hint? Thx.

EDIT
Sorry, had an error (I removed ).
Actually, why am I using the for-each is because I need the document exactly as it was except for a few nodes. In the example above the final output should look like this:
<?xml version="1.0" encoding="UTF-8"?>
<XDSDocumentEntry>
    <author authorRole="XDSITEST_DICOM_INSTANCE_PUBLISHER" authorPerson="XDSITEST"
           authorInstitution="Some institution"/>
    <author>
        <authorInstitution>
            <organizationName>Some institution</organizationName>
        </authorInstitution>
        <authorRole>XDSITEST_DICOM_INSTANCE_PUBLISHER</authorRole>
        <authorPerson>
            <assigningAuthorityName>XDSITEST</assigningAuthorityName>
        </authorPerson>
    </author>
    <classCode displayName="Communication" codingScheme="Connect-a-thon classCodes">Communication</classCode>
    <confidentialityCode displayName="Celebrity" codingScheme="Connect-a-thon confidentialityCodes">
    C</confidentialityCode>
</XDSDocumentEntry>

EDIT 2
I created this template as suggested by @Martin. But still how do I select the node name 'author'??
<xsl:template match="node()|@*">
    <xsl:copy>
        <xsl:choose>
            <xsl:when test="local-name()=author">
                    a
            </xsl:when>
            <xsl:otherwise>
                <xsl:apply-templates select="node()|@*"/>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:copy>
</xsl:template>

A: It is hard to tell what goes wrong without knowing the context node of your for-each. I would suggest you forget about for-each and instead start writing templates e.g.
<xsl:template match="XDSDocumentEntry/*">
  <!-- output here what you want to output for child elements of XDSDocumentEntry -->
</xsl:template>

<xsl:template match="XDSDocumentEntry/author">
  <!-- put needed special treatement of author element here -->
</xsl:template>

If you still have problems then show us what kind of output you want to create for the sample input you posted, then we can help with the proper XSLT code.
[edit]
If all you want is copying nodes besides the child nodes of the author element then two templates suffice:
<xsl:template match="@* | node()">
  <xsl:copy>
    <xsl:apply-templates select="@* | node()"/>
  </xsl:copy>
</xsl:template>

<xsl:template match="XDSDocumentEntry/author">
  <xsl:copy>
    <xsl:apply-templates select="@*"/>
  </xsl:copy>
</xsl:template>

A: This stylesheet:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="node()|@*" name="identity">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="author/node()"/>
    <xsl:template match="author">
        <xsl:call-template name="identity"/>
        <xsl:copy>
            <xsl:apply-templates select="@*" mode="element"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="@*" mode="element">
        <xsl:element name="{name()}">
            <xsl:apply-templates select="." mode="value"/>
        </xsl:element>
    </xsl:template>
    <xsl:template match="author/@authorPerson" mode="value">
        <assigningAuthorityName>
            <xsl:value-of select="."/>
        </assigningAuthorityName>
    </xsl:template>
</xsl:stylesheet>

Output:
<XDSDocumentEntry id="DOC01">
    <author authorRole="XDSITEST_DICOM_INSTANCE_PUBLISHER" authorPerson="XDSITEST"></author>
    <author>
        <authorRole>XDSITEST_DICOM_INSTANCE_PUBLISHER</authorRole>
        <authorPerson>
            <assigningAuthorityName>XDSITEST</assigningAuthorityName>
        </authorPerson>
    </author>
    <classCode displayName="Communication" codingScheme="Connect-a-thon classCodes">Communication</classCode>
    <confidentialityCode displayName="Celebrity" codingScheme="Connect-a-thon confidentialityCodes"></confidentialityCode>
</XDSDocumentEntry>

A:
I created this template as suggested
  by @Martin. But still how do I select
  the node name 'author'??

Answer:
You do not select. Instead, you override the identity template with a more specific template that matches exactly the node(s) (in your case the author element, for which you want a different processing than simply copy "as-is":
<xsl:template match="author">
  <!-- Put your specific code here -->
</xsl:template>

Using and overriding the identity rule is the most fundamental and powerful XSLT design pattern. Read more about it here.


text:
Q: hillshade and slopeshade geotiffs fail to convert to new projection using gdalwarp I'm trying to convert my three DEM products (colour, hillshade and slopeshade; the latter two generated using gdaldem) from EPSG:4326 -> EPSG:3857 using gdalwarp, via the command:
gdalwarp -of GTiff -s_srs epsg:4326 -t_srs epsg:3857 -co "tfw=yes" {src} {dst}

This works fine for the colour geotiff, but the resulting hillshade and slopeshade geotiffs now appear blank.
Sample output from gdalinfo for the slopeshade geotiff is below, with links to the original and converted files at the bottom.
gdalinfo before:
Driver: GTiff/GeoTIFF
Files: slopeshade_dem.tif
Size is 4557, 3577
Coordinate System is:
GEOGCS["WGS 84",
    DATUM["WGS_1984",
        SPHEROID["WGS 84",6378137,298.257223563,
            AUTHORITY["EPSG","7030"]],
        AUTHORITY["EPSG","6326"]],
    PRIMEM["Greenwich",0],
    UNIT["degree",0.0174532925199433],
    AUTHORITY["EPSG","4326"]]
Origin = (-121.460761599999998,38.583444700000001)
Pixel Size = (0.000000654597323,-0.000000654598826)
Metadata:
  AREA_OR_POINT=Area
Image Structure Metadata:
  INTERLEAVE=PIXEL
Corner Coordinates:
Upper Left  (-121.4607616,  38.5834447) (121d27'38.74"W, 38d35' 0.40"N)
Lower Left  (-121.4607616,  38.5811032) (121d27'38.74"W, 38d34'51.97"N)
Upper Right (-121.4577786,  38.5834447) (121d27'28.00"W, 38d35' 0.40"N)
Lower Right (-121.4577786,  38.5811032) (121d27'28.00"W, 38d34'51.97"N)
Center      (-121.4592701,  38.5822740) (121d27'33.37"W, 38d34'56.19"N)
Band 1 Block=4557x1 Type=Byte, ColorInterp=Gray
  Mask Flags: PER_DATASET ALPHA
Band 2 Block=4557x1 Type=Byte, ColorInterp=Alpha

gdalinfo after:
Driver: GTiff/GeoTIFF
Files: slopeshade_dem.tif
Size is 4088, 4105
Coordinate System is:
PROJCS["WGS 84 / Pseudo-Mercator",
    GEOGCS["WGS 84",
        DATUM["WGS_1984",
            SPHEROID["WGS 84",6378137,298.257223563,
                AUTHORITY["EPSG","7030"]],
            AUTHORITY["EPSG","6326"]],
        PRIMEM["Greenwich",0],
        UNIT["degree",0.0174532925199433],
        AUTHORITY["EPSG","4326"]],
    PROJECTION["Mercator_1SP"],
    PARAMETER["central_meridian",0],
    PARAMETER["scale_factor",1],
    PARAMETER["false_easting",0],
    PARAMETER["false_northing",0],
    UNIT["metre",1,
        AUTHORITY["EPSG","9001"]],
    EXTENSION["PROJ4","+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext  +no_defs"],
    AUTHORITY["EPSG","3857"]]
Origin = (-13520950.132675198838115,4662178.034760829061270)
Pixel Size = (0.081230547006284,-0.081230547006284)
Metadata:
  AREA_OR_POINT=Area
Image Structure Metadata:
  INTERLEAVE=PIXEL
Corner Coordinates:
Upper Left  (-13520950.133, 4662178.035) (121d27'38.74"W, 38d35' 0.40"N)
Lower Left  (-13520950.133, 4661844.583) (121d27'38.74"W, 38d34'51.97"N)
Upper Right (-13520618.062, 4662178.035) (121d27'28.00"W, 38d35' 0.40"N)
Lower Right (-13520618.062, 4661844.583) (121d27'28.00"W, 38d34'51.97"N)
Center      (-13520784.097, 4662011.309) (121d27'33.37"W, 38d34'56.19"N)
Band 1 Block=4088x1 Type=Byte, ColorInterp=Gray
Band 2 Block=4088x1 Type=Byte, ColorInterp=Undefined

Links to the slopeshade file before conversion (in EPSG:4326):
https://www.dropbox.com/s/9safqs1hkngnasf/slopeshade_dem.tif?dl=0
Links to the slopeshade file after conversion (in EPSG:3857):
https://www.dropbox.com/s/ebmgnbhrzog01ui/slopeshade_dem.tif?dl=0


text:
Q: Triple Nested Navigators w/ React-Navigation and Typescript in React Native I am writing an app in which I have a base Stack, that contains a StartupScreen, another Stack with two AuthScreens, and then finally a Tab Navigator.
As a quick example, this looks like this:
export type AppStackParamsList = {
  StartupScreen: undefined;
  AuthStack: NavigatorScreenParams<AuthStackParamsList>;
  HomeTabs: NavigatorScreenParams<HomeTabsParamsList>;
};
const Stack = createStackNavigator<AppStackParamsList>();

<Stack.Navigator screenOptions={{ headerShown: false }}>
      <Stack.Screen
        options={{ gestureEnabled: false }}
        name="StartupScreen"
        component={StartupScreen}
      />
      <Stack.Screen name="AuthStack" component={AuthStack} />
      <Stack.Screen name="HomeTabs" component={HomeTabs} />
</Stack.Navigator>

Here is HomeTabs:
export type HomeTabsParamsList = {
  HomeStack: NavigatorScreenParams<HomeStackParamsList>;
};

const Tabs = createBottomTabNavigator<HomeTabsParamsList>();
const HomeTabs = () => {
  return (
    <Tabs.Navigator screenOptions={{ headerShown: false }}>
      <Tabs.Screen name="HomeStack" component={HomeStack} />
    </Tabs.Navigator>
  );
};

And finally HomeStack
export type HomeStackParamsList = {
    HomeScreen: undefined;
}

const Stack = createStackNavigator<HomeStackParamsList>();
const HomeStack = () => {
  return (
    <Stack.Navigator screenOptions={{headerShown: false }}>
        <Stack.Screen name="HomeScreen" component={HomeScreen}/>
    </Stack.Navigator>
  )
}

The start up screen is shown initially and does some work to find out if there's a user, and if so, then navigate to the HomeTabs, otherwise, navigate to the AuthStack which contains a sign in and sign up screen.
type Props = StackScreenProps<AppStackParamsList, "StartupScreen">;

...

 if (auth) {
      navigation.navigate("HomeTabs");
    } else {
      navigation.navigate("AuthStack", { screen: "SignInScreen" });
    }

The AuthStack is working fine, and from StartupScreen I am able to navigate to AuthStack no problem.
My problem is coming in at navigating to the HomeTabs. in the above conditional, when I try to navigate to HomeTabs from StartupScreen, i am shown the typescript warning:
Argument of type 'string' is not assignable to parameter of type '{ key: string; params?: undefined; merge?: boolean | undefined; } | { name: "StartupScreen"; key?: string | undefined; params: undefined; merge?: boolean | undefined; } | { key: string; params?: NavigatorScreenParams<...> | undefined; merge?: boolean | undefined; } | { ...; } | { ...; } | { ...; }'

I'm extremely confused by this as I'm even getting proper code completion for the screens that are nested in the Tab Navigator.
For example, if I type:
navigation.navigate("HomeTabs", { screen: "HomeStack" });

VScode is able to autocomplete this as if TS is aware the screen is there.
I thought by using the nested navigator pattern all the way up the navigator tree, this would be no problem, but clearly I have something wrong here and I have a feeling it's because it's a nested Tab navigator and not a nested Stack navigator, but I'm not sure of that.
Just to reiterate, the pattern I have is, from the bottom-most stack going UP:
export type HomeStackParamsList = {
    HomeScreen: undefined;
}
export type HomeTabsParamsList = {
  HomeStack: NavigatorScreenParams<HomeStackParamsList>;
};
And finally:

export type AppStackParamsList = {
  StartupScreen: undefined;
  AuthStack: NavigatorScreenParams<AuthStackParamsList>;
  HomeTabs: NavigatorScreenParams<HomeTabsParamsList>;
};

Can anyone see what I've done wrong here?
Maybe I have the entire philosophy wrong?


text:
Q: Flutter - showing a PopupMenuButton in BottomNavigationBar I am trying to show a menu when a navigation bar item is clicked. This was my attempt:
  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
        length: 3,
        child: Scaffold(
            appBar: MyAppBar(
              title: "Home",
              context: context,
            ),
            bottomNavigationBar: BottomNavigationBar(
              items: [
                BottomNavigationBarItem(
                    icon: new Icon(Icons.home), title: Text('Home')),
                BottomNavigationBarItem(
                    icon: new Icon(Icons.book), title: Text('Second')),
                BottomNavigationBarItem(
                    icon: new PopupMenuButton(
                      icon: Icon(Icons.add),
                      itemBuilder: (_) => <PopupMenuItem<String>>[
                            new PopupMenuItem<String>(
                                child: const Text('test1'), value: 'test1'),
                            new PopupMenuItem<String>(
                                child: const Text('test2'), value: 'test2'),
                          ],
                    ),
                    title: Text('more')),
              ],
              currentIndex: 0,
            ),
            body: new Container()));
  }

I encountered two problems. First one is the display of the NavigationBarItem. There is a padding between the icon the title that I could not remove (even by adding padding: EdgeInsets.all(0.0)) (as the picture below shows). And the second is that I need to click exactly on the icon for the menu to appear.

I tried calling showMenu directly (the method that PopupMenuButton calls) when a BottomNavigationBarItem of index=2 (for example) is clicked. But it was tricky how to determine the location of origin where the menu should appear from.

A: Here's my attempt at it:
@override
  Widget build(BuildContext context) {
    return Material(
        child:  DefaultTabController(
        length: 3,
        child: Scaffold(
            appBar: AppBar(
              title: Text("Home"),
            ),
            bottomNavigationBar: BottomNavigationBar(
              items: [
                BottomNavigationBarItem(
                    icon: new Icon(Icons.home), title: Text('Home')),
                BottomNavigationBarItem(
                    icon: new Icon(Icons.book), title: Text('Second')),
                BottomNavigationBarItem(
                    icon: new Icon(Icons.add),
                    title: Text('More')),
              ],
              currentIndex: 0,
              onTap: (int index) async {
                if(index == 2){
                  await showMenu<String>(
                    context: context,
                    position: RelativeRect.fromLTRB(1000.0, 1000.0, 0.0, 0.0),
                    items: <PopupMenuItem<String>>[
                      new PopupMenuItem<String>(
                                child: const Text('test1'), value: 'test1'),
                            new PopupMenuItem<String>(
                                child: const Text('test2'), value: 'test2'),
                    ],
                    elevation: 8.0,
                  );
                }
              },
            ),
            body: new Container())));
  }

Basically using the showMenu method as you said except I've put the values for the RelativeRect as 1000.0 so that it'll be in the bottom right of any device. You could mess around with these values to get a position more right above the icon but I think having it like this works well:

A: Here's an attempt that uses the showMenu directly and calling the function buttonMenuPosition to get the position for the menu. It's fairly fragile, but you can change the location of the button to the middle for example with bar.size.center instead of bar.size.bottomRight. With some MATH and by manually manipulating Offset objects (if/when you have more than 3 items), you can change the location to have the menu on one that isn't the center or at the end).
RelativeRect buttonMenuPosition(BuildContext c) {
    final RenderBox bar = c.findRenderObject();
    final RenderBox overlay = Overlay.of(c).context.findRenderObject();
    final RelativeRect position = RelativeRect.fromRect(
      Rect.fromPoints(
        bar.localToGlobal(bar.size.bottomRight(Offset.zero), ancestor: overlay),
        bar.localToGlobal(bar.size.bottomRight(Offset.zero), ancestor: overlay),
      ),
      Offset.zero & overlay.size,
    );
    return position;
  }

  @override
  Widget build(BuildContext context) {

    final key = GlobalKey<State<BottomNavigationBar>>();

    return DefaultTabController(
        length: 3,
        child: Scaffold(
            appBar: AppBar(
              title: Text("Home"),
            ),
            bottomNavigationBar: BottomNavigationBar(
              key: key,
              items: [
                const BottomNavigationBarItem(
                    icon: Icon(Icons.home), title: Text('Home')),
                const BottomNavigationBarItem(
                    icon: Icon(Icons.book), title: Text('Second')),
                const BottomNavigationBarItem(
                    icon: Icon(Icons.add), title: Text('more')),
              ],
              currentIndex: 0,
              onTap: (index) async {
                final position = buttonMenuPosition(key.currentContext);
                if (index == 2) {
                  final result = await showMenu(
                    context: context,
                    position: position,
                    items: <PopupMenuItem<String>>[
                      const PopupMenuItem<String>(
                          child: Text('test1'), value: 'test1'),
                      const PopupMenuItem<String>(
                          child: Text('test2'), value: 'test2'),
                    ],
                  );
                }
              },
            ),
            body: Container()));
  }


text:
Q: Bash: slice of positional parameters How can I get a slice of $@ in Bash without first having to copy all positional parameters to another array like this?
argv=( "$@" )
echo "${argv[@]:2}";

A: More array slicing examples in bash
In place of using some_array_variable in your code (argv in your case), simply use @ in that variable name's place. The symbol @ represents the input argument array, and you can treat it exactly like you'd treat any other array. The confusion is simply that we are accustomed to seeing it almost always paired with the $ character like this: $@, and so we don't realize that the @ character is the array itself, and can be used alone as an array variable as well.
So, here are some examples:
Slice from the input argument array, @, which is normally seen and accessed simply as $@:
# array slicing basic format 1: grab a certain length starting at a certain
# index
echo "${@:2:5}"
#         │ │
#         │ └────> slice length
#         └──────> slice starting index

# array slicing basic format 2: grab all remaining array elements starting at a
# certain index through to the end
echo "${@:2}"
#         │
#         │
#         └──────> slice starting index

More array reminders to myself:
The following are general array reminders to myself that may benefit others landing on this page too.
# store a slice from an array into a new array
new_array=("${@:4}")

# print the entire array
echo "new_array = ${new_array[@]}"

Here is a runnable example of generic array slicing and array element access in bash, inspired by this source:
(Use @ as the input argument array if desired, instead of a below, according to your use case)
a=(one two three four five six)   # define a new array, `a`, with 6 elements
echo "$a"           # print first element of array a
echo "${a}"         # print first element of array a
echo "${a[0]}"      # print first element of array a
echo "${a[1]}"      # print *second* element of array a
echo "${#a[@]}"     # print number of elements in array a
echo "${a[@]:1:3}"  # print 2nd through 4th elements; ie: the 3 elements
                    # starting at index 1, inclusive, so: indices 1, 2, and 3
                    # (output: `two three four`)
echo "${a[@]:1}"    # print 2nd element onward

Run it all
Copy and paste all code chunks above into a file called array_slicing_demo.sh, and mark it executable with chmod +x array_slicing_demo.sh so that you can run it. Or, just download my demo array_slicing_demo.sh file from my eRCaGuy_hello_world repo here.
Then, run it like this:
./array_slicing_demo.sh a b c d e f g h i j k

...and you will see the following output:

b c d e f
b c d e f g h i j k
new_array = d e f g h i j k
one
one
one
two
6
two three four
two three four five six

References

*

*Bash: slice of positional parameters

*Single parenthesis in bash variable assignment
Keywords: array access in bash; bash array indexing; access elments in arrays in bash; bash array slicing; print arrays in bash; print array elements in bash

A: You can use the same format as for any other array. To extract the 2nd and 3rd elements from $@, you would do:
echo "${@:1:2}"
          - -
          | |----> slice length
          |------> slice starting index

A: I usually do this:
somefunc() {
    local message="$1"
    shift
    echo "message = $message"
    echo "other   = $@"
}
somefunc first second third goforth

which will print:
message = first
other   = second third goforth

You can expand on the concept by shifting after second, third, etc. argument

A: For function parameters, the answer with echo "${@:1:2}" didn't work for me at all. Also, I wanted the slice-off the first element, since it was a different parameter. What did work was:
function foo(){ #takes single param + array of params
  local param1="$1".                   #first param
  local -a tmp=( "${@}" )              #copy all params
  local -a rem_params=( "${tmp[@]:1}") #slice off first:Works!
# local -a rem_params=( "${@[@]:1}"  ) #DID NOT WORK, ERROR
# local -a rem_params=( "{@:1}"      ) #DID NOT SLICE
  echo "${rem_params[@]}"
}

Maybe I'll write to test to see how this works with positional arguments for at the script-level, but no time right now.


text:
Q: AWS lambda websocket implementation using custom domain name has POST issues I have an AWS API gateway websocket lambda implementation.  I have connected a custom domain to the API gateway.  I am able to connect and disconnect just fine.  But when I try to post messages using the AWS.ApiGatewayManagementApi the custom domain name is causing a problem.
I was building the endpoint using parms, as follows:
const apigwManagementApi = new AWS.ApiGatewayManagementApi({
    apiVersion: '2018-11-29',
    endpoint: event.requestContext.domainName + '/' + event.requestContext.stage
  });

And then calling it as follows:
await apigwManagementApi.postToConnection({ ConnectionId: connectionId, Data: postData }).promise();

This resulted in an error as follows:
2021-01-07T09:56:12.751Z    846f4674-0ed9-422b-8b35-64f0c43a10de    INFO    NotFoundException: No method found matching route test/@connections/YxcdBcOkrPECHwA= for http method POST.
    at Object.extractError (/var/runtime/node_modules/aws-sdk/lib/protocol/json.js:52:27)
    at Request.extractError (/var/runtime/node_modules/aws-sdk/lib/protocol/rest_json.js:55:8)
    at Request.callListeners (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:106:20)
    at Request.emit (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:78:10)
    at Request.emit (/var/runtime/node_modules/aws-sdk/lib/request.js:688:14)
    at Request.transition (/var/runtime/node_modules/aws-sdk/lib/request.js:22:10)
    at AcceptorStateMachine.runTo (/var/runtime/node_modules/aws-sdk/lib/state_machine.js:14:12)
    at /var/runtime/node_modules/aws-sdk/lib/state_machine.js:26:10
    at Request.<anonymous> (/var/runtime/node_modules/aws-sdk/lib/request.js:38:9)
    at Request.<anonymous> (/var/runtime/node_modules/aws-sdk/lib/request.js:690:12) {
  code: 'NotFoundException',
  time: 2021-01-07T09:56:12.712Z,
  requestId: '43b744b9-25ef-4a15-82ed-6ecb13062208',
  statusCode: 404,
  retryable: false,
  retryDelay: 64.57971601177839
}

I then changed the code to use a hard-coded value for the AWS gateway endpoint, which looks like this (actual id ogjkythg67m changed for privacy):
const apigwManagementApi = new AWS.ApiGatewayManagementApi({
    apiVersion: '2018-11-29',
    endpoint: "https://ogjkythg67m.execute-api.eu-west-2.amazonaws.com/test"
  });

At this point everything started working.
So, it seems that I can't use the event.requestContext.domainName + '/' + event.requestContext.stage vars to build my endpoint when using a custom domain.
I don't really want to hard-code the endpoint into the code.  Is there any way to configure my AWS API gateway or lambda definition to leverage the custom domain name, or circumvent the issue in some other way?
Thanks.

A: I'm late to the party I'm sure,
This happened to me today, I'd just built upon the sample provided by AWS.
there they also append the stage like your code above
const apigwManagementApi = new AWS.ApiGatewayManagementApi({
apiVersion: '2018-11-29',
endpoint: event.requestContext.domainName + '/' + event.requestContext.stage

});
To fix, you simply remove the code that appends the stage
 + '/' + event.requestContext.stage

then it works fine with the custom domain

A: The error message says
NotFoundException: No method found matching route test/@connections/YxcdBcOkrPECHwA= for http method POST.

so /@connections/YxcdBcOkrPECHwA= is somehow being appended to the endpoint. Looks like the websocket documenation confirms this.
Log event.requestContext.stage to confirm this yourself. The documentation doesn't seem to cover this, so you'll have to inspect event.requestContext by logging it to see if another field with just the stage is provided, or provide some string manipulation to strip the rest of that path.