text:
Q: How to handle a dict variable with 2^50 elements? I have to find SHA256 hashes of 2^25 random strings. And then look for collision (using birthday paradox for the last, say, 50 bits of the hash only).
I am storing the string:hash pair in a dict variable. Then sorting the variable with values (not keys) and then looking for collision using a O(n) loop.
The problem is that since there are 2^25 strings and their 2^25 hashes, so the dict variable has 2^50 values in it. This is EXTREMELY resource intensive. So, how do I do this with limited RAM, say, around 1GB?
What I have already tried:
1. Running this with a 6GB swap space. The program ran overnight and was still not done. This is essentially even slower than an O(n_square) search! The hashes are calculated with RAM usage of about   3.2 GB. But after that when it comes to the sort command, the RAM used starts shooting up again! I though the python sort uses In-Place-Quicksort :(
2. I have stored only the hashes and found a collision. But could not find the corresponding string since did not store it.
I am not supposed to use databases etc. At the most a text file but that doesn't help. Also, I am pretty new to Python but do not let that limit the level of your answer.
PS: this is an assignment. Some claim to have found the collisions in under one minute with 300MB RAM. Don't know if that is true. I have solved the problem but the answer is unreachable!
At work so do not have access to code right now. Will add soon.
Code:
from Crypto.Hash import SHA256
import os
import random
import string
from operator import itemgetter

def shaa():

    trun=[]
    clist={}
    for i in range(0,33554432):

        sha=SHA256.new(str(i)).hexdigest()
        sha=int(bin(int(sha,16))[-50:],2)
        clist[i]=sha

    print 'Hashes done.'

    clist=sorted(clist.items(), key=itemgetter(1))
    for i in range(0,33554432):

        if(clist[i]==clist[i+1]):
            #print string[i],string[i+1]
            print clist[i]
            return 1
    return 2

result=2
while(result==2):
    result=shaa()

A: I'd go for something like this:
Open 16 files (opened in binary mode should be fine; this will be easiest if all your strings have the same length).  Generate your strings and hashes, and write them to a file depending on the first 4 bit of the hash.  Then load and process each file separately.  This will reduce memory usage by a factor of 16.  (Of course you can use any number of files as long as you don't run out of file handles.  Having to open and close each file on every access will become rather slow.)
If generating the strings and hashes is relatively inexpensive, you don't even need the files.  Simply do 16 passes, and in each pass keep only thoses hashes the upper nibbles of which match the pass number.

A: One way to solve the problem is to use a very long bitfield, so that every hash is mapped to certain position in 2^25 bits long memory block.
A better, yet non-100%-assurance manner to solve this kind of problems is done via Bloom filter or other probabilistic data structures.

A Bloom filter is a space-efficient probabilistic data structure that is used to test whether an element is a member of a set. False positives are possible, but false negatives are not; i.e. a query returns either "inside set (may be wrong)" or "definitely not in set".
Bloom filters have a strong space advantage over other data structures for representing sets, such as self-balancing binary search trees, tries, hash tables, or simple arrays or linked lists of the entries.
A Bloom filter with 1% error requires only about 9.6 bits per element — regardless of the size of the elements.

So, 9.6 bits per 2^25 elements, will need just 38.4 MiB of memory.

A: I think the key insight here -- which I admit evaded me for some time, till I came back to this a few hours later -- is that the sha256 hash digest is its own hash. In other words, you don't have to do any additional hashing or set creation. All you have to do is create a custom hash table, using the sha256 digest as the hash. To save space, don't store the strings; just create a bit-array (using shift operations on integers in an array of ints created with table = numpy.zeros(table_size / bits_per_int + 1, dtype='i')) to detect collisions, and then save colliding strings in a dict mapping hashes to strings for lookup in a second pass.
table_size should be a large prime -- I picked one slightly larger than 2 ** 31, which made for a 268MB table -- because that will produce few new collisions/false positives (introduced by the modulo operation on the hash). You can save the strings themselves to a text file, which you can iterate over.
So for any string, the index of the corresponding bit to set would be index = int(hashlib.sha256('foo').hexdigest(), base=16) % table_size. Then calculate the major_index = index / bits_in_int and minor_index = index % bits_in_int, use shift and bitwise operations on minor_index to check and store the correct bit in the int at table[major_index], and so on.
Now do a pass through the strings. Whenever a string generates a hash that maps to a bit that has already been set, store a hash:string pair in a dictionary. Or better yet, store a hash:[string_list] pair, appending new strings to the list in the case of multiple collisions. Now for any colliding pair of strings (a, b), the dictionary will contain the hash and value of b. Then do a second pass through the strings, hashing each in turn, and checking the dictionary for each hash. If the hash is in the dictionary, and the string is not already in the corresponding list, add the string to the list. Some of the strings in the dictionary will not correspond to true collisions; the [string_list] for most of those hashes will be only one-item long, and those hash:[string_list] pairs may be discarded. The others are probably true collisions resulting from the hash function itself, rather than from the modulo operation. However, you may still have a few false positives to weed out, in those cases where there was both a true and a false positive; you'll have to double-check the resulting lists for false positives.
BasicWolf's suggestion of using a bloom filter is a good one, and might result in a smaller table. But it adds a lot of complication; I didn't bother. I tried the above method on newline-terminated strings from '0\n' to '33554431\n' and found two hashes with a 54-bit overlap. It took 11 minutes, and the maximum memory usage was about 350MB (though that could probably be reduced.) I did some profiling and found that most of the time was spent calculating offsets for the bit-table. Coding this in c would probably provide a significant speed-up, and pre-hashing and storing the hashes as well as the strings would help too.
In fact, I tried pre-hashing the strings, and replaced my rather ad-hoc numpy-based bitarray with a bitarray from the c-based extension module of the same name. This reduced the runtime to just over 2 minutes, while keeping the memory profile just around 350MB.
Close enough for government work, I think. Since this is an assignment, I won't post the code, but I'm happy to provide additional pointers.

A: Why don't you use a dictionary from last-50-bits-of-hash to string?

A: Split the hashed for example in groups of 10 chars. And nest the values this way you will have recursive search but it should be faster


text:
Q: Responsive navbar design I'm learning about responsive web design and now my webpage is almost 100% responsive. The only problem is the navbar, when it turns into a hamburger menu, it should show the dropdown menu when you click on it but it does nothing, I used some javascript because of the tutorial I was watching, but I don't how to use it at the moment.
Here's the html of the navbar:

      <button class="hb-button">

INICIO

CONTACTO

REGISTRATE

INICIAR SESION

      </button>

INICIO

CONTACTO

Contactanos

              <form>
               <input type="text" name="" placeholder="Tu nombre">
               <input type="text" name="" placeholder="Tu apellido">
               <input type="text" name="" placeholder="Tu e-mail">
               <textarea name="" id="" cols="30" rows="10" placeholder="Tu mensaje"></textarea>
               <input type="submit" name="" value="Listo" >
              </form>

REGISTRATE

Ingresa tus datos

              <form>

¿Cómo te llamas?

                <input type="text" name="" placeholder="Tu nombre">

¿Cuál es tu apellido?

                <input type="text" name="" placeholder="Tu apellido">

¿Cuándo naciste?

                <input type="date">

¿Cómo es tu correo?

                <input type="text" name="" placeholder="Tu e-mail">

Elige una buena contraseña

                <input type="password" name="" placeholder="Elige una contraseña">

Confirmala (¡por si acaso!)

                <input type="password" name="" placeholder="Confirmala">
                <input type="submit" name="" value="Listo" >
              </form>

INGRESAR

Datos

              <form>

                <input type="text" name="" placeholder="Escribir e-mail">

                <input type="password" name="" placeholder="Escribir Contraseña">
                <input type="submit" name="" value="Listo">
                ¿Contraseña olvidada?
              </form>

As you can see, I've made one navbar for the computer and another one for the hamburger menu, now look how I'm trying to make it come to life in css:
.hb-button{
                float: right;
                background: #222;
                color: #ffffff;
                border: none;
                font-size: 18px;
                padding: 5px 10px;
                border-radius: 3px;
                cursor: pointer;
                display: none;
            }
            nav{
                float: right;

                width: 100%;
                float: right;
            }
            nav ul{

                margin: 0;
                padding: 0;
                text-align: center;
                list-style: none;
                position: relative;
                z-index:1000;
                float: right;
            }
            nav li{
                float: right;
                display: inline-block;
                margin-left: 3.66%;
                padding: 1.46%;
                position: relative;
            }
            nav a{
                color: lightgrey;

            }
            nav a:hover {
                color: white;
                text-decoration: none;

            }
            body{
                margin: 0;
                background: #15151515;
                font-family: sans-serif;

            }
            @media screen and (max-width: 768px){
                .logo{
                    float: none;
                }
                .menu.show{
                    max-height: 20em;
                }
                .hb-button{
                    display: inline;
                }
                .superbanner{
                    display: none;
                }
                .values{
                    display: none;
                }
                nav ul li{
                    display: none;
                }
            }

I think that's enough for you to see of the css, the rest is just some details for the font and the hover of the normal navbar. And this is what the tutorial made me do on javascript (which I don't really understand):
$(document).ready(function(){
                $('.hb-button').on('click', function(){
                    $('menu').toggleClass('show');
                });
            });

I hope I was clear, if you need any more info of my program please make me know, thanks.

A: Kavindra is right. You should use .mobilemenu instead.
$(document).ready(function(){
    $('.hb-button').on('click', function(){
        $('.mobilemenu').toggleClass('show');
    });
});

I see that li is display: none when width is < 768px. You may also add this inside your media query
.show li {
    display: inline-block;
}

A: You mobile menu has the class mobilemenu. But in your code you add toggle class in menu. It should be;
$(document).ready(function(){
    $('.hb-button').on('click', function(){
        $('.mobilemenu').toggleClass('show');
    });
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Extracting data from a custom listview I have created a custom listview with two TextViews with ID text1 and text2. text1 shows a place and text2 shows a description. At first when I implemented the onListItemClicked method and fed the data into a toast it showed the data in the first textview which is the place in text1. Now wanted to extract from text 2 so found an answered suggested by someone here on S/O but it now only extracts data from the text2 of the first list item and not where I have clicked. Any idea how to get data dynamically? Not familiar with data sources so all data is in 2arrays,or is there no way and I have to get data at that position from the second array that holds descriptions? Some code from the custom list class:
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    View parentView =(View)v.getParent();
    String text;
    text=((TextView) parentView.findViewById(R.id.text2)).getText().toString();
        Toast.makeText(this, text+" !here(description)",
        Toast.LENGTH_LONG).show();
}

A: The View v in onListItemClick represents the ViewGroup for the row you've clicked. Therefore, you don't need the getParent method. Change your code as follows:
@Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
    String text;
    text=((TextView) v.findViewById(R.id.text2)).getText().toString();
    Toast.makeText(this, text+" !here(description)", Toast.LENGTH_LONG).show();
}

The parentView, as you have it, would refer to the entire ListView's view hierarchy. Within that, there would be multiple Views that each contain a TextView with id == R.id.text2. I would guess that findViewById would just grab the first one it finds in that hierarchy, which is why it's always returning the value from the first row.


text:
Q: How do i make a div stick down from his div container? So i have Three Divs. One container and two inside. The thing i want to do is kind of a sticky footer.

HTML:

CSS:
.container{
    width:500px;
    height:500px;
    background:green;
}

.one{
    width:100%;
    height:50px;
    background:blue;
}

.two{
    width:100%;
    height:50px;
    background:red;
}

I know it maybe a rookie question, but im here to learn and i didnt find an answer.
Here is a JSFIDDLE: http://jsfiddle.net/oz0amshe/
If someone can tell me how do i make to .two stay down of .container i will be very happy.
Thank you all for your support.

A: Depending on your needs, it may be enough to simply position the div absolutely in relation to the container. So for example:
.container {
  position: relative;
}
.two {
  position: absolute;
  bottom: 0;
}

Here your adjusted fiddle.


text:
Q: Understanding the memory ordering for C++ atomics in a single thread According to the point 1.10.19 in http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf, the compiler cannot reorder the atomic operations on same object even in the relaxed ordering.
Below is my understanding on the memory ordering (considering only single thread):

*

*Incase of memory_order_seq_cst the atomic operations irrespective on any object cannot be reordered.

*Incase on memory_order_release/memory_order_acquire, as stated above the atomic operations on same object cannot be reordered.

My question is about the ordering of the Atomic operations on different objects in case of acquire/release ordering?
Question can be better understood from  https://www.youtube.com/watch?v=A8eCGOqgvH4 starting at 42:30.
Now in case of operations on same object as stated in the draft they cannot be reordered hence "SC Acq/Rel" is followed, but what about operations on different objects? Can the condition mentioned in "Plain Acq/Rel" in the video happen in this case i.e. acquire of one object be reordered above the release of other?


text:
Q: List.split output trouble I was practicing some coding and I decided to make a parrot translator. The basic point of this game is, that after every word in a sentence, you should put the syllable "pa". I had written the code for that:
    print("This is the PARROT Translator!")
    original = input("Please enter a sentence you want to translate: ")

    words = list(original.split())

    for words in words:
         print(words + "pa")

but the problem I have and I dont know how to fix is, when I split the sentence, the output wont be in the same line, but every word will be at it's own.

A: You should use end="" at the end of your print:
print(words + "pa", end="")

EDIT:
For explanation you can read here

A: I am not very good in python, so possibly you will have some issues with version support, but this should work in most cases
import sys

print("This is the PARROT Translator!")
original = input("Please enter a sentence you want to translate: ")

words = list(original.split())

for word in words:
  sys.stdout.write(word + "pa")


text:
Q: Can't install latest Steam on Ubuntu LTS 20.04 Focal Fossa So I cannot install steam at all... It complains about many dependencies that can't be installed.
Steam says it needs: libgl1-mesa-dri:i386 libgl1:i386
Output of apt-cache policy libgl1-mesa-dri:i386 libgl1:i386
libgl1-mesa-dri:i386:
  Installed: (none)
  Candidate: 20.0.4-2ubuntu1
  Version table:
     20.0.4-2ubuntu1 500
        500 http://us.archive.ubuntu.com/ubuntu focal/main i386 Packages
     19.2.8-0ubuntu0~19.10.3 -1
        100 /var/lib/dpkg/status
libgl1:i386:
  Installed: (none)
  Candidate: 1.3.1-1
  Version table:
     1.3.1-1 500
        500 http://us.archive.ubuntu.com/ubuntu focal/main i386 Packages

Output of sudo aptitude install libgl1-mesa-dri:i386 libgl1:i386
The following NEW packages will be installed:
  libatomic1:i386{a} libdrm-amdgpu1:i386{a} libdrm-intel1:i386{a} libdrm-nouveau2:i386{a} libdrm-radeon1:i386{a} libdrm2:i386{a} libedit2:i386{a} libelf1:i386{a} libexpat1:i386{a}
  libffi7:i386{a} libgl1:i386 libgl1-mesa-dri:i386{b} libglapi-mesa:i386{ab} libglvnd0:i386{a} libglx-mesa0:i386{ab} libglx0:i386{a} libllvm9:i386{a} libpciaccess0:i386{a}
  libsensors5:i386{a} libstdc++6:i386{a} libvulkan1:i386{a} libwayland-client0:i386{a} libx11-xcb1:i386{a} libxcb-dri2-0:i386{a} libxcb-dri3-0:i386{a} libxcb-glx0:i386{a}
  libxcb-present0:i386{a} libxcb-randr0:i386{a} libxcb-sync1:i386{a} libxdamage1:i386{a} libxfixes3:i386{a} libxshmfence1:i386{a} libxxf86vm1:i386{a} libzstd1:i386{a}
  mesa-vulkan-drivers:i386{a}
0 packages upgraded, 35 newly installed, 0 to remove and 0 not upgraded.
Need to get 30.1 MB of archives. After unpacking 382 MB will be used.
The following packages have unmet dependencies:
 libglapi-mesa : Breaks: libglapi-mesa:i386 (!= 20.1~git2003140730.b93a19~oibaf~e) but 20.0.4-2ubuntu1 is to be installed
 libglapi-mesa:i386 : Breaks: libglapi-mesa (!= 20.0.4-2ubuntu1) but 20.1~git2003140730.b93a19~oibaf~e is installed
 libgl1-mesa-dri : Breaks: libgl1-mesa-dri:i386 (!= 20.1~git2003140730.b93a19~oibaf~e) but 20.0.4-2ubuntu1 is to be installed
 libgl1-mesa-dri:i386 : Breaks: libgl1-mesa-dri (!= 20.0.4-2ubuntu1) but 20.1~git2003140730.b93a19~oibaf~e is installed
 libglx-mesa0 : Breaks: libglx-mesa0:i386 (!= 20.1~git2003140730.b93a19~oibaf~e) but 20.0.4-2ubuntu1 is to be installed
 libglx-mesa0:i386 : Breaks: libglx-mesa0 (!= 20.0.4-2ubuntu1) but 20.1~git2003140730.b93a19~oibaf~e is installed
The following actions will resolve these dependencies:

     Keep the following packages at their current version:
1)     libgl1:i386 [Not Installed]
2)     libgl1-mesa-dri:i386 [Not Installed]
3)     libglapi-mesa:i386 [Not Installed]
4)     libglx-mesa0:i386 [Not Installed]
5)     libglx0:i386 [Not Installed]

If I try to say "No", aptitude offers to remove practically every package I have (including all stuff needed for KDE Plasma, Latte, etc.
Output of neofetch:
OS: Ubuntu 20.04 LTS x86_64
Host: SVS1511BFXB C60AZDBR
Kernel: 5.4.0-26-generic
Uptime: 43 mins
Packages: 3385 (dpkg), 3 (snap)
Shell: zsh 5.8
Resolution: 1920x1080 @ 59.94Hz, 1920x1080 @ 60.00Hz
DE: Plasma
WM: KWin
WM Theme: Gently
Theme: Gently [Plasma], Breeze-Dark [GTK2/3]
Icons: MB-Cherry-Suru-GLOW [Plasma], MB-Cherry-Suru-GLOW [GTK2/3]
CPU: Intel i7-3612QM (8) @ 3.100GHz [154.4°F]
GPU: Intel 3rd Gen Core processor Graphics Controller
GPU: NVIDIA GeForce GT 640M LE
Memory: 2484MiB / 11880MiB (20%) [---============]
GPU Driver: i915
Font: Iosevka Nerd Font Regular 10 [Plasma], Iosevka Nerd Font, Light 10 [GTK2/3]
Locale: en_US.UTF-8

A: This is likely due to mismatched multiarch packages.
The most useful post I've found is this from @kisak:

The most common situation with Ubuntu is that a newer version of a 64 bit package got installed, but the package manager doesn't have the exact same version available for 32 bit. Debian's multiarch implementation requires that all 64 bit and 32 bit variants of a package have the exact same version. Apt won't automatically pull in an older 64 bit version of a package than what's installed in order to allow the 32 bit variant to proceed and simply tells the user it's not going to happen.

For me, it was an issue with libllvm11 after upgrade where I had a :amd64 version from a llvm-toolchain ppa. The :i386 version from the mesa ppa could not match it, which was shown by running this command:
$ apt policy libllvm11 libllvm11:i386

Only found which package was the problem by experimental install/remove and seeing what caused the entire desktop environment to want to uninstall.
In your case, I note you have mesa packages with the version 20.1~git2003140730.b93a19~oibaf~e which suggests they're from ppa:oibaf/graphics-drivers rather than the (similar) Valve ppa:kisak/kisak-mesa. So, it may be worth purging the existing graphics stack, and installing the other one to see if that's the cause.
sudo apt install ppa-purge
sudo ppa-purge ppa:oibaf/graphics-drivers
sudo add-apt-repository ppa:kisak/kisak-mesa
sudo apt-get update
sudo apt-get dist-upgrade

That's a little destructive, so if you can work out the exact problem package(s) and downgrade first, that may be safer.


text:
Q: findViewById() returns null in sum of two integers simple application I am new to android.I have written code for Sum of two integers. I am getting NULLPointerException. findViewById() method returns null. Can someone help me to fix the error.
    <EditText
        android:id="@+id/firstInt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:hint="@string/InputHint"
        />

    <EditText
        android:id="@+id/secondInt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:hint="@string/InputHint"
        />

    <TextView
        android:id="@+id/result"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Result"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:textSize="18dp"
        />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/add"
        android:layout_gravity="center"
        android:onClick="calculateAdd"/>

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

        EditText e1 = (EditText)findViewById(R.id.firstInt);
        EditText e2 = (EditText)findViewById(R.id.secondInt);
        TextView tv = (TextView)findViewById(R.id.result);
    }

    public void calculateAdd(View view){

            int x = Integer.parseInt(e1.getText().toString());
            int y = Integer.parseInt(e2.getText().toString());

            int z = x + y;

        tv.setText(z);
    }

It is a very simple program I have written. But, facing the issue.
My stack trace error:
java.lang.IllegalStateException: Could not execute method for android:onClick at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference

A: You are just Declaring the EditText inside the Scope of onCreate() method.
EditText e1, e2;
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    e1 = (EditText)findViewById(R.id.firstInt);
    e2 = (EditText)findViewById(R.id.secondInt);
    tv = (TextView)findViewById(R.id.result);
}

public void calculateAdd(View view){
    int x = Integer.parseInt(e1.getText().toString());
    int y = Integer.parseInt(e2.getText().toString());

    int z = x + y;
    tv.setText(z);
}

May this helps you.
if you need more information Please refer to this link https://stackoverflow.com/a/51688200/5343866


text:
Q: Error loading page on clicking an anchor tag in android phonegap app in ice cream sandwhich i am developing an android phonegap app using phonegap 1.3 and jquery mobile 1.0 My app works perfectly fine in all android versions before 4.0.0
But in 4.0.0 and above im facing an issue. I have an anchor which when users click, takes the to another 'page'.

    Whats up?

In the emulator having android 4.0.3, when i click on this i get an error saying "Error loading page" When i check the logs in logcat, i see an error saying
Unknown chromium error: -6

any idea as to what can i do to get it working?

A: Since you are using jQuery I would recommend to use jQuery to wire up your events as well. With that being said using e.preventDefault(); and e.stopImmediatePropagation(); should stop jQuery mobile from performing the default action on the .
$("#verify").click(function (e) {
    e.stopImmediatePropagation();
    e.preventDefault();
    //Do important stuff....
});

Update
The better way to use your existing markup would be to simply add rel="external" to your  And your onclick should behave correctly.

  VERIFY

This will work since jQuery Mobile will treat the link as a normal  tag and return false will simply stop the default action.

A: In jQuery Mobile, when you want to use  , you'd better use  rel="external" in  , in order to jump to target page correctly.
If you want to use JavaScript, you'd better not to use in , because href is hash allocation but not JavaScript code attribute.
jQuery Mobile do not support anchor. If you need to use anchor, you have to do some trade-off. You can reference this link, jQuery Mobile Anchor Linking

A: This error was coming because webkit in ics is broken in handling
?param=abc

with urls. So if u have a url like
domain.com?p1=a

which u hit, then you would get such an error. The best fix for now would be to test your webapp in browser and see when and where you add params to the url and remove those.
You can in place save those params  in localstorage and retrieve when needed.

A: Sometimes the jquery itself adds those url params in ajax requests. This is the case when you activated caching.
You could easily disable this feature for the whole project using:
$.ajaxSetup({ cache: true });

Hope this helps somebody.


text:
Q: How do I get shoes executable into my path? I'm getting started with shoes and the nks docs tell me two write a script and then launch it like this:
> shoes myapp.rb

the shoes executable is in the Shoes.app I installed. Thus, shoes is not in my path so I can't do this.
Tried symlinking shoes into /usr/local/bin but I get this error when I try to start it.
> shoes myapp.rb
FSPathMakeRef(/usr/local/bin/../../../Shoes.app) failed with error -43.

any ideas?
Geoff
PS. Additional information: OSX Leopard. Shoes version, Raisins. Installed from dmg. The link was made from and absolute path ->
> sudo ln -s /Applications/Shoes.app/Contents/MacOS/shoes shoes

A: You need to give an absolute path when making the symlink
and you need to give the path inside the app bundle, such as Shoes.app/Contents/MacOS/Shoes maybe
Edit:
you could always add the following line to your .profile (assuming bash)
export PATH=$PATH:/Applications/Shoes.app/Contents/MacOS/

although it's not a very nice solution
Edit:
alias shoes=/Applications/Shoes.app/Contents/MacOS/shoes

may be a cleaner solution


text:
Q: Graph embedded in PyQt5 is black without showing anything I wanted to plot a graph in a PyQt5 window but it is completely black. I followed this tutorial and tried replacing my code with the static_canvas the author wrote, but its still black. Complete code works fine, the problem arises when I only keep a single graph.
My code:
from PyQt5 import QtCore, QtGui, QtWidgets
from matplotlib.backends.backend_qt5agg import FigureCanvasQT
from matplotlib.figure import Figure
import matplotlib.pyplot as pyp

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.centralwidget)
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.horizontalLayout_2.addLayout(self.horizontalLayout)
        MainWindow.setCentralWidget(self.centralwidget)

        self.canvas = FigureCanvasQT(Figure())
        self.horizontalLayout.addWidget(self.canvas)

        self.ax = self.canvas.figure.subplots()
        values = [i+1 for i in range(10)]
        axe = [i for i in range(10)]
        self.ax.plot(axe, values)
        # pyp.show() doesn't do anything

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

Regardless of what I try to plot, the result is the same black window. What is the issue?
Also, how do I go about linking a function that plots something to the FigureCanvasQT? I want to embed a function from a different file to do and show the plot without having to write so much code in the window file.

A: In the tutorial that links FigureCanvasQT is not used but FigureCanvas. When analyzing the source code it is observed that FigureCanvasQT is FigureCanvas but when exporting(see here) it as _Backend more properties are added. So the solution is to change to:
from matplotlib.backends.backend_qt5agg import FigureCanvas

# ...
self.canvas = FigureCanvas(Figure())
# ...


text:
Q: Sending JS variable data to a downloadable page This javascript function takes JSON and formats it to XML.  The data is a long XML string, whic I would like to allow the user to download. I'm trying to use ajax to post the data to a php page wichi will create the file and then allow the user to download it.
 json2xml(eval(data));

JS
 $.ajax({
   type: 'POST',
   url: 'download/functions.php',
   data: xml2,
   dataType: XML
 });

I have used this PHP function to write to a file, but I'm not sure how to now send the js variable to this function.
 $data = $_POST['xml2'];

 writetoxml($data, 'WF-XML'.$current. '.xml');

 function writetoxml($stringData, $myFile) {
    $current = date('m-d-Y-g-i-s');
    $fh = fopen('download/'.$myFile, 'w') or die("can't open file");
    fwrite($fh, $stringData);
    fclose($fh);
    download($file);
  }

 function downloadFile($file) {

 if(!file)
 {
     // File doesn't exist, output error
     die('file not found');
 }
 else
 {
     // Set headers
     header("Cache-Control: public");
     header("Content-Description: File Transfer");
     header("Content-Disposition: attachment; filename=$file");
     header("Content-Type: application/csv");
     header("Content-Transfer-Encoding: binary");

     // Read the file from disk
     readfile($file);
     exit;
 }

}
This is currently returning a server 500 error.

A: Updated:
With your provided jQuery AJAX call:
$.ajax({
   type: 'POST',
   url: 'download/yourphpscript.php',
   data: { xml: xml2 },
   dataType: XML
});

Your PHP would look like this:
<?php
$xml = $_POST['xml'];
// Not sure where you're trying to get $file from

writetoxml($xml, $file);

function writetoxml($stringData, $myFile) {
    $current = date('m-d-Y-g-i-s');
    $fh = fopen('download/'.$myFile, 'w') or die("can't open file");
    fwrite($fh, $stringdata);
    fclose($fh);

    download($file);
}

function download($file)
{
    if (file_exists($file)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename='.basename($file));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        ob_clean();
        flush();
        readfile($file);
        exit;
    }
}
?>

Try passing an object  (in this case { key: value } into the data property of the $.ajax call so that you can reference it by your key.  In this case our key is xml so on the PHP side, we grab $_POST['xml'] and that should give you the contents of xml2.
The download code was taken from the PHP docs on readfile().  However, I still can't help but think there is a better way to accomplish this.
I would HIGHLY recommend against allowing the user to effectively create a web accessible file containing whatever they want on your server.  As aforementioned, a clarification of your general goal would be helpful.  I think I understand what you're trying to do but why you are doing it would be nice to know as there may be a better and safer way to accomplish the same result.


text:
Q: Knockout Mapping attempt not mapping with JSON responses I am new to knockout and cannot seem to get a simple mapping to work at all. I am in an MVC4 C#.
My View looks like such:
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
    ViewBag.Title = "Index";
}

Simple Mapping Example

The time on the server is:
and  user(s) are connected.

@section Scripts
{

}

Example JSON that is returned from the controller call 'Mapping/GetServerInfo' is:
{"ServerTime":"2013-03-13T14:24:10.5675104-07:00","NumberOfUsersConnected":5}

For the data-binds I have tried text and value, neither one causes any data to be bound and displayed.
Am I missing something really obvious?
As per the question in the comments yes this is what is in my Layout.

Thanks

A: From the $.getJSON documentation

The success callback is passed the returned data, which is typically a
  JavaScript object or array as defined by the JSON structure and parsed
  using the $.parseJSON() method.

So your the data variable is holding an already parsed object so you need to use the ko.mapping.fromJS method:
$.getJSON('/Mapping/GetServerInfo', function(data) {
   ko.mapping.fromJS(data, {}, vm);
});


text:
Q: Possible reasons why a valid PHP class method would not work I have this perfectly valid and defined PHP class method that just refuses to work. I have this class:
class SessionHandler{
    public function startSession(){
        ....
        ....
    }

    public function endSession(){
        ....
        ....
    }
}

So I instantiate object and call method:
$sessHandler=new SessionHandler();
$sessHandler->startSession();

It used to work, but somehow just stopped working, with this error:
Fatal error: Call to undefined method SessionHandler::startSession() in C:\wamp\www\mywebapp\models\user.php on line 212

I have gone over the code and cannot find anything wrong. The class and method I called are very much valid and fully defined. So I'm just wondering if there's some kind of bug in PHP that causes this behaviour. I use PHP version 5.4.16

A: PHP 5.4+ has it's own, built-in class named SessionHandler. Since the class already exists, whatever autoloading strategy you're using is not loading your version of SessionHandler.


text:
Q: AddThis button will not work inside AJAX, but will work normally Basically, this is what I'm doing.
User visits site, loads "index.html"
Within index.html, it automatically loads, through AJAX, "details.html" into a DIV.
I put an ADDTHIS button on "details.html".  However, for some reason , the roll-over doesn't work.
When I visit details.html in the browser, the roll-over works. I'm guessing it's because of the AJAX?

A: addthis.toolbox(".addthis_toolbox");

A: if i understand your question correctly, in the callback of the ajax function, bind the roll-over to the add-this button.
 $.ajax({
   type: "POST",
   url: "some.php",
   data: "name=John&location=Boston",
   success: function(){
     $('.addthis_button').hover(
       function(){
         //do mouse over
       },function(){
         //do mouse out
     });
   }
 });

you can also try
$('.addthis_button').live('mouseover',function(){//do mouseover});
$('.addthis_button').live('mouseout',function(){//do mouseout});

i've never used live, but it seems like it would work for you since your add_this button's get created after the $(document).ready()

A: Ran in the same problem and this solved it for me in all major browsers (IE6+, FF, Safari in MAC/XP):
http://joecurlee.com/2010/01/21/how-to-use-addthis-with-ajax-and-overflowauto/comment-page-1/#comment-24

A: I recently ran in to issues with using AddThis on an all AJAX site and was able to come up with a couple of solutions for this issue.
It turns out there is a variable that you can pass when loading the AJAX script as well as a way to re-initialize the script if the DOM is reloaded via AJAX.
I have posted the full solution in detail on my blog here:
http://joecurlee.com/2010/01/21/how-to-use-addthis-with-ajax-and-overflowauto/
To briefly summarize, the solution is loading AddThis with the variable domready=1 appended, and re-initializing the script by deleting the initial load and then reloading the script dynamically:
var script = 'http://s7.addthis.com/js/250/addthis_widget.js#domready=1';
if (window.addthis){
    window.addthis = null;
}
$.getScript( script );

A: I had the same problem. Fixed it with the following code. I hope that fixes it for you too.
Original Method:
    var script = 'http://s7.addthis.com/js/300/addthis_widget.js?domready=1';
    if (window.addthis){
        window.addthis = null;
    }
    $.getScript( script );

New Method:

In AJAX REQUEST you can use like this:-
$.ajax({
    url:Url,
    type: 'POST',
    cache: false,
    success: function(res){
        var script = 'http://s7.addthis.com/js/250/addthis_widget.js#domready=1';
        if (window.addthis) {
            window.addthis = null;
            window._adr = null;
            window._atc = null;
            window._atd = null;
            window._ate = null;
            window._atr = null;
            window._atw = null;
        }
        $.getScript(script);
        // your custom code
    }
});

A: It seems like the script is calling the onLoad event of javascript and using this ajax call won't actually trigger that event. You could try other "share this" widget?
Like http://sharethis.com/#STS=g12m3ugh.21zb
or pre-load that button?
Can you post a little bit more of the story on what are you doing?

A: Is details.html a fully compliant page on it's own? HTML, BODY, HEAD tags, etc?
If so, I think things can get kind screwy when you try to load it into another page. I would either change details.html to just include the barebones markup that you need - or - if you need it to still be individually accessible - you could use jQuery to strip out the needed bits after the ajax call and only inject that portion.
Details.html

    The needy bits.......

Index.html
$("#targetDivID").load("detail.html #details");

A: Add this snippet of .js to the .html you are loading. Replace "#atbutton" with your button's selector.

addthis.button("#atbutton");


text:
Q: Upload file to a server with jquery and java Im doing a webapp to upload files to a server.
I have this form in my view:
<body>
    <form>
        <input id="file" type="file" name="file">
        <input id="send" value="Upload" type="button" />
    </form>
</body>

And i send the file with jquery and ajax:
var form = new FormData();
    form.append('file', $("#file")[0].files[0]);

    $.ajax({
        type: 'POST',
        url: 'http://localhost:8080/UploadMotion/upload',
        cache: false,
        contentType: false,
        processData: false,
        data: form,
        success: function (data) {
            alert("Funciono");
        },
        error: function () {
            alert("Fallo");
        }
    });

The jquery looks like correct, because the value of the file is sent correctly in the form var.
I send this data to my controller, but I'm not receiving the correct file. I'm receiving a temporal file, with this format:
...\...\AppData\Local\Temp\upload_c72334c_14b9858dd1d__8000_00000004.tmp

This is the code of the controller:
public Render upload(File file) throws IOException{

    String folderName = "C:\\Users\\Inma\\Documents\\MisDescargas";
    String token = UUID.randomUUID().toString();
    String fileName = folderName+ File.separator + token;

    FileInputStream inputStream = new FileInputStream(file);
    FileOutputStream outputStream = new FileOutputStream(fileName);

    IOUtils.copy(inputStream, outputStream);
    inputStream.close();
    outputStream.close();

    return renderJSON("token",token);

}

I use webmotion, a framework to develop web applications.
This is the mapping file:
[config]
   package.views=WEB-INF/views
   package.actions=com.vincle.actions

[actions]
   GET       /                      view:index.jsp
   POST         /upload                MainController.upload
   GET          /download              MainController.download

The networks screen shows this: http://postimg.org/image/lguc3q1ex/
When I try to create the FileInputStream to copy this file to my server, I get the exception FileNotFound exception, because this file doesn't exist.
What is the problem? Why don't I recieve the correct file?
Thanks in advance


text:
Q: Finding the Ratio of Segments of a Triangle In $\triangle ABC$, $AB$ = $5$, $BC = 7$, $AC = 9$, and $BD= 5$. Determine the ratio $AD:DC$ if I have to represent my answer as the ratio $k:w$ where $k$ and $w$ are relatively prime positive integers.
I know the answer I must come to is $19:8$.

A: Use Stewart's Theorem:
$$\frac{AB^2}{AD.AC}-\frac{BD^2}{AD.DC}+\frac{BC^2}{CD.AC}=1$$
$$\frac{5^2}{9AD}-\frac{5^2}{AD.DC}+\frac{7^2}{9CD}=1\quad (1)$$
Now call $$\frac{AD}{DC}=k→\frac{AD+DC}{DC}=k+1→\frac{9}{DC}=k+1→DC=\frac{9}{k+1}\quad (2)$$
And
$$AD= \frac{9k}{k+1}\quad (3)$$
Now replace $(2)$ and $(3)$ in $(1)$ and finish the calculations.

A: The ratios of the areas of the three triangles are equal to the ratios of the lengths of the bottom edges. If we work with a known area, we can find $AD$, and then $AD:DC=AD:(9-AD)$.
We can use Heron's formula to compute the areas. For the outer triangle, $S_1=(5+7+9)/2=\frac{21}2$ and $A_1=\sqrt{S_1(S_1-AB)(S_1-BC)(S_1-AC)}=\frac{21}4\sqrt{11}$. Setting $x$ to be the length $AD$, we have for the inner isosceles triangle $S_2=(x+5+5)/2$ and $A_2=\sqrt{S_2(S_2-x)(S_2-5)^2}$. Set $A_2/A_1=AD/AC=x/9$ and square both sides to eliminate the radical. This gives you a quartic equation for $x$, but an $x^2$ can be factored out leaving an easily-solved quadratic equation. Use the constraint that $0\lt x\lt9$ to eliminate the extraneous solution.

A: By the cosine law we have
$$\cos A =\frac{25+81-49}{2\cdot 5\cdot 9}$$
and this can help you find $AD,$ which I don't think should be $5\sqrt2.$


text:
Q: Icon for Mac OSX bundle I compile a Mac OSX bundle, called MyBundle.bundle, which is used as a plugin for another application. I want the bundle have a unique icon and so I set the Info.plist file to say:
<key>CFBundleIconFile</key>
<string>MyIcon.icns</string>

and place the file MyIcon.icns in the bundle's MyBundle.bundle/Contents/Resources folder.
This does not work, the finder show a generic icon for the bundle and ignores the specified MyIcon.icns file. If I change the bundle's extension from .bundle to .app the icon immediately shows - so I know the Info.plist is correct.
I found a work around that simulates a user doing copy and paste of an icon on the bundle:
I add the icon as a resource of type "icns" and id -16455 to the bundle's .rsrc file.
I than call
/Developer/Tools/SetFile -a BC MyBundle.bundle

This works, but is really lame. Starting in Mac OS 10.8 SetFile takes forever to execute.
My question: Is there away to force the Finder to show the bundle's icon without such hacks?
BTW: There is a question on same subject: Set icon of non app mac os x bundle; but the only answer there instructs on how to create an icon, and does not help with the problem.

A: You can use NSWorkspace
[[NSWorkspace sharedWorkspace] setIcon:(NSImage *)image forFile:(NSString *)fullPath options:(NSWorkspaceIconCreationOptions)options]
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSWorkspace_Class/Reference/Reference.html

A: This solution will associate the same icon for all your .bundle. I'm not sure this what you need (or if you need a specific/different icon for each of your .bundle).
If you can modify the app bundle: you can define a document type to associate with the app. To do so you have to edit app package:

*

*put the plugin icon in the app resources : TheOtherApp.app/Contents/Resources/MyIcon.icns

*edit the TheOtherApp.app/Contents/Info.plistand add something like this:
 <key>CFBundleDocumentTypes</key>
 <array>
  <dict>
    <key>CFBundleTypeName</key>
    <string>TheOtherApp Plugin</string>
    <key>CFBundleTypeRole</key>
    <string>None</string>
    <key>CFBundleTypeIconFile</key>
    <string>FlexoDocument.icns</string>
    <key>CFBundleTypeExtensions</key>
    <array>
      <string>bundle</string>
    </array>
    <key>LSTypeIsPackage</key>
    <string>true</string>
  </dict>
</array>

more Info about CFBundleDocumentTypes on developer.apple.com
You may need to relaunch the finder and/or the app to see the effect.

A: Try without the .icns part in your plist.info file:
<key>CFBundleIconFile</key>
<string>MyIcon.icns</string>

change it to:
<key>CFBundleIconFile</key>
<string>MyIcon</string>

I sucesfully create a bundle with a custom icon here with this technique: https://gist.github.com/Noitidart/6a2cbe0b4c74499765be

A: Easy Way: Open a picture file select all copy, click on the item, apple-i to get info, click on the icon in the popup window and apple-v.
Thats about as easy as it gets.


text:
Q: Класс "Ломаная на плоскости" Условие и постановка задачи: Ломаная на плоскости задаётся последовательностью пар координат, определяющих положение точек этой ломаной на координатной плоскости. Для двух ломаных определяется сумма — ломаная, состоящая последовательно из точек первой ломаной и, затем, второй ломаной. Геометрически это можно представить соединением отрезком последней точки первой ломаной и первой точки второй.Задание. Написать класс "ломаная на плоскости" и оператор "сумма ломаных";
В качестве кода я сделал следующее: ввожу 2 массива произвольной длины, ну а дальще перегрузкой оператора "+" объединяю их. НО, возникает ошибка "double free detected in tcache 2".
#include <iostream>
using namespace std;
int i=0;
class Array
{
private:
    int size;
   unsigned int* data;
public:
// конструктор
    Array(){}
    Array(int asize) {
        size=asize;
        data=(unsigned int*)new int[size];
        if(data) cout<<"Massiv inicializir\n";
        else cout<<"ne hvatka pamiati\n";
    }
~Array(){
    delete[] data;
    cout<<"Object uni4tojen\n";
}
        //Далее методы
Array(const Array &ob)   //Определение конструктора //копирования
{
 size=ob.size;
 data=(unsigned int*)new int [size];
 for(int i=0;i<ob.size;i++)
  data[i]=ob.data[i];
}
void print(){
    for(i=0;i<size;i++){
    cout<<*(data+i)<<" ";
}
cout<<endl;
}

void scan(){
cout<<"Vvedite massiv iz:"<<size<<"simvolov \n";
for(int i=0;i<size;i++){
cin>>*(data+i);
}
}
Array operator+(const Array& ob){
    this->size=size;
    Array tmp(size+ob.size);
    for(i=0;i<size;i++)
    {
        tmp.data[i]=*(data+i);//this->data[i]=data[i];
    }
    for(i=size;i<size+ob.size;i++) tmp.data[i]=ob.data[i-size];
 return tmp;
}
};
int main(){
    Array first(3);
    Array second(2);
    first.scan();
    second.scan();
    Array third(5);
    third=first+second;
    third.print();
 return 0;
}

Прошу объяснить Почему возникла эта ошибка(скорее всего всё из-за выделения доп.памяти) и способ ее исправления.  Спасибо.
Кстати, я задавал ранее вопрос про Ломаную,условие такое же, но код не подходящий, поэтому я решил задать отдельный вопрос про эту задачу,но уже с нужным мне кодом.

A: У вас нет оператора присваивания, а само присваивание есть:
third=first+second;

Соответственно, он генерируется компилятором, при этом выполняется простое почленное присваивание (т.е. просто присваивание указателей, а не копирование содержимого памяти), что в результате вызывает утечку памяти (память объекта third не удаляется) + приводит к освобождению одной и той же памяти дважды (временного объекта, создаваемого при суммировании, и объекта third).
Помните о правиле большой тройки :) — если уж работаете с памятью — деструктор, копирующий конструктор и оператор присваивания обязательны...
Рекомендую идиому присваивания через копирование: пишется функция swap для обмена членов двух объектов, потом создается временный объект, обмен с ним — и все готово. В вашем варианте примерно так:
void swap(Array& a) {
    std::swap(size,a.size);
    std::swap(data,a.data);
}

Array& operator=(const Array& a)
{
    if (this != &a) { // Необязательно!!
        Array tmp(a);
        swap(tmp);
    }
    return *this;
}


text:
Q: URL just removes parameters I've created an API for use on my website.
The API I made strips everything using mysql_real_escape_string then puts it into the database.
But the problem I'm having is the URL that my php scripts are using to access the API is cut short sometimes...
Which I have narrowed down to one of the parameters...
When its Ford Mondeo 22' the URL that is passed to simplexml_load_file is

http://mydomain.com/api/create.xml?api_number=brho15p6z1dhqwf5tsff&env=live&number=AJ20023232&title=Ford Mondeo 22'&image=http://mydomain.com/wp-content/uploads/2012/10/914955-150x150.jpg

but the API reports back the URL accessed as

http://mydomain.com/api/create.xml?api_number=brho15p6z1dhqwf5tsff&env=live&number=AJ20023232&title=Ford

If I remove the single quote then everything works fine, any idea how to correct this I suspect there's something I've overlooked when passing variables in the URL

A: It is the spaces in the "Ford Mondeo 22'" value that is causing the problem. You cannot have a spaces in the URL. You need to use escape characters. The encoded version of the parameter should be
Ford%20Mondeo%2022'
%20 is the escape character for space
I.e. the whole URL should read as follows:
http://mydomain.com/api/create.xml?api_number=brho15p6z1dhqwf5tsff&env=live&number=AJ20023232&title=Ford%20Mondeo%2022'&image=http://mydomain.com/wp-content/uploads/2012/10/914955-150x150.jpg

EDIT:
Your comment indicates that you use PHP. In PHP, you can use urlencode($foo) and urldecode($foo) to switch between the normal string and the encoding string.


text:
Q: How can I record an aws pinpoint event from angular 8 I'm trying to record an event, from angular to AWS, when the AuthComponent is loaded in the browser. It's printed to the console as undefined. And this console.log is the one in the (then) AnalyticsService file. The browser doesn't show an error and I can't see the log in AWS PP, am I missing any settings?
These would be my environment.ts and environment.test.ts
amplify: {
    ...
    Analytics: {
      disabled: false,
      autoSessionRecord: true,
      AWSPinpoint: {
        appId: 'lorem',
        region: 'ipsum',
        mandatorySignIn: false,
        autoSessionRecord: true,
        endpointId: null
      }
    }
  },

this is where I try to have the event recorded auth.component.ts
export class AuthComponent implements OnInit {

  constructor(private analyticsService: AnalyticsService) { }

  ngOnInit() {
    this.analyticsService.logevent('CUSTOMER_FIRST_EVENT', {});
  }

}

and analytics.service.ts
export class AnalyticsService {
  constructor() {}

  logevent(eventname: string, data: any) {
      let record = {
        name: eventname,
        attributes: data
      };
      console.log({logevent: record});
      Analytics.record(record)
        .then(e => {
          console.log(e);
        })
        .catch(err => {
          console.log(err);
        });
  }
}

A: In the roles associated with the cognito pool for anonymous and authenticated users, add to the policy, the "mobiletargeting: UpdateEndpoint" permission, also check that the environments, that you want to be record, have disabled:false and autoSessionRecord:true inside the Analytics object.


text:
Q: Sending an email through VB6 I am wondering if there is a way to send an email (SMTP) through VB6. I have an application that just needs to send a simple email when the user is done to let a group know that the application has processed. Is there a way to do that?

A: You should hopefully have the CDOSYS libraries installed on your machine:

CDO Messaging - MSDN
Creating and Sending a Message - MSDN
Sending email using CDOSYS ( THE REAL DEAL )
ASP Sending e-mail with CDOSYS

If you don't have that library (and aren't able to install it) then there's always CDONTS to fall back on but it is deprecated:

Using the CDONTS component to send email from ASP pages.

A: I found this here:
Dim UserName$, UserMail$, MailRecipiant$, MailBody$, SockData$

Private Sub Command1_Click()
UserName = "YourUserName_or_Addr"
UserMail = "Your Name <You@provider.com>"
MailRecipiant = UserMail
MailBody = "The message goes here"
Winsock1.LocalPort = 0
Winsock1.RemoteHost = "smtp-server"
Winsock1.RemotePort = 25
Winsock1.Connect
End Sub

Private Sub Winsock1_Connect()
Label1 = "Sending message..."
Winsock1.SendData "EHLO " & UserName & vbCrLf
If Not WaitFor("250") Then GoTo 100
Winsock1.SendData "MAIL FROM: " & UserMail & vbCrLf
If Not WaitFor("250") Then GoTo 100
Winsock1.SendData "RCPT TO: " & MailRecipiant & vbCrLf
If Not WaitFor("250") Then GoTo 100
Winsock1.SendData "DATA" & vbCrLf
If Not WaitFor("354") Then GoTo 100
Winsock1.SendData MailBody & vbCrLf & "." & vbCrLf
If Not WaitFor("250") Then GoTo 100
Winsock1.SendData "QUIT" & vbCrLf
If Not WaitFor("221") Then GoTo 100
Label1 = "Message sent"
GoTo 200
100
Label1 = SockData
200
Winsock1.Close
End Sub

Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
Winsock1.GetData SockData
End Sub

Private Sub Winsock1_Error(ByVal Number As Integer, Description As String, ByVal Scode As Long, ByVal Source As String, ByVal HelpFile As String, ByVal HelpContext As Long, CancelDisplay As Boolean)
Label1 = "Error: " & Description
SockData = "Error"
Winsock1.Close
End Sub

Private Function WaitFor(SockResponse As String) As Boolean
Do While Left(SockData, 3) <> SockResponse And Left(SockData, 3) <> "220" And Left(SockData, 3) <> "250"
  DoEvents
  If Left(SockData, 3) > "400" Then Exit Function
Loop
WaitFor = 1
SockData = ""
End Function

A: Yep - depends on which version of windows you're using. Assuming one of the later versions - CDO.Message works great.
Sub SendMessage(MailFrom,MailTo,Subject,Message)
    Dim ObjSendMail
    Set ObjSendMail = CreateObject("CDO.Message")

    'This section provides the configuration information for the remote SMTP server.

    With ObjSendMail.Configuration.Fields
    .Item ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 'Send the message using the network (SMTP over the network).
    .Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smpt server Address"
    .Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
    .Item ("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = False 'Use SSL for the connection (True or False)
    .Item ("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 60

    ' If your server requires outgoing authentication uncomment the lines below and use a valid email address and password.
'    .Item ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1 'basic (clear-text) authentication
'    .Item ("http://schemas.microsoft.com/cdo/configuration/sendusername") = MailFrom
'    .Item ("http://schemas.microsoft.com/cdo/configuration/sendpassword") = yourpassword

    .Update
    End With

    'End remote SMTP server configuration section==

    ObjSendMail.To = MailTo
    ObjSendMail.Subject = Subject
    ObjSendMail.From = MailFrom

    ' we are sending a html email.. simply switch the comments around to send a text email instead
    ObjSendMail.HTMLBody = Message
    'ObjSendMail.TextBody = Message

    ObjSendMail.Send

    Set ObjSendMail = Nothing
End Sub

A: Dave has a good solution if you really need to send email from the client's PC.  However, sometimes you get into trouble with firewalls and such.  In the case where you are connecting to a SQL Server, I have found it is simpler and easier to manage if you proxy your mail through SQL Server (either by queuing it into an outgoing mail table, or calling the xp_sendmail stored proc itself).
Here is a tutorial on how to get SQL Mail setup and working on the server, and at the end it shows how to use a stored procedure to send an email.
I found this solution to be advantageous because:

*

*Windows 7 computers were blocking all outbound SMTP

*Implementing all the retries and such to do outbound email "right" was quite complicated

*Using the queue method with SQL Server, but not actually setting up SQL Mail on my development or test databases, the emails stayed in the queue unless I was running against the production server


text: Q: Why am I not able to login to the admin After the login credentials are submitted, the login page is retained. There is no invalid username or password message. The URL changed from wp-admin to wp-login.php with the querystrings. The console on the browser inspector says The Cookie has been rejected because it is already expired.


text:
Q: how can i create mini photo while creating photo? i have a photo upload service on django.
when i add a photo I want it to add one more photo with 50% split.
If I put it in the pre_save on my photo save service, it can't find the photo (because it's not actually on the server) If I add it to the post_save, it goes into loop and adds unlimited
when I add a photo (postman or etc.) How can get to save a small photo at a time?.
here is my model
class UserPhoto(General, Status):
    user = models.ForeignKey(UserBase, on_delete=models.CASCADE, verbose_name="User Id", related_name='UserPhoto_user',
                             null=True, blank=True)
    link = models.ImageField(blank=True, null=True)
    order = models.IntegerField(null=True, blank=True)
    mini_link = models.ImageField(upload_to='mini_photos', blank=True, null=True)

    class Meta:
        db_table = 'user_photos'

my view
class UserPhoto(APIView):
    def get_object(self, pk):
        try:
            return Photo.objects.get(user__user__pk=pk)
        except Exception as e:
            return e

    def get(self, request):
        try:
            photo = self.get_object(request.user.pk)
            serializer = UserPhotoSerializer(photo)
            return Response(serializer.data)
        except Exception as e:
            print(e)

    def post(self, request):
        serializer = UserPhotoSerializer(data=request.data, context={'request': request})
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def put(self, request):
        photo = self.get_object(request.user.pk)
        serializer = UserPhotoSerializer(photo, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

my serializer
class UserPhotoSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserPhoto
        fields = '__all__'

    def create(self, validated_data):
        validated_data["user"] = self.context['request'].user.User_userbase
        return UserPhoto.objects.create(**validated_data)

my signal
@receiver(pre_save, sender=UserPhoto)
    def create_mini_photo(sender, instance=None, created=False, **kwargs):
    blob = BytesIO()
    path = instance.link.path
    image = Image.open(path)
    width, height = image.size
    resized_image = image.resize((int(width / 2), int(height / 2)))
    resized_image = resized_image.convert('RGB')
    resized_image.save(blob, 'JPEG')
    instance.mini_link.save(str(instance.link), File(blob), save=False)

A: as I understand there is status in the user photo model, when you add a new one, you will deactivate the old data and create a new record.
Therefore, you can first update the create method on the serializer as follows;
    def create(self, validated_data):
       validated_data["user"] = self.context['request'].user.User_userbase
       validated_data["status"] = "Active"
       photos = UserPhoto.objects.filter(user=self.context['request'].user.User_userbase, status="Active")
       if len(photos) > 0:
          for photo_obj in photos:
               photo_obj.status = "Passive"
               photo_obj.save()
       return UserPhoto.objects.create(**validated_data)

After making this update, you can make the codes work only on the new record by using the created parameter in the signal. Thus, after uploading the real photo, a new recording will be created and the inside of the signal will work, and when recording the 50% reduced photo, it will not work because there is no new recording. The important point here is that you use post_save because the photo must be saved. Example;
@receiver(post_save, sender=UserPhoto)
def create_mini_photo(sender, instance=None, created=False, **kwargs):
    if created:
       blob = BytesIO()
       path = instance.link.path
       image = Image.open(path)
       width, height = image.size
       resized_image = image.resize((int(width / 2), int(height / 2)))
       resized_image = resized_image.convert('RGB')
       resized_image.save(blob, 'JPEG')
       instance.mini_link.save(str(instance.link), File(blob), save=False)


text:
Q: Why my chrome crash when downloading ISO image file by using XMLHttpRequest As title, my target is to monitor download status(total file size&current load file size). So, I write a simple code to help. But there exist a strange situation that is my chrome crash when download ISO OS image file(not picture file!!!). Are there any wrong of my code? BTW, when I observe console log for total size file and current load size file. I can't realize where the loaded file exactly store location.(but it indeed progress...until load 1GB then crash!) Are there any one who knows that?
<body>

    function TriggerProgressEvent() {
        //var progressBar = document.getElementById('p');
        var xhr = new XMLHttpRequest();
        var x = document.createElement("PROGRESS");
        console.log('Entering TriggerProgressEvent');

        xhr.open('GET', 'http://127.0.0.1:8080/features/upload/en_windows_server_2012_r2_essentials_x64_dvd_2707177.iso',true);
        xhr.send();

        xhr.onprogress = function(event) {
            if(event.lengthComputable) {
                console.log(event.total);
                console.log(event.loaded);
                x.setAttribute("max", event.total);
                x.setAttribute("value", event.loaded);
                document.body.appendChild(x);
            }
        };
        xhr.onloadend = function(event) {
            //console.log(event.loaded);
            x.setAttribute("value", event.loaded);
            document.body.appendChild(x);
        };
    }
    </script>
</body>


text:
Q: Can't figure out overloaded constructor using list of lists I've been assigned to make a program that analyzes the performance of a hashtable by taking in an ifstream of an English dictionary, all of Shakespeare's works, and a data file for a topographical map. I was almost done, but I got stuck.
Below is my code. I'm having trouble with the overloaded constructor using the "first" and "last" iterators in the .h file. My guess about what it should look like is commented out, but out of everything we learned this chapter, I can't figure out what to do. My teacher didn't teach us this at all.
Here is my .h file:
#ifndef HASHTABLE_H_INCLUDED
#define HASHTABLE_H_INCLUDED

#include <iostream>
#include <list>
#include <fstream>
#include <chrono>
#include <vector>
#include <algorithm>
#include <iterator>
#include <cstdlib>

using namespace std;
using std::chrono::system_clock;

const size_t HASHTABLE_SIZE = 1048576;

template<typename T>
class HashTable
{
public:

    HashTable() :hashTable(new list<T>(HASHTABLE_SIZE)){}   ///allocates hashTable to 1048576
    ~HashTable() {delete[] hashTable;}
    template<typename InputIterator> HashTable(InputIterator first, InputIterator last);
    ///{
        ///first = hashTable?
        ///last = hashTable + HASHTABLE_SIZE?
    ///}
    using iterator = list<T>*;
    iterator begin()    ///points to beginning of array
    {
        iterator it;
        it = hashTable;
        return it;
    }
    iterator end()  ///points to one element past the last valid element
    {
        iterator it;
        it = hashTable + HASHTABLE_SIZE;
        return it;
    }
    void insert(const T& key); ///hash input key, use that to index into hash table, then push
                             ///back the element into the list at that index
    iterator find(const T& key)   ///hash input key, use that to index into has table, then
                                ///see if the key exists in the list at that index
    {
        size_t locate = hash_it(key);
        list<T>& lst = hashTable[locate];
        iterator it;
        it = std::find(begin(),end(),lst);
        if(it != hashTable + HASHTABLE_SIZE)
        {
            return it;
        }
        return end();
    }

private:

    list<T>* hashTable; ///This is a pointer to an allocated array of lists
    size_t hash_it(const string& key)
    {
        size_t hash = 0;
        for(size_t i = 0, n = key.size();i < n; i++)
            hash = (hash << 2) ^ key[i];
        return hash % HASHTABLE_SIZE;
    }
    size_t hash_it(const int& key) {return key * (key + 3) % HASHTABLE_SIZE;}
};

#endif // HASHTABLE_H_INCLUDED

And here's the main we're using:
#include "HashTable.h"

int main()
{
    istream_iterator<string> eos1;

    cout << "Loading the complete works of Shakespeare into a vector..." << endl;
    ifstream f("shakespeare.txt");
    if(!f)
        cout << "Failed loading shakespeare.txt" << endl;
    istream_iterator<string> iit(f);
    vector<string> vShake(iit, eos1);

    cout << "Loading English dictionary into hash table as C++ strings..." << endl;
    ifstream f2("words_alpha.txt");
    if(!f2)
        cout << "Failed loading words_alpha.txt" << endl;
    istream_iterator<string> iit2(f2);
    HashTable<string> ht1(iit2, eos1);
    //ht1.loadTable(f2);

    int foundCount = 0;
    auto t1 = system_clock::now();
    for(const string& str : vShake)
    {
        auto it = ht1.find(str);
        if(it != ht1.end())
            foundCount++;
    }
    auto t2 = system_clock::now();
    cout << foundCount << " out of " << vShake.size() << " total words matched.\n";
    cout << "Time to search HashTable: "
         << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()
         << "ms" << endl;

    cout << "Loading up a vector with 500000 randoms [0:30000]" << endl;
    vector<int> vElev;
    for(size_t i = 0; i < 500000; i++)
        vElev.push_back(rand() % 30001);

    cout << "Loading elevations file into hash table as ints..." << endl;
    ifstream f3("map-input-844-480.dat");
    if(!f3)
        cout << "Failed loading map-input-844-480.dat" << endl;
    istream_iterator<int> iit3(f3);
    istream_iterator<int> eos2;
    HashTable<int> ht2(iit3, eos2);
    //ht2.loadTable(f3);

    foundCount = 0;
    t1 = system_clock::now();
    for(const int& x : vElev)
    {
        auto it = ht2.find(x);
        if(it != ht2.end())
            foundCount++;
    }
    t2 = system_clock::now();
    cout << foundCount << " out of " << vElev.size() << " total elevations matched.\n";
    cout << "Time to search HashTable: "
         << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count()
         << "ms" << endl;

    return 0;
}

A: *

*You do not need the pointer list<T>* hashTable. Use list<T> hashTable and forget about destructor (by the way delete [] there is an error, it must be used after new Type[]), leave it default.

*List is not a proper container for hash table. It does not have access by index for constant time. std::vector<T> is appropriate.

*template<typename InputIterator> HashTable(InputIterator first, InputIterator last) -- it should insert elements from first till last into the hash table. Like this below:

HashTable(InputIterator first, InputIterator last)`
{
    for (; first != last; ++first)
        insert(*first);
}

Other problems: you declared hashTables as list of T, and then it used as vector of list of T.


text:
Q: How to get character like go down stairs in Google Sheets I want to get a character from string but the path is like going downstairs in Google Sheets

The string is like:
y    C    I    6    8    V    5
~5   Z    n    I    L    w    f
V    ~s   i    w    J    d    _
o    R    ~4   2    i    v    f
9    ^    j    ~h   r    u    #
Z    y    Q    7    ~1   u    a
T    t    z    u    _    ~!   Q
G    Y    n    r    *    t    ~^
J    A    l    v    F    j    d
a    2    l    -    y    O    B
h    B    w    %    n    a    4
M    t    _    P    D    W    a

And  expect the output is:
5    s    4    h    1    !    ^

I put ~ in front of the character that demo the path I want to get.
The logic is I will find the first column which cell is 5 and then get start from that cell.
Example sheet link
https://docs.google.com/spreadsheets/d/1UQEGEl_rqAMFePDAGoueTI47xF8T_DyrvJ3de5pkLRA/edit#gid=306981885
I tried auto-fill but it could only incrementally either row or column. And I hope to incremental both row and column.

A: ={INDIRECT("A"&MATCH(5, A1:A14, 0)),
  INDIRECT("B"&MATCH(5, A1:A14, 0)+1),
  INDIRECT("C"&MATCH(5, A1:A14, 0)+2),
  INDIRECT("D"&MATCH(5, A1:A14, 0)+3),
  INDIRECT("E"&MATCH(5, A1:A14, 0)+4),
  INDIRECT("F"&MATCH(5, A1:A14, 0)+5),
  INDIRECT("G"&MATCH(5, A1:A14, 0)+6)}

for a large scale scenario you can use this one and drag it to the right:
=INDIRECT(ADDRESS(MATCH(5, $A1:$A14, 0)+COLUMN()-1, COLUMN(), 4))

A: You can also do it with an array formula if you want to:
=ArrayFormula(hlookup(column(A2:G13),{column(A2:G13);A2:G13},match(5,A2:A13,0)+column(A2:G13)))


text:
Q: Does VS code have variable explorer object like we have it in spyder? I will post the picture of what exactly I am asking variable explorer in spyder

So do we have this feature in VS code?
I tried a lot to find it on google but was unhappy to not find it.

A: spyder is probably running a REPL (Jupyter is doing that also). From that python process they show the local and global variables, just like a debugger would do on a breakpoint.
If you use Python Interactive you have similar functionality with the Variables Explorer and Data Viewer or use Jupyter notebooks

A: *

*Open your .py script in vscode

*Right click anywhere on the script > Run current File in interactive Window

*In the toolbar of the interactive window click on the variable icon

*You can  now consult the values of variables created by your script

A: You can now find all variables in a Jupyter Notebook in VS Code in the Output panel under Jupyter: Variables


text:
Q: Occasionally, Action leaves the conversation and a google search for the user query is returned instead We have an action where the user can say the name of a company, and the action will return a number of scores for said company. During testing, we have found that the action leaves the conversation and a google search for the queried company is returned instead.
This happens intermittently. More often than not, the action will return the score. Has anyone ever come across this behaviour before?
Behaviour observed on an Android phone and a Google Nest Hub.

A: This is an example of No-Match yielding, where the Assistant will answer a question that a user asked which your conversation is unable to match. This may because you're using a fallback intent to capture this query, which implicitly signals that your action cannot handle this prompt.
To get around it, you should move to a pattern where you have an intent that captures free-form text and ensure that intent gets matched.


text:
Q: Is there a Linux equivalent of "Robocopy /CREATE"? I'm looking for a Linux equivalent of the command Robocopy /CREATE, which recreates a complete empty file tree with all the attributes of folders and files in the source, except the files' contents. Rsync, which is said to be the equivalent of Robocopy for general file synchronization purposes, doesn't seem to have a similar option.
I'm recovering data from a 4TB hard disk drive, with the main partition formatted in Ext4, so far I could clone 47% with HDDSuperClone until it started to suffer serious issues, but the partition is still not accessible on the recovery drive, while recovery softwares like R-Studio and DMDE can't reconstruct the original metadata structure, and the drive's current degraded condition may not allow to recover significantly more useful data.
So, since the original drive can still be mounted on Lubuntu (albeit with difficulty), if I have to resort to "raw file carving", i.e. scan the recovered data with tools that detect file signatures and extract all detected files in bulk (I'm using mainly R-Studio and Photorec for that purpose), I'd like to at least provide the drive's owner with a way of sorting such a mess more conveniently than doing it from scratch with no reference.
Obviously, in such a context, the command I'm looking for should proceed quickly and only analyze a few key filesystem structures, not involve a thorough scan of the partition which would only wear out that drive further.

A: There is --attributes-only option for cp. It's not required by POSIX, so not every implementation of cp will understand it; still cp from GNU coreutils in your Lubuntu does support it.

--attributes-only
  don't copy the file data, just the attributes

It creates files of size 0. To copy a directory tree you need -R, so
cp -R --attributes-only /path/to/mountpoint/ /where/to/copy/to


text:
Q: Make div child occupy 100% of div parent even when hiding their sidebar how is it possible to define a child div occupy 100 % of the parent div?
I want to do a layout with a sidebar and I want to set my main to occupy 100% of what is left over by taking width from the sidebar

.bodySection {
  height: 100%;
  width: 100%;
  overflow: auto;
}

.sidenav {
  top: 0;
  bottom: 0;
  left: 0;

  position: absolute;
  overflow: hidden;
  z-index: 5;
  background: rgb(250, 250, 250);
  width: 230px;
  padding-top: 55px;
  box-shadow: 1px 1px 1px 1px rgba(0.2, 0.2, 0.2, 0.2);
}

.sidenav a {
  padding: 6px 8px 6px 16px;
  text-decoration: none;
  font-size: 15px;
  color: #636363;
  display: block;
  background: rgb(247, 247, 247);

}

.sidenav a:hover {
    background: rgb(241, 241, 241);
}

.main {
  margin-left: 230px;
  background: rgb(187, 187, 187);
  /* Same as the width of the sidenav */
  padding: 0px;

    About
    Services
    Clients
    Contact

    Hello

The idea is that the div with Hello occupies 100% of the screen, and even though I use a function in js to hide the sidebar it continues with 100%
also it is necessary to leave the height 100%

A: The css calc function works great for this purpose. Add this
.main{
width: calc(100% - 230px);
}


text:
Q: No such module Swift package manager for 'purchases' module I've quite literally tried everything and read every article/done hours of research. I cannot build my Xcode Project due to the fact it cannot find the module 'purchases' from: RevenueCat/purchases.
Everything was working well before I upgrade my Mac to the latest Ventura beta with the newest version of Xcode, where the issue started happening, I downgraded both my OS and Xcode thinking this issue would subside, but it hasn't.
I've tried resetting the package cache, deleting derived data, gone through each SO post and tried their answers, still nothing.
Yes the module and it's packages/frameworks are apart of my target

A: I had the issue this morning, and most of the issue was that I tried to upgrade from 3.x.x to 4.x.x at once, and swift compiler wanted to kill itself.
If you still use import Purchases ; then it's still 3.x.x and I solved it using:
products: [
  ...
  .library(name: "Premium", targets: ["Premium"]),
  ...
],
dependencies: [
  ...
  .package(url: "https://github.com/RevenueCat/purchases-ios.git", from: "3.0.0"),
  ...
],
targets: [
  ...
  .target(name: "Premium", dependencies: [
    .product(name: "Purchases", package: "purchases-ios"),
  ]),
  ...
]

Upgrading to 4.x.x wasn't that hard once I got 3.x.x compiling again.
This is what my Package.swift file looks like now:
products: [
  ...
  .library(name: "Premium", targets: ["Premium"]),
  ...
],
dependencies: [
  ...
  .package(url: "https://github.com/RevenueCat/purchases-ios.git", from: "4.0.0"),
  ...
],
targets: [
  ...
  .target(name: "Premium", dependencies: [
    .product(name: "RevenueCat", package: "purchases-ios"),
  ]),
  ...
]

And now, I need to use import RevenueCat as explained in the migration guide


text:
Q: Server 2000 DC down after crash and restore Problem: Server 2000 DC hard drive failed. Purchased new drive, installed server 2000 and restored everything from a backup. Everything is back up, however none of the client machines can connect to the server and view "my documents". Initially we had 3 DC, however we are down to 1 because of hardware failures so this one server is carrying all the FSMO roles.
Some of the errors:
dcgetdcname call failed
can't open the group policy (Failed to find a domain controller. There may be a policy that prevents you from selecting another domain controller.)
sometimes the active directory won't open
A Time Server could not be located.
The server holding the PDC role is down.
NIC won't save static IP settings (although the machine IP stays the same)
Any help would be greatly appreciate.

A: When a DC goes down, just restoring a system backup is not sufficient; you must perform an Active Directory Restore, and in your case, an authoritative restore since it is the only DC left.
Look here for details: http://support.microsoft.com/kb/241594


text:
Q: YAML Parsing Issue in Rails I have an issue on Elastic Beanstalk deployment which is:
YAML syntax error occurred while parsing /var/app/ondeck/config/database.yml. Please note that YAML must be consistently indented using spaces. Tabs are not allowed. Error: (<unknown>): found character that cannot start any token while scanning for the next token at line 2 column 1 /var/app/ondeck/config/environment.rb:5:in `<top (required)>' /opt/rubies/ruby-2.4.2/bin/bundle:23:in `load' /opt/rubies/ruby-2.4.2/bin/bundle:23:in `<main>'

Caused by: Psych::SyntaxError: (<unknown>): found character that cannot start any token while scanning for the next token at line 2 column 1 /var/app/ondeck/config/environment.rb:5:in `<top (required)>' /opt/rubies/ruby-2.4.2/bin/bundle:23:in `load' /opt/rubies/ruby-2.4.2/bin/bundle:23:in `<main>' Tasks: TOP => environment (See full trace by running task with --trace).

As what I have read, this is because YAML forbids using tabs, instead it uses spaces.
The problem is that I manually checked every YAML file for tabs, and never found one. I think I missed something so my question is: is there any script that can go through my entire source code replacing tabs with 2 spaces in every YAML file?

A: It's ruby after all: it's easier and faster to write the script rather than ask questions on SO and google for it.
Dir['*/**/*.yml'].each do |f|
  File.write(f, File.read(f).gsub(/\t/, '  '))
end


text:
Q: jQuery:Ajax Don't work loaded scripts I have this code :
//--Async load page

$("body").on("click", "a:not([data-noajax])", function(){
    href = $(this).attr("href");

    pageLoad(href + " .page-wrapper", ".page-wrapper", href);
    //$('#header').load(href+' #header');
    //$('#footer').load(href+' #footer');
    return false;
});

function pageLoad(from, where, href)
{

    href = typeof href === 'undefined' ? "" : href;
    loading();
    //$(where).empty();
    $(where).load(from, function(data){
        loading(false);
        $("html, body").animate({ scrollTop: $(".page-header h1").offset().top }, "slow");

        title = $(".page-header h1").text();
        parent.location.hash = href;
        window.history.pushState($(document).html(), title, href);
        document.title = title;
        $(document).ready(function() {
            $('.page-header h1').text(title);
        })
    });

}

//--

working, but....scripts which will load another page don't work ((
example : go on the http://amour05.ru , click on some post title, and after try reload page;
first we don't see comments widget, and after reload we see it.
p.s. sorry for my english ((
RIGHT SOURCE CODE :
<!DOCTYPE HTML>

<meta charset="utf-8" />
<meta name="MobileOptimized" content="320"/>
<meta name="HandheldFriendly" content="true"/>
<meta name="viewport" content="width=device_width, initial_scale=1.0" />
    <title>кто знает расписание пересдач ...</title>

    <link rel="stylesheet" type="text/css" href="/theme/bootstrap/css/bootstrap.min.css" />
    <link rel="stylesheet" type="text/css" href="/theme/bootstrap/css/bootstrap-theme.min.css" />
    <link rel="stylesheet" type="text/css" href="/theme/style/style.css" />

    <link rel="stylesheet" type="text/css"  href="/theme/style/jquery/jquery-ui.css" />

                <form id="search" action="/search.php" class="navbar-search pull-right" method="POST">
                    <input type="search" name="search_text" value="" class="search-query" placeholder="Поиск">
                </form>
                amour05.ru

Меню

Главная

Добавить признание

Поиск по сайту

Написать админу

кто знает расписание пересдач ...

Анонимно

            кто знает расписание пересдач 3-его курса ЮФ пожалуйста скиньте.спасибо огромное))

Статистика

31.01.2014 18:58

комментариев : 0

просмотров : 34

уникальных : 10

Главная

О проекте

GENERATED SOURCE :

<meta charset="utf-8">
<meta name="MobileOptimized" content="320">
<meta name="HandheldFriendly" content="true">
<meta name="viewport" content="width=device_width, initial_scale=1.0">
    <title>кто знает расписание пересдач ...</title>

    <link rel="stylesheet" type="text/css" href="/theme/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="/theme/bootstrap/css/bootstrap-theme.min.css">
    <link rel="stylesheet" type="text/css" href="/theme/style/style.css">

    <link rel="stylesheet" type="text/css" href="/theme/style/jquery/jquery-ui.css">

 идет загрузка

                <form id="search" action="/search.php" class="navbar-search pull-right" method="POST">
                    <input name="search_text" value="" class="search-query" placeholder="Поиск" type="search">
                </form>
                amour05.ru

Меню

Главная

Добавить признание

Поиск по сайту

Написать админу

кто знает расписание пересдач ...

Анонимно

            кто знает расписание пересдач 3-его курса ЮФ пожалуйста скиньте.спасибо огромное))

Статистика

31.01.2014 18:58

комментариев : 0

просмотров : 26

уникальных : 8

Главная

О проекте


text:
Q: Change in Bitnami Wordpress AWS Public IP Public IP of my wordpress website hosted on AWS got changed.
After getting the new Public IP i update the wp_options table for site_url and also wp_configs.php
But the url of my static content is like:
http://52.36.13.144/52.36.13.144/wp-content/uploads/2016/08/deepika.jpg

The host ip is getting appended twice. I am not able to figure out why?

A: Bitnami stacks automatically update the configuration during boot up when there has been a change of IP address.
The issue you describe can happen if the value of WP_SITEURL or WP_HOME in the wp_configs.php file doesn't include the http:// prefix. Instead of setting the IP address manually, you may define them as follows:
define('WP_SITEURL', 'http://' . $_SERVER['HTTP_HOST'] . '/');
define('WP_HOME', 'http://' . $_SERVER['HTTP_HOST'] . '/');

With those setting in place, you may set the value of the options siteurl and home in the wp_options table of the site database to http://127.0.0.1/wordpress/.


text:
Q: Definition of very ample divisor Sorry for my bad English.
Let $X$ be scheme over $Y$, and $\mathscr{L}$ be invertible sheaf on $X$.
By definition of Hartshorne's algebraic geometry (p120),

$\mathscr{L}$ is very ample relative to $Y$, if there is an immersion $i:X\to \mathbb{P}^r_Y$ for some $r$, such that $i^{*}(\mathscr{O}(1))\cong \mathscr{L}$.

On the other hand, Hartshorne's  proof of Iv.Prop.3.1(b) (p307) ,
let $D$ be divisor on curve $X$, $D$ is very ample iff correspond morphism $X\to  \mathbb{P}^r_k $ is closed immersion.
Why is tihs? Thanks.


text:
Q: VerifyError when using ActionBarDrawerToggle with AppCompat and ActionBarActivity on Gingerbread My app is dependent on the Android Support Library V7 AppCompat (support repository version 2) for the Action Bar. That library project in Eclipse includes the Android Support Library V4 (version 18) as a dependency in its libs/ directory. My app's project folder does not contain the support libraries in libs/, presumably relying on AppCompat to export that. For the most part, my navigation drawer code resembles the standard example.
Everything works fine on Android 4+, but on Android 2 devices (both the Gingerbread emulator and a DROID 2), I get a VerifyError when the activity starts:
08-18 23:50:06.538: E/AndroidRuntime(6232): java.lang.VerifyError: com.myapp.activities.MainActivity$2
08-18 23:50:06.538: E/AndroidRuntime(6232):     at com.myapp.activities.MainActivity.onCreate(MainActivity.java:76)
08-18 23:50:06.538: E/AndroidRuntime(6232):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
...

It turns out the crash is occurring when I'm calling the constructor for ActionBarDrawerToggle.
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;

public class MainActivity extends ActionBarActivity {
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle drawerToggle;

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

    drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
    drawerView = (ListView)findViewById(R.id.left_drawer);
    drawerView.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView parent, View view, int position, long id) {
            selectItem(position);
        }
    });
    drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close) {
        public void onDrawerClosed(View view) {
            invalidateOptionsMenu();
        }

        public void onDrawerOpened(View drawerView) {
            invalidateOptionsMenu();
        }
    };
    drawerLayout.setDrawerListener(drawerToggle);
    ...
}

Note that the prior call to cast a DrawerLayout does not cause a VerifyError.
ADT 22, target API 17, min API 7. Not using Proguard, my project.properties is simply:
target=android-17
android.library.reference.1=../libraries/appcompat

I do have Android Private Libraries marked as an exported entry on my build path (in both the project and AppCompat library project), which seems to rule out one of the most common causes of VerifyError with the support library.

A: The issue was using invalidateOptionsMenu() instead of supportInvalidateOptionsMenu().


text:
Q: vuejs v-cloak placement while assets download Currently I'm making vuejs SPA, and the build size is pretty big, so I want to place some loading indicator instead of blank page while vue is downloading its assets.
I've found out that in this case, the solution is v-cloak, but what I dont understand is, in every example the v-cloak is putted inside index.html, whereas in my project src there are no index.html, there is only main.js and vue.app.
there are index.html, but is located inside public folder(which i think its a build file?).
nevertheless, I've tried to put v-cloak directive inside Vue.app, and its still showing blank page while vue downloading its assets. please point me in the right direction.
thanks for all the help.
here's my App.vue:
<template>

      Loading...

      <router-view />

</template>

and when I put some loading indicator in public/index.html, it work, but how do I remove it after vue finished loading?
heres my public/index.html
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <title><%= webpackConfig.name %></title>

      We're sorry but <%= webpackConfig.name %> doesn't work properly without JavaScript enabled. Please enable it to continue.

    Loading

A: v-cloak is supposed to be used on the application's mounting point (the el  specified in new Vue()), not within a component. Vue does not process v-cloak anywhere else but the mounting point, so it has no effect in App.vue.
To use v-cloak:

*

*In public/index.html, add the v-cloak attribute to div#app, and a

*Adjacent to div#app, add a loading icon, and style it so that it's hidden when the v-cloak attribute is removed (i.e., :not([v-cloak])):

demo


text:
Q: MS Visual Web Developer 2010 Express won't save state MY VWD 2010 Express has stopped saving state and every time I re-open a project all files are closed.  It worked properly for months, whenever I would open a project all the files that were open when I closed it would re-open.  I tried deleting my .suo file but made no difference.

A: In the Windows menu select "Reset Window Layout"


text:
Q: Putty can only connect if sudo is used I have a remote machine running Ubuntu 20.04 and I am remoting into it from windows using Remote Desktop Connection. I have installed XRDP and followed this [guide][1] to create the files 45-allow-colord.pkla  46-allow-update-repo.pkla. I no longer have to enter my password 10+ times when I make a new remote connection.
I am trying to use Putty to make a serial connection to my device. If I run Putty and attempt to make a connection I am told that the serial port cannot be opened.
If I run sudo putty I get the error
No protocol specified
Unable to init server: Could not connect: Connection refused

(putty:2739): Gtk-WARNING **: 09:53:15.031: cannot open display: :10.0

I then run xhost +si:localuser:root followed by sudo putty and everything works as expected.
I am wondering can I run xhost +si:localuser:root at login, or is there a way to remove all restrictions from my XRDP session, to have the session act as if I was logged onto the Ubuntu machine itself?
[1]: https://c-nergy.be/blog/?p=14058


text:
Q: Get difference between Window ShowDialog cancel and close In our app we use WPF and Caliburn Micro. We use a custom WindowManager:
public class OurWindowManager : Caliburn.Micro.WindowManager
{
    protected override Window EnsureWindow(object model, object view, bool isDialog)
    {
        var window = base.EnsureWindow(model, view, isDialog);
        if (isDialog) window.ResizeMode = ResizeMode.NoResize;
        window.Icon = new BitmapImage(new Uri("pack://application:,,,/NWB.ico"));

        // TODO: Change to dynamic minWidth/minHeight based on window
        window.MinWidth = 600;

        new WindowSettingsBehavior().Attach(window);

        return window;
    }
}

In our code we mostly use this WindowManager like so:
public void SomeMethod()
{
    var result = _windowManager.ShowDialog(new ConfirmDialogViewModel("some title",
        "some text"));
    if(result == true){ // if OK is pressed
        // do something on OK
    }
    // do nothing
}

In one of my recent methods I want to do the following (in semi pseudo-code):
public void SomeOtherMethod()
{
    _windowManager.ShowDialog(new ConfirmDialogViewModel("some title", "some text"));
    //if window is closed without pressing any of the buttons
        return; // do nothing

    //if OK is pressed {
        // do something on OK
    }
    // if Cancel is pressed: do something else
}

Unfortunately, ShowDialog also returns false if the Window is closed (even though the ShowDialog returns a Nullable bool (bool?)).
So, what I did so far is just completely remove the Close Button by making a new Window-Behavior, and I've added it to the OurWindowManager class inside the if(isDialog):
if (isDialog)
{
    window.ResizeMode = ResizeMode.NoResize;
    new WindowHideBarBehavior().Attach(window);
}

This works, and I now got a Window with just a title, and without a Close (X) button. Unfortunately, the window can still be closed with Alt+F4 and such. I thought about catching Alt+F4 and cancel the closing, but since Alt+F4 is standard Window behavior, I don't think users will appreciate it a lot and I find it a bit unintuitive for the users to disable it..
So, my question: How can I accomplish the pseudo-code in SomeOtherMethod mentioned above. Is there a way to get the difference between closing a Dialog or canceling a Dialog. (NOTE: As mentioned above, keep in mind we use Caliburn.Micro.WindowManager, not the default C# WPF one. Don't know if there are a lot of differences, but I guess there are at least some.)

EDIT:
I also know I can catch the closing event and cancel the closing:
window.Closing -= DisableDialogClosing;
if (isDialog)
{
    window.ResizeMode = ResizeMode.NoResize;
    new WindowHideBarBehavior().Attach(window);
    window.Closing += DisableDialogClosing;
}

...

private static void DisableDialogClosing(object sender, CancelEventArgs e)
{
    e.Cancel = true;
}

But then it also cancels the closing when I want it to close (for example when the Cancel/OK button is pressed). Maybe I can add some kind of Property-flag to this overridden Closing-EventHandler, but perhaps you guys/girls have other suggestions to accomplish the same results.

A: You can fulfil your requirements if you just implement your own dialog Window by extending the Window class. From inside your custom Window, you can handle the Closed event and set the Window.DialogResult property to null in that case. For the normal Ok and Cancel states, you can simply attach Click handlers to those Buttons and set the Window.DialogResult property to true and false accordingly.
private void CustomDialogWindow_Close(object sender, RoutedEventArgs e)
{
    DialogResult = null;
}

private void OkButton_Click(object sender, RoutedEventArgs e)
{
    DialogResult = true;
}

private void CancelButton_Click(object sender, RoutedEventArgs e)
{
    DialogResult = false;
}

You could then check for the Window closed state like this:
if (CustomDialogWindow.DialogResult == null) DoSomethingUponDialogWindowClose();

You can find further helpful information in the following pages on MSDN:

Dialog Boxes Overview
Window.DialogResult Property

A: After @Sinatr's suggestion I've added a ClosedBy property to my ConfirmDialogViewModel:
(before):
public sealed class ConfirmDialogViewModel : Screen
{
    public ConfirmDialogViewModel(string title, string message)
    {
        DisplayName = title;
        Message = message;
    }

    public string Message { get; set; }

    public void Ok()
    {
        TryClose(true);
    }

    public void Cancel()
    {
        TryClose(false);
    }
}

(after):
public sealed class ConfirmDialogViewModel : Screen
{
    public ClosedBy CloseReason { get; private set; }

    public ConfirmDialogViewModel(string title, string message)
    {
        DisplayName = title;
        Message = message;
        CloseReason = ClosedBy.Other;
    }

    public string Message { get; set; }

    public void Ok()
    {
        CloseReason = ClosedBy.Ok;
        TryClose(true);
    }

    public void Cancel()
    {
        CloseReason = ClosedBy.Cancel;
        TryClose(false);
    }
}

public enum ClosedBy
{
    Other,
    Ok,
    Cancel
}

And I now use it like so:
public void SomeOtherMethod()
{
    var confirmDialog = new ConfirmDialogViewModel("some title", "some text");
    var result = _windowManager.ShowDialog(confirmDialog);
    if(result == null || confirmDialog.CloseReason == ClosedBy.Other) return;

    if(result == true && confirmDialog.CloseReason == ClosedBy.Ok){
        // Do something on OK
    }
    // Do something on cancel
}

I still kept the behavior to remove the close button, and also added window.ShowInTaskbar = false; to the OurWindowManager inside the if(isDialog).