text:
Q: Two's Complement in Python Is there a built in function in python which will convert a binary string, for example '111111111111', to the two's complement integer -1?

A: This will give you the two's complement efficiently using bitwise logic:
def twos_complement(value, bitWidth):
    if value >= 2**bitWidth:
        # This catches when someone tries to give a value that is out of range
        raise ValueError("Value: {} out of range of {}-bit value.".format(value, bitWidth))
    return value - int((value << 1) & 2**bitWidth)

How it works:
First, we make sure that the user has passed us a value that is within the range of the supplied bit range (e.g. someone gives us 0xFFFF and specifies 8 bits) Another solution to that problem would be to bitwise AND (&) the value with (2**bitWidth)-1
To get the result, the value is shifted by 1 bit to the left. This moves the MSB of the value (the sign bit) into position to be anded with 2**bitWidth. When the sign bit is '0' the subtrahend becomes 0 and the result is value - 0. When the sign bit is '1' the subtrahend becomes 2**bitWidth and the result is value - 2**bitWidth
Example 1: If the parameters are value=0xFF (255d, b11111111) and bitWidth=8

*

*0xFF - int((0xFF << 1) & 2**8)

*0xFF - int((0x1FE) & 0x100)

*0xFF - int(0x100)

*255  - 256

*-1

Example 2: If the parameters are value=0x1F (31d, b11111) and bitWidth=6

*

*0x1F - int((0x1F << 1) & 2**6)

*0x1F - int((0x3E) & 0x40)

*0x1F - int(0x00)

*31   - 0

*31

Example 3: value = 0x80, bitWidth = 7
ValueError: Value: 128 out of range of 7-bit value.
Example 4: value = 0x80, bitWitdh = 8

*

*0x80 - int((0x80 << 1) & 2**8)

*0x80 - int((0x100) & 0x100)

*0x80 - int(0x100)

*128  - 256

*-128

Now, using what others have already posted, pass your bitstring into int(bitstring, 2) and pass to the twos_complement method's value parameter.

A: A couple of implementations (just an illustration, not intended for use):
def to_int(bin):
    x = int(bin, 2)
    if bin[0] == '1': # "sign bit", big-endian
       x -= 2**len(bin)
    return x

def to_int(bin): # from definition
    n = 0
    for i, b in enumerate(reversed(bin)):
        if b == '1':
           if i != (len(bin)-1):
              n += 2**i
           else: # MSB
              n -= 2**i
    return n

A: in case someone needs the inverse direction too:
def num_to_bin(num, wordsize):
    if num < 0:
        num = 2**wordsize+num
    base = bin(num)[2:]
    padding_size = wordsize - len(base)
    return '0' * padding_size + base

for i in range(7, -9, -1):
    print num_to_bin(i, 4)

should output this:
0111
0110
0101
0100
0011
0010
0001
0000
1111
1110
1101
1100
1011
1010
1001
1000

A: No, there is no builtin function that converts two's complement binary strings into decimals.
A simple user defined function that does this:
def two2dec(s):
  if s[0] == '1':
    return -1 * (int(''.join('1' if x == '0' else '0' for x in s), 2) + 1)
  else:
    return int(s, 2)

Note that this function doesn't take the bit width as parameter, instead positive input values have to be specified with one or more leading zero bits.
Examples:
In [2]: two2dec('1111')
Out[2]: -1

In [3]: two2dec('111111111111')
Out[3]: -1

In [4]: two2dec('0101')
Out[4]: 5

In [5]: two2dec('10000000')
Out[5]: -128

In [6]: two2dec('11111110')
Out[6]: -2

In [7]: two2dec('01111111')
Out[7]: 127

A: You can use the bit_length() function to convert numbers to their two's complement:
def twos_complement(j):
   return j-(1<<(j.bit_length()))

In [1]: twos_complement(0b111111111111)
Out[1]: -1

A: Since Python 3.2, there are built-in functions for byte manipulation: https://docs.python.org/3/library/stdtypes.html#int.to_bytes.
By combining to_bytes and from_bytes, you get
def twos(val_str, bytes):
    import sys
    val = int(val_str, 2)
    b = val.to_bytes(bytes, byteorder=sys.byteorder, signed=False)
    return int.from_bytes(b, byteorder=sys.byteorder, signed=True)

Check:
twos('11111111', 1)  # gives -1
twos('01111111', 1)  # gives 127

For older versions of Python, travc's answer is good but it does not work for negative values if one would like to work with integers instead of strings. A twos' complement function for which f(f(val)) == val is true for each val is:
def twos_complement(val, nbits):
    """Compute the 2's complement of int value val"""
    if val < 0:
        val = (1 << nbits) + val
    else:
        if (val & (1 << (nbits - 1))) != 0:
            # If sign bit is set.
            # compute negative value.
            val = val - (1 << nbits)
    return val

A: It's not built in, but if you want unusual length numbers then you could use the bitstring module.
>>> from bitstring import Bits
>>> a = Bits(bin='111111111111')
>>> a.int
-1

The same object can equivalently be created in several ways, including
>>> b = Bits(int=-1, length=12)

It just behaves like a string of bits of arbitrary length, and uses properties to get different interpretations:
>>> print a.int, a.uint, a.bin, a.hex, a.oct
-1 4095 111111111111 fff 7777

A: you could convert the integer to bytes and then use struct.unpack to convert:
from struct import unpack

x = unpack("b", 0b11111111.to_bytes(length=1, byteorder="little"))
print(x)  # (-1,)

A: >>> bits_in_word=12
>>> int('111111111111',2)-(1<<bits_in_word)
-1

This works because:

The two's complement of a binary
  number is defined as the value
  obtained by subtracting the number
  from a large power of two
  (specifically, from 2^N for an N-bit
  two's complement). The two's
  complement of the number then behaves
  like the negative of the original
  number in most arithmetic, and it can
  coexist with positive numbers in a
  natural way.

A: Two's complement subtracts off (1<<bits) if the highest bit is 1.  Taking 8 bits for example, this gives a range of 127 to -128.
A function for two's complement of an int...
def twos_comp(val, bits):
    """compute the 2's complement of int value val"""
    if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255
        val = val - (1 << bits)        # compute negative value
    return val                         # return positive value as is

Going from a binary string is particularly easy...
binary_string = '1111' # or whatever... no '0b' prefix
out = twos_comp(int(binary_string,2), len(binary_string))

A bit more useful to me is going from hex values (32 bits in this example)...
hex_string = '0xFFFFFFFF' # or whatever... '0x' prefix doesn't matter
out = twos_comp(int(hex_string,16), 32)

A: Since erikb85 brought up performance, here's travc's answer against Scott Griffiths':
In [534]: a = [0b111111111111, 0b100000000000, 0b1, 0] * 1000
In [535]: %timeit [twos_comp(x, 12) for x in a]
100 loops, best of 3: 8.8 ms per loop
In [536]: %timeit [bitstring.Bits(uint=x, length=12).int for x in a]
10 loops, best of 3: 55.9 ms per loop

So, bitstring is, as found in the other question, almost an order of magnitude slower than int. But on the other hand, it's hard to beat the simplicity—I'm converting a uint to a bit-string then to an int; you'd have to work hard not to understand this, or to find anywhere to introduce a bug. And as Scott Griffiths' answer implies, there's a lot more flexibility to the class which might be useful to the same app. But on the third hand, travc's answer makes it clear what's actually happening—even a novice should be able to understand what conversion from an unsigned int to a 2s complement signed int means just from reading 2 lines of code.
Anyway, unlike the other question, which was about directly manipulating bits, this one is all about doing arithmetic on fixed-length ints, just oddly-sized ones. So I'm guessing if you need performance, it's probably because you have a whole bunch of these things, so you probably want it to be vectorized. Adapting travc's answer to numpy:
def twos_comp_np(vals, bits):
    """compute the 2's compliment of array of int values vals"""
    vals[vals & (1<<(bits-1)) != 0] -= (1<<bits)
    return vals

Now:
In [543]: a = np.array(a)
In [544]: %timeit twos_comp_np(a.copy(), 12)
10000 loops, best of 3: 63.5 µs per loop

You could probably beat that with custom C code, but you probably don't have to.

A: Unfortunately there is no built-in function to cast an unsigned integer to a two's complement signed value, but we can define a function to do so using bitwise operations:
def s12(value):
    return -(value & 0b100000000000) | (value & 0b011111111111)

The first bitwise-and operation is used to sign-extend negative numbers (most significant bit is set), while the second is used to grab the remaining 11 bits. This works since integers in Python are treated as arbitrary precision two's complement values.
You can then combine this with the int function to convert a string of binary digits into the unsigned integer form, then interpret it as a 12-bit signed value.
>>> s12(int('111111111111', 2))
-1
>>> s12(int('011111111111', 2))
2047
>>> s12(int('100000000000', 2))
-2048

One nice property of this function is that it's idempotent, thus the value of an already signed value will not change.
>>> s12(-1)
-1

A: Use ~, ^, and a mask (mask determines the total number of bits)
# Given negative value, obtain its two's complement form in 16 bits

>>> mask = (1 << 16) - 1
>>> a = -6
>>> bin(~(a ^ mask))
'0b1111111111111010'

# Given 16-bit signed binary string, return the integer value
>>> mask = (1 << 16) - 1
>>> b = '1111111111110101'
>>> ~(int(b, 2) ^ mask)
-11

A: I'm using Python 3.4.0
In Python 3 we have some problems with data types transformation.
So... here I'll tell a tip for those (like me) that works a lot with hex strings.
I'll take an hex data and make an complement it:
a = b'acad0109'

compl = int(a,16)-pow(2,32)

result=hex(compl)
print(result)
print(int(result,16))
print(bin(int(result,16)))

result = -1397948151 or -0x5352fef7 or '-0b1010011010100101111111011110111'

A: This works for 3 bytes. Live code is here
def twos_compliment(byte_arr):
   a = byte_arr[0]; b = byte_arr[1]; c = byte_arr[2]
   out = ((a<<16)&0xff0000) | ((b<<8)&0xff00) | (c&0xff)
   neg = (a & (1<<7) != 0)  # first bit of a is the "signed bit." if it's a 1, then the value is negative
   if neg: out -= (1 << 24)
   print(hex(a), hex(b), hex(c), neg, out)
   return out

twos_compliment([0x00, 0x00, 0x01])
>>> 1

twos_compliment([0xff,0xff,0xff])
>>> -1

twos_compliment([0b00010010, 0b11010110, 0b10000111])
>>> 1234567

twos_compliment([0b11101101, 0b00101001, 0b01111001])
>>> -1234567

twos_compliment([0b01110100, 0b11001011, 0b10110001])
>>> 7654321

twos_compliment([0b10001011, 0b00110100, 0b01001111])
>>> -7654321

A: Ok i had this issue with uLaw compression algorithm with PCM wav file type. And what i've found out is that two's complement is kinda making a negative value of some binary number as can be seen here.And after consulting with wikipedia i deemed it true.
The guy explained it as finding least significant bit and flipping all after it. I must say that all these solutions above didn't help me much. When i tried on 0x67ff it gave me some off result instead of -26623. Now solutions may have worked if someone knew the least significant bit is scanning list of data but i didn't knew since data in PCM varies. So here is my answer:
max_data = b'\xff\x67' #maximum value i've got from uLaw data chunk to test

def twos_compliment(short_byte): # 2 bytes
    short_byte = signedShort(short_byte) # converting binary string to integer from struct.unpack i've just shortened it.
    valid_nibble = min([ x*4 for x in range(4) if (short_byte>>(x*4))&0xf ])
    bit_shift = valid_nibble + min( [ x for x in [1,2,4,8] if ( ( short_byte>>valid_nibble )&0xf )&x ] )
    return (~short_byte)^( 2**bit_shift-1 )

data  = 0x67ff
bit4 = '{0:04b}'.format
bit16 = lambda x: ' '.join( map( bit4, reversed([ x&0xf, (x>>4)&0xf, (x>>8)&0xf, (x>>12)&0xf ]) ) )

# print( bit16(0x67ff) , ' : ', bit16( twos_compliment(  b'\xff\x67' ) ) )
# print( bit16(0x67f0) , ' : ', bit16( twos_compliment(  b'\xf0\x67' ) ) )
# print( bit16(0x6700) , ' : ', bit16( twos_compliment(  b'\x00\x67' ) ) )
# print( bit16(0x6000) , ' : ', bit16( twos_compliment(  b'\x00\x60' ) ) )
print( data, twos_compliment(max_data) )

Now since code is unreadable i will walk you through the idea.
## example data, for testing... in general unknown
data = 0x67ff # 26623 or 0110 0111 1111 1111

This is just any hexadecimal value, i needed test to be sure but in general it could be anything in range of int. So not to loop over whole bunch of 65535 values short integer can have i decided to split it by nibbles ( 4 bits ). It could be done like this if you haven't used bitwise operators before.
nibble_mask = 0xf # 1111
valid_nibble = []

for x in range(4): #0,1,2,3 aka places of bit value
    # for individual bits you could go 1<<x as you will see later

    # x*4 is because we are shifting bit places , so 0xFA>>4 = 0xF
    #     so 0x67ff>>0*4 = 0x67ff
    #     so 0x67ff>>1*4 = 0x67f
    #     so 0x67ff>>2*4 = 0x67
    #     so 0x67ff>>3*4 = 0x6
    # and nibble mask just makes it confided to 1 nibble so 0xFA&0xF=0xA
    if (data>>(x*4))&nibble_mask: valid_nibble.append(x*4) # to avoid multiplying it with 4 later

So we are searching for least significant bit so here the min(valid_nibble ) will suffice. Here we've gotten the place where first active (with setted bit) nibble is. Now we just need is to find where in desired nibble is our first setted bit.
bit_shift = min(valid_nibble)
for x in range(4):
    # in my example above [1,2,4,8] i did this to spare python calculating
    ver_data = data>>min(bit_shift ) # shifting from 0xFABA to lets say 0xFA
    ver_data &= nibble_mask # from 0xFA to 0xA
    if ver_data&(1<<x):
        bit_shift += (1<<x)
        break

Now here i need to clarify somethings since seeing ~ and ^ can confuse people who aren't used to this:
XOR: ^: 2 numbers are necesery
This operation is kinda illogical, for each 2 bits it scans if both are either 1 or 0 it will be 0, for everything else 1.
 0b10110
^0b11100
---------
 0b01010

And another example:
 0b10110
^0b11111
---------
 0b01001

1's complement : ~ - doesn't need any other number
This operation flips every bit in a number. It is very similar to what we are after but it doesn't leave the least significant bit.
0b10110
~
0b01001

And as we can see here 1's compliment is same as number XOR full set bits.

Now that we've understood each other, we will getting two's complement by restoring all bites to least significant bit in one's complement.
data = ~data # one's complement of data

This unfortunately flipped all bits in our number, so we just need to find a way to flip back the numbers we want. We can do that with bit_shift since it is bit position of our bit we need to keep. So when calculating number of data some number of bits can hold we can do that with 2**n and for nibble we get 16 since we are calculating 0 in values of bits.
2**4 = 16 # in binary 1 0000

But we need the bytes after the 1 so we can use that to diminish the value by 1 and we can get.
2**4 -1 = 15 # in binary 0 1111

So lets see the logic in concrete example:
 0b110110
 lsb = 2 # binary 10

~0b110110
----------
 0b001001 # here is that 01 we don't like

 0b001001
^0b000011 # 2**2 = 4 ; 4-1 = 3 in binary 0b11
---------
 0b001010

I hope this help'd you or any newbie that had this same problem and researched their a** off finding the solution. Have in mind this code i wrote is frankenstein code , that i why i had to explain it. It could be done more prettier, if anyone wants to make my code pretty please be my guest.

A: Here's a version to convert each value in a hex string to it's two's complement version.

In [5159]: twoscomplement('f0079debdd9abe0fdb8adca9dbc89a807b707f')
Out[5159]: '10097325337652013586346735487680959091'

def twoscomplement(hm):
   twoscomplement=''
   for x in range(0,len(hm)):
       value = int(hm[x],16)
       if value % 2 == 1:
         twoscomplement+=hex(value ^ 14)[2:]
       else:
         twoscomplement+=hex(((value-1)^15)&0xf)[2:]
   return twoscomplement

A: Still a very relevant question, but none of the answers worked in my scenario - which is surprising.
Here's a very simple function to calculate n-bit 2's complement integer values from an integer value.
This function especially ensures that the returned value is NOT seen as a negative value by python, as it breaks the very nature of 2's complement numbers.
2's complement numbers were originally created to work with both positive and negative values on architectures that do not natively support them. It's a conversion and is all about using the bits available to represent and calculate with both positive and negative numbers.
Therefore the number of bits can be specified, defaults to 16, and can by setting it to 0, be set to the required number of bits for the given value.
    def twos_comp(val, bits=16):
        """compute the 2's complement of int value """
        if bits == 0:      # Use as many bits needed for the value.
            bits = val.bit_length()
        return ((val & (2 ** bits) - 1) - (2 ** bits)) * -1

Test code:
    value = 6752
    print(f'{value:05d} = 0x{value:04x} = 0b{value:016b}')

    value = twos_comp(value)
    print(f'{value:05d} = 0x{value:04x} = 0b{value:016b}')

    value = twos_comp(value)
    print(f'{value:05d} = 0x{value:04x} = 0b{value:016b}')

Test code output:
 06752 = 0x1a60 = 0b0001101001100000
 01440 = 0x05a0 = 0b0000010110100000
 06752 = 0x1a60 = 0b0001101001100000

A: Subtract 2^nbits from negative values:
In [75]: (lambda x: int(x,2) - 2**len(x)*int(x[0]))('10000000')
Out[75]: -128

In [76]: (lambda x: int(x,2) - 2**len(x)*int(x[0]))('01111111')
Out[76]: 127

In [77]: (lambda x: int(x,2) - 2**len(x)*int(x[0]))('0111')
Out[77]: 7

In [78]: (lambda x: int(x,2) - 2**len(x)*int(x[0]))('1111001')
Out[78]: -7

*

*works for any length input

*handles positive and negative values correctly

*NOTE: positive values must have leading zeros

A: It's much easier than all that...
for X on N bits:
Comp = (-X) & (2**N - 1)
def twoComplement(number, nBits):
    return (-number) & (2**nBits - 1)


text:
Q: Stuck in crashlytics, no verification from firebase on running app I want to add crashlytics to my app , i followed google docs but when adding crashlytics the verification to run your app never completes.
The verification 3rd step i really struggle with.
Although fabric Io works, it shows the icon in my app and also i can view errors using fabric.
These are my gradle files
App gradle
   uildscript {
    repositories {
        maven { url 'https://maven.fabric.io/public' }
    }

    dependencies {
        classpath 'io.fabric.tools:gradle:1.+'
    }
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

repositories {
    maven { url 'https://maven.fabric.io/public' }
}

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.innovate.duplicatefileremoval"
        minSdkVersion 14
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    configurations.all { //fix ClassNotFoundException : OnUnhandledKeyEventListener
        resolutionStrategy.eachDependency { details ->
            def requested = details.requested
            if (requested.group == "com.android.support") {
                if (!requested.name.startsWith("multidex")) {
                    details.useVersion "26.+"
                }
            }
        }
    }

    implementation 'com.android.support:appcompat-v7:26.0.0'

    testImplementation 'junit:junit:4.12'
    apply plugin: 'io.fabric'
    implementation 'com.google.firebase:firebase-core:16.0.1'
    implementation 'com.makeramen:roundedimageview:2.3.0'
    implementation 'com.android.support:recyclerview-v7:26.0.0'
    implementation 'com.android.support:cardview-v7:26.0.0'
    implementation project(':sectionedrecyclerview')
    implementation 'commons-io:commons-io:2.6'
    implementation 'com.github.ybq:Android-SpinKit:1.2.0'
    api 'com.google.guava:guava:27.1-android'
    implementation 'com.tuyenmonkey:mkloader:1.4.0'
    implementation ('com.github.bumptech.glide:glide:4.9.0'){
        exclude group: 'com.android.support'
    }
    annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0'
    implementation 'com.crashlytics.sdk.android:crashlytics:2.10.0'
    implementation 'com.crashlytics.sdk.android:crashlytics-ndk:2.1.0'
}
apply plugin: 'com.google.gms.google-services'

crashlytics {
    enableNdk true
    androidNdkOut 'src/main/obj'
    androidNdkLibsOut 'src/main/libs'
}

this is project gradle
    buildscript {
    repositories {
        jcenter()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
        // Add the following repositories:
        google()  // Google's Maven repository

        maven {
            url 'https://maven.fabric.io/public'
        }
    }
    dependencies {
         classpath 'com.android.tools.build:gradle:3.2.0'
        classpath 'com.google.gms:google-services:4.0.1'
        //Crashlytics requires Google Services plugin version 3.1.2 or higher
        classpath 'io.fabric.tools:gradle:1.25.4'
       //  classpath 'com.google.gms:google-services:3.0.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
        // Check that you have the following line (if not, add it):
        google()  // Google's Maven repository
        // ...
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

i have run my app several times still nothing.

A: Most likely you have to add the debug/release key fingerprints to the console.
Debug is simple to connect, for release you need to switch the build-type once.
It does not need any crashes to confirm the connection.

redpajama_set_name: RedPajamaStackExchange


text:
Q: insmod error, invalid module format, fedora 35 I'm attempting to learn about kernel modules and followed along with a simple hello world example. My computer is running fedora 35. When I run sudo insmod mymodule.ko i get the error insmod: ERROR: could not insert module mymodule.ko: Invalid module format.
From reading other peoples issues it seems to do with the kernel version being mismatched with what the module was compiled for, however uname -r returns 5.16.18-200.fc35.x86_64 and modinfo mymodule.ko gives vermagic: 5.16.18-200.fc35.x86_64 SMP preempt mod_unload which seems to suggest they are the same.
Following some other posts I tried dmesg and got:
[ 1689.372354] module: x86/modules: Skipping invalid relocation target, existing value is nonzero for type 1, loc 00000000d2334323, val ffffffffc140e000 which is quite different to what other users were experiencing (and doesn't seem to relate to kernel version), however I cannot make sense of it.
My makefile, in case it is useful:
obj-m += mymodule.o

all:
        make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules

clean:
        make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean

A: This post set me on the right path and might help others not using fedora
Linux Kernel Module Development "module: x86/modules: Skipping invalid relocation target, existing value is nonzero for type 1"
The issue was with the kernel headers, as always the problem was solved with the reliable uninstall and reinstall:
sudo dnf remove kernel-devel
sudo dnf install kernel-devel


text:
Q: Is it possible to read parquet files in chunks? For example, pandas's read_csv has a chunk_size argument which allows the read_csv to return an iterator on the CSV file so we can read it in chunks.
The Parquet format stores the data in chunks, but there isn't a documented way to read in it chunks like read_csv.
Is there a way to read parquet files in chunks?

A: If your parquet file was not created with row groups, the read_row_group method doesn't seem to work (there is only one group!).
However if your parquet file is partitioned as a directory of parquet files you can use the fastparquet engine, which only works on individual files, to read files then, concatenate the files in pandas or get the values and concatenate the ndarrays
import pandas as pd
from glob import glob
files = sorted(glob('dat.parquet/part*'))

data = pd.read_parquet(files[0],engine='fastparquet')
for f in files[1:]:
    data = pd.concat([data,pd.read_parquet(f,engine='fastparquet')])

A: I'm not sure if one can do it directly from pandas but pyarrow exposes read_row_group.  The resulting Table should be convertable to a pandas dataframe with to_pandas
As of pyarrow 3.0 there is now a iter_batches method that can be used.

A: This is an old question but the follwoing worked for me if you want to read all chunks in one liner without using concat:
pd.read_parquet("chunks_*", engine="fastparquet")

or if you want to read specific chunks you can try:
pd.read_parquet("chunks_[1-2]*", engine="fastparquet")

(this way you will read only the first two chunks, it is also not necessary to specify an engine)

A: You can use iter_batches
from pyarrow. to_pandas method should give you pandas DataFrame.
Example:
import pyarrow.parquet as pq

parquet_file = pq.ParquetFile('example.parquet')

for batch in parquet_file.iter_batches():
    print("RecordBatch")
    batch_df = batch.to_pandas()
    print("batch_df:", batch_df)

A: You can't use a generator/iterator over a parquet file because it is a compressed file. You need to fully decompress it first.


text:
Q: Create a new date from date - (minus) the UTC offset submitButton.addEventListener(
    "click", function(e) {
        e.preventDefault();

        validateTimeDate();

        if(!timeInPast && !dateInPast) {
            var hour = parseInt(hourInput.value);
            var day = parseInt(dayInput.value);

            var utcOffset = parseInt(timezoneInput.value);
            var newHour = hour - utcOffset;
            if(hour < 0) {
                day--;
                hour = 24 + utcOffset;
            }
        }
    }
);

I have the following code, where I'm attempting to validate whether the date/time that is currently being worked with is past the current time/date. I'm attempting to add timezone support, so I have a UTC offset (-12, 12) range. I made a start by attempting to deduct the UTC offset hours from the current working hour, and if this sets the hour below 0, deduct from the day and remove the offset from hour many hours are in a day.
But this is going to get really messy, because as well as day, I'm going to have to do the same for month, year, etc.
I'm wondering if there's a way to take a Date object and make a new Date object or translate this date object against a UTC offset? I could them simply do if(offsetDate < new Date() {
(I haven't provided my full code, as I'm not having an issue with the actual execution of the code, simply the logic behind it/approach)


text:
Q: Setting proxy server in Eclipse Mars I am using a server "http://abc/xyz.pac",port 80 to connect to internet in Internet Options. How do i configure the same in eclipse.
FYI, there are lot many multiple proxies in this pac file and they keep getting updated. so is there a way to directly apply this pac file onto eclipse.

A: Go to Window > Preference > Network connections Select the "Native" as the "Active Provider". It will use pac file designated in IE to connect to Internet.


text:
Q: mount -a does not work, but mounting manually works lsb_release & uname
[wellbye@AY130622174524343529Z:~]lsb_release -a
LSB Version:    core-9.20160110ubuntu0.2-amd64:core-9.20160110ubuntu0.2-noarch:security-9.20160110ubuntu0.2-amd64:security-9.20160110ubuntu0.2-noarch
Distributor ID: Ubuntu
Description:    Ubuntu 16.04.3
LTS Release:    16.04
Codename:       xenial

[wellbye@AY130622174524343529Z:~]uname -a
Linux AY130622174524343529Z 4.4.0-105-generic #128-Ubuntu SMP Thu Dec 14 12:42:11 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

/etc/fstab:
UUID=e2048966-750b-4795-a9a2-7b477d6681bf / ext4 errors=remount-ro 0 1
/dev/xvdb1 /newdisk ext3 rw,user,noauto,exec,utf8 0 0

sudo mount -a has neither effect nor error, but manually mounting works:
 sudo mount -t auto /dev/xvdb1 /newdisk/

what's the problem with fstab ?

A: I see you have the noauto flag set.  This means "don't mount with the -a flag"
From man 5 fstab
          noauto do not mount when "mount -a"  is  given  (e.g.,  at  boot
                 time)

A: Below Should be format while mounting with UUID
UUID=UUIDNUMBER /directory ext4 rw,user,exec 0 0


text:
Q: I have Messages in iCloud but messages still not perfectly synced I have Messages in iCloud on my iPhone (6S, latest OS version 11.4) - or at least I think I do: In iPhone Settings -> [my Apple profile] -> iCloud I have Messages switched to on. I also have Messages on my MacBook Pro, which has the latest version of Mac OS.
However today my iPhone was off because it didn't have enough charge. My Mom (who also has an iPhone with iMessage) sent me a message. The message showed up on my Mac. However even after I restored power to my iPhone and restarted it a couple times, the message never showed up on my iPhone.
So what is going wrong? I thought this, at least, would be solved by Messages in iCloud.

A: While there is no sync now button, you could force one by turning iCloud Sync off and then back on.


text:
Q: Scrape website that require login with BeautifulSoup I want to scrape website that requires login with Python and BeautifulSoup and requests libs. (no selenium)
This is my code:
import requests
from bs4 import BeautifulSoup

auth = (username, password)
headers = {
    'authority': 'signon.springer.com',
    'cache-control': 'max-age=0',
    'upgrade-insecure-requests': '1',
    'origin': 'https://signon.springer.com',
    'content-type': 'application/x-www-form-urlencoded',
    'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36',
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'sec-fetch-site': 'same-origin',
    'sec-fetch-mode': 'navigate',
    'sec-fetch-user': '?1',
    'sec-fetch-dest': 'document',
    'referer': 'https://signon.springer.com/login?service=https%3A%2F%2Fpress.nature.com%2Fcallback%3Fclient_name%3DCasClienthttps%3A%2F%2Fpress.nature.com&locale=en&gtm=GTM-WDRMH37&message=This+page+is+only+accessible+for+approved+journalists.+Please+log+into+your+press+site+account.+For+more+information%3A+https%3A%2F%2Fpress.nature.com%2Fapprove-as-a-journalist&_ga=2.25951165.1431685211.1610963078-2026442578.1607341887',
    'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8',
    'cookie': 'SESSION=40d2be77-b3df-4eb6-9f3b-dac31ab66ce3',
}

params = (
    ('service', 'https://press.nature.com/callback?client_name=CasClienthttps://press.nature.com'),
    ('locale', 'en'),
    ('gtm', 'GTM-WDRMH37'),
    ('message', 'This page is only accessible for approved journalists. Please log into your press site account. For more information: https://press.nature.com/approve-as-a-journalist'),
    ('_ga', '2.25951165.1431685211.1610963078-2026442578.1607341887'),
)

data = {
  'username': username,
  'password': password,
  'rememberMe': 'true',
  'lt': 'LT-95560-qF7CZnAtuDqWS1sFQgBMqPVifS5mTg-16c07928-2faa-4ce0-58c7-5a1f',
  'execution': 'e1s1',
  '_eventId': 'submit',
  'submit': 'Login'
}

session = requests.session()
response = session.post('https://signon.springer.com/login', headers=headers, params=params, data=data, auth = auth)
print(response)
#time.sleep(5) does not make any diference
soup = BeautifulSoup(response.content, 'html.parser')
print(soup) # im not getting the results that I want

I'm not getting required HTML page with all data that I want, the HTML page that I'm getting is login page. This is the HTML response:
https://www.codepile.net/pile/EGY0YQMv
I think that the problem is because I want to scrape this page:
https://press.nature.com/press-releases
But when I click on that link (and Im not logged in) it redirects me to different website for loggin in:
https://signon.springer.com/login
For getting all headers and params and data values I have used:
inspect page -> network -> find login request -> copy cURL -> https://curl.trillworks.com/

I have tried multiple post and get methods, I have tried with and without auth param, but result is the same.
What am I doing wrong?

A: Try running the script filling in your username and password fields and let me know what you get. If it still doesn't log you in, make sure to use additional headers within post requests.
import requests
from bs4 import BeautifulSoup

link = 'https://signon.springer.com/login'

with requests.Session() as s:
    s.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36'
    res = s.get(link)
    soup = BeautifulSoup(res.text,'html.parser')
    payload = {i['name']:i.get('value','') for i in soup.select('input[name]')}
    #what the above line does is parse the keys and valuse available in the login form
    payload['username'] = username
    payload['password'] = password

    print(payload) #when you print this, you should see the required parameters within payload

    s.post(link,data=payload)
    #as we have laready logged in, the login cookies are stored within the session
    #in our subsequesnt requests we are reusing the same session we have been using from the very beginning
    r = s.get('https://press.nature.com/press-releases')
    print(r.status_code)
    print(r.text)

A: Have you tried using selenium alongside bs4 and requests?
You can let the browser wait until it selects an element:
driver = webdriver.Chrome()
driver.implicitly_wait(10) #secs
driver.get("https://press.nature.com/press-releases") #redirect to login link
#then login
driver.get("https://press.nature.com/press-releases") #link behind login

So you can go to the login url and login, then go to the place you want to scrape.

A: I think your auth parameter isn't in the correct format to be accepted by requests. You can try importing HTTPBasicAuth
from requests.auth import HTTPBasicAuth
auth = HTTPBasicAuth(username, password)


text:
Q: Hosting service for APNS Is there any good service for Apple Push Notification Service (APNS)?
I've checked Site5, but I'm not sure if I cant achieve this with hostbasic plan. Will they allow outgoing connections on the ports 2195 and 2196 in order to able to send push notification?
Can anyone confirm this or suggest some better services?
PS (I  also need to support PHP and MySQL).

A: 1and1.com suffers all the same faults as any other shared hosting provider, but they give you ssh access with the ability to install and compile packages if you ever need to.  There's an admin panel for cronjobs but you can also do it via SSH via crontab. If you're not interested in SSH then I'd go elsewhere.

A: I've purchased hosting plan on site5 (hostbasic) and everything works fine.
Didn't had to ask to open additional ports, 2195 and 2196 seems to be already opened.

A: I Recently Used the Hosting from Dreamhost (Shared Hosting) , They have the port 2195 open and support push notifications under apns. Its working for me, may be others can get some help too.
EDIT:
Current I m using Shared Hosting from Host Gator and when i requested, they have opened the port 2195 (Only out-bond) for me and its working!!! I can able to send notification. Cheers!!!
Hostgator is cheaper than Site5, compare plans here  and here.


text:
Q: How Can I Set a Payment Unit by Country with Flutter Pay? How can I determine currencies by country? I am receiving payment transaction using Pay with Flutter plugin.
How can I make the following values in USD for America and TRY for Turkey according to the user's country.
"countryCode": "US",
"currencyCode": "USD",
const String defaultApplePay = '''{
      "provider": "apple_pay",
      "data": {
        "merchantIdentifier": "merchant.com.sams.fish",
        "displayName": "Sam's Fish",
        "merchantCapabilities": ["3DS", "debit", "credit"],
        "supportedNetworks": ["amex", "visa", "discover", "masterCard"],
        "countryCode": "US",
        "currencyCode": "USD",
        "requiredBillingContactFields": ["emailAddress", "name", "phoneNumber", "postalAddress"],
        "requiredShippingContactFields": [],
        "shippingMethods": [
          {
            "amount": "0.00",
            "detail": "Available within an hour",
            "identifier": "in_store_pickup",
            "label": "In-Store Pickup"
          },
          {
            "amount": "4.99",
            "detail": "5-8 Business Days",
            "identifier": "flat_rate_shipping_id_2",
            "label": "UPS Ground"
          },
          {
            "amount": "29.99",
            "detail": "1-3 Business Days",
            "identifier": "flat_rate_shipping_id_1",
            "label": "FedEx Priority Mail"
          }
        ]
      }
    }''';

I tried to do it with the codes in the getCurrency() method above, but it adjusts according to the device language. Idont want this.
String getCurrency() {
    //var format = NumberFormat.simpleCurrency(locale: Platform.localeName);
    Locale myLocale = Localizations.localeOf(context);
    return myLocale.countryCode ?? "";
  }


text:
Q: Apache2 - Subdomain to port -> forwarding Okay, I'm at a certain point where I feel a huge amount of stupidity on myself because of reading hundreds of manual and instruction pages and still not getting it. I hope you can help me!
I have a server running Ubuntu Server. On the server I'm running ddclient for updating my IP with dyn.com. There I have a domain "rasterkomplex.net" which points to the updated IP. Easy.
There is also a camera connected to the server which runs it's own webserver @ port 3360.
When I'm now entering: rasterkomplex.net:3360 - voilà.
But now comes 2 minecraft server running simultaneously on 5001 and 5002. For every mc-server, there's the dynmap-plugins which runs also a webserver on different port. And then a webstorage on... you get it? I don't want to remember like 8 or more ports, just for accessing the related service.
What I want to accomplish:
cam.rasterwerks.net -> internal to 127.0.0.1:3360
mc1.rasterwerks.net -> internal to 127.0.0.1:5001
mc2.rasterwerks.net -> internal to 127.0.0.2:5002
etc. etc. etc.

I read a lot about VHosts, ProxyPass etc. But I'm not able to manage it getting work.
Can you give me a direction how to accomplish this? If it has to do with VHosts, maybe a sample?
Thank you very very much for your time!
Regards,
Elias.

A: You can do it with apache on one hand with ProxyPass of mod_proxy redirecting you here or there, or, what you also can do is install haproxy. Then, based on the Host in the URL that's being requested pass the request to one or another web storage.
An example config of haproxy doing exactly that would be:
frontend public
bind        X.X.X.X:80
mode        http
log         global
option      httplog
option      dontlognull
option      httpclose
maxconn     8000
clitimeout  90000

reqisetbe   ^Host:\ .*hudson    hudson

backend hudson
    mode            http
    balance         roundrobin
    contimeout      120000
    srvtimeout      120000
    redispatch
    retries         5
    server          internal.host.com Y.Y.Y.Y:8080 check inter 1000

So in this example, haproxy is bound to port 80 and when URL that's requested contains *.hudson, it gets redirected to an internal.host.com with IP of Y.Y.Y.Y to port 8080.
Now, for the apache based solution.
You can define multiple VHosts, with different names, each of them containing the following.
To do name-based vhosting, your apache config should contain:
NameVirtualHost *

Then, the vhost itself, should be:
<Virtualhost *>
  DocumentRoot "/var/www/somewhere"
  ServerName localhost
  ServerAdmin support@mycompany.com
  DirectoryIndex index.html index.php
  ProxyRequests On
  ProxyPreserveHost On
  ProxyVia full

  <proxy>
    Order deny,allow
    Allow from all
  </proxy>

  ProxyPass        /  http://somehost:1234/
  ProxyPassReverse /  http://somehost:1234/
</Virtualhost>

Feel free to choose whatever solution seems more viable to you.


text:
Q: How to access the parameter of a parameter? this is a work in progress, but I was wondering about how to access a specific file.
My main method is supposed to construct a new FileInputStream with a new file as its parameter. Then, I am supposed to call getCounts method that accepts a FileInputStream object to return some kind of map. Inside the getCounts method, I am having trouble finishing this as I have to be able to access the file inside it, and FileInputStream doesn't seem to have a accessor for it. In other words, how do I access this file used to construct the FileInputStream object that goes into the getCounts Method as a parameter, inside the getCounts method? Ultimately, I am supposed to use the keys/values of the map to get the most reoccurring character of the text file. Thanks.
Here is my code:
import java.util.*;
import java.io.*;

public class test2 {
public static void main(String[] q) throws FileNotFoundException {

    // This is for the character mapping
    Scanner console = new Scanner(System.in);
    System.out.println("Count characters of which file? ");
    FileInputStream output = new FileInputStream(new File(console.nextLine()));
    Map<Character, Integer> results = getCounts(output);
    // do stuff with this map later on...
}

 // character counting method (WIP)
 public static Map<Character, Integer> getCounts(FileInputStream input) {
     Map<Character, Integer> output = new TreeMap<Character, Integer>(); // treemap keeps keys in sorted order (chars alphabetized)
     // Problem here: need to access the file object that was instiantiated
     byte[] fileContent = new byte[(int) file.length()]; // puts all the bytes from file into byte[] to process
     input.read(fileContent);
     String test = new String(fileContent);

     // missing stuff here; use map to map keys as characters and occurrences as values.

     return output;
 }
}

A: If you are going to use FileInputStream, then you will need to loop, doing multiple reads
byte[] fileContent = new byte [1024];

while ((input.read (fileContent) != -1) {

     // save fileContent somewhere
     // e.g.
     arrlist.add (new String (fileContent));

}

A: Ideally I would pass the the length as a parameter to getCounts() but since you're not allowed to do it, you can save the file-length into a class-static parameter:
private static long length;

public static void main(String[] q) throws IOException {

        // This is for the character mapping
        Scanner console = new Scanner(System.in);
        System.out.println("Count characters of which file? ");
        File file = new File(console.nextLine());
        FileInputStream output = new FileInputStream(file);
        length = file.length();
        Map<Character, Integer> results = getCounts(output);
        // do stuff with this map later on...
    }

    // character counting method (WIP)
    public static Map<Character, Integer> getCounts(FileInputStream input) throws IOException {
        Map<Character, Integer> output = new TreeMap<Character, Integer>(); // treemap keeps keys in sorted order (chars alphabetized)
        // Problem here: need to access the file object that was instantiated
        byte[] fileContent = new byte[(int) length]; // puts all the bytes from file into byte[] to process
        input.read(fileContent);
        String test = new String(fileContent);
        System.out.println("test = " + test);

        // missing stuff here; use map to map keys as characters and occurrences as values.

        return output;
    }


text:
Q: ReSharper C++: Allow CString as a %s printf parameter? Anybody know of a way to disable the ReSharper inspection for CStrings passed directly as %s parameters?
CString s = "some string";
printf("string = %s", s);

ReSharper reports "Invalid printf format specifier", which is technically correct but this syntax is supported by MS, and used extensively in the code base I work with.
I suspect there isn't a way to filter out only this specific invalid format specifier case, but I thought I'd throw it out there anyway in hopes that I've missed something.

A: We'll change the inspection to allow passing CString to corresponding string format specifiers, please follow https://youtrack.jetbrains.com/issue/RSCPP-20109.


text:
Q: Why hash of a key is maintained inside a HashMap node? I wanted to understand why hash (final int hash) of a key is maintained inside linked list node mapped to a HashMap bucket? Once the bucket is identified using hashcode of a key, then key itself could be used to compare the key values present inside the nodes of linked list using equals.
static class Node<K,V> implements Map.Entry<K,V> {
    final int hash; // Why is it here?
    final K key;
    V value;
    Node<K,V> next;
    Node(int hash, K key, V value, Node<K,V> next) {
        this.hash = hash;
        this.key = key;
        this.value = value;
        this.next = next;
    }

I know there must be some reason for this. If anybody please help me understand this with an example. Thanks !


text:
Q: Обработка нажатия нескольких кнопок Одна за одной. Кому не лень прочитать код. Думаю, идея довольно понятна (простой калькулятор).
import java.awt.FlowLayout;

import javax.swing.*;

public class calc_97_lvl {

    public static JLabel jlab;

    calc_97_lvl() {

        ListenCalc LC = new ListenCalc();

        JFrame jfrm = new JFrame("Калькулятор Кузнецова");
        jfrm.setSize(185, 157);
        jfrm.setLayout(new FlowLayout());
        jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jfrm.setVisible(true);
        JLabel jlab = new JLabel();
        jlab.setText("egeherjrj!");
        jlab.setSize(150, 150);

        JButton but1 = new JButton("+");
        JButton but2 = new JButton("-");
        JButton but3 = new JButton("*");
        JButton but4 = new JButton("/");
        JButton but5 = new JButton(".");
        JButton but6 = new JButton("e");
        JButton but7 = new JButton("=");

        JButton b1 = new JButton("1");
        JButton b2 = new JButton("2");
        JButton b3 = new JButton("3");
        JButton b4 = new JButton("4");
        JButton b5 = new JButton("5");
        JButton b6 = new JButton("6");
        JButton b7 = new JButton("7");
        JButton b8 = new JButton("8");
        JButton b9 = new JButton("9");
        JButton b0 = new JButton("0");

        but1.addActionListener(LC);
        but2.addActionListener(LC);
        but3.addActionListener(LC);
        but4.addActionListener(LC);
        but5.addActionListener(LC);
        but6.addActionListener(LC);
        but7.addActionListener(LC);

        b1.addActionListener(LC);
        b2.addActionListener(LC);
        b3.addActionListener(LC);
        b4.addActionListener(LC);
        b5.addActionListener(LC);
        b6.addActionListener(LC);
        b7.addActionListener(LC);
        b8.addActionListener(LC);
        b9.addActionListener(LC);
        b0.addActionListener(LC);

        jfrm.add(jlab);
        jfrm.add(b1);
        jfrm.add(b2);
        jfrm.add(b3);
        jfrm.add(but1);
        jfrm.add(b4);
        jfrm.add(b5);
        jfrm.add(b6);
        jfrm.add(but2);
        jfrm.add(b7);
        jfrm.add(b8);
        jfrm.add(b9);
        jfrm.add(but3);
        jfrm.add(but5);
        jfrm.add(b0);
        jfrm.add(but6);
        jfrm.add(but7);

    }
    public void set_jlab(String newText) {
        jlab.setText(newText);
    }
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new calc_97_lvl();
            }
        });
    }
}

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.StringTokenizer;

public class ListenCalc implements ActionListener {

    double numberResult;

    public void actionPerformed(ActionEvent ae) {
        resultGiver(ae.getActionCommand());
    }

    public double resultGiver(String textResult) {
        StringTokenizer ST = new StringTokenizer(textResult, "+-*/e", true);

        String s1 = ST.nextToken();
        String s2 = ST.nextToken();
        String s3 = ST.nextToken();
        double op1 = Double.parseDouble(s1);
        double op2 = Double.parseDouble(s3);
        if (s2.equals("+")) {
            numberResult = op1 + op2;
        } else if (s2.equals("-")) {
            numberResult = op1 - op2;
        } else if (s2.equals("*")) {
            numberResult = op1 * op2;
        } else if (s2.equals("/")) {
            numberResult = op1 / op2;
        } else {}
        return 0;
    }
}

A: Че-то вы тут накуролесили аж страшно смотреть на код.

*

*На фига все напихали в конструктор вашего класса?

*На фига еще и вызов конструктора запихали в асинхронный вызов обработчика сообщений оконной системы.

Надо все делать проще и деревяннее - слишком много думали и мало читали документацию.
Возьмите за основу такой пример, а если не хватит почерпните мудрость тут


text:
Q: Using each value in a list as key in key value pair I'm trying to write a custom function that takes an RDD, lower cases each record, splits it into characters, and then uses each record as the key in a key value pair where the value is always 1. I've written two other custom functions that do the lower casing and the character splitting, to_lower() and to_characters(), respectively.
I've tried a few different things, but so far I've only been able to get the entire list as the key instead of each record being in its own pair.
#Attempt 1
def rdd_to_character_value_pairs(rdd):
  lowerRDD = rdd.map(lambda x: to_lower(x))
  characterRDD = lowerRDD.map(lambda x: to_characters(x))
  pairedRDD = characterRDD.map(lambda x: ([char for char in characterRDD], 1))
return pairedRDD

#Attempt 2
def rdd_to_character_value_pairs(rdd):
  lowerRDD = rdd.map(lambda x: to_lower(x))
  characterRDD = lowerRDD.map(lambda x: to_characters(x))
  for i in characterRDD.collect():
     return ([char for char in characterRDD], 1)
     #have also tried return (i,1)

I understand that you can't iterate over an RDD, but I haven't been able to get any of the workarounds to work either.

A: some_list = ["value1", "value2"]
some_dict = {value_as_key: 'some_value' for value_as_key in some_list}

Output:
{'value1': 'some_value', 'value2': 'some_value'}


text:
Q: Get YouTube playlist videos anonymously I would like to display a list of videos from a YouTube playlist in an intranet application.
Is it possible to get the list of videos from a YouTube playlist using the Data api (or any other way) without requiring the user to login?
Everything that I have read so far in the YouTube data api requires the user to be signed in to authenticate.

A: unfortunately, you can't access youtube data API with anonymously user.
Your application must have authorization credentials to be able to use the YouTube Data API.
The Developers Console associates your credentials with the APIs that you indicate that your application will use. Note that the Developers Console does not allow you to select the YouTube Data API (v2). However, authorization credentials for the v3 API will also work for the v2 API.
If possible, you should actually use YouTube Data API (v3) rather than the v2 API in your application. The YouTube API blog explains some of the benefits that the newer API offers, and we have added a year's worth of additional functionality to the API since that blog post!
related link : https://developers.google.com/youtube/2.0/developers_guide_protocol_oauth2#OAuth2_Client_Side_Web_Applications_Flow


text:
Q: How to add "$" string to an interpolated value? say I want to produce $small by adding an interpolated value to '$', or, in other words, by concatenating the string '$' to an interpolated value. Something like this:
$#{value}

or this:
"$" + #{value}

None of them seem to work in sass/scss. Is there a working syntax for this?
I need this because I'm building this mixin that accept media queries names (it comes from my framework, too long to explain, and a little offtopic) and I'd like to strip out the dollar when passing arguments:
@mixin prog-prop($property-name, $mq-values){
  @each $mq in $mq-values{
    @include mq(#{nth($mq, 1)}){ #{$property-name}: #{nth($mq, 2)} }
  }
}

A: I don't know why you want to do so, but this is a way:
$value:'string';

$value: '$#{$value}';

.value{
  content: $value;
}


text:
Q: GridFS in Laravel 5.4 doesn't work I'm using PHP7, Laravel 5.4 and jenssegers/laravel-mongodb (PECL package). I need to use GridFS, that it's included into the MongoDB PECL package, so I'm trying to get GridFS like this:
$gridfs = DB::connection('mongo')->getMongoDB()->getGridFS();

But it's throwing the exception: "Call to undefined method MongoDB\Database::getGridFS()".
Any idea of this?

A: If you using mongo-php-library 2.2 driver, getGridFS() method no longer exists, however you can use Bucket class for upload and download documents to mongodb grid. You can try the following:
//upload file
$bucket = \DB::connection('mongodb')->getMongoDB()->selectGridFSBucket();
$resource = fopen($file_path, "a+");
$file_id = $bucket->uploadFromStream($file_path, $resource);

//download file
$bucket = \DB::connection('mongodb')->getMongoDB()->selectGridFSBucket();
$file_metadata = $bucket->findOne(["_id" => $file_id]);
$path = $file_metadata->filename;

if(!file_exists($path)) {
    $downloadStream = $bucket->openDownloadStream($file_id);
    $stream = stream_get_contents($downloadStream, -1);
    $ifp = fopen($path, "a+");
    fwrite($ifp, $stream);
    fclose($ifp);
}

Note that $file_id variable is an ObjectId, if you have an string value, you need to convert to ObjectId: $file_id = new \MongoDB\BSON\ObjectID($str_file_id);


text:
Q: Can animals spawn? The new release of Minecraft: PE features baby animals. Will these animals eventually spawn in existing worlds, or will my kids (who have built some rather elaborate structures for the Pocket Edition) have to start over?
It appears to be the case that animals never spawn in older versions of PE; are the baby animals a change to that, or are they just a new thing which could be running around at the beginning of a game?

A: Unfortunately, your kids would have to start over in a new world in order to get the baby animals.
According to the update changelog on the Minecraft Wiki, baby animals only will spawn in new worlds, in the same fashion as adult animals spawn.

A: I had a game that was made before I updated, then while I was playing it, I found a cute little baby sheep racing around near my house!

A: If their Minecraft PE is 1.6.1 or later, I am 100 percent sure that your kids will just have to wait a bit. (About a month in Minecraft days) and if there are few enough remaining animals, new ones will spawn. Eventually. Some of the new spawns will be babies.  This unfortunately will wear off in time though.
I know this because I spent hours fencing all the animals in my world.  No more spawned for about 3 (real) months. My brother joined on multiplayer and immediately proceeded to kill all my sheep. I was very angry. After a while I went outside and was logging, when I actually saw a baby sheep spawn out of nowhere. Then a cow and a pig. Then a baby chicken. Etc. I checked this on every site I could find on this topic. 8 out of ten said the same thing.  Good luck!

A: If you haven't explored the entire area yet, the chunks wouldn't have been generated in that area, so it's possible to find baby animals. If you explored the whole seed, then you will have to make a new save and make sure you don't explore everywhere at once, because something might be added in a few updates that will be really superior and that thing might spawn into your unexplored chunks.Therefore, it is possible to do this, only if you have not explored the entire area in which the new items could spawn it. Ask your kids if they explored the entire area or not.


text:
Q: VS2008 : Can't debug, error "AspNetHostingPermission" Man, I'm having a rough day.
I have a ASP.NET 2.0 application with AJAX extensions and I want to debug an unruly function. When I press Debug, it goes to compile the site, but it errors out :
Error   945 Request for the permission of type
  'System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral,
  PublicKeyToken=b77a5c561934e089' failed.
  W:\..\Application\Folder\default.aspx 42

How can I get this thing to run in debug mode? It runs fine when I browse it normally.
.
Here's my web.config just in case:
<?xml version="1.0"?>
<configuration>
  <configSections>
    <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">

        <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">

        </sectionGroup>
      </sectionGroup>
    </sectionGroup>
  </configSections>

  <connectionStrings>
    <remove name="LocalSqlServer"/>
     <add name="LocalSqlServer" .../>
  </connectionStrings>
  <appSettings>
    <add key=.../>
    <add key.../>
  </appSettings>

  <system.web>

    <httpRuntime executionTimeout="300"  maxRequestLength="548576"
          useFullyQualifiedRedirectUrl="false" />

    <compilation debug="true">
      <assemblies>
        <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        <add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
      </assemblies>
    </compilation>

    <machineKey validationKey="..." ... />

    <roleManager enabled="true"/>
    <membership userIsOnlineTimeWindow="20" defaultProvider="SqlProvider" >
      <providers>
        <remove name="SqlProvider"/>
        <remove name="AspNetSqlMembershipProvider" />
        <add connectionStringName="LocalSqlServer" ... />
      </providers>
    </membership>

    <authentication mode="Forms">
      <forms name="..." loginUrl="index.aspx" defaultUrl="Default.aspx"
       timeout="600" cookieless="AutoDetect" enableCrossAppRedirects="true" />
    </authentication>
    <authorization>
      <deny users="?"/>
    </authorization>

    <customErrors mode="Off" defaultRedirect="Error.aspx">

    </customErrors>

    <pages>
      <controls>
        <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add tagPrefix="cc2" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      </controls>
    </pages>
    <httpHandlers>
      <remove verb="*" path="*.asmx"/>
      <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
    </httpHandlers>
    <httpModules>
      <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    </httpModules>
  </system.web>

  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
        <providerOption name="CompilerVersion" value="v3.5"/>
        <providerOption name="WarnAsError" value="false"/>
      </compiler>
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" warningLevel="4" type="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
        <providerOption name="CompilerVersion" value="v3.5"/>
        <providerOption name="OptionInfer" value="true"/>
        <providerOption name="WarnAsError" value="false"/>
      </compiler>
    </compilers>
  </system.codedom>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <modules>
      <remove name="ScriptModule"/>
      <add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    </modules>
    <handlers>
      <remove name="WebServiceHandlerFactory-Integrated"/>
      <remove name="ScriptHandlerFactory"/>
      <remove name="ScriptHandlerFactoryAppServices"/>
      <remove name="ScriptResource"/>
      <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    </handlers>
  </system.webServer>

  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>

  <location path="Error.aspx">
    <system.web>
      <authorization>
        <allow users="?"/>
      </authorization>
    </system.web>
  </location>

  <system.net>
    <mailSettings>
      <smtp from="...">
        <network host="..." password="" userName=""/>
      </smtp>
    </mailSettings>
  </system.net>
</configuration>

A: It sounds like a permissions issue on that folder. Is W: a network drive of some sort?
Additional info


text:
Q: raised ... 25 basis points or raised ... by 25 basis points? I would like to know if it is correct to add the word "by" in the following sentence:  Today, bank x raised its loan rate by 25 basis points.

A: This is an interesting example, and to be honest I think it shows the weakness of many dictionaries. The verb "raise" is listed in most dictionaries as transitive, however, that is rather a simplification of the truth. A more correct measure of a verb's argument count would be its valency.
Verbs in English can be monovalent, when they take only a subject, divalent when they take a subject and an object, and trivalent when they take a subject and two objects. The verb "to read" can be all three. For example:
He reads.
He reads a book.
He reads her a book.

Obviously these are monovalent, divalent and trivalent respectively.
In the case of "raise" it seems that it can be both divalent and trivalent. If we say:
The bank raised interest rates by 25 basis points.

We are using it as a divalent verb with a prepositional phrase (by 25 basis points.)
If we say:
The bank raised interest rates 25 basis points.

We are using it as a trivalent verb with two objects, "interest rates" and "25 basis points."
I think this trivalent approach is uncommon, and I suspect it is more common in the American English dialect, but it is not unique to this construction. For example:
My promotion means they raise my salary $10,000.

Would also be acceptable, and a trivalent usage of this verb.

A: Adding the word "by" sounds more correct to me. Without it, the sentence seems like it is missing something in the spot where the word "by" would have been.


text:
Q: Are there any projects that started out as a Prolog prototype PyPy's JIT started out as a Prolog prototype: http://morepypy.blogspot.com/2008/06/hi-all-some-news-from-jit-front.html.
Gambit Scheme and Erlang also started out implemented in Prolog.
Are there any other notable (or not so notable) projects that started out in Prolog and then reimplemented in a more mainstream language ?

A: Mercury was bootstrapped in Prolog, just like Erlang.


text:
Q: How do I enter full_path and path_extension using the import package in Windows? How do I enter full_path and path_extension using the import package?
I am using Windows and want to point to c:\tex\proj\pic\alpha having proj as the directory hosting the tex file (I would like to point to pic\alpha relative to proj with path_extension).
I tried c/tex/proj/pic/alpha and c:\tex\proj\pic\alpha as full_path but it didn't help me find the file beta.tex_pdf in alpha directory. The file beta.pdf_tex was created by Inkscape.
\usepackage{import}

\import{c/tex/proj/pic/alpha}{beta.pdf_tex}%File `beta.pdf_tex' not found.

I can't figure out how to make a MWE out of this.
Edit:
\begin{figure}[!th]
   \centering
   \def\svgwidth{5cm}
   \input{beta.pdf_tex}
\end{figure}

This works but then I have to put beta.pdf_tex in the same folder as the tex file.

A: I had forgot the semicolon (:) and the trailing / for the absolute path.
The relative path uses \subimport and needs to start with ./ and end with a trailing forward slash.
\documentclass{report}

\usepackage{import}

\begin{document}

    \import{C:/tex/proj/pic/alpha/}{beta.pdf_tex}% Absolute path
    \subimport{./pic/alpha/}{beta.pdf_tex}% Relative path

\end{document}

Edit:
Observe that the backward slashes used in Windows ( c:\tex\proj\pic\alpha ) turns into forward slashes. I would avoid using spaces in folder names but if you have to I would try replacing the space with an asterisk (*) in the path used in (La)TeX. Another alternative is to use MS-DOS 8.3 file name format. If the 8.3 file name format gets you in trouble with tilde (~) you might need to replace for example ~1 with \string~1. The 8.3 format can be seen by using dir /X in cmd (Win+R).


text:
Q: Is in MVC ASP.NET, MVC the Presentation part of a Layered Design and should it be Loosely coupled? I saw some people arguing that MVC is different as an Layered design. I wonder if this is true. If you look at the BlipAjax sample on GitHub you can see that the website Blip.Web has the MVC structure, but thats only a part of the whole application. To be a complete application you need more. The more comes from the Blip.Data, for the repositories and the Blip.Entities for the Classes. The whole is a layered design.
So if you look how a layered design can be composed then you have :

*

*BlipAjax.Web as Presentation layer (with MVC),

*BlipAjax.Data as Business Layer (with EF Code first),

*BlipAjax.Enties as Model Layer (with EF-POCOs with annotations).

A problem that I have with Fowler is how do I use the "Model" layer in the Web application?

The Duwamish Architecture Diagram is very old but still very valid. Lots of Architecture images like Fowler are missing to much information. In this Diagram you can see that "Common" is something like a "Model". The "Model" can comunnicatie with different layers and not only with one like Fowler. The "loosely coupled" Diagram seems to be a good fit for MVC.

So is a Loosely Coupled Architecture the Answer of it?


text:
Q: Codeigniter select SUM give mysqld cpu high I'm still facing issue with calculating total sum amount of transaction, while it return the total sum it keep cpu high.
Cpu usage
Model class code
public function get_topup_sender_balance()
{

$this->db->select('SUM(total) as total');
$this->db->from('transactions');
$array = array('sender' => $this->session->id, 'status' => 'Processed', 'payment_type' => 'Topup', 'payment_method' => 'BalanceTopup');
$this->db->where($array);
$this->db->group_by('id');
$res = $this->db->get();
if($res->num_rows() > 0)
{
    return round($res->result(),2);
}else{
     return '0';
}

}
Helper custom library
public function transaction_balance() {

    $sender_topup = $this->CI->myac_model->get_topup_sender_balance();
    return number_format($sender_topup, 2, '.', '');
}

On Controller class and views page i call $this->helper_api->transaction_balance() to get customer balance and is return well balance but mysqld cpu will be high
And on mysql logs i get
# Query_time: 0.353698  Lock_time: 0.000111 Rows_sent: 0  Rows_examined: 484565
SET timestamp=1543791344;
SELECT SUM(total) as total
FROM `transactions`
WHERE `sender` = '4'
AND `status` = 'Processed'
AND `payment_type` = 'Topup'
AND `payment_method` = 'BalanceTopup'
GROUP BY `id`;

Any solution/idea to solve this pleases.


text:
Q: Android, how do can I get a list of all files in a folder? I need the name (String) of all files in res/raw/
I tried:
File f = new File("/");
String[] someFiles = f.list();

It looks like the root directory is the root of the android emulator...and not my computers root directory. That makes enough sense, but doesn't really help me find out where the raw folder exists.
Update: Thanks for all the great replies. It appears that some of these are working, but only getting me half way. Perhaps a more detailed description will aid
I want to get all the mp3 files in the raw folder so I can get all the names, then add them to a URI to play a random MP3 in the following way...
String uriStr = "android.resource://"+ "com.example.phone"+ "/" + "raw/dennis";
Uri uri = Uri.parse(uriStr);
singletonMediaPlayer = MediaPlayer.create(c, uri);

When I put "dennis.mp3" into the assets folder, it does show up as expected, however, using the above code, I can't access that MP3 anymore, unless there is something along the line of:
String uriStr = "android.assets://"+ "com.example.phone"+ "/" + "dennis";
Uri uri = Uri.parse(uriStr);

A: To list all the names of your raw assets, which are basically the filenames with the extensions stripped off, you can do this:
public void listRaw(){
    Field[] fields=R.raw.class.getFields();
    for(int count=0; count < fields.length; count++){
        Log.i("Raw Asset: ", fields[count].getName());
    }
}

Since the actual files aren't just sitting on the filesystem once they're on the phone, the name is irrelevant, and you'll need to refer to them by the integer assigned to that resource name. In the above example, you could get this integer thus:
int resourceID=fields[count].getInt(fields[count]);

This is the same int which you'd get by referring to R.raw.whateveryounamedtheresource

A:
I need the name (String) of all files in res/raw/

There are no files in res/raw/ on the device. Those are resources. There is no good way to iterate over resources, other than by using reflection to iterate over the static data members of the R.raw class to get the various ID names and values.

but doesn't really help me find out where the raw folder exists.

As a folder, it only exists on your development machine. It is not a folder on the device.

A: You can use AssetManager:
As far as I can remember, you will have list with (just try different paths):
final String[] allFilesInPackage = getContext().getResources().getAssets().list("");

A: Look at http://developer.android.com/reference/android/content/res/Resources.html
You can generally acquire the Resources instance associated with your application with getResources().
Resources class provides access to http://developer.android.com/reference/android/content/res/AssetManager.html (see to getAssets() method).
And finally obtain access to your packaged (apk) files with AssetManager.list() method.
Enjoy!

A: This code will retrieve all the files from 'New Foder' of sdCard.
    File sdCardRoot = Environment.getExternalStorageDirectory();
    File yourDir = new File(sdCardRoot, "New Folder");
    for (File f : yourDir.listFiles()) {
        if (f.isFile())
        {
           String name = f.getName();
           Log.i("file names", name);

        }

     }

and also make sure to add android sd card write permission in your manifest.xml file

A: From a Context, you can call something like this:
getResources().getAssets().list("thePath");

link to documentation


text:
Q: WebBrowser font size in pixels I am trying to set the font size in C# WebBrowswer in pixels.
I tried:
webBrowser1.Document.Write(@"TEXT ");

but the number before "px" doesn't seem to have any affect.
What am I doing wrong?
Edit:
Whole function:
private void Form1_Load(object sender, EventArgs e)
{
    webBrowser1.Navigate("about:blank");
    webBrowser1.Document.Write("Big Red Writing!");
}

Update:
I tested the exe file on another pc and it worked properly. But here, even ... doesn't work. All give the same size.
Any ideas?

A: Try terminated quotes (\") without using string literal. I have tried this and works 100%:
webBrowser1.Document.Write("Big Red Writing!");

A: You can try this :
webBrowser1.Navigate("about:blank");
HtmlDocument objHtmlDoc = this.webBrowser1.Document;
objHtmlDoc.Write("TEXT ");

A: I thought about resetting the Internet explorer settings using this fix:
http://support.microsoft.com/kb/923737
and the problem was solved.


text:
Q: Spark Select with a List of Columns Scala I am trying to find a good way of doing a spark select with a List[Column, I am exploding a column than passing back all the columns I am interested in with my exploded column.
var columns = getColumns(x) // Returns a List[Column]
tempDf.select(columns)   //trying to get

Trying to find a good way of doing this I know, if it were a string I could do something like
val result = dataframe.select(columnNames.head, columnNames.tail: _*)

A: For spark 2.0 seems that you have two options. Both depends on how you manage your columns (Strings or Columns).
Spark code (spark-sql_2.11/org/apache/spark/sql/Dataset.scala):
def select(cols: Column*): DataFrame = withPlan {
  Project(cols.map(_.named), logicalPlan)
}

def select(col: String, cols: String*): DataFrame = select((col +: cols).map(Column(_)) : _*)

You can see how internally spark is converting your head & tail to a list of Columns to call again Select.
So, in that case if you want a clear code I will recommend:
If columns: List[String]:
import org.apache.spark.sql.functions.col
df.select(columns.map(col): _*)

Otherwise, if columns: List[Columns]:
df.select(columns: _*)


text:
Q: Python: how to format facebook date (ISO 8601) in jinja2? While creating flask app to show facebook events data I've encountered a problem with event['start_time'] (facebook-graph-api) object formatting. When trying to format object in jinja placeholder in my index.html file I get an error: jinja2.exceptions.UndefinedError: 'datetime' is undefined. Libraries imported in app.py)
What I've already tried was formatting event['start_date'] in app.py and pasting it to render_template which formatted the date correctly but printed only first input under every event in flask for loop.
Also looking for other solutions I was trying to use dateutil.parser.parse on event['start_time']  filter with similar to first error- dateutil is undefined. Using strftime on event['start_time'] and applying filter based on strftime gave me an error 'str object' has no attribute 'strftime'.
So it looks like I'm not getting those libraries from app.py in jinja or it has something to do with event['start_time'] format.
Thank you in advance for any clues :)
app.py:
from flask import Flask, render_template
import json
import facebook
import datetime
from time import strptime, strftime

# Configure application
app = Flask(__name__)

@app.route("/")
def home():
token = {"EAAFKVKHsjTsBAFvCVusn4Drd2l5BFfJKJKhoQRgW623E96lxekibwJLMIlSXIUl2IUhZAevlnfK7T2NZBMMW7Lil0ZCGxlUlnerEyoGvG5iipMO2JDbmJJyfad39yIjDDeBBul5d6ehWLE8byiCQPTjmxr5ZBAIZD"}

graph = facebook.GraphAPI(token)
events = graph.get_connections(id="me", connection_name="events", fields="id, name, place, start_time, cover")

return render_template("index.html", events=events)

index.html:
{% block body %}
{% for event in events['data'] recursive %}

{{ event['name'] }}, {{ event['place']['name'] }}

{{ datetime.datetime.strptime(event['start_time'],'%Y-%m-%dT%H:%M:%S+0200').strftime("%d.%m.%Y, %H:%M") }}

{% endfor %}
{% endblock %}

Expected result is date formatted in flask loop according to chosen format (for example %d.%m.%Y, %H:%M) instead of ISO format.


text:
Q: My network icon is always a question mark and I can't access internet on any network lspci -knn grep - i net -A3
O2:OO.O Ethernet controller [0200]: Realtek Semiconductor Ca., Ltd. RTL8111/8168
/8411 PCI Express Gigabit Ethernet Controller [10ec:8168] (rev 15)
        Subsystem: Hewlett-Packard Company RTL8111/8168/8411 PCI Express Gigabit
 Ethernet Controller [103c:8331]
        Kernel driver in use: r8169
        Kernel modules: r8169
03:OO.O Network controller [0280]: Intel Corporation Device [8086:24fb] (rev 10)
        Subsystem: Intel Corporation Device [8086:2110]
        Kernel driver in use: iwlwifi
        Kernel modules: iwlwifi

Screen

Screen2

I'm typing this from my desktop PC Windows OS. My laptop runs Ubuntu and until just recently I've tried to connect to my school network, but gave up since nothing worked.
RFKILL list
0: Phy8: Wireless LAN
         Soft Blocked:no
         Hard blocked:no
1: hci0:Bluetooth
Soft Blocked: no
RFKILL list

0: phy0: Wireless LAN
Soft blocked: no
hard blocked: no
1:hci0: Bluetooth
Soft blocked: no
Hard blocked :no

I've never been able to use any networks. I can connect to them but I can't do anything. And my internet icon in the top right is just a question mark.
What can I try?

A: Based on the content of your chat session you should revert the /etc/network interfaces file that you edited to it's default content:
# interfaces(5) file used by ifup(8) and ifdown(8)
auto lo
iface lo inet loopback

According to the info in your question, there's no issue with the kernel drivers in use and both the wired and wireless connections are properly recognized. Your wireless interface is not blocked so this should resolve your issue. If not, drop me a comment and I'll expand my answer as necessary.


text:
Q: TypeScript best way to restore prototype chain? (Node.js) I have questions about the Object.setPrototypeOf(this, new.target.prototype) function because of this MDN warning:

Warning: Changing the [[Prototype]] of an object is, by the nature of how modern JavaScript engines optimize property accesses, currently a very slow operation in every browser and JavaScript engine. In addition, the effects of altering inheritance are subtle and far-flung, and are not limited to simply the time spent in the Object.setPrototypeOf(...) statement, but may extend to any code that has access to any object whose [[Prototype]] has been altered.

Because this feature is a part of the language, it is still the burden on engine developers to implement that feature performantly (ideally). Until engine developers address this issue, if you are concerned about performance, you should avoid setting the [[Prototype]] of an object. Instead, create a new object with the desired [[Prototype]] using Object.create().

So what would be the best way to restore the prototype string in TypeScript (Node.js) without using Object.setPrototypeOf(this, new.target.prototype) (but using classes)? This is all because of an error management middleware implemented in Express, in which I need to make use of instanceof to determine the origin of the error and thus return a proper response, but whenever I make a class that extends from Error, the error instanceof Error returns true, but error instanceof CustomError returns false. Doing a little research I found this in the official TypeScript documentation:

The new.target meta-property is new syntax introduced in ES2015. When an instance of a constructor is created via new, the value of new.target is set to be a reference to the constructor function initially used to allocate the instance. If a function is called rather than constructed via new, new.target is set to undefined.

new.target comes in handy when Object.setPrototypeOf or proto needs to be set in a class constructor. One such use case is inheriting from Error in NodeJS v4 and higher

// Example

class CustomError extends Error {
    constructor(message?: string) {
        super(message); // 'Error' breaks prototype chain here
        Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain
    }
}

// Results

var CustomError = (function (_super) {
  __extends(CustomError, _super);
  function CustomError() {
    var _newTarget = this.constructor;
    var _this = _super.apply(this, arguments);  // 'Error' breaks prototype chain here
    _this.__proto__ = _newTarget.prototype; // restore prototype chain
    return _this;
  }
  return CustomError;
})(Error);

And I thought okay everything is perfect since the code at the moment of being converted, I suppose that the compiler will take care of that function that is slow and will replace it with another procedure that is more efficient, but to my surprise it's not like that and I'm a little worried about the performance (I'm working on a big project).
I'm using TypeScript version 3.9.6 in Node 14.5.0, these are screenshots of the tests I did:
TypeScript with Node
TypeScript Playground
TypeScript compiler results


text:
Q: How to switch language in qt virtual keyboard in my application qml page? I have a Qt app on ARM board and because of touch I/O I should use the virtual keyboard. I have had config it and set English and Persian languages. Now I have a problem, I want to use just English for integer value, I can show the numbers in virtual keyboard but if the user has set the language to Persian, my text input set to Persian number. But I want all numbers in English format.(like the IP is in English format)
So, how to change the language for virtual keyboard when user just put integer value?


text:
Q: Selecting column names that have specified value We are receiving rather large files, of which we have no control over the format of, that are being bulk-loaded into a SQL Server table via SSIS to be later imported into our internal structure. These files can contain over 800 columns, and often the column names are not immediately recognizable.
As a result, we have a large table that represents the contents of the file with over 800 Varchar columns.
The problem is: I know what specific values I'm looking for in this data, but I do not know what column contains it.  And eyeballing the data to find said column is neither efficient nor ideal.
My question is: is it at all possible to search a table by some value N and return the column names that have that value? I'd post some code that I've tried, but I really don't  know where to start on this one... or if it's even possible.
For example:
A   B   C   D   E   F   G   H   I   J   K   L   M   N   ...
------------------------------------------------------------
'a' 'a' 'a' 'a' 'a' 'b' 'a' 'a' 'a' 'b' 'b' 'a' 'a' 'c' ...

If I were to search this table for the value 'b', I would want to get back the following results:
Columns
---------
F
J
K

Is something like this possible to do?

A: This script will search all tables and all string columns for a specific string.  You might be able to adapt this for your needs:
DECLARE @tableName sysname
DECLARE @columnName sysname
DECLARE @value varchar(100)
DECLARE @sql varchar(2000)
DECLARE @sqlPreamble varchar(100)

SET @value = 'EDUQ4' -- *** Set this to the value you're searching for *** --

SET @sqlPreamble = 'IF EXISTS (SELECT 1 FROM '

DECLARE theTableCursor CURSOR FAST_FORWARD FOR
    SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES
     WHERE TABLE_SCHEMA = 'dbo' AND TABLE_TYPE = 'BASE TABLE'
       AND TABLE_NAME NOT LIKE '%temp%' AND TABLE_NAME != 'dtproperties' AND TABLE_NAME != 'sysdiagrams'
     ORDER BY TABLE_NAME

OPEN theTableCursor
FETCH NEXT FROM theTableCursor INTO @tableName

WHILE @@FETCH_STATUS = 0 -- spin through Table entries
BEGIN
    DECLARE theColumnCursor CURSOR FAST_FORWARD FOR
        SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
         WHERE TABLE_NAME = @tableName AND (DATA_TYPE = 'nvarchar' OR DATA_TYPE = 'varchar')
         ORDER BY ORDINAL_POSITION

    OPEN theColumnCursor
    FETCH NEXT FROM theColumnCursor INTO @columnName

    WHILE @@FETCH_STATUS = 0 -- spin through Column entries
    BEGIN
        SET @sql = @tableName + ' WHERE ' + @columnName + ' LIKE ''' + @value +
                   ''') PRINT ''Value found in Table: ' + @tableName + ', Column: ' +  @columnName + ''''
        EXEC (@sqlPreamble + @sql)
        FETCH NEXT FROM theColumnCursor INTO @columnName
    END
    CLOSE theColumnCursor
    DEALLOCATE theColumnCursor

    FETCH NEXT FROM theTableCursor INTO @tableName
END
CLOSE theTableCursor
DEALLOCATE theTableCursor

A: One option you have is to be a little creative using XML in SQL Server.
Turn a row at a time into XML using cross apply and query for the nodes that has a certain value in a second cross apply.
Finally you output the distinct list of node names.
declare @Value nvarchar(max)

set @Value= 'b'

select distinct T3.X.value('local-name(.)', 'nvarchar(128)') as ColName
from YourTable as T1
  cross apply (select T1.* for xml path(''), type) as T2(X)
  cross apply T2.X.nodes('*[text() = sql:variable("@Value")]') as T3(X)

SQL Fiddle

A: If you have access to the files are RegEx will be must faster than performing a generic search in SQL.
If you are forced to use SQL @pmbAustin's answer is the way to go.  Be warned, it won't run quickly.


text:
Q: When describing something's colour, would you hyphenate the words? Eg, "blood-red" versus "royal blue" Generally, as a rule, I always hyphenate words to make them into a single adjective, so I've been putting "blood-red", "forest-green", "royal-blue" and the like, but the moment I typed "royal-blue", my instincts kicked in.
It didn't look right to me. Perhaps it's because this is an official colour or the fact that the word "royal" is unrelated to blue, but I'm not sure.
What do you guys think?
P.S. I'm using British English, if that helps.

A: You would not use hyphens when the phrase is used as a noun:

Blood red had always been his favorite color.
  The flag had white lion on a field of forest green.
  The dress was a fine royal blue.

Generally, I'd recommend that you use hyphens when the phrase is used as an adjective (i.e. a compound modifier):

He drank the sweet, blood-red wine.
  The flag, forest-green and proud, was raised at noon.
  The royal-blue dress fitted her well.

However, if the color phrase is part of a larger adjectival phrase where the color phrase itself is being modified, leave the hyphens off:

Her extravagantly royal blue dress was a sight to behold.

There may be still be some disagreement on this, though, and there are no absolute rules that apply to all possible word combinations. You are free to use whatever form you feel is most natural and easy to understand.

A: As an add-on to the information in other answers, I would point out that color names that are made up of two colors can written with a hypen:
blue-green

NOUN A colour intermediate between blue and green; a pigment of this
colour.
ADJECTIVE Of a colour intermediate between blue and green. Lexico

A colour intermediate between blue and green; a pigment of this
colour.
1994   A. Theroux Primary Colors 4   The Greeks called the color
kyanos (hence 'cyan') while the Romans would call it caeruleus, a name
still used today for the artificial blue-green made from cobalt
stannate.
2006   L. Eiseman Color: Messages & Meanings 78/2   By tweaking a true
green to a blue green, an interesting new dimension is added. OED

Cool colors seem to recede from the eyes, which is why a dress in a
blue-green looks smaller than it actually is. Linda Przybyszewski; The Lost Art of Dress

It discharged itself by a small stream into another, into which a
number of large pines had been blown by a winter storm, or fallen from
some other cause: in this lake its colour was blue green. Angler
An; Salmonia

Some of these names may be more recent and may apply to specific points (values) in a color model (e.g., RGB or CMYK):
Wiki has entries for:

Red-violet is a deep tone of rosy magenta. Wiki

Red-purple is the color that is called Rojo-Purpura (the Spanish word for "red-purple") in the Guía de coloraciones (Guide to
colorations) by Rosa Gallego and Juan Carlos Sanz, a color dictionary
published in 2005 that is widely popular in the Hispanophone realm.
Although red-purple is a seldom used color name in English, in
Spanish it is regarded one of the major tones of purple. Wiki

Displayed at right is the web color "orange-red". It was formulated in
1987 as one of the X11 colors, which became known as the X11 web
colors after the invention of the World Wide Web in 1991.
At right is displayed the Crayola color "red-orange". It has been a
Crayola color since 1930. Wiki

There are also what are known as impossible colors "that do not appear in ordinary visual functioning," but which the eye (brain) can be "tricked" into seeing.  Two of those are yellow–blue and red-green. See the Wiki page for demonstrations. Wiki
We'd probably use terms like reddish orange, orangish red, and yellowish blue.

A: Some colors may be compound nouns, and wouldn't be hyphenated. "Blood red" isn't a color, but Forest Green is a color of green.
No?
He wore a blood-red tie.
Her car was British racing green.

A: Dashes (not hyphens) connect words when their separation would be ambiguous:
Green table eating parrot.
We know that tables do not eat parrots, but this would be clearer
Green table-eating parrot.
Or even
Green-table-eating parrot. (although I would go for a re-write at this point)
In short, anytime the association between words is ambiguous, use dashes.


text:
Q: script to save a .py into another directory within the file itself Let's say I create a file called file.py in a directory called directory1. When running file.py, is there a way I can have file.py save it's own script to another directory, say directory2, as a .txt file or a .py file?
Thank you!

A: generelly, if you're using an editor to write the code, you could just save it to another directory with different file extension.
But do I guess right that you want to get a backup in a different direcotry? It depends on your editor, most will do that nowadays.
But sure you can write something like this in your file which just copies it to a dir of your choice:
import os, shutil

if not os.access(dirname, os.F_OK):
    os.mkdir(dirname, 0o700)

shutil.copy(fname, dirname)

What this code does is, it first creates a directory if it doesn't exist, jet, and gives it read, write and execute permissions. Than it copies the content of fname, which contains the file name of the file itself and copies it to the directory you just created.
But why woul you copy the recent code you just wrote to a different location?
Edit:
For keeping track of your work, there are better ways to do that, for example version control systems like darcs, subversion (aka svn) or gitorious (which is mainly webbased). They save your work with different version numbers and you don't have to alter the file names each time you achieved a milestone. They help you opening up branches, join them later and keep your code executable if you choose to get an earlier version.
With:
fname = "work_today.txt"

you can save the code, even the very same code of the file it contains, to new file name.
you have to alter the filename correctly, cut off the extension and concatenate the new string. –


text:
Q: @Ajax.BeginForm request/response ok but controller does not redirec @using (Ajax.BeginForm("Login", "Account", "",
            new AjaxOptions { HttpMethod = "POST" },
            new { id = "loginForm", name = "loginForm" }))
{
 ...
}

This form perform a request and receive a response 200 OK. Debbuging I can see the response html but I don´t get redirected.
If I do it manually without using html helps I get successfully redirected to where I need to.
This is the controller:
//
    // POST: /Account/Login
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Login(LoginModel model)
    {
        MembershipProvider mp = Membership.Provider;
        bool isDigital = bool.Parse(Request.Form.GetValues("hasDigital")[0]);
        string certDBNumber;

        if (isDigital)
        {
            /*** Retira só o que enteressa do Certificado.Subject (CPF/CNPJ)*/
            string code = Request.Form.GetValues("code")[0];
            string[] dataArray = code.Split(',');
            string data = dataArray.Last();
            string[] numberArr = data.Split(':');
            string number = numberArr.Last();

            /*** Resgata chave do usuário no banco ***/
            using (tgpwebgedEntities context = new tgpwebgedEntities())
            {
                var userObj = from u in context.aspnet_Users
                              where u.UserName == model.UserName
                              select u.UserId;
                Guid userID = userObj.First();
                var obj = from u in context.sistema_UsersCertified
                          where u.userID == userID select u.keyNumber;
                certDBNumber = obj.First();
            }

            //Verifica se usuário é credenciado
            if (number == certDBNumber) {
                FormsAuthentication.SetAuthCookie(model.UserName, false);
                return RedirectToAction("Index", "Home");
            }
        }//Login sem certificado digital
        else
        {
            if (ModelState.IsValid &&
                           mp.ValidateUser(model.UserName, model.Password))
            {
                FormsAuthentication.SetAuthCookie(model.UserName, false);
                return RedirectToAction("Index", "Home");
            }
        }
        /*** Se chegou até aqui algo deu errado. Mostra denovo o form ***/
        ModelState.AddModelError("", "Username ou Password incorreto!.");
        return View(model);
    }

Why this strange behavior?

A: As a result of this being an ajax post, you cannot redirect. An option would be to return a value such that the success function realized the redirection needed to take place, and then issued
if( someReturnedFlag == true ){
 window.location = redirectionUrl;//http://www.stackoverflow.com
}

Alternatively, you could make a redirection view
RedirectionView.cshtml
@{
 Layout = null;
}

And then return this view from your ajax post and it would redirect.

Edit
This got more attention than I expected, so I thought I would improve this answer a little bit with two more complete examples.

1: jQuery's ajax
view:
$.ajax({
        url: "@(Url.Action("TargetAction","TargetController"))",
        type: 'POST',
        data: $("#loginForm").serialize(),
        success: function (URL) {
         window.location = URL;
        }
});

controller:
public class TargetController: Controller
[HttpPost]
public string TargetAction(ViewModel model)
{
 //use model (note that the serialized form was bound to the model)
 return "http://www.stackoverflow.com";
}

2: RedirectionView.cshtml
main view:
@{
 AjaxOptions ajaxOpts = new AjaxOptions
 {
    UpdateTargetId = "redirectWhenDone"
 };
}

@using (Ajax.BeginForm("TargetAction", ajaxOpts))
{
 ...
}

RedirectionView.cshtml
@model string
@{
 Layout = null;
}

Controller
[HttpPost]
public ActionResult TargetAction(ViewModel vm)
{
 //use ViewModel

 ...

 //it is important to use an object here for the string
 object url = "http://www.stackoverflow.com";
 //otherwise the View() method will consider the string a parent location and look
 //for the RedirectionView in the wrong place (basically using the wrong overload)
 return View("RedirectionView", url );
}


text:
Q: How to Add a Computer or User to an OU in Group Policy Management Console (GPMC.msc) On my Windows 2008R2 domain controller, I am trying to add computer objects into an organization unit (OU) in GPMC - so that I could apply a group policy objects (GPO) to that OU.
In GMPC I have created an OU called NY_Computers. I wish to add to this OU the computer PC_WIN7 defined in AD (Active Directory) - but I am unable to do this.
Right-mouse clicking on the  NY_Computers OU will only allow me to create another sub-OU (no where can I create a new computer or user or group)
NB: I can do this in AD Users & Computers console - but then I am unable to create any GPO (withing AD Users & Computers)
Am I overlooking something obvious ?

A: No, you're not overlooking something. They're two different tools for doing two different things. Use ADUC for creating, modifying, etc. Users, Groups, OU's, etc. and use GPMC for creating, modifying, etc. Group Policy objects.
(You can use the GPMC to create, modify, etc. OU's, but just use ADUC for that).