text:
Q: How to get width and height of a Webview in android I want to determine the width and the height of the WebView. I have already tried it using:
webView.getWidth();
webView.getHeight();

but the resulting log always shows them to be 0.

A: Here's a more elegant solution
public void onCreate(Bundle savedInstanceState) {

        webView = (WebView) findViewById(R.id.webView1);

        webView.addOnLayoutChangeListener(new OnLayoutChangeListener() {

            @Override
            public void onLayoutChange(View v, int left, int top, int right,int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                 int w= webView.getWidth();
                 int h= webView.getHeight();

            }
        });

    }

A: You were probably checking for the sizes too soon, most likely in the onCreate. Instead, try this:
webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView webView, String url) {
                super.onPageFinished(webView, url);
                Log.i(TAG, findViewById(R.id.my_component).getWidth(););
            }
        });

A: The onPageFinished call back approach does not work when using loadData or loadDataWithBaseURL. I saw another solution on Andromedev using JavaScript, but I'm not convinced that this is the best path to take.

A: For anyone else who still struggles.
Use these methods to get the height and the width of your webview.
computeHorizontalScrollRange(); -> for width
computeVerticalScrollRange(); -> for height

A: Hmmm - I looked through the WevView source and I can see that internally they are using View#getWidth and View#getHeight here's one of the WebView's private methods:
/*
 * Return the width of the view where the content of WebView should render
 * to.
 */
private int getViewWidth() {
    if (!isVerticalScrollBarEnabled() || mOverlayVerticalScrollbar) {
        return getWidth();
    } else {
        return getWidth() - getVerticalScrollbarWidth();
    }
}

As noted in the comments you have to make sure you are measuring it after you assign the activity layout e.g. setContentView(R.layout.mylayout);

A: you are checking size of webview too early.
you can try this in following method
@Override
public void onWindowFocusChanged(boolean hasFocus) {
    // TODO Auto-generated method stub
    super.onWindowFocusChanged(hasFocus);
            webView.getWidth();
            webView.getHeight();
}

A: You need the width and height of the WebView CONTENTS, after you loaded your HTML.
YES you do, but there is no getContentWidth method (only a view port value),
AND the getContentHeight() is inaccurate !
Answer: sub-class WebView:
/*
  Jon Goodwin
*/
package com.example.html2pdf;//your package

import android.content.Context;
import android.util.AttributeSet;
import android.webkit.WebView;

class CustomWebView extends WebView
{
    public int rawContentWidth   = 0;                         //unneeded
    public int rawContentHeight  = 0;                         //unneeded
    Context    mContext          = null;                      //unneeded

    public CustomWebView(Context context)                     //unused constructor
    {
        super(context);
        mContext = this.getContext();
    }

    public CustomWebView(Context context, AttributeSet attrs) //inflate constructor
    {
        super(context,attrs);
        mContext = context;
    }

    public int getContentWidth()
    {
        int ret = super.computeHorizontalScrollRange();//working after load of page
        rawContentWidth = ret;
        return ret;
    }

    public int getContentHeight()
    {
        int ret = super.computeVerticalScrollRange(); //working after load of page
        rawContentHeight = ret;
        return ret;
    }
//=========
}//class
//=========

A: I used a work-around , instead of fetching from unreliable webview get from DisplayMetrics, assuming you have webview width almost equal to phone screen size and height almost equal to height of phone screensize.
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int height = (int) displayMetrics.heightPixels*0.9;
int width = displayMetrics.widthPixels;

A: If you want to get The Height and Width load time you can't get it because load time can't get it. I suggest to use the webview Touchevent and get the height and width. Otherwise use another view click event and get the height and width.
webView.getWidth();
webView.getHeight();

Use this.

A: I had the same problem. I just put initWebView method in onWindowFocusChangedt.
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    initWebView();
}

private void initWebView(){
    if(isOnline()){
        venueWebView = (WebView) findViewById(R.id.venueWebView);
        String url = "some url";
        int viewWight = venueWebView.getWidth();
        int viewHeight = venueWebView.getHeight();
        venueWebView.loadUrl(url);
    }

A: I hope my answer helps somebody.
If you want to get height of webview after content is loaded then this could be helpful.
ViewTreeObserver viewTreeObserver  = mWebView.getViewTreeObserver();
viewTreeObserver.addOnPreDrawListener(new OnPreDrawListener() {
 @Override
 public boolean onPreDraw() {
     int height = mWebView.getMeasuredHeight();
        if( height != 0 ){
      Toast.makeText(getActivity(),"height:"+height,Toast.LENGTH_SHORT).show();
                             mWebView.getViewTreeObserver().removeOnPreDrawListener(this);
                       }
                       return false;
               }
       });

A: If you want to get the original height after loading content, you can use the below code. Though the code is deprecated, yet it works perfectly.
webview.setPictureListener(new WebView.PictureListener() {
        @Override
        public void onNewPicture(WebView webView, @Nullable Picture picture) {
            int height = webview.getContentHeight();
            int height1 = webview.getMeasuredHeight();
            int height2 = webview.getHeight();
        }
    });


text:
Q: How to load collada model I have used sketchup to convert a sketch file in a collada (dae) file.
loader = new THREE.ColladaLoader()
loader.load('collada_models/robot.dae', loaderSuccess)

loaderSuccess = function(collada){
   console.log(collada)
   model = collada.scene
   scene.add(model)
}

I get the model data in my console. But I dont see the model in my scene.
Any Ideas why? I have forgot something?
Lights, And AnimationFrame are added.
Edit:
collada.scene.children[ 0 ].geometry;
collada.scene.children[ 0 ].material;

are both undefined, is this a problem? A export problem?
Thanks!

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to draw with replacement instead of blending I'm trying to "draw" areas of transparency onto a bitmap -- like cutting holes in the image.
The following code does not draw a line of transparency because drawing a transparent line onto a bitmap of course blends instead of replaces. (Why the default is to do the more complicated of the two drawing operations, makes no sense.)
Bitmap myBitmap = new Bitmap(50, 50);
Graphics g = Graphics.FromImage(myBitmap);
g.FillRectangle(Brushes.Black, 0, 0, 50, 50);
g.FillEllipse(Brushes.Transparent, 25, 0, 25, 25); //Does nothing
g.DrawLine(Pens.Transparent, 0, 0, 50, 50); //Does nothing

How would I modify this so that a transparent circle and line replace what's in the bitmap instead of blending?
(Note that this is the trivial case of "drawing" complete transparency. The end I'm going toward is the ability to "draw" modifying the alpha channel only without creating my own pixel by pixel operation. Being able to do complete transparency will suffice though.)

Following answer in article suggested as a duplicate, I've also tried the following (which does not work)
        base.OnPaint(e);
        Bitmap myBitmap = new Bitmap(50, 50);
        e.Graphics.FillRectangle(Brushes.Black, 0, 0, 50, 50);
        Graphics g = Graphics.FromImage(myBitmap);
        g.FillEllipse(new SolidBrush(Color.FromArgb(150, 125, 125, 125)), 25, 0, 25, 25);
        g.DrawLine(new Pen(Color.FromArgb(150,25,25,25)), 0, 0, 50, 50);
        g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver;
        e.Graphics.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver;
        e.Graphics.DrawImage(myBitmap, 0, 0);

also tested this with SourceCopy

A: This works totally fine for me
Bitmap bmp = new Bitmap(50, 50, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
using (Graphics g = Graphics.FromImage(bmp))
{
    g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy;
    g.FillRectangle(Brushes.Black, 0, 0, 50, 50);
    g.FillEllipse(Brushes.Transparent, 25, 0, 25, 25);
    g.DrawLine(Pens.Transparent, 0, 0, 50, 50);
    g.Flush();
}
bmp.Save("Test.bmp");


text:
Q: How to select 2 different columns from two different tables with COUNT and WHERE clause I really need your help on this, I have these queries where I want to select 2 columns of 2 different tables with count and where statement..
SELECT Error_Code as ISERR,
       COUNT(Error_Code) as A
FROM COMPIS
WHERE test_date BETWEEN '2020-01-01 06:00:00' AND '2020-01-10 18:00:00'
  AND Error_Code <> ' '
GROUP BY Error_Code

SELECT error_code as SCERR,
       COUNT(error_code) as B
FROM COMPSER
WHERE test_date_time BETWEEN '2020-01-01 06:00:00' AND '2020-01-10 18:00:00'
  AND error_code <> ' '
GROUP BY error_code

I have tried these queries, but this only showed me null values.
SELECT A, a.ISERR, B, b.SCERR
FROM ( SELECT Error_Code as ISERR,
              COUNT(Error_Code) as A
       FROM COMPIS
       WHERE test_date BETWEEN '2020-01-01 06:00:00' AND '2020-01-10 18:00:00'
         AND Error_Code <> ' '
       GROUP BY Error_Code ) a,
     ( SELECT error_code as SCERR,
              COUNT(error_code) as B
       FROM COMPSER
       WHERE test_date_time BETWEEN '2020-01-01 06:00:00' AND '2020-01-10 18:00:00'
         AND error_code <> ' '
       GROUP BY error_code ) b

OUTPUT was:
A    | ISERR | B   | SCERR
-----+-------+-----+------
null   null   null   null

Your help will be appreciated. Thanks

A: SELECT error_code,
       SUM(CASE WHEN table='A' THEN cnt END) cnt_A,
       SUM(CASE WHEN table='B' THEN cnt END) cnt_B
FROM ( SELECT Error_Code as ISERR,
              COUNT(Error_Code) as cnt,
              `A` as table
       FROM COMPIS
       WHERE test_date BETWEEN '2020-01-01 06:00:00' AND '2020-01-10 18:00:00'
         AND Error_Code <> ' '
       GROUP BY Error_Code
     UNION ALL
       SELECT error_code,
              COUNT(error_code),
              'B'
       FROM COMPSER
       WHERE test_date_time BETWEEN '2020-01-01 06:00:00' AND '2020-01-10 18:00:00'
         AND error_code <> ' '
       GROUP BY error_code ) total
GROUP BY error_code

If you need NULL instead of zeros use MAX instead SUM.


text:
Q: How to make an encrypted executable file I have made a tool/program on Ubuntu written in Python. I want to give this to my friend to test on his PC, but I don't want to share the source code.
This program has many folders and many .py files. Is there a way to turn all this code into one encrypted executable file (like a binary file)?

A: You can always obfuscate the source code. Here you can use the tool pyobfuscate. To know more about obfuscation, go to obfuscating Python code and information about protecting Python code.


text:
Q: How to Calculate Time Difference Between Two TIMESTAMP in Android I am saving Current Date time as Timestamp with below code in my Android
 userValues.put("rTime",  ServerValue.TIMESTAMP);

Now I want to calculate difference as
String posttime=1576917051506 //retrieve saved timestamp
 String currenttime=ServerValue.TIMESTAMP //current time
 difference=1hour 25 minutes
how can i achieve this

A:  String posttime=1576917051506
 String currenttime=ServerValue.TIMESTAMP

first of all convert times to Long
   long time1 = Long.valueof(posttime)
   long time2 = Long.valueof(currenttime)
   long diffrence  = time2-time1
   String myValue = convertSecondsToHMmSs(diffrence)

Now myValue is your time diffrence. like 1h:2m
  public static String convertSecondsToHMmSs(long millis) {
       long seconds = (millis / 1000) % 60;
long minutes = (millis / (1000 * 60)) % 60;
long hours = millis / (1000 * 60 * 60);

StringBuilder b = new StringBuilder();
b.append(hours == 0 ? "00" : hours < 10 ? String.valueOf("0" + hours) :
String.valueOf(hours));
b.append(":");
b.append(minutes == 0 ? "00" : minutes < 10 ? String.valueOf("0" + minutes) :
String.valueOf(minutes));
b.append(":");
b.append(seconds == 0 ? "00" : seconds < 10 ? String.valueOf("0" + seconds) :
String.valueOf(seconds));
return b.toString();
    }

A: Using Joda time:
DateTime startTime, endTime;
Period p = new Period(startTime, endTime);
long hours = p.getHours();
long minutes = p.getMinutes();


text:
Q: CommunicationException while client's ctx.lookup() in GlassFish 3.1 I have one entity class which implements Serializable and I got this error on client:

javax.naming.CommunicationException:
  Communication exception for
  SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory,
  java.naming.factory.url.pkgs=com.sun.enterprise.naming,
  java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl}
  [Root exception is
  java.rmi.MarshalException: CORBA
  BAD_PARAM 1398079494 Maybe; nested
  exception is:
    java.io.NotSerializableException:
  ----------BEGIN server-side stack trace----------
  org.omg.CORBA.BAD_PARAM: WARNING:
  IOP00100006: Class
  com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate
  is not Serializable  vmcid: SUN  minor
  code: 6 completed: Maybe

when I'm doing SomeService serv = (SomeService)ctx.lookup("java:global/MyProject/SomeServiceImpl");
Does Entity class should be in the same package both in server and in client?
Now Entity class is in the package (dir) of Client App and in the package (dir) where SomeService interface is on the server.

A: I added @Remote annotation to service interface and error disapeared.

A: I tried the following and everything works Ok.
When creating InitialContext as:
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.enterprise.naming.SerialInitContextFactory");
props.setProperty("org.omg.CORBA.ORBInitialHost", "localhost");
props.setProperty("org.omg.CORBA.ORBInitialPort", "3700");

InitialContext ctx = new InitialContext(props);

And later,
myBeanService = (MyBeanService) ctx.lookup("java:global/AppName/MyBeanService");

Shows that exception, but if I just call this way:
myBeanService = (MyBeanService) new InitialContext().lookup("java:global/AppName/MyBeanService");

There is no problem. The problem are the JNDI properties.


text:
Q: How cannot I install a Google Chrome App I developed myself? I have created a Google Chrome App and published in webstore, but not listed.
When I go to this URL:
https://chrome.google.com/webstore/detail/my-app/thisistheid?hl=en
This appears in the installation button:

However, during development, I could install the application manually.
What is wrong here?
EDIT:
This is the manifest.json file:
{
  "manifest_version": 2,
  "name": "App Name",
  "description": "blablabla.",
  "version": "1.1",
  "permissions": [

  ],
  "app": {
    "background": {
      "scripts": [ "main.js" ]
    }
  },
  "externally_connectable": {
    "matches": [ "*://localhost:*/*" ]
  },
  "sockets": {
    "tcp": {
      "connect": "localhost:1437"
    }
  },
  "icons": {
    "16": "img/icon16.png",
    "32": "img/icon32.png",
    "48": "img/icon48.png",
    "128": "img/icon128.png"
  },
  "web_accessible_resources": [ "img/logo.jpg" ]
}


text:
Q: Возможность создания составного первичного ключа MySQL Всем привет.
Интересует вопрос может ли первичный суррогатный ключ некой таблицы входить в какой- нибудь составной первичный ключ этой же таблицы?


text:
Q: Karma-Jasmine: Import Spy with noImplicitAny If I set this in the tsconfig.json file of an Angular 4+ project:
"noImplicitAny": true,

...and import this to be used in a unit-test:
import { Spy } from "karma-jasmine";

...I am seeing this console error on npm test:
ERROR in C:/test-project/src/app/components/test/test.component.spec.ts (1,21):
Could not find a declaration file for module 'karma-jasmine'.
'C:/test-project/node_modules/karma-jasmine/lib/index.js' implicitly has an 'any' type.
Try `npm install @types/karma-jasmine` if it exists or add a new declaration (.d.ts) file containing `declare module 'karma-jasmine';`

I tried this:

*

*npm install --save-dev @types/karma-jasmine

*Add "types": [ "karma-jasmine" ] to tsconfig.json
...and am now seeing this console error on npm test:
ERROR in C:/test-project/src/app/components/test/test.component.spec.ts (1,21):
File 'C:/test-project/node_modules/@types/karma-jasmine/index.d.ts' is not a module.

How can I import Spy if "noImplicitAny": true is set?
If this is set to false (which is the default value), the import and usage works without error.
Example usage:
const testSpy: Spy = spyOn(testService, "test").and.callThrough();

A: That's because the name of the framework is Jasmine. Karma is test runner that shouldn't be mentioned in specs, and karma-jasmine is Karma plugin to seamlessly run Jasmine specs.
Since jasmine is a namespace, it should be:
import * as jasmine from "jasmine";

const spy: jasmine.Spy = ...;

jasmine is supposed to be global, and jasmine.Spy can be used directly without import.


text:
Q: Topological entanglement entropy in transverse quantum Ising model? I have seen from literature that the $Z_2$ lattice gauge theory in 2d could be mapped into a quantum Ising model with gauge constraints on the Hilbert space by dual transformation. The deconfined phase in $Z_2$ gauge theory corresponds to paramagnetic state in quantum Ising model. Does that mean there is topological entanglement entropy (EE) in the quantum Ising model in paramagnetic state? If yes, does that EE corresponds to topological order in quantum Ising model?

A: Duality transformation does not preserve topological order, and hence not preserving the topological entanglement entropy. The quantum Ising model has no topological entanglement entropy. See this related question for more discussions.


text:
Q: Low memory consumption watermarking for Python I'm trying to add an image watermark to images (image sizes can go up to 2.5MB), but my current solutions require a larger amount of memory - at the moment I'm using https://bitbucket.org/codekoala/django-watermark.
Because of the 60MB memory limit define by my hosting, I'm getting MemoryError errors.
It could be a memory leak or 2.5MB images are just too big for 60MB ram limit. Before I do anymore investigations, does anybody know for a low memory consumption image watermarker? Current one uses PIL (afaik is the best for the job). As I recall, it offers an option to load image by parts - it could be my solution but I don't find any resources regarding it.
Best regards,
E

A: Python offers little ready / productized tools for progressive image processing. My recommendation way is simply to move a hosting where you can safely decompress a full image to the memory. This does not go for Python, but for other platforms as well generally.
The only thing which can be buffered with PIL is loading the image over the network connection, so that you can start processing the image before it has been fully received.


text:
Q: Как сделать управление, как в игре "Overcooked"? Хочу сделать управление игроком, как в игре "Overcooked".
Трейлер с геймплеем.
Моё текущее управление игроком.

PlayerController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerControllerTransform : MonoBehaviour {

    private string moveInputAxis = "Vertical";
    private string turnInputAxis = "Horizontal";

    public float rotationRate = 360f;
    public float moveSpeed = 1;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update ()
    {
        float moveAxis = Input.GetAxis (moveInputAxis);
        float turnAxis = Input.GetAxis (turnInputAxis);

        //Обновляет каждый кадр наше положение и поворот
        ApplyInput (moveAxis, turnAxis);
    }

    private void ApplyInput(float moveInput, float turnInput)
    {
        Move (moveInput);
        Turn(turnInput);
    }

    private void Move(float input)
    {
        transform.Translate (Vector3.forward*input*moveSpeed);//Можно добавить Time.DeltaTime
    }

    private void Turn(float input)
    {
        transform.Rotate (0,input * rotationRate * Time.deltaTime,0);
    }
}

В чём проблема. В игре куда нажал (WASD), туда носом повернул и пошёл.(Как я понял) У меня же на данный момент, управление больше похоже на управление машиной. A-D-отвечают за поворот. W-вперёд,S-назад.
В итоге хочу сделать управление аналогичное игровому.
p.s. Ещё видео с геймплеем, чтобы понять лучше игровое управление.
Спасибо за внимание.

A: Вообще с вопросами "Как игра X сделала Y" лучше обращаться к самим разработчикам. И не потому что кому "лень" отвечать на такие вопросы, а просто потому что зачастую довольно сложно воссоздать что-то из другой игры 1в1.

Наверняка такое можно сделать и другим способом, но я решил пойти через 2 этапа:

*

*вращение персонажа в зависимости от ввода

*перемещение персонажа через transform.forward, благо персонаж в данной игре всегда двигается только лицом вперед

Ввод данных
Тут все максимально просто и не отличается от варианта в вопросе, но записываю я все это дело в вектор, чтобы потом получать через него углы и прочие нужные вещи:
private Vector3 moveVector;

...

void HandleInput() {
    moveVector.x = Input.GetAxis("Horizontal");
    moveVector.z = Input.GetAxis("Vertical");
}

Вращение
Казалось бы, можно просто использовать
transform.Rotate(Vector3.up, Vector3.Angle(transform.forward, moveVector));

Но Vector3.Angle возвращает наименьший угол между векторами, т.е. от 0 до 180, что приводит к таким результатам при вращении на угол от 0 до 360:

Один из выходов из данной ситуации - написать свою функцию определения угла между векторами для диапазона углов [0..360]:
float Angle360(Vector3 from, Vector3 to, Vector3 right) {
    float angle = Vector3.Angle(from, to);
    return (Vector3.Angle(right, to) > 90f) ? 360f - angle : angle;
}

Такую функцию очень просто найти в гугле - не хочу перегружать вопрос ее объяснением.
А затем применяем все это дело в Update:
void Update () {
    HandleInput();

    transform.Rotate(Vector3.up, Angle360(transform.forward, moveVector, transform.right));
}

И получаем почти нужное нам вращение:

Перемещение
Все практически элементарно: использует Transform.Translate, не забывая добавить переменную для скорости:
public float speed = 2f;

...

transform.Translate(transform.forward * speed * Time.deltaTime, Space.World);

Данный код будет постоянно двигать объект по направлению его локального "прямо". Но мы хотим двигать его только при вводе пользователя.
Логичный выход из ситуации - использовать модуль вектора moveVector, предварительно его нормализовав, дабы получить значение в диапазоне [0..1]:
transform.Translate(
    moveVector.normalized.sqrMagnitude * transform.forward * speed * Time.deltaTime,
    Space.World
);

В данном случае можно использовать квадрат модуля просто потому что квадрат модуля всегда будет равен либо 0, либо 1, а sqrt(1) == 1/-1, sqrt(0) == 0. -1 нас по понятным причинам не беспокоит.
Но чисто по ощущениям - результаты я не замерял, проще обойтись вообще без этого модуля и сделать вот так:
float Moves() {
    if(moveVector.x != 0 || moveVector.z != 0) {
        return 1f;
    }
    else {
        return 0f;
    }
}

Стоит отметить, что данный метод будет всегда выдавать вектор движения 1. Если игра поддерживает геймпады, где джойстики могут выдавать значения по обеим осям [0..1], лучше использовать модуль вектора.
И подставив результат этого метода в Translate.

В конечном итоге получили какой-то такой компонент:
public class OvercookedLikeMovement : MonoBehaviour {

    public float speed = 2f;

    private Vector3 moveVector;

    void Update () {
        HandleInput();

        transform.Rotate(Vector3.up, Angle360(transform.forward, moveVector, transform.right));

        transform.Translate(
            Moves() * transform.forward * speed * Time.deltaTime,
            Space.World
        );
    }

    void HandleInput() {
        moveVector.x = Input.GetAxis("Horizontal");
        moveVector.z = Input.GetAxis("Vertical");
    }

    float Moves() {
        if(moveVector.x != 0 || moveVector.z != 0)
            return 1f;
        else
            return 0f;
    }

    float Angle360(Vector3 from, Vector3 to, Vector3 right) {
        float angle = Vector3.Angle(from, to);
        return (Vector3.Angle(right, to) > 90f) ? 360f - angle : angle;
    }
}

Результат в Unity:

P.S.
Видно, что объект иногда двигается рывками. Причиной этому служит резкая смена угла поворота объекта, это не баг, а закономерный результат кода выше и чище без интерполяции не сделать.
Что бы я сделал на вашем месте?
Посмотрел бы в сторону Tween движков для Unity, с помощью которых можно все это дело сгладить и сделать более натуральным, что ли. Но результат на данный момент, как по мне, очень похож на OverCooked.


text:
Q: The roots of $x^3+mx+n$ where $n<0$ This question is from a high school book under the "applications of derivates" section.
The question says,

Given $x^3+mx+n$ where $n<0$ and there are three roots $r_1<r_2<r_3$,
  what can be surely said about the roots?

Clearly, the product of the roots is a positive number. So, either all roots are positive, or only one of them is positive. Also, since there is no term with $x^2$, the sum of the roots is zero, so, they can't be all positive.
Hence, the answer is $r_1<r_2<0<r_3$.
However, I fail to see how this result can be derived using derivatives.

A: You made a mistake when you stated that the product of the three roots is negative. Indeed, by Vieta's formulas, $n = -r_1 r_2 r_3$, so the product $r_1 r_2 r_3$ must be positive.
Anyway, let us prove the result using derivatives. Let $f(x) = x^3 + m x + n$. Then $f'(x) = 3x^2 + m$.
You can prove that $m < 0$ (otherwise we get a contradiction). Then $f'(x) > 0$ if and only if $x < -k \lor x > k$, where $k = \sqrt{-m/3}$. Therefore $f$ is increasing in $]-\infty, -k[$, decreasing in $]-k, k[$, and again increasing in $]k, +\infty[$.
Since $f(0) = n < 0$ and $f$ is first decreasing and then increasing in $]0, +\infty[$, we see that there is exactly one positive root, which must be $r_3$. Then the other roots $r_1$ and $r_2$ are negative, and so $r_1 < r_2 < 0 < r_3$.

A: let $$f(x)=x^3+mx+n$$ where $$n<0$$ then we get
$$f'(x)=3x^2+m$$
and we have in the first case where $$m\geq 0$$ then our $$f(x)$$ is monotonously increasing and since we have $$n<0$$ exactly one root
in the case of $$m<0$$ we get
$$x_{1,2}=\pm\sqrt{\frac{-m}{3}}$$ then we get since $$f''(x)=6x$$ :
$$f''(x_1)>0$$ so we have a minimium point at $$(x_1;f(x_1)$$ in the other case a maximum point at $$(x_2,f(x_2))$$
can you proceed?


text:
Q: Is it possible to run whole testsuite as iteration in automation? I have scenario where whole test cases has shared (global) parameter which changes based on Test rounds with MTM.
So here we can say shared parameter is a common parameter based on Test round
For example
Test Round 1 globalVar="abc" executes TC1,TC2,TC3 for "abc"
Test Round 2 globalVar="pqr" executes TC1,TC2,TC3 for "pqr"
Test Round 3 globalVar="xyz" executes TC1,TC2,TC3 for "xyz"

I want to use this globalVar  in automation in such manner that when we execute:
-Test Round 1,  test cases will execute for globalVar  ="abc".
-Test Round 2,  test cases will execute for globalVar  ="pqr".
-Test Round 3,  test cases will execute for globalVar  ="xyz".

Now I have few queries:
1) Is it possible to change or pass globalVar value dynamically  in MTM based on Test round?
2) How do we use shared variable globalVar in coded UI test cases?(Need piece of code)?
3) Is it possible to define common global variable for test cases  while writing test cases in codedUI, which we can change dynamically  while execution of test cases in MTM?

A: I believe you could do this by data driving your tests and then modifying the data file from within the test.

*

*I'm not sure about dynamically changing variables in MTM, but you can definitely use MTM as a Data Source.

*MS Test framework has built in functionality for data driven tests.
https://msdn.microsoft.com/en-us/library/ee624082.aspx

*You would use and modify the same data source for multiple tests.


text:
Q: how to find a table with a certain row id, add a class to the row and call button click using jquery I have table with certain rows. Each rows has an id assigned to e.g. and a cell containing a button.

 columns data <input type="Submit" name="Select" />

 columns data <input type="Submit" name="Select" />

 columns data <input type="Submit" name="Select" />

using jquery how can I find a row with a certain id say '68' and add a class hightlight to it and fire click event of the Select button present inside the row
I m trying something on these lines
$('#templateSite tr').find('#'+data.siteId).addClass('highlight');

where data.siteId will be the value like 68
Any ideas?

A: Try like this:
$('tr#'+data.siteId).addClass("highlight").find("input[type='submit']").trigger('click');

A: You are looking for tr with a child id of id. Try:
$('#templateSite tr#'+data.siteId + " td").addClass('highlight');
$('#templateSite tr#'+data.siteId).find("input[type='submit']").trigger('click');


text:
Q: Why was my question about a python feature closed? Why was my question closed? What would be the correct site to post it at? I tried to write a solution in Python and it didn't work out, and as Python is a programming language I really don't know why it was marked as off-topic.

A: The question was closed because it is not related to a programming problem.  It's a system administration problem, really.  I would not vote to close it if it were on Serverfault.


text:
Q: Windows 10 - ObjectOutputStream can't find relative paths because current working directory is System32 When I call method
System.out.print(new File("").getAbsolutePath())
from main I get the project workspace
C:\Users\darkr\Desktop\NuovoWorkSpace\ProjectName.
When it gets called by our save() method, which serializes what we need, suddenly the absolute path given from
new File("").getAbsolutePath()
becomes System32 (for me) and Desktop directory for my colleagues.
We're using gitHub to share our changes but this makes it almost impossible.

A: The code you have new File("").getAbsolutePath() is commonly used to determine the current directory from where you launched your application's main(String[]) method. So it looks like you are running from C:\Windows\System32 not on desktop folder.
The easiest way to fix your issue is to edit your application shortcut (see .lnk file and set "Start in" folder), or cd to be in an appropriate writable directory before running your application, or change your application to use file chooser to pick the target location for saves.
Alternatively pick sensible output paths for writing to instead of "", some good candidates are:
// Local user profile
File folder = new File(System.getenv("LOCALAPPDATA"), "myfolder");
// Roaming user profile
File folder = new File(System.getenv("APPDATA"), "myfolder");
// Temp folder:
File folder = new File(System.getProperty("java.io.tmpdir"), "myfolder")

Some sites suggest one of the following lines to locate Desktop, but this is unreliable because it will not work if the folder has been moved or run on some non-English installations:
File maybeDesktop = new File(System.getProperty("user.home"), "Desktop");
Path maybeDesktop = Path.of(System.getProperty("user.home"), "Desktop");

If you want to read the exact location of user Desktop from Java, you need to use JNI/JNA/Panama call to Windows API functions SHGetFolderPath or SHGetKnownFolderPath.


text:
Q: Universal file association file I am using multiple desktops / windows managers (KDE, Openbox wm, and i3 wm ) on my PC and I want to establish an unified and universal file where I would set file associations for my whole system.
I am on Arch Linux and from this thread and Arch wiki I concluded that I need to create a /usr/share/applications/mimeapp.list which wasn't working for the guy in a linked thread. He claims file should be renamed to /usr/share/applications/mimeapp.list. Well whatever... This file of mine looks like this:
[Default Applications]
application/pdf=masterpdfeditor.desktop
image/vnd.djvu=masterpdfeditor.desktop

text/plain=kate.desktop
text/x-markdown=kate.desktop
application/x-shellscript=kate.desktop
text/x-java=kate.desktop
inode/x-empty=kate.desktop
text/x-python=kate.desktop
text/x-readme=kate.desktop
application/x-ruby=kate.desktop
text/x-ruby=kate.desktop
text/x-tex=kate.desktop

text/html=firefox.desktop
text/rhtml=kate.desktop
image/png=gthumb.desktop
image/jpeg=gthumb.desktop
x-scheme-handler/http=firefox.desktop
x-scheme-handler/https=firefox.desktop
x-scheme-handler/ftp=firefox.desktop
x-scheme-handler/chrome=firefox.desktop
application/x-extension-htm=firefox.desktop
application/x-extension-html=firefox.desktop
application/x-extension-shtml=firefox.desktop
application/xhtml+xml=firefox.desktop
application/x-extension-xhtml=firefox.desktop
application/x-extension-xht=firefox.desktop
video/ogg=mplayer.desktop
video/x-msvideo=mplayer.desktop
audio/mpeg=mplayer.desktop
video/quicktime=mplayer.desktop
video/webm=mplayer.desktop
video/x-flv=mplayer.desktop
video/mp4=mplayer.desktop
application/ogg=mplayer.desktop
audio/x-flac=mplayer.desktop
audio/mp4=mplayer.desktop
application/x-flash-video=mplayer.desktop

But even if I configured my PC to open .tex files using kate, they are still opened with kile IDE. This happens every time I open this file type in dolphin or thunar.
I figured out that kile and thunar are behaving according to our file associations settings in KDE's systemsettings5 and are completely ignoring defaults.list and I don't want that, because I want to avoid systemsetting's GUI which is clumsy and forces me to click every setting and change it. There are no Bulk actions like resetting / deleting the file associations profile...

QUESTION
So how can I force my Xorg server to use defaults.list and completely ignore systemsettings5? And one more thing... Where does systemsettings5 get it's settings? Is it from the `/usr/share/applications/*.desktop files? What would happen if I delete those?


text:
Q: MySQL for Excel exporting incorrectly formats dates I am trying to export an Excel sheet to a MySQL table. I asked to create a new table and insert the data from excel.
Using Excel 2013, brand new MySQL for Excel add-in, and brand new MySQL (running on my desktop in Windows 7).
At first I would get the error message

Error Code: 1064. You have an error in your SQL syntax; check the
  manual that corresponds to your MySQL server version for the right
  syntax to use near
  ':00:00,10:00:00,9/1/2010,12/20/2010,'HEIEUS','K2I4','M',0,0,3,'X','PP','2010-11-'
  at line 4

After pasting the SQL statement into a MySQL Workbench query I was told there was a missing parentheses right in front of a date.
I figured out that if I added quotes around the date (in DateTime format), that line would be read in and the error would move a line down to the next row insertion. Examples I have seen do show that the date text should be inside quotes (https://www.ntchosting.com/encyclopedia/databases/mysql/insert-date/).
It is impractical for me to copy the sql statement, paste into MySQL Workbench, then add quotes to all the dates for thousands of rows. Does anyone know of a way to get Excel to format the dates correctly. Or has anyone even seen this before?

A: This is a bit of a hack, because it works around the MySQL plugin for Excel which should be working.  You can try exporting your data from Excel as CSV.  Make certain that every column is quoted when you export it.
Then import the data into MySQL using LOAD DATA:
LOAD DATA INFILE 'data.csv' INTO TABLE tbl_name
FIELDS TERMINATED BY ',' ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES;


text:
Q: difference between mapM and forM Could you tell me is there exists some difference between mapM and forM ?
Look at signatures:
mapM :: Monad m => (a -> m b) -> [a] -> m [b]
forM :: Monad m => [a] -> (a -> m b) -> m [b]

The only thing is order of arguments.  It is unvailable, but does it really only difference ?

A: forM is defined as flip mapM in base:
-- | 'forM' is 'mapM' with its arguments flipped. For a version that
-- ignores the results see 'Data.Foldable.forM_'.
forM :: (Traversable t, Monad m) => t a -> (a -> m b) -> m (t b)
{-# INLINE forM #-}
forM = flip mapM


text:
Q: Show user location on ios map using Delphi I wanted to show Apple map on my Delphi multi-device application. I am using TMapView component to display my map. It manages to show the map on my application, but it cannot show the user's current location on the map with a marker on it. How can I solve this? The tutorial I am referencing is from here.

A: What you could use is the option UserLocation in the TMapView.LayerOptions property as on the image below:


text:
Q: C++ Webcam Capture in VS 2012 - Library Error: "Unable to Start Program" Trying to capture video from my webcam device using Visual Studio 2012 with C++.  My goal is to be able to view live feed from a USB camera for some ROV projects. I found a website (http://www.codeproject.com/Articles/559437/Capturing-video-from-web-camera-on-Windows-and) that has a Visual Studio solution.  However, when I compile, I get an error that reads: "Unable to start program.  VideoInputVS2012\videoInput\Debug\videoInput.lib".  I tried including the library in the solution, but it didn't seem to work.  Any suggestions?

A: What type of project are you building? If it is a static library you will not be able to run it. You may want to check your Project settings for the output target type.

-----------------------Updated Edit--------------------------------------------------

The codeproject code you downloaded has a project that generaters a static .lib file.
You will need to create a another project that references this .lib file in order to use  it.
There are actually two downloads that show the .lib class being used.

*

*TestVideoInputVS2012x86.zip - uses the OpenCV framework for presenting live video

*The second example is based on the SimpleCapture example from the
Windows SDK (this code -SimpleCaptureVS2012x86.zip, application -
SimpleCaptureVS2012x86-exe.zip).

Here is also an example provided of how to call the videoInput.lib static class:
For using this library it is enough to include videoInput.h and videoInput .lib in your project. This class is made as a singleton which makes managing of resources easy.
//TestvideoInput.cpp
#include "stdafx.h"
#include "videoInput.h"
#pragma comment(lib,"videoInput.lib")

...

The codeproject being referenced and discussed was created by Evgeny Pereguda


text:
Q: Input fields aren't clickable with textarea in form. Bootstrap 3 For some reason, when I add a text area to my form using bootstrap 3, the input fields become not clickable but if I take the textarea out they seem to work fine.
My Code:

<form class="form col-lg-12" role="form">

    Your Name:
    <input type="email" class="form-control cntct" placeholder="Name" />

    Your Email Address:
    <input type="text" class="form-control cntct" placeholder="Email" />

        Your Message:
            <textarea class="form-control" rows="5" placeholder="Message"></textarea>

  <button type="submit" class="btn btn-cntct">Send Your Message</button>
</form>

Anyone's help is greatly appreciated. If you need the link to see it live, the url is http://themelux.com/dev/YouSale/ you can view the contact form at the bottom of the page.
Thanks :)

A: <form class="form col-lg-12">

    Your Name:
    <input type="email" class="form-control cntct" placeholder="Name">

    Your Email Address:
    <input type="text" class="form-control cntct" placeholder="Email">

        Your Message:
            <textarea class="form-control" rows="5" placeholder="Message"></textarea>

  <button type="submit" class="btn btn-cntct">Send Your Message</button>
</form>

A: Try giving your class col-lg-6 a higher z-index then col-lg-12.
At the moment they are overlapping.
.col-lg-6 {
    z-index:5;
}

.col-lg-12 {
     z-index:1;
}

A: The div containing your text area is on top of the div containing the text inputs.
your .col-lg-6 class is floating left and your .col-lg-12 class is not so it overlaps.
Add a float:left; to .col-lg-12 or else add a clear:left; to the div containing the textarea.

A: You should put your form contents inside rows, in this case your textarea would be on its own row. There shouldn't be any need to mess with the css of columns etc. to do this, otherwise you might wonder why you're using a grid system in the first place.
Update with code:

<form class="form col-lg-12" role="form">

          Your Name:
          <input type="email" class="form-control cntct" placeholder="Name" />

          Your Email Address:
          <input type="text" class="form-control cntct" placeholder="Email" />

          Your Message:
          <textarea class="form-control" rows="5" placeholder="Message"></textarea>

           <button type="submit" class="btn btn-cntct">Send Your Message</button>

</form>

It's not great markup (though it's better than before), but that's grid systems for you.


text:
Q: pmap data format (Julia 1.1.0) I have a function which I run using pmap. I would like the output to be a vector - p - whose entries are the output of each iteration run parallel. For illustration, the code is as below:
@everywhere function addo(mc,mcf)

p = zeros(Int64,mcf) ;

p[mc] = mc ;

return p

end

pmap(mc -> addo(mc,mcf),1:1:mcf) ;

The output I get is
100-element Array{Array{Int64,1},1}:
 [1, 0, 0, 0, 0, 0, 0, 0, 0, 0  …  0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
 [0, 2, 0, 0, 0, 0, 0, 0, 0, 0  …  0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
 [0, 0, 3, 0, 0, 0, 0, 0, 0, 0  …  0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
 ⋮
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0  …  0, 0, 0, 0, 0, 0, 0, 98, 0, 0]
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0  …  0, 0, 0, 0, 0, 0, 0, 0, 99, 0]
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0  …  0, 0, 0, 0, 0, 0, 0, 0, 0, 100]

Instead, I need something like this, p = [1,2,3,4,...,100];
How do I get the output in the desired format?

A: pmap, similar to map, applies your transformation function,mc -> addo(mc, mcf), to each element in the collection 1:1:mcf. The problem in your code is that for each element in the collection you are creating a new vector of size mcf and the overall result becomes an array of the arrays you create in each transformation, whereas what you want is the result of pmap to be of size mcf. Therefore, for each element in the collection, you should return only one element. pmap already gives you a collection grouping the results of each transformation.
@everywhere function addo(mc)
    return mc
end

p = pmap(mc -> addo(mc), 1:1:mcf)

This will give you p = [1,2,3,4,...,100].


text:
Q: pass string as system argument variable to gnuplot from python I am trying to pass a string as System Argument variable to gnuplot from python. I have done this several times before, but surprisingly it does not work this time. I used this Topic How to pass command line argument to gnuplot?, but I did not work
import subprocess
ii=2
while ii<5:
    if (ii==2):
            name='rectangular'
            a="gnuplot -e 'name="+name+ "' graph3.gp"
    if (ii==3):
            name='trapezoidal'
    if (ii==4):
            name='simpson'

    a="gnuplot -e 'name="+str(simpson)+ "' graph3.gp"
    subprocess.call(a, shell='true')
    ii=ii+1

I always get the same error message:
line 0: undefined variable: rectangular

line 0: undefined variable: trapezoidal

line 0: undefined variable: simpson

A: Couple things:

*

*call takes a list of args

*shell takes a boolean (True not 'true')

*you may have a type in trying to cast "simpson" as a string instead of name?

maybe something like:
subprocess.call(a.split(), shell=True) # or
subprocess.call(["gnuplot", "-e", "'name={}".format(str(name)), "graph3.gp"], shell=True)

A: Ok, I figured out how it can be done. Everything has to be passed as a string:
import subprocess
ii=2
while ii<5:
    if (ii==2):
             name='name="rectangular"'
    if (ii==3):
            name='name="trapezoidal"'
    if (ii==4):
            name='name="simpson"'
    a="gnuplot -e {0} graph3.gp".format(name)
    subprocess.call(a.split(), shell=False)
    ii=ii+1

~


text:
Q: Replace double quotes (within qualifiers) in CSV for SSIS import I have a SSIS package importing data from a .csv file. This file has doulbe quotes (") qualifiers for each entry in it but also in between. I also added commas (,) as a column delimiter. I can't give you the original data I'm working with but here is an example how my data is passed in Flat File Source:
"ID-1","A "B"", C, D, E","Today"
"ID-2","A, B, C, D, E,F","Yesterday"
"ID-3","A and nothing else","Today"

As you can see the second column can contain quotes (and commas) which smashes my SSIS import with an error pointing at this line.
I'm not really familiar with regular expressions, but I've heard that this might help in this case.
In my eyes I need to replace all the double quotes (") by single quotes (') except...

*

*...all quotes at the beginning of one line

*...all quotes at the end of one line

*...quotes which are part of ","
Can anyone of you help me out in this thing? Would be great!
Thanks in advance!

A: To replace double quotes with single quotes according to your specifications, use this simple regex. This regex will allow whitespace at the beginning and/or end of lines.
string pattern = @"(?<!^\s*|,)""(?!,""|\s*$)";
string resultString = Regex.Replace(subjectString, pattern, "'", RegexOptions.Multiline);

This is the explanation of the pattern:
// (?<!^\s*|,)"(?!,"|\s*$)
//
// Options: ^ and $ match at line breaks
//
// Assert that it is impossible to match the regex below with the match ending at this position (negative lookbehind) «(?<!^\s*|,)»
//    Match either the regular expression below (attempting the next alternative only if this one fails) «^\s*»
//       Assert position at the beginning of a line (at beginning of the string or after a line break character) «^»
//       Match a single character that is a "whitespace character" (spaces, tabs, and line breaks) «\s*»
//          Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
//    Or match regular expression number 2 below (the entire group fails if this one fails to match) «,»
//       Match the character "," literally «,»
// Match the character """ literally «"»
// Assert that it is impossible to match the regex below starting at this position (negative lookahead) «(?!,"|\s*$)»
//    Match either the regular expression below (attempting the next alternative only if this one fails) «,"»
//       Match the characters ","" literally «,"»
//    Or match regular expression number 2 below (the entire group fails if this one fails to match) «\s*$»
//       Match a single character that is a "whitespace character" (spaces, tabs, and line breaks) «\s*»
//          Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
//       Assert position at the end of a line (at the end of the string or before a line break character) «$»

A: You can split columns with regex match pattern
/(?:(?<=^")|(?<=",")).*?(?:(?="\s*$)|(?=","))/g

See this demo.

A: while loading CSV with double quotes and comma there is one limitation that extra double quotes has been added and the data also enclosed with the double quotes you can check in the preview of source file.
So, add the derived column task and give the below expression:-
(REPLACE(REPLACE(RIGHT(SUBSTRING(TRIM(COL2),1,LEN(COL2) - 1),LEN(COL2) - 2)," ","@"),"\"\"","\""),"@"," ")
the bold part removes the data enclosed with double quotes.
Try this and do let me know if this is helpful

A: Use text qualifier " for CSV destination
before inserting values to CSV destination, add a derived column expression
REPLACE(REPLACE([Column1],",",""),"\"","")

This will retain " in your text field


text:
Q: Bijection but not diffeomorphism Let $f:\mathbb{R}\to \mathbb{R}$ be the function defined as $$f(x) =
\begin{cases}
x+x^2\sin \frac{1}{x}, & \text{if }x\neq 0 \\
0, & \text{if }x=0.
\end{cases}$$
I want to prove the following:

*

*there are neighborhoods $U$ of $0$ and $V$ of $0$ such that $f:U\to V$ is a bijection.

*there is no neighborhood of $0$ where the function $f$ is diffeomorphism.

My approach: I think that it should be not so difficult but I am missing something.
First of all, one can show that $$f'(x) =
\begin{cases}
1+2x\sin \frac{1}{x}-\cos \frac{1}{x}, & \text{if }x\neq 0 \\
1, & \text{if }x=0.
\end{cases}$$ Also $f'(\frac{1}{2\pi n})=0$, i.e, one can find arbitrary small zero of $f'$.
I am wondering can anyone answer my questions?
Thank you!

A: I've already showed that $f'(\frac{1}{2\pi n})=0$ for each $n\geq 1$. One can check that $f''(\frac{1}{2\pi n})\neq0$. Indeed, for $x\neq 0$, we have $f''(x)=(2-\frac{1}{x^2})\sin \frac{1}{x}-\frac{2}{x}\cos \frac{1}{x}$ and hence $f''(\frac{1}{2\pi n})=-4\pi n$.
Hence $\frac{1}{2\pi n}$ is a local extrema.
Suppose that there are nbhds $U$ and $V$ of $0$ such that $f:U\to V$ is a bijection. Since $f$ is continuous on $U$, then $f$ is strictly monotone on $U$. However, $\exists N$ such that $\frac{1}{2\pi N}\in U$ and since $\frac{1}{2\pi N}$ is a local extrema, then we have a contradiction.


text:
Q: OpenMP FFTW with Fortran not thread safe I am trying to use the FFTW with openMP and Fortran, but I get wrong results when executing in parallel, which also change their values every execution step, displaying typical behaviour when parallelisation goes wrong.
I am aiming for a simple 3d real-to-complex transformation. Following the FFTW tutorial, I took all but the call to dfftw_execute_dft_r2c() out of the parallel region, but it doesn't seem to work.
I use FFTW 3.3.8, configured with ./configure --enable-threads --enable-openmp --enable-mpi and compile my code with gfortran program.f03 -o program.o -I/usr/include -fopenmp -lfftw3_omp -lfftw3 -g -Wall.
This is how my program looks like:
program use_fftw

  use,intrinsic :: iso_c_binding
  use omp_lib
  implicit none
  include 'fftw3.f03'

  integer, parameter     :: dp=kind(1.0d0)
  integer, parameter     :: Nx = 10
  integer, parameter     :: Ny = 5
  integer, parameter     :: Nz = 5
  real(dp), parameter    :: pi = 3.1415926d0
  real(dp), parameter    :: physical_length_x = 20.d0
  real(dp), parameter    :: physical_length_y = 10.d0
  real(dp), parameter    :: physical_length_z = 10.d0
  real(dp), parameter    :: lambda1 = 0.5d0
  real(dp), parameter    :: lambda2 = 0.7d0
  real(dp), parameter    :: lambda3 = 0.9d0
  real(dp), parameter    :: dx = physical_length_x/real(Nx,dp)
  real(dp), parameter    :: dy = physical_length_y/real(Ny,dp)
  real(dp), parameter    :: dz = physical_length_z/real(Nz,dp)

  integer :: void, nthreads

  integer :: i, j, k
  real(dp):: d

  complex(dp), allocatable, dimension(:,:,:)  :: arr_out
  real(dp), allocatable, dimension(:,:,:)     :: arr_in
  integer*8                                   :: plan_forward

  allocate(arr_in( 1:Nx, 1:Ny, 1:Nz));     arr_in = 0
  allocate(arr_out(1:Nx/2+1, 1:Ny, 1:Nz)); arr_out = 0

  !------------------------------
  ! Initialize fftw stuff
  !------------------------------

  ! Call before any FFTW routine is called outside of parallel region
  void = fftw_init_threads()
  if (void==0) then
    write(*,*) "Error in fftw_init_threads, quitting"
    stop
  endif
  nthreads = omp_get_num_threads()
  call fftw_plan_with_nthreads(nthreads)

  ! plan execution is thread-safe, but plan creation and destruction are not:
  ! you should create/destroy plans only from a single thread
  call dfftw_plan_dft_r2c_3d(plan_forward, Nx, Ny, Nz, arr_in, arr_out, FFTW_ESTIMATE)

  !--------------------------------
  ! Start parallel region
  !--------------------------------

  !$OMP PARALLEL PRIVATE( j, k, d)

    ! Fill array with wave
    ! NOTE: wave only depends on x so you can plot it later.
    !$OMP DO
      do i = 1, Nx
        d = 2.0*pi*i*dx
        do j = 1, Ny
          do k = 1, Nz
            arr_in(i,j,k) = cos(d/lambda1)+sin(d/lambda2)+cos(d/lambda3)
          enddo
        enddo
      enddo
    !$OMP END DO

    call dfftw_execute_dft_r2c(plan_forward, arr_in, arr_out)

  !$OMP END PARALLEL

  !-----------------
  ! print results
  !-----------------

  do i=1, Nx/2+1
    do j=1, Ny
      do k=1, Nz
        write(*,'(F12.6,A3,F12.6,A3)',advance='no') real(arr_out(i,j,k)), " , ", aimag(arr_out(i,j,k)), " ||"
      enddo
      write(*,*)
    enddo
    write(*,*)
  enddo

  deallocate(arr_in, arr_out)
  ! destroy plans is not thread-safe; do only with single
  call dfftw_destroy_plan(plan_forward)

end program use_fftw

I also tried moving the initialisation part of FFTW (void = fftw_init_threads(); call fftw_plan_with_nthreads(nthreads); call dfftw_plan_dft_r2c_3d(...) into the parallel region, using a !$OMP SINGLE block and synchronising with a barrier afterwards, but the situation didn't improve.
Can anyone help me?
EDIT: I was able to test my program on another system, the problem remains. So the issue apparently isn't in my implementation of openmp or FFTW, but somewhere in the program itself.

A: You should normally call fftw execute routines outside of the parallel region. They have their own parallel regions inside them and they will take care of running the transform in parallel with that many threads as you requested during planning. They will re-use your existing OpenMP threads.
You can also call them inside a parallel region, but on different arrays, not on the same arrays! And then your plan should be planned to use 1 thread. Each thread would then preform a 2D transform of a slice of the array, for example.
The thread-safety means you can call the routines concurrently, but each for different data.


text:
Q: Why object pointer prefix is added to the value? (Swift 4) I am trying to parse the string of characters and save them to the array:
enum Token {
    case Number(Int)
    case Minus
    case Plus
}

var tokens = [Token]()

for char in ["1","-","3","+","9"] {switch char {
        case "0"..."9":
            //start of a number - need to grab the rest
            let digit = Int(String(char))!
            tokens.append(.Number(digit))
        case "+":
            tokens.append(.Plus)
        case "-":
            tokens.append(.Minus)
        default:
            //smth unexpected - need to send back an error
            print("ends...")
        }
}

print(tokens)

But the values are added with prefixes, that look like pointers. The result of the code above is:
[__lldb_expr_14.Token.Number(1), __lldb_expr_14.Token.Minus, __lldb_expr_14.Token.Number(3), __lldb_expr_14.Token.Plus, __lldb_expr_14.Token.Number(9)]

How can I get read of this prefixes so that the resulted array looked as:
[Token.Number(1), Token.Minus, Token.Number(3), Token.Plus, Token.Number(9)]

And why were these prefixes added?

A: This happens because your Token type does not implement CustomStringConvertible. You should implement it.
enum Token : CustomStringConvertible {
    case Number(Int)
    case Minus
    case Plus

    var description: String {
        // return a string that describes "self"
    }
}

One possible way to implement this is:
var description: String {
    switch self {
        case .Number(let x): return "Number(\(x))"
        case .Minus: return "Minus"
        case .Plus: return "Plus"
    }
}

Also note that enum cases should be in camelCase instead of PascalCase.


text:
Q: For what $k$ does $ \lim_{n \to \infty} k \uparrow\uparrow n $ converge? Let $k \in \mathbb{R}$; for what $k$ does
$$ \lim_{n \to \infty} k \uparrow\uparrow n $$
converge?
Note: The double up-arrow refers to Knuth's up-arrow notation, so $k \uparrow\uparrow n$ means $n$ levels of $k^{k^{\dots}}$.

A: This answer only covers the case of positive $k$. For $k \in (0, 1]$ the limit trivially converges. The case $k > 1$ is covered below.
finding upper bound
Assuming the limit converges to a real number $x$, we have
\begin{align}
k^x &= x \\
x \ln k &= \ln x \\
\ln k &= \frac{\ln x}{x} =: f(x)
\end{align}
The function $f$ looks like this. WolframAlpha tells us that
$$ \max_{x > 0} f(x) = f\left( \frac{1}{e} \right) = \frac{1}{e} $$
Therefore the upper bound of $k$ is
$$ k_0 = e^{1/e} \approx 1.445 $$
proof
Now we need to prove our assumption above, i.e. the limit does converge within the entire interval $(1, k_0]$. First pick any $k$ in the interval. Let $x_0$ be a solution to $k^x = x$ with the given $k$; from the plot we can see that $k > 1 \implies x_0 > 1$. Then, construct a sequence $\{a_n\}$ such that $a_0 = 1$, and $a_{i+1} = k^{a_i}$ (in other words, $a_n = k \uparrow\uparrow n$) for all natural number $i$. The first few terms look like
$$ a_1 = k, \quad a_2 = k^k, \quad a_3 = k^{k^k}, \quad \ldots $$
Since $a_0 = 1 < x_0$, and for any $i \in \mathbb{N}$
$$ a_i < x_0 \quad \implies \quad a_{i+1} = k^{a_i} < k^{x_0} = x_0 $$
By induction we know that the entire sequence $\{a_n\}$ is strictly smaller than $x_0$. In addition, we know that $a_1 = k > 1 = a_0$, and for any positive $i$ we have
$$ a_i > a_{i-1} \quad \implies \quad a_{i+1} = k^{a_i} > k^{a_{i-1}} = a_i $$
By induction we know that the sequence $\{a_n\}$ is strictly increasing. In other words, the sequence is bounded in interval $[1, x_0)$. Because the metric space for $\mathbb{R}$ (with the canonical metric and order operator) is compact, monotonic and bounded sequence converges. Q.E.D.


text:
Q: Why did i get this "module 'nltk.translate.metrics' has no attribute 'precision'"? import codes, i've tried importing precision and all the library i still can't get it work
import nltk
import string
import pandas as pd
import nltk.metrics
import collections

from nltk import precision
from nltk.metrics.scores import (accuracy, precision, recall, f_measure,log_likelihood, approxrand)
from nltk import precision
from nltk.tag import pos_tag
from nltk.tokenize import word_tokenize
from nltk.tokenize import sent_tokenize
from nltk.stem.wordnet import WordNetLemmatizer
from nltk import classify
from nltk.corpus import stopwords
from nltk import NaiveBayesClassifier
from random import shuffle
from nltk.metrics.scores import (precision, recall)

the codes below are the codes i use to implement the codes
path = os.path.join('c:' + os.sep, 'Users', 'User', 'Documents', 'Reviews_Labeled.csv')
df = pd.read_csv(path)

positive = []
negative = []
for i in range(0,df.shape[0]):
    if df.iloc[i][1] == 'Positive':
        positive.append(df.iloc[i][0])
    else:
        negative.append(df.iloc[i][0])

positive_tokens = []
for i in positive:
    positive_tokens.append(word_tokenize(i))

negative_tokens = []
for i in negative:
    negative_tokens.append(word_tokenize(i))

def is_clean(word: str):
    if word in string.punctuation:
        return False
    if word.isnumeric():
        return False
    if word in stopwords.words('english'):
        return False
    return True

def clean_tokens(tokens: list):
    return [word.lower() for word in tokens if is_clean(word)]

positive_tokens_cleaned = [clean_tokens(tokens) for tokens in positive_tokens]
negative_tokens_cleaned = [clean_tokens(tokens) for tokens in negative_tokens]

lemmatizer = WordNetLemmatizer()

def lemmatize(word: str, tag: str):
    if tag.startswith('NN'):
        pos = 'n'
    elif tag.startswith('VB'):
        pos = 'v'
    else:
        pos = 'a'
    return lemmatizer.lemmatize(word, pos)

def lemmatize_tokens(tokens: list):
    return [lemmatize(word, tag) for word, tag in pos_tag(tokens)]

positive_tokens_normalized = [lemmatize_tokens(tokens) for tokens in positive_tokens_cleaned]
negative_tokens_normalized = [lemmatize_tokens(tokens) for tokens in negative_tokens_cleaned]

dataset = positive_dataset + negative_dataset

shuffle(dataset)

train_ds = dataset[:5126]
test_ds = dataset[5126:]

classifier = NaiveBayesClassifier.train(train_ds)
classify.accuracy(classifier, test_ds)

when i'm searching other people question this is the way people call out the precision value and other metrics value
refsets = collections.defaultdict(set)
testsets = collections.defaultdict(set)

for i, (feats, label) in enumerate(test_ds):
    refsets[label].add(i)
    observed = classifier.classify(feats)
    testsets[observed].add(i)

this is the code i use to try and print the precision value
print(nltk.metrics.scores.precision(refsets['pos'],testsets['pos']))

this is the error i got

print(nltk.metrics.precision(refsets['pos'],testsets['pos']))

this also give the same error
so how do i solve the error message what did i do wrong?

A: I have the same issue as you, and here's my solution:
print(nltk.precision(refsets['pos'],testsets['pos']))

I noticed that the error was the attribute error, showing that it is trying to access to the ntlk.translate.metrics which certainly do not have the precision function you want.
Instead, the precision function that you wanted is located in at the ntlk.metrics.score.
Which both of the module serves a very different purpose.
My guess is the compiler is just having hard time finding the ntlk.metrics.score module with the calling you did.
You can refer to the ntlk documentation for more detail implementation of the ntlk.metrics.score
https://www.nltk.org/api/nltk.metrics.scores.html

A: nltk.scores.precision also should work.


text:
Q: A gambler with 3 alike dice. Here's the problem:- We are given 3 alike dice and (this problem had multiple parts when I tried it, Here I am taking only one scenario) it is said that we will win the game if the sum of numbers appearing on the dice is less than 11(strictly).We are given only a single throw(in which you throw all 3 alike dice together). We are required to find the probability that we win.
Here is how I approached the problem.Lets 1st of all assume that the dice arn't alike but distinct so the 3 dice can show numbers like (113),(131),(311)
Then I thought that "simply because you cant distinguish between the dice doesn't mean that occuring of of the sum 5 should include only 113 and 122. ie the probability that the sum 5 occurs shouldn't be simply 2/216"
That made me realize that I should treat the dice as distinct So I went ahead with this idea of treating dice as distinct. This follows that I should calculate all possible combinations of nubers on 3 dices with sum less than 11. hence only possilibilties of sum is {3,4,5...10}
to calculate this i used beggars method:-
$$x_1+ x_2+x_3 =y$$ where $y\subset{3,4,5...10}$ and $x_1,x_2,x_3$ are all greater than 1
solving this for all y in the set yeilds:-
$${9\choose2}+{8\choose2}+{7\choose2}+{6\choose2}+{5\choose2}+{4\choose2}+{3\choose2}+{2\choose2}$$
Ok so this yeilds${10\choose3}$=120 ie the total no of ways =120 hence probability =120/216. But it comes out be 1/2. Kindly tell where am i wrong.

A: I don't understand where you're getting the various $\binom k2$ components of your summand, but there are a couple of different ways to approach the problem.  The easiest is to use symmetry.  Note that for each die, $n_i$ and $7-n_i$ are equally likely.  Thus, $\sum n_i$ and $21-\sum n_i$ are equally likely.  That means the numbers $3$ through $10$ and the numbers $11$ through $18$ are equally likely, and those two cases exhaust the sample space, so your probability must be $\frac 12$.
Alternatively, the number of solutions in positive integers of $n_1+n_2+n_3 \leq 10$ with each $1 \leq n_i \leq 6$ is the same as the number of solutions in non-negative integers of $m_1+m_2+m_3 \leq 7$ with each $m_i \leq 5$, which is the same as the number of solutions with $m_i \leq 5$ of $m_1+m_2+m_3+z=7$.  Use stars-and-bars to see that there are $\binom{10}{3}=120$ unconstrained solutions to this equation.
From this, you have to subtract the number of solutions for which $m_i \geq 6$ for some $i$.  It's easy to see that for each $i$ there are $4$ "forbidden" solutions, for a total of $4 \cdot 3=12$.  Thus, the total number of permissible solutions is $120-12=108$, which is exactly half of $216$.
It looks like you may have overlooked the constraint that no single die can give a result greater than $6$.

A: The roll of three dice $(a,b,c)$ where $1 \le a,b,c \le 6$ is equally likely as the roll $(7-a,7-b,7-c)$. So if $X=a+b+c$, then $P(X=x)=P(X=21-x)$; i.e., the distribution of the sum of the three dice is symmetrical about $21/2$.  Consequently, $P(X \le 10) = P(X \le 21/2) = 1/2$.

A: A very simple approach which struck me is literally to count desired cases since the cases are limited and easy to count, as below:
$1$. numbers on the dice are different:
$$(1,2,3),(1,2,4),(1,2,5),(1,2,6),(1,3,4),(1,3,5),(1,3,6),(1,4,5),(2,3,4),(2,3,5);$$
hence in this state we have $10\times6=60$ cases.
$2$. two of numbers on the dice are the same:
$$(1,1,2),(1,1,3),(1,1,4),(1,1,5),(1,1,6),(2,2,1),(2,2,3),(2,2,4),(2,2,5),(2,2,6),$$
$$(3,3,1),(3,3,2),(3,3,4),(4,4,1),(4,4,2);$$
hence in this state we have $15\times3=45$ cases.
$3$. all numbers on the dice are the same:
$$(1,1,1),(2,2,2),(3,3,3);$$
hence in this state we have $3\times1=3$ cases.
Therefore, the result is $\frac{60+45+3}{216}=0.5$.


text:
Q: How to spy on an activity In my instrumentation/unit test, I'd like to verify that an Activity's method is called in onCreate (when app is launched AND while it is already open) and onNewIntent.
I've tried ActivityTestRule, but I ran into two problems:

*

*I have to invoke onNewIntent on the ui thread, because it modifies the view. So I'm forced to do something like Thread.sleep to wait for the task to finish

*It's impossible to spy the activity in the rule without hacking the library

I've also looked into Robolectric, but it seems like it has a reputation for being flaky and slow.
Any suggestions for possible approaches with Espresso or Mockito or a different testing framework?


text:
Q: Rsync error 23: some files were not transferred, when copying files from Windows drive to external HDD I wanted to copy files from the Windows drive to external HDD using rsync, with the following command:
rsync -azv --progress --exclude-from '/home/mint/exclude.txt' '/media/mint/OS/' '/media/mint/external_hdd/C_drive_backup/'

In exclude.txt I had Windows, Program Files and ProgramData folders, since I don't need them. So I initiated the command given above and went to sleep. When I woke up, here's what I got:
sent 169,748,362,821 bytes  received 3,982,112 bytes  16,898,347.01 bytes/sec
total size is 193,085,110,161  speedup is 1.14
rsync error: some files/attrs were not transferred (see previous errors) (code 23) at main.c(1183) [sender=3.1.0]

So should I be worried that something didn't get copied? If I use the command du -hs /media/mint/OS/* | sort -h and calculate the total size I should get, it's something around 187 GB (compared to rsync's output in bytes to gigabytes: 169,748,362,821 -> ~158GB. 193,085,110,161 -> ~179GB.)
Can I see which files/folders did not get copied? If I scroll up, I can see the last 200 lines and all of those have 100% completion.
Should I just copy the files again? Or is there a way to compare the files on external HDD and the Windows drive?

A: If you haven't saved the whole output from rsync, then the only way to find what wasn't copied is to run another traversal to compare. You might as well run rsync again: its whole point is not to transfer what has already been transferred. Don't pass the -v parameter so that you won't be overwhelmed by boring output.
rsync -aq … 2>rsync.err

(You can use rsync -anq … to compare without transferring, but if you've just made a copy, it won't copy anything again, so -n doesn't make any difference in this scenario.)

A: If neither the source or destination has been changed, an option is to run rsync again with the -n switch to see what what would be transferred without copying data. Adding -q will suppress regular output, only displaying files that could not be transferred.
rsync -azvqn --exclude-from '/home/mint/exclude.txt' '/media/mint/OS/' '/media/mint/external_hdd/C_drive_backup/'

A: When I was facing exactly same error (while copying a folder from remote ubuntu server to my local ubuntu pc), I could resolved this easily, by changing the source location to be at root (made it less deep).
If that wouldn't have resolved the problem, next step would have been to choose target location too as less deep, as possible.


text:
Q: Lost magnification under Mountain Lion I am missing one nice feature after moving to Mountain Lion. I was able on Lion to press control and  drag with two fingers to magnify an area of the screen, which is particularly helpful when working with image editors that lack this function.
Was this merely a key binding that was removed, or has the feature itself been abandoned?

A: The feature is still present and you might be able to set it up again as follows according to this Apple Support page:

For example, if you have a trackpad and used the default settings,
  zoom in by holding down the Control (^) key while you drag two fingers
  up on the trackpad. Zoom out by holding down the Control key while you
  drag two fingers down on the trackpad.

Check System Preferences => Accessibility => Zoom (under Seeing) to make sure that you have Use scroll gesture with modifier keys to zoom enabled.


text:
Q: JQuery fade out problems? In Rails Hey guys, attached below is my code, and then my CSS. They item fades in correctly, but wont seem to fade out.

Set

Cancel

Class for defer-pop:
.defer-pop{
    -moz-border-radius: 10px;
    border-radius: 10px;
    -webkit-border-radius: 10px;
    border:1px solid #CCC;
    position:relative;
    top:-80px;
    left:-90px;
    background-color:#fff;
    background-image: -webkit-gradient(
        linear,
        left bottom,
        left top,
        color-stop(0, rgb(212,212,212)),
        color-stop(0.62, rgb(245,245,245))
    );
    background-image: -moz-linear-gradient(
        center bottom,
        rgb(212,212,212) 0%,
        rgb(245,245,245) 62%
    );
    display:none;
    width:200px;
    height:80px;
    font-size:10px;
     box-shadow:0px 1px 0px #ababab;
    -webkit-box-shadow:0px 0px 10px #ababab;
    -moz-box-shadow:0 1px 0px #ababab;
}

Any help would be great!
Thanks

A: I believe this is because set-22 is a child of click-22 and the event handler for click on click-22 is fired when set-22 is clicked.  To confirm this, put logging or alert statements in both event handlers.  To stop this behavior, use event.stopImmediatePropagation() which prevents all other event handlers from firing, or event.stopPropagation() to prevent parent event handlers from firing in the child's event handler:
$("#click-22").click(function() {
    $("#22").fadeIn("slow");
});
$("#set-22").click(function(event) {
    event.stopImmediatePropagation();
    $("#22").fadeOut("slow");
});

stopImmediatePropagation() prevents the event from propagating up to parent elements, and prevents other event handlers from firing.  I tweaked your example and have it working here: http://jsfiddle.net/andrewwhitaker/a4ffk/
Other notes:

*

*Don't use numbers as ids.  This violates the W3 specification and can cause problems with your script in some browsers.

A: HTML

Set

Cancel

Javascript

Css for my help
.defer-pop{
    width:200px;
    height:200px
}

Remember include jquery.js above  tag
and tip-
you should be writing your code in
$(document).ready(function(){
    //your logic here
});


text:
Q: Dynamically create CLR object from the string As a result of some service action I'm getting in the result property string with value "MyNamespace.Models.Car"
How can I dynamically create the object (empty) from this string value? Or how else can I dynamically recognize clr type from this string?
var result = service.getSomeData(req);
result.CustomVal holds the value of "MyNamespace.Models.Car";

Note that I cannot change the service.

A: With reflection you can find all types in assembly, then use Activator.CreateInstance Documenation


text:
Q: Combinations of a String The following was a job interview question which I struggled with.
(Unnecessary switching between list and set, tested it and realised it was missing an expected output, too many steps).
If possible, looking for the proper answer or maybe a guide on how I should have tackled the problem. Thank you.
Question: Give a String, find all possible combinations from it (Front and Reverse).
Print all combinations and total count of combinations. Order doesn't matter.

Example s = 'polo'
Front Answer = 'p', 'po', 'pol', 'polo', 'ol',
'olo', 'lo', 'o', 'l'.
Reverse Answer: 'o', 'ol', 'olo', 'olop',
'lop', 'op', 'p', 'l'.

My answer:
count = 0
count2 = -1
length = len(s)
my_list = []
for i in s:
    temp = s[count:]
    temp2 = s[:count2]
    my_list.append(i)
    my_list.append(temp)
    my_list.append(temp2)
    count += 1
    count2 -= 1

my_set = set(my_list)
for f in my_set:
    print(f)
print(len(my_set)) # Answer for front

new_list = []
for f in my_set:
    new_list.append(f[::-1])

print('Reverse Result:')
for f in new_list:
    print(f)
print(len(new_list)) # Answer for reverse

A: You can do this with two nested for-loops. One will loop through the start indexes and the nested one loops through the end indexes (starting from the start + 1 going to the length of s +1 to reach the very end).
With these two indexes (start and end), we can use string slicing to append that combination to the list forward. This gives you all the combinations as you see below.
To get the reversed ones, you could do a for-loop as you have done reversing the order of the forward ones, but to save the space, in the code below, we just append the same index but sliced from the reversed s (olop).
s = "polo"

forward = []
backward = []
for start in range(len(s)):
    for end in range(start+1, len(s)+1):
        forward.append(s[start:end])
        backward.append(s[::-1][start:end])

print(forward)
print(backward)
print(len(forward) + len(backward))

which outputs:
['p', 'po', 'pol', 'polo', 'o', 'ol', 'olo', 'l', 'lo', 'o']
['o', 'ol', 'olo', 'olop', 'l', 'lo', 'lop', 'o', 'op', 'p']
20

If you really wanted to make the code clean and short, you could do the same thing in a list-comprehension. The logic remains the same, but we just compress it down to 1 line:
s = "polo"

forward = [s[start:end] for start in range(len(s)) for end in range(start+1, len(s)+1)]
backward = [c[::-1] for c in forward]

print(forward)
print(backward)
print(len(forward) + len(backward))

which gives the same output as before.
Hope this helps!

A: Try this:
   string = "polo"
   x = [string[i:j] for i in range(len(string)) for j in range(len(string),0,-1) if j > i ]
   x.sort()
   print("Forward:",x[::-1])
   print("Reverse:",x[::])


text:
Q: shopping in vs shopping on I would like to know if there is a difference in the following sentence depending on the preposition. Both seem to be correct.
I saw a celebrity while I was shopping in/on Oxford St.
Thank you!

A: Typically, you shop "in" a specific store, market, mall, village square, etc. You shop "on" a street. "I was shopping in Oxford St." wouldn't actually be correct, although the audience would understand what was meant. "I was shopping in a store on Oxford St." would be accurate.


text:
Q: 'posts_per_page' in costum page type i have a problem with the 'posts_per_page'- no matter that i set it to, e.g 10 or 0, it always only show one post!
<?php $loop = new WP_Query( array( 'post_type' => 'producenter', 'posts_per_page' => 0, 'orderby' => 'rand', 'post__not_in' => array($post->ID) ) ); ?>

Andre leverandører:

<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>

<a href="<?php the_permalink(); ?>">
<?php the_post_thumbnail(); ?>

<?php the_title(); ?>

<?php if( get_field( "deloverskrift" ) ): ?>

<?php the_field( "deloverskrift" ); ?>

<?php endif; ?>

<?php endwhile; ?>

A: 0 isn't a valid value for posts_per_page. WordPress will see it as empty and default to the posts_per_page option. If you want all the posts use nopaging or posts_per_page => -1.
$query = new \WP_Query([
  'post_type' => 'producenter',
  'nopaging' => true,
  'orderby' => 'rand',
  'post__not_in' => [$post->ID],
]);

As far as why it's only showing 1 post, is that what you have set in the default posts per page option? Not sure why it would only show one post if you set posts_per_page to 10.


text:
Q: ELF replace WSL-path to Windows-Path (GCC / ARM / CortexM) If you build a cortexM firmware on linux (WSL in this case), the resulting *.elf file for debugging will carry "nix" paths, example:
/home/user/project/
/home/user/project/Src/main.c
/home/user/project/Inc
/home/user/project/Inc/Legacy
/home/user/project/FreeRTOS/task.c

Im looking for a solution to replace those paths inside the ELF file automatically as the project is too large to do it by hand every time.

*

*Tried GDB Command "set substitute-path"
set substitute-path /home/user/project D:\workspace\project\
set substitute-path /home/user/project D:\\workspace\\project\\
Both cases did not work.

*Tried GCC build and link Command:
"-fdebug-prefix-map=/home/user/project=D:\workspace\project"
"-fdebug-prefix-map=/home/user/project=D:\\workspace\\project\\"
Both (1) and (2) did not work, as it seems it just replaces the beginning of a file path but then leaves the remaining path untouched, eg
D:\workspace\project\Src/main.c


text:
Q: Linux Change directory shortcut I am using Bourne shell in Linux and I am trying to create a shortcut in my .profile to quickly jump between subdirectories.
I want to create a shortcut "cds" jump from the first directory to the 2nd below. These are just sample directories for his example.
/web/site/dev1/css
/web/site/test1/css
Usage:  cds dev1 test1
cds() {
   echo `pwd` | sed -e "s/$1/$2/g"
   cd `pwd` | sed -e "s/$1/$2/g"
   pwd
}

The echo works but the cd line does not. Can you tell me why it does not work and how to get it to work? Thanks for your help.

A: In your function, when you do
   echo `pwd` | sed -e "s/$1/$2/g"

the output from echo is being piped into sed and the change is made. sed will print its output to the standard output.
However, cd doesn't write anything to the output, so you're cding to the current directory (pwd) and then piping the (empty) output into sed to replace the directory. Instead, you can call cd with the argument of the output of pwd piped through sed.
Here is the code you want instead:
cds() {
  cd $(pwd | sed -e "s/$1/$2/g")
  pwd
}

First, this evaluates the code inside the $(), namely pwd | sed -e "s/$1/$2/g". pwd prints the current path to stdout, and sed replaces the part of the path given by the arguments. So $(pwd | sed -e "s/$1/$2/g" evaluates to the new directory. Then, cd goes to that directory.


text:
Q: How do I create blank space between rows in tkinter? I am aware that in tkinter padx and pady are supposed to create padding outside of the object; and ipady and ipadx are supposed to create padding inside the object. In my case pady seems to also be creating padding inside an object.
The code I've used:
from tkinter import *

screen = Tk()

input_field = Entry(screen, bd=0.5, width=25, font=('Calibri', 16, 'bold')).grid(column=0, row=0, columnspan=3, padx=10, pady=10, ipady=13, ipadx=20)
button1 = Button(screen, bd=0.5, text="1", padx=40, pady=35, font=('Calibri', 16, 'bold')).grid(column=0, row=3)
button2 = Button(screen, bd=0.5, text="2", padx=40, pady=35, font=('Calibri', 16, 'bold')).grid(column=1, row=3)
button3 = Button(screen, bd=0.5, text="3", padx=40, pady=35, font=('Calibri', 16, 'bold')).grid(column=2, row=3)
button4 = Button(screen, bd=0.5, text="4", padx=40, pady=35, font=('Calibri', 16, 'bold')).grid(column=0, row=2)
button5 = Button(screen, bd=0.5, text="5", padx=40, pady=35, font=('Calibri', 16, 'bold')).grid(column=1, row=2)
button6 = Button(screen, bd=0.5, text="6", padx=40, pady=35, font=('Calibri', 16, 'bold')).grid(column=2, row=2)
button7 = Button(screen, bd=0.5, text="7", padx=40, pady=35, font=('Calibri', 16, 'bold')).grid(column=0, row=1)
button8 = Button(screen, bd=0.5, text="8", padx=40, pady=35, font=('Calibri', 16, 'bold')).grid(column=1, row=1)
button9 = Button(screen, bd=0.5, text="9", padx=40, pady=35, font=('Calibri', 16, 'bold')).grid(column=2, row=1)

screen.mainloop()

Output:
Code output
How would I go about solving this?

A: Use pady in grid(pady = 5) and it works fine
from tkinter import *

screen = Tk()

input_field = Entry(screen, bd=0.5, width=25, font=('Calibri', 16, 'bold')).grid(column=0, row=0, columnspan=3, padx=10, pady=10, ipady=13, ipadx=20)
button1 = Button(screen, bd=0.5, text="1", padx=40, pady=35, font=('Calibri', 16, 'bold')).grid(column=0, row=3, pady=5)
button2 = Button(screen, bd=0.5, text="2", padx=40, pady=35, font=('Calibri', 16, 'bold')).grid(column=1, row=3, pady=5)
button3 = Button(screen, bd=0.5, text="3", padx=40, pady=35, font=('Calibri', 16, 'bold')).grid(column=2, row=3, pady=5)
button4 = Button(screen, bd=0.5, text="4", padx=40, pady=35, font=('Calibri', 16, 'bold')).grid(column=0, row=2, pady=5)
button5 = Button(screen, bd=0.5, text="5", padx=40, pady=35, font=('Calibri', 16, 'bold')).grid(column=1, row=2, pady=5)
button6 = Button(screen, bd=0.5, text="6", padx=40, pady=35, font=('Calibri', 16, 'bold')).grid(column=2, row=2, pady=5)
button7 = Button(screen, bd=0.5, text="7", padx=40, pady=35, font=('Calibri', 16, 'bold')).grid(column=0, row=1, pady=5)
button8 = Button(screen, bd=0.5, text="8", padx=40, pady=35, font=('Calibri', 16, 'bold')).grid(column=1, row=1, pady=5)
button9 = Button(screen, bd=0.5, text="9", padx=40, pady=35, font=('Calibri', 16, 'bold')).grid(column=2, row=1, pady=5)

screen.mainloop()

P.S. I like to make a class for similar buttons so I don't have to write all settings again for each button


text:
Q: Junk values ([39m[22m[0m) in text file copied from Linux to Windows I am running a Angular build using  command "ng build" and redirecting output to a text file in Linux machine.
When I open the text file in Linux machine, I can see like below:
Date: 2018-06-06T15:02:32.798Z
Hash: 0f42957c12b1984f5d9d
Time: 177103ms
chunk {common} common.chunk.js, common.chunk.js.map (common) 6.77 MB  [rendered]
chunk {image.module} image.module.chunk.js, image.module.chunk.js.map () 443 kB  [rendered]
chunk {inline} inline.bundle.js, inline.bundle.js.map (inline) 5.83 kB [entry] [rendered]
chunk {main} main.bundle.js, main.bundle.js.map (main) 1.01 MB [initial] [rendered]

but, when I scp the file to Windows machine and while opening it in notepad, I am getting like below:
[0mDate: [1m[37m2018-06-06T15:02:32.798Z[39m[22m[0m
[0mHash: [1m[37m0f42957c12b1984f5d9d[39m[22m[0m
[0mTime: [1m[37m177103[39m[22mms[0m
[0mchunk {[1m[33mcommon[39m[22m} [1m[32mcommon.chunk.js, common.chunk.js.map[39m[22m (common) 6.77 MB [1m[32m [rendered][39m[22m[0m
[0mchunk {[1m[33mimage.module[39m[22m} [1m[32mimage.module.chunk.js, image.module.chunk.js.map[39m[22m () 443 kB [1m[32m [rendered][39m[22m[0m
[0mchunk {[1m[33minline[39m[22m} [1m[32minline.bundle.js, inline.bundle.js.map[39m[22m (inline) 5.83 kB [1m[33m[entry][39m[22m[1m[32m [rendered][39m[22m[0m
[0mchunk {[1m[33mmain[39m[22m} [1m[32mmain.bundle.js, main.bundle.js.map[39m[22m (main) 1.01 MB [1m[33m[initial][39m[22m[1m[32m [rendered][39m[22m[0m

How do I resolve this issue?


text:
Q: The difference between some sentences with adjective+noun+to do smt/for I was told that

"We are looking for an eager person to work for our company"

is not the same as

"We are looking for a person who is eager to work for our company"

, but the same as

"We are looking for a person to work for our company, who is eager."

So it means that "An eager person to do smt" is not the same as "A person eager to do smt"
Okay..
If this logic is correct,
Does "the hardest book for me" mean "the book for me which is the hardest" ?
or
does "the most difficult book for me to read" mean "the book for me to read, which is the most difficult" ?
I believe that there is definitely a problem here.
In my opinion;

The hardest book for me to read is Inferno. = The book which is the hardest for me to read is Inferno.
"You are the most amazing friend to hang out with." = "You are the friend who is the most amazing to hang out with."

There is something wrong because what I was told is not working properly.

A: The bit you are missing is that eager can take a complement (introduced by for, or a to-infinitive clause), and when it does it has a different meaning from eager without a complement.
Neither hard nor amazing has this property. You can say that something is hard for somebody, but that narrows its scope, it doesn't change the basic meaning. (Structurally, this suggests that the for argument is an adjunct rather than a complement)

A:
The most difficult book for me to read...

is a rather clumsy way of putting the words together, though you will hear it from the mouths of native speakers.
If the idea is that the book is complicated and difficult, far more so than any other book under consideration, the phrase that belongs together is most difficult to read.
If the idea is that the book is complicated and difficult for me in particular, although someone else might not find it so, the phrase that belongs together is
most difficult for me to read.

The book most difficult for me to read is X.

for me can be moved to the head of the sentence:

For me, the book most difficult to read is X.


text:
Q: How to simply downsample a triangular mesh? This requirement occur when I show the surface mesh in Matlab by trisurf, because the mesh is dense (high-resolution) and it is rendered slowly and can not be rotated. So I am wondering there is some intuitive method to downsample the mesh while keep the basic shape ?
Before I post the question here, I have Googled. A popular tool iso2mesh, has a similar function, remeshsurf.  But it firstly reconstruct the volume by the original mesh and the construct the new mesh according to the desired resolution. An important flaw, in my opinion, is that it change the original shape.
Anyone has some idea ? The Matlab function would be the best since it is easy to be tested.
Thanks.
Nico

A: You should downsample your data,
[x,y]=meshgrid(1:15,1:15);
tri = delaunay(x,y);
z = peaks(15);
trisurf(tri,x,y,z)
figure
x1 = x(1 : 2 : end,1 : 2 : end);
y1 = y(1 : 2 : end,1 : 2 : end);
z1 = z(1 : 2 : end,1 : 2 : end);
tri1 = delaunay(x1,y1);
trisurf(tri1,x1,y1,z1)

You could even use downsample function on each data.

A: @Kamtal (Originally I added this post as a comments but it prompts "too long post")Many thanks. I guess, your method is a good choice only when the hull of the shape is obviouse. For other cases, for an instance, the cortex of a human brain, the Matlab delaunay function is not smart enough to re-generate the triangular mesh while reserving the basic shape (fold). Here (about 1.7M) I have uploaded an example which describes a surface of the cortex (both left and right hemisphere). It could be displayed by the following code,

    load mysurf.mat;
    figure, trisurf(mysurf.tri, mysurf.coord(:,1),mysurf.coord(:,2),mysurf.coord(:,3));
    view(-90,0);
    daspect([1 1 1]); axis tight; camlight; axis vis3d off;
    lighting phong;
    material shiny;
    shading interp;


text:
Q: проблема с MediaPlayer? public void soundPlay(MediaPlayer sound) {
    if (sound.isPlaying())
    sound.pause();
    else
    {   sound.start();
      sound.setLooping(true); } }

public void soundPlay2(MediaPlayer sound) {
    if (sound.isPlaying()) {
        sound.pause();
    }
    }

Здравствуйте, я только учусь программированию. Сейчас работаю над музыкой в приложение, использую самый простой код для музыки в андроид приложениях, но теперь его недостаточно. Мне нужно чтобы:

*

*Музыка не накладывалась друг на друга если пользователь нажимает назад и обратно заходит (т.к. музыка будет фоном).

*При сворачивание приложения музыка останавливалась.

*При звонке музыка останавливалась.

Подскажите пожалуйста как это всё реализовать либо ссылку где я могу найти ответы на свои вопросы. Желательно на русском языке. Все мои попытки найти ответы в гугле не увенчались успехом, во всех уроках что я нашел по музыке нет ответов именно на мои потребности.


text:
Q: Issue with converting ES query to sort nested objects by key and value to Java API (ES version 6.2) I would like to convert the below ES query to Java API
{
  "sort": [
{
  "nested_objects.Value": {
    "order": "desc",
    "nested_path": "nested_objects",
    "nested_filter": {
      "term": { "nested_objects.Key": "abc" }
      }
     }
   }
  ]
}

Tried to write a query as below but looks like the previously working methods are now deprecated in ES 6.2
FieldSortBuilder mySort = SortBuilders.fieldSort("nested_objects.Value")
                .setNestedFilter(QueryBuilders.nestedQuery("nested_objects",
                        QueryBuilders.termQuery("nested_objects.Key", "abc"), ScoreMode.Avg))
                .order(SortOrder.DESC);

setNestedFilter() appears to be deprecated any alternatives?

A: I've copied the below text from this Deprecated List Link
org.elasticsearch.search.sort.FieldSortBuilder.getNestedFilter()
set nested sort with FieldSortBuilder.setNestedSort(NestedSortBuilder) and retrieve with FieldSortBuilder.getNestedSort()

org.elasticsearch.search.sort.FieldSortBuilder.getNestedPath()
set nested sort with FieldSortBuilder.setNestedSort(NestedSortBuilder) and retrieve with FieldSortBuilder.getNestedSort()

You can see how they mentioned that you would need to make use of NestedSortBuilder
Below is what you can do. Simply create a Term Query using QueryBuilder and make use of it in setFilter method chaining to setNestedSort.
    QueryBuilder query = QueryBuilders.boolQuery()
            .must(QueryBuilders.termQuery("nested_objects.Key", "abc"));

    FieldSortBuilder mySort = SortBuilders.fieldSort("nested_objects.Value")
            .order(SortOrder.DESC)
            .setNestedSort(new NestedSortBuilder("nested_objects")
            .setFilter(query));

Hope it helps!


text:
Q: How to fix PHP "Invalid Argument Supplied For Foreach()" <?php
include "config.php";
if(isset($_FILES['berkas'])){
    foreach ($_FILES['berkas']['name'] as $file=>$name){
        $filename = date('Ymd-His',time()).mt-rand().'-'.$name;
        try{
            if(move_uploaded_file($_FILES['berkas']['tmp_name'][$file], 'uploads/'.$filename));{
                $stmt= $db->prepare("insert into multipleload values('',?)");
                $stmt ->bindParam(1,$filename);
                $stmt->execute();

            }
        } catch (Exception $e){
            echo $e;
        }

    }
}
?>

Error is on line 3
I've already tried if(is_array()){ } but it doesn't stop error message.
I'm trying to make a document submission php file btw. I've looked through previous posts and have really only found that clearly its not getting an array.

A: foreach expects the variable that will loop through to be an array .
and it seems that $_FILES['berkas']['name'] is not an array it is represent a string of the file name so . you should use it like this
foreach ($_FILES['berkas'] as $file => $name ){
    // your code here
}

A: it's because the structure of $_FILES is as follows:
$_FILES[fieldname] => array(
    [name] => array( /* these arrays are the size you expect */ )
    [type] => array( /* these arrays are the size you expect */ )
    [tmp_name] => array( /* these arrays are the size you expect */ )
    [error] => array( /* these arrays are the size you expect */ )
    [size] => array( /* these arrays are the size you expect */ )
);

So when you're trying to iterate over _FILES you're supplying an array as opposite to an associative array. Instead, your foreach should look like:
foreach ($_FILES['berkas'] as $type=>$value) {
    // if $type is 'name', do something
}

If you're trying to iterate over just the name, you can do
foreach ($_FILES['berkas']['name'] as $name) {
    // if $type is 'name', do something
}

A: You probably want to loop through the $_FILES superglobal like so:
foreach ($_FILES as $file => $data) {

where $data will be an array containing keys 'name', 'type', 'size', etc. See http://php.net/manual/en/features.file-upload.post-method.php for more info about how this works.


text:
Q: Google docs: Insert TOC through scripting I have a Google Document with paragraphs formatted as Heading 1 and Heading 2. I would like to create a table of content (TOC) in the document by script, not manually.
I have tried to find a tutorial or something like that, but I cannot. Maybe because this is not possible? Do I have to make the TOC by using the menu in Docs?
All I could find is: Class TableOfContents
Please let me know if a scripted TOC is possible.

A: Some elements in Google Docs, including TableOfContents, can't be inserted programmatically. From GAS documentation:

Elements shown in bold can be inserted; non-bold elements can only be
  manipulated in place.

More details here https://developers.google.com/apps-script/guides/docs


text:
Q: How can I base64 encode using Fable (F#)? I use FetchAPI of Fable.PowerPack to make basic authentication application, but I am in trouble because I can not base64 encode.
For example, I wrote such a code,
let base64enc str =
    str
    |> Seq.map byte
    |> Array.ofSeq
    |> System.Convert.ToBase64String

However, the following error occurs.
Error FABLE: Can not find replacement for System.Convert.ToBase64String
Is there any way?

A: I think the JavaScript btoa function does what you need. The easiest and quickest way to make it available in Fable is to use the Emit attribute:
[<Emit("btoa($0)")>]
let toBase64String (bytes:byte[]) : string = failwith "JS"

There might be some slight differences between the .NET method and the JS function, in which case you'll probably need to reimplement those on your own.
Also, this sounds like a thing that Fable could support - the replacements for .NET operations are generally defined in the Replacements.fs file and if you were interested in sending a pull request to add mapping for ToBase64String and others, that would be amazing!


text:
Q: How to only show important node's name on the networkx graph? The graph looks messy and barely recognize anything.
I only want it to show the name of nodes with high centrality,
but I don't know how. I can only show all the names now.
Graph:the result of the following codes

G_D=nx.Graph() G_D.add_edges_from(G5.edges(data=True))
nx.draw(G_D,nx.spring_layout(G_D),node_size=[v * 10 for v in
  df.iloc[:,0]],with_labels= True)

A: nx.draw has an argument labels, which in combination with with_labels=True can draw only labels you want, only how you want.

labels (dictionary, optional (default=None)) – Node labels in a
  dictionary keyed by node of text labels

For example, you can pick nodes 'label' parameter and draw labels for nodes that have 3 or more neighbours:
labels = {
    n: (G.nodes[n]['label']
        if len(list(nx.all_neighbors(G, n))) > 2
        else '')
    for n in G.nodes
}
nx.draw(G, with_labels=True, labels=labels)

P.S. I don't recommend to use basic networkx drawing functional. There are many powerful visualization libraries better than networkx. Even in networkx docs you can find the same opinion. One can use Gephi, Graphviz (with various libraries) or Cytoscape for really HUGE graphs.


text:
Q: Is it possible to put an Image on a colored Rectangle with iText? I'm working on a Java project and I'd like to know if iText allows to put an Image object on a Rectangle object (this rectangle is filled with a color). In alternative, if it is not possible, how can I do? Thanks!

A: You are probably adding the rectangle using PdfContentByte and the behavior you described tells me that you are adding the Image using document.add().
If you obtained the PdfContentByte using PdfWriter.getDirectContent(), all the content you add to that canvas will be on top of the content you add with Document.add(). You should use PdfWriter.getDirectContentUnder() if you want it the other way round.
However, since you already have a PdfContentByte instance anyway, it could be easier to replace:
document.add(image);

with:
pdfContentByte.addImage(image);

That way, the image will also cover the rectangle (provided that you add the image after drawing the rectangle).


text:
Q: How to solve the differential equation $y' = \frac{x+y}{x-y}$? Solve the following differential equation:

$y' = \frac{x+y}{x-y}$

Someone please help me start this problem. This does not look like a regular first-order differential equation in the form  $y' + 2xy = x$. Thank you.

A: Hint: It's homogenous of degree 1 which suggests the substitution
$$
y=xv\implies y'=xv'+v
$$
and
$$
xv'+v=\frac{x+xv}{x-xv}=\frac{1+v}{1-v}\stackrel{\text{algebra}}{\implies}
\frac{1-v}{v^2+1}\mathrm dv=\frac{1}{x}\mathrm dx\implies \int \frac{1-v}{v^2+1}\,\mathrm dv=\ln x+c\\
\implies \int\frac{1}{v^2+1}\,\mathrm dv-\int \frac{v}{v^2+1}\,\mathrm dv=\ln x+c\\
\implies\arctan(v)-\frac{1}{2}\ln (v^2+1)=\ln x+c\\
\implies\arctan\left(\frac{y}{x}\right)-\frac{1}{2}\ln \left(\frac{y^2}{x^2}+1\right)=\ln x+c
$$
and I am afraid we will have to be satisfied with the implicit solution.
edit: Following @Artem's suggestion we can rewrite this curve in polar coordinates and it simplifies nicely, although the caveat is it makes $y$'s role difficult to
see
$$
\arctan\left(\frac{y}{x}\right)-\frac{1}{2}\ln \left(\frac{y^2}{x^2}+1\right)=\ln x+c\\
\implies \theta-\ln \left(\sqrt{\frac{r^2}{r^2\cos^2 \theta}}\right)-\ln r\cos \theta=c\\
\implies \theta+\ln (\cos \theta)-\ln (r\cos \theta)=c\\
\implies \theta+\ln\left(\frac{1}{r}\right)=c\\
\implies \theta-c=-\ln\left(\frac{1}{r}\right)=\ln r\\
\implies Ae^{\theta}=r
$$


text:
Q: Clarification on SKLearn's 'neg_root_mean_squared_error' score If I'm running some RFECV runs with various regressors, using neg_root_mean_squared_error as the scoring metric, when I executed the score = rfe.score(X_train, y_train) line, I get scores that look like this:

So, which of these would be a "better" score? I thought neg_root_mean_squared_error would produce a negative number? So if these are positive, would I want to aim for the LOWER numbers?
Thanks!

A: The RFECV's score method is still just a delegate to its model's score method, and so for these probably the R2 score, not your negative rmse. The negative rmse is being used to determine which number of features to select; you can also see some of those scores in the grid_scores_ or cv_results_ attribute, and can use the mean_squared_error metric function to find those scores for the refit estimator.