How convert Hex number to Hex escaped Sequence(i.e. \x equivalent) in a lua

Question: In various languages, hex values shows as \xhh values in a string literal by using the \x escape sequence

I using encrypting library in lua and hex ouptut is like:

e6dd6bf41a97b89980b2bc2e838bd1bb746b83139b4c1e7c73bdedcc18a01ec24e26703a60cc19d29750c22084470da889e67375afcd9b12595748f6b6ce2d7b436d56ab84e70c819ef52b1edf63148b0ee2cce672ff4d57115c7b51abaaf8a7

but in python library output is:

\xe6\xddk\xf4\x1a\x97\xb8\x99\x80\xb2\xbc.\x83\x8b\xd1\xbbtk\x83\x13\x9bL\x1e|s\xbd\xed\xcc\x18\xa0\x1e\xc2N&p:`\xcc\x19\xd2\x97P\xc2 \x84G\r\xa8\x89\xe6su\xaf\xcd\x9b\x12YWH\xf6\xb6\xce-{CmV\xab\x84\xe7\x0c\x81\x9e\xf5+\x1e\xdfc\x14\x8b\x0e\xe2\xcc\xe6r\xffMW\x11\\{Q\xab\xaa\xf8\xa7

how can i convert Hex number to Hex escaped sequence?
Answer: Here is an example code, some characters may fall out, but the gist is this:
local s= [[e6dd6bf41a97b89980b2bc2e838bd1bb746b83139b4c1e7c73bdedcc18a01ec24e26703a60cc19d29750c22084470da889e67375afcd9b12595748f6b6ce2d7b436d56ab84e70c819ef52b1edf63148b0ee2cce672ff4d57115c7b51abaaf8a7]]

function escape (s)
      return string.gsub(s, '..', function (c)
            local ch = tonumber(c,16)
            if ch==10 then return '\\n'
            elseif ch==13  then return '\\r' -- 9 and \\t ?
            elseif ch==92  then return '\\\\'
            elseif 0x1F<ch and ch<0x7f then return string.char(ch)
            else  return string.format("\\x%s", c)
            end
          end)
 end

 print (escape (s) )

maybe there are more elegant solutions with definition of exception characters.


arquivos batch - encontrar diretorio do arquivo atual

Question: Eu tenho um arquivo batch que faz o cmd apontar para outro diretório.
Mas em um certo momento, preciso que ele volte para o diretório do próprio arquivo batch. É possível  fazer isso?
Answer: No início do código pode salvar o diretório que o arquivo batch está com o comando:
set backDir=%cd%

E depois voltar para ele com o comando:
cd %backDir%

Answer: Sugiro uso do cd /d %~dp0:
cd /d altera o drive atual + o diretório atual para o drive e o diretório onde o batch foi inicialmente executado:
:: você pode criar uma variável:
set "_cd_batch_path=cd /d "%~dp0" "

:: ou simplesmente usar o command:

cd /d "%~dp0"

sempre que for necessário voltar use a variavel %_cd_batch_path% ou simplesmente "cd /d %~dp0":
%_cd_batch_path%

:: ou ::

!_cd_batch_path!

:: ou ainda ::

cd /d "%~dp0"

Comment: Olá caro kapptuz, entendi o que disse sobre o >null e >nul, quando notar erros de digitação assim vocÊ pode comentar diretamente na resposta, somos uma comunidade, toda critica e revisão de texto e código é aceita. Obrigado!


Get inward and outward codes from UK postal code

Question: I'm trying to find a way to split a UK postcode from the user entry. The initial entry is validated by the below regex and it's working fine.
var regex = @"^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))[0-9][A-Za-z]{2})$";

Now I need to split the postcode into outward and inward codes so that I can send them separately to the client's ERP to get the shipping cost.
Example.

User input: DD81UN
  Desired output: DD8 1UN
User input: DN551PT
  Desired output: DN55 1PT
Comment: What's the logic to separate outward and inward codes?
Comment: http://www.mrs.org.uk/pdf/postcodeformat.pdf
Answer: Only adding spaces:
As per the wikipedia entry on outward and inward codes for UK Postal codes, the rules are as follows:

An outward code is between two and four characters long
An inward code is three characters long

So if you have already extracted the code, to add spaces or split, simply add a space before the 3rd character from the end since the inward code is always 3 characters in length:
string extractedCode = "DD81UN";
extractedCode = extractedCode.Insert(extractedCode.Length - 3, " ");
// Output: DD8 1UN

Improving the Regular expression:
Based on the rules in the link you shared, here's a better version of the regex, that extracts UK Postal Codes from any text, even if they contain a space:
\b([A-PR-UWYZ](?:(?:\d{1,2}|\d[A-HJ-KSTUW])|(?:[A-HK-Y]\d(?:\d|[A-Z])?)))\s?(\d[ABD-HJLNP-UW-Z]{2})\b

\b represents word boundary at start and end
([A-PR-UWYZ](?:(?:\d{1,2}|\d[A-HJ-KSTUW])|(?:[A-HK-Y]\d(?:\d|[A-Z])?))) is the first capturing group to match outward code which may be two to four characters in length.

[A-PR-UWYZ] since the first character cannot have Q, V or X
(?:\d{1,2}|\d[A-HJ-KSTUW]) allows formats AN, ANN and ANA and restricts characters as per the rules in the third position
(?:[A-HK-Y]\d(?:\d|[A-Z])?)) allows formats AAN, AANN and AANA and doesn't allow I, J and Z in the 2nd position

\s? matches an optional space between outward and inward codes.
(\d[ABD-HJLNP-UW-Z]{2}) is the second capturing group for outward codes. It allows one digit followed by two characters as per the rules.

Regex101 Demo

The letters Q, V and X are not used in the first position
The letters I,J and Z are not used in the second position.
The only letters to appear in the third position are A, B, C, D, E, F, G, H, J, K, S, T, U and W.
The second half of the postcode is always consistent numeric, alpha, alpha format and the letters C, I, K, M, O and
V are never used.

If your objective is to only match and add space, match using above and replace with $1 $2 since the above regex matches outward codes in the first group and inward codes in the 2nd group.
Here's a dotnet fiddle which demonstrates the same.
string input = "sample DD81UN DN55 1PT WRONG text 123456";
Regex r = new Regex(@"\b([A-PR-UWYZ](?:(?:\d{1,2}|\d[A-HJ-KSTUW])|(?:[A-HK-Y]\d(?:\d|[A-Z])?)))\s?(\d[ABD-HJLNP-UW-Z]{2})\b");

// To add spaces between each codes
string output = r.Replace(input, "$1 $2");

// To get all codes
var results = r.Matches(output);

Comment: Great. I was not sure about the length of the inward code. This works perfectly now. Thanks a lot.
Comment: @samithagun added a dotnet fiddle demo as well as some explanation for the regex. If the answer helped solve your problem, you might want to mark it as accepted answer. Thanks!
Answer: Try This.
namespace UKPostCodeConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string firstPostCode = "DD81UN";
            string secondPostCode = "DN551PT";
            Console.WriteLine(ParseToUkPostcode(firstPostCode));
            Console.WriteLine(ParseToUkPostcode(secondPostCode));
            Console.Read();
        }
        public static string ParseToUkPostcode(string aPostcode)
        {
            string finalPostcode = aPostcode;

            finalPostcode = finalPostcode.Replace(" ", "").Trim();
            string outWardResult = finalPostcode.Substring(0, finalPostcode.Length - 3);
            string inWardResult = finalPostcode.Substring(Math.Max(0, finalPostcode.Length - 3));
            string postCodeResult = string.Format("{0} {1}", outWardResult, inWardResult);
            finalPostcode = postCodeResult;

            return finalPostcode;
        }
    }
}

OUTPUT

Hope it solves your problem


HTML Form. When to use named frame in target attribute?

Question: In HTML Form  we can set target attribute to various values: <code>_blank|_self|_parent|_top|framename</code>.
But what is use case of named frame in target attribute?
Answer: This is relevant if you are using frames for your page layout, however frames are rarely used these days.
Comment: Frames are no longer supported in HTML5 so this particular use of framename should be considered deprecated. It should still work with iframes however.
Answer: According to the docs you can specify the name of an iframe that you want the response to be displayed in.
http://www.w3schools.com/tags/att_form_target.asp#
(from docs) Note: Frames and framesets are not supported in HTML5, so the _parent, _top and framename values are now mostly used with iframes.


After Swift 3 conversion, I can't get rid of error: "Ambiguous use of 'indexOfObject(passingTest:)'"

Question: I'm using NSArray's indexesOfObjects(passingTest:), but after I converted my code to Swift 3 I get the error: "Ambiguous use of 'indexOfObject(passingTest:)'".
My code below worked fine with Swift 2.3.
let indexesOfBubbleConstraints = bubbleConstraints.indexesOfObjects(passingTest: { (constraint, idx, stop) in
        if let view = constraint.firstItem as? UIView{
            return view.tag == usernameTag
        }
        else{
            return false
        }
    })

For Swift 3, I also had to cast constraint to AnyObject, but that doesn't fix the actual problem.
I ended up using func indexesOfObjects(options: NSEnumerationOptions = [], passingTest: (Any, Int, UnsafeMutablePointer<ObjCBool>) -> Bool) with an empty Array for options as below. This works, but I still don't understand why I'm getting the "Ambiguous..." error with my original implementation.
let indexesOfBubbleConstraints = bubbleConstraints.indexesOfObjects(options: [], passingTest: { (constraint, idx, stop) in
        if let view = (constraint as AnyObject).firstItem as? UIView{
            return view.tag == usernameTag
        }
        else{
            return false
        }
    })

Answer: In Objective-C, the two indexesOf methods are distinct two methods:
- (NSIndexSet *)indexesOfObjectsPassingTest:(BOOL (NS_NOESCAPE ^)(ObjectType obj, NSUInteger idx, BOOL *stop))predicate NS_AVAILABLE(10_6, 4_0);
- (NSIndexSet *)indexesOfObjectsWithOptions:(NSEnumerationOptions)opts passingTest:(BOOL (NS_NOESCAPE ^)(ObjectType obj, NSUInteger idx, BOOL *stop))predicate NS_AVAILABLE(10_6, 4_0);

And now, Swift 3 import those as ambiguous two methods:
@available(iOS 4.0, *)
open func indexesOfObjects(passingTest predicate: (Any, Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> IndexSet

@available(iOS 4.0, *)
open func indexesOfObjects(options opts: NSEnumerationOptions = [], passingTest predicate: (Any, Int, UnsafeMutablePointer<ObjCBool>) -> Bool) -> IndexSet

One is indexesOfObjects(passingTest:), and another is indexesOfObjects(options:passingTest:). And unfortunately, Swift 3 has given a default value for the parameter options, which has made a simple call like bubbleConstraints.indexesOfObjects(passingTest: ...) ambiguous.
It may be calling

indexesOfObjects(passingTest:)

or

indexesOfObjects(options:passingTest:) with giving default value to options

(Swift should not give a default value, if it causes this sort of ambiguity. Better send a bug report.)
In this case, your workaround code, using indexesOfObjects(options:passingTest:) should work, but there is another work around:
bubbleConstraints.indexesOfObjects(passingTest:) {constraint, idx, stop in
    //...
}

The method reference .indexesOfObjects(passingTest:) returns the method indexesOfObjects(passingTest:) as a closure, and the above expression is calling it.

By the way, you better consider using Swift's collection methods, rather than using an NSArrays method:
let indexesOfBubbleConstraints = bubbleConstraints.enumerated().lazy
    .filter {(idx, constraint) in
        //...
    }.map{$0.offset}

Comment: Great detailed answer! I also appreciate your last comment and will definitely do as you recommend.


Identification of the infinitely dimensional unit sphere

Question: I have some doubts about a statement from class:
Let $\mathbb{R}^\omega$ be the countable product of $\mathbb{R}$. Equip $\mathbb{R}^\omega$ with the scalar product $\sum_{k = 1}^\infty x_i y_i$ and the induced norm. We identify $\mathbb{R}^n$ with the space generated by the first $n$ coordinates. Let $S^\infty = \bigcup_n S^n \subset \mathbb{R}^\omega$ ($S^n$ being the unit sphere in $\mathbb{R}^n$) and let $B^\infty = \{(x_k)_{k \in \mathbb{N}} \mid \sum_{k = 1}^\infty x_k^2 = 1\}$. Show that we can identify $S^\infty$ with $B^\infty$.
What bothers me about this question is that clearly $S^\infty \subset B^\infty$. However, I could take the sequence $(0, \frac{\sqrt{6}}{\pi} \frac{1}{1},  \frac{\sqrt{6}}{\pi}  \frac{1}{2}, \frac{\sqrt{6}}{\pi}  \frac{1}{3} , \dotsc)$. This sequence has norm $1$ under the assumptions in the statement. But the sequence also has infinitely many non-zero elements. So how can it be in on of the $S^\infty$?
Comment: You didn't define $S^n$.
Comment: thank you, I fixed it
Comment: The statement does seem false as stated, by the reasoning presented. As a side note, you could also use a zenos paradox sequence like $(0, 1/\sqrt{2}, 1/\sqrt{4}, 1/\sqrt{8}, \dots)$ instead of the Basel sequence. Also, it looks like there are some square roots missing in your Basel sequence.
Comment: oh yes, thank you. I started with the Basel sequence and then forgot about the square roots^^
Comment: Perhaps it's asking for identifying the closure of $S^\infty$ with $B^\infty$.
Comment: Thank you for your input. I double checked and it is not.
Comment: @mathology I'm curious, were you ever able to determine what they meant by this question? Did you mention your counterexample, and what was their response?
Answer: If $\mathbb{R}^\omega$ is the countable product of $\mathbb{R}$, then $\sum_{k = 1}^\infty x_i y_i$ does not define a scalar product because the series may diverge.
Thus we have to restrict to either
$$\ell^2 = \{ (x_n) \in \mathbb{R}^\omega \mid \sum_{n = 1}^\infty x_n^2 < \infty\}$$
or to
$$\ell^2_0 = \{ (x_n) \in \mathbb{R}^\omega \mid x_n = 0 \text{ for almost all } n\} \subset \ell^2.$$
Then we get a scalar product and an induced norm.
If we work in $\ell^2$, then $S^\infty \subsetneqq B^\infty$ as you correctly stated in your question.
However, if we work in $\ell^2_0$, then trivially  $S^\infty = B^\infty$.


Cannot download ace using Grunt and shell (Codebox) Permission errors (Virtual Macine)

Question: Working from Codebox 0.8.1
Here is a Gist containing the 3 files that Codebox uses to build its editor addon.
I am on windows running virtualbox ubuntu/precise64 through vagrant in administrative cmd when running npm install all I am fine but when I run sudo npm start I receive the following:
Building addons in ./addons/ (force=false)
Optimizing cb.files.editor
error for optimization of cb.files.editor
options= { baseUrl: 'addons/cb.files.editor',
  name: 'client',
  out: '/project/addons/cb.files.editor/addon-built.js',
  paths: { 'require-tools': '/project/core/cb.addons/require-tools' },
  optimize: 'uglify',
  map:
   { '*':
      { css: 'require-tools/css/css',
        less: 'require-tools/less/less',
        text: 'require-tools/text/text' } } }
{ [Error: Command failed: node /project/node_modules/requirejs/bin/r.js -o baseUrl=addons/cb.files.editor name=client out=/project/addons/cb.files.editor/addon-built.js paths.requi
re-tools=/project/core/cb.addons/require-tools optimize=uglify map.*.css=require-tools/css/css map.*.less=require-tools/less/less map.*.text=require-tools/text/text  (exited with e
rror code 1)]
  killed: false,
  code: 1,
  signal: null,
  stdout: '\nTracing dependencies for: client\nError: ENOENT, no such file or directory \'/project/addons/cb.files.editor/ace/ace.js\'\nIn module tree:\n    client\n      ace\n\nEr
ror: Error: ENOENT, no such file or directory \'/project/addons/cb.files.editor/ace/ace.js\'\nIn module tree:\n    client\n      ace\n\n    at Object.fs.openSync (fs.js:432:18)\n\n
',
  stderr: '' }

If I run npm start (no sudo):
Running "exec:build_files_editor" (exec) task
>> npm
>>
>> WARN
>>
>> package.json
>> firstname.lastname@example.com No repository field.
>> npm
>>
>> WARN
>>
>> package.json
>> firstname.lastname@example.com No README data

> firstname.lastname@example.com postinstall /project/addons/cb.files.editor
> ./download_ace.sh && ./build.sh

>> sh: 1:
>> ./download_ace.sh: not found
>>
>> npm ERR! weird error 127
>> npm
>> WARN This failure might be due to the use of legacy binary "node"
>> npm WARN For further explanations, please read
>> /usr/share/doc/nodejs/README.Debian
>> npm
>>
>> ERR!
>>
>> not ok
>> code 0
>> Exited with code: 1.
Warning: Task "exec:build_files_editor" failed. Use --force to continue.

Any help would be great?
Answer: After breaking the problem down, and trying to execute each shell script individually I found it was a problem with Windows line endings in my Linux VM.
The solution dos2unix by using this library I was able to convert all the files in the project to LF (Linux) line endings.
After entering the project directory all I had to do was run this command:
find . -type f -exec dos2unix {} \;

Now if I run npm start the project compiles correctly.
For any other user encountering this problem I recommend setting up your IDE to default to LF line endings using EditorConfig.


Posicionar elementos na horizontal

Question: Tenho o seguinte trecho de código, mas todos os elementos vem um em baixo do outro, gostaria que eles viesse um ao lado do outro, é possível sem ter que mexe na posição de cada elemento separadamente?

10

20

30

40

50

60

70

80

90

100

110

120

130

Answer: Elementos
 são por padrão em bloco (estilo do user agent usa display: block;), então basta trocar por ou outro elemento que seja inline, como , algo como:

    10
    20
    30
    40
    50
    60
    70
    80
    90
    100
    110
    120
    130

Note que se os elementos atingirem a largura limite do elemento pai ou do view-port (ou do body, depende de como configurou) você poderia usar white-space: nowrap;, exemplo:

.back {
    white-space: nowrap;
}

    10
    20
    30
    40
    50
    60
    70
    80
    90
    100
    110
    120
    130
    10
    20
    30
    40
    50
    60
    70
    80
    90
    100
    110
    120
    130
    10
    20
    30
    40
    50
    60
    70
    80
    90
    100
    110
    120
    130

Comment: Legal, não sabia disso, obrigado
Comment: Ainda não posso aceitar a resposta, mas quando liberarem eu aceito
Comment: @JeffHenrique teste antes com calma, não tem prazo para aceitar a resposta, pode aceitar ela quando estiver confiante que resolveu o  seu problema, se não tiver resolvido basta comentar aqui.
Comment: Ok, mas eu testei e funcionou como queria, obrigado

Posicionar elementos na horizontal


Android Help with stopping activity crashing (FC) when no internet connection is present

Question: I have followed a tutorial to download images remotely, it works fine when an internet connection is present, but when you launch the activity with no internet connection present the activity crashes "force Closes"
I'am unfortunately an android novice so i'm not sure what to do to stop it crashing. Is their a way to just toast a message stating "Sorry Internet is required" with a blank screen, nothing fancy, just to stop it crashing.
Hope someone can show me how to do this,
Thankyou
Lucy
private ImageAdapter imageAdapter;

private ArrayList<String> PhotoURLS = new ArrayList<String>();

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
      this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN ,
            WindowManager.LayoutParams.FLAG_FULLSCREEN );

    setContentView(R.layout.galleryview);

    public static boolean isDataConnectionAvailable(Context context){
        ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        if(info == null)
            return false;

        return connectivityManager.getActiveNetworkInfo().isConnected();
    }

    imageAdapter = new ImageAdapter(this);
    final ImageView imgView = (ImageView) findViewById(R.id.GalleryView);
    Gallery g = (Gallery) findViewById(R.id.Gallery);
    g.setAdapter(imageAdapter);
    g.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v,
                int position, long id) {
            imgView.setImageDrawable(LoadImageFromURL(PhotoURLS
                    .get(position)));
            imgView.setScaleType(ImageView.ScaleType.FIT_XY);
        }
    });

    // replace this code to set your image urls in list
    PhotoURLS.add("http://domain.com/image-286.jpg");
    PhotoURLS.add("http://domain.com/image-285.jpg");
    PhotoURLS.add("http://domain.com/image-284.jpg");
    PhotoURLS.add("http://domain.com/image-283.jpg");
    PhotoURLS.add("http://domain.com/image-282.jpg");
    PhotoURLS.add("http://domain.com/image-281.jpg");

    new AddImageTask().execute();

}

class AddImageTask extends AsyncTask<Void, Void, Void> {
    @Override
    protected Void doInBackground(Void... unused) {
        for (String url : PhotoURLS) {
            String filename = url.substring(url.lastIndexOf("/") + 1,
                    url.length());
            filename = "th_" + filename;
            String thumburl = url.substring(0, url.lastIndexOf("/") + 1);
            imageAdapter.addItem(LoadThumbnailFromURL(thumburl + filename));
            publishProgress();
            //SystemClock.sleep(200);
        }

        return (null);
    }

    @Override
    protected void onProgressUpdate(Void... unused) {
        imageAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onPostExecute(Void unused) {
    }
}

private Drawable LoadThumbnailFromURL(String url) {
    try {
        URLConnection connection = new URL(url).openConnection();
        String contentType = connection.getHeaderField("Content-Type");
        boolean isImage = contentType.startsWith("image/");
        if(isImage){
            HttpGet httpRequest = new HttpGet(url);
            HttpClient httpclient = new DefaultHttpClient();
            HttpResponse response = (HttpResponse) httpclient
                    .execute(httpRequest);
            HttpEntity entity = response.getEntity();
            BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(entity);

            InputStream is = bufferedHttpEntity.getContent();
            Drawable d = Drawable.createFromStream(is, "src Name");
            return d;
        } else {
            Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.no_image);
            Drawable d = new BitmapDrawable(b);
            return d;
        }
    } catch (Exception e) {
        Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_LONG)
                .show();
        Log.e(e.getClass().getName(), e.getMessage(), e);
        return null;
    }
}

private Drawable LoadImageFromURL(String url) {
    try {
        URLConnection connection = new URL(url).openConnection();
        String contentType = connection.getHeaderField("Content-Type");
        boolean isImage = contentType.startsWith("image/");
        if(isImage){
            HttpGet httpRequest = new HttpGet(url);
            HttpClient httpclient = new DefaultHttpClient();
            HttpResponse response = (HttpResponse) httpclient
                    .execute(httpRequest);
            HttpEntity entity = response.getEntity();
            BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(
                    entity);
            InputStream is = bufferedHttpEntity.getContent();

            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(is, null, o);

            // The new size we want to scale to
            final int REQUIRED_SIZE = 320;

            // Find the correct scale value. It should be the power of 2.
            int width_tmp = o.outWidth, height_tmp = o.outHeight;
            int scale = 1;
            while (true) {
                if (width_tmp / 2 < REQUIRED_SIZE
                        || height_tmp / 2 < REQUIRED_SIZE)
                    break;
                width_tmp /= 2;
                height_tmp /= 2;
                scale *= 2;
            }

            // Decode with inSampleSize
            is = bufferedHttpEntity.getContent();
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            Bitmap b = BitmapFactory.decodeStream(is, null, o2);
            Drawable d = new BitmapDrawable(b);
            return d;
        } else {
            Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.no_image);
            Drawable d = new BitmapDrawable(b);
            return d;
        }
    } catch (Exception e) {
        Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_LONG)
                .show();
        Log.e(e.getClass().getName(), e.getMessage(), e);
        return null;
    }
}

public class ImageAdapter extends BaseAdapter {
    int mGalleryItemBackground;
    private Context mContext;

    ArrayList<Drawable> drawablesFromUrl = new ArrayList<Drawable>();

    public ImageAdapter(Context c) {
        mContext = c;
        TypedArray a = obtainStyledAttributes(R.styleable.GalleryTheme);
        mGalleryItemBackground = a.getResourceId(
        R.styleable.GalleryTheme_android_galleryItemBackground, 0);
        a.recycle();
    }

    public void addItem(Drawable item) {
        drawablesFromUrl.add(item);
    }

    public int getCount() {
        return drawablesFromUrl.size();
    }

    public Drawable getItem(int position) {
        return drawablesFromUrl.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView i = new ImageView(mContext);

        i.setImageDrawable(drawablesFromUrl.get(position));
        i.setLayoutParams(new Gallery.LayoutParams(70, 110));
        i.setScaleType(ImageView.ScaleType.FIT_CENTER);
        //i.setBackgroundResource(mGalleryItemBackground);

        return i;

    }

}

}

Answer: you can check connection availability:
public static boolean isDataConnectionAvailable(Context context){
        ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        if(info == null)
            return false;

        return connectivityManager.getActiveNetworkInfo().isConnected();
    }

Note: Add permission to your manifest file:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Comment: Hi, Thankyou for the quick reply, like i said i'am a novice, so i'am not sure where i would put this in the code i have posted. If possible could someone add it to the code, with a comment line explaining what its actually doing to stop it crashing. This way i may be able to remember in the future what is happening and how it is working. Thankyou, Lucy
Comment: call the above fucntion isDataConnectionAvailable and if it returns true then execute your code...
Comment: Hi, I have added the above code, (see edited code above) but i seem to get errors, please could you have a look to see what i have done or more importantly not done correctly. How do i call the above function so if internet is available execute the rest of the code, and if no internet toast a message "no internet". Thankyou for your help so far
Answer: I can confirm Vineet's answer is good as I had the same issue.
My code that was not working is as follows:
public boolean isOnline() {

final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo networkInfo = cm.getActiveNetworkInfo();
boolean connected = networkInfo.isConnected();

    if (connected)
        return true;
    else
        return false;

}
And the issue with my above example is that networkInfo.isConnected() does not appear to have a value.  I was setting a boolean value to null, which (and yes my Java is sketchy since I am a newbie) I believe is not allowed, hence the app would throw up an exception and crash.
Here is now I solved it using Vineet's solution.
public boolean isOnline() {

final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo networkInfo = cm.getActiveNetworkInfo();

if(networkInfo == null)
    return false;
else
    return networkInfo.isConnected();

}
Now, it works correctly and the app no longer crashes.  Hope this solution helps someone.  And I suspect a JAVA guru will be able to better explain the issue with setting boolean to Null not being allowed.


BizTalk and Visual Studio 2017

Question: Can Visual Studio 2017 be used for BizTalk project work?
I seemed to get issues when I open a solution file that relates to BizTalk using Visual Studio 2017.
i.e. Errors re. the .btproj files.

Error is "the application which this project type is based on was not found."
  Please try this link for further information: http://go.microsoft.com/fwlink/?LinkID=299083&projecttype=EF7E3281-CD33-11D4-8326-00C04FA0CE8D

This link doesn't seem to specifically mention Visual Studio 2017 be used for BizTalk project work.
Comment: I wondered why this question is "put on hold" ? This is yes / no type of answer to this question ?
Comment: This site https://social.msdn.microsoft.com/Forums/en-US/9e0a4bbf-c13f-4027-a85f-8ec1351937c2/vs2017-biztalk-project-templates-install?forum=biztalkgeneral    says BizTalk 2016 it is VS 2015 only, you cannot use VS 2017
Comment: This is a very good question. I am surprised why it is negatively voted. Going to upvote it.
Answer: Each version of BizTalk requires a specific version of Visual Studio. Currently the latest version is BizTalk 2016, which requires Visual Studio 2015 see Hardware and Software Requirements for BizTalk Server 2016
When BizTalk 2020 comes out it will be Visual Studio 2019. So no, you can't use Visual Studio 2017 for BizTalk development
Note: You will have needed to run the BizTalk Setup and installed the Developer SDK after you have installed the correct Visual Studio.

BizTalk 2020 projects require Visual Studio 2019
BizTalk 2016 projects require Visual Studio 2015
BizTalk 2013 R2 projects require Visual Studio 2013
BizTalk 2013 projects require Visual Studio 2012
BizTalk 2010 projects require Visual Studio 2010

With Visual Studio 2019 you also have to install an extension, see Biztalk 2020 - Project not showing in Visual Studio 2019
Comment: BizTalk projects are install thru the extensions of VSTudio.
Comment: @PhilippePecqueur For Visual Studio 2019/BizTalk 2020, yes, earlier version not.

BizTalk and Visual Studio 2017


How to append a time/datestamp to a file name in an html file

Question: I have an html form with an image upload section and it works fine, however for data management reasons I would like the image file name to have the time/datestamp added to it when it uploads.
What used to happen, was that if the file would be uploaded via a phone it would be called image.jpg which would be overwritten if a new file by the same name would be uploaded (understandably)
However what I want to have happen, is that the file would be called something like image091118151821 for the 11 September 2018 15:18:21. or something like that.
The HTML Form:
<form method="POST" action="incident-submit.php" enctype="multipart/form-data">
div class="element-date">Date<input class="large" data-format="yyyy-mm-dd" type="date" name="date" placeholder="yyyy-mm-dd"/>

Division<input class="large" type="text" name="input" />

Location within Division<input class="large" type="text" name="input1" />

Employee Division<input class="large" type="text" name="input2" />

Cause of events<textarea class="large" name="textarea" cols="20" rows="5" ></textarea>

<input type="file" name="image">

  <button type="submit" name="upload">POST</button>

And the PHP that submits the data to the database:
// If upload button is clicked ...
  if (isset($_POST['upload'])) {
    // Get image name
    $image = $_FILES['image']['name'];
    // Get text

    $date = $_POST['date'];
    $division = $_POST['input'];
    $location = $_POST['input1'];
    $employeedivision = $_POST['input2'];
    $events = $_POST['textarea'];

    // image file directory
    $target = "img/".basename($image);

...
    if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
    $msg = "Image uploaded successfully";
}else{
    $msg = "Failed to upload image";
}

I then changed the
$image = $_FILES['image']['name'];

line to:
$image = $_FILES['image'.date('m-d-Y_hia').'.jpg']['name'.date('m-d-Y_hia').'.jpg'];

And it seems to not upload anything
Is there a way I can cause that to happen, it does not have to be done in php, javascript is also fine
Could someone help me solve this conundrum?
Thanks in advance
Comment: Possible duplicate of [How to change name of uploaded file in php?](https://stackoverflow.com/questions/20444798/how-to-change-name-of-uploaded-file-in-php)
Answer: Using the handy pathinfo() function you can dig out all the seperate parts of a filename. Then just use those and the date() function to build the filename of your choice.
$path_parts = pathinfo($_FILES['image']['name']);

$dest_filename = $path_parts['filename'] . date('mdyHis') . '.' . $path_parts['extension'];

// image file directory
$target = "img/$dest_filename";

If you want to seperate the filename from the date to make it a little easier to read you could try
$dest_filename = $path_parts['filename'] .
                 '_' .
                 date('mdyHis') .
                 '.' .
                 $path_parts['extension'];

Answer: You need to change this line
$target = "img/".basename($image);

to:
$target = "img/".basename(explode('.',$image)[0] . date('m-d-Y_hia') . explode('.',$image)[1]);

Comment: Thank you, it nearly works, the only thing is, that the "." is missing before the file extention. .i.e. IMG_794409-11-2018_0858amJPG instead of IMG_794409-11-2018_0858am.JPG
Comment: Be careful using this method, you may lose the extension and a part of the file name. Imagine a file called "image.white.jpg" would result in something like: "image.1474741.white"
Also exploding two time the exact same string two times in a row isn't a good practice


Como remover o ponto da casa decimal

Question: Tenho esse metodo
   public void calcularVotosTotal(){

    System.out.println("votos valiudos " + this.getNumeroEleitores() * 0.8 + "% " + " Votos Brancos "
                        + this.getNumeroEleitores() * 0.06 + "% " + " votos nulos "
                        +this.getNumeroEleitores() * 0.14 + "% ");
}

Tenho aqui o metodo principal
 public static void main(String[] args) {
    AlgoritimoNumeroTotalPessoas antp = new AlgoritimoNumeroTotalPessoas(100);
    antp.totalEleitores();
    antp.calcularVotosTotal();
}

e aqui a saída do console abaixo, como faço para remover os pontos na casa decimal? e deixar a saida assim 80%, 6%, 14%
Numero total de eleitores 100
votos validos 80.0%  Votos Brancos 6.0%  votos nulos 14.000000000000002%

Comment: sei que existem algumas classes como format, BigDecimal, mas nao soube como utilizar nesse estrutura, pois sou iniciante ainda.
Comment: O que o método `getNumeroEleitores` retorna?
Comment: o metodo getNumeroEleitores é so um java bean do atributo numeroEleitores que é do tipo double
Answer: Pelo o que vi, você deseja retornar um valor inteiro, acho que o "problema" está no retorno do método getNumeroEleitores, que na verdade deveria ser um long, imagino que você esteja retornado um double ou float, nesse caso basta você realizar uma conversão para um long, segue um exemplo abaixo:
public class HelloWorld{
     public static void main(String []args){
        double d = 15.5;
        System.out.println((long) d); //saida: 15
     }
}

Obs: Usei o long por medo de estourar o valor máximo de int.
Comment: fica do mesmo jeito ainda assim
Comment: me mostra como ficou o método `getNumeroEleitores`
Answer: Deu certo eu tava fazendo o cast de forma errado, obg a todos!
public void calcularVotosTotal(){

    System.out.println( "votos validos "  + (int)(this.getNumeroEleitores() *  0.8) + "% " + " Votos Brancos "
                        + (int)(this.getNumeroEleitores() * 0.06) + "% " + " votos nulos "
                        + (int)(this.getNumeroEleitores() *  0.14) + "% ");
}

Como remover o ponto da casa decimal


How can render a Block on a Contact form Page

Question: I want to render a Block on a special content type page and on the contact form page. All works fine, but i didn`t found any way to print the Block also on the contact form page.
i use in the page.tpl.php:
if(isset($node) && $node->type === 'page') {
   ....
}

Hope someone can help! Thx
Answer: Following the logic exactly as you have laid it out, you could test for
if (arg(0) == 'contact')

to output the block on the contact page. However, is there a reason you're not using the block admin page to place this block instead? Other options here that might be easier to maintain would be:

place the block in the region you want using the Context module
copy the page.tpl.php file from your theme to page--contact.tpl.php and add your block content there
Comment: Hey, great thanks to you! I need the block twice, for the footer and for some content pages in one sidebar ... i hoped this was the easier way, but i didn`t found a solution for the contact page ... think yours should work!


Rails 3 - How to use stylesheet's compiled name inside javascript file?

Question: I have javascript file in rails app, where i pull in the stylesheet like this -
<code>   loadAssets: function(){
    var stylesheet = document.createElement('link');
    stylesheet.href = "<%= asset_path('lib/myStyles.css') %>";
    stylesheet.rel = 'stylesheet';
    stylesheet.type = 'text/css';
    document.getElementsByTagName('head')[0].appendChild(stylesheet);
}
</code>
But asset_path helper used here, just gives plain myStyles.css name, where it should have been compiled name of that css file.
Because of this, i can't expire cache and get new myStyles.css file.
So, my question is, how can i get compiled name of this myStles.css file in my javascript file. Above code containing javascript file also gets compiled.
Comment: I would suspect that getting the asset pipeline to compile css before js can let the asset_path function yield the proper path?
Answer: <code><%= asset_path('lib/myStyles.css'), :digest => true) %>
</code>
Comment: you need to make sure it is a js.erb file to embed ruby
Comment: For sure. I assumed that if asset_path was returning any name at all for them that it was already a js.erb file.


Is it possible to do hammer-ons and pull-offs on a lap steel guitar without only using open strings?

Question: Is there a practical way to do hammer-ons and pull-offs on a lap steel without only using open strings? As a lap steel has no frets and the strings are too high to push it to the fretboard.
I've tried to use a bottleneck on my pinky to make a barre chord. But that makes playing with your left hand really hard, and you have to deal with two intonations. I've seen some video's of people doing it this way but it sounds a bit sloppy and out of tune.
I've also come across a device knows as the Pedal slide. I think this is the closest thing available right now. But I'm not convinced yet. You can only use your thumb, you sacrifice a lot of left hand mobility and it feels too light because it's hollow.
Answer: I could imagine the steel guitar equivalent of two-hand tapping; holding a second bar in your right hand. There trick with "normal" tapping is that you don't just pull off, but a bit to the side to impart vibrations, so for the steel version, you'd snag the strings with the bar, maybe using a Shubb-style instead of a bullet-style. You'd have a problem switching back and forth from normal picking, I'd think, but it could be interesting.
Comment: Normal tapping surely does involve just pull offs - they're the ones that pluck with the fretting finger.
Comment: @Tim How does that differ from what I wrote?


Straight lines question

Question: In a triangle $ABC$, the bisectors of angles $B$ and $C$ lie on lines $x=y$ and $y=0$. If $A$ is $(1,2)$ then equation of $BC$ is?
Answer: The image of $A$ with respect to the angle bisectors of $B$ and $C$ will lie on the line $BC$. This can be deducted from the definition of an angular bisector.
Hence, Image of $ (1,2) $ in $ x = y $ is $ (2,1) $.
And Image of $ (1,2) $ in $ y = 0 $ is $ (1,-2) $.
Both of these points will lie on BC.
Hence its formula is :
$ 3x-y-5=0 $

Straight lines question


Equilibrium Temperature in a Rod

Question: Consider heat flow in a rod of length $l$
\begin{align*}
    u_t = ku_{xx} - hu, 0 < x < l\\
    u(0,t) = u(l,t) = 0, t > 0\\
    u(x,0) = f(x), 0 \leq x \leq l\\
\end{align*}
I am trying to find the equilibrium temperature.
I am new to these problems but I think the equilibrium temperature is reached when $u_t = 0$. Thus I say that,
\begin{align*}
    0 &= ku_xx - hu \\
\end{align*}
For fixed $t=0$ define $y(x) := u(x,0)$ so we have an ODE in $y$
\begin{align*}
    0 &= ky''(x) - hy(x)\\
    y(x) &= \frac{c_1 k e^{hx/k}}{h} + c_2
\end{align*}
From the boundary condition we know that $y(x) = f(x)$, but this is not enough to solve for $c_1$ and $c_2$. It seems like we need more information. I know that we also have that $u(0,t) = y(0) = 0$ but even if we also had that we could still not solve for $c_1$ and $c_2$. I am confused how to proceed can anyone help?
Answer: You are correct that the equilibrium temperature is found when $u_t=0$. However, you should think of this as the temperature as $t \to \infty$, not when $t=0$. That is, $f(x)$ should have no bearing on the equilibrium solution.  So, we have to solve
$$ku_{xx} = hu$$
with boundary conditions
$$u(0)=u(\ell) = 0.$$
Then, the solutions are of the form
$$u(x) = C_1 e^{x\sqrt{h/k}} + C_2 e^{-x\sqrt{h/k}}.$$
Using the boundary conditions, I calculated $C_1 = e^{-\ell \sqrt{h/k}}-e^{\ell \sqrt{h/k}}$ and $C_2 = -C_1$.

Equilibrium Temperature in a Rod


date.format is not a function reacr-dates

Question: I was trying to use singleDatePicer from react-dates,which is a popular date picker library by airbnb, on selecting a date, it throws the error date.format is not a function, and just breaks, my code sandbox link is -> https://08cg1.csb.app/. Thanks in Advance.
Answer: singleDatePicker will accept moment object as date props so you need to change onDateChange like below:-
onDateChange={(date) => setDate(date)};

Answer: onDateChange={(date) => {setDate(date);}}

Here, Don't change the date format and then set the state.
Just set the state directly.
If you want to display that selected date somewhere else, there use the moment.
The issue was, once you changed the date format, that format is not supporting as value.
Comment: Hey, Thank you, this is way more explainable


Troubleshooting web server continuous load issue

Question: I am a beginner at managing a web server. And I am trying to learn how to troubleshoot an issue in Windows Server 2008 R2 running IIS 7.5 with a .NET 4.0 MVC website.
A website I manage has been running perfectly on a GoDaddy shared hosting plan for months. The last code update to the website was about 6 weeks ago. Several days ago the website stopped working from one minute to the next. Literally, it was more like one second to the next. One of the website admin's loaded a page, clicked a link and the next page never loaded. It has been down ever since.
I spent approx. 5 hours on the phone with 4 different GoDaddy technicians. Each time they determined that it was something in the website programming. (There are 2 of us that have access to the FTP of the site. We were both on our way to work when it stopped working.)
To test it, I published the site to our in-house dev server and it worked. I then re-published to the GoDaddy shared hosting and it still did not work.
The primary issue is that the site loads and loads and never comes up.
I thought maybe I would try another host, so I have spun up a Windows VM server on Rackspace (Win 2K8 R2), installed IIS 7.5, and have a basic site up and going. If I load a basic index.html file into the folder, I can see the "Hello world" message both locally on the web server and publicly from my office.
However, as soon as I load the ASP.NET content into the folder, I get the continuous load issue again.
As I said before, on the in-house dev server (which is also Win 2K8 R2 w/ IIS 7.5) the website works fine. For the moment, I have redirected the primary domain to my office IP, created some firewall rules to forward the packets, and am successfully hosting the website from the dev server. But this is not a long term solution.
I have spent hours in the last few days looking for solutions online, and have tried a number of things. But I have not had to troubleshoot a web hosting issue like this where I do not get any obvious error messages. I am looking for ways to troubleshoot this issue in IIS, or find error messages or logs, or something that could point me to the issue. But my lack of knowledge in managing a web server is getting in the way.
Thank you!
Comment: did you work this out as we've had a very similar problem. We solved it by creating a new app pool and then assigning the site to it (we couldn't restart the app pool as it wouldn't restart). We don't know if this is a permanent or temporary fix though!
Comment: I just posted my answer. It was a permissions issue. For some reason GoDaddy wiped out our folder permissions, but since we had originally set them very early in the project, we had forgotten that it was a thing we needed to watch out for.
Answer: I finally solved this last week.
There is a configuration file that is apart of our web application that needs read/write permissions for IIS. On our shared hosting account at GoDaddy, the permissions had been removed for some unknown reason. And when we loaded the application onto the test server, I basically just forgot that we had to reset those permissions on the new server. On our in-house dev server, the permissions had been configured way back at the beginning of the project.
On the test server we spun up at Rackspace, I added "Full Control" for the "IIS_IUSRS" to the parent directory where the file resides. On the GoDaddy shared hosting account, I went into the File Manager and set the permissions to web read/write on the directory.
The coding issue was that since the file is being accessed by a library that is used by the web application, the error was not being properly handled. If too many errors happen in a row, IIS can enter that continuous load state under certain conditions.
I stripped the site down to bare-bones and started adding dependencies back one at a time. Then when the error occurred, it wasn't so deep in the system, so I started actually getting helpful event logs. It's like the problem was so deep that it created an entirely unstable application and even the errors weren't being properly reported.
Comment: Hi, I encounter the same problem. May I know the process stripped the site down?
Comment: @want_to_be_calm I backed up all site files offline, and deleted them from the webserver. Then started by adding a basic index.html just to see it load. Our site had a front-end, customer facing part, which was static content, and a database driven backend. So, I started with the static content as I added back the files and folders and tested along the way....
Comment: ...In our case, when I added back the login page I started seeing errors because it was the first place that the database was being hit. Our application had a static resource (not a web.config) file with specific settings, and that file was not accessible because of permissions on the directory it was in.
Answer: I would go and try to make an export of the site from one web server to another, then check .net version, app pools (including framework). If that does not work get process hacker or another tool to get some insight into what might be taking so much resources-IE some methods might take millions of CPU cycles.If all that does not work have a look into professional IIS 7 optimisation or test if it's performance with IE Tester, JMeter and see what content is taking so much time then try to optimist it.
Comment: We spun a test server up at Rackspace and had a similar issue. There however, it would not continuously load. It would time out after 30 seconds or so with a can't load page message. The event logs were no help. Eventually, I stripped the site down to nothing and started adding dependencies back one at a time until it crashed.
Comment: See if you have any extra packages installed on one of the servers, export the IIS configuration then via IIS (to be sure that you have the same settings), see if all the requirements are met like SSL, Authentification provider ...
Comment: @jwatts1980 how to stripped the site down?


Maximal clique problem

Question: I understood what clique is all the nodes of the sub graph have to be connected to each other. In the following figure, it says that the maximal clique is {1,2,3,4,5}. But as per the definition of clique {1,2,3,4,5} is not a clique. Could someone explain this?
<code>                    1
                   *  *
                  *     *
                 2*******3
                 *       *
                 *       *
                 4       5
                  *     *
                   *    *
                    *  *
                      6
</code>
Consider the ***** as an edge.
Comment: It may be better to upload the original image or provide a citation to the original problem.  Perhaps the way your figure is drawn here does not exactly match the original figure in question.
Comment: {1,2,3,4,5} is indeed not a clique. {1,2,3} is the largest clique in this graph.
Comment: By connected, do you mean *adjacent*?  Two vertices can be connected without being adjacent.  In the usual definition, a *clique* is a complete subgraph, i.e., any two vertices are adjacent.  Your version of cliques is known to most mathematicians as *connected subgraphs*.
Comment: I tried uploading it but I dont have reputation 10 so it didnt allow me :(
Answer: Your understanding of clique is correct.
However the maximal clique in that graph is {1,2,3} and not {1,2,3,4,5}.
{1,2,3,4,5} is not even a clique in that graph.
Answer: A clique of a graph is a subset of the vertices with the property that each vertex of this subset is adjacent to every other vertex of the subset (complete induced subgraph)

Maximal clique problem


Creating a Queue in C++ - What is a malloc error?

Question: I am creating a simple queue, however I am getting a weird error:
compile(46096,0x7fffb263d380) malloc: * error for object 0x7f9c61c00340: pointer being freed was not allocated
* set a breakpoint in malloc_error_break to debug
If I reduce the number of enqueue methods I just get a segmentation fault.
My main class:
#include <iostream>
#include "queue.h"
using namespace std;

template <typename ItemType>
void enqueue(const ItemType &i, node<ItemType>* &n, const long &p) {

    node<ItemType> *nn = new node<ItemType>;

    nn->item = i;
    nn->next = n;
    n = nn;
}

template <typename ItemType>
ItemType dequeue(node<ItemType>* &n) {

    ItemType fr;
    node<ItemType> *ptr;

    ptr=n;
    n = n->next;
    while(ptr->next != NULL){
        ptr = ptr->next;
    }

    fr = ptr->item;

    delete ptr;
    return fr;

}

int main() {

    node<int> *head;
    enqueue(13,head, 1);
    enqueue(10,head, 2);
    enqueue(18,head, 3);
    cout<item<<"\t"<next->item<<"\t"<next->next->item<<endl;
    cout<<dequeue(head)<<"\t";
    cout<<dequeue(head)<<"\t";
    cout<<dequeue(head)<<endl;

    //cout<<dequeue(head)<<endl; // create error cathcing

}

My node wrapper class:
#include <iostream>

template <typename ItemType>
struct node {
    ItemType item;
    node<ItemType> *next;
    int priority;
};

Comment: Is there a reason why you are not using `std::queue` instead of rolling your own manually? In any case, you are not initializing `head` to null before using it, so you have nodes with invalid `next` values
Comment: Seems like the runtime is telling you the exact problem. I mean ***error for object 0x7f9c61c00340: pointer being freed was not allocated*** why I mention this is you don't always get such a detailed error message.
Comment: Compile with all warnings and debug info: `g++ -Wall -Wextra -g` with [GCC](http://gcc.gnu.org/). Read [how to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). Use [valgrind](http://valgrind.org/)
Answer: You do: node<int> *head; and then enqueue it with nn->next = n;
This ends up storing unintialized memory, then fails at deletion.
Try node<int> *head = NULL;
Comment: Is there a specific reason to use `NULL` instead of `nullptr`?
Comment: Probably because the code in the question uses `NULL` instead.
Comment: it prints the same number (13) for every dequeue. however it did remove the error


Texto e imagem responsiva

Question: sou meio novato trabalhando com métodos responsivos e estou tendo problemas com um detalhe, preciso trocar o texto de um btn por uma imagem quando minha aplicação for acessada por celular.
Alguém poderia me ajudar com isso?
<button class="btn btn-lg btn-info btn-block text-uppercase" id="prosseguir" type="submit">Prosseguir</button>

Eu gostaria que ao redimensionar a tela, o btn substituísse o "Prosseguir" por um icone.
Grato.
Comment: Aparentemente você está usando Bootstrap. Essa informação é correta? Se sim, qual versão?
Comment: Estou usando a versão 4
Answer: Existem vária formas de fazer e uma delas é colocando um span dentro do button como eu fiz nesse exemplo. depois com a regra @media vc esconde e mostra esse span, ao mesmo tempo que vc retira o texto do bottun colocando o font-size:0 por exemplo.
Então caso a tela tenha no máximo 610px de largura a imagem aparece, caso seja mais quer 610px o texto do button aparece. Vc pode ajustar isso na regra @media caso queira

A início vc pode pensar que não é uma forma totalmente semântica, porém o lado positivo é que mesmo com o font-size:0 o texto pode continuar visível para leitores de tela, porém não aparece para o usuário comum.
Veja o código correspondente a imagem acima:

.icon {
    height: 16px;
    width: 16px;
    background-image: url(https://placecage.com/16/16);
    vertical-align: middle;
    display: none;
}
@media screen and (max-width:610px) {
    .icon {
        display: inline-block;
    }
    button {
        font-size: 0;
    }
}
<button class="btn btn-lg btn-info btn-block text-uppercase" id="prosseguir" type="submit">
    Prosseguir

</button>
Answer: Como complemento à resposta do Hugo, o Bootstrap já tem ferramentas para alterar a propriedade display variando de acordo com a largura do viewport (através das media queries). São as classes d-* (documentação).
OBS: quando me referir à xs, é o tamanho da tela (< 576px). Pois o BT4 usa a abordagem Mobile First, ou seja, se não especificado explicitamente os estilos são aplicados à telas xs (extra small)
Você pode dizer para imagem ficar escondida em todas as larguras, exceto xs usando as classes:
Prosseguir

d-none faz com que o span seja display: none, e d-sm-block faz com que seja display: block para telas sm ou maiores, ou seja, ficará oculto apenas em telas xs.
Já na imagem você usaria:

d-inline-block faz com que a img seja display: inline-block, e d-sm-none faz com que seja display: none para telas sm ou maiores, ou seja, ficará visível apenas em telas xs.
Dessa maneira a visibilidade do span e do img ficam mutuamente excludentes.
Exemplo:

html, body {
  padding-top: 40px;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">

    <button class="btn btn-lg btn-info btn-block text-uppercase">
      Prosseguir

    </button>

Você pode deixar o snippet em tela cheia (link "página toda") e alterar a largura da janela do seu navegador para ver a responsividade funcionando
Comment: Bootstrap 4 não tem XS ;) https://getbootstrap.com.br/docs/4.1/layout/grid/#par%C3%A2metros-grid Outra dica, já que não vai ter texto no button, não se esqueça de colocar ALT na imagem
Comment: Eu reli a resposta e não vi onde disse classes XS. Eu disse tamanho de tela XS. E não tem a classe XS porque ela é a padrão (Extra small < 576px) devido à abordagem Mobile-First. Me ajuda aí Hugo, não entendi o porquê do comentário. hahahah
Comment: É pq no Bootstrap 3 existe col-xs-* e XS é usado em várias outras coisas, já no Bootstrap 4 XS deixou de existir... as vezes isso pode confundir as pessoas. Foi apenas uma observação
Comment: Muito obrigado, deu certinho as dicas de vocês e obrigado pelos links de documentação, me elucidou bastante.

Texto e imagem responsiva


Nginx get / from /index.php without "directory index is forbidden" elsewhere

Question: I need / to be shown like /index.php.
Right now I have
index index.php;
if ( $request_uri = /index.php ) { return 301 /; }
location / { try_files $uri $uri/ =404; }

And everything works fine but there are some errors like
directory index of "/home/.../public_html/tmp/" is forbidden

which I want to remove. The problem here is $uri/ in try_files $uri $uri/ =404;
https://stackoverflow.com/questions/19285355/nginx-403-error-directory-index-of-folder-is-forbidden/38046124#38046124
Ubuntu + Nginx: directory index of "/var/www/app/my-app/" is forbidden
But if I change this to try_files $uri =404; or try_files $uri /index.html index.php =404; then "/" just stops working and shows 404
Why does removing $uri/ prevent showing index.php if I have index index.php;?
How can I set that / should check index.php and if there is no index.php then just shows 404 without throwing "is forbidden" error?
Comment: Does your website have more than one `index.php` file?
Comment: Maybe there are several but I only care about root `/index.php`. It all works now but with `directory index of "..." is forbidden` when someone hit page that is not here because of `$uri/`.
Answer: The $uri/ term in a try_files statement has two distinct purposes.
If the URI does not end with a /, but does reference a directory, Nginx will generate a 301 redirection to append a /.
If the URI ends with a / and references a directory, the Index functionality will be invoked, which can either result in an internal redirection to an index file, or a 403 response if the index file is not found.
One solution to suppressing the 403 response without affecting too many other things is to handle URIs which end with a / differently.
For example:
location ~ /$ {
    if (-f ${request_filename}index.php) {
        rewrite ^(.*)/$ $1/index.php last;
    }
    return 404;
}

The above will test for the existence of index.php within the directory, and return 404 if it does not exist.
Answer: The following approach might work:
location = /index.php {
    return 301 /;
}

location / {
    try_files $uri $uri/ /index.php =404;
}


Find the minimal polynomial for $\sqrt[3]{2}$

Question: Find the minimal polynomial for $\sqrt[3]{2}$
I understand the solution as far as finding a basis, seeing how it acts by left multiplication on $\sqrt[3]{2}$, finding a matrix, finding the eigenvalues, and getting the polynomial that way.
What I don't understnad is what my basis should be. Should $\{1,\sqrt[3]{2},\sqrt[3]{4}\}$ be a basis because they are powers of $\sqrt[n]{2}$ for $n=0,1,2$?
Comment: Although in general getting the minimal polynomial the way you propose works, in this case (and nearly every case you do by hand) it is much easier to 'see' a polynomial that has $\sqrt[3]{2}$ as a root and prove that it is irreducible.
Comment: That is a basis; they are $n$th powers of $\sqrt[3]2\,$ for $n=0,1,2$
Answer: I suppose that you have to find the minimal polynomial on $\mathbb{Q}$. Let us put $\zeta=\sqrt[3]2$, then you have that $X^3-2$ has $\zeta$ as root, moreover it is irreducible by Eisenstein criterion, so it is the minimal polynomial of $\zeta$.


Sql query with selected and splited column value from another table

Question: I have 2 tables
First table
Id Type Value
1   2   1,2,3,5
2   1   1,3,6
3   1   2,3,1,6

Second table
Id Name
1  Leon
2  Anna
3  Biorn
4  Alex
5  Peter
6  Luis

Values in First table are Ids in Second table.
I need query that returns all names by type from the first table
For example:
Type = 1
return: Leon,Anna,Biorn,Luis
type = 2
return: Leon,Anna,Biorn,Peter

I'm trying to create a View that will look like this:
Type Name
1    Leon
1    Anna
1    Biorn
1    Luis
2    Leon
2    Anna
2    Biorn
2    Peter

So I can easily select all the names by type, but I can't figure out how to do it. Please help!
Answer: You seem to recognize that this is a poor data structure.  You should have a junction table -- storing lists of integers as a delimited string is not a SQLish data structure.
Sometimes, we are stuck with other people's bad design decisions.  Here is one thing you can do:
select t1.type, t2.name
from table1 t1 join
     table2 t2
     on ',' + t1.value + ',' like ',%' + cast(t2.id as varchar(255)) + '%,';


How to localize JSF composite component?

Question: I'm having trouble localizing a composite component (Mojarra 2.2, Glassfish 4.0).
I tried BalusC's solution here to put the properties file in the same directory as the composite component with the same file name as the composite component and a .properties extension -- that works to externalize the strings from the composite component's definition.
But when I want to localize the strings (by adding _en suffix to the property file's filename) I get this error (only thing changed is the name of the properties file):
[2013-08-08T13:49:04.234-0500] [glassfish 4.0] [WARNING] [] [javax.enterprise.web] [tid: _ThreadID=24 _ThreadName=http-listener-1(5)] [timeMillis: 1375987744234] [levelValue: 900] [[
  StandardWrapperValve[Faces Servlet]: Servlet.service() for servlet Faces Servlet threw exception
java.lang.NullPointerException
at javax.faces.component.UIComponent.findComponentResourceBundleLocaleMatch(UIComponent.java:1204)
at javax.faces.component.UIComponent.getResourceBundleMap(UIComponent.java:1007)
at sun.reflect.GeneratedMethodAccessor1226.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at javax.el.BeanELResolver.getValue(BeanELResolver.java:363)
at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
at com.sun.el.parser.AstValue.getValue(AstValue.java:140)
at com.sun.el.parser.AstValue.getValue(AstValue.java:204)
at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:226)
at org.jboss.weld.el.WeldValueExpression.getValue(WeldValueExpression.java:50)
at com.sun.faces.facelets.el.ELText$ELTextVariable.writeText(ELText.java:227)
at com.sun.faces.facelets.compiler.TextInstruction.write(TextInstruction.java:85)
at com.sun.faces.facelets.compiler.UIInstructions.encodeBegin(UIInstructions.java:82)
at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeRecursive(HtmlBasicRenderer.java:302)
at com.sun.faces.renderkit.html_basic.GroupRenderer.encodeChildren(GroupRenderer.java:115)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:894)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1856)

...

I read an article (post from 24/Aug/12 03:50 PM) that JSF localizes differently than standard Java and that the properties files would go in resources/en/<library>/<component>.properties, so I put mycomp.properties there and got the error again.
My default locale is actually "en_US" -- I tried that as well with the same results.
So, this works:
resources/lib/mycomp.xhtml, resources/lib/mycomp.properties
These don't work:
resources/lib/mycomp.xhtml, resources/lib/mycomp_en.properties
resources/lib/mycomp.xhtml, resources/en/lib/mycomp.properties
What am I doing wrong?
Answer: I can reproduce your problem. This is quite embarrassing. Apparently something changed related to this in a newer Mojarra version. I can't get both the old and new approach to work in 2.2.0.
I peeked in the Mojarra source code again, starting at UIComponent#getResourceBundleMap(), and I learned that the resource bundle is first searched based on the FQN of the component's class. We could easily make use of it.
If not already done, first create a backing component class:
package com.example.composite;

@FacesComponent("myComposite")
public class MyComposite extends UINamingContainer {
    // Can be kept empty.
}

And declare it in the composite component definition:
<cc:interface componentType="myComposite">

Then, you can simply put the MyComposite.properties, MyComposite_en.properties, etc in the very same com.example.composite package. It worked for me.
Comment: I tried that work-around, but get the same error.  I verified the backing component class is being instantiated (so, presumably it's properly associated with the composite component), but still get the NullPointerException when trying to obtain the string with `#{cc.resourceBundleMap.title}`.  Could there be something else I need to do, as well?  I've defined a `` in `faces-config.xml` to use for app-wide localization -- could that be complicating things? if I reference that bundle in the composite component, it works, so that could suffice as a work-around, I suppose.


views of node with weight

Question:
Possible Duplicate:
How can I add a "weight" functionalitiy to nodes?

I have views of node for example 10 last of news,I want when create a views of node , I can set this weight, means that create own list.
for example , I chose first node , second node ...
please help me
Comment: ...and also of [Is there any way to reorder the nodes in a View?](http://drupal.stackexchange.com/questions/2573/is-there-any-way-to-reorder-the-nodes-in-a-view)
Answer: You should extend your contenttype with a weight field for this and use it as sort parameter. If your drupalversion is 6 you could use the CCK module for that.
Comment: I want create own list and handle my list for example with drag and drod

views of node with weight


div class="container" not working in html page with almost no css

Question: Inside my HTML page i use the class container. But the navbar isn't responding to this and i don't see the reason why it does this. I tried putting the class everywhere in the code but it just keeps taking all the space.

<!DOCTYPE html>

        <meta charset="utf-8" />

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

        <title>JK Websites & computers</title>

                        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

                        </button>
                        WebSiteName

 Sign Up

 Login

Comment: did you try to put your navbar into a div.container ? like here https://getbootstrap.com/examples/navbar/
Comment: Yes, exactly the same result.
Comment: check the developer console for any errors regarding the integrity...
Answer: The problem is caused by the class :  navbar-fixed-top.
It goes full width, here is a link to a solution and its example with your code
Navbar fixed to top but not full-width
example :
JSFIDDLE
HTML

css
@media all and (min-width: 768px) {
  .navbar-fixed-width {
    width: 768px;
    margin-left: auto;
    margin-right:auto;
 }
}

@media all and (min-width: 992px) {
  .navbar-fixed-width {
    width: 992px;
    margin-left: auto;
    margin-right:auto;
  }

}

@media all and (min-width: 1200px) {
  .navbar-fixed-width {
    width: 1200px;
    margin-left: auto;
    margin-right:auto;
  }
}

Dont forget to wrap your code with

Answer: I know why it isn't working. This is because Google Chrome and Chrome doesn't support it.
Answer:

/into CSS/
.clearfix:after{
    display: table;
    content: '';
    clear: both;
}

Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Evaluating the line integral given $C, \vec{F}$

Question: I wish to verify if my answer is correct:
Find $\int_C \vec{F}\cdot\,d\vec{R}$ where $\vec{F}(x,y) = \langle \tanh^2x, -3x\rangle$ and $C$ is the portion of the parabola $x = (y+1)^2$ from (1,0) to (4,1).
My solution:
Parametrize the parabola  $x = (y+1)^2$ as $\vec{R}(t) = \langle t, |\sqrt{t}|-1\rangle$. Since $x$ ranges from 1 to 4, then $1 \leq t \leq 4$ as well. Now,
\begin{align*}
        \text{Let }\vec{F} &= \langle \tanh^2x, -3x\rangle\\
        \vec{F}(\vec{R}(t)) &= \langle \tanh^2t, -3t\rangle
    \end{align*}
and
\begin{align*}
    \vec{R}'(t) &= \left\langle 1, \dfrac{1}{2\sqrt{t}} \right\rangle.
\end{align*}
Hence,
\begin{align*}
    \vec{F}(\vec{R}(t))\cdot\vec{R}'(t) &= \langle \tanh^2t, -3t\rangle \cdot \left\langle 1, \dfrac{1}{2\sqrt{t}} \right\rangle = \tanh^2t - \dfrac{3\sqrt{t}}{2}
\end{align*}
Thus,
\begin{align*}
    \int_{C_2} \vec{F}(\vec{R}(t))\cdot\vec{R}'(t)\,dt &= \int_1^4 \tanh^2t - \dfrac{3\sqrt{t}}{2}\,dt\\
    &= \ln(e^{-2t}+1) + \dfrac{2e^{-2t}}{2e^{-2t} + e^{-4t} + 1} - t^{\frac{3}{2}}\bigg|_1^4\\
    &= \fbox{$\ln(e^{-8}+1) + \dfrac{2e^{-8}}{2e^{-8} + e^{-16} + 1} - 8 - \left(\ln(e^{-2}+1) + \dfrac{2e^{-2}}{2e^{-2} + e^{-4} + 1} - 1\right)$}
\end{align*}
My answer really looks awkward, which is why I am asking if it is correct. Otherwise, where did I go wrong?
Answer: Something seems to have gone wrong with your integral. Note that,
$\displaystyle \int \tanh^2 (t) = t - \tanh (t) + C$
As $ \displaystyle \tanh(t) = \frac{e^{2t} - 1}{e^{2t}+1}$ ,
$\displaystyle I = \int \tanh^2 (t) = \int \left(\frac{e^{2t} -1}{e^{2t}+1}\right)^2 \ dt = \int \frac{(e^{2t} + 1)^2 - 4e^{2t}}{(e^{2t}+1)^2} \ dt$
$ \displaystyle = \int \: dt \: - 2 \int \frac{2e^{2t}}{(e^{2t} + 1)^2} \ dt$
In second integral, substituting $e^{2t}+1 = u, \ 2 e^{2t} dt = du$ and that leads to, $ \displaystyle I = t + \frac{2}{e^{2t}+1} + C$
It can also be written as $ \displaystyle I = t - \left(1 - \frac{2}{e^{2t}+1}\right) + C_1 = t - \tanh(t) + C_1$
So the line integral should be $\displaystyle \left[t + \frac{2}{e^{2t}+1} - t^{3/2}  \right]_1^4 = \frac{2}{1+e^8} - \frac{2}{1+e^2} - 4$
or $ \  \displaystyle \tanh(1) - \tanh(4) - 4$


Degree of accuracy for the Gauss-Lobatta quadrature formula

Question: We would like to approximate the integral of $f$ over an interval $[a,b]$ with positive measure $\mu$. To this end, we choose $n$ points $x_1, x_2, \ldots, x_n$ inside the open interval $(a,b)$ together with the end points $a$ and $b$ and we choose $n+2$ weights $\lambda_a, \lambda_b, \lambda_{x_1}, \lambda_{x_2}, \ldots, \lambda_{x_n}$ in such a way that we hope that the formula (called the Gauss-Lobatta quadrature formula) $\displaystyle \lambda_af(a) + \lambda_bf(b) + \sum_{k=1}^n \lambda_{x_k}f(x_k)$ is a good approximation to $\displaystyle \int_a^b f(x) d\mu(x)$. If this formula is exact whenever $f$ is a polynomial of degree at most $m$, we say that our formula has degree of accuracy $m$.
Polynomials $p_0, p_1, \ldots, p_n, \ldots$ (where $p_n$ has degree $n$) are called orthogonal polynomials for the measure $\mu$ if $\displaystyle \int_a^b p_i(x)p_j(x) d\mu(x) = 0$ for $i \neq j$.
I would like to prove the following: our formula has degree of accuracy $2n+1$ if, and only if, $x_1, x_2, \ldots, x_n$ are the zeros of the orthogonal polynomial of degree $n$ for the modified measure $(x-a)(x-b)d\mu(x)$.
Any help would be much appreciated!
Answer: Let $f$ be a polynomial of degree at most $2n+1$ and let $L$ be the Lagrange interpolant for $f$ at the interpolation points $a, x_1, \ldots, x_n, b$, where the $x_i$ are the zeros of the orthogonal polynomial $p_n$ for the measure $\mu_0$ with $d\mu_0(x) = (x-a)(x-b)d\mu(x)$. We can write
$$L = \displaystyle f(a)\ell_a(x) + f(b)\ell_b(x) + \sum_{j=1}^n f(x_j)\ell_{x_j}(x)$$
where $\ell_a, \ell_b$ and $\ell_{x_j}$ are the fundamental polynomials of Lagrange interpolation Then $f - L$ is a polynomial of degree at most $2n+1$ with zeros at the interpolation points, so we can write it as $p_n(x)(x-a)(x-b)q(x)$, where $q(x)$ is a polynomial of degree at most $n-1$. Integrating this and using the orthogonality relation we obtain:
$$\int_a^b f(x) - L(x) d\mu(x) = \int_a^b p_n(x)(x-a)(x-b)q(x) d\mu(x) \\
= \int_a^b p_n(x)q(x) d\mu_0(x) = 0$$
And we conclude that with $\lambda_a = \int_a^b \ell_a(x) d\mu(x)$ with similar expressions for the other weights, our formula has degree of accuracy $2n+1$.
While on the other hand, if the $x_i$ are not the zeros of $p_n(x)$, then for $p(x) = (x-x_1)\cdots(x-x_n)$ there exists a polynomial $q$ with degree at most $n-1$ such that $\int_a^b p(x)q(x) d\mu_0(x) \neq 0$.
Note that degree of accuracy $2n+2$ cannot be achieved if the support of $\mu$ contains more than $n$ points, since for $q(x) = (x-x_1)\cdots(x-x_n)$ (with the $x_i$ the zeros of $p_n(x)$) we have that $q_0(x) = q(x)^2(x-a)(x-b)$ is a polynomial of degree $2n+2$ with
$$\displaystyle \int_a^b q_0(x)\mu(x) = \int_a^b q(x)^2d\mu_0(x) > 0$$
while $\displaystyle \lambda_aq_0(a) + \lambda_bq_0(b) + \sum_{k=1}^n \lambda_{x_k}q_0(x_k) = 0$, since we evaluate $q_0$ at its zeros in that sum.


Using moment to calculate the number of days between 2 dates

Question: I'm trying to work out the number of days between 2 dates in Javascript with the following code.
    console.log(self.StartDate());
    var start = moment(self.StartDate(), "YYYY-MM-DD");
    console.log(start);
    console.log(self.EndDate());
    var end = moment(self.EndDate(), "YYYY-MM-DD");
    console.log(end);
    var duration = moment.duration(start.diff(end));
    console.log(duration);

    //no of days between start and end
    console.log(duration.asDays());

console output:
Thu Jun 20 2019 01:00:00 GMT+0100 (British Summer Time)
n {_isAMomentObject: true, _i: Thu Jun 20 2019 01:00:00 GMT+0100 (British Summer Time), _f: "YYYY-MM-DD", _isUTC: false, _pf: {…}, …}_d: Wed Aug 19 0020 00:00:00 GMT-0001 (British Summer Time) {}_f: "YYYY-MM-DD"_i: Thu Jun 20 2019 01:00:00 GMT+0100 (British Summer Time) {}_isAMomentObject: true_isUTC: false_locale: r {_ordinalParse: /\d{1,2}(th|st|nd|rd)/, ordinal: ƒ, _abbr: "en", _ordinalParseLenient: /\d{1,2}(th|st|nd|rd)|\d{1,2}/}_pf: {empty: false, unusedTokens: Array(0), unusedInput: Array(3), overflow: 1, charsLeftOver: 49, …}__proto__: Object
Mon Jun 24 2019 15:10:41 GMT+0100 (British Summer Time)
n {_isAMomentObject: true, _i: Mon Jun 24 2019 15:10:41 GMT+0100 (British Summer Time), _f: "YYYY-MM-DD", _isUTC: false, _pf: {…}, …}
Ea {_milliseconds: -126230400000, _days: 0, _months: 0, _data: {…}, _locale: r}
-1461

self.StartDate() is 20/06/2019 and self.EndDate() is 24/06/2019 so I'm exciting the alert to display 4 however it displays -1461.
Why is this the case?
Comment: `20/06/2019` is not `"YYYY-MM-DD"`
Comment: Stop using alert. Use `console.log` and look at the output in your dev tools console tab. That said, you don't show code that uses the days you claim to be using, so can you show what moment.js thinks is in those two dates (using console.log and then copying the output)?
Comment: Visit https://stackoverflow.com/questions/36600687/moment-js-two-dates-difference-in-number-of-days
Comment: @Mike'Pomax'Kamermans modified the OP
Comment: Where do you get the date data from?
Answer: The problem is that your dates are not formatted the way you tell moment.js they are. 20/06/2019 is DD/MM/YYYY and not YYYY-MM-DD. As per the documentation, non-numeric characters are ignored so 20/06/2019 would be parsed as 2006-20-19. Since such a date does not exist, Moment.js tries to guess what you actually meant and it comes up with 2020-06-19:

var start = moment("20/06/2019", "YYYY-MM-DD");

console.log(start);

Same thing happens with the end date.
You need to either change the format you tell to Moment.js or fix the start and end dates to use the format you specified, in both cases, you'd get the correct result:

var self = {
    StartDate: () => "20/06/2019",
    EndDate: () => "24/06/2019"
}

var start = moment(self.StartDate(), "DD/MM/YYYY"); //using the correct format
var end = moment(self.EndDate(), "DD/MM/YYYY");
var duration = moment.duration(start.diff(end));

console.log(duration.asDays());

var self = {
    StartDate: () => "2019-06-20", //using dates in the correct format
    EndDate: () => "2019-06-24"
}

var start = moment(self.StartDate(), "YYYY-MM-DD");
var end = moment(self.EndDate(), "YYYY-MM-DD");
var duration = moment.duration(start.diff(end));

console.log(duration.asDays());

Answer: Your code should work perfectly fine. You should only swap start and end at the defference calculation to get positive values.

var startDate = moment("2019-06-20", "YYYY-MM-DD");
var endDate = moment("2019-06-24", "YYYY-MM-DD");
var duration = moment.duration(startDate.diff(endDate));

//no of days between start and end
console.log(duration.asDays());

var duration = moment.duration(endDate.diff(startDate));
console.log(duration.asDays());

If you are only interested in the difference calculated in days, this code will be shorter:

var startDate = moment("2019-06-20", "YYYY-MM-DD");
var endDate = moment("2019-06-24", "YYYY-MM-DD");
var diff  = startDate.diff(endDate, 'days');
console.log(diff);

var diff  = endDate.diff(startDate, 'days');
console.log(diff);

There has to be some issue with the dates themselves.
And in fact, it's the way you parse the date strings

// This is parsed as the 19th day of 6th month in year 2020
var startDate = moment("20/06/2019", "YYYY-MM-DD");
// This is parsed as the 19th day of 6th month in year 2024
var endDate = moment("24/06/2019", "YYYY-MM-DD");
var diff  = endDate.diff(startDate, 'days');
console.log({"start": startDate, "end": endDate, "diff": diff});

// You either need to change the date strings or the format strings
var startDate = moment("20/06/2019", "DD/MM/YYYY");
var endDate = moment("24/06/2019", "DD/MM/YYYY");
var diff  = endDate.diff(startDate, 'days');
console.log({"start": startDate, "end": endDate, "diff": diff});

// You either need to change the date strings or the format strings
var startDate = moment("2019-06-20", "YYYY-MM-DD");
var endDate = moment("2019-06-24", "YYYY-MM-DD");
var diff  = endDate.diff(startDate, 'days');
console.log({"start": startDate, "end": endDate, "diff": diff});

Comment: "*Your code should work perfectly fine*" it doesn't. The dates are wrong.
Comment: No, the date strings were there from the beginning. Check [my comment](https://stackoverflow.com/questions/56738328/using-moment-to-calculate-the-number-of-days-between-2-dates/56738454?noredirect=1#comment100035425_56738328) from 3 minutes after posting the question. I know that the edit history omits recent enough edits but I do know I saw the dates immediately.
Comment: There were no dates presented with the format at the first time of writing.
Comment: Then how was I able to include the exact date that OP used in my comment?
Comment: It was an assumption. I made the same assumption and tried out the days diff between my assumed date format and it matched the calculated diff in the OP.
I assume! :)
Comment: So, I assumed that the text "*self.StartDate() is 20/06/2019 and self.EndDate() is 24/06/2019*" was there [in the first recorded revision, before the first recorded edit by the OP](https://stackoverflow.com/revisions/56738328/1)? Wait, how did I guess *the exact date* that OP used, not just the format?
Comment: It's the text under the console output. Note that those are not strings, but British English dates. But I think discussing this further is nitpicking
Answer: Your date is invalid, you specified a start date of "20/06/2019" which is a template of "DD/MM/YYYY", but told moment to use the template of "YYYY-MM-DD".
You simply need to replace the template that you pass to moment, and here is a bit cleaner way to do it:
const DEFAULT_DATE_TEMPLATE = "DD/MM/YYYY";

const getDaysBetweenDates = (date1, date2, dateTemplate = DEFAULT_DATE_TEMPLATE) => {
    const start = moment(date1, dateTemplate);
    const end = moment(date2, dateTemplate);
    const duration = moment.duration(start.diff(end));
    const daysDiff = duration.asDays();

    // for your example you will get -4, abs will make it into 4 for you
    return Math.abs(daysDiff);
}

const myDiff = getDaysBetweenDates('20/06/2019', '24/06/2019');
console.log(myDiff); // 4

// or if you rather keep your other template
const myDiff2 = getDaysBetweenDates('2019-06-20', '2019-06-24', 'YYYY-MM-DD');
console.log(myDiff2); // 4


Passar informação entre duas páginas PHP

Question: boa tarde! Eu estou tendo o seguinte problema: eu tenho uma página php denominada localidade que possui os campos "nome" e "cidade". No campo nome, eu digito o nome da localidade, como por exemplo, "Rincão Bonito", e no campo cidade eu recupero de uma tabela tebelaCidades. Acontece que quando eu clico no botão "Pesquisar", por meio da url do controller, a página que contém a tabela de cidades é acessada, ou seja, se antes o link era http://jfsjunior.tcc.sistema/localidade/cadastro, agora se torna http://jfsjunior.tcc.sistema/cidade/pesquisaCidade/tela-localidade. Quando eu clico em selecionar, o dado é carregado no input da cidade corretamente, mas o que o nome que eu digitei no campo nome volta vazio. Eu sei que como eu chamo a página localidade para inserir os dados da cidade, então a página é renderizada e, logo, todo campo que tinha sido preenchido, volta vazio. Então a questão é: como eu posso resolver esse problema?
Obs.: estou usando o framework Laravel (template engine Blade).
Desde de já agradeço.
Comment: Eu acho que o problema está na construção da aplicação. Você manda para outra página para pesquisar a localidade e, em seguida, retorna para  a mesma página com os dados preenchidos? Não seria melhor usar AJAX?
Comment: Pois é @Wallace Maxters, já me disseram isso, mas eu não tenho muito conhecimento sobre ajax, e infelizmente não tenho tempo (tcc), para estudar Ajax, daí publiquei com a esperança que alguém tivesse passado por algo semelhante e pudesse compartilhar suas conquistas ou como conseguiu resolver o problema.
Answer: No botão coloque coloque um evento onClick assim:

Crie um javascript simples
function procuraPelaCidade(){
   var nome = document.getElementById("#idDoCampoNome").value;
   var cidade = document.getElementById("#idDoCampoCidade").value;
   window.location = "jfsjunior.tcc.sistema/localidade/"+cidade+"/"+nome;
}

Se voce está usando laravel, você pode passar os dados que precisar pela rota.
Por exemplo,
Route::get('jfsjunior.tcc.sistema/localidade/{cidade}/{nome}',['as'=>'localidade.view', 'uses'=>'nomeDoController@view']);

Não precisa ser exatamente assim, pode passar o nome da cidade e nome, como você deseja, é so um exemplo.
Dentro do nomeDoController faça um function assim:
 public function view($cidade, $nome){
   return view('tela-localidade', compact('cidade','nome'))
 }

Crie uma página nova tela-localidade.blade.php ou altere aquela mesma página para com inputs assim:
  @if($cidade != null)
  <input id="idDoCampoCidade" value="{{$cidade}}">
  @endif
  @if($nome != null)
  <input id="idDoCampoNome" value="{{$nome}}">
  @endif

Seria realmente mais facil usando um ajax, mas creio que assim funcione também. Se tiver alguma falha de codigo minha, parta da ideia de redirecionamento de paginas por javascript, simples. Crie uma rota com os parametros desejados. Manipule o redirecionamento com valores passados dentro do controller da rota. Trate esses mesmos valores pelo blade.
Comment: Obrigado João V. Araújo!
Comment: então, eu capturaria os dados da página localidade, faria a pesquisa na página pesquisaCidade e depois carregaria a página localidade com os dados capturados previamente junto com a cidade selecionada? Mas no caso, se são mais de dois dados? Assim, e tenho outras telas com o mesmo problema e têm mais campos (indiquei a da localidade por ser mais simples). Ficaria complexa a url não?
Comment: Você pode passar multiplos valores pela url sim, ou esse valor passado pode ser um json ou array. Se nao me engano. Voce so precisa fazer com que as rotas na pasta routes, no arquivo web.php aceitem valores na url. E depois manipule pelo metodo responsavel pela contrução da pagina. Entendeu?
Comment: Entendi... então eu posso passar um array pela url? Daí creio que fique melhor... vou pesquisar a respeito e implementar e posto o resultado!
Comment: De uma olhada aqui:
https://laracasts.com/discuss/channels/laravel/not-able-to-pass-this-array-to-controller-through-route

E aqui tambem:
https://stackoverflow.com/questions/35359419/laravel-redirectroute-with-an-array-parameter
Comment: Espero ter ajudado em algo


List element needs to be clicked twice when checking if it has a class

Question: made a basic list with the option to click the items and then it would show the next ul.
This works, but when there is already a list shown, and you try to click on another heading you need to click that heading twice before it shows the related ul.
An example is this fiddle: http://jsfiddle.net/yu8ac6g7/
By default, the extra lists are hidden. To replicate my issue:

click on the first item so the next ul is shown
then click on the second so the first ul is hidden and the second is shown.

Now, if you try to click on the first item nothing happens. You have to click the item again before the jQuery action happens. This will be the same until you reload the page.
Any help / a better way of doing what I am trying?
Backup code:
$(".expanding_mobile_tab").on('click', function () {
    if ($(this).hasClass('mobile_tab_closed')) {
        $(this).removeClass('mobile_tab_closed').addClass('mobile_tab_open');
        $(".features_mobile_details_tab").hide();
        $(this).next('ul').fadeToggle();
        $('html,body').animate({
            scrollTop: $(".mobile_detail_tabs").offset().top
        }, 800);
    } else {
        $(this).removeClass('mobile_tab_open').addClass('mobile_tab_closed');
        $(this).next('ul').fadeOut();
        console.log('close');
    }
});

Features

Registration  FFF FFFF

Colour  Black

Year  2013

Fuel Type  Diesel

Mileage  16336

Combined MPG  62.80

Transmission  Automatic

Tax Band  C

Engine Size (cc)  1,995

CO2 (g/km)  118

Body Style  2

4 Wheel Drive  No

Spec Check

Armrest front, sliding : £140

Automatic transmission : £1550

Centre armrest for rear seats : £75

Enhanced Bluetooth telephone preparation with USB audio interface and Voice Control : £430

Exterior mirrors - folding, auto dimming : £300

Media package - BMW Business : £990

Metallic paint : £645

Seat heating for driver and front passenger : £325

Sun protection glass : £265

Comment: FYI your `ul`/`li` code is invalid - only `li` elements can be immediate children of `ul`.
Answer: That is because clicked element does not have the required class used in if condition. You can rather check for visibility of next ul element to make show/hide decision :
$(".expanding_mobile_tab").on('click', function () {
 if (! $(this).next('ul').is(':visible')) {
    $(this).removeClass('mobile_tab_closed').addClass('mobile_tab_open');
    $(".features_mobile_details_tab").hide();
    $(this).next('ul').fadeToggle();
    $('html,body').animate({
        scrollTop: $(".mobile_detail_tabs").offset().top
    }, 800);
} else {
    $(this).removeClass('mobile_tab_open').addClass('mobile_tab_closed');
    $(this).next('ul').fadeOut();
    console.log('close');
}});

Working Demo
Answer: You can simply do it as follows:
$(".expanding_mobile_tab").on('click', function () {
    $('.expanding_mobile_tab').toggleClass('mobile_tab_closed')
                              .toggleClass('.mobile_tab_open');
    $(".features_mobile_details_tab").not($(this).next()).hide();
    $(this).next('ul').fadeToggle();
    $('html,body').animate({
        scrollTop: $(".mobile_detail_tabs").offset().top
    }, 800);
});

Updated Fiddle
Answer: try this
Fiddle
$(".expanding_mobile_tab").on('click', function () {
    if ($(this).hasClass('mobile_tab_closed')) {
        $(".mobile_tab_open").removeClass('mobile_tab_open').addClass('mobile_tab_closed');
        $(this).removeClass('mobile_tab_closed').addClass('mobile_tab_open');
        $(".features_mobile_details_tab").hide();
        $(this).next('ul').fadeToggle();
        $('html,body').animate({
            scrollTop: $(".mobile_detail_tabs").offset().top
        }, 800);
    } else {
        $(this).removeClass('mobile_tab_open').addClass('mobile_tab_closed');
        $(this).next('ul').fadeOut();
        console.log('close');
    }
});


Custom Module not showing up

Question: Playing around with Drupal 8 and trying to create a custom module with a custom block:
I have a module.info.yaml file:
name: Custom Module
description: Description Here
package: Custom Module
type: module
core: 8.x

dependencies:
  - block

I have a src/Plugin/CustomBlock/CustomBlock.php file:
<?php

/**
 * Provides a 'Custom' Block
 *
 * @Block(
 *   id = "custom_block",
 *   admin_label = @Translation("Custom Block"),
 * )
 */

namespace Drupal\custom_block\Plugin\Block;

use Drupal\Core\Block\BlockBase;

class CustomBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {
    return array(
      '#markup' => $this->t('Hello, World!'),
    );
  }
}

The module is in /modules/custom/module. I have installed contrib modules in /modules/contrib with no issue.
If I go to the Extend page, my module is not listed.
Please let me know what I am missing here?
Answer: Typo on the module file name:
module.info.yaml

Should be
module.info.yml

Comment: Yep. D8 only requires `.info.yml` file in order to show up on the module's page.
Answer: EDIT: I think I'm mistaken, sorry!  For now, just putting this note into the comment -- when I have a more definitive answer, I'll update again.

FWIW, with Drupal core 8.7.7, our custom module didn't show on /admin/modules until I added the new core_version_requirement key to mymodule.info.yml, i.e.
core_version_requirement: '^8'

For now, I kept the old core: 8.x line in there, too, b/c I'm unsure whether it's good/bad/neutral to have both -- I think it's still being decided, tbh.  Speaking of which, there's a change record and a ton of issue threads (active and completed) you can check out to learn more, if you wish:

8.7.7 release notes excerpt:

Core versioning support in *.info.yml files
  Drupal 8.7.7 introduces a new core_version_requirement key to
  *.info.yml files, allowing contributed modules to specify specific versions for Drupal core compatiblity, as well as to indicate that
  they are compatible with both Drupal 8 and the forthcoming Drupal 9
  release. See the change record for more details.

Change record (mentioned in that excerpt)
Main issue thread for this functionality -- plus all the related
issues listed on the right.
Answer: Also make sure your web server has file permissions to the module.
Answer: Web server permissions may indeed be the issue, especially if everything else seems fine.
https://www.drupal.org/docs/security-in-drupal/securing-file-permissions-and-ownership
I constantly run this set of commands because my Windows ftp client sets ownership to my-user:my-user.  Your web server might not be apache.
(requires a symlink to your drupal root folder from the server root)
cd /drupal9
sudo chown -R my-user:apache .
sudo find . -type d -exec chmod 750 '{}' \;
sudo find . -type f -exec chmod 640 '{}' \;
cd web/sites
sudo find . -type d -name files -exec chmod 770 '{}' \;
for d in ./*/files
do
   sudo find $d -type d -exec chmod 770 '{}' \;
   sudo find $d -type f -exec chmod 660 '{}' \;
done

Custom Module not showing up


MySQL 8.0 Workbench hangs on fetching but can access tables

Question: I just downloaded the latest version of MySQL workbench and MySQL for windows 10. I'm working with a very small tutorial database. In the Schemas tab, some of the tables, views, stored procedures, and functions have "fetching..." next to them, which never resolves. Others do resolve. For the tables listed as "fetching..." I am able to work with them directly via SQL commands. I just can't browse them using the workbench. Any ideas what's going on?
Comment: Does this answer your question? [Tables and views keep on fetching in MYSQL](https://stackoverflow.com/questions/57905821/tables-and-views-keep-on-fetching-in-mysql)
Answer: For me it worked by just closing the Workbench and reopening again.
Answer: Does this persist with a refresh of the database (right click and select refresh/refresh all)?  IF so, that seems like either there's a lot of meta data that is clogging up the processing or perhaps an issue with the installation of the Workbench.  If it persists, especially with other datasets, I'd uninstall/reinstall.  Apologies for not being able to provide more!


How to attack zone defense?

Question: What gameplays do you use to attack a zone defense, and specially 2-1-2 type? And how do you work it in practice?
I usually practice it with game situation, but are there some exercises to develop team level?
I also appreciate if you have videos, articles or book to recommend.
Answer: There are many ways to attack a zone. This article suggests three strategies:

Play your best ballhandler in the middle (high post)
Attack behind the zone (short corner)
Attack gaps in the zone

Another article has some other suggestions:

Attack the weakside

Another strategy is to attack using outside shots (three pointers or long two's), but such this method is only effective if you have several good/accurate long range shooters.
In general, all of these strategies attempt to take advantage of the zone's gaps in defensive coverage. Good ball movement can pull the defenders out of position, leaving your players with a (hopefully) easy, undefended shot.
Comment: Combination of quick passing and movement is definitely the key to breaking the zone. Addition to the outside shot strategy: this will only work with slow defenders in top zones. Guys who are quick on their feet will get in your face even when you're on the 3pt line so you'll have to work extra hard to set up an open shot.
Comment: @DmitrySelitskiy: I don't agree with you, the cure for crushing the zone defense has pretty much always been sinking 3 pt.s. If it works in the top leagues (where you'd expect the guards to be quick) it will work in the lower leagues as well.
Answer: @JW8 is pretty much on the ball there, I just want to add that good zone will usually employ double teams on critical players. Moving the ball around to find the open player is the best way to tire and frustrate the opponent. If you have a good shooter that's even better. Otherwise having a strong man inside (pivot/center in European/American terms) will facilitate things as he can force his way to the basket, either playing 1-2-1 or pulling in a secondary defender, which in that case he can dish out an assist to the open player.
What might happen is that if there is a designated shooter in the team and it's pretty obvious that you anti-zone offense is built around getting him to shoot long distance, then the defending team might go to a hybrid defense, where they give one quick defender on your shooting guard, and the rest stays on a zone defense. Wouldn't hurt to be prepared for that :)

How to attack zone defense?