text:
Q: Error importing react components from NPM package in NextJS I'm trying to publish my first package to npm for learning purposes. I've created a few react components with typescript and have published them to npm here.
And here's the ts.config I used for building and compiling the package:
{
  "compilerOptions": {
    "strict": true,
    "jsx": "react",
    "declaration": true,
    "esModuleInterop": true,
    "outDir": "dist",
    "target": "es6",
    "module": "es6",
    "moduleResolution": "node"
  },
  "include": ["src"]
}

This worked fine, but the problems occur when trying to use these components in my NextJS app using npx create-next-app@latest. After initializing everything and successfully npm install pirate-ui@1.0.5, I cleared out the src/pages/index.tsx file to get rid of the boilerplate and tried implementing the components like this:
import { TextInput } from 'pirate-ui';
import { useState } from 'react';

interface StateValues {
  [key: string]: string;
}

export default function Home() {
  const [val, setVal] = useState<StateValues>({
    val: '',
  });
  return (
    <TextInput
      name="testing"
      id="my-id"
      curState={val.val}
      raiseState={setVal}
      styles={{ div: '', label: '', input: '' }}
    />
  );
}

VScode's autocomplete works, and i'm able to see the props and type defs for the component, and am not experiencing any typescript errors. However, upon running npm run dev I get this error:
error - /Users/sailormetz/Development/Web/testing-pirate-ui/node_modules/pirate-ui/index.js:1
export { TextInput } from './TextInput';
^^^^^^

SyntaxError: Unexpected token 'export'
    at Object.compileFunction (node:vm:360:18)
    at wrapSafe (node:internal/modules/cjs/loader:1088:15)
    at Module._compile (node:internal/modules/cjs/loader:1123:27)
    at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)

It's throwing an error on the export statement in my index.js file. Why is this happening? For what its worth, I followed this tutorial here.
Feel like I'm doing something silly, or getting something wrong in my ts.config.
Thanks.


text:
Q: Combining 2 (or 3) Javascripts when both use an ID I'm just in the process of learning HTML and JS and have the need to combine two functions - both work on their own. I have browsed through the suggestions, and tried about 3 different methods,  but I still can't work it out.
I have a link that exposes a hidden div when clicked and I now need the text to change to "Close" … default is closed and text says open. Both the JavaScript work on their own.
I cannot use external files with this.
My question is:
How do I get the 3 functions below to work from the one link?
JavaScript file 1
function toggle_visibility(id) {
    var e = document.getElementById(id);
    if(e.style.display == 'none')
    e.style.display = 'block';
    else
    e.style.display = 'none';
}

JavaScript file 2
function openTri() {
    document.getElementById('tri').innerHTML = "Open";
}
function cloTri() {
    document.getElementById('tri').innerHTML = "Close;";
}

A: I'm guessing at what you want to do but might be this
function toggle_visibility(id) {
    var e = document.getElementById(id);
    if(e.style.display == 'none') {
        e.style.display = 'block';
        document.getElementById('tri').innerHTML = "Close;";
    }
    else {
        e.style.display = 'none';
         document.getElementById('tri').innerHTML = "Open";
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Screen rotation with ViewPager - Problem with FragmentManager and FragmentPagerAdapter I'm having some problems when dealing with Fragment using ViewPager.
What I'm having:
An activity (say, MainActivity) that contains a ViewPager to display some Fragment(s). Some of them contains a callback interface, which will be called to do somethings in the MainActivity.
The MainActivity has a FragmentPagerAdapter class, which is used as the adapter of the ViewPager. And a List<Fragment> in FragmentPagerAdapter to store some Fragment that will be displayed on the ViewPager.
What I'm expecting:
First launch, the Fragment called the callback interface's methods when I hit a button in it and MainActivity did somethings inside that. It worked great.
After a screen rotation, I expected it to work the same as the first launch BUT
NullPointerException: attempt to invoke a method on a null reference object (particularly, the Fragment's interface) hit me in my face.
What I know:
- The getItem(int position) won't be called again once the Fragment is created. Instead the instantiateItem(ViewGroup container, int position) will be called.
- FragmentManager will store some Fragment in mActive.mValues
- ViewPager and fragments — what's the right way to store fragment's state? (I did reference to this and some other same topics on StackOverflow too.)
What I have tried and saw:
- Override instantiateItem(ViewGroup container, int position)
- Debugged for 1 day. I saw that when I pass getSupportFragmentManager() in MainActivity's onCreate() method to FragmentPagerAdapter's super constructor, in the first launch, it has an "address in memory", assume it was '1a1a1a1'. The mActive.mValues of FragmentManager saved some Fragment' "address in memory" which are identical to the List<Fragment> containing them (assume it was 'qwertyu'). Which meaned it was right.
But when I rotated the screen, passing the getSupportFragmentManager() again, the "address in memory" was completely different, assume '9f9f9f9'. And FragmentManager's mActive.mValues contained a different set of Fragment' "address in memory" too (assume 'abcdeff'), although the number of Fragment in it was equal to the number of Fragment that was saved on the first launch (before rotation).
I have added a Fragment to the List<Fragment> with a new "address in memory" (assume 'abababa'), has the callback interface. But when I hit the button in it, it was the Fragment that was in the FragmentManager's mActive.mValues after the rotation (with "address in memory" is 'abcdeff' as I assumed above), and that one didn't have the callback interface (due to not being set in MainActivity first). And caused the NullPointerException as mentioned above.
My questions now is:
- First of all, how to get rid of this problem!? It would be better to keep using FragmentPagerAdapter instead of another class. But I will consider using other class too.
- Second, can you explain why FragmentManager saved the Fragment instance before rotation. But after rotation, it creates a completely different Fragment instance but still uses it instead of the Fragment that was saved in the List<Fragment>?
Here is the code (I think I didn't use the instantiateItem(ViewGroup container, int position) method in the right way so it still caused the problem).
public class MainActivity extends AppCompatActivity {

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

        //Attach the SectionsPagerAdapter to the ViewPager
        SectionsPagerAdapter pagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
        ViewPager viewPager = findViewById(R.id.viewPager);
        viewPager.setAdapter(pagerAdapter);
    }

    //
    //
    //Adapter class
    private class SectionsPagerAdapter extends FragmentPagerAdapter {
        private static final int PAGE_HOME = 0;
        private int tabCount = 1;
        private List<Fragment> fragmentList = new ArrayList<>();
        private List<String> fragmentTitleList = new ArrayList<>();
        //private FragmentManager fragmentManager;

        SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
            //fragmentManager = fm;

            //Default HomeFragment
            HomeFragment homeFragment = new HomeFragment();
            //Callback interface
            homeFragment.setOnCategoryFragmentChangedListener(new HomeFragment.OnCategoryFragmentChangedListener() {
                //This method will be called when a button in HomeFragment is clicked
                @Override
                public void onAddNewCategory(String categoryName) {
                    addNewCategory(categoryName);
                }
            });
            fragmentList.add(homeFragment);
            fragmentTitleList.add("Home");
        }

        @Override
        public Fragment getItem(int position) {
            return fragmentList.get(position);
        }

        @Override
        public int getCount() {
            return tabCount;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return fragmentTitleList.get(position);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            fragmentList.set(position, (Fragment) super.instantiateItem(container, position));
            return fragmentList.get(position);
        }

        private void addNewCategory(String categoryName) {
            CategoryFragment fragment = new CategoryFragment();

            tabCount += 1;
            fragmentList.add(fragment);
            fragmentTitleList.add(categoryName);
            notifyDataSetChanged();
        }
    }
}

Please help. I'm being insane for 2 days now...!

A: I believe android restarts the activity during orientation change thus making multiple instances of FragmentPagerAdapter and multiple set of instances of List.
I don't completely understand your question but I suspect instantiateItem doesn't do anything anyway. Doesn't the Fragment getItem(int pos) work without overriding instantiateItem()?

A: Oh well, right after i felt in sleep, I found the solution. It's true that I didn't use the instantiateItem() method in the right way. After debugging again, I found that the instantiateItem() method get call whenever I swipe (or choose if using TabLayout as well) to another Fragment, and even get call before getItem(int pos), no matter what it's the first launch or after rotation. Which is why I think we should set things up for the Fragment in the instantiateItem() method.
So here is how I use the instantiateItem() method now:
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            fragmentList.set(position, (Fragment) super.instantiateItem(container, position));
            Fragment fragment = fragmentList.get(position);
            if (position == PAGE_HOME) {
                ((HomeFragment) fragment).setOnCategoryFragmentChangedListener(new HomeFragment.OnCategoryFragmentChangedListener() {
                    @Override
                    public void onAddNewCategory(String categoryName) {
                        addNewCategory(categoryName);
                    }
                });
            }
            return fragment;
        }

If anyone have a better solution, please just tell me if you don't mind. I will consider about it.


text:
Q: GroupBy can't be translated I'm trying to remove duplicates from my database. I'm using Entity Framework Core and .NET 5. EF Core is having trouble materializing my group by:
protected async Task RemoveDuplicates(CryptoInfoContext cryptoContext)
{
    try
    {
        var duplicates = cryptoContext.HistoricalCandles
            .GroupBy(x => new { x.StartDate, x.GranularitySeconds })
            .Where(x => x.Count() > 1)
            .ToList()
            .Select(x => x.FirstOrDefault())
            .ToList();

        cryptoContext.RemoveRange(duplicates);
        await cryptoContext.SaveChangesAsync();
    }
    catch(Exception ex)
    {
        Console.WriteLine(ex);
    }
}

I'm getting an error:

Unable to translate the given 'GroupBy' pattern. Call 'AsEnumerable' before 'GroupBy' to evaluate it client-side

I don't feel like materializing all of my rows to remove the duplicates.
Is there a list of known issues with group by?
how can I work around this issue?

A: Thanks to @GertArnold for pointing me in the right direction.   Apparently EF Group by only support aggregate queries.
As pointed out by this article:
var ctx = new EntertainmentDbContext(conString);

var dataTask = ctx
            .Ratings
            .GroupBy(x => x.Source)
            .Select(x => new {Source = x.Key, Count = x.Count()})
            .OrderByDescending(x => x.Count)
            .ToListAsync();

var data = await dataTask;

Which will generate SQL like so:
SELECT "r"."Source", COUNT(*) AS "Count"
FROM "Ratings" AS "r"
GROUP BY "r"."Source"
ORDER BY COUNT(*) DESC

Note: currently pretty much nothing else works, you CANNOT even apply a where before the group by.
Additionally there is an open EF Core issue  Please vote on it so they actually fix this instead of pushing it another release

A: Your group by value is I guess a DateTime. Only scalar values can be used in group by clause, because SQL cannot group by on date either.
Look also this git issue on more detailed explanation and this question on SQL details.
As for a workaround - I did't try it, but probably you could group by time string representation or ticks.


text:
Q: Object value is not preserved from view to controller I am using a model to pass values from controller to model. Say I have a first controller action method :
    public ActionResult CreateADForm(SiteDirectionModel model){
        MyModel myModel= new MyModel{
            id = model.id,
            name = model.name,
            //an so on
            siteDirection = model //a SiteDirectionModel object
        };
        return View(myModel);
    }

The point of this method is to preload some values and then pass it to a view with a form :
@model MyProject.Models.MyModel
@using (Html.BeginForm("ValidateForm", "Create", FormMethod.Post))
        {
            @Html.AntiForgeryToken()

            @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                @Html.LabelFor(m=>m.name, new { @class= "col-md-2 control-label" })

                    @Html.TextBoxFor(m => m.name, new { @class = "form-control" })
                    @Html.ValidationMessageFor(m => m.name, "", new { @class = "text-danger" })

            <input type="submit" value="Créer l'utilisateur" class="btn btn-primary" />

My problem is that now when I validate this form, I try to retrieve SiteDirectionModel siteDirection but it is always null. I wanted to do that, so that in case the form is not valid, then I return to the form with errors shown (like textboxes not filled for example), but it's dysfunctional. I'm guessing that the values have to be attributed when filling the form which is why I keep getting null, but have you any idea how to do this?

A: Form validation happens after the roundtrip to the server is complete (i.e. after form POST).
Therefore you have to send all values back to the server that you require in the receiving action.
Add hidden fields for the properties of siteDirection you need.
@Html.HiddenFor(m => m.siteDirection.Name)
@Html.HiddenFor(m => m.siteDirection.Value)
@* ... *@

Alternatively, send the ID of the siteDirection and load this entity from the DB again.


text:
Q: Live server in vscode in Ubuntu is not loading in Android mobile phone I created a simple webpage and started the liveserver in vscode in ubuntu

*

*It opened the webpage in Ubuntu with the url http://127.0.0.1:5500/

*I opened the webpage in android with the url http://192.168.43.208:5500/
(I know to open with the router IP and the laptop and android are in same network), but it kept on loading and the webpage was not loaded.

*Whereas the same process in it windows worked.
Please help me to fix this, I am dual booting ubuntu and windows.

A: Had the same issue, the problem is the firewall.
You can set the wi-fi you are connected to to be a private network, then it will work.
https://support.microsoft.com/en-us/windows/make-a-wi-fi-network-public-or-private-in-windows-10-0460117d-8d3e-a7ac-f003-7a0da607448d


text:
Q: confuse to make error message in PHP all this code is work, what left is I try to echo a message if query not find anything..

include("config.php");

$search = $_POST['search'];

$sql = mysql_query("SELECT * FROM barangtbl WHERE nama LIKE '%$search%' ") or die(mysql_error());
  while ($res=mysql_fetch_array($sql)) {
    echo $res['nama'].'
';
  }

?>

A: Write this:
if(mysql_num_rows($sql)) {
  while ($res=mysql_fetch_array($sql)) {
    echo $res['nama'].'
';
  }
}
else
{
 echo "Not found";
}

A: try this:
if($sql)
{
    echo  "success";
}
else
{
    echo  "Error";
}

A: Try this:
include("config.php");

$search = $_POST['search'];

$sql = mysql_query("SELECT * FROM barangtbl WHERE nama LIKE '%$search%' ") or die(mysql_error());
if(mysql_num_rows($sql))
{
  while ($res=mysql_fetch_array($sql)) {
    echo $res['nama'].'
';
  }
}
else
{
   echo "The query resulted in an Empty Set";
}

Here,
mysql_num_rows($sql) will output the total no of rows in the result. If the query's output is zero rows, the value of mysql_num_rows($sql) is zero which will lead to the if condition being false and hence executing the else part.

A: John V is right.
But i would suggest you to use mysqli instead of the deprecated mysql function
(deprecated since version 5.5)
http://php.net/manual/en/book.mysqli.php


text:
Q: How to get App Catalog site URL using JavaScript? Is there a way to programmatically get the App Catalog site URL in a SharePoint Framework (SPFx) Web Part? I'd like to read/set the SharePoint Tenant Properties in my Web Part. However, we need to know the App Catalog site URL in order to use the @pnp library or make REST call.
Since there is only one App Catalog site for each tenant, is there a way we can find its URL using JavaScript instead of asking users' input?
Thanks.

A: When it comes to SPFx, Waldek to the rescue !
You need to make GET request to an undocumented endpoint /_api/SP_TenantSettings_Current which will give you the App Catalog Url.
Minimal code for that is:
var appCatalogUrl = "https://<your-tenant>.sharepoint.com/_api/SP_TenantSettings_Current";
this.context.spHttpClient.get(appCatalogUrl,
  SPHttpClient.configurations.v1,
  {
    headers: {
      'Accept': 'application/json;odata=nometadata',
      'odata-version': ''
    }
  })
  .then((response: SPHttpClientResponse) => {
    response.json().then((value: any) => {
      console.log(value);

      var appCatalogUrlValue = value.CorporateCatalogUrl;

      if(appCatalogUrlValue && appCatalogUrlValue.length > 0){
        // do some stuff using it
      }
});

Reference - Get the tenant app catalog URL using the REST API
As mentioned in the blog, it is undocumented and looks like it is reverse engineered from the tenantSettings.CorporateCatalogUrl CSOM property. So, you can use it in production at your own risk !
Best option would be to ask for user's input if you are only using REST, because since the API is in preview it might be subject to change by Microsoft which can break your solution.
If its an option for you to use CSOM, would suggest that you use the TenantSettings.CorporateCatalogUrl property itself since it is defined in the CSOM code itself.


text:
Q: Binary Formatter not really Working (Unity, C#) This code should make a File where the UUID cant be read by normal people locking in the file but  this is the output :
    ÿÿÿÿ          $45b7f364-99ce-4f4a-b592-21d3a40ae79a

and you can see the full UUID : 45b7f364-99ce-4f4a-b592-21d3a40ae79a
What is the problem or am i understanding the Binary Formatter wrong?
    private void Start()
    {
        if (!Directory.Exists(Application.persistentDataPath + @"\Saves\Local\PlayerInfo\"))
        {
            Directory.CreateDirectory(Application.persistentDataPath + @"\Saves\Local\PlayerInfo\");
        }

        print(playerUUID());
    }

    public string playerUUID()
    {
        string path = Application.persistentDataPath + @"\Saves\Local\PlayerInfo\" + "PlayerInfo.data";
        string pathbackup = Application.persistentDataPath + @"\Saves\Local\PlayerInfo\" + "PlayerInfo.data.backup";
        if (File.Exists(path))
        {
            try
            {
                BinaryFormatter formatter = new BinaryFormatter();

                FileStream stream = new FileStream(path, FileMode.Open);

                print("UUID Found");

                return formatter.Deserialize(stream) as string;
            }
            catch
            {
                print("UUID Damaged! Creating new");

                File.Copy(path, pathbackup);

                BinaryFormatter formatter = new BinaryFormatter();
                FileStream stream = new FileStream(path, FileMode.Create);

                string newUUID = System.Guid.NewGuid().ToString();

                formatter.Serialize(stream, newUUID);
                stream.Close();

                return newUUID;
            }
        }
        else
        {
            print("UUID not found! Creating new");

            BinaryFormatter formatter = new BinaryFormatter();
            FileStream stream = new FileStream(path, FileMode.Create);

            string newUUID = System.Guid.NewGuid().ToString();

            formatter.Serialize(stream, newUUID);
            stream.Close();

            return newUUID;
        }
    }


text:
Q: Echo all links in a HTML page PHP How would I echo all links from an HTML page use DOMDocument?
My current code
$html = file_get_contents("http://en.wikipedia.org");
$dom = new DOMDocument;
$dom->loadHTML($html);
$output = new DOMDocument;
$links = $dom ->getElementsByTagName('a');
foreach($links as $link)
{
     $output->importNode($link);
}
echo $output -> saveHTML();

A: Here it is:
<?php
$html = file_get_contents("http://en.wikipedia.org");
$dom = new DOMDocument;
$dom->loadHTML($html);
$output = new DOMDocument;
$output->formatOutput = true;
$links = $dom ->getElementsByTagName('a');
foreach($links as $link){
    $node = $output->importNode($link, true);
    $output->appendChild($node);
}
echo $output -> saveHTML();


text:
Q: Exactly which .NET version does Windows Server 2008 R2 Core support? So, Microsoft added .NET support to Windows Server 2008 R2 Core, but which is the latest version that is supported? I know it has to be either .NET 3.5 or .NET 3.5 SP1, but which is it?

A: Windows Server 2008 R2, as well as Windows 7, comes with built-in .NET Framework 3.5 SP1.
http://social.technet.microsoft.com/Forums/en/windowsserver2008r2webtechnologies/thread/ac1bf719-0a88-4b5d-be98-395f2623e805

A: Vs. 2 and Vs. 3.5 (SP1) are in the box, but Vs. 4 is also supported on Windows Server 2008 R2 Core, but you have to download a special version.


text:
Q: I'm trying to simply print out or write/display dynamically on a webpage whatever is in the title tags using javascript I've tried a couple things like document.title and also giving the title tag and id and pulling the innerHTML.
<script>document.getElementByID('tr').innerHTML="";</script>
There's got to be a simpler way to do this and I'm just forgetting and can't figure it out atm.
my title tags are normal
<title></title>

or should i use the
<title id="tr"></title>

Any help would be greatly appreciated. Thank you.

A: You are correct that you can get the title tag content by
document.title
//or
document.querySelectorAll('title')[0].innerHTML;

But I'm not sure where you want to put it.  You are grabbing a  element now, but probably want to put it somewhere else;
In your HTML:
<h3 id='title'> </h3>

In your JavaScript
var title = document.title;
var domElem = document.getElementById('title');
//Add title to DOM element
domElem.innerHTML = title;


text:
Q: How to get the original text of a sentence after CoreNLP does ssplit? Tokenization by CoreNLP changes the sentence text. Stitching together tokens separated by white space isn't a true reconstruction. Things get complicated if the sentence contains round brackets and other punctuation. Please see the code block below.
Properties props = new Properties();
props.setProperty("annotators", "tokenize, ssplit");
pipeline = new StanfordCoreNLP(props);

Annotation document = new Annotation(paragraph);
pipeline.annotate(document);

List<CoreMap>sentences = document.get(SentencesAnnotation.class);

List<String> sentenceList = new ArrayList<>();
for (CoreMap sentence : sentences)
{
    //How to get the original text of sentence?
}

A: Answering my own question. Its pretty easy. Insert the following line in place of the comment in the question code block.
String sentenceString = Sentence.listToOriginalTextString(sentence.get(TokensAnnotation.class));

A: for (CoreMap sentence : sentences)
{
    String sentenceStr = sentence.get(CoreAnnotations.TextAnnotation.class)
}


text:
Q: Faster alternative to nested loops? I have a need to create a list of combinations of numbers. The numbers are quite small so I can use byte rather than int. However it requires many nested loops in order to get every possible combination. I'm wondering if there's a more efficient manner to do what I'm after. Code so far is:
var data = new List<byte[]>();
for (byte a = 0; a < 2; a++)
for (byte b = 0; b < 3; b++)
for (byte c = 0; c < 4; c++)
for (byte d = 0; d < 3; d++)
for (byte e = 0; e < 4; e++)
for (byte f = 0; f < 3; f++)
for (byte g = 0; g < 3; g++)
for (byte h = 0; h < 4; h++)
for (byte i = 0; i < 2; i++)
for (byte j = 0; j < 4; j++)
for (byte k = 0; k < 4; k++)
for (byte l = 0; l < 3; l++)
for (byte m = 0; m < 4; m++)
{
    data.Add(new [] {a, b, c, d, e, f, g, h, i, j, k, l, m});
}

I was considering using something like a BitArray but I'm not sure how I could incorporate it.
Any recommendations would be greatly appreciated. Alternatively, perhaps this is the fastest way of doing what I want?
EDIT
Couple of quick points (and apologies I didn't put these in the original post):

*

*The numbers and the order of them (2, 3, 4, 3, 4, 3, 3 etc) are very important, so using a solution such as Generating Permutations using LINQ won't help because the maximums in each 'column' are different

*I'm not a mathematician, so I apologise if I'm not using the technical terms like 'permutations' and 'combinations' correctly :)

*I do need to populate all of these combinations at once - I can't just grab one or another based on an index

*Using byte is faster than using int, I guarantee it. It's also a lot better on memory usage to have 67m+ arrays of bytes rather than ints

*My ultimate goal here is to look for a faster alternative to nested loops.

*I considered using parallel programming, but due to the iterative nature of what I'm trying to achieve, I couldn't find a way to do it successfully (even with ConcurrentBag) - however I'm happy to be proved wrong :)

CONCLUSION
Caramiriel has provided a good micro-optimisation which shaves some time off the loops, so I've marked that answer as correct. Eric also mentioned that it is faster to pre-allocate the List. But, at this stage it seems that the nested loops are in fact the fastest possible way of doing this (depressing, I know!).
If you want to try exactly what I was trying to benchmark with StopWatch, go with 13 loops counting up to 4 in each loop - that makes about 67m+ lines in the list. On my machine (i5-3320M 2.6GHz) it takes about 2.2s to do the optimised version.

A: var numbers = new[] { 2, 3, 4, 3, 4, 3, 3, 4, 2, 4, 4, 3, 4 };
var result = (numbers.Select(i => Enumerable.Range(0, i))).CartesianProduct();

Using the extension method at
http://ericlippert.com/2010/06/28/computing-a-cartesian-product-with-linq/
public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences)
{
    // base case:
    IEnumerable<IEnumerable<T>> result =
        new[] { Enumerable.Empty<T>() };
    foreach (var sequence in sequences)
    {
        // don't close over the loop variable (fixed in C# 5 BTW)
        var s = sequence;
        // recursive case: use SelectMany to build
        // the new product out of the old one
        result =
            from seq in result
            from item in s
            select seq.Concat(new[] { item });
    }
    return result;
}

A: List has an array internally where it stores it values, with a fixed length . When You call List.Add it checks if there is enough space. When it dcannot add the new element it will create a new array of a larger size, copy all the previous elements over, then add then new one. This takes quite a few cycles.
Since you know the number of elements already, you can create the list of the correct size, that should be a lot faster already.
Also, not sure how you access the values, but you could create this thing one and save the image in code (loading it from disk will probably be slower than what you;re doing now. How many times do you read/ write to this thing?

A: As a reminder: you probably do not need this kind of code while developing your own solution. This can and should only used in very specific situations. Readability is often more important than speed.
You can use the properties of a struct and allocate the structure in advance. I cut off some levels in the sample below, but I'm sure you'll be able to figure out the specifics. Runs about 5-6 times faster than the original (release mode).
The block:
struct ByteBlock
{
    public byte A;
    public byte B;
    public byte C;
    public byte D;
    public byte E;
}

The loop:
var data = new ByteBlock[2*3*4*3*4];
var counter = 0;

var bytes = new ByteBlock();

for (byte a = 0; a < 2; a++)
{
    bytes.A = a;
    for (byte b = 0; b < 3; b++)
    {
        bytes.B = b;
        for (byte c = 0; c < 4; c++)
        {
            bytes.C = c;
            for (byte d = 0; d < 3; d++)
            {
                bytes.D = d;
                for (byte e = 0; e < 4; e++)
                {
                    bytes.E = e;
                    data[counter++] = bytes;
                }
            }
        }
    }
}

It's faster because it doesn't allocate a new list every time you add it to the list. Also since it's creating this list, it needs a reference to every other value (a,b,c,d,e). You can assume each value is only modified once inside the loop, so we can optimize it to do so (data locality).
Also read the comments for side-effects.
Edited the answer to use an T[] instead of a List<T>.

A: Here's a different way that only need 2 loop. The idea is to increase the first element and if that number goes over than increase the next one.
Instead of displaying the data, you can use currentValues.Clone and add that cloned version into your list. For me this ran faster than your version.
byte[] maxValues = {2, 3, 4};
byte[] currentValues = {0, 0, 0};

do {
    Console.WriteLine("{0}, {1}, {2}", currentValues[0], currentValues[1], currentValues[2]);

    currentValues[0] += 1;

    for (int i = 0; i <= maxValues.Count - 2; i++) {
        if (currentValues[i] < maxValues[i]) {
            break;
        }

        currentValues[i] = 0;
        currentValues[i + 1] += 1;
    }

// Stop the whole thing if the last number is over
// } while (currentValues[currentValues.Length-1] < maxValues[maxValues.Length-1]);
} while (currentValues.Last() < maxValues.Last());

*

*Hope this code works, I converted it from vb

A: What you are doing is counting (with variable radix, but still counting).
Since you are using C#, I assume you don't want to play with useful memory layout  and data structures that let you really optimize your code.
So here I'm posting something different, which may not suit your case, but it's worth noting: In case you actually access the list in a sparse fashion, here a class that let you compute the i-th element in linear time (rather than exponential as the other answers)
class Counter
{
    public int[] Radices;

    public int[] this[int n]
    {
        get
        {
            int[] v = new int[Radices.Length];
            int i = Radices.Length - 1;

            while (n != 0 && i >= 0)
            {
                //Hope C# has an IL-opcode for div-and-reminder like x86 do
                v[i] = n % Radices[i];
                n /= Radices[i--];
            }
            return v;
        }
    }
}

You can use this class this way
Counter c = new Counter();
c.Radices = new int[] { 2,3,4,3,4,3,3,4,2,4,4,3,4};

now c[i] is the same as your list, name it l, l[i].
As you can see, you can easily avoid all those loops :) even when you pre compute all the list at whole since you can simply implement a Carry-Ripple counter.
Counters are a very studied subject, I strongly advice to search for some literature if you feel.

A: All your numbers are compile time constant.
What about unrolling all the loops into a list (using your program to write code):
data.Add(new [] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0});
data.Add(new [] {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0});
etc.

That should at least take away the overhead of the for loops (if there is any).
I'm not familiar with C# too much, but there seems to be some means of serializing objects. What if you just generated that List and serialized it in some form? I'm not sure if the deserialization is quicker then creating the List and adding the elements, though.

A: Do you need the result to be an array of arrays? With the current setup the length of the inner arrays is fixed and could be replaced with structs. This would allow the entire thing to be reserved as one continuous block of memory and provides easier access to the elements (not sure how you use this thing lateron).
The approach below is much faster (41ms vs 1071ms for the original on my box):
struct element {
    public byte a;
    public byte b;
    public byte c;
    public byte d;
    public byte e;
    public byte f;
    public byte g;
    public byte h;
    public byte i;
    public byte j;
    public byte k;
    public byte l;
    public byte m;
}

element[] WithStruct() {
    var t = new element[3981312];
    int z = 0;
    for (byte a = 0; a < 2; a++)
    for (byte b = 0; b < 3; b++)
    for (byte c = 0; c < 4; c++)
    for (byte d = 0; d < 3; d++)
    for (byte e = 0; e < 4; e++)
    for (byte f = 0; f < 3; f++)
    for (byte g = 0; g < 3; g++)
    for (byte h = 0; h < 4; h++)
    for (byte i = 0; i < 2; i++)
    for (byte j = 0; j < 4; j++)
    for (byte k = 0; k < 4; k++)
    for (byte l = 0; l < 3; l++)
    for (byte m = 0; m < 4; m++)
    {
        t[z].a = a;
        t[z].b = b;
        t[z].c = c;
        t[z].d = d;
        t[z].e = e;
        t[z].f = f;
        t[z].g = g;
        t[z].h = h;
        t[z].i = i;
        t[z].j = j;
        t[z].k = k;
        t[z].l = l;
        t[z].m = m;
        z++;
    }
    return t;
}

A: On my machine, this generates the combinations in 222 ms vs 760 ms (the 13 for loops):
private static byte[,] GenerateCombinations(byte[] maxNumberPerLevel)
{
    var levels = maxNumberPerLevel.Length;

    var periodsPerLevel = new int[levels];
    var totalItems = 1;
    for (var i = 0; i < levels; i++)
    {
        periodsPerLevel[i] = totalItems;
        totalItems *= maxNumberPerLevel[i];
    }

    var results = new byte[totalItems, levels];

    Parallel.For(0, levels, level =>
    {
        var periodPerLevel = periodsPerLevel[level];
        var maxPerLevel = maxNumberPerLevel[level];
        for (var i = 0; i < totalItems; i++)
            results[i, level] = (byte)(i / periodPerLevel % maxPerLevel);
    });

    return results;
}

A: Method 1
One way to make it faster is to specify the capacity if you plan to keep using List<byte[]>, like this.
var data = new List<byte[]>(2 * 3 * 4 * 3 * 4 * 3 * 3 * 4 * 2 * 4 * 4 * 3 * 4);

Method 2
Furthermore, you could use System.Array directly to gain faster access.  I recommend this approach if your question insists that every element be physically populated in memory, upfront.
var data = new byte[2 * 3 * 4 * 3 * 4 * 3 * 3 * 4 * 2 * 4 * 4 * 3 * 4][];
int counter = 0;

for (byte a = 0; a < 2; a++)
    for (byte b = 0; b < 3; b++)
        for (byte c = 0; c < 4; c++)
            for (byte d = 0; d < 3; d++)
                for (byte e = 0; e < 4; e++)
                    for (byte f = 0; f < 3; f++)
                        for (byte g = 0; g < 3; g++)
                            for (byte h = 0; h < 4; h++)
                                for (byte i = 0; i < 2; i++)
                                    for (byte j = 0; j < 4; j++)
                                        for (byte k = 0; k < 4; k++)
                                            for (byte l = 0; l < 3; l++)
                                                for (byte m = 0; m < 4; m++)
                                                    data[counter++] = new[] { a, b, c, d, e, f, g, h, i, j, k, l, m };

This takes 596ms to complete on my computer, which is about 10.4% faster than the code in question (which takes 658ms).

Method 3
Alternatively, you can use the following technique for low cost initialization that suits access in a sparse fashion.  This is especially favorable when only some elements may be needed and determining them all upfront is considered unnecessary.  Moreover, techniques like these may become the only viable option when working with more vast elements when memory runs short.
In this implementation every element is left to be determined lazily, on-the-fly, upon access.  Naturally, this comes at a cost of additional CPU that is incurred during access.
class HypotheticalBytes
{
    private readonly int _c1, _c2, _c3, _c4, _c5, _c6, _c7, _c8, _c9, _c10, _c11, _c12;
    private readonly int _t0, _t1, _t2, _t3, _t4, _t5, _t6, _t7, _t8, _t9, _t10, _t11;

    public int Count
    {
        get { return _t0; }
    }

    public HypotheticalBytes(
        int c0, int c1, int c2, int c3, int c4, int c5, int c6, int c7, int c8, int c9, int c10, int c11, int c12)
    {
        _c1 = c1;
        _c2 = c2;
        _c3 = c3;
        _c4 = c4;
        _c5 = c5;
        _c6 = c6;
        _c7 = c7;
        _c8 = c8;
        _c9 = c9;
        _c10 = c10;
        _c11 = c11;
        _c12 = c12;
        _t11 = _c12 * c11;
        _t10 = _t11 * c10;
        _t9 = _t10 * c9;
        _t8 = _t9 * c8;
        _t7 = _t8 * c7;
        _t6 = _t7 * c6;
        _t5 = _t6 * c5;
        _t4 = _t5 * c4;
        _t3 = _t4 * c3;
        _t2 = _t3 * c2;
        _t1 = _t2 * c1;
        _t0 = _t1 * c0;
    }

    public byte[] this[int index]
    {
        get
        {
            return new[]
            {
                (byte)(index / _t1),
                (byte)((index / _t2) % _c1),
                (byte)((index / _t3) % _c2),
                (byte)((index / _t4) % _c3),
                (byte)((index / _t5) % _c4),
                (byte)((index / _t6) % _c5),
                (byte)((index / _t7) % _c6),
                (byte)((index / _t8) % _c7),
                (byte)((index / _t9) % _c8),
                (byte)((index / _t10) % _c9),
                (byte)((index / _t11) % _c10),
                (byte)((index / _c12) % _c11),
                (byte)(index % _c12)
            };
        }
    }
}

This takes 897ms to complete on my computer (also creating & adding to an Array as in Method 2), which is about a 36.3% slower than the code in question (which takes 658ms).

A: What about using Parallel.For() to run it? (Struct optimization kudos to @Caramiriel). I slightly modified the values (a is 5 instead of 2) so I'm more confident in the results.
    var data = new ConcurrentStack<List<Bytes>>();
    var sw = new Stopwatch();

    sw.Start();

    Parallel.For(0, 5, () => new List<Bytes>(3*4*3*4*3*3*4*2*4*4*3*4),
      (a, loop, localList) => {
        var bytes = new Bytes();
        bytes.A = (byte) a;
        for (byte b = 0; b < 3; b++) {
          bytes.B = b;
          for (byte c = 0; c < 4; c++) {
            bytes.C = c;
            for (byte d = 0; d < 3; d++) {
              bytes.D = d;
              for (byte e = 0; e < 4; e++) {
                bytes.E = e;
                for (byte f = 0; f < 3; f++) {
                  bytes.F = f;
                  for (byte g = 0; g < 3; g++) {
                    bytes.G = g;
                    for (byte h = 0; h < 4; h++) {
                      bytes.H = h;
                      for (byte i = 0; i < 2; i++) {
                        bytes.I = i;
                        for (byte j = 0; j < 4; j++) {
                          bytes.J = j;
                          for (byte k = 0; k < 4; k++) {
                            bytes.K = k;
                            for (byte l = 0; l < 3; l++) {
                              bytes.L = l;
                              for (byte m = 0; m < 4; m++) {
                                bytes.M = m;
                                localList.Add(bytes);
                              }
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }

        return localList;
      }, x => {
        data.Push(x);
    });

    var joinedData = _join(data);

_join() is a private method, defined as:
private static IList<Bytes> _join(IEnumerable<IList<Bytes>> data) {
  var value = new List<Bytes>();
  foreach (var d in data) {
    value.AddRange(d);
  }
  return value;
}

On my system, this version runs approximately 6 times faster (1.718 seconds versus 0.266 seconds).

A: Some of your numbers fit entirely on an integer nuimber of bits, so you can "pack" them with the upper level number :
for (byte lm = 0; lm < 12; lm++)
{
    ...
    t[z].l = (lm&12)>>2;
    t[z].m = lm&3;
    ...
}

Of course, this makes the code less readable, but you saved one loop. This can be done each time one of the numbers is a power of two, which is seven time in your case.

A: Here is another solution. Outside of VS it runs as fast as 437.5 ms which is 26% faster than the original code (593.7 on my computer):
static List<byte[]> Combinations(byte[] maxs)
{
  int length = maxs.Length;
  int count = 1; // 3981312;
  Array.ForEach(maxs, m => count *= m);
  byte[][] data = new byte[count][];
  byte[] counters = new byte[length];

  for (int r = 0; r < count; r++)
  {
    byte[] row = new byte[length];
    for (int c = 0; c < length; c++)
      row[c] = counters[c];
    data[r] = row;

    for (int i = length - 1; i >= 0; i--)
    {
      counters[i]++;
      if (counters[i] == maxs[i])
        counters[i] = 0;
      else
        break;
    }
  }

  return data.ToList();
}


text:
Q: Can anyone please explain this python syntax - reverse word Could anyone please explain what is, message = " " and for b in variable: message = b+message?
variable = raw_input("Input a word to reverse: ")
message = ""
for b in variable:
    message = b+message
print (message)

Thank you

A: Code:
variable = raw_input("Input a word to reverse: ")
message = ""
for b in variable:
    message = b+message
print (message)

Example : Input a word to reverse:
"Hello"
for loop : Iteration by iteration

*

*b="H" in variable
message = H+""="H"

*b="e" in variable
message = e+"H"="eH"

*b="l" in variable

message = l+"eH"="leH"

*b="l" in variable

message = l+"eH"="lleH"

*b="o" in variable

message = l+"eH"="olleH"
Hope this helps you with clear understanding.

A: Oh boy. This is basic stuff... You should probably look into some Python tutorials...
message = ""

Is assigning an empty string to a variable
for b in variable:

Is a construct that will step through each item in variable and within the following block you can access that item via b.  So in this case variable is a string and this will step through each letter of the string
message = b+message

Is taking the letter as mentioned above, and pretending it to the existing message and then assigning that back to message.  So if message was 'eh' and the next letter was 'l'. Then message would now equal 'leh'


text:
Q: in Mac, how to press command and option at the same time? in Xcode, many hotkeys need you to press the command+option, which fingers I should use?
For example:

*

*option+CMD+left/right: to folder some code

*shift+option+CMD+left/right: to folder all method

A: With your Left hand, use the Index (pointing) & 2nd finger & middle fingers to hold Option (Alt),  Command and/or Shift on left side of keyboard.
Use your Right hand to hit the other key needed, which is always only one key at a time.
You can hold down the Option/Command/Control/Shift keys for as long as you want without it doing anything - only when you hit another key (with your right hand) will the action be performed.
There's a reason they call it finger gymnastics.  Just try resetting your System Management Controller (SMC) or PRAM!
–––––––––––––––––––––––––––––––––––––––
Here's my "finger gymnastics" to hit the EMACS combo you mentioned in the comments - ⌘+⌥+⌃+⇧ ! (Control+Shift hit with one finger.)
It's possible your keyboard layout doesn't allow this.  Most Apple-compliant keyboards (and my MS Surface keyboard) will allow this.
You can still press another key with the other hand if needed.
Piano lessons may help ;^)   [I do think this whole topic is hilariously non-technical, I'm glad you asked]


text:
Q: Passing arguments to bash script with subprocess I am trying to pass arguments to a bash script from python. The official documentation says that you need to separate with comma but I'm using it and it does not work.
subprocess.run(["/bin/bash test.sh", "hello", "dog", "3" ], shell=True)

In the bash script I have this basic code:
echo "The number of arguments is: $#"

The result is: The number of arguments is: 0
Any advice? I decided it to pass as a string (Not so clean), putting a space " "+"hello" + " dog" + " 3"
Regards,

A: You have two options.

*

*call it with a list of arguments but without shell=True:
subprocess.run(["/bin/bash", "test.sh", "hello", "dog", "3" ])

*pass a single string with shell=True:
subprocess.run("/bin/bash test.sh hello dog 3", shell=True)

From docs of subprocess:

On POSIX with shell=True, the shell defaults to /bin/sh. If args is a string, the string specifies the command to execute through the shell. This means that the string must be formatted exactly as it would be when typed at the shell prompt. This includes, for example, quoting or backslash escaping filenames with spaces in them. If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional arguments to the shell itself.

More info about shell flag: Actual meaning of 'shell=True' in subprocess


text:
Q: Integer score to letter grade in C? This program should be really easy but for some reason I can't figure out how to rework the logic so that it uses 'if' statements only (no else).
Basically it is like this
if(score >= 90)
grade = 'A';
else if(score >= 80)
grade = 'B';

etc
We are meant to rework this logic so that it uses only 'if' and not 'else'. I've tried a few ways and none of them seem to work for me. The way I tried which I thought would work is this
if(score <= 100)
{
    if(score < 90)
    {
        if(score <80)
        {
            if(score <70)
            {
                if(score <60)
                {
                    grade = 'F';
                }
                grade = 'D';
            }
            grade = 'C';
        }
        grade = 'B';
    }
}
if(score >= 90)
    grade = 'A';

This will get the grade of A correctly, and B but when I go below 80, it always gives me B. Can anyone point out my error? Or perhaps and easier way to do this?

A: I actually figured it out on my own before you guys posted, but I appreciate the help! I'm posting this as an answer cuz I did it differently then the two answers posted.
if(score < 60)
grade = 'F';
if(score >= 60)
grade = 'D';
if(score >=70)
grade = 'C';
if(score >=80)
grade = 'B';
if(score >= 90)
grade = 'A';

Basically just took the if-else logic and flipped it upside down without the else's. Thanks again!

A: Two possibilities (nested and not):
grade = 'A';
if(score < 90)
{
    grade = 'B';
    if(score < 80)
    {
        grade = 'C';
        //...
    }
}

if(score >= 90) grade = 'A';
if(score >= 80 && score < 90) grade = 'B';
if(score >= 70 && score < 80) grade = 'C';
...

A: Try separating the If statements
if(score < 90)
{grade = 'B';}
if(score <80)
{grade = 'C';}
if(score <70)
{grade = 'D';}
if(score <60)
{grade = 'F';}

if(score >= 90)
grade = 'A';

A: Always check from the smallest range up and compare with </<=, or check from the maximum range down with >/>=. Besides use else if to avoid redundant checks like most of the above answers. For example OP's solution compares score with 60 twice, which is unnecessary
if (score < 60)
    grade = 'F';
else if (score < 70)
    grade = 'D';
else if (score < 80)
    grade = 'C';
else if (score < 90)
    grade = 'B';
else
    grade = 'A';

But you don't actually need that many if blocks
const char* SCORE[] = "FDCBA";
if (score < 60)
    grade = 'F'; // or = SCORE[0];
else if (score < 100);
    grade = SCORE[score/10 - 5];
else if (score == 100)
    grade = 'A'; // or = SCORE[4];


text:
Q: EditText.setError for a not focusable view I want to show error for a not focusable EditText. But I can not see the message. Only red icon. Somebody says I need to request the focus manually. This is how I did:
mStartDateEditText.requestFocus();
mStartDateEditText.setError("Message");

But it doesn't work.

A: In my case is similar i used a TextWatcher , e.g.:
   username.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(s.length()==0){
                    username.requestFocus();
                    username.setError("Please enter your username.");
                }else{
                    username.setError(null);
                }
            }
        });


text:
Q: How to remove first and last character of a string in Rust? I'm wondering how I can remove the first and last character of a string in Rust.
Example:
Input:
"Hello World"
Output:
"ello Worl"

A: You can use the .chars() iterator and ignore the first and last characters:
fn rem_first_and_last(value: &str) -> &str {
    let mut chars = value.chars();
    chars.next();
    chars.next_back();
    chars.as_str()
}

It returns an empty string for zero- or one-sized strings and it will handle multi-byte unicode characters correctly. See it working on the playground.

A: …or the trivial solution
also works with Unicode characters:
let mut s = "Hello World".to_string();
s.pop();      // remove last
if s.len() > 0 {
    s.remove(0);  // remove first
}

A: I did this by using string slices.
fn main() {
    let string: &str = "Hello World";
    let first_last_off: &str = &string[1..string.len() - 1];
    println!("{}", first_last_off);
}

I took all the characters in the string until the end of the string - 1.

A: You can also use split_at().
let msg = "Hello, world!";
let msg = msg.split_at(msg.len() - 1);
let msg = msg.0.split_at(1);
println!("{}", msg.1);

ello, world

split_at() returns the following: (&str, &str).


text:
Q: 2 items using same layout i want to create a layout on my items that every child in my div is aligned same height as it is in the other item div.
 i tried doing it with grid:
.textgrid { grid-row: 2; }

.profilegrid { grid-row: 1; }

.imagesgrid { grid-row: 3; }

.deletegrid { grid-row: 4; }

.gridhandler {
  display: grid;
  grid-template-rows: max-content auto min-content max-content;
}

.gridhandler is the div that is a child in the whole list.
does anybody know how i can align all the grid rows at the same height even if one of the texts is longer than one other?
regards,
Sebastian


text:
Q: AngularJS json data not showing on textarea I'm trying to query data from mongodb database and display the data on a form, following is my json response, the data will not show in textarea but if replace textarea with input field the data is showing, the following does not work
<textarea rows="15" class="form-control" ngmodel="pageContent.content"></textarea>

it works if i replace textarea with input field
<input class="form-control" type="text" ng-model="pageContent.content" />

JSON data
{
  "_id": "59f768a4f26ad23a7c6bfa3d",
  "title": "test title",
  "url": "test url",
  "content": "test content",
  "menuIndex": 4,
  "date": "2017-10-30T18:00:04.113Z",
  "__v": 0
}

View File

{{heading}}

<form role="form" id="add-page" ng-submit="savePage()">

        Page ID
        <input class="form-control" type="text" readonly ngmodel="pageContent._id" />

        Page Title
        <input class="form-control" type="text" ng-model="pageContent.title" />

        Page URL Alias
        <input class="form-control" type="text" ng-model="pageContent.url" />

        Menu Index
        <input class="form-control" type="number" ng-model="pageContent.menuIndex" />

        Page Content
        <textarea rows="15" class="form-control" ngmodel="pageContent.content"></textarea>

    <input type="submit" class="btn btn-success" value="Save">

</form>

Pages Model
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Page = new Schema({
    title: String,
    url: { type: String, index: { unique: true } },
    content: String,
    menuIndex: Number,
    date: Date
});
var Page = mongoose.model('Page', Page);
module.exports = Page;

Can someone please help me on this?

A: In some of the input you have ngmodel change them as ng-model
<input class="form-control" type="text" readonly ng-model="pageContent._id" />


text:
Q: Cordova - InAppBrowser is not getting closed in iOS with executeScript used I am trying to close inAppBrowser instance in cordova app for iOS inside executeScript callback function.
var ref=null;
ref = window.open(encodeURI(g3SSOUrl), '_blank', 'location=no');
ref.addEventListener('loadstart', activityAfterLoadStart);
ref.addEventListener('loadstop', function(event){
 ref.executeScript(
     { code: "document.body.innerHTML" },
     function( values ) {
         values=values+"";
         if(values.lastIndexOf("objectsMap")!=-1){
             var dataStr=values.split(">")[1].split("<")[0];
             console.log("values ----> "+dataStr);
             activityAfterIDPLoginSuccess(JSON.parse(dataStr));
             setTimeout(function(){
                   ref.close();
               },2000);

         }
     }
 );
});

But inAppBrowser instance is not getting closed. it works if I close inAppBrowser in normal callback functions of inAppBrowser.
Does anybody has idea about this issue?
Thanks

A: I was getting error for issue of cordova plugin,
I updated dialogs plugin now its working.
Due to that error it was not executing setTimeout command as well.


text:
Q: How to find partial derivative if given antiderivative In my book exercise I need to find $\frac{მz}{მx}$, if $F(xz,yz)=0$
I try to do it like that
$$ F'_{xz}(d(xz))+F'_{yz}(d(yz))=0 $$
$$ F'_{xz}(z+x\frac{მz}{მx})+F'_{yz}(z\frac{მy}{მx}+y\frac{მz}{მx})=0 $$
express from it $\frac{მz}{მx}$
$$ \frac{მz}{მx}=\frac{-F'_{xz}*z-F'_{yz}*z\frac{მy}{მx}}{F'_{xz}*x+F'_{yz}*y} $$
but answer in the end of the book don't have part with $\frac{მy}{მx}$

A: Write $$\frac {\partial}{\partial u}F(u,v)=F_1(u,v),\frac {\partial}{\partial v}F(u,v)=F_2(u,v).$$ The given equation defines $z$ implicitly as a function of $x$ and $y.$ By the chain rule, $$F_1(xz,yz)(z+x\frac{\partial z}{\partial x})+F_2(xz,yz)(y\frac{\partial z}{\partial x})=0.$$
$$F_1(xz,yz)z+F_1(xz,yz)x\frac{\partial z}{\partial x}+F_2(xz,yz)(y\frac{\partial z}{\partial x})=0.$$ $$(F_1(xz,yz)x+F_2(xz,yz)y)\frac{\partial z}{\partial x}=-F_1(xz,yz)z$$
$$\frac{\partial z}{\partial x}=-\frac{F_1(xz,yz)z}{F_1(xz,yz)x+F_2(xz,yz)y}$$
provided $F_1(xz,yz)x+F_2(xz,yz)y \ne 0.$


text:
Q: How to pause KafkaJS consumer and retry after sometime I'm using KafkaJS ( https://kafka.js.org ) to connect to a Kafka cluster. My consumers are responsible for processing tasks which can fail at some time and succeed after waiting for a duration (for example, 1 hour).
Before this duration, any attempt to process any task will result to another failure.
I tried to use Pause & Resume method as described at https://kafka.js.org/docs/consuming#a-name-pause-resume-a-pause-resume. However, the consumer restart immediately and keep consuming the failed task again.
How can I pause consuming messages without committing a failed one and restarting the consumer immediately?


text:
Q: How to POST long URL using AFNetworking I am hitting very long URL to the server like below URL which contains 1000 of numbers , I am getting an error :HTTP Error 404.15 - Not Found
The request filtering module is configured to deny a request where the query string is too long.  when i hit in browser . If i hit with some less number Server is replying with required results.
How can i hit the long URL using AFnetworking and handling php code , Please suggest me answer .
http://bb.trackfleet.biz/smscalling/json_array.php?contacts=+9198739443xxx:9900456xxx:+919953107xxx:9611443xxx:+919986447xxx:9986781xxx:+919901434xxx:+919686647xxx:+919036256xxx:+918197711xxx:9449800xxx:+918884420xx:

A: User getPath function of afhttpclient
    NSDictionary *params1 = [NSDictionary dictionaryWithObjectsAndKeys:
                             appdelegate.uuid, @"param",
                             nil];
    AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:
                            base_url];
    [client getPath:@"url" parameters:params1 success:^(AFHTTPRequestOperation *operation, id responseObject) {


text:
Q: Default height of div is different than computed result I have a webpage that contains a div. That webpage can only be accessed by users who have authenticated (the div contains the account/logout buttons). If the user has not authenticated, then it is simply a green bar of a fixed height. The font-size is 11pt, with padding of 0.25em on top and bottom. However, when I set the height of the div to 1.5em it is too short; by exactly 0.25em. So if I set the height of the div to 1.75em it is pixel-perfect.
Why must the height be greater than expected (1em (11pt) + 0.25em at top and bottom should be 1.5em)?
The css code I have is
#navbar
{
    clear:both;
    overflow:hidden;
    background-color: #006633;
    font-size: 11pt;
    height: 1.75em;
}

#navbarItems
{
    list-style-type: none;
    margin: 0;
    padding: 0;
    float: right;
}

.navbarItem
{
    display: block;
    float: left;
    padding: 0;
    margin: 0;
}

.navbarItemLink
{
    display:block;
    color: #ffffff;
    text-decoration: none;
    text-align: center;
    padding: 0.25em;
    font-size: 11pt;
}

and the HTML is

ACCOUNT

LOGOUT

A: Your line-height is adding extra pixels in between.
Add
line-height: 1em;

To your navbar


text:
Q: Verifying that a DataTable is sorted I am working on creating a custom database test condition in Visual Studio, and I am trying to verify a sort order.
I have no problem verifying that the rows in a DataTable are actually sorted, but I also want to verify that each sort column has at least one grouping with more than one distinct value.
I am maintaining a list of integers that define the sorted columns (negative integers indicate a descending sort order - and the absolute value of the integer is the column number).
Let me clarify.
I am writing a unit test condition that verifies a sorted DataTable.  I can verify that the row are in the correct sorted order, but I want to verify that the result set contains data that actually tests the sort.  In order words, a result set with only one row or any number of duplicate rows is indeed sorted, but that doesn't actually test the sort.
I need to verify that each level of the sort contains at least two distinct values in at least one grouping.
In the past I used a combination of SQL and .Net code and used the following set of queries to make sure there was enough data to test the sort.
SELECT TOP 1 COUNT(DISTINCT column1)
FROM table
HAVING COUNT(DISTINCT column1) > 1

SELECT TOP 1 column1, COUNT(DISTINCT column2)
FROM table
GROUP BY column1
HAVING COUNT(DISTINCT column2) > 1

SELECT TOP 1 column1, column2, COUNT(DISTINCT column3)
FROM table
GROUP BY column1, column2
HAVING COUNT(DISTINCT column3) > 1

Where I have a query for each level and all queries must return a non-empty result set in order for the unit test to pass.
My real question is how do I duplicate/convert the SQL code above to LINQ?

A: I presume you verify that it's sorted with a double loop along the lines of for (int i = 1; i < rowCount; i++) {
    for (int j = 0; j < sortColCount; j++) {
        int col = colNum(sortCols[j]);
        int d = Compare(GetValue(rows[i], col), GetValue(rows[i-1], col));
        if (d == 0) continue;
        // Insert here
        Assert(d == colDir(sortCols[j]));
    }
}
What you need to do is where I've put the comment insert a command to flag sort column d as tested (using e.g. a bool array). Then after the loop assert that each sort column is tested.

A: You could save the cost of the necessary iteration by hooking the DataTable's TableNewRow, RowChanging and RowChanged events to track/enforce whether or not the DataTable is sequenced the way you expect to be.
Otherwise, it's brute force:
foreach ( int i = 1 ; i < dt.Rows.Length ; ++i )
{
  DataRow prev = dt.Rows[i-1] ;
  DataRow curr = dt.Rows[i  ] ;

  Assert( CompareRows(prev,curr) <= 0 ) ;

}

Where CompareRows(prev,curr) returns the usual sort of comparison result: -1 for prev < curr, 0 for prev == curr and +1 for prev > curr );


text:
Q: Maintaining cookies between HTTP requests sent by Android Apps I'm building an Android app to provide the functionality of a website on android phones.
People are required to login, and they remain logged in using cookies, allowing them to do things under their own account. All the code for logging in/authentication has been done for the website, and I'm now writing an Android app to do the same thing.
My question is, if the Android app sends a HTTP request to the PHP server, and the server in return sets some cookies (to show that the user has logged on), would these cookies remain set on the Android app during all future HTTP requests to the server?
Or, do I need to work out a new authentication scheme for android, e.g passing a special token to the app on user login, and the app providing this token during all future requests to authenticate the user?

A: Once You logined in App,you should save token in SharedPrefrences.And you can use in each Http Request later.Even when app is Restart you have that token.So SharedPredPrefrence is better for that.

A: You should use the CookieManager and CookieStore To save Cookies.

CookieManager will store cookies of every incoming HTTP response into CookieStore, and retrieve cookies for every outgoing HTTP request.Expired HttpCookies should be removed from this store by themselves.

You would use this with the HttpURLConnection Class.

A: once you logged in put inside the SharedPreferences
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userName", "Rock");
editor.putString("token", "token@123");

get from the SharedPreferences
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String username = sharedPreferences.getString("userName", "");
String token = sharedPreferences.getString("token", "");


text:
Q: how do I call the function from the upper class? the class is not inherited class a{

private:
        class b* b = new b;
        int getSomeWhatValue(){

        }
};

class b{
private:
        void bFunc(){
               //I want to call an getsomewhatvalue() here
        }
};

I made the code really simply. How do I call an a's function at b? I tried to use thispointer, but didn't work :(

A: Your scenario will cause a cyclic calling (i.e. never ending loop of A creating an instance of B which in tern creates an instance of A and the loop continues), so its not permissible.
You have two options:

*

*Declare "int getSomeWhatValue()" as static, and call it through the class (instead through an instance).

*Pass a pointer to the function you want to call (int getSomeWhatValue()) and delcare the prototype somewhere outside of class A or B.


text:
Q: Is there any way that I can stop multi translation without using inline As explained in this document:
Is there still a use for inline?

So, what is the actual purpose of the inline keyword? It's simple: a
function marked inline can be defined in more than one translation
unit without violating the One Definition Rule (ODR). Imagine these
two files:

but using inline in this way has a problem as explained in this document:
https://www.ibm.com/support/knowledgecenter/en/ssw_ibm_i_71/rzarg/inline_linkage.htm

Redefining an inline function with the same name but with a different
function body is illegal; however, the compiler does not flag this as
an error, but simply generates a function body for the version defined
in the first file entered on the compilation command line, and
discards the others.

Is there a way that I can define a function in the header file and use it in multiple translations and if I accidentally redefine a function twice with two different function body, the compiler can generate an error? (assuming that all functions are inside the same namespace)
Is there any plan to have such keyword in further versions of C++
Edit
I already saw the answer that set as duplicate, but that question did not refer to issue that IBM reported on using inline functions.
The duplicate explained that now a day, inline is used for preventing multi-translation, which I also referred in my question, but there is no reference to the problem that it generates.


text:
Q: Flutter Web | Create .vcf file (vCard) and download it Flutter Web | Create .vcf file (vCard) and download it.
ive been searching for a while and reading a lot of discussion but still no clear solution. already tried searching in pub.dev and all that is available is for the IOS and Android.


text:
Q: iPhone - Automate Appstore submission Did anyone try scripting/Automating an Appstore app submission?
It will be amazing if we can save all the necessary info in a plist or a server, Click on one button to generate and Upload the App to iTunes connect.
This will be very useful if we have to develop template based Apps.
Any expert opinions/comments/samples?

A: I don't know if I'm allowed to say the specifics (as it is under NDA right now), but if you're a registered developer the latest xcode kinda has this sort of thing (as I said, no more detail than that).


text:
Q: How can I compose 3 different, simultaneous gestures in SwiftUI? Trying to compose 3 simultaneous gestures in SwiftUI, yet SwiftUI's SimultaneousGesture() only works with 2 gestures.
For example I have a basic View such as:
struct myRect: View {
    var body: some View {
        Rectangle()
            .fill(Color.red)
            .frame(width: 200, height: 200)
    }
}

And I need this view to be draggable, rotatable, and resizable.
I'm assuming I would need to use DragGesture(), RotationGesture(), and MagnificationGesture(). But I'm stuck since SimultaneousGesture() only takes in 2 gestures max. How can I get these 3 gestures to work on my View?
Edit:
I should specify that these gestures have to work simultaneously. This is exactly like the question asked here: Pinch, Pan, and Rotate Text Simultaneously like Snapchat [SWIFT 3]
However that was for UIKit. Is it possible to do this in SwiftUI?

A: Your view myRect may have clash with other views.
I test SimultaneousGesture() modifier, it works fine having three gestures by any sequence like blow:
struct myRect: View {
let rg = RotationGesture().onChanged({ a in
    print("Angle = \(a.degrees)")
})
let dg = DragGesture(minimumDistance: 1, coordinateSpace: .local).onChanged({ v in
    print("Translate = \(v.translation.width)")
})
let mg = MagnificationGesture().onChanged({ s in
    print("scale = \(s)")
})
var body: some View {
    Rectangle()
        .fill(Color.red)
        .frame(width: 200, height: 200)
        .simultaneousGesture(rg)
        .simultaneousGesture(mg)
        .simultaneousGesture(dg)
}
}

A: @Mir's answer was absolutely correct. But you could also do it the following way.
As you will see, all gestures fire simultaneously.
The real problem here is the SwiftUI 'design' choice that I would rather consider a bug.
Just try to touch the same view a second time while you are dragging and your first gesture will stop updating and even leave you dangling without an .onEnded callback. The new (second) gesture does not fire any callback at all, it's non-existent and just kills your first gesture!!! So no way to establish a decent state machine, sorry :-)
Yet another (third) touchDown spins up a correctly functioning new drag gesture, totally ignorant of the first two attempts, even if you didn't release the finger(s) from gesture one and two, and they are still on the screen ;-)
That is the reason why 2 finger gestures like rotation and magnification don't fire simultaneously with 1 finger drag gestures because the first subsequent touch after a (single finger) drag kills the whole drag gesture.
It has nothing to do with the rotation/magnification gestures per se…
_
struct ContentView: View {
@GestureState var state: DragGesture.Value?

var body: some View {

    let drag3 = DragGesture(minimumDistance: 0, coordinateSpace: .global)
        .onChanged { gesture in print("DRAG 3 - onChanged \(gesture.startLocation)") }
        .onEnded { gesture in print("DRAG 3 - onEnded \(gesture.startLocation)") }
        .updating($state) { value, _, _ in print("DRAG 3 - updating \(value.startLocation)") }

    let drag2 = DragGesture(minimumDistance: 0, coordinateSpace: .global)
        .onChanged { gesture in print("DRAG 2 - onChanged \(gesture.startLocation)") }
        .onEnded { gesture in print("DRAG 2 - onEnded \(gesture.startLocation)")}
        .updating($state) { value, _, _ in print("DRAG 2 - updating \(value.startLocation)")}
        .simultaneously(with: drag3)

    let drag1 = DragGesture(minimumDistance: 0, coordinateSpace: .global)
        .onChanged { gesture in print("DRAG 1 - onChanged \(gesture.startLocation)") }
        .onEnded { gesture in print("DRAG 1 - onEnded \(gesture.startLocation)") }
        .updating($state) { value, _, _ in print("DRAG 1 - updating \(value.startLocation)") }
        .simultaneously(with: drag2)

    HStack() {
        Rectangle()
            .fill(Color.red)
            .frame(width: 200, height: 200)
            .gesture(drag1)
        //.simultaneousGesture(drag1)
        //.simultaneousGesture(drag2)
        //.simultaneousGesture(drag3)
    }
}

}


text:
Q: how to change the color of underline of TextInputLayout? how do I change the color of underline of TextInputLayout?
I have tried to set colorControlNormal, colorControlActivated, colorControlHighLight in themes but it does not work.
I want to set the color of underline white instead of black:

A: please apply a custom theme in your text input layout
example
    <style name="MYAppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorControlNormal">#c5c5c5</item>
    <item name="colorControlActivated">@color/colorPrimary</item>
    <item name="colorControlHighlight">@color/colorPrimaryDark</item>
</style>

A: use backgroundTint .
android:backgroundTint="@color/white"

A: To change bottom line color, you can try this in your app Theme like below:
<style name="Theme.App.Base" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorControlNormal">#fffff</item>
<item name="colorControlActivated">#fffff</item>
<item name="colorControlHighlight">#fffff</item>
</style>

A: I have a style for that where I override
 <style name="FormLabel">
    <item name="colorControlNormal">@color/white</item>
    <item name="colorControlActivated">@color/white</item>
    <item name="colorControlHighlight">@color/white</item>
 </style>

and I set this style to the EditText wrapped around the TextInputLayout.

A: Try this my friend
<style name="MYAppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#FF0000</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">#FF0000</item>

A:
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">#FFFFFF</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">#FFFFFF</item>
</style>


text:
Q: npm permission issue on fresh install of Homestead / Vagrant / Laravel Two days dealing with this issue and it is winning.
I have a fresh install of Windows 10 host, running the latest versions of Vagrant, laravel/homestead (Ubuntu 18.04 LTS box, v 6.0.0), Virtualbox, laravel, git for windows, node.js for windows.
vagrant, git, virtualbox are set to run as administrator in windows.
I create a Laravel project called blog like this:
vagrant@homestead:~/src$ composer create-project --prefer-dist laravel/laravel blog

All creates OK. I then try and install npm like this:
vagrant@homestead:~/src/blog$ npm install -g npm@latest

And I get:
npm WARN checkPermissions Missing write access to /usr/lib/node_modules/npm
npm WARN checkPermissions Missing write access to /usr/lib/node_modules
npm ERR! path /usr/lib/node_modules/npm
npm ERR! code EACCES
npm ERR! errno -13
npm ERR! syscall access
npm ERR! Error: EACCES: permission denied, access '/usr/lib/node_modules/npm'
npm ERR!  { Error: EACCES: permission denied, access '/usr/lib/node_modules/npm'
npm ERR!   stack: 'Error: EACCES: permission denied, access \'/usr/lib/node_modules/npm\'',
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'access',
npm ERR!   path: '/usr/lib/node_modules/npm' }
npm ERR!
npm ERR! The operation was rejected by your operating system.
npm ERR! It is likely you do not have the permissions to access this file as the current user
npm ERR!
npm ERR! If you believe this might be a permissions issue, please double-check the
npm ERR! permissions of the file and its containing directories, or try running
npm ERR! the command again as root/Administrator (though this is not recommended).

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/vagrant/.npm/_logs/2018-05-05T00_57_41_110Z-debug.log

But when i check vagrant user permissions:
vagrant@homestead:~/src/blog$ groups
vagrant adm cdrom sudo dip www-data plugdev lxd lpadmin sambashare

So I solve this with the not recommended by npm message:
vagrant@homestead:~/src/blog$ sudo npm install -g npm@latest

I now go and install an npm package like highcharts:
vagrant@homestead:~/src/blog$ npm install --save highcharts
npm WARN rollback Rolling back highcharts@6.1.0 failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/src/blog/node_modules/highcharts/package.json.2262439515'
npm ERR! path /home/vagrant/src/blog/node_modules/highcharts/package.json.2262439515
npm ERR! code ETXTBSY
npm ERR! errno -26
npm ERR! syscall rename
npm ERR! ETXTBSY: text file is busy, rename '/home/vagrant/src/blog/node_modules/highcharts/package.json.2262439515' -> '/home/vagrant/src/blog/node_modules/highcharts/package.json'

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/vagrant/.npm/_logs/2018-05-05T01_10_24_241Z-debug.log

I try sudo to install package, same result
vagrant@homestead:~/src/blog$ sudo npm install --save --no-bin-links highcharts
npm WARN rollback Rolling back highcharts@6.1.0 failed (this is probably harmless): ETXTBSY: text file is busy, unlink '/home/vagrant/src/blog/node_modules/highcharts/package.json.1984492036'
npm ERR! path /home/vagrant/src/blog/node_modules/highcharts/package.json.1984492036
npm ERR! code ETXTBSY
npm ERR! errno -26
npm ERR! syscall rename
npm ERR! ETXTBSY: text file is busy, rename '/home/vagrant/src/blog/node_modules/highcharts/package.json.1984492036' -> '/home/vagrant/src/blog/node_modules/highcharts/package.json'

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/vagrant/.npm/_logs/2018-05-05T01_58_13_140Z-debug.log

The result is a highchatrts folder in node_modules with only the packaje.json.1984492036 file in it.
I cannot seem to find a way around this. Using --no-bin-links gives the same error.
Any help is appreciated.

A: I got it all working by running npm install from the git host os, not from the ubuntu vm. Not what I wanted but I move forward and have learned something and creeped closer to insanity...

A: I had this same issue two days ago, try running sudo npm install --unsafe-perm , undo any changes you made first though, cause i don't know how valet works (sad Linux user)


text:
Q: How does one achieve this layout with CSS?
The individual elements I have created using CSS and bootstrap standards however to get them to stack like that I do not know where to begin. Is it possible?

A: I think this code is helpful to you based on the above picture...
Please find the sample also in  CodePen

.icon {
  width:100px;
  height: 100px;
  padding: 5px;
}

.left-pane {
  height: 300px;
  background:#00b386;
}
<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

A: try this code..
http://codepen.io/anon/pen/zrdrVd

Example headline.

Example headline.

Example headline.

Example headline.

A: You'll probably want to read up some more on the possibilities of the bootstrap grid system.
That layout is achieved by creating two half-width (6 out of 12) columns, and then nesting 3 rows inside the right column. Example: https://jsfiddle.net/edjgdg2s/


text:
Q: Enable of Bluetooth with BluetoothManager is not working I'm trying to activate BLE (Bluetooth Low Energy) on an Android Phone (currently using an emulator on Android Studio). I know that I can't use Bluetooth with an emulator, but even without it I'm still having some troubles here is the code.
My main problem is where the bluetoothAdapter.isEnabled() is located. I have added the manifest.permission.BLUETOOTH for it but even after doing so I can't seem to understand where I may have made a mistake.
    // Initializes Bluetooth adapter.
       @SuppressLint("NewApi")

   public final BluetoothManager bluetoothManager = getSystemService(BluetoothManager.class);

BluetoothAdapter bluetoothAdapter = null;
if  (bluetoothManager != null)
{
    bluetoothAdapter = bluetoothManager.getAdapter();
}

if  (bluetoothAdapter != null && !bluetoothAdapter.isEnabled())
{
    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}

A: I don't really get your issue, as you do not mention, what exactly doesn't work, but I expect that bluetooth is not turning on.
So here are the official android guides from Google:
https://developer.android.com/guide/topics/connectivity/bluetooth
https://developer.android.com/guide/topics/connectivity/bluetooth-le#permissions
I think you're missing the BLUETOOTH_ADMIN, as well as the ACCESS_FINE_LOCATION permission, which is required for BLE if you're not using Device Companion Manager.
Please just follow the steps from the Links and it should work!
PS: Please have a look at correct spelling, grammar as well as on the format of the post and provide clear and concise information if you need help. It's not really easy to figure out what you need with the information provided.


text:
Q: Android получить метаданные изображения Как можно получить метаданные(время создания и размер файла) png изоражения? По возможности без подключения сторонних бибилиотек.

A: Размер файла
file.length()

Даты создания через родные классы не получить вроде. Только последнего изменения
file.lastModified()

Если сильо надо - можно хранить в дате модификации дату "создания". Когда открываете файл - запоминаете в отдельную переменную время модификации. Перед закрытием вписываете запомненную дату с помощью setLastModified


text:
Q: JAX-WS: Adding Outbound Headers to Service Call I have the following client...
@WebService(name = "MyService", targetNamespace = "http://namespace")
@SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
@XmlSeeAlso({
  ObjectFactory.class
})
public interface MyService{
  ....
}

Another class
public MyService getService(){
    URL aURL = new MyHelper().getClass().getClassLoader().getResource(myURL);
    QName qname = new QName("http://xml.othersite.net/MyService/", "MyService");
    return super.getPort(qname, MyService.class);
}

How do I set the outbound SOAP headers for the MyService object returned by the previous.

A: I have a working code that uses sun internal API. It's not good practice, but it works well.
WSBindingProvider bp = (WSBindingProvider) service;
bp.setOutboundHeaders(getHeaders());


text: Q: We have a multifield with rte and have used JSON_STORE. We are facing an issue of href getting removed when dialog is saved for the second time We have a multifield with rte and have used JSON_STORE. We are facing an issue of href getting removed when dialog is saved for the second time. First time the href value is retained but second time it's removed. Making the storage NODE_STORE resolves the issue but it's a time consuming process since there are many live pages using the component. Anyone has any other solution for this.


text:
Q: Displaying differently styled features from within a single shapefile in QGIS I am using QGIS 3.22.1. I have a single FEMA NRI shapefile layer in my project that contains many 'features' (aka columns in the attribute table). For instance, there are columns for risk of drought, hurricanes, and other natural disasters. I know how to pick off a specific feature and create a style to display it nicely on the map. But, I want to be able to apply different styles to several more of these features and then easily toggle between or even turn them on simultaneously.
In the left side layers panel, I'd like to see something that emulates this:
|_|FEMA Shapefile Layer
    |_| Drought Risk
        -> Categorized Style Classification
    |_| Hurricane Risk
        -> Categorized Style Classification
|_|Other Shapefile Layer(s)

Then I want to be able to be able to select and show Drought Risk, Hurricane Risk, or both on top of each other, hopefully with simple checkbox toggles.
Is the best way to do this to simply duplicate the layer and apply a different style to each of the copies?

A: Sometimes the simplest answer is the best one, and you already identified it.

Is the best way to do this to simply duplicate the layer and apply a different style to each of the copies?

Import the layer into the map as many times as needed using the same source and theme each layer.  A layer should generally only have one function and therefore one theme. Using the same source, will ensure that all the layers will have the most up-to-date information and each thematic layer can be easily toggled.
You can use QGIS' Content Groups organize and allow you to toggle the visibility of all layers.

A: The so called "Styles" the best solution for this. Right-click your layer and "Add..." a new Style (you can also rename the currently selected style there, e. g. from "Default" to "Drought Risk").

Then you can set up this new Style's symbology in any way you like and easily switch between them.

By using this approach you have a well setup project, these Styles can also be used in Layouts or Map Themes in a straight-forward way.

A: To define different styles based on conditions from attribute values, use styling with Rule based renderer (see docu). You can achieve (almost?) everything you could do with other methods.
You can add as many styles as you want and define for each simple or complex conditions when it should be visible. It will be still one layer only, but with many different styles.
Basic settings
In the layer panel as well as in the Layer styling, you can activate and deactivate each style by clicking the checkbox next to it: see the red arrows in the screenshot.
One layer, styled with four different styles, here based on a filter condition (Rule) based on the polygon's Name attribute - you could include other attribute fields to create complex conditions:

Use with scalar attributes: data driven override (manual)
If you have scalar attributes and want to get a graduated style based on the attribute value, you can use data driven override for any part of the style like color, fill style, stroke width, stroke style etc. Set a rule based renderer and then in the style settings, click on the data driven override icon at the right side of the setting options and click on Assistant:

Then select a source (be it an attribute field or a more complex expression), load min/max values (or enter them manually) and select a color ramp to get a graduated style.
Graduated style: solid fill with a white-to-blue color ramp, based on the attribute value (see label for the value for each feature); Storke color and stroke width (border of each polygon) similarily styled based on the same attribute:

Refine selected rules to create categorized or graduated styles (automatic)
You have even more options selecting one rule defined style by selecting one of the three options under Refine selected rules (right click rule or open it at the bottom of the panel, see screenshot). Here, you can, between elso, choose Add categories to rule or Add Ranges to rule to create a style that corresponds to Categorized or Graduated layer style rendering.
Graduated style based on the attribute value, but only for features with value > 50. I used Add ranges to rules with the expression scale_linear( value,50,100,0,100) to "spread" the color ramp (use the full spectrum of the white-to-red color scale) for values from 50 to 100:


text:
Q: How to return previous selected item in array? I created dynamic pills tabs.
And it works except for one thing.
Perhaps most important. When I remove the pills I want it back to the route that was previously opened.
I am created stackblitz example without routes page: -> https://stackblitz.com/edit/pills-tabs?file=app/app.component.html
Here is all code except router page.
Only different is in ts file 15 line of code I have routerLink="{{ tab.path }}":
 <mat-chip color="primary" selected [removable]="removable" (removed)="removeTab(fruit)" routerLink="{{ tab.path }}">   {{ tab.name }}     <mat-icon matChipRemove *ngIf="removable" class="x-icon">  ✖ </mat-icon>  </mat-chip

I want again set question.
This is work but when I remove pills I want to return previous tab. like a route navigate to previous tab. In Vue.js it is like router.go(-1)...
How to do it?

A: You can use the location service:
import { Location } from '@angular/common';

...

constructor(private _location: Location) {}

...

backToTheLastUrl() {
  this._location.back();
}


text:
Q: Conversion of CSV Files to XLSX Files using perl I'm trying to convert CSV Files to XLSX Files using perl script. While doing so, if there is any double quotes in between the field of CSV, it is getting divided and writing into two different fields in XLSX. Could you please help me in avoiding this..?
For e.g: the field is:- I'm going to meet my fried "Richard". I need to discuss a lot with him.
Above data is divided into two fields like:
1st field --> I'm going to meet my fried "Richard".
2nd field --> I need to discuss a lot with him.

Here is code:
my $aoa = csv (in => $csv_file,
               encoding => "UTF-8",
               sep_char    => ',',
               quote_char  => '"',
               allow_loose_quotes => 1,
               escape_char => undef
);

Is there any code I can add here like allow_loose_escapes => 1 to have the entire field as one. Appreciate your help.


text:
Q: Unary relationship with attributes in Barker and UML notations? I have a problem with creating database notation and it's about unary relationship with attributes, i know how to draw my database notation in chen because there u can attach attribute to relationship, but I also need to create this in Barker and UML notation, i've read that i can do it by drawing relationship with attributes as an entity but teacher said to me that i need to change it and didn't give me any tip about it(i don't know if there is a way to do so maybe i shouldn't include it in e-r barker and chen notations?), i can't find anything else on the internet or i'm blind, can someone help me with it?
Adding an image on how i made it :

So the main entity is named pojazd which means vehicle and the relationship with attribute is named jest_czterokolowcem which means is_fourwheeler and if the vehicle is a four wheeler im adding attribute which is color.
The things that I already tried is searching over internet and asking some people
I only need help or explanation on how to draw relationship with attribute in Barker and UML notation


text:
Q: Qt module (QtSerialPort) not found in Qt custom build (cross compiled for ARM) I have Qt 5.5.1 custom build (cross compiled on x86 for ARM development). So the project is building on x86 host and then deployed to Jetson TK1 development board.
I have the error:

Project ERROR: Unknown module(s) in QT: serialport

I can see build library: /home/alan/work/qt/qt-everywhere-opensource-src-5.5.1/qtserialport/lib/libQt5SerialPort.so.5.5.1, source and header files for QtSerialPort module in qt build directory. So I think the module is build but not properly installed. Never deal with custom Qt modules so how to check if module build and installed correctly?
Update: Qt was build but was not installed into OS (Qt Creator allows to use such builds to creating kits).

A: Modules only available after install. Another option - link module as separate library.


text:
Q: Unity 5.2 - Animate Sprite I am having difficulty animating a sprite in Unity.
I want the Sprites sprite(image) to change in a looping animation.
So far I have created a new animation and added the sprites to the animation timeline as shown in the image below.

As you can see above, I am also animating the colour of the sprite.The GameObject looks like this:

When the scene is run, the colour component animates as expected, however the sprite does not change.

What am I doing wrong?

A: Try manually change colour. If you don't see effect, check your shader in material. Maybe your shader haven't property Colour. You can too try change default shader.


text:
Q: Covert table dataframe to json api request in python I scrape a table on a site using pandas and get a dataframe. I only need one column of data from the dataframe that has long titles. I need to insert these titles into a json api request that looks like this:
payload = "{\n    \"campaign_id\": 1,\n    \"identifiers\": [\n        {\n            \"identifier\": \"scraped titles\",\n            \"type\": \"keyword\"\n        }\n    ]\n}"

as you can see though each, title is a nested dictionary pair. (i think that's what you'd call it). And therefore I need each title to be iterated as above: {"identifier":"Scraped Title", "type":"keyword"} for the whole table.
so what I have is data table:
Identifier
1
2
3
4
n
and what I need is
{'identifier': '1', 'type': 'keyword'}, {'identifier': '2', 'type': 'keyword'}, {'identifier': '3', 'type': 'keyword'}, {'identifier': '4', 'type': 'keyword'}, {'identifier': 'n', 'type': 'keyword'}
Thanks!

A: Try this,
items = [1, 2, 3, 4, 5...]

# list comprehension..
print([{'identifier': item, 'type': 'keyword'} for item in items])

Output
[{'identifier': 1, 'type': 'keyword'}, {'identifier': 2, 'type': 'keyword'}..]


text:
Q: How to give java enough time to assign a value to a variable? I have a loop in which at the end of the loop a String[] is added to an ArrayList(which is declared in the class not a method) and at the beginning of the loop said String[] is cleared of its contents:
String[] a = new String[2];
while(true){
  a[0] = "";
  a[1] = "";
  -----some code----

(that adds to a[0] and a[1])

  -----some code----
  //lets call our ArrayList list
  list.add(a);
}

so more often than not, what is stored on the list is an empty String. I think it is because java moves on to the next step too fast but I don't know for sure, any help please?
Here is all of my code:
static ArrayList<String[]> Names = new ArrayList<String[]>();
public static void read(BufferedReader stream){
        String[] aux = new String[2];
        char it = 2;

    try{
        while(it != (char) -1){
            aux[0] = "";
            aux[1] = "";
            it = (char) stream.read();

            while(Character.isLetter(it)){
                aux[0] += it;
                it = (char) stream.read();
            }

            it = (char) stream.read();

            while(Character.isDigit(it)){
                aux[1] += it;
                it = (char) stream.read();
            }
            Names.add(aux);
            stream.read();
        }

    }catch(IOException e){
        System.out.print("IOException(read): ");
        System.err.println(e.getMessage());
    }

}

A: When you add the array referenced by a (or aux in the second example) to your list, The variable a still refers to the string array. When you re-initialize the string array elements to empty strings you also wipe the entries in the list because they are the same data structure. You have multiple references to the same array.
You need to create a new array for each pass through the loop so that the list elements will actually contain separate arrays. Move the line initializing the array
String[] a = new String[2];

to inside the while loop. That way the array will get reallocated so that the local variable won't be pointing to the same array you previously added to the arrayList.
Here's a small test program that reproduces the problem:
import java.util.*;

public class DupeArr {
    public void testBad() {
        System.out.println("bad, multiple references to same array");
        List<String[]> list = new ArrayList<String[]>();
        String[] arr = {"a", "b"};
        for (int i = 0; i < 2; i++) {
            arr[0] = "" + i;
            arr[1] = "" + (i * 10);
            list.add(arr);
        }
        System.out.println(list.get(0)[0]);
        System.out.println(list.get(0)[1]);
        System.out.println(list.get(1)[0]);
        System.out.println(list.get(1)[1]);
        System.out.println(list.get(0)[0].equals(list.get(1)[0]));
        System.out.println(list.get(0)[1].equals(list.get(1)[1]));
        // printing true means these lists point to the same array
        System.out.println("same reference=" + (list.get(0) == list.get(1)));
    }

    public void testGood() {
        System.out.println("good, new array for each list item");
        List<String[]> list = new ArrayList<String[]>();
        for (int i = 0; i < 2; i++) {
            String[] arr = {"a", "b"};
            arr[0] = "" + i;
            arr[1] = "" + (i * 10);
            list.add(arr);
        }
        System.out.println(list.get(0)[0]);
        System.out.println(list.get(0)[1]);
        System.out.println(list.get(1)[0]);
        System.out.println(list.get(1)[1]);
        System.out.println(list.get(0)[0].equals(list.get(1)[0]));
        System.out.println(list.get(0)[1].equals(list.get(1)[1]));
        // printing false means these lists point to different arrays
        System.out.println("same reference=" + (list.get(0) == list.get(1)));
    }
    public static void main(String[] args) {
       DupeArr dupeArr = new DupeArr();
       dupeArr.testBad();
       dupeArr.testGood();
    }
}

The output for this is
bad, multiple references to same array
1
10
1
10
true
true
same reference=true
good, new array for each list item
0
0
1
10
false
false
same reference=false


text:
Q: How to clear header manager programmatically I have a TestPlan
Thread-group
 HttpSampler
  pre-processor
  HttpHeaderManager[empty]
  HttpRequestDefaults[empty]
  Post-processor

I am using a pre-processor script to add headers dynamically to headerManager from reading a json file. it goes well .
import org.apache.jmeter.protocol.http.control.Header
int min = args[0].toInteger()
int max = args[1].toInteger()
int random =  min + (int) (Math.random() * ((max - min) + 1));
// here 'inputjson' referring to slurped json object

 inputjson.Headers.each{
        it.each{    key,value -> sampler.getHeaderManager().add(new Header(key.replace('$random',random.toString()),value.replace('$random',(random+2).toString())));
               }
    }

the issue is, if a thread loop count is 3, then the set of headers are adding 3 times.
then I added a post processor script
sampler.getHeaderManager().clear()

This time initial[loop-1] run is going fine, next[loop-2] loop is a clear request with no headers. how can I achieve, each request will go with only 1 set of headers

A: Here is my working example - HeaderManager.clear() did not work, but removing the header by its name did its job.
import org.apache.jmeter.protocol.http.control.Header;
sampler.getHeaderManager().removeHeaderNamed("Authorization");
sampler.getHeaderManager().add(new Header("Authorization", "Bearer " + vars.get("token")));

A: You can use below code to remove headers programatically - first, getting the headers count and looping till the end of headers count.
int headers_size = sampler.getHeaderManager().size();
log.info("headers_size: "+ headers_size);
while(headers_size > 0) {
  log.info("header to be removed:"+ sampler.getHeaderManager().get(0));
  sampler.getHeaderManager().remove(0);
  headers_size = sampler.getHeaderManager().size();
}

A: This will done by
adding sampler.setHeaderManager(new HeaderManager()) just before the headerManger add section .
each time a new HeaderManger will get added and will be used. Not sure it is the best solution , but its a working solution.

A: Don't use the f$%$ing method HeaderManager.clear() which existence I still don't get, and do not do that in a post-processor, better do this in your preprocessor before adding headers to Header Manager.
headerMgr = sampler.getHeaderManager();
while(headerMgr.getHeaders().iterator().hasNext()) {
    headerName = headerMgr.getHeaders().iterator().next().getStringValue().split("\\s+")[0];
    headerMgr.removeHeaderNamed(headerName);
}