text:
Q: regex get by multiple separator? I want separate the sentence
hey ! there you are

to
["hey!","there you are"]

in js. now I found that
(?<=\!)

keep separator with before element.
but what if I want to use the rule to the "!!" or "!!!"?
so my goal is change to separate sentence from
hey! there!!! you are!!!!

to
["hey!","there!!!", "you are!!!!"]

but is it possible?
I tried to \(?<=!+) or \(?<=\+!) but fail.
I don't know even it possible to get !, !!..n by once

A: In addition to the elegant solution by The fourth bird, this specific requirement can be met by simply splitting on the regex, (?<=!)\s+|$ which can be explained as "One or more whitespace characters, or end of line, preceded by a !".

const regex = /(?<=!)\s+|$/;
[
  "hey! there!!! you are!!!!",
  "hey ! there you are"
].forEach(s =>
  console.log(
    s.split(regex)
    .map(s => s.replace(/\s+!/, "!").trim())
  )
);

A: Based on your needs my solution was to first get the exclamations, then get the strings (split by exclamations).
This method creates two arrays, one of exclamations and one of the strings.
Then I just loop over them, concatenate them, and push into a new array.
As a starting point it should be enough, you can always modify and built on top of this.

const str          = 'hey! there!!! you are!!!!';
const exclamations = str.match(/!+/g);
const characters   = str.split(/!+/).filter(s => s.trim());

let newArr = [];

for (i = 0; i < characters.length; i++) {
  newArr.push(characters[i].trim() + exclamations[i]);
}

console.log(newArr); // ["hey!","there!!!","you are!!!!"]

A: You could use split with 2 lookarounds, asserting ! to the left and not ! to the right. If you want to remove the leading whitespace chars before the exclamation mark you could do some sanitizing:

const regex = /(?<=!)(?!!)/g;
[
  "hey! there!!! you are!!!!",
  "hey ! there you are"
].forEach(s =>
  console.log(
    s.split(regex)
    .map(s => s.replace(/\s+!/, "!").trim())
  )
);

Another option could be to match the parts instead of splitting:
[^\s!].*?(?:!(?!!)|$)

See a regex demo.

const regex = /[^\s!].*?(?:!(?!!)|$)/g;
[
  "hey! there!!! you are!!!!",
  "hey ! there you are"
].forEach(s =>
  console.log(s.match(regex))
);

A: Here is yet another solution using a .split() and .reduce(). This does not use a lookbehind, for those concerned about Safari and other browsers not supporting it:

[
  'hey ! there you are',
  'hey! there!!! you are!!!!'
].forEach(str => {
  let result = str
  .split(/( *!+ *)/) // split and keep split pattern because of parenthesis
  .filter(Boolean)   // filter out empty items
  .reduce((acc, val, idx) => {
    if(idx % 2) {
      // !+ split pattern => combine with previous array item
      acc[acc.length - 1] += val.trim();
    } else {
      acc.push(val);
    }
    return acc;
  }, []);
  console.log(str, ' => ', result);
});

Output:
hey ! there you are  =>  [
  "hey!",
  "there you are"
]
hey! there!!! you are!!!!  =>  [
  "hey!",
  "there!!!",
  "you are!!!!"
]


text:
Q: Extending ManagedPerformanceCounter I have been trying to add my own performance counter, and I'm unable to use this performance counter for my routes.
Could anyone tell me how to use a custom performance counter instead of ManagedPerformanceCounter?
Thank you.

A: if you are looking for a JMX solution...you can register a processor and use custom APIs to retrieve stats...
http://camel.apache.org/why-is-my-processor-not-showing-up-in-jconsole.html
also, here are some notes on using JMX to retrieve route stats...
http://benoday.blogspot.com/2010/08/managing-camel-routes-with-jmx-apis.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: Double scroll sections in row I'm trying to achieve a scroll section containing a row which contains a list view and a details view. The goal is to have one scroll view that scroll both the list and the details view. From an UX perspective, both sections should always be seen, such as if one section is much larger than the other, the smaller section will always be seen.
I'm under the impression that this is the use case for NestedScrollView so ultimately what I'm after is something using it. I know it's possible to sync multiple controllers together programmatically, but I'm hoping for something simpler.
Like the following (this is just an example, my screen does not look anything like this):

The code below is where I got to. It throws an error that scrollController is used in multiple places. Another problem is that scrolling the left side till the end does not scroll the right side till the end.
Here is a full repro:
https://github.com/cedvdb/flutter_repros/tree/double_scroll
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: NestedScrollView(
        headerSliverBuilder: (context, innerBoxIsScrolled) => [
          SliverAppBar(
            title: const Text('example'),
          )
        ],
        body: Row(
          children: [
            SizedBox(
              width: 500,
              child: ListView.builder(
                itemCount: 30,
                itemBuilder: (context, index) => ListTile(
                  title: Text('tile $index'),
                ),
              ),
            ),
            const SizedBox(
              width: 20,
            ),
            Expanded(
              child: SingleChildScrollView(
                child: Column(
                  children: [
                    Container(height: 500, color: Colors.yellow),
                    Container(height: 500, color: Colors.orange),
                    Container(height: 500, color: Colors.blue),
                    Container(height: 500, color: Colors.yellow),
                  ],
                ),
              ),
            ),
            const SizedBox(
              width: 20,
            ),
          ],
        ),
      ),
    );
  }
}

A: Try this one, it works for me.
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: NestedScrollView(
        headerSliverBuilder: (context, innerBoxIsScrolled) => [
          SliverAppBar(
            title: const Text('example'),
          )
        ],
        body: SingleChildScrollView (
          child: Row(
            crossAxisAlignment : CrossAxisAlignment.start,
          children: [
            SizedBox(
              width: 500,
              child: ListView.builder(
                itemCount: 30,
                shrinkWrap: true,
                itemBuilder: (context, index) => ListTile(
                  title: Text('tile $index'),
                ),
              ),
            ),
            const SizedBox(
              width: 20,
            ),
            Expanded(
//               child: SingleChildScrollView(
                child: Column(
                  children: [
                    Container(height: 500, color: Colors.yellow),
                    Container(height: 500, color: Colors.orange),
                    Container(height: 500, color: Colors.blue),
                    Container(height: 500, color: Colors.yellow),
                  ],
//                 ),
              ),
            ),
            const SizedBox(
              width: 20,
            ),
          ],
        ),
          ),
      ),
    );
  }
}

A: So basically when you are using one scrollview with two scrollable widgets flutter can't decide how to draw the scrollbar. so if you disable scrollbar then your code will stop throwing error(if you are okay with no scrollbar it will scroll but no scrollbars will be displayed).
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      //this line added here!
      scrollBehavior: ScrollConfiguration.of(context).copyWith(scrollbars: false),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: NestedScrollView(
        headerSliverBuilder: (context, innerBoxIsScrolled) => [
          SliverAppBar(
            title: const Text('example'),
          )
        ],
        body: Row(
          children: [
            SizedBox(
              width: 500,
              child: ListView.builder(
                itemCount: 30,
                itemBuilder: (context, index) => ListTile(
                  title: Text('tile $index'),
                ),
              ),
            ),
            const SizedBox(
              width: 20,
            ),
            Expanded(
              child: SingleChildScrollView(
                child: Column(
                  children: [
                    Container(height: 500, color: Colors.yellow),
                    Container(height: 500, color: Colors.orange),
                    Container(height: 500, color: Colors.blue),
                    Container(height: 500, color: Colors.yellow),
                  ],
                ),
              ),
            ),
            const SizedBox(
              width: 20,
            ),
          ],
        ),
      ),
    );
  }
}

A: What i understood is that there are two scrolls and items from one point to items in the other and you need a method to move the second one on a event (scroll) but by the example having different size lines i asume it's some kind of cursor in a array thing; if that is what you need you only have to implement the exact movement you want, the example just scrolls to the place of the line you click
import 'package:flutter/material.dart';
import 'dart:math';

void main() => runApp(const App());

class App extends StatelessWidget {
  const App({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Page_Home(),
      ),
    );
  }
}

class List_Element {
  String title;
  String content;
  final GlobalKey _key;

  List_Element(
    this.title,
    this.content,
  ) : this._key = GlobalKey();

  GlobalKey get_key() => _key;
}

class Page_Home extends StatefulWidget {
  const Page_Home({Key? key}) : super(key: key);

  @override
  _Page_Home createState() => _Page_Home();
}

class _Page_Home extends State<Page_Home> {
  late List<List_Element> elements;
  final scroll_view = ScrollController();

  double _get_heigth(key) {
    final size = key.currentContext!.size;
    if (size != null) {
      return size.height;
    } else {
      return 0;
    }
  }

  Widget build_list(BuildContext ctx) {
    return SingleChildScrollView(
      child: Column(
        children: List<Widget>.generate(elements.length, (i) {
          return InkWell(
              onTap: () {
                double pos = 0;
                for (int e = 0; e < i; e++) {
                  pos += _get_heigth(elements[e].get_key());
                }
                scroll_view.animateTo(
                  pos,
                  duration: const Duration(seconds: 1),
                  curve: Curves.easeIn,
                );
                print("Jump $i to $pos");
              },
              child: Container(
                margin: EdgeInsets.only(top: 10),
                color: Colors.blueGrey,
                width: double.infinity,
                height: 30,
                child: Center(child: Text("Line ${elements[i].title}")),
              ));
        }),
      ),
    );
  }

  Widget build_element_view(BuildContext ctx) {
    return SingleChildScrollView(
      controller: scroll_view,
      child: Column(
        children: List<Widget>.generate(elements.length, (i) {
          return Container(
            margin: EdgeInsets.only(top: 10),
            color: Colors.blueGrey,
            width: double.infinity,
            child: Text(elements[i].content),
            key: elements[i].get_key(),
          );
        }),
      ),
    );
  }

  @override
  void dispose() {
    scroll_view.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext ctx) {
    Size vsize = MediaQuery.of(ctx).size;
    this.elements = List<List_Element>.generate(
        30,
        (i) => List_Element(
              i.toString(),
              i.toString() * Random().nextInt(300),
            ));

    return ConstrainedBox(
      constraints: BoxConstraints.tight(vsize),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          SizedBox(
            width: vsize.width * 0.4,
            height: vsize.height,
            child: this.build_list(ctx),
          ),
          SizedBox(
            width: vsize.width * 0.5,
            height: vsize.height,
            child: this.build_element_view(ctx),
          ),
        ],
      ),
    );
  }
}

A: I could not get the behavior I wanted (and I'm not even sure it makes sens anymore) so I made 2 scroll in the row:
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  ScrollController left = ScrollController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: NestedScrollView(
        headerSliverBuilder: (context, innerBoxIsScrolled) => [
          SliverAppBar.medium(
            title: const Text('example'),
          ),
        ],
        body: LayoutBuilder(builder: (context, constraints) {
          return Row(
            children: [
              Container(
                color: Colors.greenAccent,
                height: constraints.maxHeight,
                width: 400,
                child: MyListView(controller: left),
              ),
              Expanded(
                child: SingleChildScrollView(
                  child: Column(
                    children: [
                      Container(height: 500, color: Colors.yellow),
                      Container(height: 500, color: Colors.orange),
                      Container(height: 500, color: Colors.blue),
                      Container(height: 500, color: Colors.yellow),
                    ],
                  ),
                ),
              ),
            ],
          );
        }),
      ),
    );
  }
}

class MyListView extends StatelessWidget {
  final ScrollController? controller;
  const MyListView({Key? key, this.controller}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return CustomScrollView(
      controller: controller,
      slivers: [
        SliverFixedExtentList(
          itemExtent: 60,
          delegate: SliverChildBuilderDelegate(
              (context, index) => ListTile(
                    title: Text('tile $index'),
                  ),
              childCount: 30),
        ),
        const SliverToBoxAdapter(
          child: Padding(
            padding: EdgeInsets.all(8.0),
            child: Text('secon list'),
          ),
        ),
        SliverFixedExtentList(
          itemExtent: 60,
          delegate: SliverChildBuilderDelegate(
            (context, index) => ListTile(
              title: Text('tile $index'),
            ),
            childCount: 30,
          ),
        ),
      ],
    );
  }
}


text:
Q: Relation between free homotopy and in the same conjugacy class I had the following question when doing Hatcher's exercise 1.1.6.:
Question: two fundamental group $\pi_1(X,x_0)$ and $\pi_1(X,y_0)$ are isomorphic, induced by the path connecting $x_0$ and $y_0$. Does this ismorphism preserves the conjugacy classes? (assume $X$ is connected)
Hatcher's exercise could be viewed as a special case with $x_0=y_0$, which allows us to use other loops in $\pi_1(X,x_0)$ and the retraction trick. In the general cases with $x_0\neq y_0$, I'm curious whether this is still true. In some concrete examples, such as $X$ being the "figure of 8", or $X=SU(2)/\mathbb{Q}$ with $\mathbb{Q}$ being the quaternion group, I could construct loops that satisfy the statement.
In my attempt of a general proof, I got stuck at the following place.
I know how to prove that "two loops $f$ and $g$ (without common points) are freely homotopic iff there is a path $p$ connecting $x_0\in f$ and $y_0\in g$ such that $f$ is homotopic to $pgp^{-1}$". But I don't know how to show $pgp^{-1}$ and $g$ are in the same conjugacy class.
I'm not sure whether the statement is true or not. I'll be grateful if anyone can provide some hints or references.

A: Yes.
First note that a group isomorphism $\phi : \pi_1(X,x_0) \to \pi_1(X,y_0)$ is induced by any path $u$ from $x_0$ to $y_0$ via $\phi(g) = [u^{-1}] * g * [u]$. Here $*$ denotes composition of path homotopy classes. In general $\phi$ depends on the choice of $u$ (unless $X$ is simply connected), thus one should not say that $\phi$ is induced by the path connecting $x_0$ and $y_0$.
Your question is whether $\phi$ preserves the conjugacy classes. An equivalent question is whether for two loops $\gamma_i$ based at $x_0$ which are freely homotopic also the loops $u^{-1} * \gamma_i * u$ are freely homotopic. We should be aware that free homotopy of loops needs interpretation. We can regard loops $\gamma$ as pointed maps $(S^1,*) \to (X,x_0)$; then $\pi_1(X,x_0)$ consists of pointed homotopy classes of such maps. A free homotopy is then a homotopy which is not required to be basepoint-preserving.  We can also regard loops $\gamma$ as closed paths $I  \to X$ such that $\gamma(0)= \gamma(1) = x_0$; then $\pi_1(X,x_0)$ consists of their path homotopy classes. A free homotopy of closed paths (or a loop homotopy) is not required to be basepoint-preserving, but is assumed to produce a closed path at each time $t$. See the answer to Characterizing simply connected spaces for a discussion.
In the "path interpretation" it is very easy to see that each loop $\gamma$ based at $x_0$ is freely homotopic to the loop $u^{-1} * \gamma * u$ based at $y_0$ which answers your question. Explicitly we define
$$H :  I \times I \to X, H(s,t) = \begin{cases} u(t(1 - 3s)) & s\le 1/3 \\ \gamma(3s - 1) & 1/3 \le s \le 2/3 \\ u(t(3s-2)) & s \ge 2/3 \end{cases}.$$
This is a loop homotopy from $c * \gamma *c$ to $u^{-1} * \gamma * u$, where $c$ is the constant path at $x_0$. But clearly $c * \gamma *c$ and $\gamma$ are path homotopic, in particular loop homotopic.
Update:
That $\phi$ preserves conjugacy classes can easily  be seen directly (without using free homotopies). In fact, each group homomorphism $\psi : A \to B$ preserves conjugacy classes:
Let $a_1, a_2 \in A$ be conjugate in $A$, i.e. $a_2 = g^{-1}a_1g$ for some $g \in A$. Then $\psi(a_2) = \psi(g)^{-1}\psi(a_1)\psi(g)$. Hence $\psi(a_1), \psi(a_2) \in B$ are conjugate in $B$.
Now recall that $\phi$ is a group isomorphism. Therefore $\phi$ induces a bijection between conjugacy classes in $\pi_1(X,x_0)$ and conjugacy classes in $\pi_1(X,y_0)$.
However, I think it is an additional interesting information that each loop $\gamma$ based at $x_0$ is freely homotopic to the loop $u^{-1} * \gamma * u$ based at $y_0$.


text:
Q: Вывести первый элемент массива по наибольшему значению совпадений Есть массив
$feedbacks = [
    ['id' => 1023, 'user_id'=> 44393, 'msg'=> 'Comment 1', 'rate' => 5 ],
    ['id' => 1024, 'user_id'=> 22341, 'msg'=> 'Comment 2', 'rate' => 4 ],
    ['id' => 1025, 'user_id'=> 22341, 'msg'=> 'Comment 3', 'rate' => 4 ],
    ['id' => 1026, 'user_id'=> 44393, 'msg'=> 'Comment 4', 'rate' => 2 ],
    ['id' => 1027, 'user_id'=> 22341, 'msg'=> 'Comment 5', 'rate' => 3 ],
    ['id' => 1028, 'user_id'=> 75874, 'msg'=> 'Comment 6', 'rate' => 5 ],
    ['id' => 1029, 'user_id'=> 11223, 'msg'=> 'Comment 7', 'rate' => 1 ],
    ['id' => 1030, 'user_id'=> 44421, 'msg'=> 'Comment 8', 'rate' => 4 ],
]

Необходимо вывести того, кто больше всех комментариев оставил.
usort($feedbacks, "sorting");

function sorting($a, $b) {
     return $a['user_id'] == $b['user_id'];
}

Но тут первым выходит пользователь 44393, а нужен 22341 потому что кол вхождений 3 а у 44393 - 2

A: Вот так можно, если айдишник. Немного магии:
$users = array_count_values(array_column($feedbacks, 'user_id'));
  asort($users);
  end( $users);
  echo(key($users));

A:
Добавлю вариант для версии PHP <= 5.4:

$feedbacks = [
    ['id' => 1023, 'user_id'=> 44393, 'msg'=> 'Comment 1', 'rate' => 5 ],
    ['id' => 1024, 'user_id'=> 22341, 'msg'=> 'Comment 2', 'rate' => 4 ],
    ['id' => 1025, 'user_id'=> 22341, 'msg'=> 'Comment 3', 'rate' => 4 ],
    ['id' => 1026, 'user_id'=> 44393, 'msg'=> 'Comment 4', 'rate' => 2 ],
    ['id' => 1027, 'user_id'=> 22341, 'msg'=> 'Comment 5', 'rate' => 3 ],
    ['id' => 1028, 'user_id'=> 75874, 'msg'=> 'Comment 6', 'rate' => 5 ],
    ['id' => 1029, 'user_id'=> 11223, 'msg'=> 'Comment 7', 'rate' => 1 ],
    ['id' => 1030, 'user_id'=> 44421, 'msg'=> 'Comment 8', 'rate' => 4 ]
];

array_walk_recursive($feedbacks, function($v, $k) use(&$user_id) {
    $k != 'user_id' ?: $user_id[] = $v;
});
$user_id = array_count_values($user_id);
echo array_flip($user_id)[max($user_id)]; // 22341

Просмотр


text:
Q: Cannot delete flash9.ocx Some kinda voodoo, indeed.
Bought a new boot drive, and it's time to use the old drive for data. I thought I'd save some time by just wiping the unneeded system folders, instead of backing up, formatting, and restoring. Wups!
I have a single Adobe file that absolutely will not be deleted. G:\Windows\SysWOW64\Macromed\Flash\flash9.ocx - though it may have started with a different file name. I'm able to rename it, oddly enough.
To be clear, the drive is currently plugged in externally. So I can boot the computer, plug this drive in afterward, and immediately attempt to delete. "File in use" box reads "the action can't be completed because the file is open in another program".
I'd format at this point, but it's my white whale, and I have to know if Adobe has inserted some nasty little registry hack - or whatever it is - making this impossible.
Since I'm sure it'll come up, I've taken ownership of the file - and this was the trick preventing me from deleting anything else on the drive - full rights on the file permissions, you name it, I've fiddled with the file itself.
I'm about to try uninstalling flash from the system drive, in case that aligns the planets properly. Sometimes I wish I were less stubborn, and could just format already.

A: As it turns out, there were a couple of explicit "deny" permissions in the box. I'd forgotten that those override the "allow"s. Got rid of those and I was able to delete the file without a problem. Kind of embarrassing that I didn't see them before!

A: Look for Unlocker 1.9.1 , a nice little utility to delete files that don't want to be deleted....usually constantly running in memory and not doing anything useful anyways.

A: Kara's answer is correct. Adobe stuck two deny ACEs on the files:
DENY  Everyone         Write Attributes
DENY  ANONYMOUS LOGIN  Write Attributes

removing the first of these allows the file to be deleted. The second doesn't matter in this case.

A: I cannot confirm this, but every now and then, when I try to delete a user profile, Windows will not let me delete the user.dat registry file, saying it is in use. I know that it is not, but I have always thought that it was just because the name was the same as the one in use for the current user, which is from a different location. I tend to think this is a similar situation.
I would just format the drive and be done with it. If you really have doubts, you can search the registry for:
G:\Windows\SysWOW64\Macromed\Flash\flash9.ocx

A: .ocx files are like .dll's in that they are components used by other programs.  So if that other program is open it is likely considered "in use" by Windows.
If you have Internet Explorer or another browser open, that could be a cause.  Internet Explorer is itself made up of a number of "COM" components and it's possible another program is using such a component which is loaded that particular .ocx.  Seems silly, and it'd be nice if you could easily find which components belong to which program and which are currently active, but that's Windows.
(Edit: after reading your question more carefully, I don't think this is related to your issue.  It's likely a permissions issue.  Anyway the following still applies...)
You might be able to delete it from Safe mode.  You defintely could delete it by booting a Linux live CD or Windows PE CD and deleting it from there.
Since the registry, particularly the user.dat part of it. comprises a user's account settings, you can be sure it's open and "in use" as long as you are logged in.  For some reason it tends to stay opened after you logged off most of the time (likely by a program forgetting to close it before that program terminates).  You can kill it by rebooting, logging in to another administrator account, and deleting it without logging in to that account.

A: In addition to removing the deny permissions, I found I had to change the ownership properties.
Right click on the file or folder in question
Choose 'Properties'
Click on the Security tab
Click on 'Edit'
If 'everyone' is not present Click on 'Add'
Type 'everyone' (without quotes) and press OK

In the lower part of the dialog, choose 'Full Control' and then press OK

Try deleting again.

Edit:
Also, sometimes it is necessary to do this process with the parent folders containing the files in question.

A: 1. iObitUnlocker
I buy new hard disk. Old hard disk I begin to use for backups my data. I manually remove some data from my old hard disk, but some folders not delete due to files with .ocx extension.
I can not delete my .ocx files use LockHunter and Unlocker programs.
But free iObitUnlocker program delete .ocx files. I need press select file → press Context_Menu → iObitUnlocker → Left_Click to arrow down near Unlock button → Unlock & Delete → OK.

2. Demonstration

A: Go into the file properties. Go into security, users. Don't click on the "Deny" Checkbox, but "REMOVE" the special permissions that deny access.  Apply changes, THEN you can easily delete the file.

A: start cmd as an admin .
first we delete "ANONYMOUS LOGIN" who take control of the file .
second we give full access to "anyone" to the file.
third we delete flash folder  and all files in it .
and wrote in it like this :
 cacls C:\Windows\System32\Macromed\Flash /e /r "ANONYMOUS LOGIN"
  cacls C:\Windows\System32\Macromed\Flash /e /p "Everyone":f
  rd  <C:\Windows\System32\Macromed\Flash /s /q


text:
Q: Dump a Table from MySQL Database directly from sql server using bash How can I dump a table from a MySQL database using a bash script?
Like we can use the below command to dump a table
mysql -u username -p database_name > file.sql

But how can I dump only a single table from a database?
Can someone please help me for the same?

A: Very simple
#!/bin/bash
mysqldump -uUSERNAME -pPASSWORD DBNAME MYTABLE > DBNAME-MYTABLE.sql

For backup purposes you might want to add a date like this:
#!/bin/bash
cur=`date +"%Y-%m-%d"`
mysqldump -uUSERNAME -pPASSWORD DBNAME MYTABLE > DBNAME-MYTABLE-${cur}.sql


text:
Q: Netbeans CLose JFrame After Creating I Want to CLose JFrame after creating it.
(not with button).
but on Constructor
public class ClientSideForm extends javax.swing.JFrame {

    LocalInformation li = new LocalInformation();
    ClientSetting cs = new ClientSetting();

    public ClientSideForm() throws UnknownHostException {
        initComponents();

        setLocalInfo();
        setDefault();

        try {
            if (!StartApp()) {
                JOptionPane.showMessageDialog(rootPane, "Terjadi Kesalahan Dalam Membuka Aplikasi Utama", "Kesalahan", JOptionPane.ERROR_MESSAGE);
            } else {

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        this.dispose();
    }
}

If I implemented on button it work perfectly
But I want to close this JFrame after creating it.
Thanks

A:
I Want to CLose JFrame after creating it.
  (not with button).
  but on Constructor

No. You don't. You do not want to attempt to display a Swing GUI object and then close it before it has been fully constructed. What I think you want to do (your question is not fully clear on this) is to display the window, display a JOptionPane, and then close the GUI window. If so, you want to do this in the code that calls the GUI object's constructor, not within the constructor, so that you're dealing with a fully realized object. So for example, something like:
ClientSideForm clientForm = new ClientSideForm();
clientForm.setVisible(true);
JOptionPane.showMessageDialog(rootPane, "Terjadi Kesalahan Dalam Membuka Aplikasi Utama",
        "Kesalahan", JOptionPane.ERROR_MESSAGE);
clientForm.dispose();

Side notes:

*

*The button works because even though it is created in a method called by the ClientSideForm constructor, and even though its ActionListener has likely been attached in this same part of your code, it does not perform its actions within the constructor but only afterwards, after the ClientSideForm object has been fully created and displayed, when the button press stimulates its ActionListener's action.

*If your GUI has several JFrames that are displayed and then go away, consider revising the structure that is more user friendly, since most users don't want a bunch of windows pushed to them. Please have a look at The Use of Multiple JFrames, Good/Bad Practice? to see why this is important and to see the alternatives that are available.

*If you want to GUI to be displayed for a set period of time, and then closed, use a Swing Timer for this.

*You are potentially painting yourself in a corner by having your class extend JFrame, forcing you to create and display JFrames, when often more flexibility is called for. In fact, I would venture that most of the Swing GUI code that I've created and that I've seen does not extend JFrame, and in fact it is rare that you'll ever want to do this. More commonly your GUI classes will be geared towards creating JPanels, which can then be placed into JFrames or JDialogs, or JTabbedPanes, or swapped via CardLayouts, wherever needed. This will greatly increase the flexibility of your GUI coding.

For example, the following code will show a GUI, and half of the time, will show a JOptionPane error message, and then close the GUI after the error message has been closed, and the other half of the time will show the GUI for 2 seconds and then close it automatically:
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

@SuppressWarnings("serial")
public class TestPanel extends JPanel {
    private static final int PREF_W = 500;
    private static final int PREF_H = 400;
    private static final int TIMER_DELAY = 2 * 1000; // 2 seconds

    public TestPanel() {
        JLabel label = new JLabel("Test GUI");
        label.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 100));

        setPreferredSize(new Dimension(PREF_W, PREF_H));
        setLayout(new GridBagLayout());
        add(label);
    }

    // this code is called from a main method, but could be called anywhere, from
    // a JButton's action listener perhaps. If so, then I'd probably not create
    // a new JFrame but rather a JDialog, and place my TestPanel within it
    private static void createAndShowGui() {
        TestPanel mainPanel = new TestPanel();

        JFrame frame = new JFrame("Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        if (Math.random() > 0.5) {
            // 50% chance of this happening
            String message = "Error In Opening Main App";
            int type = JOptionPane.ERROR_MESSAGE;
            JOptionPane.showMessageDialog(frame, message, "Error", type);
            frame.dispose();
        } else {
            // run timer
            new Timer(TIMER_DELAY, new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    frame.dispose();  // dispose gui when time's up
                    ((Timer) e.getSource()).stop();  // and stop the timer
                }

            }).start();
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }

}


text:
Q: How to figure out which wireless driver I need? I posted this question on SuperUser and was told to look up the specs for [my] specific wireless card and see if there is a Linux driver for it.... Essentially I have an issue with my wireless configuration and it could be because of a bad or non-existent driver for my wireless card.
I'm new to Ubuntu (I have 12.04 installed) and can't seem to find the exact model of my wireless card, and similarly, which driver I need for it. I tried running lsmod but couldn't decipher if what I need is already loaded.
So I ask: how can I tell what device driver is needed to support the wireless card that my laptop shipped with? Thanks in advance!
Update:
Running lspci -nn | grep 0280 produces the following output:

02:00.0 Network controller [0280]: Broadcom Corporation BCM43228 802.11a/b/g/n [14e4:4359]

Searching these forums for the 14e4:4359 driver, I found this post which seems to be very similar to the problem that I am having. However, seeing that my question is concerned with 12.04, and the other question is with 12.10, and seeing that the other question is not the exactly the same scenario as what I'm describing, is more than 3 months old, and was never definitively answered, I argue that this is not a duplicate!
Like that other question, running sudo iwconfig produces the following output on my machine:
lo        no wireless extensions.
eth0      no wireless extensions.
tun0      no wireless extensions.

Running sudo modprobe wl produces:

FATAL: Module wl not found.

Running dmesg | grep wl produces:

[    2.232664] ACPI Error: [EABF] Namespace lookup failure, AE_ALREADY_EXISTS (20110623/dswload2-316)

A: Please open a terminal and run:
lspci -nn | grep 0280

Find the eight-digit PCI.ID for your wireless device and search this forum or ubuntuforums.org for the PCI.ID and you will find out what driver is required. If you get stuck, post it here and we'll help. Here is a sample from my machine:
Intel Corporation Centrino Advanced-N 6200 [8086:4239]

In my example above, a search for 8086:4239 suggests the driver is iwlwifi.


text:
Q: App background refresh ios9 swift I've been developing an app that uses location services for iOS with swift.  It's been excellent until ios9.  For some reason my app stops running when put in the background, but only on the physical device.  The simulator runs fine in the background.  I am logging stuff via NSLog so I can tell it stops on the device versus the sim.
Yes I have the info.plist set.  Yes I have background capabilities turned on.  This really did work in iOS8 but for some reason with 9 the app stops executing in the background.
I have background refresh turned on in the settings, and my app is set to always request location updates, which is also turned on in the phone's settings.
I am at a bit of a loss as to why this is happening is so I am guessing there may have been some code changes with xcode7 and/or ios9 that I need to implement.
Any help is very much appreciated!!!
Rob

A: So it appears Apple requires a new thing in iOS9 :
allowsBackgroundLocationUpdates = true

This is for the location manager.
My final code looks like :
    // this is needed for ios9 to get the location even when it's backgrounded
    if #available(iOS 9.0, *) {
        self.locationManager.allowsBackgroundLocationUpdates = true
    } else {
        // Fallback on earlier versions
    }


text:
Q: Using Interlocked.CompareExchange to increment a counter until a value I need to increment a counter until it reaches a particular number. I can use two parallel task to increment the number. Instead of using a lock to check if the number has not reach the maximum allowed value and then incrementing, I thought using Interlocked.CompareExchange in the following manner:
public class CompareExchangeStrategy
{
  private int _counter = 0;
   private int _max;

public CompareExchangeStrategy(int max)
{
    _max = max;
}

public void Increment()
{
    Task task1 = new Task(new Action(DoWork));
    Task task2 = new Task(new Action(DoWork));
    task1.Start();
    task2.Start();
    Task[] tasks = new Task[2] { task1, task2 };
    Task.WaitAll(tasks);

}

private void DoWork()
{
    while (true)
    {
        int initial = _counter;
        if (initial >= _max)
        {
            break;
        }
        int computed = initial + 1;
        Interlocked.CompareExchange(ref _counter, computed, initial);
    }
}

 }

This code is taking more to execute (for _max= 1,000,000) than the lock approach:
public class LockStrategy
{
    private int _counter = 0;
    private int _max;

    public LockStrategy(int max)
    {
        _max = max;
    }

    public void Increment()
    {
        Task task1 = new Task(new Action(DoWork));
        Task task2 = new Task(new Action(DoWork));
        task1.Start();
        task2.Start();
        Task[] tasks = new Task[2] { task1, task2 };
        Task.WaitAll(tasks);

    }

    private void DoWork()
    {
        while (true)
            {
                lock (_lockObject)
                {
                    if (_counter < _max)
                    {
                        _counter++;
                    }
                    else
                    {
                        break;
                    }
                }
            }
    }

   }

There might be a problem with the way I am using Interlocked.CompareExchange but I have not been able to figure out. Is there a better way to perform the above logic without using lock (aka Interlocked methods)?

Update

I was able to come with a version which performs as good as the lock version (for iterations = 1,000,000 and better for > 1,000,000 iterations).

    SpinWait spinwait = new SpinWait();
    int lock =0;
                while(true)
                {

                    if (Interlocked.CompareExchange(ref lock, 1, 0) != 1)
                    {

                        if (_counter < _max)
                        {
                            _counter++;
                            Interlocked.Exchange(ref lock, 0);
                        }
                        else
                        {
                            Interlocked.Exchange(ref lock, 0);
                            break;
                        }

                    }
                    else
                    {
                        spinwait.SpinOnce();
                    }
                }

The difference is made by the spin. If the task is unable to increment the variable on first go it spins providing an opportunity for task 2 to progress further instead of performing a busy spin wait.
I suspect lock pretty much does the same, it could employ a strategy to spin and allow the thread currently owning the lock to execute.

A: The problem here is that you are actually doing a lot more work in the Interlocked version - by which I mean more iterations. This is because a lot of the time the CompareExchange isn't doing anything, because the value was changed by the other thread. You can see this by adding a total to each loop:
    int total = 0;
    while (true)
    {
        int initial = Thread.VolatileRead(ref _counter);
        if (initial >= _max)
        {
            break;
        }
        int computed = initial + 1;
        Interlocked.CompareExchange(ref _counter, computed, initial);
        total++;
    }
    Console.WriteLine(total);

(note I also added a VolatileRead to ensure _counter isn't held in a register)
I get much more than iterations (via total) that you might expect here. The point is that when using Interlocked in this way, you need to add a strategy for what happens if the value changed, i.e. a retry strategy.
For example, a crude retry strategy might be:
    while (true)
    {
        int initial = Thread.VolatileRead(ref _counter);
        if (initial >= _max)
        {
            break;
        }
        int computed = initial + 1;
        if (Interlocked.CompareExchange(ref _counter, computed, initial)
                          != initial) continue;
        total++;
    }

which is to say: keep retrying until you make it work - any "doing" code would only happen after that check (where the total++ line is currently). This, however, makes the code more expensive.
If lock is cheaper: use lock. There's nothing wrong with lock, and indeed it is very optimized internally. Lock-free is not automatically the same as "fastest" or indeed "simplest".

A: I've managed to achieve almost the same performance as lockstrategy using the following code:
public class CompareExchangeStrategy {
        volatile private int _counter = 0;
        private int _max;

        public CompareExchangeStrategy(int max) {
            _max = max;
        }

        public void Increment() {
            Task task1 = new Task(new Action(DoWork));
            Task task2 = new Task(new Action(DoWork));
            task1.Start();
            task2.Start();
            Task[] tasks = new Task[2] { task1, task2 };
            Task.WaitAll(tasks);

        }

        private void DoWork() {
            while(true) {
                if(Interlocked.Add(ref _counter, 1) >= _max)
                    break;
            }
        }
    }


text:
Q: Count the number of Occurences of duplicates R Code I need a line of code that will search a vector of numbers and return the number of occurrences.  For Example
a=c(15,32,27, 63, 15,99, 32,32)

dup=unique(a[duplicated(V.Ints)])
len=length(unique(duplicated(dup)))

I get:
> dup
#[1] 15, 32

> len
#[1] 2

but what I need is:
> dup
#[1] 15, 32

> len
#[1] 5

Thank you!

A: Arun's suggestion in the comments is the way to go:
> sum(a %in% c(15,32))
#[1] 5

For more general usage:
sum(a %in% unique(a[duplicated(a)]))

Or a one-liner in the spirit of Mr Flick's approach:
sum(a %in% names(which(table(a) > 1)))

A: You can count frequencies with
table(a)
# a
# 15 27 32 63 99
#  2  1  3  1  1

You can filter to find only the duplicates
Filter(function(x) x>1, table(a))
# a
# 15 32
#  2  3
names(Filter(function(x) x>1, table(a)))
# [1] "15" "32"

and you can take the sum to find the total length of duplicates
sum(Filter(function(x) x>1, table(a)))
# [1] 5

A: Another variation is to grab all the duplicated values then use length() for len and unique() for dup
x <- a[duplicated(a) | duplicated(a, fromLast=TRUE)]

length(x)
# [1] 5
unique(x)
# [1] 15 32


text:
Q: Upper bounds on phase space momenta Suppose I wish to calculate the phase space volume for the process $\overline{X}X \to A_1 A_2 A_3 A_4 A_5$ in the CM frame of $\overline{X}, X$ so that $\sqrt{s} = 2m_X$. The volume is given by
$$
V \propto
\int d^3 p_1
\int d^3 p_2
\int d^3 p_3
\int d^3 p_4
\int d^3 p_5
\frac{1}{E_1}  \frac{1}{E_2} \frac{1}{E_3} \frac{1}{E_4}  \frac{1}{E_5}
\delta[2m_X - (\sum_{f=1}^5 E_f)]\ \delta^{(3)}(\sum_{f=1}^5 \mathbf{p}_f).
$$
Define $\mathbf{P} = \sum_{f=1}^5 \mathbf{p}_i$. Integrating out the 3D delta function we obtain
$$
 V= (2\pi)
\int d^3 p_1
\int d^3 p_2
\int d^3 p_3
\int d p_4 d(\cos\theta_{34})
\frac{1}{E_1}  \frac{1}{E_2} \frac{1}{E_3} \frac{p_4^2}{E_4}  \frac{1}{E_5(\mathbf{P} = 0)}
\frac{\delta(\cos\theta_{34} -z_0)}{|\partial_{\cos\theta_{34}} E_5(\mathbf{P}=0)|_{z_0} }
$$
where $\cos\theta_{34} := \mathbf{p_3\cdot p_4}/p_3p_4$ and $z_0$ is the value of $\cos\theta_{34}$ such that
$$2m_X - E_1 - E_2 - E_3 -E_4 - E_5(\mathbf{P}=0) = 0$$
and the factor of $1/{|\partial_{\cos\theta_{34}} E_5(\mathbf{P}=0)|_{z_0} }$ is just the Jacobian we pick up from the identity
$$
\delta(g(x)) = \sum_{x_0}\frac{\delta(x-x_0)}{|g'(x_0)|}
$$

Now, after integrating out the delta function we must enforce the fact that the integral is to be $0$ whenever $|z_0|>1$. This amounts to forcing the conservation of energy on the integrand.
Define the region as phase space $\Xi$ as
$$
\Xi(p_1, p_2, p_3, p_4, \cos\theta_{14}, \cos\theta_{12}, \cos\theta_{23}) = \begin{cases} 1 \ \ , \ \  -1 \leq z_0 \leq 1 \\
0 \ \ , \ \ \text{otherwise}
\end{cases}
$$
Therefore, an equivalent expression for the phase space volume $V$ is given by
\begin{align}
V &= (2\pi)
{\int_{\mathbb{R}^3} d^3 p_1
\int_{\mathbb{R}^3}  d^3 p_2
\int_{\mathbb{R}^3}  d^3 p_3
\int_0^\infty d p_4 }\\
& \Xi \cdot \frac{1}{E_1}  \frac{1}{E_2} \frac{1}{E_3} \frac{p_4^2}{E_4}  \frac{1}{E_5(\mathbf{P} = 0)_{z_0}}
\frac{1}{|\partial_{\cos\theta_{34}} E_5(\mathbf{P}=0)|_{z_0} }.
\end{align}

Doing this integral numerically proves to be very difficult since I need to integrate over all of the space. Hence every numerical integration scheme will be fooled into thinking this is zero since it doesn't know that all the action is happening in the regions where $\Xi =1$.
Question: Is there a finite upper bound on the limit of integration with respect to $dp_i$, such that I may entirely cover the region $\Xi = 1$?
My Conjecture: My reasoning is that, yes, after enforcing conservation of energy via the $1D$-energy delta function the momenta $p_i$ are bound above by $p_i^{max} \leq \sqrt{(2 m_X )^2 - m_i^2}$. This leads me to propose the following conjecture that
\begin{align}
\frac{dV}{d\Omega_1 d\Omega_2 d\Omega_3} &= (2\pi)
{\int_0^{p_1^{max}} d p_1
\int_0^{p_2^{max}} d p_2
\int_0^{p_3^{max}} d p_3
\int_0^{p_4^{max}} d p_4 }\\
& \Xi \cdot \frac{p_1^2}{E_1}  \frac{p_2^2}{E_2} \frac{p_3^2}{E_3} \frac{p_4^2}{E_4}  \frac{1}{E_5(\mathbf{P} = 0)_{z_0}}
\frac{ 1}{|\partial_{\cos\theta_{34}} E_5(\mathbf{P}=0)|_{z_0} }.
\end{align}


text:
Q: How to read Jenkins credentials at Folder level I am trying to migrate credentials from Jenkins to another credentials store.
I want to read the credentials from the Jenkins store, and have found this script (https://github.com/tkrzeminski/jenkins-groovy-scripts/blob/master/show-all-credentials.groovy
The script does the job OK for SystemCredentialsProvider credentials for the global domain at root level.
But my credentials are stored in a Folder, so the script does not work for me.
I am using the Jenkins script console to execute the script.
If I navigate to the Jenkins Credentials configuration page and hover over the icon for one of my credential entries, the tooltip says "Folder Credentials Provider".
====================================================
Question: How do I read all of the the credentials from a Folder in Jenkins?
====================================================
Please see script, below:
import jenkins.model.*
import com.cloudbees.plugins.credentials.*
import com.cloudbees.plugins.credentials.impl.*
import com.cloudbees.plugins.credentials.domains.*
import com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey
import com.cloudbees.jenkins.plugins.awscredentials.AWSCredentialsImpl
import org.jenkinsci.plugins.plaincredentials.StringCredentials
import org.jenkinsci.plugins.plaincredentials.impl.FileCredentialsImpl

def showRow = { credentialType, secretId, username = null, password = null, description = null ->
  println("${credentialType} : ".padLeft(20) + secretId?.padRight(38)+" | " +username?.padRight(20)+" | " +password?.padRight(40) + " | " +description)
}

// set Credentials domain name (null means is it global)
domainName = null

credentialsStore = Jenkins.instance.getExtensionList('com.cloudbees.plugins.credentials.SystemCredentialsProvider')[0]?.getStore()
domain = new Domain(domainName, null, Collections.<DomainSpecification>emptyList())

credentialsStore?.getCredentials(domain).each{
  if(it instanceof UsernamePasswordCredentialsImpl)
    showRow("user/password", it.id, it.username, it.password?.getPlainText(), it.description)
  else if(it instanceof BasicSSHUserPrivateKey)
    showRow("ssh priv key", it.id, it.passphrase?.getPlainText(), it.privateKeySource?.getPrivateKey(), it.description)
  else if(it instanceof AWSCredentialsImpl)
    showRow("aws", it.id, it.accessKey, it.secretKey?.getPlainText(), it.description)
  else if(it instanceof StringCredentials)
    showRow("secret text", it.id, it.secret?.getPlainText(), '', it.description)
  else if(it instanceof FileCredentialsImpl)
    showRow("secret file", it.id, it.content?.text, '', it.description)
  else
    showRow("something else", it.id, '', '', '')
}

return

A: i simply created a Java class to retrieve the credentials from either global or folder scope:
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials;
import com.cloudbees.hudson.plugins.folder.Folder

class JenkinsCredentials
{
    /**
    * this method gets a 'StandardUsernamePasswordCredentials' for a userName, the 'StandardUsernamePasswordCredentials' object
    * have 2 fields - user and password, which can be used to login to other systems,
    * the username is searched for first in the global jenkins level, and if not found then it is searched at the folder level
     */
    public static StandardUsernamePasswordCredentials getCredentialsByUsername(String userName, String fromFolder) throws Exception
    {
        List credsList = CredentialsProvider.lookupCredentials(StandardUsernamePasswordCredentials.class, Jenkins.getInstance());
        if(credsList == null || credsList.size() == 0)
        {
            credsList = getFolderLevelCredentialsList(fromFolder);
        }
        return credsList.findResult { it.username == userName ? it : null };
    }

    /**
    * this method gets a 'StandardUsernamePasswordCredentials' for a userID, the 'StandardUsernamePasswordCredentials' object
    * have 2 fields - user and password, which can be used to login to other systems,
    * the userID is searched for first in the global jenkins level, and if not found then it is searched at the folder level
     */
    public static StandardUsernamePasswordCredentials getCredentialsByID(String userID, String fromFolder) throws Exception
    {
        List credsList = CredentialsProvider.lookupCredentials(StandardUsernamePasswordCredentials.class, Jenkins.getInstance());
        if(credsList == null || credsList.size() == 0)
        {
            credsList = getFolderLevelCredentialsList(fromFolder);
        }
        return credsList.findResult { it.id == userID ? it : null };
    }

    /**
    * this method gets a 'StandardUsernamePasswordCredentials' for a userName, the 'StandardUsernamePasswordCredentials' object
    * have 2 fields - user and password, which can be used to login to other systems,
    * the username is searched for at the folder level who's name we provided as 'fromFolder'
     */
    public static StandardUsernamePasswordCredentials getFolderCredentialsByUsername(String userName, String fromFolder) throws Exception
    {
        List credsList = getFolderLevelCredentialsList(fromFolder);
        return credsList.findResult { it.username == userName ? it : null };
    }

    /**
    * this method gets a 'StandardUsernamePasswordCredentials' for a userID, the 'StandardUsernamePasswordCredentials' object
    * have 2 fields - user and password, which can be used to login to other systems,
    * the userID is searched for at the folder level who's name we provided as 'fromFolder'
    */
    public static StandardUsernamePasswordCredentials getFolderCredentialsByID(String userID, String fromFolder) throws Exception
    {
        List credsList = getFolderLevelCredentialsList(fromFolder);
        return credsList.findResult { it.id == userID ? it : null };
    }

    /**
    * this method gets a list of credentials set at a folder level, the method receives the folder name to get the credentials from
     */
    public static List getFolderLevelCredentialsList(String folderName)
    {
        return CredentialsProvider.lookupCredentials(StandardUsernamePasswordCredentials.class, getFolderItem(folderName));
    }

    /**
    * this method fetch a 'Folder' item from jenkins instance by a folder name
    * it then can be used in the other methods to search for a user credentials at that folder level
     */
    public static Folder getFolderItem(String folderName)
    {
        def allJenkinsItems = Jenkins.getInstance().getItems();
        for (currentJenkinsItem in allJenkinsItems)
        {
            if(currentJenkinsItem instanceof Folder)
            {
                if(((Folder)currentJenkinsItem).getFullName().contains(folderName))
                {
                    return (Folder)currentJenkinsItem;
                }
            }
        }

    }
}

then you can use it like this:
get credentials for userName 'shay bc' from folder named 'MyJenkinsFolder':
// get the credentials
StandardUsernamePasswordCredentials shaybcCredentials = JenkinsCredentials.getFolderCredentialsByUsername("shay bc", "MyJenkinsFolder")

// login to some system using the credentials
sshSession.login(shaybcCredentials.getUsername(), shaybcCredentials.getPassword())

get credentials for userID 'sbc' from folder named 'MyJenkinsFolder':
// get the credentials
StandardUsernamePasswordCredentials sbcCredentials = JenkinsCredentials.getFolderCredentialsByID("sbc", "MyJenkinsFolder")

// login to some system using the credentials
sshSession.login(sbcCredentials.getUsername(), sbcCredentials.getPassword())

A: The class shared by @Shaybc was most of the solution, and although a commenter suggested it was not a complete solution by itself, I was able to guess how to implement it correctly into such a complete solution in my own Groovy script.
The Folder returned by JenkinsCredentials.getFolderItem('foldername') is taking the same string slug as your folder is addressed by in Jenkins. So if you have a folder with a descriptive name, and a slug, like "Folder Name" and "foldername", the right string to use to retrieve the folder itself is "foldername".
The example provided here shows how to retrieve credentials from the global store, this is Jenkins.instance – for complete documentation the script they provide is copied here:
import jenkins.*
import jenkins.model.*
import hudson.*
import hudson.model.*
def jenkinsCredentials = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
        com.cloudbees.plugins.credentials.Credentials.class,
        Jenkins.instance,
        null,
        null
);
for (creds in jenkinsCredentials) {
    println(jenkinsCredentials.id)
    }

So, start your script by defining class JenkinsCredentials as @Shaybc described, then instead of calling CredentialsProvider.lookupCredentials with Jenkins.instance, retrieve the folder and pass it in there instead.
My folder was called "ft" and (skipping over the import/boilerplate at the top and the definition of JenkinsCredentials helper class,) the remainder of my invocation in the Groovy script looked like:
def folder = JenkinsCredentials.getFolderItem('ft');

def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
        com.cloudbees.plugins.credentials.Credentials.class,
        folder,
        null,
        null
);
for (c in creds) {
    println(c.id + ": " + c.description)
}

Hope this helped someone! and by the way, if your credentials are stored in a file instead of a string, you have one more step... the file will not have any useful content in the "description" attribute, you need the byte stream stored at c.getContent()
So, that final loop with some metaprogramming to dynamically check for the availability of a getContent() method to call:
for (c in creds) {
 if (c.metaClass.respondsTo(c, 'getContent')) {
  println(
   IOUtils.toString(c.getContent(), StandardCharsets.UTF_8)
  )
 }
 println(c.id + ": " + c.description)
}

That last part was borrowed from this answer, which shows as well how you can import StandardCharsets and IOUtils: https://stackoverflow.com/a/42360792/661659

A: Just to add to this really awesome class from @Shaybc... If you're like me and have nested folders, you'll want to change up the Class method getFolderItem to recurse into all of the "sub-folders"... Otherwise you'll only ever get a return/hit on the top-level (root) Jenkins items.
Here's what that looks like, replacing the getFolderItem method and adding a getFolderItemRecursively method to do the work.
private static Folder getFolderItemRecursively(Folder folder, String folderName) {
    for (nestedItem in folder.getItems()) {
        if (nestedItem instanceof Folder) {
            if(nestedItem.getFullName().contains(folderName)) {
                return nestedItem;
            } else {
                def recurse = getFolderItemRecursively(nestedItem, folderName);
                if (recurse instanceof Folder) {
                    return recurse;
                }
            }
        }
    }
}
public static Folder getFolderItem(String folderName)
{
    for (item in Jenkins.getInstance().getItems())
    {
        if(item instanceof Folder)
        {
            if(item.getFullName().contains(folderName))
            {
                return item;
            } else {
                def recurse = getFolderItemRecursively(item, folderName);
                if (recurse instanceof Folder) {
                    return recurse;
                }
            }
        }
    }
}

A: import jenkins.model.*
import hudson.model.ModelObject
import com.cloudbees.plugins.credentials.*
import com.cloudbees.plugins.credentials.impl.*
import com.cloudbees.plugins.credentials.domains.*
import com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey
import com.cloudbees.jenkins.plugins.awscredentials.AWSCredentialsImpl
import org.jenkinsci.plugins.plaincredentials.StringCredentials
import org.jenkinsci.plugins.plaincredentials.impl.FileCredentialsImpl
import com.cloudbees.hudson.plugins.folder.Folder

class DeepCredentialsPrinter {

  private static final boolean DEBUG = false;

  private final out;
  private final Set<CredentialsStore> visitedStores = new HashSet<>();

  DeepCredentialsPrinter(out) {
      this.out = out;
  }

  private void start() {
    process(Jenkins.getInstance())
  }

  private void process(ItemGroup group) {
    printCreds(group);

    List<ItemGroup> items = group.getItems();
    if (items == null || items.isEmpty()) {
      return;
    }

    for (item in items) {
      if (item instanceof ItemGroup) {
        process(item);
      } else if (item instanceof Item) {
        printCreds(item)
      } else {
        if (DEBUG) {
          out.println("[DEBUG] unsupported item type: " + item.getClass().getCanonicalName());
        }
      }
    }
  }

  private void printCreds(ModelObject model) {
    for (store in CredentialsProvider.lookupStores(model)) {
      if (visitedStores.add(store)) { // only visit new stores
        print(model.getFullName(), store.getCredentials(Domain.global()));
      }
    }
  }

  private void print(String fullname, List<Credentials> creds) {
    if (creds.isEmpty()) {
      if (DEBUG) {
        out.println("[DEBUG] No credentials in /" + fullname);
      }
    } else {
      for (c in creds) {
        out.println("Folder: /" + fullname)
        out.println("   id: " + c.id)
        if (c.properties.description) {
            out.println("   description: " + c.description)
        }
        if (c.properties.username) {
            out.println("   username: " + c.username)
        }
        if (c.properties.password) {
            out.println("   password: " + c.password)
        }
        if (c.properties.passphrase) {
            out.println("   passphrase: " + c.passphrase)
        }
        if (c.properties.secret) {
            out.println("   secret: " + c.secret)
        }
        if (c.properties.secretBytes) {
            out.println("    secretBytes: ")
            out.println("\n" + new String(c.secretBytes.getPlainData()))
        }
        if (c.properties.privateKeySource) {
            out.println("   privateKey: " + c.getPrivateKey())
        }
        if (c.properties.apiToken) {
            out.println("   apiToken: " + c.apiToken)
        }
        if (c.properties.token) {
            out.println("   token: " + c.token)
        }
        out.println("")
        }
    }
  }
}

new DeepCredentialsPrinter(getBinding().out).start();

From all the above comments, Here is the code to list all the folder level credentials which prints all properties based on type of credential

A: Somewhat related to the original ask, I needed to do the inventory of all credentials stored in Jenkins. None of the answers so far have provided a solution that works out-of-the-box to dump all Jenkins credentials...
Based on the elements of answers provided by @TimWelch and @Kingdon, I wrote the following groovy (admin) script, which prints all credentials IDs and their type starting from the root folder to the deepest folders (recursive), while also avoiding printing duplicates:
import jenkins.model.*
import hudson.model.ModelObject
import com.cloudbees.plugins.credentials.*
import com.cloudbees.plugins.credentials.impl.*
import com.cloudbees.plugins.credentials.domains.*
import com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey
import com.cloudbees.jenkins.plugins.awscredentials.AWSCredentialsImpl
import org.jenkinsci.plugins.plaincredentials.StringCredentials
import org.jenkinsci.plugins.plaincredentials.impl.FileCredentialsImpl
import com.cloudbees.hudson.plugins.folder.Folder

class DeepCredentialsPrinter {

  private static final boolean DEBUG = false;

  private final out;
  private final Set<CredentialsStore> visitedStores = new HashSet<>();

  DeepCredentialsPrinter(out) {
      this.out = out;
  }

  private void start() {
    out.println("Folder,Credentials Type,Credentials ID") // header
    process(Jenkins.getInstance())
  }

  private void process(ItemGroup group) {
    printCreds(group);

    List<ItemGroup> items = group.getItems();
    if (items == null || items.isEmpty()) {
      return;
    }

    for (item in items) {
      if (item instanceof ItemGroup) {
        process(item);
      } else if (item instanceof Item) {
        printCreds(item)
      } else {
        if (DEBUG) {
          out.println("[DEBUG] unsupported item type: " + item.getClass().getCanonicalName());
        }
      }
    }
  }

  private void printCreds(ModelObject model) {
    for (store in CredentialsProvider.lookupStores(model)) {
      if (visitedStores.add(store)) { // only visit new stores
        print(model.getFullName(), store.getCredentials(Domain.global()));
      }
    }
  }

  private void print(String fullname, List<Credentials> creds) {
    if (creds.isEmpty()) {
      if (DEBUG) {
        out.println("[DEBUG] No credentials in /" + fullname);
      }
    } else {
      for (c in creds) {
        out.printf("/%s,%s,%s\n", fullname, c.getClass().getSimpleName(), c.id)
      }
    }
  }
}

new DeepCredentialsPrinter(getBinding().out).start();

gist: https://gist.github.com/fabienrenaud/349764873855533abc71b7fadafdf29e
The printCreds method can easily be extended to print more data for each secret type.


text:
Q: Schedule task in Windows Task Scheduler C# My application requires a re-start at midnight time daily. For this job, according to me, the task scheduler would be the ideal thing to use but I haven't been able to find how to use the Task Scheduler APIs in C# (no external libraries to be used)
Once starting the application from Task Scheduler is done, I also wanted suggestions how to shutdown the application automatically at a certain time (even if the app at that particular time might be unresponsive, displaying some error message box or not working due to some problem)

A: Well, I suppose you don't know about the schtasks command.
You could simply open a command prompt and type schtasks /? to see the options available.
The one needed here is /create. Of course this option requires a series of parameter to configure your scheduled task. But at the end you could resolve all calling:
Process.Start("schtasks", commandParams);

For the close process part, I use a little utility called pskill found in the Sysinternals suite from Microsoft's Mark Russinovich. Also this could be called inside a batch file set as scheduled task.
EDIT: Changed from psshutdown to pskill (You need to close only your app right?)

A: I suggest you write a service to handle this. Also, why does it require a restart?
If however you must use task scheduler, try it like this:
schtasks /create /SC DAILY /TN AppName /TR AppExecutablePath /ST 0
0:00 /ET TIMEFORENDTASK

You can simply type this in a batch script and run the batch script when the user is installing the app, then put this in the uninstall batch script:
schtasks /delete /TN AppName


text:
Q: How to find/export only one value (primary SMTP) from multi-valued Proxy Addresses I have a script which search values in attribute Company and Proxy Addresses.
Get-ADUser  -Filter * -SearchBase 'OU=Stu,OU=LOWA,OU=IDLOWA,DC=ad,DC=ju,DC=com' -Properties company,proxyaddresses | select company, @{L='ProxyAddress'; E={$_.proxyaddresses -join"; "}}
Company has two char, but Proxy Addresses is multi-valued, for example:
smtp:adam@ff.ju.com,SMTP:adam@zf.ju.com,smtp:adam@ju.com
or
smtp:adam@ff.ju.com,SMTP:adam@ef.ju.com
or
SMTP:adam@ff.ju.com
I need export/save to variable or csv file only primary SMTP address, that means SMTP:xxx@xxx
Thanks

A: This code will get you all the primary SMTP addresses for the given searchbase parameter, pipes the output to a TXT file. Maybe it needs a little tweaking for some more info, but I think this will get you going:
$users = Get-ADUser  -Filter * -SearchBase 'OU=Stu,OU=LOWA,OU=IDLOWA,DC=ad,DC=ju,DC=com' -Properties proxyaddresses
$primarySMTPAddress = @()
foreach ($address in $users.proxyAddresses)
{
    if (($address.Length -gt 5) -and ($address.SubString(0,5) -ceq 'SMTP:'))
    {
        $primarySMTPAddress += $address.SubString(5)
    }
}

$primarySMTPAddress | out-file -Pathg C:\tmp\PrimarySMTPAdresses.txt

Change the out-file path to a valid location.


text:
Q: Set GridView PageSize from Jquery I want to set the PageSize from a JQuery, the reson is that the gridView have a diffrent height on diffrent screens.
here is the Jquery i run on the page and the GridView
<script>
     //Initial load of page
     $(document).ready(sizePage);

     //Every resize of window
     $(window).resize(sizePage);

     //Dynamically assign height
     function sizePage() {
         var newHeight = $("#page").height() / 1.5;
         $("#mid").css("height", newHeight + "px");
         $("#box1").css("height", newHeight + "px");
         $("#box2").css("height", newHeight + "px");
         $("#field2").css("height", newHeight - 80 + "px");
         $('#<%= GridView.ClientID %>').attr("PageSize", "5");
     }
</script>

<asp:GridView ID="GridView" CssClass="tekst" Width="100%" runat="server" AllowPaging="true" AutoGenerateColumns="false" BorderWidth="0px" GridLines="None" OnPageIndexChanging="GridView_PageIndexChanging" OnRowCommand="GridView_RowCommand" OnRowDataBound="GridView_RowDataBound">
<Columns>
    <asp:BoundField DataField="nyhed_overskrift" HeaderText="Title" HeaderStyle-HorizontalAlign="Left" HeaderStyle-CssClass="headcontent2" />
    <asp:BoundField DataField="nyhed_dato" HeaderText="Oprettet" HeaderStyle-Width="80" ItemStyle-HorizontalAlign="Center" HeaderStyle-CssClass="headcontent2" />
    <asp:BoundField DataField="nyhed_id" HeaderText="ID" HeaderStyle-CssClass="invis" HeaderStyle-Width="0" ItemStyle-CssClass="invis" ItemStyle-Width="0" />
    <asp:ButtonField ButtonType="Image" ImageUrl="Image/Diverse/Arrow.png" CommandName="LaesNyhed" HeaderStyle-Width="50px" />
</Columns>
<PagerStyle VerticalAlign="Bottom" HorizontalAlign="Center" CssClass="tekst" />
</asp:GridView>

A: You can use UpdatePanel with HiddenField to solve this issue
<script type="text/javascript">
    //Initial load of page
    $(document).ready(sizePage);

    //Every resize of window
    $(window).resize(sizePage);

    //Dynamically assign height
    function sizePage() {
        var newHeight = $("#page").height() / 1.5;
        $("#mid").css("height", newHeight + "px");
        $("#box1").css("height", newHeight + "px");
        $("#box2").css("height", newHeight + "px");
        $("#field2").css("height", newHeight - 80 + "px");
        //$('#<%= GridView.ClientID %>').attr("PageSize", "5");
        $('#<%= PageSizeHiddenField.ClientID %>').val('5'); //this is page size
        $('#<%= SetPageSizeButton.ClientID %>').click(); //async postback
    }
</script>
<script runat="server">
    protected void SetPageSize_Click(object sender, EventArgs e)
    {
        GridView.PageSize = int.Parse(PageSizeHiddenField.Value);
        GridView.PageIndex = 0;
        GridView.DataBind();
        MyUpdatePanel.Update();
    }
</script>
<asp:HiddenField runat="server" ID="PageSizeHiddenField" />
<asp:Button ID="SetPageSizeButton" runat="server" Style="display: none" OnClick="SetPageSize_Click" />
<asp:UpdatePanel runat="server" ID="MyUpdatePanel" UpdateMode="Conditional">
    <ContentTemplate>
        <asp:GridView ID="GridView" CssClass="tekst" Width="100%" runat="server" AllowPaging="true"
            AutoGenerateColumns="false" BorderWidth="0px" GridLines="None" OnPageIndexChanging="GridView_PageIndexChanging"
            OnRowCommand="GridView_RowCommand" OnRowDataBound="GridView_RowDataBound">
            <Columns>
                <asp:BoundField DataField="nyhed_overskrift" HeaderText="Title" HeaderStyle-HorizontalAlign="Left"
                    HeaderStyle-CssClass="headcontent2" />
                <asp:BoundField DataField="nyhed_dato" HeaderText="Oprettet" HeaderStyle-Width="80"
                    ItemStyle-HorizontalAlign="Center" HeaderStyle-CssClass="headcontent2" />
                <asp:BoundField DataField="nyhed_id" HeaderText="ID" HeaderStyle-CssClass="invis"
                    HeaderStyle-Width="0" ItemStyle-CssClass="invis" ItemStyle-Width="0" />
                <asp:ButtonField ButtonType="Image" ImageUrl="Image/Diverse/Arrow.png" CommandName="LaesNyhed"
                    HeaderStyle-Width="50px" />
            </Columns>
            <PagerStyle VerticalAlign="Bottom" HorizontalAlign="Center" CssClass="tekst" />
        </asp:GridView>
    </ContentTemplate>
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="SetPageSizeButton" EventName="Click" />
    </Triggers>
</asp:UpdatePanel>


text:
Q: nested forEach loops - error "forEach is not a function" I had a simple for each, but realised I needed to get a different property of my JSON, so I need now to have 2 nested forEach loops, but I am not sure how to do this properly. I am getting an error saying my second forEach is not a function.
I had this code first:
getExample.then(function(response) {
  response.data.forEach(function(x) {
    x.friendlyName = x.AccountTransferFinalityCategoryName + "-" + x.AccountTransferFinalityName;
  });
});

than I tried to change it to this:
response.data.forEach(function (x) {
  x.accounttransferfinalitycategory.forEach(function (y) {
    x.friendlyName = x.accounttransferfinalitycategory[y].AccountTransferFinalityCategoryName + "-" + x.AccountTransferFinalityName;
  });
});

But I get an error now, what is the proper way to do this?

A: I'm not sure what exactly you want to say , but i think your problem is with applying forEach to object,
be sure that x.accounttransferfinalitycategory is array , if it is object try below code
x =  x.accounttransferfinalitycategory;
Object.keys(x).forEach(function (key){
    console.log(x[key]);
});

or update your question with response and expected output :-)

A: I think you need this
$.each(result, function () { console.log(this.Id); console.log(this.Value); });


text:
Q: Java- Como remover un ArrayList de una lista y añadirlo en otra con exito? Llevo varios días atascada con este código ya casi lo termino pero he llegado a un punto donde no se muy bien como continuar. Mi código es un menú de un garaje de coches donde hay una lista de coches para registrarlos en el garaje y otra para registrar las reparaciones.
Funcionamiento del menú --> Se insertan coches en el listado una vez ingresados los coches podemos ver el listado de coches que tenemos en el taller, si no hemos insertado ningún coche avisa que no tenemos coches ingresados, a continuación podemos marcar como reparados usando la matrícula, nos pregunta que coche deseamos reparar y le indicamos la matrícula ( aquí es donde estoy atascada, ya que quiero quitar un coche de la lista de coches y pasarla a reparados, pero me añade en reparados y no me la borra con el remove de la lista anterior), también tenemos otra lista que muestra los coches reparados o si no hay muestra un mensaje, finalmente una opción para retirar los coches de nuestra lista de reparados, como que ya han salido del garaje y la ultima para salir del menú y finalizar el programa.
En el caso de retirar los coches con el remove de mi garaje me pasa exactamente igual que en el caaso de querer eliminar coches de mi registro inicial, no encuentro que debo de estar haciendo mal.
Comparto las 2 clases que tengo.
Main
import java.util.ArrayList;
import java.util.Scanner;

public class Main {
    //creamos el ArrayList de Coche en el main para que lo cojan todos los metodos
    static ArrayList <Coche> listadoCoches = new ArrayList<Coche>();
    static ArrayList <Coche> listadoReparados = new ArrayList<Coche>();
    public static void main(String[] args) {
        int preguntaMenu;
        System.out.println("***Bienvenido al programa de registro de coches***");

        Scanner lector = new Scanner(System.in);

        do {
            System.out.println("Tiene "+listadoCoches.size()+" coches en su taller");
            System.out.println("Que operacion desea realizar? Introduzca una opcion:\n1.Registrar un coche\n2.Listado coches"
            + "\n3.Marcar como reparado\n4.Listado coches reparados\n5.Retirar Vehiculo\n6.Salir");
            preguntaMenu = lector.nextInt();

            if(preguntaMenu == 1){
                registrarCoche();
            }
            else if (preguntaMenu == 2){
                listadoCoches();
            }
            else if (preguntaMenu == 3){
                menuReparados();
            }
            else if (preguntaMenu == 4){
                listadoReparados();
            }
            else if (preguntaMenu == 5){
                retirarVehiculo();
            }
        } while (preguntaMenu != 6);
        System.out.println("Fin");
    }

    public static void registrarCoche() {
        String model;
        String color;
        String marca;
        int nPuertas;
        String matricula;
        String cilindrada;
        int fechaMatricula;
        String respuesta;

        Scanner lector = new Scanner(System.in);

        //empezamos un bucle mientras el usuario desee insertar mas usuarios
        do {
            System.out.println("Quiere registrar un coche?(S/N)");
            respuesta = lector.next();
            //si la respuesta es s volvera a preguntar nombre y suelo sino dira gracias
            if (respuesta.equalsIgnoreCase("s")) {

                System.out.println("Indique la matricula:");
                matricula = lector.next();

                System.out.println("Indique el anyo de matriculacion:(solo el anyo)");
                fechaMatricula = lector.nextInt();

                System.out.println("Cual es el modelo del coche?");
                model = lector.next();

                System.out.println("Indique su color:");
                color = lector.next();

                System.out.println("Indique la Marca del vehiculo");
                marca = lector.next();

                System.out.println("Introduzca la cilindrada del vehiculo: ");
                cilindrada = lector.next();

                System.out.println("Cuantas puertas tiene el vehiculo?");
                nPuertas = lector.nextInt();

                listadoCoches.add(new Coche(model,color,marca,nPuertas,matricula,cilindrada,fechaMatricula));

            }

        }while(respuesta.equalsIgnoreCase("s")); //mientras la respuesta sea s
    }

    public static void listadoCoches() {
        //imprimimos el listado de coches el hashset es recorrido por un for
        System.out.println("\n**Coches pendientes de reparacion**");
        for(Coche c: listadoCoches) {
            System.out.println("\n"+c.mostrarInfo());
        }
        System.out.println("\n************************\n");
    }

    public static void menuReparados() {
        String matricula = null;

        System.out.println("Tiene "+listadoCoches.size()+" coches pendientes de reparacion");

        Scanner lector = new Scanner(System.in);

        do {
            if(listadoCoches.size() > 0 ) {
                System.out.println("Introduzca la matricula del coche que desea reparar\nIntroduzca Salir para finalizar");
                matricula = lector.nextLine();

                if(matricula.equalsIgnoreCase("salir"))
                {
                    System.out.println("Gracias!");
                }else {
                    listadoReparados.add(new Coche(matricula));
                    //int pos = listadoCoches.indexOf(matricula);
                    listadoCoches.remove(matricula);
                }
            }
            else {
                System.out.println("****************************\nNo hay ningun coche para reparar\n****************************");
            }
        }while(!matricula.equalsIgnoreCase("salir"));
    }

    public static void listadoReparados() {
        if(listadoReparados.size() > 0 ) {
            System.out.println("Estos son los coches que ya tiene reparados");
            for(Coche reparado: listadoReparados) {
                System.out.println("\n"+reparado.mostrarInfoMat());
            }
        }
        else {
            System.out.println("****************************\nNo hay ningun coche reparado\n****************************");
        }
    }

    public static void retirarVehiculo() {
        String matricula = null;

        System.out.println("Tiene "+listadoReparados.size()+" coches reparados");

        Scanner lector = new Scanner(System.in);

        do {
            if(listadoReparados.size() > 0 ) {
                System.out.println("Introduzca la matricula del coche que desea retirar del taller\nIntroduzca Salir para finalizar");
                matricula = lector.nextLine();

                if(matricula.equalsIgnoreCase("salir"))
                {
                    System.out.println("Gracias!");
                }else {
                    listadoReparados.remove(new Coche(matricula));
                }
            }
            else {
                System.out.println("****************************\nNo hay ningun coche para retirar\n****************************");
            }
        }while(!matricula.equalsIgnoreCase("salir"));

    }
}

Objeto Coche
public class Coche {
//variables
private String model;
private String color;
private String marca;
private int nPuertas;
private String matricula;
private String  cilindrada;
private int fechaMatricula;

//constructor prefabricado
public Coche(String matricula) {
    this.matricula = matricula;
}

//constructor
public Coche(String model, String color, String marca, int nPuertas, String matricula, String cilindrada,
        int fechaMatricula) {
    this.model = model;
    this.color = color;
    this.marca = marca;
    this.nPuertas = nPuertas;
    this.matricula = matricula;
    this.cilindrada = cilindrada;
    this.fechaMatricula = fechaMatricula;
}

//getters y setters

public String getModel() {
    return model;
}

public void setModel(String model) {
    this.model = model;
}

public String getColor() {
    return color;
}

public void setColor(String color) {
    this.color = color;
}

public String getMarca() {
    return marca;
}

public void setMarca(String marca) {
    this.marca = marca;
}

public int getnPuertas() {
    return nPuertas;
}

public void setnPuertas(int nPuertas) {
    this.nPuertas = nPuertas;
}

public String getMatricula() {
    return matricula;
}

public void setMatricula(String matricula) {
    this.matricula = matricula;
}

public String getCilindrada() {
    return cilindrada;
}

public void setCilindrada(String cilindrada) {
    this.cilindrada = cilindrada;
}

public int getFechaMatricula() {
    return fechaMatricula;
}

public void setFechaMatricula(int fechaMatricula) {
    this.fechaMatricula = fechaMatricula;
}

//metodo mostrar info
public String mostrarInfo() {
    return "Matricula: "+matricula+"\nFecha de matriculacion: "+fechaMatricula+"\nModelo: "+model+"\nColor: "+color+"\nMarca: "+marca+
            "\nCilindrada: "+cilindrada+"\nNumero de Puertas: "+nPuertas;
}

//metodo mostrar info
    public String mostrarInfoMat() {
        return "Matricula: "+matricula;
    }
}

En el caso de coche escribí dos constructores ya que en reparados no me pide que incluya nada mas solo que la matrícula.
¿Alguna idea? Creo que el fallo se debe a los dos constructores del objeto coche que no tienen que ver entre sí pero no logro descifrarlo, ni como arreglarlo

A: En método remove acepta como parámetros el índice del elemento que quieres eliminar o el objeto que espera sea de la misma clase del elemento que quieres eliminar. Tú estas haciendo remove(matricula) y matrícula es string por lo tanto es falso. Según la versión Java:
Java 1.8:
    listadoCoches.removeIf(c -> c.matricula.equals(matricula));

Java  1.7 :
        Tienes dos opciones:

*

*Añadir a la clase Coche una función override "equals" que  compare los objetos de la clase solo por matrícula y hagas remove(new Coche(matricula)). Por esto no funciona el remove de listadoReparados

*Iteres por listadoCoches hasta encontrar el objeto con la matricula. Al encontrarlo borras este objeto.
    Iterator<Coche> itr = listadoCoches.iterator();

     while (itr.hasNext()) {
          Coche c = itr.next();

          if (c.matricula.equals(matricula)) {
                 listadoCoches.remove(c);
                 break;
         }
    }


text:
Q: Agreggate rows from SQL combining values and removing NULLs into a single row I have the following query in DB2 for which I need to combine the rows with values with the ones with nulls into a single line, eventually removing the nulls when there is valid data for that column.
The SQL is
select z.po_id, scdc.ship_id, dcdc.ship_id, scus.ship_id, dcus.ship_id

from covinfos.ibm_plant_order z

left join COVINFOS.IPO_LINE_TO_CASE A ON z.po_id = a.po_id

left JOIN COVINFOS.SHIPMENT scus ON (A.SHIP_ID = scus.SHIP_ID AND A.SHIP_TO_LOC_CODE = scus.SHIP_TO_LOC_CODE and scus.loc_type = 'CUS')

left join COVINFOS.SHIPMENT_EVENT dcus ON (scus.SHIP_ID = dcus.SHIP_ID_856 AND scus.SHIP_TO_LOC_CODE = dcus.SHIP_TO_LOC_CD856
AND dcus.SHIP_EVNT_CD = 'D')

left JOIN COVINFOS.SHIPMENT scdc ON (A.SHIP_ID = scdc.SHIP_ID AND A.SHIP_TO_LOC_CODE = scdc.SHIP_TO_LOC_CODE and scdc.loc_type = 'CDC')

left join COVINFOS.SHIPMENT_EVENT dcdc ON (scdc.SHIP_ID = dcdc.SHIP_ID_856 AND scdc.SHIP_TO_LOC_CODE = dcdc.SHIP_TO_LOC_CD856
AND dcdc.SHIP_EVNT_CD = 'D')

where

z.po_id = 'BQG546'

The result is as seen in image below.

I would like to see just 1 row, grouping by PO_ID and only show the non null values when applicable (if the column has all nulls like column 3 then it would end up in null I assume)
I am using QMF for Workstation z/OS V11.1 Fix Pack 3 to run this query. I tried XMLCAST but not sure if I was using it correctly. LISTAGG seems to be not supported in this client. I would like to then implement it in Cognos BI so again it could work or not.
Does anyone know how to solve this?
Thanks

A: Just use aggregation:
select z.po_id, max(scdc.ship_id), max(dcdc.ship_id), max(scus.ship_id), max(dcus.ship_id)
from . . .
group by z.po_id;

There appears to be at most one non-NULL value in each column so max() suffices.


text:
Q: How to use SFTP with .pem file in C#.net? Problem: I am using C# .net platform to SFTP a file to remote host with a key file/.pem file and no password.
C#.net source code:
ProcessStartInfo p = new ProcessStartInfo
{
    FileName = "sh",
    Arguments = "upload.sh " + file
};
p.RedirectStandardOutput = true;
p.UseShellExecute = false;
p.CreateNoWindow = true;
Process proc1 = new Process();
proc1.StartInfo = p;
proc1.Start();
string result = proc1.StandardOutput.ReadToEnd();
log.InfoFormat(result);

upload.sh:
sftp -i testsftp-key testsftp@sftp.xxx-xxx.com
put  filename

here

*

*testsftp-key     :.pem filename(key file),

*testsftp         :username,

*sftp.xxx-xxx.com :host address.

*filename         :file to be uploaded

File is not getting uploaded when exe is executed by rrot user/cronjob. Executing using non-root user like pi uploads the file.
Permissions are 777 for all.
Error:
permission denied

How to solve this permission issue?

A: I found an answer to this:
ProcessStartInfo p = new ProcessStartInfo
{
    FileName = "sh",
    Arguments = "/home/pi/../upload.sh " + file
};
p.RedirectStandardOutput = true;
p.RedirectStandardError = true;
p.UseShellExecute = false;
p.CreateNoWindow = false;
Process proc1 = new Process();
proc1.StartInfo = p;
proc1.Start();
string result = "";
using (System.IO.StreamReader output = proc1.StandardOutput)
{
    result = output.ReadToEnd();
}
string error = "";
using (System.IO.StreamReader output = proc1.StandardError)
{
    error = output.ReadToEnd();
}
log.InfoFormat("SFTP result: {0}", result);
log.InfoFormat("{0}", error);

I am capturing the redirected stdout and stderr using streamreader. Now i can see the script upload.sh being run successfully and uploading the file to the remote server as well.
I took help from here:
How to capture Shell command output in C#?


text:
Q: Ubuntu - Sequential file naming with User input I am trying to create a custom command for renaming image sequences.
I am studying Visual Effects and sometimes have to rename files sequentially.
I want to navigate to the directory where the images are saved, call the command, receive a prompt to enter a prefix for the file name (EG. {PREFIX}_%04d.png), and execute the command after entering said prefix.
Now I know from another post that I can rename files sequentially via:
for i in *.jpg; do
    p=$(printf "USERINPUTHERE_%04d.jpg" ${n})
    mv ${i} ${p}
    let n=n+1
done

But I am not sure how or if it's possible to have the command request input before fully executing.

A: $ cat cmd.sh
#!/bin/bash

create_file()
{
    echo hello > "$1"
    echo "created $1"
}

format()
{
    printf "%s_%04d.jpg" "$1" "$2"
}

read -p "enter prefix: " PREFIX
i=1
FILE="$(format "$PREFIX" "$i")"
while [ -e "$FILE" ]; do
    ((i++))
    FILE="$(format "$PREFIX" "$i")"
done
create_file "$FILE"
$ ./cmd.sh
enter prefix: hello
created hello_0001.jpg
$ ./cmd.sh
enter prefix: hello
created hello_0002.jpg
$ ./cmd.sh
enter prefix: world
created world_0001.jpg
$ ./cmd.sh
enter prefix: hello
created hello_0003.jpg
$ ls *.jpg
hello_0001.jpg  hello_0002.jpg  hello_0003.jpg  world_0001.jpg

You can have create_file() do whatever you need, and format() format the filename however you feel like.
Also note that this is a very underoptimized implementation. If you plan to have many files, then it would be better to remember the last created file for each prefix.
All that said, it would be more useful to accept the file name as an argument instead of prompting for it, because then you can easily use your command in scripts.


text:
Q: Who introduced the Kite to Smullyan's combinator birds? I am reading To Mock a Mockingbird by Raymond Smullyan. I was led to it by various people describing the lambda calculus combinators using Smullyan's ornithological notation, such as this video and this paper. but I am confused about one thing. Both people use the bird "kestrel" for true and "kite" for false. Kestrel is the bird where A(Bx) = B, and Smullyan does indeed include that bird in the "Hopeless Egocentricity" section. Keenan, in the first link, describes the Kite as "The Kite ignores what it hears and always responds with the Idiot song, so it is the KI bird." The Kite is the Kestrel(Idiot) bird, which in the second link is described as a bird where Ki(Ax) = x.
But I have looked and as far as I can tell Smullyan never mentions the kite, nor does he mention a bird that is the Kestrel listening to the Idiot or where A(Bx) = x in the "Who's Who Among the Birds" section. I searched for 'Kite' in the Google Books version of TMAM and came up with nothing.
My question: Is the kite in TMAM and I missed it? And if Smullyan didn't invent the Kite, who did? And why do people describe it as if it came from TMAM when it didn't?

A: I found this (here) by googling.
;; A few birds and aliases not necessarily given in the book
  ;; but discussed in David Keenan's http://dkeenan.com/Lambda/
  (define identity-bird*   (λ (x y) (x y)))
  (define kite             (λ (x y) y))
  (define konstant-mocker  (λ (x y) (y y)))
  (define crossed-konstant-mocker (λ (x y) (x x)))
  (define idiot-bird* identity-bird*)
  (define pairing vireo))


text:
Q: StAX vs jsoup : which is better way to parse a webpage if XML is available through API I am trying to scrape some data from Wikipedia from 100 pages (approx.). (the pages have same format).
Wikipedia has made its API available which gives the content in XML format or I can directly get the data from the page using jsoup.
Which method should I use to scrape the data ?

A: Since an API is available you should use that approach. The content is well formed and the representation is not going to change without you noticing, which well may be the case with the web page. Using html scraping to get the content you want is error prone since a minor change in the styling can break your selectors and render you scraper useless.
Since wikipedia uses XML most probably uses a SOAP web service (not necessarily though). If that's the case there should be a wsdl available which you can use with CXF framework to generate a web service client in no time. If you are not familiar with soap services take a look here http://cxf.apache.org/docs/a-simple-jax-ws-service.html .
CXF comes with some great pojo generator scripts. Check wsdl2java. Running this script you can give a target (wsdl) and the script will generate all the classes you need to consume that web service.
Update
Wikipedia uses REST services, it just gives the option of xml as the content type. The response is fairly simple. One could use Gson for the response, and then parse the attribute of interest which is html content with jsoup.
Update

*

*Create a maven project like this https://www.youtube.com/watch?v=uv9tXFrTLtI

*Add Stax dependency in the pom http://mvnrepository.com/artifact/stax/stax/1.2.0

*Get coding by beginning with an example http://www.javacodegeeks.com/2013/05/parsing-xml-using-dom-sax-and-stax-parser-in-java.html


text:
Q: Prove that $A[b_1,...,b_n]$ is a finitely generated A-module The following question was left to prove as an exercise in my course on Commutative Algebra.

Question:  If $b_1 ,...,b_n \in B$ are integral over A, then show that $A[b_1,...,b_n]$ is a finitely generated A-module.

So, I have to prove that for any $x\in A[b_1,...,b_n]$ , $x=a_1 m_1+...+a_n m_n$ , where $a_i$'s belong to A and all $m_i$'s belong to $A[b_1,...,b_n]$.
$b_1$ is integral over A means that  there exists $a_i\in A$ such that ${b_1}^n + {b_1}^{n-1} a_1 +...+a_n=0$.
But the problem I am facing is that I am not able to understand how should I use what is given to prove that   $A[b_1,...,b_n]$ is a finitely generated A-module.
Kindly give some hints, I would like to complete this on my own.

A: Say $b$ be integral over $A$
thus, $b^n+a_{n-1}b^{n-1}+...+a_1b+a_0=0$ where $a_0, a_1,...,a_n$ are in $A$
then any element of $A[b]$ can be expressed as a $A$ -linear combination of $b^{n-1},...,b,1$ and hence this ring is finitely generated  over $A$.
Now if $B$ is finitely generated over $A$ and $C$ is finitely generated over $B$ then $C$ also is  finitely generated over $A$. So that $A[b_1,b_2]$ is finitely generated over $A[b_1]$ (Since $b_2$ satisfies a monic polynomial equation over $A$ and hence over $A[b_1]$) and hence finitely generated over $A$ and then carrying on in this way we can show that $A[b_1,b_2,...b_n]$ is finitely generated over $A$


text:
Q: Heroku db:migrate says a column that does not exist does not exist and recommends renaming it I ran:
heroku run rake db:migrate

And the error is:
ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR:  column "book" does not exist

And it recommends:
: ALTER TABLE "books" RENAME COLUMN "book" TO "want"

"books" is a table. "want" is a column of that table.
This is printed three times.
My schema:
  create_table "books", force: :cascade do |t|
    t.text "want"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.bigint "user_id"
    t.text "starting"
    t.index ["user_id"], name: "index_books_on_user_id"
  end

In the middle of the error, it says:
/app/db/migrate/20190801032030_change_book_book_column_name.rb:3:in `change'

This is something I used long time ago to change the column name. The content is:
  def change
    rename_column :books, :book, :want
  end

I can't remember what I may have done with this so that I am getting this error now. Can you please help?
UPDATE
Frustrated, I deleted that migration file. Then I ran again. This time, I got this error:
Table 'posts' has no foreign key for {:to_table=>"books", :column=>"books_id"}

It also mentions a file:
/app/db/migrate/20190806222313_remove_book_ref_to_posts.rb:3:in `change'

Whose content is:
  def change
    remove_reference :posts, :books, foreign_key: true
  end

Schema for posts:
  create_table "posts", force: :cascade do |t|
    t.text "text"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.bigint "book_id"
    t.index ["book_id"], name: "index_posts_on_book_id"
  end

...what can I do?

A: This may happens for (at least) two different reasons:

*

*The column / table was renamed manually using a SQL client, by connecting directly to the database

*The migration 20190806222313_remove_book_ref_to_posts was deployed and "migrated", but you somewhat updated the file and re-deployed to Heroku.

For the first point, I suggest to not update the database schema outside a migration. This makes your application being outside the 12 factors scope, which makes replayability hard (a key point for 12 factors applications). For example, if you re-deploy your application to a new environment and a new database, you would have to run the migrations once, see them fails, re-do the manual schema update you did on your previous database, then run again the migrations. Very painful.
For the second point, I've learned the hard way and have been in this situation more than once in the past. Here is what I do now that is 100% effective:

*

*If you work with multiple branches, and deploy a specific branch to Heroku for testing, always rollback first your database migrations. (heroku run rails db:rollback STEP=XXX) where STEP is the number of migrations to be rollbacked.

*NEVER update a migration file once it's been deployed or shared with a co-worker. It makes re-playing the previous migration painful and can introduce downtime.

*If you are in one of 1) or 2) situation and you still need to re-run the migration for any reason, you will have to manually remove the corresponding row in the table schema_migrations. This table has a single column which is the ID of all the migrations that were applied (migrated) to your database.
So, let's say I have the migration file "123_my_migration.rb" that I deployed to Heroku and migrated, a new row will exists in the schema_migrations table with 123 as value. It means that your migration will never be executed again, unless you remove this row from the table.

It's a bit of discipline, but once you got it, you will really enjoy every minute of your discipline and will be confident enough with every deployment and migration you have to do. Good luck!

A: The solution was to delete that migration also and then creating another migration to delete the existing want column, and then creating another migration to create a new want column, and then deleting that migration which deleted the want column. Basically getting rid of all discrepancies -- giving no excuse for Heroku to say a column doesn't exist.


text:
Q: Django on CentOS/Bluehost: Attempt to Write a Readonly Database, which Chmod besides 777 to use? I am trying to get writing privileges to my sqlite3.db file in my django project hosted on bluehost, but I cannot get any other chmod command to work besides the dangerous/risky chmod 777. When I chmod 777 the db file and the directory, everything works perfectly.
However, in order to be more prudent, I've tried chmodding 775 the directory of the sqlite file and chmod 664 the actual db file itself. No luck. I still get OperationalError: Attempt to Write to a Read Only Database whenever I access a feature that requires writing to the db.
I appreciate any assistance.

A: The user accessing the database (www-data?) needs to have write privileges to the folder the data resides in as well as the file itself.  I would probably change the group ownership (chgrp) of the folder to www-data and add a group sticky bit to the folder as well (chmod g+s dbfolder).  The last one makes sure that any new files created belongs to the group owner.
If you're on bluehost you should also have access to MySql (which is a much better choice for web-facing db).