node_modules/.bin/vue-cli-service build --target lib --name vue-json-schema-form src/components/index.js
Sync-free lazy singleton
public class Singleton {
public static Singleton getInstance() {
return SingletonHolder.instance;
}
private static class SingletonHolder {
public static final Singleton instance = new Singleton();
}
}
Pipeline собственно для лямбд. Для него здесь вместо |
использован /
.
Класс PV вообще можно использовать и для одного аргумента, но тогда на выходе у него будет массив с одним элементом соответвенно.
Код без проблем компилируется как в Java-классы так и в Javascript.
Пример использования:
P(1.0) / {it + 3} / {it - 2} / {it * 5} / {println(it)}
PV(1, 2, 3) / {it + 3} / {it - 2} / {it * 7} / {println(it)}
Реализация на Kotlin, который на момент публикации отсутствовал среди доступных языков.
Запустить можно здесь
Upd: еще немного упростил реализацию
// Pipeline with one argument
class P<A> (val v: A) {
inline fun <B> div(op: (A) -> B) = P(op(v))
}
// Pipeline with multiple arguments
class PV<A> (vararg val v: A) {
inline fun <reified B> div(op: (A) -> B) = PV(*array(v.map{op(it)}))
inline fun <reified T> array(col: List<T>) = Array<T>(col.size()){col[it]}
}
Один из комбинаторов неподвижной точки.
Реализация на Kotlin, который на момент публикации отсутствовал среди доступных языков.
Запустить можно здесь
class Main <A, B> {
val Y = { f: ((A)->B) -> (A)->B ->
class R(val rf: (R) -> (A)->B) {
fun invoke(r: R) = rf(r)
}
val g = { r: R -> f({ arg -> r(r)(arg) }) }
g(R(g))
}
}
fun Main<Int, Int>.run() {
val factorial = Y({ f -> { n -> if (n <= 0) 1 else f(n - 1) * n } })
val fibonacci = Y({ f -> { n -> if (n < 2) n else f(n - 1) + f(n - 2) } })
println(1..10 map { factorial(it) })
println(1..10 map { fibonacci(it) })
}
fun main(args: Array<String>) = Main<Int, Int>().run()
Lock-free and wait-free Singleton
package concurrency;
import java.util.concurrent.atomic.AtomicReference;
public class Singleton {
private static AtomicReference<Singleton> instance;
private Singleton() {
instance = new AtomicReference<>();
}
public static Singleton getInstance() {
if (instance == null) {
Singleton s = new Singleton();
instance.compareAndSet(null, s);
}
return instance.get();
}
}
If you're Software Engineer in Test, which aims to create good reliable automated web tests, this snippet will help you to understand how Java 8 could improve some common approaches, make your code more concise and straightforward.
public class BasePage {
private WebDriverWait wait;
// Skipping other instance variables and constructor
public WebElement findElement(By locator, Function<By, ExpectedCondition<WebElement>> expectedCondition) {
return wait.until(expectedCondition.apply(locator));
}
public boolean getElementState(By locator, Predicate<WebElement> expectedState) {
return expectedState.test(findElement(locator, ExpectedConditions::presenceOfElementLocated));
}
}
public class LoginPage extends BasePage {
private By buttonLogOn = By.id("elementId");
// Skipping constructor
public boolean isLoginButtonEnabled() {
return getElementState(buttonLogOn, WebElement::isEnabled);
}
}
CacheManager стандартными силами.
class CacheManager {
private final ExecutorService executor = Executors.newCachedThreadPool();
private final Map<String, Map.Entry<Future, Long>> cacheData = new ConcurrentHashMap();
public Future get(final String key, final long timeLife, final Method method, final Object[] args) {
Map.Entry<Future, Long> sr = cacheData.get(key);
if (sr != null && sr.getValue() > System.currentTimeMillis()) {
return sr.getKey();
}
Future val = executor.submit(new Callable() {
public Object call() throws Exception {
return method.invoke(args);
}});
cacheData.put(key, new AbstractMap.SimpleEntry(val, timeLife + System.currentTimeMillis()));
return val;
}
//... evict && evict old data by scheduler
}
Для тех, кому надоело постоянно кастовать
public class BaseActivity extends AppCompatActivity {
public <T extends View> T findViewWithId(final int id) {
return (T) super.findViewById(id);
}
}
Используя O(1) по памяти находится возможное начало цикла в односвязном списке.
Соль решения в том, чтобы заставить 2 указателя бегать с разной скоростью. Как только один догоняет другой -- значит есть цикл. Если аккуратно посчитать, то пробежав еще с одинаковой скоростью от начала списка и с места встречи, новое место встречи будет началом цикла.
Полное описание задачи: https://leetcode.com/problems/linked-list-cycle-ii/
public ListNode detectCycle(ListNode head) {
if (head == null || head.next == null) return null;
else if (head.next == head) return head;
ListNode p1 = head, p2 = head;
while (p2 != null) {
p1 = p1.next;
p2 = p2.next;
if (p2 != null) p2 = p2.next;
if (p1 == p2) break;
}
if (p2 == null) return null;
while (head != p2) {
head = head.next;
p2 = p2.next;
}
return head;
}
Equilibrium index of an array is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes.
public static int solution(int[] A) {
long before = 0, after = 0, sum = 0;
for (int i = 0; i < A.length; i++) {
sum += A[i];
}
for (int i = 0; i < A.length; i++) {
after = 0;
before = 0;
for (int j = 0; j < i; j++) {
before += A[j];
}
after = sum - before - A[i];
if (after == before) {
return i;
}
}
return -1;
}