text:
Q: Django Elasticsearch AWS httplib UnicodeDecodeError I'm trying to setup Elasticsearch with Django (without Haystack).
Everything works perfectly locally.
But when I try to use the elasticsearch-py  client with IAM based authentication on AWS I get this error :
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 827, in _send_output
msg += message_body
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position132: ordinal not in range(128)

I tried to use aws-es-connection and requests-aws4auth but I get the same error.
It only works when I allow open access on AWS and use only elasticsearch-py like so
from elasticsearch import Elasticsearch, RequestsHttpConnection
ES_CLIENT = Elasticsearch(
    ['search-domain-xxx.us-east-1.es.amazonaws.com'],
connection_class=RequestsHttpConnection
)

But I want something more secure ...
I think it is a utf-8/unicode/str problem but I can't manage to resolve it :(

A: I finally manage to fix the bug by using a custom serializer :
from elasticsearch import Elasticsearch, RequestsHttpConnection, serializer, compat, exceptions

class JSONSerializerPython2(serializer.JSONSerializer):
"""Override elasticsearch library serializer to ensure it encodes utf characters during json dump.
See original at: https://github.com/elastic/elasticsearch-py/blob/master/elasticsearch/serializer.py#L42
A description of how ensure_ascii encodes unicode characters to ensure they can be sent across the wire
as ascii can be found here: https://docs.python.org/2/library/json.html#basic-usage
"""
def dumps(self, data):
    # don't serialize strings
    if isinstance(data, compat.string_types):
        return data
    try:
        return json.dumps(data, default=self.default, ensure_ascii=True)
    except (ValueError, TypeError) as e:
        raise exceptions.SerializationError(data, e)

and then pass the serializer to elasticsearch
from elasticsearch import Elasticsearch
es = Elasticsearch(..., serializer=JSONSerializerPython2())

I found the solution here

A: If someone can find the reason behind this error, I would be immensely grateful. Things I have tried with no luck:

*

*encode things to 'utf-8' before writing (result: no errors thrown, es index not even created)

*something like the code-snippet below (result: no errors thrown, es index not even created)
def convert_unicode_to_str(item):
    if isinstance(item, basestring):
        return str(item)
    .....
    .....

[Note: This is a bit of a hack, but it gets the job done]
So, sys.setdefaultencoding(..) is not available in the sys module's namespace. This is solved by calling the reload function on sys.
Now, prior to writing to ES, setting the default encoding to 'utf-8' solves this problem. Just to be sure that nothing else breaks as a result of this, I think it is a good idea to reset the default encoding to what it was before the switch.
reload(sys)

# keep track of what the old encoding was
old_encoding = sys.getdefaultencoding()

# set the default encoding to `itf-8`
sys.setdefaultencoding('utf-8')

#################
## write to es ##
#################

# reset the state of the world to what it was
sys.setdefaultencoding(old_encoding)

A: extending Debosmit Ray's solution for django-haystack.
add to search_indexes:
def set_default_utf8(method):
    """
    Set utf-8 as default encoding, perform `method`,
    then set the old encoding back.
    """
    def wrapper(*args, **kwargs):
        reload(sys)
        old_encoding = sys.getdefaultencoding()
        sys.setdefaultencoding('utf-8')

        result = method(*args, **kwargs)

        sys.setdefaultencoding(old_encoding)
        return result
    return wrapper

class EntryIndex(SearchIndex):
    text = CharField(document=True, use_template=True)
    ...

    @set_default_utf8
    def update(self, using=None):
        """Overrides entire index update to use UTF-8."""
        super(StreamEntryIndex, self).update(using)

    @set_default_utf8
    def update_object(self, instance, using=None, **kwargs):
        """Overrides index update for a single object using UTF-8."""
        super(StreamEntryIndex, self).update_object(instance, using, **kwargs)


text:
Q: GIMP - Something wrong with color? So I was trying to color in some lines and I picked a red to do so. When I tried to pick a black, instead of color over the red, it colored around the red, but would not color on the red. I can color over the red with lighter colors, but can not with darker. Please help?

A: Check the mode[1] of either the paint tool or the layer you are painting on. If it not Normal (for instance it could be in "Lighten only" mode) then unexpected things[2] can happen.
[1] Drop-down selector at the top of the Layers list for layers, or at the top of the Tool option dialog for paint tools
[2] if you don't know about layer/paint modes of course.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Flatten pandas df I am trying to flatten out a pandas df. For the df below I'm trying to move the names up in Column E and shift the other columns to the right.
import pandas as pd

d = ({
    'D' : ['08:00:00','X','08:10:00','X'],
    'H' : ['1','','1',''],
    'B' : ['Stop','X','Res','X'],
    'A' : ['X','','X',''],
    'C' : ['En','X','Se','X'],
    'E' : ['M','John','M','Gary'],
    'F' : ['Place','','Place',''],
    })

df = pd.DataFrame(data=d)

Output:
   A     B   C         D     E      F  H
0  X  Stop  En  08:00:00     M  Place  1
1        X   X         X  John
2  X   Res  Se  08:10:00     M  Place  1
3        X   X         X  Gary

Whereas my intended output is:
   A     B   C         D     E      F  G
0  X  Stop  En  08:00:00  John  Place  1
1  X   Res  Se  08:10:00  Gary  Place  1

I've have tried
df = pd.DataFrame(np.column_stack((df.iloc[::2], df.iloc[1::2, [0]])), columns=['A','B','C','D','E','F','G','H'])

But this drops the Names:
   A     B   C         D  E      F  G  H
0  X  Stop  En  08:00:00  M  Place  1
1  X   Res  Se  08:10:00  M  Place  1

A: Assumption: The rule of "every other row" seen in example holds for the entire dataset
df2 = df[df.columns[:4]].iloc[::2].reset_index(drop=True)
df3 = df[df.columns[4]].iloc[1::2].reset_index(drop=True)
df4 = df[df.columns[5:]].iloc[::2].reset_index(drop=True)
pd.concat([df2, df3, df4], axis=1)

A: [Newbie here too]hm....I am sure there is a better and scalable implementation out for this usecase. However, I got this hack to solve this specific requirement
q = df.drop(index=[1,3],inplace=True)
s = df['E'].values.reshape(-1,2)
w =pd.DataFrame(s)
pd.concat([q,w],axis=1)

A: Here's a way replace X,M,'' with np.nan,sort the values and dropna i.e
c = ['B','C','D','E']

to_ex = ['X','M']
di = dict(zip(to_ex,[pd.np.nan]*len(to_ex)))

df[c] = df[c].replace(di)

df = df.replace('',pd.np.nan)

df = df.apply( sorted,key=pd.isnull).dropna()

    A   B   C      D       E      F    H
0  X  Stop  En  08:00:00  John  Place  1
1  X   Res  Se  08:10:00  Gary  Place  1

If you want to remove every second row perhaps the solution is simple i.e
df['E'] = df['E'].shift(-1)
df = df.loc[0::2]

A: Here's one way to do it:
df = df.reindex(sorted(df.columns), axis=1)

sliced = df[::2].copy()

# creating a slot for the 'E' column
sliced.rename(columns={'E': 'F', 'F': 'G'}, inplace=True)
sliced['E'] = df[1::2]['E'].values

sliced = sliced.reindex(sorted(sliced.columns), axis=1)

Output:
   A     B   C         D     E  F      G  H
0  X  Stop  En  08:00:00  John  M  Place  1
2  X   Res  Se  08:10:00  Gary  M  Place  1


text:
Q: unzip contents in-app purchase ios apple hosted contents are downloading as .zip in case of in-app purchase.
m trying to unzip these contents but filed to open .zip file with zipArchive.
ZipArchive* za = [[ZipArchive alloc] init];
za.delegate = self;
NSString *path = [download.contentURL path];
if([[NSFileManager defaultManager] fileExistsAtPath:path])
{
    NSLog(@"File Exists: %@", path);
}
else
{
    NSLog(@"file not exists: %@", path);
}

if( [za UnzipOpenFile:path] ) {
    if( [za UnzipFileTo:dir overWrite:YES] != NO )
    {
        NSLog(@"unzip data success");
        //unzip data success
        //do something
    }
    else
    {
        NSLog(@"unzip failed");
    }

    [za UnzipCloseFile];
}
else
{
    NSLog(@"unzip can't open file");
}

output is
File Exists:....path..
unzip cant open file
Rather its working fine if I bundle a .zip file own
path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"module.zip"];

ZipArchive* za = [[ZipArchive alloc] init];
za.delegate = self;
if([[NSFileManager defaultManager] fileExistsAtPath:path])
{
    NSLog(@"File Exists: %@", path);
}
else
{
    NSLog(@"file not exists: %@", path);
}

if( [za UnzipOpenFile:path] ) {
    if( [za UnzipFileTo:dir overWrite:YES] != NO )
    {
        NSLog(@"unzip data success");
        //unzip data success
        //do something
    }
    else
    {
        NSLog(@"unzip failed");
    }

    [za UnzipCloseFile];
}
else
{
    NSLog(@"unzip can't open file");
}

here out put is
File Exists: /var/mobile/Applications/B22970ED-D30A-460A-A0A1-C8458795C370/myApp.app/module.zip

myApp[615:907] 63 entries in the zip file
2013-10-29 18:39:46.012 myApp[615:907] unzip data success

A: Do not try to unzip package. This is just a folder. You can look at the content using this code:
NSArray *tempArrayForContentsOfDirectory =[[NSFileManager defaultManager] contentsOfDirectoryAtPath:[download.contentURL path] error:&error];


text:
Q: Outlook Not Running Visual Basic After Restart So I have created a visual basic script in outlook that creates a random signature by pulling from Git.
The script works correctly but whenever I restart my machine the script doesn't run at all.
I fixed the issue by going to
"File"->"Options"->"Trust Center"->"Trust Center Settings..."->"Macro Settings"->"Enable all macros"

This let the VBA code work whenever I opened and closed Outlook but is there a better way to have the code work whenever I reopen Outlook or restart my machine.
I have tried to use
Private Sub Application_Startup()

    MsgBox "Hi"

End Sub

While that code did work when I first put it in, whenever I restarted outlook it said it couldn't run because "Macros were disabled"
Here is my code for the random signature, anyway to have this work whenever I restart outlook or my machine? Or is the macro setting I edited the correct way to go?
Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)

' Validate that the item sent is an email.
    If Item.Class <> olMail Then Exit Sub

'These first variables is to find the file the .bat file created within the AppData folder
'Set enviro to %APPDATA%
    Dim enviro As String
    enviro = CStr(Environ("APPDATA"))
'Create a new variable that sets the file path for the RepoDir.txt
    RepoPath = enviro & "\RepoDir.txt"

'Create a new variable to grab the line of text in RepoDir.txt
    Dim RepoFilePath As String
    Dim strFirstLine As String

'The new variable calls the RepoPath Variable, opens it and reads the first line of the file and copies it into a variable
    RepoFilePath = RepoPath
    Open RepoFilePath For Input As #1
    Line Input #1, strFirstLine
    Close #1

'The script runs a Shell command that opens the command line, cds to the Repo path within the str variable, does a git pull, and outputs the error level to a file in the temp directory
    Shell ("cmd /c cd " & strFirstLine & " & git pull RandomSig & echo %ERRORLEVEL% > %TEMP%\gitPull.txt 2>&1")

'These second set of variables is to find the file the Shell command created within the TEMP folder
'Set enviro to %TEMP%
    Dim Gitenviro As String
    Gitenviro = CStr(Environ("TEMP"))
'Create a new variable that sets the file path for the RepoDir.txt
    PullResult = Gitenviro & "\gitPull.txt"

'Create a new variable to grab the line of text in RepoDir.txt
    Dim GitFilePath As String
    Dim GitFirstLine As String

'The new variable calls the PullResult Variable, opens it and reads the first line of the file and copies it into a variable
    GitFilePath = PullResult
    Open GitFilePath For Input As #2
    Line Input #2, GitFirstLine
    Close #2
    'MsgBox (GitFirstLine)

'The variable is checked to see if it does not equal 0, and if it doesn't the message is cancelled
    If GitFirstLine <> 0 Then
        MsgBox "There was an error when attempting to do the Git Pull, cancelling message"
        Cancel = True
    End If

    Const SearchString = "%Random_Line%"
    Dim QuotesFile As String

    QuotesFile = strFirstLine & "quotes.txt"

    If InStr(Item.Body, SearchString) Then
        If FileOrDirExists(QuotesFile) = False Then
            MsgBox ("Quotes file wasn't found! Canceling message")
            Cancel = True
        Else
            Dim lines() As String
            Dim numLines As Integer
            numLines = 0

        ' Open the file for reading
            Open QuotesFile For Input As #1

        ' Go over each line in the file and save it in the array + count it
            Do Until EOF(1)
                ReDim Preserve lines(numLines + 1)
                Line Input #1, lines(numLines)
                numLines = numLines + 1
            Loop

            Close #1

        ' Get the random line number
            Dim randLine As Integer
            randLine = Int(numLines * Rnd()) + 1

        ' Insert the random quote
            Item.HTMLBody = Replace(Item.HTMLBody, SearchString, lines(randLine))
            Item.HTMLBody = Replace(Item.HTMLBody, "%Random_Num%", randLine)
        End If
    End If
    End Sub

    Function FileOrDirExists(PathName As String)
    Dim iTemp As Integer

    On Error Resume Next
    iTemp = GetAttr(PathName)

    Select Case Err.Number
    Case Is = 0
        FileOrDirExists = True
    Case Else
        FileOrDirExists = False
    End Select

    On Error GoTo 0
End Function

A: It's highly recommended to leave your macro security setting to only allow self-sign certificate Macros,

Do not use the Low option or run all

Create a self-signing certificate

*

*Go to Start > All Programs > Microsoft Office > Microsoft Office Tools, and then click Digital Certificate for VBA Projects.

*In the Your certificate's name box, type in name for the certificate.

*Click OK. then SelfCert Success message will appears, click OK.

*Go to Developer tab > click Visual Basic. or ALT+F11

*In Visual Basic Editor, go to Tools > Digital Signature.

*Digital Signature dialog appears and click on Choose and  you'll get a screen to select a certificate. Now you can choose the certificate you just created.

Edit
locating SelfCert.exe
Go to Start menu and typing VBA should bring up the SelfCert.exe.

Alternative method of locating SelfCert.exe
if you Can't find it in the Start Menu? then By default you can find SelfCert.exe in the following location
Windows 32-bit
C:\Program Files\Microsoft Office\Office <version number>
Windows 64-bit with Office 32-bit
C:\Program Files (x86)\Microsoft Office\Office <version number>
Windows 64-bit with Office 64-bit
C:\Program Files\Microsoft Office\Office <version number>
Office 365 (Subscription based or Click-to-Run version of Office 2013)
C:\Program Files\Microsoft Office 15\root\office15
If SelfCert.exe is not installed
Then run Office setup and choose Add or Remove Features.
With older versions of Office you'll need to choose Custom installation and then Advanced customization.
Expand the Office Shared Features section and select Digital Certificate for VBA Projects to run from your computer.
Simply run SelfCert.exe after locating it.


text:
Q: Form validations (Server Side) examples in ZK MVVM Can you please explain how to do form validations on the server side using the MVVM approach. I tried it but could not do it effectively. I have done small validations on the client side using intbox etc.
But I want to do validations like:

*

*The value of an attribute should not exceed say 100.

*If value of attribute A is filled by the user then attribute B becomes mandatory and like that.

*If value of attribute A is 100 and B is 50 then value of attribute C becomes mandatory and cannot exceed 150

I am not able to figure out a way of doing it in MVVM. I am using ZK CE 6.0.0 version.
I tried the code mentioned below:
Validation.zul
<zk>
    <window title="Validation" border="normal"
        apply="org.zkoss.bind.BindComposer" id="validtionWin"
        viewModel="@id('vm') @init('com.nagarro.validator.CustomValidator')">
        <intbox
            value="@save(vm.quantity) @validator(vm.rangeValidator)" />

        <button label="Submit"></button>
    </window>
</zk>

ViewModel
CustomValidator.java
import org.zkoss.bind.ValidationContext;
import org.zkoss.bind.Validator;
import org.zkoss.bind.validator.AbstractValidator;

public class CustomValidator implements Validator{

    private Validator rangeValidator;

    private String quantity;

    /**
     * @return the quantity
     */
    public String getQuantity() {
        return quantity;
    }

    /**
     * @param quantity
     *            the quantity to set
     */
    public void setQuantity(String quantity) {
        this.quantity = quantity;
    }
    @Override
    public void validate(ValidationContext ctx) {

    }

    /**
     * @return the rangeValidator
     */
    public Validator getRangeValidator() {
        return new AbstractValidator() {
            public void validate(ValidationContext ctx) {
                Integer val = (Integer)ctx.getProperty().getValue();
                if(val<10 || val>100){
                    addInvalidMessage(ctx, "value must not < 10 or > 100, but is "+val);
                }
            }
        };
    }

    /**
     * @param rangeValidator the rangeValidator to set
     */
    public void setRangeValidator(Validator rangeValidator) {
        this.rangeValidator = rangeValidator;
    }

}

Please figure out the mistake in the above code. :)
I get the following WARNING when I run the above code.
Jan 16, 2013 4:58:07 PM org.zkoss.bind.validator.AbstractValidator
addInvalidMessages:84 WARNING: ValidationMessages not found on binder
org.zkoss.bind.AnnotateBinder@cf7fda, please init it

How should I set the validation Message Please Help. :)

A: Check out this or use constraints for InputElements.
If you need more details or have problems, please provide some code.
Edit
You are missing
validationMessages="@id('vmsgs')

at your Window.
Please read this to understand.


text:
Q: Multiple form submission using ajax-django I wanted to submit multiple forms using ajax.
actually I was trying to build a single page with the Name of the existing users in my DB
with a option to send a friend request (here name is taken as a input just for example) .
so obviously the page cannot be refreshed after each request sent.
I am using django. and after searching i found a way to submit a single form not multiple.
this is the code.
can someone help me?
 <form id="{{user.id}}" > {% csrf_token %}
        name:<input type="text" id="name{{user.id}}"><br>
        <input type="submit" value="Send Request">
    </form>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script type='text/javascript'>
        $(document).on('submit','#{{user.id}}',function(e){
            e.preventDefault();
            $.ajax({
                type:'POST',
                url:'',
                data:{
                    name:$('#name{{user.id}}').val(),
                    csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
                },
                success:function(){
                    alert("this is the user id{{user.id}}")
                }
            });
        })
    </script>

even if I pass different user id from the views..and loop through it.its still not happening.
Thanks


text:
Q: Array.prototype.indexOf being added to end of arrays in IE8 I know IE8 and earlier doesn't have an indexOf function. I'm defining it as follows:
if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(obj, start) {
         for (var i = (start || 0), j = this.length; i < j; i++) {
             if (this[i] === obj) { return i; }
         }
         return -1;
    }
}

I can correctly get the index of values in an array, but the function is being added to the end of my arrays when using IE8 and earlier. Therefore, I'm getting things like:
obj.obj2[0] = 'data'
obj.obj2[1] = 'other data'
obj.obj2['indexOf'] = [definition of indexOf function]

Not surprisingly, this is breaking everything else on the site. Problem isn't happening in IE10 or 9.  Any and all help is appreciated.

A: It is added to the prototype, so everytime you treat your array like an object (for..in loop is one example), it will show up. It does not show up in other browsers because they already have the indexOf method by default, so you're not modifying the prototype.
You can use obj.hasOwnProperty(propertyName) to test whether a property is defined directly on your object (in this case, your array, which is an object basically) or somewhere else in the prototype chain.

A: Sounds like you might be doing something wrong when iterating through your arrays. I ran the following in IE8 and didn't get the behavior you mentioned:
if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(obj, start) {
         for (var i = (start || 0), j = this.length; i < j; i++) {
             if (this[i] === obj) { return i + " used prototype"; }
         }
         return -1;
    }
}

var myCars=new Array("Saab","Volvo","BMW");
document.write(myCars.indexOf("Volvo") + "

");

for (i = 0; i < myCars.length; i++)
    document.write(i + ": " + myCars[i] + "
");

output:
1 used prototype

0: Saab
1: Volvo
2: BMW

A: In the case when we use Array.prototype.someFunction,
to filter truly array's elements in IE 8, we can use:
for (var i = 0, len = myArray.length; i < len; i++) {
    if (typeof myArray[i] === "function") {break;}

    // some code for myArray trully elements
}

A: IE<9 doesn't have an .indexOf() function for Array, to define the exact spec version, run this before trying to use it:
if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length >>> 0;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

Reference


text:
Q: Regular expression to check the start with string than space than integer value and integer value should not be start with zero I just wanted to make the regular expression to check the given value
For example I need to check the below value in regular expression ,integer value should not start with zero and it could be any value but only it should not be start with zero, e.g.:
m=text 123034

I wanted to make sure that after space integer value should not start with a zero.

A: I have put a similar string "m=text 12345" in a file (file.txt), and launched following command:
grep "^[a-z]=[a-zA-Z]* [1-9][0-9]*" file.txt

Explanation:

*

*^ : beginning of line

*[a-z] : any letter from a to z

*[a-zA-Z]* : any letter, small of capital, for a number of times (can be 0)

*[1-9]     : the number should not start with a zero

*[0-9]*    : the rest of the number can contain zeroes


text:
Q: Does the Facebook Chat API support image (photo) attachments? I'm looking at potentially integrating my IM app with the Facebook Chat API. From the docs (https://developers.facebook.com/docs/chat/), it's not clear whether I can send and receive image/photo attachments. It looks like it wasn't doable as of a year ago (Sending photo in Facebook chat), but I'm hoping something has changed? Specifically:
(1) Can I use the Facebook Chat API to retrieve photos attached to incoming messages?
(2) Can I attach a photo to an outgoing message?
Thanks!


text:
Q: How i can read kafka offset per partition I can't for-loop read kafka per partition, I don't know what wrong in my code, it don't show the value that I print
example: i want to firsttime read all offset partition 0 and second read all offset partition 1.
(Firsttime for me post in stackoverflow. Sorry for commucation, I hope you understand me.)
    Consumer<String, String> consumer = new KafkaConsumer<>(props);
    consumer.subscribe(topicNames);
    List<KafkaTopicDataResponse> results = new ArrayList<>();

    try {
        Set<TopicPartition> assignments = consumer.assignment();
        Object[] assignArray = assignments.toArray();
        for (Object topicPartition : assignArray){
            boolean flag = true;
            int receiveRow = 0;
            while (true) {
                ConsumerRecords<String, String> records = consumer.poll(100);
                if (flag) {
                    consumer.seek((TopicPartition) topicPartition,0);
                    flag = false;
                }
                for (ConsumerRecord<String, String> record : records) {
                    receiveRow++;
                    System.out.printf("offset = %d, partition = %d, key = %s, value = %s%n", record.offset(), record.partition(), record.key(), record.value());
                    logger.info("count : "+ receiveRow);

                }
                if (receiveRow >= limitRow){
                    break;
                }

            }
        }
    } catch(Exception e) {
        logger.error("Exception occured while consuing messages",e);
    }finally {
        consumer.close();
    }

A:
I want to firsttime read all offset partition 0 and second read all
  offset partition 1.

You said, you want to read all offsets from partition 0 and then partition 1. How do you say all when the data is flowing i.e. new data keeps on arriving?
So when you say all it should be all data at a given instant of time. For this, you would need to assign the partitions one by one, get the end offsets at that instant of time and read them till that end offset.
consumer.assign(Collections.singletonList(new TopicPartition("topic", 0)));

and then you need to fetch the end offsets, because if data keeps on coming to this partition, this partition would never complete.
TopicPartition tp = new TopicPartition("topic", 0);
long endOffset = consumer.endOffsets(Collections.singletonList(tp)).get(tp);

Now, you have to call poll() and check if the last record is >= endOffset-1
flag = true;
while(flag) {
       ConsumerRecords records = consumer.poll(Duration.ofSeconds(10));
       for(ConsumerRecord record: records) {
          // process them
          if(record.offset() >= (endOffset-1)) {
             flag = false;
             break;
          }
       }
}

Repeat the same steps with other partitions also.


text:
Q: How to disable the refresh after show() Basic form of the code is given below that i want rectified. while running the code once it reaches .show() function the page is getting refreshed. I don't want that. Can you help me with this dilemma!!!!
Please see the code below :
Code:
$(document).ready(function() {
    $("#mandate").hide();
    $("#submit").click(function() {
        var password = $("#password").val();
        if(password=='') {
            $("#mandate").show();
        }
        else {
            alert("Form Submitted Successfully..!!");
        }
    }
}

HTML:

Password is mandatory*

A: Add return false; to your code.
$(document).ready(function() {
        $("#mandate").hide();
        $("#submit").click(function() {
        var password = $("#password").val();
        if(password=='') {
            $("#mandate").show();
            return false;
        }
        else
        {
        alert("Form Submitted Successfully..!!");
        }
});

The return false will return false to the event. That tells the browser to stop following events, like follow a link. It is similar to event.preventDefault()


text:
Q: Writing a temporary compiler to write a compiler in the new language What is the term used to refer to when you create a new language and write the compiler for that language, in a different one, then once the 'temporary' compiler is well-developed, rewrite it in the same language using that temporary compiler?

A: The term for that is "bootstrapping".

A: Q: "If one needs a compiler for language X to obtain a compiler for language X (which is written in language X), how did the first compiler get written?"
A: Bootstrapping

A: Once you get into the new language, its called "bootstrapping"
You don't need the temporary compiler to handle the whole language, just enough to let you get started with the first version of the real compiler. Then keep adding features and using them in the next rev.


text:
Q: Signal Detector (Field Strength Meter) Hello I have attached a circuit of a Field Strength Meter that I came up with, my target frequency is around 500Mhz.
I was wondering if a design like this will even be able to tune to 500Mhz.
I am also wondering if I can swap the Ammeter with a current amplifier and then connect that to an LED instead to show the presence of the target frequency.
If there is something horribly wrong with this idea, please do tell.

Picture of a transistor based current amplifier that I was going to connect instead of the Ammeter.

Note: sorry these are not BC547 transistors but 2N2222A

A: The thing that is horribly wrong that your transistors won't start conducting until the voltage at base reaches 1.3V. And that's a lot. You'll need to use either opamp with dual supply or a germanium transistor connected to a silicon one as a Sziklai pair.
EDIT: You can stay with your original circuit, just add some bias to the capacitor: connect the upper capacitor leg to the central point of a 10k:0.9k voltage divider, and connect the divider to +12 and ground.


text:
Q: Finding all urls in string including hyphens I am looking for regex that would find all of the following urls:
hello.com
hello1.com
1hello.com
hello-1.com
hello-hi1.com
1hello-hi.com
h3ll0.com
I have tried a few different Regexs but nothing seems to be quite right.
regex = re.compile('\w+\.(com|org|net)')
data = regex.search(string)
url = data.group(0)

I want it to return all of the above urls

A: You can add this part (-\w+)* in your regex which will allow it to have optional hyphen in the domain name part of your url. You can use this URL,
\w+(?:-\w+)*\.(?:com|org|net)
   ^^^^^^^^^ this allows the URL to have optional hyphen

Demo
You should make the group non-capture unless you really need them as it improves its performance.

A: Could try spliting the string by a '.' delimiter and then checking if the value is in a white list of say ['com', 'org', 'net', 'io' ....]
For example
whitelist = {'com', 'org', 'net', 'io'}
possible_url = 'hello.com'
if possible_url.split('.')[-1] in whitelist:
    return True

A: using a simple regex can cause you to accidentally match words. for example simply using [\w-]+\.(com|org|net) demo#1 would meet your requirements but would miss all the other domains, miss sub-domains and match normal words.
This regex might be better suited \b\w[-.\w]+\.(com|org|net)\b demo#2


text:
Q: Is the trivial representation a subrepresentation of a tensor power of any irreducible complex representation of a finite group? Let $G$ be a finite group,  $V$ an irreducible complex representation and $\mathbb{1}$ the trivial representation.
Question: $\exists n >0$ such that $\mathbb{1} \le V^{\otimes n}$?

A: Yes

*

*If $n := \dim V$, then $V^{\otimes n}$ contains the $1$-dimensional representation $\bigwedge^n V$ as a summand, so we may assume $\dim V = 1$.

*If $V$ is $1$-dimensional, it corresponds to a character $\chi: G\to {\mathbb C}^{\times}$, and since $G$ is finite, the $|G|$-th tensor power of $V$ will be trivial.

A: Yes, let $N\leq G$ be the kernel of the representation, so $V$ is a faithful $G/N$-module.
Now we know that there is an $n$ such that the trivial module is a $G/N$-submodule of $V^{\otimes n}$ (some number at most one less than the number of distinct values the character of $V$ takes will work). But now this $G/N$-submodule is also a $G$-submodule, and it is clearly still the trivial module.


text:
Q: Are there number-theoretic graphs that are far from being isomorphic I say that two graphs $G_1=(V_1,E_1)$, $G_2 = (V_2,E_2)$
with the same number of vertices, edges,
are $\epsilon$-far from being isomorphic, if for any bijection between $V_1$ and $V_2$, the fraction of
pairs $(x,y)$ for which $(x,y)\in E_2$ conditioned on $(x,y)\in E_1$
is at most $1-\epsilon$.
I am looking of for an infinite family of $\epsilon$-nonisomorphic graph pairs, for which $\epsilon$ is lower-bounded by a positive constant such that these graph pairs are not distinguishable by
first-order criteria, like degree distribution, spectra, etc.
I am wandering whether it is reasonable to look for such graph pairs from number-theoretic constructions:
For example, it is known that there are Paley graphs (say, $P(p^2)$ for prime $p$) for which there exist Peisert graphs (on $GF(p)\times GF(p)$) that are non-isomorphic to them, but with the same parameters, and even co-spectral.  Is it possible to show that they are in fact "highly" non-isomorphic as well?

A: Combinatorics might be a good place to look. I give below a huge family of pairwise non-isomorphic $57$ point graphs all regular of degree $24.$ I suspect that some of them are fairly far from being isomorphic in your sense but have no idea how easy it would be to find the distance given two specific graphs.
There are $11,084,874,829$ isomorphism classes of STS(19) - a steiner triple system with 19 points (and 57 blocks). Each leads to a unique strongly regular graph with parameters SRG(57,24,11,9)  (There might be other SRG(57,24,11,9), I'm not sure. ) One forms such a graph with a vertex for each block and an edge joining blocks with a common point.These graphs certainly have much in common. They all have the same spectrum and are regular. Every edge is in $11$ triangles and any pair of non-adjacent vertices is connected by $9$ paths of length $2$. All these graphs have exactly 19 $K_9$ subgraphs which correspond to the points. There are also ways in which they can be quite different. One of them has an automorphism group of order $432$. The vast majority, $11,084,710,071$, have no automorphisms at all. Three of them have $84$ Pasch configurations (the maximum number) and  $2,591$ of them have none at all.
As I said, I do not actually know how far a pair of these can be from being isomorphic (in your sense), nor how one would prove that the distance is large. But the Pasch configuration information leads me to speculate that some might be far apart.
A Pasch configuration in a STS is a set of four blocks and six points of the form $uvw,wxy,uxz,vyz$ These are exactly the cases of four pairwise intersecting blocks with no point in common to any three. In the graphs this corresponds to a $K_4$ which overlaps no $K_9$ in a $K_3.$
Whatever is true here is no doubt reflected more extremely in the case of STS(v) for $v \gt 19$ points.  I just don't know if these have been exhaustively enumerated for $v \gt 19.$
There are also great numbers of  strongly regular graphs which have equal parameters but are pairwise non-isomorphic arising from sets of $j$ pairwise orthogonal $k \times k$ latin squares.
LATER I do like the example above and it seems in the spirit that you want. But here is another case where it might be easier to prove distance. In a precise sense, most trees are not determined by their spectrum.
There are many constructions. Here is a small pair which share the spectrum and  degree sequence.

It is not so hard to see that they are not fully isomorphic and there is a vertex bijection which preserves 3/4 of the edges (So they are $1/4$ far from being isokmorphic?)  The condition

there is a vertex of degree $2$ whose neighbors have degrees $3$ and $4$ .

does distinguish them.
I imagine that there are more intricate trees which are harder to immediately tell apart and which are almost $1/2$ far from being isomorphic. Perhaps even $1-\varepsilon$.


text:
Q: Newlander-Nirenberg in dimension 2 What is the easiest (and what is the most elementary) way of proving
Newlander-Nirenberg theorem for Riemannian surfaces? I was able to reduce
it to existence of non-trivial harmonic functions (locally) on 2-dimensional
Riemannian manifolds, but this seems to be non-trivial, too. I want to have a construction using 1-dimensional complex analysis and not much else.
A similar question was asked here.

A: I like the discussion (only possible in this dimension) which uses (1) the fact that Calderón—Zygmund operators which are smoothing of order one transform bounded measurable functions into continuous ones with $e\log1/e$ modulus of continuity and (2)  Osgood's elementary theorem that this modulus of continuity is good enough for unique solutions of ODEs.
Now in a chart with a bounded measurable change of almost complex structure thought of at each point as point in the unit disc with non-Euclidean geometry and at the origin the standard structure in the chart, draw the Poincaré geodesic between these two structures.
Applying the Cauchy transform converts the bounded measurable infinitesimal distortion of conformal structure into an Osgood vector field.
We can integrate this and move along the geodesic path.
This produces a composition of homeomorphisms with the  required bounded conformal distortion.
To get charts with holomorphic overlap mappings modify the starting charts by these constructed homeomorphisms with bounded conformal distortion and use this fact: "homeomorphisms with bounded conformal distortion and zero distortion ae. are holomorphic".
This proves Newlander—Nirenberg for bounded measurable almost complex structures (relative to a standard background).
This is not the most elementary proof of the smooth result but to me it is the conceptually easiest proof.
It also gives a natural and very strong statement with lots of applications not possible using the smooth result.
Also the same proof scheme (use Calderón—Zygmund then Osgood to inch your way to a solution) also solves the Euler equation for 2D incompressible fluid motion for any fixed time which is not known in higher dimensions.
Dennis Sullivan

A: There is also a proof, due to Joe Kohn, using $L^2$ methods, which is relatively easy.  I think the proof, for general n, is in Hormander's book.  As Mohan says, there is need to establish regularity results, but they are standard.  This proof is no easier in 1d, though; it is essentially the same.

A: As Mohan Ramachandran mentioned in a comment above, there is a short and clear proof in Adrien Douady and X. Buff, Le théorème d'intégrabilité des structures presque complexes, The Mandelbrot set, theme and variations, London Math. Soc. Lecture Note Ser., vol. 274, Cambridge Univ. Press, Cambridge, 2000, pp. 307–324. MR 1765096. With some local work, you show that the problem of constructing local holomorphic coordinates reduces to a Beltrami equation, close to the Cauchy--Riemann equation and equal to it outside some compact set. Then you apply elementary $L^2$ methods, using Fourier transform and convolution to construct a very explicit iteration scheme to converge to a solution.


text:
Q: How to access service through ingress from inside and outside server Using nodePort service with ingress, I success expose the service to the out world.
--- service
NAMESPACE       NAME            TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)
default         kubernetes      ClusterIP   10.96.0.1        <none>        443/TCP
default         postgres        ClusterIP   10.106.182.170   <none>        5432/TCP
default         user-api        NodePort    10.99.12.136     <none>        3000:32099/TCP
ingress-nginx   ingress-nginx   NodePort    10.110.104.0     <none>        80:31691/TCP,443:30593/TCP
--- ingress
NAME          HOSTS                ADDRESS        PORTS   AGE
app-ingress   example.com          10.110.104.0   80      3h27m

The rule of ingress show below.
  Host                Path  Backends
  ----                ----  --------
  example.com
                      /user-api   user-api:3000 (172.16.117.201:3000)

If my user-api have a restful api /v1/health interface, how to access this api inside and outside server?

A: From the inside, http://user-api.default:3000/user-api. From the outside, use any node external IP (see kubectl get node -o wide for a list of them).


text:
Q: Bearer token failure MockMvc test Java Spring Boot I'm failing to understand why this does not work. I'm assuming it's something simple that I'm overlooking. All other other test methods not utilizing a token work fine. There is no expiration currently on the token, and I can use it fine with Postman.
@Test
public void getUser() throws Exception {

    String token = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJsd2lsbGlhbXMxNiIsInJvbGVzIjoidXNlciIsImlhdCI6MTUxNDQ0OTgzM30.WKMQ_oPPiDcc6sGtMJ1Y9hlrAAc6U3xQLuEHyAnM1FU";
    MvcResult mvcResult = mockMvc.perform(

            MockMvcRequestBuilders.get("/api/users/lwilliams16")
            .header("authentication", "Bearer " + token))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON))
            .andDo(print())
            .andReturn();

    System.out.println(mvcResult.getResponse().getContentAsString());
}

A: I was utilizing the word Authentication instead of Authorization. It's late. Also, the correct response type is APPLICATION_JSON_UTF8.
@Test
public void getUser() throws Exception {

    String token = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJsd2lsbGlhbXMxNiIsInJvbGVzIjoidXNlciIsImlhdCI6MTUxNDQ0OTgzM30.WKMQ_oPPiDcc6sGtMJ1Y9hlrAAc6U3xQLuEHyAnM1FU";
    MvcResult mvcResult = mockMvc.perform(

            MockMvcRequestBuilders.get("/api/users/lwilliams16")
            .header("authorization", "Bearer " + token))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
            .andDo(print())
            .andReturn();

    System.out.println(mvcResult.getResponse().getContentAsString());
}


text:
Q: PXUnboundDefault Not working The following is not working:
public class SOLineExt : PXCacheExtension<SOLine>
{
    [PXUnboundDefault(typeof(Search<INItemStats.lastCost, Where<INItemStats.inventoryID, Equal<Current<SOLine.inventoryID>>>>))]
    [PXDecimal]
    [PXUIField(DisplayName = "Last Cost", Enabled = false, Visible = true, IsReadOnly = true)]
    public virtual Decimal? UsrLastCost { get; set; }

I have basically the same query running correctly in another customization.
Previously the query was in an event handler and I could see the SQL being executed by running the request profiler. After moving the query to an attributre, the query does not show up in the request profiler.

A: Reviewing the INItemStatus DAC it contains 2 keys (InventoryID and SiteID). When adding the siteid to the query I was able to return results.
Using this:
[PXUnboundDefault(typeof(Search<INItemStats.lastCost,
    Where<INItemStats.inventoryID, Equal<Current<SOLine.inventoryID>>,
        And<INItemStats.siteID, Equal<Current<SOLine.siteID>>>>>),
    PersistingCheck = PXPersistingCheck.Nothing)]
[PXDecimal]
[PXUIField(DisplayName = "Last Cost", Enabled = false)]
public virtual Decimal? ItemSiteLastCost { get; set; }

Returned the following:


text:
Q: Why thead content is not repeating in each and every print page while I try to print the web page? I have a table and I'm trying to print it. It's working fine in the normal mode but when I rotate my th then it is visible in the first print page but not visible on other pages.

th span {
  transform-origin: 0 50%;
  transform: rotate(-90deg);
  white-space: nowrap;
  display: block;
  position: relative;
  top: 0;
  left: 50%;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">

      Firstname
      Lastname
      Email

      John
      Doe
      john@example.com

      Mary
      Moe
      mary@example.com

      July
      Dooley
      july@example.com

      Mary
      Moe
      mary@example.com

      July
      Dooley
      july@example.com

      John
      Doe
      john@example.com

      Mary
      Moe
      mary@example.com

      July
      Dooley
      july@example.com

Screenshot of first and second print page:
First print page:

Second print page:

Note: This is working when I remove rotate span from th
What is missing?

A: Some browsers repeat the thead element on each page, as they are supposed to. But some browsers will not, you need to add extra css for your table header as
thead {display: table-header-group;}

Note: Opera 7.5 and IE 5 won't repeat headers no matter what you try.

A: I got my answer it is fixed now & working fine because of now I use CSS in print script code instead of normal CSS.

A: For Print you may use separate CSS.
Add the code inside the print media like below.
@media print {

    // Your code here

}

Hope it will work.

A: You might need to give your th some padding
th {
    padding: 3em;
}

What my print looks like after I add padding to th


text:
Q: Using JDeveloper to develop a portlet for JavaFX project Suppose I developed a JavaFX project using netbeans 6.8 (JavaFX SDK plugin installed), and right now I need to convert this JavaFX UI to portlet and display it in a web page.
And I'm only allowed to do this using JDeveloper. So how could I achieve this? I'm using Oracle WebLogic Service as my web application server.
-Regards from Isaac.

A: The only way I'm able to resolve this is create portlet which embeds JavaFX applet inside.


text:
Q: GridLayout - Aligning Element I am trying to reduce the space between 2 columns, have tried using negative margins, but did not work. Is there a way to bring the 2 elements in the image closer ?
<?xml version="1.0" encoding="utf-8"?>
<GridLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:useDefaultMargins="true"
    android:alignmentMode="alignBounds"
    android:columnOrderPreserved="false"
    android:layout_gravity="center"
    android:orientation="horizontal"
    android:stretchMode="columnWidth"
    android:background="@color/orange"
    android:textSize="12sp"
    android:columnCount="8">
  <ImageButton
        android:id="@+id/settings"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_columnSpan="1"
        android:layout_gravity="left"
        android:src="@drawable/settings" />
    <TextView
        android:id="@+id/currentCityName"
        android:layout_column="2"
        android:textSize="22sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:text="City name"
        android:layout_columnSpan="4"
        android:layout_gravity="center_horizontal"

        />
  <ImageButton
        android:id="@+id/refresh"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_column="7"

        android:layout_columnSpan="1"
        android:layout_gravity="right"
        android:src="@drawable/reload" />
    <ImageView
        android:id="@+id/currentWeatherImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_columnSpan="8"
        android:layout_rowSpan="3"
        android:layout_gravity="center_horizontal"
        android:src="@drawable/cloud" />
    <ImageView
        android:id="@+id/humidityIcon"
        android:layout_width="20dp"
        android:paddingTop="10dp"
        android:paddingLeft="0dp"
        android:paddingRight="0dp"
        android:layout_marginRight="0dp"
        android:layout_gravity="left"
        android:background="#000000"
        android:src="@drawable/humidity" />
    <TextView
        android:id="@+id/humidity"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="13sp"
        android:paddingTop="10dp"
        android:paddingLeft="0dp"
        android:layout_marginLeft="0dp"
        android:layout_gravity="left"
        android:background="#FFFFFF"
        />
    <TextView
        android:id="@+id/temperature"
        android:layout_columnSpan="4"
        android:layout_rowSpan="2"
        android:textSize="49sp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="5dp"
        android:layout_gravity="center_horizontal"/>
    <ImageView
        android:id="@+id/windSpeedIcon"
        android:layout_width="30dp"
        android:layout_marginRight="1dp"
        android:paddingRight="1dp"
        android:layout_gravity="right"
        android:src="@drawable/wind" />

    <TextView
        android:id="@+id/windSpeed"
        android:textSize="12sp"

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        />
    <!-- android:layout_width="40dp" -->
    <TextView
        android:id="@+id/precipitationIcon"
        android:textSize="28sp"
        android:layout_width="40dp"
        />
    <TextView
        android:id="@+id/precipitation"
        android:layout_column="0"
        android:textSize="13sp"
        android:layout_width="40dp"
        />
    <TextView
        android:id="@+id/windDirection16Point"
        android:textSize="13sp"
        android:layout_width="80dp"
        android:layout_columnSpan="2"
        />
    <TextView
    android:id="@+id/weatherDescription"
    android:layout_gravity="center_horizontal"
    android:layout_row="7"
    android:layout_columnSpan="8"/>

<TextView
    android:id="@+id/section_label"
    android:layout_margin="5dp"
    android:layout_columnSpan="8" />
<EditText
    android:minLines="4"
    android:maxLines="4"
    android:id="@+id/edit"
    android:layout_columnSpan="8"/>

A: I suggest implementing the entire view using a RelativeLayout, should be the best solution for the entire view.

A: You are tackling the wrong problem – you are asking how to reduce the space between columns in a grid layout, but maybe you should't have used such a layout in the first place!
What you should have been using for your specific layout, is a combination of relative positioning and compound drawables (here, with android:drawableStart).

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="80dp"
    android:background="#d89018"
    android:paddingBottom="4dp"
    android:paddingLeft="8dp"
    android:paddingRight="8dp"
    android:paddingTop="4dp"
    >

    <TextView
        android:id="@+id/temperature"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:text="25 ℃"
        android:textColor="#fff"
        android:textSize="49sp"
        />

    <TextView
        android:id="@+id/humidity"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:drawableStart="@drawable/humidity"
        android:gravity="center_vertical"
        android:text="83 %"
        android:textColor="#fff"
        />

    <TextView
        android:id="@+id/windSpeed"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:drawableStart="@drawable/wind"
        android:gravity="center_vertical"
        android:text="19 km/h"
        android:textColor="#fff"
        />

    <TextView
        android:id="@+id/precipitation"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentStart="true"
        android:drawableStart="@drawable/precipitation"
        android:gravity="center_vertical"
        android:text="0.1 mm"
        android:textColor="#fff"
        />

    <TextView
        android:id="@+id/windDirection16Point"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:layout_alignLeft="@id/windSpeed"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:drawableStart="@drawable/windDirection"
        android:gravity="center_vertical"
        android:text="NNW"
        android:textColor="#fff"
        />

</RelativeLayout>

Not only this layout is simpler, you also let Android take care of all the spacing for you. To change the spacing between the compound drawable and the text, use android:drawablePadding in the layout's code above; in Java code, that would be TextView.setCompoundDrawablePadding).

 Icons used for the sample: water, windsock, rainy-weather and wind-rose.

A: I think what's happening is that your Views are being stretched because they are trying to match the width of another view in their columns.
Try decreasing the columnSpan of your Views or separate your layout into two separate GridLayouts.
Or, consider using a different layout altogether. I would recommend RelativeLayout here instead of GridLayout, but I don't know how this fits into a larger window.

A: try this:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="100dp">

    <LinearLayout
      android:id="@+id/col1"
      android:layout_width="match_parent"
      android:layout_height="fill_parent"
      android:orientation="vertical"
      android:layout_weight="2.4"
      >
        <LinearLayout
          android:id="@+id/col1_row1"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:gravity="center_vertical"
          >
          <ImageView
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:src="@drawable/icon"/>
          <TextView
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="83%"/>
      </LinearLayout>
        <LinearLayout
          android:id="@+id/col1_row2"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:gravity="center_vertical"
          >
          <ImageView
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:src="@drawable/icon"/>
          <TextView
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="1.0mm"/>
      </LinearLayout>
    </LinearLayout>

    <LinearLayout
      android:id="@+id/col2"
      android:layout_width="match_parent"
      android:layout_height="fill_parent"
      android:orientation="vertical"
      android:layout_weight="2.0"
      android:gravity="center"
      >
      <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="25'"
          android:textSize="50dp"
          />
    </LinearLayout>

    <LinearLayout
      android:id="@+id/col3"
      android:layout_width="match_parent"
      android:layout_height="fill_parent"
      android:orientation="vertical"
      android:layout_weight="2.4"
      >
        <LinearLayout
          android:id="@+id/col3_row1"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:gravity="center_vertical"
          >
          <ImageView
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:src="@drawable/icon"/>
          <TextView
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="19Km"/>
      </LinearLayout>
        <LinearLayout
          android:id="@+id/col3_row2"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:gravity="center_vertical"
          >
          <ImageView
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:src="@drawable/icon"/>
          <TextView
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="NNW"/>
      </LinearLayout>
    </LinearLayout>

</LinearLayout>

A: I think you should change usedefaultMargins to false and give your own margins to the elements.
android:useDefaultMargins="false";


text:
Q: Angularjs ng-class class order/precedence EDIT:It turns out to be a confusion on my side, pls see my own answer.
I came across a strange behavior when attempting to reorder the precedence of multiple classes in ng-class.
ng-class="{'e':($index%2>0),'btn-primary':($index>3)}"

http://jsfiddle.net/6JjFM/1/
The thing is that no matter how you change the order of the expressions in ng-class it always seems to apply the class which is last in the stylesheet(ie in the css if you put the .btn-primary below .e it will start using the background-color of .btn-primary).
Same thing occurs if I use the ng-class-even to put the .e class.
If you actually inspect the code with chrome it shows up the order to be "btn-primary e" however the background-color of .e does not override the one of btn-primary.
Is there some way to change the precedence of the classes in the ng-class using angular without using css tricks such as !important etc.

A: Your problem is not actually on ng-class, as I see he work as how he design for.
Solution 1:
Yes, use CSS trick. Add below style to your stylesheet:
.e.btn-primary{
    background-color: #F5F5F5;
}

It will now use e background color.
Solution 2:
Use ng-style

3),'e':($index%2>0)}"
    ng-repeat="row in rows"
    ng-style="$index%2>0 && {'backgroundColor': '#F5F5F5'}"
    >{{row}}

ng-style will add inline style to the element, and it will overwrite onfile stylesheet.

A: That is expected behavior. The order of the classes in ng-class won't matter. CSS looks at specificity and if that is same it applies the class that appears 2nd. In your case, .e and .btn-primary have the same specificity so the class that appears later in the css will override the earlier class (if they both change the same attributes).
See here for an example of how I changed the specificity to ensure the class that appears first gets applied...
I've increased the specificity of btn-primary by adding div to it. The background of the div hence appears in blue.
index.html:

    <meta charset="UTF-8">
    <title>Document</title>

0, 'btn-primary':value>3}">
        hello world

script.js:
var app = angular.module('app', [])

app.controller('TeamController', function($scope) {
  $scope.value = 7;
});

A: All answers are absolutely right and I thank you for them!
My confusion comes from working too long with jquery and dynamically adding classes on events to elements.
$('#el').click(function(){
        $('#el').addClass("two")
    });

http://jsfiddle.net/4Gtk6/
What I realized the moment I wrote down my question, is that in this case ng-repeat re-renders the page each time something changes(in the scope based on some event) and conforms to the stylesheet order and the specificity of each class.
Thanks again!


text:
Q: Getting an Error 500 on php myadmin using MAMP and a MAC I'm using a MAC OS and I have MAMP installed. I  have set up my database in PHP myAdmin however when I go into Designer tab to set up my relationships, I get Error 500.
/Applications/MAMP/bin/php/php7.2.8/conf/php.ini <- Version I'm running

Thank you all (sorry I haven't given a more technical description I'm a newby.

A: As someone already suggested in this link all you have to do is to open
/Applications/MAMP/bin/phpMyAdmin/libraries/classes/Database/Designer/Common.php

And on line 268 edit from
return null; to return array();


text:
Q: Struts2 + Hibernate : No target setted for Hibernate Session object I use Struts2 + Hibernate. I get in my console this error : No target setted for Hibernate Session object at /test - Method: xxxa.action.TestAction.testFunc(). Use the hibernatePlugin.sessionTarget property or the SessionTarget Annotation.. Is it only a warning or an error? in both cases, what is required to do? Thank you.

A: I've the same problem using Struts2 + Hibernate. Every part of the puzzle was ok, database, pojo class, fields,... finally I fixed this simply putting my java classes (DAO, Entity pojo class, Action class) inside a package, instead of a blank one.


text:
Q: Practical uses of the immutable flag in Linux Does anyone have real world scenarios where they've used the immutable flag in Linux?

chattr +i file.txt

Since root can unset the attribute, it seems like you're protecting the file against users who have root access but aren't aware of the feature.

A: I've seen this used in virtual hosting setups where file(s) need to remain in directories that users have access to, e.g. php5.fcgi. I also occasionally use it to add an extra step to deleting important files, to protect them from my own absent-mindedness.

A: It's quite handy for for hacking someone else's systems and keeping your trojaned binaries from being deleted!!

A: I use this on any directory that is only intended to be a mount point.  It prevents files from mistakenly getting written if the file system isn't mounted.

A: Usually to protect against automatic deletion of the file, eg. through cleaning of temporary directories etc. though of course you have to hope whatever might delete that file behaves well on failure :)

A: To keep pesky developers and hacking sysadmins off your ish.


text:
Q: Scrapyd: How to retrieve spiders or version of a scrapyd project? It apears that either the documentation of scrapyd is wrong or that there is a bug. I want to retrieve the list of spiders from a deployed project. the docs tell me to do it this way:
curl http://localhost:6800/listspiders.json?project=myproject

So in my environment it looks like this:
merlin@192-143-0-9 spider2 % curl http://localhost:6800/listspiders.json?project=crawler
zsh: no matches found: http://localhost:6800/listspiders.json?project=crawler

So the command seems not to be recognised. Lets check the project availability:
merlin@192-143-0-9 spider2 % curl http://localhost:6800/listprojects.json
{"node_name": "192-143-0-9.ip.airmobile.co.za", "status": "ok", "projects": ["crawler"]}

Looks OK to me.
Checking the docs again, the other API calls take a parameter not as a GET but in a different way:
curl http://localhost:6800/schedule.json -d project=myproject -d spider=somespider

Applying this to listspiders:
merlin@192-143-0-9 spider2 % curl http://localhost:6800/listspiders.json -d project=crawler
{"node_name": "192-143-0-9.ip.airmobile.co.za", "status": "error", "message": "Expected one of [b'HEAD', b'object', b'GET']"}

Missing the GET parameter. So it looks like we are runnning in circles.
How can one retrieve a list of spiders or version (listversion) with scrapyd?

A: Maybe the url needs to be wrapped in double-quotes, Try
curl "http://localhost:6800/listspiders.json?project=crawler"


text:
Q: MongoClient not working with php I'm trying to use mongodb with php but I keep getting this error

("Class 'MongoClient' not found")

whenever I try this code:
$m = new MongoClient();

The weird part is that if I run a get_loaded_extensions(), mongodb shows up and it also shows up on the phpinfo(). I also have extension=mongodb.so on the php.ini file.
I'm on debian running MongoDB shell version: 2.6.11 and php is running mongodb version  1.1.2.

A: You're mixing up the Mongoand MongoDB extensions.
The (deprecated) Mongo extension loads via mongo.so and provides MongoClient.
You're using the newer and preferred MongoDB extension (mongodb.so) so you should be using:
$client = new MongoDB\Client("mongodb://localhost:27017");

See: http://php.net/manual/en/set.mongodb.php
vs http://nl1.php.net/manual/en/mongo.setup.php


text:
Q: How do I change the background image using jQuery animation? I want to change the background image using slow animation, but its not working
 $('body').stop().animate({background:'url(1.jpg)'},'slow');

Is there something wrong with the syntax!!

A: You can get a similar effect by fading the image opacity to 0, then change the background image, and finally fading the image back in again.
This will require a div, behind everything else on your page which is as wide as the body.

    ...

You can make it as wide as the page using CSS:
#bg {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
}

And then animate it's properties.
$('#bg')
    .animate({opacity: 0}, 'slow', function() {
        $(this)
            .css({'background-image': 'url(1.jpg)'})
            .animate({opacity: 1});
    });

You could get more of a crossover effect, by having a second background div on top of this one, which you can then fade in.

A: From the jQuery documentation:

properties that are non-numeric cannot
  be animated using basic jQuery
  functionality. (For example, width,
  height, or left can be animated but
  background-color cannot be.)

Source: http://api.jquery.com/animate/

A: You can't animate the adding/replacing of a background image. The URL is either there or not. There's no in between state.

A: The way to achieve this may be to onclick add a new class with the background image in. Then animate this?
Or fade out the image to reveal a new one?

A: I would use a faux div to cover the background as a fixed element and then animate that element i.e:

A: Here is how I did it:
$(this).animate({
    opacity: 0
}, 100, function() {
    // Callback
    $(this).css("background-image", "url(" + new_img + ")").promise().done(function(){
        // Callback of the callback :)
        $(this).animate({
            opacity: 1
        }, 600)
    });
});


text:
Q: Boolean value not inserted through Symfony When in perform update statement in pgadminIII its working fine false is updating for column value
update tbl_student_colleges set target=false where id=9

When do the same with Symfony Script values is working fine with True but not working when false.
$apptQuery = "insert into tbl_student_colleges (student_id,college_id,college_name,target,applied,accepted,attending,scholarship,created_at,created_by_id,updated_at,updated_by_id) values(:returnID,:collegeId,:collegeName,:target,:applied,:accepted,:attending,:scholarship,:date,:loggedinUser,:date,:loggedinUser)";
$em = $this->getDoctrine()->getEntityManager();
$Querystatement = $em->getConnection()->prepare($apptQuery);
$Querystatement->bindValue('returnID', $returnID);
$Querystatement->bindValue('collegeId', '2472363');//2472363
$Querystatement->bindValue('collegeName', $school->college_name);
$Querystatement->bindValue('target', $school->target == 1 ? TRUE : FALSE);
$Querystatement->bindValue('applied', $school->applied == 1 ? TRUE : FALSE);
$Querystatement->bindValue('accepted', $school->accepted == 1 ? TRUE : FALSE);
$Querystatement->bindValue('attending', $school->attending == 1 ? TRUE : FALSE);
$Querystatement->bindValue('scholarship', $school->scholarship);
$Querystatement->bindValue('date', $date);
$Querystatement->bindValue('loggedinUser', $loggedinUser);
$Querystatement->execute();

A: Use 0 instead of false and see if it works


text:
Q: Which tools do you recommend for java round-trip-engineering? I am especially interested in generating code from sequence diagrams and vice versa- ie., sequence diagrams from code. Ofcourse it would be nice if it was free and better if it was an eclipse plugin!

A: I've never seen a tool generating code from a sequence diagram in uml or doing opposite conversion. In particular, because sequence diagrams are supposed to provide high-level overview of logic flow.

A: Altova UModel can generate sequence diagram from the code, but I don't see any point from the opposite direction.
Anyway, UModel has 30 days free trail and it is really a great tool so you should check it.
Here is the
link.

A: You can reverse engineer sequence diagram from code to UML.
I don't know any tool creating a java code from a sequence diagram model !!

A: MagicDraw is a good tool. It is written in Java and if you purchase the right pluggins will do the round tripping for you.
Be wary of round tripping too much though - it kinda defeats the purpose of designing if you do too much of it. It implies that you are not really designing and then implementing the design, but rather hacking around inside a UML tool. The project leader at one company I worked for did not allow round tripping at all and did not let developers purchase the tools to do it. Having said that, it can be useful for generating diagrams from an existing code base that you did not write, to get a high level view of design and interactions.


text:
Q: Airflow tasks not gettin running I am trying to run a simple BASHOperator task in Airflow. The DAG when trigerred manually lists the tasks in Tree and Graph view but the tasks are always in not started state.
I have restarted my Airflow scheduler. I am running Airflow on local host using a Kubectl image on Docker Compose.
from airflow import DAG
from airflow.operators.dummy_operator import DummyOperator
from airflow.operators.bash_operator import BashOperator
from datetime import datetime, timedelta

default_args = {
    'owner': 'airflow',
    'depends_on_past': False,
    'email': ['vijayraghunath21@gmail.com'],
    'email_on_success': True,
    'email_on_failure': True,
    'email_on_retry': False,
    'retries': 1,
    'retry_delay': timedelta(minutes=2),
}

with DAG(
    dag_id='bash_demo',
    default_args=default_args,
    description='Bash Demo',
    start_date=datetime(2021, 1, 1),
    # schedule_interval='0 2 * * *',
    schedule_interval=None,
    max_active_runs=1,
    catchup=False,
    tags=['bash_demo'],
) as dag:
    dag.doc_md = __doc__

    # Task 1
    dummy_task = DummyOperator(task_id='dummy_task')

    # Task 2
    bash_task = BashOperator(
        task_id='bash_task', bash_command="echo 'command executed from BashOperator'")

    dummy_task >> bash_task

DAG Image

A: As shown on the image you added the DAG is set to off thus it's not running. You should click on the toggle button to set it to on.

This issue can be avoided in two ways:
Global solution- if you wills set dags_are_paused_at_creation = False in airflow.cfg - This will effect all DAGs in the system.
Local solution - if you will use is_paused_upon_creation in the DAG contractor:
with DAG(
    dag_id='bash_demo',
    ...
    is_paused_upon_creation=False,
) as dag:

This parameter specifies if the dag is paused when created for the first time. If the dag exists already, the parameter is being ignored.


text:
Q: splitting a stream how to split a stream  in to requires size, i need to send it in a sockets to another system,then i need to append them and create a FILE

A: Since it is by byte array, you could send it by chunk. You must create 3 methods. The first will accept the total byte count and might return an id or filename (of the temporary file) where the current uploaded data is stored. 2nd method is use to upload chunks of data (that is recognized by id, filename). 3rd will inform that the process is completed (based on id, filename).
When the 3rd process is completed you could do your stuff then (like save it to database, etc.)


text:
Q: What can I use in a React app as an equivalent of Angular's $http.get I am looking to make an http request within a React app and am wondering what the best method would be.
I know in Angular you can use $http.get, so something like:
$http.get('API').success(function(data) {...

But what can I use for the same purpose within a React App. Would something like Axios work?
Forgive my ignorance, total newbie here.

A: checkout window.fetch. It has a very nice API to work with. It is a fetch function is now provided in the global window scope.
if you want to support browser without fetch implemented. try a polyfill like this one from github https://github.com/github/fetch
here is a quick example
// url (required), options (optional)
fetch('/some/url', {
    method: 'get'
}).then(function(response) {
    if (response.ok) {
        return response.json()
    }
}).then(function(json) {
    console.log(json)
    // set your state, your props, your child context do whatever you want
    // with the json
    // this.setState({ data: json })
}).catch(function(err) {
    // Error :(
})

Here a great tutorial
Here is the spec

A: You can use JQuery library's ajax methods or specific libraries like Superagent. For Superagent just install it with npm, for example npm i superagent --save and make http requests for example:
request
   .get('/search')
   .end(function(err, res){
       // function body
   });

Here is complete documentation for it.


text:
Q: How to adjust parameters when training a svm model If I using rbf as the kernel function, then two parameters(c and g)  has to be adjusted. I can search every parameter pair(ci,gi),and select the best pair. Is there any better approach to find the best parameters.

A: The highlight from this blog on the kernel width choice:

To pick, say 1000 pairs (x,x') at random from your dataset, compute the distance
of all such pairs and take the median, the 0.1 and the 0.9 quantile. Now pick λ
to be the inverse any of these three numbers. With a little bit of cross
validation you will figure out which one of the three is best. In most cases you
won't need to search any further.

And this post from cross validated provides an analysis on the reason why such method works well. Basically changing the decision function for all or only one datapoint is avoided.
Besides, you may search "Heuristic method" on the parameter choice in SVM. For example, in M.Boardman et al's A Heuristic for Free Parameter Optimization with Support Vector Machines, the authors applied simulated annealing to improve parameter search efficiency compared to an exhaustive grid search.


text:
Q: Why might the author date be stuck at an old date with git? I track all my projects in git. Unfortunately, in my main repository the author date seems to be stuck. It reports as July 15, 12:25:08 -0500 for almost every commit since then. The commit date seems to be working correctly. There is evidence this might be happening in another repository, but it doesn't change enough for me to know for sure.
I've checked the .git/config file, as well as my global .gitconfig file. I can't think of anything special that happened on that day.
I'd like to figure out what's causing this so I can fix it. For bonus points, I'd like to fix all the bad author dates. Since I'm the sole developer (at this point in time) I think it's pretty safe to update all the clones (local repo, local server, GitHub).
Edit: So far, it looks like magit in Emacs might be doing it. However, I still don't know how or why.

A: There is an environment variable called GIT_COMMITTER_DATE which can be used to override the current date for new commits. Try:
env | grep GIT

and see if that is set.

A: It appears there was something corrupt in the emacs process somewhere. It is quite possible that emacs had actually been running since before the date in question and had somehow become slightly corrupted.
Restarting emacs fixed the problem. I will, however, keep an eye on things, at least for awhile.
Thank you to those who helped me track down the problem. I hadn't realized how much I rely on magit.


text:
Q: Generic Methods with Linked-list Hi I'm trying to make these 2 methods work, but even though I tried pretty much everything I can think of, it's still not working. Please tell me how to fix it!
void add(Anything value): Adds a node containing newValue to the end of the list.
void addAfter(int index, Anything value): Adds a Node node containing newValue after the node of index index(assume index start in 0).
Here's my code: (The methods above appear at the bottom)
public class Node<Anything>
{

private Anything data;
private Node next;

Node(Anything a, Node<Anything> n)
{
    data = a;
    next = n;
}

public Anything getData()
{
    return this.data;
}

public Anything setData(Anything newData)
{
    Anything oldData = this.data;
    this.data = newData;
    return oldData;
}

public void setNext(Node<Anything> newNext)
{
    this.next = newNext;
}

public Node<Anything> getNext()
{
    return this.next;
}
 }

------------------------------------------

public class CS2LinkedList<Anything>
{

private Node<Anything> first;
private Node<Anything> last;

public CS2LinkedList()
{
    first = null;
}

public boolean isEmpty()
{
    return (first == null);
}

public void addFirst(Anything d)
{
     Node<Anything> temp = first;
     first = new Node<>(d,temp);
}

public void clear()
{
    first = null;
}

public boolean contains(Anything value)
{
    for (Node curr = first; curr != null; curr = curr.getNext())
    {
        if (value.equals(curr.getData())){
            return true;
        }
    }
    return false;
}

public String toString()
{
    StringBuilder result = new StringBuilder();  //String result = "";
    for (Node curr = first; curr != null; curr = curr.getNext())
        result.append(curr.getData() + "->");  //result = result + curr.data + "->";
    result.append("[null]");
    return result.toString();   //return result + "[null]";
}

public int size()
{
    int size = 0;
    for (Node curr = first; curr != null; curr = curr.getNext()){
         size++;
         if (first==null){
                 size = 0;
            }
        }
        return size;
         }

public Anything getFirst()
{

    if (first!=null){
        return first.getData();
    }
    else{
       System.out.println("Sorry, the list is empty.");
       return null;
    }

}

public Anything getLast()
{
    if (first!= null){

        for(Node curr = first; curr != null; curr = curr.getNext()){
            first = curr;
        }
        return first.getData();
        //FIX: list2's size decreases by 1 after executing list2.getLast()
    }
    else{
        System.out.println("Sorry, the list is empty.");
        return null;
    }
}

public void add(Anything value){
    if (first==null){
        first = new Node<>(value,first);
    }

    Node<Anything> next = new Node<>(value, first);
    first.setNext(null);
    last = next;
 }

public void addAfter(int index, Anything value)
{
    return;
}
 }

A: A bit long answer, tried to explain every bit of problem and give the solution. Have patience!
You're code is exactly doing what you have told it to do, adding new nodes in reverse. It is adding the new node as the first and set the current first as new node's next while addFirst() is called.
But with the current add() method you've mentioned, you'll always get a linked list not more than one element by calling the printing toString() method, although you have the list containing not more than two nodes. Let's look at your code to understand this:
public void add(Anything value){
    if (first==null){
        first = new Node<>(value,first);
    }

    Node<Anything> next = new Node<>(value, first);
    first.setNext(null);
    last = next;
}

So what you are doing is, you're checking whether the first is null, which means, whether the current list is empty. If true then initialize first with new value (say "x") and it's next as current first, which is null. So we get [first(x)] -> [null] as our current list.
Next you're initializing a next node with the value and first as it's next. Then you are setting the next of first as null and assigning next to the last. So far we've got:
[next(x)] -> [first(x)] -> [null]        //where last node is next(x)

Now if you want to add(y), another next will be initialized with the current first as the next of this new node. Then again redundant making of null of the next of the first. And again assigning this new node to last. Now we've got:
[next(y) -> [first(x)] -> [null]

So, here we go! You are losing the current last by assigning the new node to the last, and this last will have the first as it's next, always, how many nodes you want to add, it follows the same path.
Hence, you'll get a linked list of two elements, always, with this add() method.
But why the toString() gives only [first(x)] -> [null] as linked list?
Well, look at the toString() function, it starts from first, runs until first.next == null. And, you have first.next == null, always, if you add nodes with this add() method. Therefore, such behavior of the toString().
What's the solution?
Set both of the first and last of the linked list in the constructor as null during the initialization. In the add() method, initialize the first for the first time with the value and last. And assign it to the last. return after that as we are done adding the first node. Remove the first.setNext(null) statement, initialize the new node with value and null. Make the next of the current last as new node. and assign the new node as the last. Here is the code:
public void add(Anything value) {
    if (first == null) {
        first = new Node<>(value, last);
        last = first;
        return;
    }

    Node<Anything> next = new Node<>(value, null);
    last.setNext(next);
    last = next;
}

Now if you print the toString(), you'll get:
node1->node2->node3->[null]

Hope you got your answer and desired solution!


text:
Q: How to find a proof of a formula in propositional calculus? $1.$ $\alpha$ $\rightarrow$$(\beta \rightarrow \alpha)$    --- (Ak)
$2.$ $(\alpha \rightarrow (\beta \rightarrow \gamma)) \rightarrow ((\alpha \rightarrow \beta ) \rightarrow (\alpha \rightarrow \gamma))$ --- (AS)
$3.$ $(\lnot \beta \rightarrow \lnot \alpha) \rightarrow ((\lnot \beta \rightarrow \alpha) \rightarrow \beta)$  --- (A$\lnot$)
I'm told that I can use any formula to prove something, but if I know that $\vdash \alpha \rightarrow \alpha $ why I can't use it to prove anything?
For example : To prove  $\lnot (\alpha \rightarrow \beta)\vdash \lnot \beta$
$1.$ I can write $\lnot \beta \rightarrow \lnot \beta $, or,known $\lnot \alpha \rightarrow \alpha \vdash \alpha $,I can say $(\lnot \lnot \beta \rightarrow \lnot \beta)\rightarrow \lnot \beta$.
An other example : to prove $\lnot \alpha \rightarrow \alpha \vdash \alpha $
$1.$ I could say $\alpha \rightarrow \alpha$, all the solutions I provided are not correct, but that's what I understood, can you explain what I'm missing?

A: The axiom system you are being asked to use is a standard one -- famously used in the classic textbook Elliott Mendelson, Introduction to Mathematical Logic (many editions, there is bound to be one in the library).
Since you are evidently very unclear what the rules of the deduction game are, you badly need to pause and take a slow and careful look at e.g. Mendelson's text.


text:
Q: Increment and decrement counter JS I need increment and decrement a counter when click the buttons.

const checkbox = document.getElementById('cb_enabled'),
  increment = document.getElementById('btn_increment'),
  decrement = document.getElementById('btn_decrement'),
  counter = document.getElementById('js-counter').innerHTML;

checkbox.addEventListener("change", function(checkbox) {

  if (this.checked === false) {
    increment.disabled = true;
    decrement.disabled = true;
  } else {
    increment.disabled = false;
    decrement.disabled = false;
  }
});

increment.onclick = () => {
  counter.innerHTML = 1;
}

decrement.onclick = () => {
  counter.innerHTML = 0;
}

 0

<button id="btn_decrement" type="button"> Decrement </button>
<button id="btn_increment" type="button"> Increment </button>

  Enable/Disable counter
  <input id="cb_enabled" type="checkbox" checked />

But I don't know how to increase and decrease the number (in this case, the element into js-counter).
Any ideas?

A: counter should just be the element, not its innerHTML.
To increment it, get its contents, parse it to a number, add or subtract 1, then write that back to the element.

const checkbox = document.getElementById('cb_enabled'),
  increment = document.getElementById('btn_increment'),
  decrement = document.getElementById('btn_decrement'),
  counter = document.getElementById('js-counter');

checkbox.addEventListener("change", function(checkbox) {
  if (this.checked === false) {
    increment.disabled = true;
    decrement.disabled = true;
  } else {
    increment.disabled = false;
    decrement.disabled = false;
  }
});

function add_to_counter(increment) {
  let cur_count = parseInt(counter.innerText);
  let new_count = cur_count + increment;
  counter.innerText = new_count;
}
increment.onclick = () => {
  add_to_counter(1);
}

decrement.onclick = () => {
  add_to_counter(-1);
}

 0

<button id="btn_decrement" type="button"> Decrement </button>
<button id="btn_increment" type="button"> Increment </button>

  Enable/Disable counter
  <input id="cb_enabled" type="checkbox" checked />

A: Keep reference to the counter element and not to it's innerHTML property and also don't forget to parseInt the string value before incrementing.

const checkbox = document.getElementById('cb_enabled'),
  increment = document.getElementById('btn_increment'),
  decrement = document.getElementById('btn_decrement'),
  counter = document.getElementById('js-counter');

checkbox.addEventListener("change", function(checkbox) {

  if (this.checked === false) {
    increment.disabled = true;
    decrement.disabled = true;
  } else {
    increment.disabled = false;
    decrement.disabled = false;
  }
});

increment.onclick = () => {
  const num = parseInt(counter.innerHTML);
  counter.innerHTML = num + 1;
}

decrement.onclick = () => {
   const num = parseInt(counter.innerHTML);
  counter.innerHTML = num - 1;
}

 0

<button id="btn_decrement" type="button"> Decrement </button>
<button id="btn_increment" type="button"> Increment </button>

  Enable/Disable counter
  <input id="cb_enabled" type="checkbox" checked />

A: The issue was with the counter initialization
counter = document.getElementById("js-counter").innerHTML
You are getting innerHTML reference while initialisation and also during assigning.
counter.innerHTML = 1;

const checkbox = document.getElementById('cb_enabled'),
  increment = document.getElementById('btn_increment'),
  decrement = document.getElementById('btn_decrement');
  counter = document.getElementById("js_counter");

checkbox.addEventListener("change", function(checkbox) {

  if (this.checked === false) {
    increment.disabled = true;
    decrement.disabled = true;
  } else {
    increment.disabled = false;
    decrement.disabled = false;
  }
});

increment.onclick = () => {
  counter.innerHTML = 1;
}

decrement.onclick = () => {
  counter.innerHTML = 0;
}

 0

<button id="btn_decrement" type="button"> Decrement </button>
<button id="btn_increment" type="button"> Increment </button>

  Enable/Disable counter
  <input id="cb_enabled" type="checkbox" checked />

A: I can give you functionality for increment and decrement counter from my ReactNative.Below There is Functionality for your HTML Project
const [num, setNum] = useState(0);

  function incre() {
    setNum(num + 1);
  }
  function decre() {
    if (num > 0) {
      setNum(num - 1);
    } else {
      Alert.alert('zero is the limit');
    }

Now Just Display the counter in the Div or View of the Application and Call the function on CLick or Press the Button.
     <View style={{width: '100%'}}>
            <Text>
              Count
            </Text>
            <Text>
              {num}
            </Text>
<TouchableOpacity
            style={{alignSelf: 'center'}}
            onPress={() => {
              incre();
              decre();
            }}>
</TouchableOpacity>

if it is a button in HTML
<button id="btn_decrement" type="button"  onclick={() => {
              incre();

            }}>> Decrement </button>
<button id="btn_increment" type="button" onclick={() => {
              decre();

            }}>> Decrement </button>

Functionality for your HTML;
 function incre() {

          var num=num+1;

          }

    function decre() {

              var num=num-1;

              }


text:
Q: Width of absolute positioned div not the same as children's width I'm using the Dropkick jquery plugin for custom select boxes.
It seems the absolute positioned dropdown always gets its width from the parent, and not the full width of the child list items.
How can I fix this?
See this jsfiddle.
Structure:

                <nobr>status</nobr>

                    state

                    longerwords

                    longerwords

                    longerwords

UPDATE:
It seems like the float on my .filter-lbl, is causing this.
It's because of the inline style of my .filter-lbl.
Is there a workaround to this?

A: Your dk options class does not need to be absolute unless you are looking for an overflow, absolute will ignore anything else.
Try this in your CSS
.dk_options {
  /*display: none;*/
  margin-top: -1px;
  position: relative;
  right: 0;
  width:auto;
}

This should ensure the wrapper is the right width.


text:
Q: Trying to understand a proof about onto/1-1 mappings (from Herstein's Topics in Algebra) I am working on some problems in a book I have and I want to make sure that I have an accurate possible proof. That is, I want to make sure I actually understand/ can justify the reasoning. (some of it were from hints so that is what I want to be sure I can justify,  even if the problem may be very elementary).
The question is,

*

*If the set $S$ has a finite number of elements then prove that if $\sigma$ maps from $S$ onto $S$, then $\sigma$ is one-to-one, and if $\sigma$ is one-to-one map from $S$ into $S$ , then show that $\sigma$ is onto.

$\mathbf{Proof (in \space progress)}:$
Let $|S|=n$ and let $\sigma: S \to S$ be any mapping from $S$ into $S$.
Now, because $\sigma$ is a mapping, every element in S must be mapped somewhere ( is this correct reasoning?), thus we have
$$\sigma^{-1}(S)=S$$
So, we can write $$S= \bigcup_{s \in S}\sigma^{-1}(s)$$
which is also true since $\sigma$ is a mapping and since every s is mapped to somewhere the union of all s that are mapped is all of s( is this correct reasoning)?,
This I understand so far if my reasoning has held,
The next part I am a bit confused on, it is to make use that each subset is disjoint and then use that to imply that $$|S|=\sum_{s \in S} |\sigma^{-1}(s)|$$
Now Im not exactly sure what is happening here. I mean intuitively it seems to makes sense that since each $s \in S$ can only be mapped to one other $s \in S$, then it would hold, but I still feel a bit fuzzy on it.
Moving on,  if $\sigma$ is onto then we have $|\sigma^{-1}(s)| \ge 1$ because each s must have at least one s if not more that maps to it.
and from above, this gives, $$n=|S|=\sum_{s \in S} |\sigma^{-1}(s)| \ge \sum_{s \in S} 1=n$$ (because cardinality of S is n).
And to assure the equality holds i.e. that n=n it forces that $| \sigma^{-1}(s)|=1$ for every $s \in S$ which therefor shows $\sigma$ is one-to-one
and the converse is similar, that is, if $\sigma$ is one-to-one then
$|\sigma^{-1}(s)| \le 1$ for every $s \in S$ because of course if it was more than 1 , it would imply that more then one element in $S$ maps to the same element in $S$ which is directly against the definition of one-to-one.
Which again will force us to have $| \sigma^{-1}(s)|=1$ for all $s \in S$, therefor showing that $\sigma$ is also onto.
So yea, basically, I am wondering about the validity of it all, any insight/comments on the topic, and I also added some parts in where I asked if my train of thought was valid. I hope this can all help me to understand and work on my proofs better.
Thanks everyone for the time!
Update:
Some of the comments have left me very curious about what methods I should be attempting. So ideally, if someone could give a solution to this using only what was already taught in Hersteins book, then that would be great. Because from some of the comments it seems that this technique may be too advanced.

A: I think that Herstein had a naive handling of this problem in mind. A set is finite if it can be  mapped bijectively onto some set $[n]:=\{1,2,\ldots,n\}$ with $n\in{\mathbb N}_{\geq0}$. We therefore have to prove that a surjective $f:\>[n]\to[n]$ is automatically injective, and vice versa.
I shall prove the first of these two statements, using induction. The other is similar, and is left to you. When $n=1$ the statement is obviously true. Therefore assume that $n\geq1$, and that any surjective $f:\>[n]\to[n]$ is automatically injective.
Let a surjective $g:\>[n+1]\to[n+1]$ be given, and put
$X:=\bigl\{x\in[n]\bigm|g(x)=n+1\bigr\}$.
If $g(n+1)=n+1$ consider the map
$$f:\quad[n]\to[n],\qquad x\mapsto\left\{\eqalign{1\quad&\quad(x\in X)\cr g(x)&\quad(x\notin X)\cr}\right.\quad.$$
Then $f$ is surjective, whence injective. In particular $X=\emptyset$, and it follows that $g$ is injective as well.
If $g(n+1)=j\in[n]$ the set $X$ is nonempty. Consider the map
$$f:\quad[n]\to[n],\qquad x\mapsto\left\{\eqalign{j\quad&\quad(x\in X)\cr g(x)&\quad(x\notin X)\cr}\right.\quad.$$
Then $f$ is surjective, whence injective. In particular $|X|=1$, and it follows that $g$ is injective as well.

A: You are using cardinal arithmetic in a proof of a theorem which is fundamental to proving that cardinal arithmetic has the well-known properties which we are familiar with. So this is a bit backwards. You can't use high-level conclusions to prove low-level theorems which will then be used to prove higher-level conclusions later. That's a bit circular.
A good book on naive set theory will go through the steps in a "proof-before-use" order so that you don't use theorems in a circular manner.
In this case, you should start with the definition of a finite set. There are several definitions, and the theorem you are trying to prove is roughly equivalent to one of those definitions. So you have to make sure you know what your definitions are first. One of the most popular definitions of finiteness is that a set is equinumerous to one of the finite ordinal numbers, which are defined in a quite complicated way in ZF set theory, if you prove all of the details. Alternatively there are some other definitions of finiteness which don't use the ordinal numbers on the wikipedia finite set web page.
If you start with the equinumerous-to-a-finite-ordinal-number definition for finiteness, then you have a bijection from your set to some finite ordinal number. Then you can do some manipulations on your surjection to show that it is a bijection from $S$ to $S$ using already proved properties of the finite ordinal numbers.
In conclusion, if you don't have a solid definition of a finite set, you can't make your argument logically rigorous. So your first step is to choose that definition. Then you can start using the theorems which go along with that definition, which depend on which book you are using as a source.


text:
Q: Having Trouble printing out .txt in ruby, ruby file handling the problem is it cannot print all the text of the from a .txt file. I am able to print the first 3 lines of the txt file but not the rest. So far, I am getting an error which is in print_album': undefined local variable or methodtracks' for main:Object (NameError).
Here's the code:
*I know using global variable is no good in Ruby but this exercise ask me to do it.
  module Genre
  POP, CLASSIC, JAZZ, ROCK = *1..4
  end

  $genre_names = ['Null', 'Pop', 'Classic', 'Jazz', 'Rock']

  class Album
  # NB: you will need to add tracks to the following and the initialize()
  attr_accessor :title, :artist, :genre, :tracks

  # complete the missing code:
  def initialize (atitle, aartist, agenre, arrtrk)
    # insert lines here
    @genre = agenre
    @tracks = arrtrk
    @title = atitle
    @artist = aartist

  end
end

   class Track
   attr_accessor :ttitle, :tlocation

  def initialize (tname, tloc)
    @ttitle = tname
    @tlocation = tloc
end
end

 # Reads in and returns a single track from the given file

 def read_track music_file

  mytrk_name = music_file.gets
  mytrk_location = music_file.gets
  mytrk = Track.new(mytrk_name, mytrk_location)
  mytrk

 end

 # Returns an array of tracks read from the given file

 def read_tracks music_file
 count = music_file.gets().to_i
 tracks = Array.new
 $i = 0
 # Put a loop here which increments an index to read the tracks
 while $i < count do
   track = read_track(music_file)
   tracks << track
   $i += 1
 end
 tracks
end

# Takes an array of tracks and prints them to the terminal

def print_tracks tracks
 # print all the tracks use: tracks[x] to access each track.
$i = 0
while $i < tracks.length do
    print_track(tracks[$i])
    $i +=1
end
tracks
end

# Reads in and returns a single album from the given file, with all its tracks

def read_album music_file

# read in all the Album's fields/attributes including all the tracks
# complete the missing code
album_title = music_file.gets
album_artist = music_file.gets
album_genre = music_file.gets.to_i

tracks = read_tracks(music_file)

album = Album.new(album_title, album_artist, album_genre, tracks)
album
end

# Takes a single album and prints it to the terminal along with all its tracks
def print_album album

# print out all the albums fields/attributes
# Complete the missing code.
 puts 'Album title is '+ album.title
 puts 'Artist is ' + album.artist
 puts 'Genre is ' + album.genre.to_s
 puts $genre_names[album.genre]
# print out the tracks
 print_tracks(tracks)
end

# Takes a single track and prints it to the terminal
def print_track track
 puts('Track title is: ' + track.ttitle)
 puts('Track file location is: ' + track.tlocation)
end

# Reads in an album from a file and then print the album to the terminal

def main
 music_file = File.new("album.txt", "r")
 album = read_album(music_file)
 music_file.close()

 print_album(album)
end

main

Here's is the album.txt
Greatest Hits
Neil Diamond
1
3
Crackling Rose
sounds/01-Cracklin-rose.wav
Soolaimon
sounds/06-Soolaimon.wav
Sweet Caroline
sounds/20-Sweet_Caroline.wav

Currently my output is :
Album title is Greatest Hits
Artist is Neil Diamond
Genre is 1
Pop

Expected output is :
Album title is Greatest Hits
Artist is Neil Diamond
Genre is 1
Pop
Track title is: Crackling Rose
Track file location is: sounds/01-Cracklin-rose.wav
Track title is: Soolaimon
Track file location is: sounds/06-Soolaimon.wav
Track title is: Sweet Caroline
Track file location is: sounds/20-Sweet_Caroline.wav

A: The problem is inside your def print_album album method. On the last line of the method it uses print_tracks(tracks), but tracks variable is undefined (that's exactly what error tells you).
You need to call  print_tracks(album.tracks)