text:
Q: How to limit concurrency with scheduled rule Following scenario:
I have a lambda (L1), which is triggered by several services (s1, s2, ... sN) via a scheduledRule(r1 ,r2 , ... rN) configured with cron.
The problem is that two Lambdas of type L1 triggered by the same service via the same scheduledRule must never run simultaneously. So a lambda that was triggered by s1 over r1, if it has not finished in the time until the next scheduled execution, may not be started again.
Two Lambdas that were triggered by different services via different rules should be allowed to run simultaneously.
The only possibility I can think of at the moment would be to put an SQS between rule and lambda.
Is there a more elegant solution or does SQS sound practical?

A: You can use Dynamodb to store status info, if there is running process. It's extreamly fast. Just remember to enable strongly consistent reads


text:
Q: Using Coldfusion to create a REST request Using Coldfusion I would like to create a REST service
I would like to post it to: https://www.test.co.za/ using the username "person1" and password "password1".
The data type would be: application/json
And I would like to pass the following parameters:

*

*callbackURL (string)

*amount (bigdecimal)

*reference (string)

*description (string)

This will then return:

*

*reference (string)

*redirectURL (string)

*status (string)

This is what I have got so far:
index.cfm
<cfset restInitApplication("C:\ColdFusion10\cfusion\wwwroot\restApp","IIT")>

<cfhttp url="http://127.0.0.1:8500/rest/IIT/rest" method="get">

<cfoutput>#cfhttp.filecontent#</cfoutput>

rest.cfc
<cfcomponent rest="true" restpath="restService">
    <cffunction name="sayHello" access="remote" returntype="String" httpmethod="GET">
        <cfset callbackURL = "https://www.google.com">
        <cfset amount = "100,50">
        <cfset reference = "123456789">
        <cfset description = "This is a description">
        <cfreturn rest>
    </cffunction>
</cfcomponent>

I would like to know if I am on the right track and how I would post my values to https://www.test.co.za/ with a username and password
I am not sure if it will look something like this:
<cfhttp
    url="https://www.test.co.za/"
    method="post"
    port="8500"
    result="res">
</cfhttp>

Thanks in advance

redpajama_set_name: RedPajamaStackExchange


text:
Q: Present Perfect with "that" I came across the sentence "It's been thirty years since my parents first met." I am sure that if I heard "It's been thirty years that my parents first met", I would accept it as grammatical, but I can't find any reference to support this. Am I wrong?

A: You'd have to use present perfect on both sides for that sentence to work:

It's been thirty years that my parents have been married.

Otherwise, remove the present perfect from the first part:

It was thirty years ago that my parents first met.

In both examples, as well as the ones you referenced, that acts as a conjunction, or should. If you are trying to use it as a determiner, then it simply doesn't work there.

A: In your example, you would have to use the word since.

It's been thirty years since my parents first met.

Using since here is actually related to the span of time since the moment your parents met, rather than the first half of the sentence. Using that would be grammatically incorrect. However, you could say:

When I look back on my life, it's been thirty years that I wish I could forget.

In this instance, that is used to create a relative clause, connecting the thirty years to the last half of the sentence. You can do this with other things too:

I have eaten something that wasn't good for me.

This isn't restricted to the present perfect, either:

It's going to be thirty years that I wish I could forget.

But, as soon as you're talking about the span of time, you have to use since again.

I have eaten at least three kilograms of cheese since my parents first met.
I haven't eaten anything since yesterday.


text:
Q: Complex FormData in react native What I need to do:
- POST form-data in react-native using fetch API request.
The formdata is given in follow format. It includes simple string, complex object, simple array, and complex array and file in single API call.
Do note that this is an api provided by third party vendor and i cannot change it. No, it won't accept application/json format.
Note: Pure react-native app. EXPO not supported.**.

I have data as follow. How can i serialize this data into formdata compatible?
let data = {
    string: "1",
    object: {
        a: 3,
        b: {
            c: 5
        }
    },
    array: [1,2,3],
    arrayComplex: [{id: 2, value: 2}, {id:3, value:3}],
    file: {
        name: 'Image.jpg',
        type: 'image/jpeg',
        uri: filePath,
    }
}

A: FormData supports simple key/value pair, it doesn't support nested data as objects from the values, so you should convert your JSON parts to strings:
let data = {
    string: "1",
    object: {
        a: 3,
        b: {
            c: 5
        }
    },
    array: [1,2,3],
    arrayComplex: [{id: 2, value: 2}, {id:3, value:3}],
    file: {
        name: 'Image.jpg',
        type: 'image/jpeg',
        uri: filePath,
    }
}
i.e.:
let FormDataReq = new FormData();

FormDataReq.append('arrayComplex', JSON.stringify(data.arrayComplex));

And then send your FormData as part of request's body:
fetch('https://url-to-api-endpoint.com', {
  method: 'POST',
  body: FormDataReq,
}).then((response) => response.json())
.then((result) => {
  console.log('Success:', result);
})
.catch((error) => {
  console.error('Error:', error);
});


text:
Q: Bootstrap collapsing navbar menu vertically after having centered items I have an issue with my bootstrap navbar. I recently found a way to center items in the navbar but the fact is that when the menu is collapsed these items stay horizontally aligned instead of vertically.
Here is what i have at the moment :

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    Toggle navigation

                </button>

                        link

                        link

                        link

                        link

                        link

and the important css :
.center .nav,
 .center .nav > li
{
    float:none;
    display:inline-block;
    /*display:inline; /* ie7 fix */
    /*zoom:1; /* hasLayout ie7 trigger */
    vertical-align: top;
}

.center .navbar-inner {
    text-align:center;
}

.center .dropdown-menu {
    text-align: left;
}

With this I have my items centered in the navbar but displayed horizontally in the collpased menu. I want to have some help to change it in order to get back the classic behaviour ( i mean vertically ) of bootstrap collapsing menu without altering the centered items when the menu is not collapsed.

A: Simply apply your rules inside of a media query:
@media (min-width: 767px) {
   YOUR RULES HERE
}

See working example snippet.

@media (min-width: 767px) {
  .center .nav,
  .center .nav > li {
    float: none;
    display: inline-block;
    vertical-align: top;
  }
  .center .navbar-inner {
    text-align: center;
  }
  .center .dropdown-menu {
    text-align: left;
  }
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />

          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
            Toggle navigation

          </button>

              link

              link

              link

              link

              link

A: Maybe, try to change class .dropdow-menu (how's unset) by .navbar-header which have the dropdown-menu.


text:
Q: continuously variable frequency doubler I need a tachometer for a motorcycle that 'fires' the ignition every cycle (360 degrees).  Tachs are cheap for 4 cylinder applications (fire twice per cycle, every 180 degrees) but very expensive for motorcycles.  If I could double the frequency of the pulses from the ignition, it would appear to be a 4 cylinder ignition, and I could use an inexpensive automobile tach (which have a 4-6-8 cylinder setting).  I see circuits for doubling a fixed frequency, but the ignition frequency is pretty continuously varying.  Any ideas?

A: This is a easy problem for a microcontroller.  The micro receives the tach pulses and measures the period between them.  When it gets a pulse, it emits one right away, then another half way thru the interval.  The new interval could be a little different, but I doubt most tachs are going to care that much.  Besides, the motorcycle engine just can't change speed that fast.
If you really need smooth output pulses, you can do a phase error servo.  The output pulses are produced from a firmware oscillator which can be tweaked up and down in period.  A accumulated phase error is kept, which is used to slowly vary the output frequency up and down.  For each incoming pulse, the phase error is bumped up by 2.  For each output pulse, it is bumped down by 1.  The result is a error value that tells you how far behind the output pulses are from the input.  Periodically (can be based on just a internal timer), the output pulses period is decreased when the error value is positive and increased when it is negative.  You adjust the increase and decrease value based on the maximum amount the engine can reasonably change speed.

A: I improvised a drawing below. The Idea is that you

*

*might need to extend the input pulse with a monoflop

*slightly delay the input pulse

*fire a 2nd short monoflop

*use these two signals as an input in an EOR stage

Input pulse (after optionally extending it with a mono):
|           ________________
|          /                \
+----------                  ----------

Delay the input pulse and fire a monoflop:
|                   ___
|                  /   \
+------------------     ---------------

Exclusive OR'ing these signals results in a double pulse:
|           ______     _____
|          /      \   /     \
+----------        ---       -----------


text:
Q: Host is unresolved in LAN Im getting a IOExeption 'Host is unresolved' on HttpPost. The Endpoint in this case a a computer on my LAN with a webservice. (http://pc259:8080/test/service.asmx). Im using WIFI to my LAN. Does Android know to to resolved computernames?
StringEntity se = new StringEntity(xmlDataToSend);
se.setContentType("text/xml");
HttpPost httppost = new HttpPost(endPoint);
httppost.setHeader("Content-Type","application/soap+xml");
httppost.setEntity(se);
HttpClient httpclient = new DefaultHttpClient();
Log.i(TAG, " - Before execute");
httpResponse = (BasicHttpResponse) httpclient.execute(httppost);

A: You can get Java to resolve NetBIOS names by using the JCIFS library. You can get it from http://jcifs.samba.org/. Add that to your project and then use code like this to convert a host name to an IP address.
import jcifs.netbios.NbtAddress;
...
NbtAddress nbtAddress = NbtAddress.getByName(hostname);
InetAddress address = nbtAddress.getInetAddress();
String ipAddress = address.getHostAddress();

A: Most likely pc259 is not defined in you DNS server, but is a NetBios hostname (see http://en.wikipedia.org/wiki/NetBIOS#NetBIOS_name_vs_host_name).
I don't think Android can resolve these kind of hostnames - you'll need to add this computer to the DNS repository.


text:
Q: What's the benefite of binding functions to variables in php 5.3 $test = function(){};

It's a new feature of php ver 5.3. I'm interested to know what's the reason.

A: This is called variable functions in php. We can define some functions and can assign it into variables.This means that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. Among other things, this can be used to implement callbacks, function tables, and so forth.
<?php
function foo() {
    echo "In foo()
\n";
}

function bar($arg = '')
{
    echo "In bar(); argument was '$arg'.
\n";
}

// This is a wrapper function around echo
function echoit($string)
{
    echo $string;
}

$func = 'foo';
$func();        // This calls foo()

$func = 'bar';
$func('test');  // This calls bar()

$func = 'echoit';
$func('test');  // This calls echoit()
?>

Source
Check these too


text:
Q: Problems to upload photos in Object detection google API I'm trying to upload photos to train my model for object detection API, but I couldn't click on the Import button even I uploaded the photos, in Image classification it works but here, I couldn't, someone knows the answer, please? I tried as well to upload the CSV file from my bucket, but I got so many errors !

line 13: Expected 11 columns, but found 2 columns only

A: Your CSV file isn't formatted correctly (Missing 9 out of the 11 necessary columns). You are missing the identification label as well as the bounding box coordinates for an object within the image.
Please refer to this documentation as it provides the correct CSV formatting guidelines for AutoML Vision Object Detection.

A:
I had 4 columns instead of 12, so I think mainly these are borders, however,
please check the whole sequence, cuz I eventually found out that I link buckets incorrectly.
gs://folder/video.mp4,name,(one empty space),20.50(timestamp),0.8,0.8,0.9,0.8,0.9,0.9,0.8,0.9(object detection "square" borders)
inf timestamp was working with label detection, but not with object, but with correct timestamp and empty one is proceeding. Again, one line of code is looking like that:
gs://folder/video.mp4,name, ,20.50,0.8,0.8,0.9,0.8,0.9,0.9,0.8,0.9


text:
Q: Python csv reader for row in reader - what does the throwaway underscore represent in this code? I'm reading data from a csv file. I get that 'row' is the variable that represents the loop I am going through, but what is the "_" that is being thrown away here?
for row in csv_reader:
  _, Student.objects.get_or_create(
      first_name=row[0],
      last_name=row[1],
      email=row[2],
      organisation=row[3],
      enrolled=row[4],
      last_booking=row[5],
      credits_total=row[6],
      credits_balance=row[7],
      )

For example, this code also works:
for row in csv_reader:
  Student.objects.get_or_create(
    first_name=row[0],
    last_name=row[1],
    email=row[2],
    organisation=row[3],
    enrolled=row[4],
    last_booking=row[5],
    credits_total=row[6],
    credits_balance=row[7],
    )

So I could also ask, why is the "_," even there in the first place?
I found the idea in another question's answer but the purpose of the underscore was not explained.
UPDATE NOTE
So it seems that I made a slight error when copying the original code from another post. The original code was:
  for row in csv_reader:
    _, result = Student.objects.get_or_create(...

which makes more sense now that I see this answer. The code is meant to be unpacking the RESULT of the get_or_create and throwing away one value of the tuple. I mistakenly did not copy the result variable as part of my code.

A: I have a feeling there may be a slight syntax error here.
get_or_create() returns a tuple; the object and a boolean (true if the object has been created).
An underscore is sometimes used for one of the elements in that tuple (the bool for example)
instance, _ = MyObject.objects.get_or_create()
So here _, Student.objects.get_or_create is actually valid python I just think maybe you're missing the second variable to unpack the returned tuple. If you print the type print(type(_)), it'll return "tuple" and if you print(_) you should see a tuple containing the object and the boolean.
Adding the , after _ makes _ a tuple which is why it's not giving you an error, if you remove the , it'll throw an error and if you do _,instance it'll throw an error as you'd need the = Student.... if you're unpacking the whole tuple.

A: _ has to have been defined earlier in your code-block if that code doesn't produce a syntax-error. It could be defined outside of the loop all together, and could be a "scope"-issue with the variable.
To give you a weird example for how it can be used though, we can use it inside of another loop and just "catch" the variable and do nothing with it:
d = {1:"A", 2:"B", 3:"C"}
for _, value in d.items():
    print(value)

Output:
A
B
C


text:
Q: Error executing Scripted editor: "Error showing url: The specified location is not supported" I'm getting the following error when trying to open Scripted 0.3 from Springsource
Error showing url: The specified location is not supported
I'm using Kubuntu 12.10 64 bits and installed it using npm (sudo npm install -g scripted) with the following output:
npm http GET https://registry.npmjs.org/scripted
npm http 304 https://registry.npmjs.org/scripted
npm http GET https://registry.npmjs.org/amdefine/0.0.2
npm http GET https://registry.npmjs.org/enhanced-resolve/0.4.5
npm http GET https://registry.npmjs.org/express/2.5.11
npm http GET https://registry.npmjs.org/formidable/1.0.9
npm http GET https://registry.npmjs.org/htmlparser/1.7.6
npm http GET https://registry.npmjs.org/json5/0.1.0
npm http GET https://registry.npmjs.org/node-static/0.5.9
npm http GET https://registry.npmjs.org/sockjs/0.3.1
npm http GET https://registry.npmjs.org/when/1.6.1
npm http GET https://github.com/kdvolder/websocket-multiplex/archive/master.tar.gz
npm http 304 https://registry.npmjs.org/enhanced-resolve/0.4.5
npm http 304 https://registry.npmjs.org/htmlparser/1.7.6
npm http 304 https://registry.npmjs.org/json5/0.1.0
npm http 304 https://registry.npmjs.org/node-static/0.5.9
npm WARN node-static@0.5.9 dependencies field should be hash of <name>:<version-range> pairs
npm http 304 https://registry.npmjs.org/sockjs/0.3.1
npm http 304 https://registry.npmjs.org/express/2.5.11
npm http 304 https://registry.npmjs.org/amdefine/0.0.2
npm http 304 https://registry.npmjs.org/formidable/1.0.9
npm http 304 https://registry.npmjs.org/when/1.6.1
npm http 200 https://github.com/kdvolder/websocket-multiplex/archive/master.tar.gz
npm http GET https://registry.npmjs.org/mime/1.2.4
npm http GET https://registry.npmjs.org/qs
npm http GET https://registry.npmjs.org/mkdirp/0.3.0
npm http GET https://registry.npmjs.org/connect
npm http GET https://registry.npmjs.org/faye-websocket/0.4.0
npm http GET https://registry.npmjs.org/rbytes/0.0.2
npm http GET https://registry.npmjs.org/node-uuid/1.3.3
npm http 304 https://registry.npmjs.org/mkdirp/0.3.0
npm http 304 https://registry.npmjs.org/mime/1.2.4
npm http 304 https://registry.npmjs.org/faye-websocket/0.4.0
npm http 304 https://registry.npmjs.org/rbytes/0.0.2
npm http 304 https://registry.npmjs.org/node-uuid/1.3.3
npm http 304 https://registry.npmjs.org/connect
npm http 304 https://registry.npmjs.org/qs
npm http GET https://registry.npmjs.org/connect/-/connect-1.9.2.tgz

> rbytes@0.0.2 install /usr/local/lib/node_modules/scripted/node_modules/sockjs/node_modules/rbytes
> node-waf configure build

Checking for program g++ or c++          : /usr/bin/g++
Checking for program cpp                 : /usr/bin/cpp
Checking for program ar                  : /usr/bin/ar
Checking for program ranlib              : /usr/bin/ranlib
Checking for g++                         : ok
Checking for node path                   : not found
Checking for node prefix                 : ok /usr
'configure' finished successfully (0.104s)
Waf: Entering directory `/usr/local/lib/node_modules/scripted/node_modules/sockjs/node_modules/rbytes/build'
[1/2] cxx: src/binding.cc -> build/Release/src/binding_1.o
npm http 200 https://registry.npmjs.org/connect/-/connect-1.9.2.tgz
[2/2] cxx_link: build/Release/src/binding_1.o -> build/Release/binding.node
Waf: Leaving directory `/usr/local/lib/node_modules/scripted/node_modules/sockjs/node_modules/rbytes/build'
'build' finished successfully (0.959s)
/usr/local/bin/scr -> /usr/local/lib/node_modules/scripted/bin/scr
/usr/local/bin/scripted -> /usr/local/lib/node_modules/scripted/bin/scripted
scripted@0.3.0 /usr/local/lib/node_modules/scripted
├── amdefine@0.0.2
├── node-static@0.5.9
├── when@1.6.1
├── websocket-multiplex@0.1.0
├── enhanced-resolve@0.4.5
├── json5@0.1.0
├── formidable@1.0.9
├── htmlparser@1.7.6
├── sockjs@0.3.1 (node-uuid@1.3.3 faye-websocket@0.4.0 rbytes@0.0.2)
└── express@2.5.11

I can't find any log files at the moment, is there any way to fix this?


text:
Q: Connect Bluetooth 4.0 Headset I am trying to connect my bluetooth headset.
Jabra Talk 45
Specs:
Bluetooth® compliance Bluetooth® version 4.0
Supported Bluetooth® profiles Advanced Audio Distribution (A2DP) v1.2, AVRCP ABS only. Hands-free profile v1.6,
headset profile v1.2, phone book access profile (PBAB) v1.0
Supported modes EDR (2 and 3 Mb), SCO, eSCO, sniff mode
It is not shown in the list of devices.

A: You need to check user manual of "Jabra Talk 45" to make your device discoverable/connectable after powering it ON.
Once your headphones is in discoverable mode, it will be listed on the device list of your computer/smart-phone(any source device)
Once your "Jabra Talk 45" is visible, you can click on it to pair with your source device.
(Usually an LED keeps blinking when it is discoverable and gets steady after getting connected successfully)
Cheers if it helped! :)


text:
Q: Scraping the source code using VBA-Macros I need to crawl the price values from the price comparison website (product link: https://www.toppreise.ch/prod_488002.html).  I am not able to scrape. see the highlighted price in the image that I want to capture:

Please help me how to crawl this page.
PS: toppreise.ch will not be accessible in many countries so use VPN
I am using the below code:
Private Sub SiteInfo_Click()
Dim strhtml
On Error Resume Next
ThisWorkbook.Sheets("Data Mining").Activate
Sheets("Data Mining").Range("B1").Select
Set xmlHttp = Nothing
Set xmlHttp = CreateObject("MSXML2.ServerXMLHTTP.6.0")

    StrUrl = ""
    StrUrl = Sheets("Data Mining").Range("B1").Value
    xmlHttp.Open "GET", StrUrl, False
    xmlHttp.Send
    strhtml =xmlHttp.responseText
    END Sub

When I run above code I am only getting below response text . It doesn't gives the whole page. (You can check the source code by using the product link or view here https://www.dropbox.com/s/ah80jt7a25xcicp/source%20code.txt?dl=0 )
<html><head>
        <script type="text/javascript" src="//en.toppreise.ch/js/tpjs.js"></script>
        <script type="text/javascript" src="//en.toppreise.ch/js/afxp.js"></script>
        <script type="text/javascript" src="//en.toppreise.ch/js/jquery.min.js"></script>
        <script type="text/javascript" src="//en.toppreise.ch/js/jquery-ui-autocomplete.min.js"></script>
    </head><body>...

A: This code works, Thanks SIM
Sub Get_Price()
Dim HTTP As New XMLHTTP60, HTML As New HTMLDocument
Dim post As HTMLDivElement

With HTTP
.Open "GET", "https://www.toppreise.ch/index.php?a=488002", False
.send
HTML.body.innerHTML = .responseText
End With

For Each post In HTML.getElementsByClassName("altLinesOdd")
With post.getElementsByTagName("a")
     If .Length Then R = R + 1: Cells(R, 1) = .Item(0).innerText
End With
With post.getElementsByClassName("spaceVert nobreak")
     If .Length Then Cells(R, 2) = .Item(0).innerText
End With
Next post
End Sub


text:
Q: Try & Except, maneira correta A maneira correta de usar o try e except no Python é como?
try:
  variavel = funcao()
except:
  return 'error'

Ou eu faço:
variavel = funcao() e depois eu trato, dessa forma
variavel = funcao()

try:
 return variavel
except:
 return 'error'

Tanto faz? Sou iniciante no Python, e no PHP nunca usei try e catch

A: Primeiro o correto é nunca usar um except sem nada - em Python 3 (que é o que você deveria estar usando - Python 2 é incompatível e é uma linguagem no limite pra sair de linha -use Python 3), "except" vazio é erro de sintaxe.
Mesmo o except Exception - que é uma exceção que 'pega tudo' deve ser evitado,a não ser que no bloco de tratamento de erro esteja incluído uma forma de registrar o erro para análise posterior.
A forma correta é: ter a menor quantidade de código possível dentro do bloco try, e ter as exceções mais específicas possível no Except. A ideia nunca é "fingir que não viu o erro" - e sim, impedir que o programa pare dentro de uma situação que já estava prevista e que não depende do programa: um timeout de rede, uma resposta de indisponível de um servidor, um arquivo protegido contra escrita, uma conta feita com números providos pelo usuário que chega numa divisão por zero, etc...
E por fim, quanto a sua pergunta específica - não tem tanta importância assim, mas é melhor você manter menos pontos de return dentro de uma função, por que fica mais fácil entender o que está acontecendo para debugar e dar manutenção -
então:
try:
    resultado = funcao()
except ValueError:
    resultado = "erro"

return resultado

Note como o ideal é ter exceções específicas-  se dentro da função acabar a memória disponível para o processo, isso dá um MemoryError e o programa para. Quando o programa para, o traceback vai dizer onde ocorreu o erro, e é só ir lá e corrigir o trecho que está criando um objeto maior do que é possíbel. Se fosse um Except genérico, o desenvolvedor acharia que era um ValueError, que poderia acontecer mesmo, e ia ficar horas em cima disso tentando achar o problema.


text:
Q: Conditionally formatting a cell in a pivot table based on a range of cells grouped by a Column Label Within my pivot table I currently have cells conditionally formatted- Value=1, Green and Value=0, Yellow. I would like to conditionally format based upon all the values within a row label underneath a column label equalling zero.
Because this is a pivot table, the values will be dynamic as will the number of different column labels and subcolumn labels.  I basically don't care if ALL of the items for a given row label under a specific column label = 0, but I want attention brought to the cell if it is the only one (or two or three) underneath a header that = 0.

A: I am not sure, but perhaps this is the sort of answer you want:

The default ('yellow') formula is =ISNUMBER(G3) and both rules are applied to All cells showing "Sum of C" values.
Note that as usual, pivot table will need refreshing before changes are 'recognised'.


text:
Q: Ограничение доступа к пользовательскому типу в REST API Каким образом можно предоставлять доступ только с логином и паролем определённым записям кастомного типа в WordPress? Причём, для определённого пользователя должны быть доступны только записи, которые он сам создал, если это не администратор.

A:
Каким образом можно предоставлять доступ только с логином и паролем
определённым записям кастомного типа в WordPress?

По умолчанию в ВП нельзя ограничить доступ пользователя "к определённым" записям. ВП использует политику "возможностей" используемых "ролями". См https://wordpress.org/support/article/roles-and-capabilities/
Управление доступом ролей к кастомным типам постов задаётся в register_post_type аргументами  capability_type, capabilities и map_meta_cap.
См https://wp-kama.ru/function/register_post_type#capabilities

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

Пользователи с ролью "автор" имеют возможности редактирования только своих записей.
И ещё. С версии 5.6 в ВП появилась возможность задавать пароли приложения. Это позволит не светить реальные пароли пользователей и управлять ими независимо.
См https://wp-kama.ru/handbook/rest/basic/authentication/application-passwords


text:
Q: Implement __eq__ for Python objects that contain deeply nested numpy arrays I'm having problems with numpy arrays not being comparable with == (using the semantics of np.array_equal) in the context of object attributes.
Consider the following example:
>>> import numpy as np
>>> class A:
...     def __init__(self, a):
...         self.a = a
...     def __eq__(self, other):
...         return self.__dict__ == other.__dict__
...
>>> x = A(a=[1, np.array([1, 2])])
>>> y = A(a=[1, np.array([1, 2])])
>>> x == y
Traceback (most recent call last):
  File "<ipython-input-33-9cfbd892cdaa>", line 1, in <module>
    x == y
  File "<ipython-input-30-790950997d4f>", line 5, in __eq__
    return self.__dict__ == other.__dict__
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

(ignore that __eq__ isn't perfect, it should at least check the type of other, but this is for the sake of brevity)
How would I implement an __eq__ function that handles numpy arrays being nested deep inside my object attributes (assuming everything else, such as the list in this example, compares fine with ==)? The numpy arrays might occur at an arbitrarily deep nesting level inside lists, tuples, or dicts.
I've tried coming up with a "manual" implementation of a recursive eq function that applies == to all attributes, and uses np.array_equal whenever it comes across a numpy array, but this is trickier than expected.
Does anybody have a suitable function, or an easy workaround?

A: If it is an option to change the objects x and y, you could overwrite the __eq__ method of np.ndarray according to your preference.
class eqarr(np.ndarray):
    def __eq__(self, other):
        return np.array_equal(self, other)

class A:
     def __init__(self, a):
         self.a = a
     def __eq__(self, other):
         return self.__dict__ == other.__dict__

x = A(a=[1, eqarr([1, 2])])
y = A(a=[1, eqarr([1, 2])])
x == y

This resutls in True.
If this is not possible, the only solution I can think of at the moment is to actually implement a recursive equality check function. My attempt is the following:
def eq(a, b):
    if not (hasattr(a, '__iter__') or type(a) == str):
        return a == b

    try:
        if not len(a) == len(b):
            return False

        if type(a) == np.ndarray:
            return np.array_equal(a, b)
        if isinstance(a, dict):
            return all(eq(v, b[k]) for k, v in a.items())
        else:
            return all(eq(aa, bb) for aa, bb in zip(a, b))
    except (TypeError, KeyError):
        return False

class A:
     def __init__(self, a):
         self.a = a
     def __eq__(self, other):
         return eq(self.__dict__, other.__dict__)

With your examples and all those that I came up with it worked. The solution should be applicable whenever the nested ojects have an __iter__ and a __len__ attribute.
I hope that I accounted for all possible errors, but you may need to adjust the code a little bit to make it absolutely fail-safe.
If you find a counterexample, please provide it as a comment. I am sure the code can be adjusted accordingly.
The performance of eq may not be great, but I do not know whether this is a major concern to you.
If numpy arrays are rather rare in your hierarchy (and often close to the top), you could always try a normal comparison first. This could look like the following:
def eq(a, b):
    try:
        return np.all(a == b)
    except ValueError:
        pass

    try:
        if not len(a) == len(b):
            return False

        if type(a) == np.ndarray:
            return np.array_equal(a, b)
        if isinstance(a, dict):
            return all(eq(v, b[k]) for k, v in a.items())
        else:
            return all(eq(aa, bb) for aa, bb in zip(a, b))
    except (TypeError, KeyError):
        return False


text:
Q: Skipping hover animation while reloading HTML and hovering on a element Context:
I'm making a todo web application in ASP.NET Core MVC where I load the list of todos from an API using a partial view and AJAX. Each todo item has a button which toggles its done state by calling the API and reloads the partial view on success.

The Problem:
I have a CSS rule which expands the toggle button while hovering over a specific todo item:
.todoitem .toggle-button {
    width: 10px;
    transition-duration: 0.3s;
}

.todoitem:hover .toggle-button {
    width: 60px;
}

With this, when the toggle button is pressed and subsequently the partial view reloaded, the hover animation is being replayed which is not the awaited result. Here's how it looks like:

What I want is for the toggle button to stay expanded upon reloading the partial view.

What I tried:
My initial guess for where this problem came from was that the page initially loads and displays in the "default" state, before the styles for hover are processed. Thinking that, what I tried was passing in the clicked todo's ID as a parameter into the partial view and dynamically assigning a loaded-while-hovered class to the corresponding todo item while reloading. With this I could basically negate the hover and default styles and ensure that the page would load with the toggle button expanded and shrink it while the todo item is not(:hovered). The code then looked something like this:
.todoitem .toggle-button {
    width: 10px;
    transition-duration: 0.3s;
}

.todoitem:hover .toggle-button {
    width: 60px;
}

.todoitem.loaded-while-hovered .toggle-button {
    width: 60px;
}

.todoitem.loaded-while-hovered:not(:hover) .toggle-button {
    width: 10px;
}

This however, again did not work as expected and produced exactly the same effect.
What causes this and what can I do against it? Can it be done without JavaScript? (JS is fine though)


text:
Q: How to update wireshark interface list? I installed Wireshark(v1.10.6) from software centre. In the interface list, only bluetooth is shown. I wanted to capture packets that are sent & received from wireless connection.
How should I do it? Is there any way to add wireless and wired connections into this list?

A: Usually you can't capture network interfaces as normal user, you need administrative rights to access the network layer.
You can try running wireshark as "root" and check if the interfaces are shown.
P.S.: You should use the root account only for testing purpose. Pay attention to the messagebox that will show up when you run wireshark as root.

A: Try quitting Wireshark, doing
sudo dpkg-reconfigure wireshark-common

from the command line, and restarting Wireshark.  That should give you permission to access "normal" network adapters without having to run Wireshark as root, which, as sinclair notes, you really don't want to do - to quote the doc/README.packaging file in the Wireshark source:
WIRESHARK CONTAINS OVER TWO MILLION LINES OF SOURCE CODE. DO NOT RUN
THEM AS ROOT.


text: Q: Android Amplify - Change the directory of generated configuration JSON file I am new in using AWS Amplify and I followed this guide. I didn't know that the line 'app/src/main/res' should already be pointing at my Android Project's res folder and instead I just copied paste the directory literally that's from the guide. Is there a way to change it? Thanks!


text:
Q: How get needed rows from 3 table in Laravel 5.5 I have 3 tables, Order, Products, Order_Products. I need get all field from order and products, thats ok using hasManyThrough(). But i need 1 more field from Order_products. How can i get this field ?
public function products()
{
   //in order model
 return $this->hasManyThrough('App\Models\Product','App\Models\OrderProduct','order_id','id','id','product_id');
}

using sql i need query like
SELECT
    products.*, order_products.order_id, order_products.count as order_count
FROM
    products
INNER JOIN order_products ON order_products.product_id = products.id
WHERE
    order_products.order_id = 2

A: You can access intermediate table fields by using pivot attribute on model.
Lets say you have product, Then you can access count field of orders_products
$product->pivot->count;


text:
Q: Generalization to higher dimensions of a statement about plane triangles Let $\Delta=\Delta ABC$ be a plane triangle with area $F_\Delta$ and let $P$ be a point in $\Delta$. Draw lines through $P$  parallel to the sides of $\Delta$; then $\Delta$ is decomposed into three parallelograms and three triangles $\Delta_1$, $\Delta_2$ and $\Delta_3$ (all similar to $\Delta$). For the respective areas $F_1,F_2,F_3$ of these triangles, the formula
$$\sqrt{F_\Delta}=\sqrt{F_1}+\sqrt{F_2}+\sqrt{F_3}$$ holds. Is there a generalisation of this to higher dimensions, and what is its precise formulation?


text:
Q: Trimming whatever that comes after a certain symbol and extract a certain number of sections from string I have a column containing numbers like this '12.34.56.78', '23.45.67.89' etc. and the numbers always come in four sections. However,I am only intersted in the first three sections. If the number of digits in each section is always stable, the solution would be to use SUBSTRING, however, numbers such as '123.456.78.9' is expected as well. Therefore, the only common rule that can be used is the dots.
Is there any way to cut off whatever that comes after the third dot?

A: Another option is to use the split_part function. In this function you specify 1. the string of interest, 2. your delimiter, in your case the ".", and 3. which part of the fragmented string you are interested in returning. In your case you will always have four string fragments.
Here is split_part in practice:
SELECT
      '12.34.56.78' AS original_string
    , SPLIT_PART(original_string,'.',1) AS string_fragment_1
    , SPLIT_PART(original_string,'.',2) AS string_fragment_2
    , SPLIT_PART(original_string,'.',3) AS string_fragment_3
    , SPLIT_PART(original_string,'.',1)::varchar || '.' || SPLIT_PART(original_string,'.',2) || '.' || SPLIT_PART(original_string,'.',3) AS final_output.

I believe the last column returns your desired output. Hope this helps!

A: You should be able to accomplish this like so:
select original_num,
       substring(original_num, 1, (length(original_num) - position('.' in reverse(original_num)))) as new_num
  from a_table;

with an example on DB Fiddle.

A: We can try using a regex replacement here:
SELECT num, REGEXP_REPLACE(num, '\.\d+$', '') AS num_out
FROM yourTable;


text:
Q: Store JSON Blobs in MySQL or S3 I'm going to be storing some specification data as JSON strings (height, weight etc) -- one per product. The data will be accessed very infrequently (once initially and then only again if I change an algorithm and need to update the summary metrics). My plan is to store a reference to the JSON string's location in a MySQL database, along with the rest of the product data.
Each blob is around 6k and, assuming I'm going to store 10m of them, my tests indicate that the size of a MySQL table with these 10m rows would be ~70GB (including an id column with an index). Storing them in S3 would work out slightly cheaper but it's low in both cases.
Are there any disadvantage to putting them in MySQL. Would the one very large table have an impact on the performance of the rest of the server?

A: I recommend, you

*

*Compress them: This is the ideal scenario to trade stoage space against decompression CPU cycles. JSON typically is highly compressible, say 2:1 as a minimum going up to 10:1

*Store them directly in a separate MyISAM table: This way it's guaranteed not to interfere with your other tables


text:
Q: Only get post types based on support I am trying to retrieve a list including both builtin and custom post types:
$post_types = get_post_types(array(
  'public' => TRUE,
), 'objects');

The above almost works, but I would like to exclude the attachment from this list, only returning post types with specific support such as editor, title and thumbnail. Is this possible?

A: I found out that get_post_types_by_support() seems to be the solution to get the desired result:
$post_types = get_post_types_by_support(array('title', 'editor', 'thumbnail'));

The above will return post, page and any custom post type that supports title, editor and thumbnail.
Since this will also return private post types, we could loop through the list and check if the type is viewable at the frontend. This can be done by using the is_post_type_viewable() function:
foreach ($post_types as $key => $post_type) {
  if (!is_post_type_viewable($post_type)) {
    unset($post_types[$post_type]);
  }
}

A: get_post_types() accepts an array of arguments to match the fields of a post type object. So, you could do something like this (not tested):
$post_types = get_post_types(array(
  'public'   => true,
  'supports' => array( 'editor', 'title', 'thumbnail' )
), 'objects');

Unfortunately, you can not set someting like "exclude" in this function, and also you get only post types that support exactly 'editor', 'title', 'thumbnail', no more and no less.
Or you could use get_post_types_by_support() (only for WP 4.5 and greater. Also, note that you can not exclude specific post types with this function either, but for the specific case of support for editor, title, thumbnail, attachment post type will be excluded in most cases).
$post_types = get_post_types_by_support( array( 'editor', 'title', 'thumbnail' ) );

If you want something that will work in any case, I would try to get post types based in a wider criteria, then build your own array, something like this:
$_post_types = get_post_types_by_support( array( 'editor', 'title', 'thumbnail' ) );

$post_types = [];

foreach($_post_types as $post_type) {
    // In most cases, attachment post type won't be here, but it can be
    if( $post_type->name !== 'attachment' ) {
        $post_types[] = $post_type;
    }
}

A: The simplest approach for the OP's question would be to just unset 'attachment' from the returned array;
$post_types = get_post_types(array('public' => TRUE,), 'objects');
unset($post_types['attachment']);

While not as elegant as the other solutions it has the least overhead.


text:
Q: Isomorphism of $\mathfrak{gl}_n(K)/\mathfrak{sl}_n(K)$ to $K$. Let $\mathfrak{gl}_n(K)$ be the general linear Lie algebra over a field $K$ and $\mathfrak{sl}_n(K)$ the special linear Lie algebra over $K$.
I have to show that the quotient $\mathfrak{gl}_n(K)/\mathfrak{sl}_n(K)$ is
isomorphic to the onedimensional abelian Lie algebra.
I know that this abelian Lie algebra is isomorphic to $K$ itself, so I have
to find an isomorphism of the quotient to $K$.
I think it has something to do with the trace $$tr:\mathfrak{gl}_n(K)/\mathfrak{sl}_n(K)\rightarrow K,$$
but I can't see if this is an isomorphism.
Any help or advice is very much appreciated!

A: The kernel of $\operatorname{tr}\colon\mathfrak{gl}_n(K)\longrightarrow K$ is $\mathfrak{sl}_n(K)$ and its range is $K$. Therefore, it induces a Lie algebra isomorphism from $\mathfrak{gl}_n(K)$ onto $K$.


text:
Q: Задача: сортировка рациональных дробей В этой задаче вам нужно научиться сортировать не числа, а рациональные дроби.
Входные данные
Программа получает на вход n дробей: сначала задается число n,
потом идет n строк, в каждой из которых записана одна дробь.
Дробь записана в виде a/b , где a и b — натуральные числа.
Выходные данные
Программа должна вывести список этих дробей в порядке неубывания.
Если в списке есть две равные дроби то раньше выводится дробь, у которой меньше числитель.
ПРИМЕР
ввод
3
4/2
2/6
1/2
вывод
2/6
1/2
4/2

Вот моё решение , но оно не проходит тесты и идей почему - нет
struct Point {
    string a;
    double b;
};

struct Point {
    string a;
    double b;
};

bool comp(Point a , Point b) {
    if(a.b == b.b) {
            ll cur1 = 0;
            ll cur2 = 0;
        for(int i = 0; i < a.a.size();i++) {
            if(a.a[i] == '/') {
                break;
            }
            cur1+= (a.a[i]-48)*10;
        }
        for(int i =0 ; i < b.a.size();i++) {
            if(b.a[i] == '/') {
                break;
            }
            cur2+= (b.a[i]-48)*10;
        }
        return cur1 < cur2;
    }
    return a.b < b.b;
}
int main() {
    int n;
    cin >> n;
    vector<Point> a(n);
    for(int i =0 ;i < n;i++) {
        string s;
         int f,l;
        scanf("%d/%d" , &f , &l);
        s = to_string(f) +"/" + to_string(l);
        a[i].a = s;
        double ff = f;
        double l2 = l;
        double res = ff/l2;
        a[i].b = res;
    }
    sort(a.begin(),a.end(),comp);

    for(auto x : a) {
        cout << x.a << endl;
    }

A: Ну попробуйте это:
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

struct ratio
{
    int q,d;
};

bool operator < (const ratio& a, const ratio& b)
{
    int q = a.q*b.d, d = a.d*b.q;
    if (q < d) return true;
    if (q > d) return false;
    return a.d < b.d;
}

istream& operator >> (istream& is, ratio& r)
{
    char c;
    is >> r.q >> c >> r.d;
    return is;
};

int main()
{
    vector<ratio> v;
    int N;
    cin >> N;
    for(int i = 0; i < N; ++i)
    {
        ratio r;
        cin >> r;
        v.push_back(r);
    }
    sort(v.begin(),v.end());
    for(auto r: v)
        cout << r.q << "/" << r.d << endl;
}


text:
Q: ASP.Net Razor View I may be doing it wrong... so please correct me if i am.
I've pulled my Last.FM data from their RestAPI and cached it (to be refreshed only if the cache is greater than 30 minutes old), and from there i've loaded it into an enumerated list of tracks.
I'm attempting to drop that logic in the Razor display, and never managed to make it work with more than just the foreach and if (item.image...)..., adding in the logic to drop the divs has caused razor to loose track of the closing bracket for the foreach.
Am I making this too complicated?

            @* Iterate over the Last.FM data and display it in an attractive format *@
@foreach (var group in Model.Select((x, i) => new { Group = i / 4, Item = x })
                            .GroupBy(x => x.Group)) {

    foreach(var x in group) {
        if (x.item.image != null) {

        } else {

        }

@Html.Raw(x.item.name.ToString())

    }

 }

after following Equiso's suggestion, i'm getting an odd scoping issue where either X is not in the current scope, or x does not contain a property for image...
@model IEnumerable<CCBlog.Classes.LastFmWrapper.Track>

and this is part of the LFM Wrapper class --- that i'm modeling the data after
 public struct Track
        {
            public string artist { get; set; }
            public string name { get; set; }
            public string album { get; set; }
            public string image { get; set; }
        }

I call shenanigans!

A: If you are trying to display the items in groups of 4 you could do somethig like this
@foreach (var group in Model.Select((x, i) => new { Group = i / 4, Item = x })
                            .GroupBy(x => x.Group)) {

    foreach(var x in group) {
        if (x.Item.image != null) {

        } else {

        }

@Html.Raw(x.Item.name.ToString())

    }

 }

or you could create a ViewModel that get the items grouped already.


text:
Q: Android Intent in Dialog box I'm new android developer so I need your help. I'm making a app in which a button action open a dialog box. Dialog box has a button. Can i intent on the button action? Kindly give some good possible ways. Thanks

A: you want to handle the "Ok" event and perform some action.
You have a method to handle the dialog.
public void displayAlertToChangeActivity(){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("title");
alert.setMessage("massage");

alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
  public void onClick(DialogInterface dialog, int whichButton) {
   //Do something here where "ok" clicked and then perform intent from activity context
   Intent intent = new Intent(MyActivity.this, MyNextActivity.class);
   MyActivity.this.startActivity(intent);

}
});

alert.show();

}


text:
Q: Autofac Mediatr not find My problem
My mediatr Module
public class MediatorModule : Autofac.Module
{

    protected override void Load(ContainerBuilder builder)
    {
        builder
            .RegisterAssemblyTypes(typeof(IMediator).GetTypeInfo().Assembly)
            .AsImplementedInterfaces();

        builder.RegisterAssemblyTypes(typeof(Get).GetTypeInfo().Assembly)
            .As(o => o.GetInterfaces()
                .Where(i => i.IsClosedTypeOf(typeof(IAsyncRequestHandler<,>)))
                .Select(i => new KeyedService("Handler", i)));

        builder.Register<SingleInstanceFactory>(context =>
        {
            var c = context.Resolve<IComponentContext>();
            return t => c.Resolve(t);
        });

        builder.Register<MultiInstanceFactory>(context =>
        {
            var c = context.Resolve<IComponentContext>();`
            return t => (IEnumerable<object>)c.Resolve(typeof(IEnumerable<>).MakeGenericType(t));
        });

        builder
            .RegisterGenericDecorator(
                typeof(MediatorDecorator<,>),
                typeof(IAsyncRequestHandler<,>),
                "Handler");
    }
  }
}

Autofac.Core.Registration.ComponentNotRegisteredException was unhandled by user code
HResult=-2146233088
Message=The requested service 'MediatR.IAsyncRequestHandler`2[[SCA.Prospects.Core.Application.Prospect.Crear+Command, SCA.Prospects.Core.Application, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null],[MediatR.Unit, MediatR, Version=2.1.0.0, Culture=neutral, PublicKeyToken=null]]' has not been registered. To avoid this exception, either register a component to provide the service, check for service registration using IsRegistered(), or use the ResolveOptional() method to resolve an optional dependency.

Source=Autofac

A: Look like you might be missing
  builder.RegisterType<Mediator>().As<IMediator>();

Source (search for Autofac setup)  https://github.com/jbogard/MediatR/wiki


text:
Q: Only last record is displaying in Ajax sent from Struts action This is my code to generate data table in JSP. In my Struts action class I've used list that has one object which contains two records but in my JSP its displaying only last record in the object
Struts action class:
 @ParentPackage("json-default")
        public class StrutsPaginationAction extends ActionSupport {

            private static final long serialVersionUID = 1L;
            private int iTotalRecords;
            private int iTotalDisplayRecords;
            private String sEcho;
            private String sColumns;
            private List<SmsDTO> aaData;
            private List<SmsDTO> personsList;
        DBCLass d=new DBCLass();

            public StrutsPaginationAction() {

                SmsDTO smsDTO=new SmsDTO();

                    **personsList=d.smsResult();**

                System.out.println(personsList.size());
                setiTotalDisplayRecords(personsList.size());

                setiTotalRecords(personsList.size());
                setAaData(personsList);

            }

            @Action(value = "/strutsPaginationAction", results = { @Result(name = "success", type = "json") })
            public String execute() throws Exception {
                return ActionSupport.SUCCESS;
            }

            public List<SmsDTO> getPersonsList() {
                return personsList;
            }

            public void setPersonsList(List<SmsDTO> personsList) {
                this.personsList = personsList;
            }

            public int getiTotalRecords() {
                return iTotalRecords;
            }

            public void setiTotalRecords(int iTotalRecords) {
                this.iTotalRecords = iTotalRecords;
            }

            public int getiTotalDisplayRecords() {
                return iTotalDisplayRecords;
            }

            public void setiTotalDisplayRecords(int iTotalDisplayRecords) {
                this.iTotalDisplayRecords = iTotalDisplayRecords;
            }

            public String getsEcho() {
                return sEcho;
            }

            public void setsEcho(String sEcho) {
                this.sEcho = sEcho;
            }

            public String getsColumns() {
                return sColumns;
            }

            public void setsColumns(String sColumns) {
                this.sColumns = sColumns;
            }

            public List<SmsDTO> getAaData() {
                return aaData;
            }

            public void setAaData(List<SmsDTO> aaData) {
                this.aaData = personsList;
            }
        }

My Ajax code:

Struts 2 pagination using DataTables

                    Phone
                    Name
                    Ref

A: This is the problem with database code.... previously i was instantiate object inside loop that is the reason its repeated
 public ArrayList<SmsDTO> getReulst() {
            /*ResultSet rs = null;
            Connection conn = null;
            PreparedStatement pstmt = null;
            ArrayList<SmsDTO> ar = new ArrayList<SmsDTO>();
            SmsDTO sms = null;
            try {

                conn = getConnection();
                String query = "select pt.P_MOBILE,st.S_FIRSTNAME,st.REF_ID  from parent_info pt join student_info st on pt.REF_ID = st.REF_ID  where st.S_CLASS_TO_JOIN = 10;";
                pstmt = conn.prepareStatement(query); // create a statement
                rs = pstmt.executeQuery();
                // extract data from the ResultSet
                while (rs.next()) {

sms = new SmsDTO();
-------------------

                    long phone = rs.getLong(1);
                    sms.setPhone(phone);
                    String student_name = rs.getString(2);
                    sms.setStudentname(student_name);
                    String ref = rs.getString(3);
                    sms.setRef(ref);
                    ar.add(sms);

                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    rs.close();
                    pstmt.close();
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            return ar;*/
    }
    }


text:
Q: How to check Email Already exists in AWS Cognito? I am using AWS Cognito for signin/signup. We have two step from.
1) It will ask for email.
2) If email already exists then it will ask Password or otherwise it will say create password. Button on this step displayed based on the above condition either Login or Register.
Here after user enters email, I need a way to check in cognito with AWS javascript SDK to check email already registered or not.
Thanks,

A: Amazon Amplify makes the signIn and signUp process very straightforward with the Auth importation from aws-amplify in Angular/React.
On my login page I ask every user to sign up whether or not their email is alrealdy stored in the user pool. If a user is registered, Cognito raises a "UserExistsException" exception which can be catch in the Auth.signUp promise like so :
public cognitoSignUp(username, password, email){
    Auth.signUp({
      username,
      password,
      attributes: {
          email,
      },
      validationData: []
      })
      .then(data => {
        console.log(data)
      })
      .catch(error => {
        //The user has already registered so go to the SignIn method
        if(error['code'] === "UsernameExistsException"){
          this.cognitoSignIn(username, password);
        }
        else{
          console.log(error)
        }
      });
   }
Hope that my answer was useful.

A: It's changed for SDK v3 - you need to check for e.name instead of e.code
Specific API reference
Code sample...
try {
    const existingUser = await cognito.send(
        new AdminGetUserCommand({
            UserPoolId: USER_POOL_ID,
            Username: newUserEmail
        })
    );

    if (existingUser) {
        // The user already exists
    }
} catch (adminGetUserError: any) {
    if (adminGetUserError.name && adminGetUserError.name === "UserNotFoundException") {
        // The user does not exist
    } else {
        // It was another type of error
        throw (adminGetUserError);
    }
}

A: *

*If you want to check if user exists on Front-end with aws amplify, i found the answer here https://github.com/aws-amplify/amplify-js/issues/1067
 userExist(email: string) {
    return Auth.signIn(email.toLowerCase(), '123').then(res => {
        return false;
    }).catch(error => {
     const code = error.code;
     console.log(error);
     switch (code) {
         case 'UserNotFoundException':
             return !this.redirectToRegister(email);
         case 'NotAuthorizedException':
             return true;
         case 'PasswordResetRequiredException':
           return !this.forgotPassword(email);
         case 'UserNotConfirmedException':
             return !this.redirectToCompleteRegister(email);
         default:
             return false;
     }
   });
 }

*If you want to check on server side with nodeJS if the user is free and doesn't already exist
 checkIfUserDoesntExist(email) {
 return new Promise(async (resolve, reject) => {
     const payload = {
         ClientId: configCognito.APP_CLIENT_ID,
         AuthFlow: "ADMIN_NO_SRP_AUTH",
         UserPoolId: configCognito.USER_POOL_ID,
         AuthParameters: {
             USERNAME: email,
             PASSWORD: "123",
         }
     }
     try {
         await (new AWS.CognitoIdentityServiceProvider()).adminInitiateAuth(payload).promise();
         reject(); // very unlikely
     } catch (e) {
         console.log("checkIfUserDoesntExist error", e);
         switch (e.code) {
             case 'UserNotFoundException':
                 resolve();
             case 'NotAuthorizedException':
             case 'PasswordResetRequiredException':
             case 'UserNotConfirmedException':
             default:
                 reject();
         }
     }
   });
 }

A: Just change "prevent user Existence error" to "legacy" in Security configuration of Cognito userpool, Then it will trigger errors for Auth.forgetPassword(Username), Using those error we can find weather user is there or not


text:
Q: Enter double space to replace comma in multiautocompletetextview I want to add comma when I enter double space from keyboard in multiautocompletetextview. I search lots of thing in google. But can't reach my goal. I want to replace comma for double space entering by user.
So obviously, I must have to write something logic in ontextChange() or OnAfterTextChanged() in addtextwatcher listener.but i do't got event of after add 2 space.
I have already used comma tokenizer when select word from list.but i want to add comma when user entering double space using keypad.
Thanks in advance

A: Try like this, I have not tried this code
boolean userPressedKey = false ;
int spaceCount = 0;

yourEditText.addTextChangedListener(new TextWatcher() {
    public void afterTextChanged(Editable s) {
        userPressedKey = false ;
    }

    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

    public void onTextChanged(CharSequence s, int start, int before, int count) {
        userPressedKey = true;
    });

public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (userPressedKey) {
        if (keyCode == KeyEvent.KEYCODE_SPACE) {
            spaceCount ++;
            if(spaceCount == 2){
                 //append comma to the edittext here
                 Toast.makeText(MainActivity.this, "White space is clicked twice", Toast.LENGTH_LONG).show();
            }

            return true;
        }else{
            spaceCount=0;
        }
    }
    super.onKeyDown(keyCode, event);
}

A: The simplest solution i can provide you is to use String.replace(), Here is small code snippet to help you
 @Override
protected void onCreate(Bundle savedInstanceState) {

    ...

    edt.addTextChangedListener(textWatcher);
}

And TextWatcher which you are going to set on EditText
TextWatcher textWatcher = new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        edt.removeTextChangedListener(textWatcher);
        String text = edt.getText().toString();
        text = text.replace("  ", ",");
        edt.setText(text);
        edt.setSelection(text.length());
        edt.addTextChangedListener(textWatcher);
    }

    @Override
    public void afterTextChanged(Editable editable) {

    }
};


text:
Q: How can I make my page's width fixed in the mobile responsive ( HTML / CSS ) I want to make my page act just like facebook! if you try to display facebook in a mobile phone width it will stay the same as in the computer width! see the picture link :
https://imgur.com/a/uLqtrLS
but I want the responsive to be active for big widths ! I mean that if I display on a 1600px width computer it will fit in it the same thing for TV.
but not for mobile devices.
I have already used media queries but I want the width of mobile devices look  the same as the computer width

A: I believe you're looking for the CSS media query:
@media screen and (min-width: 480px) {
    /*CSS if screen size >= 480px*/
}

You also should use the <meta name="viewport" content="width=device-width, initial-scale=1"> tag in the <head> of a page to tell mobile browsers not to change the page to fit the screen.

A: Websites like facebook is using headers to define the user device. If you see it in desktop and resize it. It does not change the view so much. But if you refresh the page it redirects you to another page https://m.facebook.com  so. All you have to do is to design multiple views with fixed width.


text:
Q: Python: Os Filesize returning Garbage for /dev/core I've written a python script that goes through my filesystem (LINUX) and collects the sizes of files.
Here is the relevant bit:
for name in files:
file_name = os.path.join(root,name)
file_size = os.stat(p).st_size
if x>1000000000000:
    print x, p

So the script returns the size and path of any files greater than a terabyte in size. (There are no such files on my system --- my SSD space is 120GB.) It prints the following output:
140737486266368 /dev/core
140737486266368 /proc/kcore

But I know that these files are not this large. Why am I getting these erroneous value?
I should note that I have run the script as root. I have permission to access these files. What's going wrong here?

A: The problem is that files in /dev and /proc are not ordinary files but just views into devices and, e.g., kernel. If you check the size of that file (it is actually the same file, just symlinked), you will notice that even ls -l reports an insanely large size.
The best approach is to skip at least /dev, /proc, /sys, and /run folders (thanks, user3553031). Another possibility would be to check the file attributes - they'll reveal these are special files. However, it might be easier to just ignore the special folders.
Unfortunately, this is highly OS specific, and the above instructions are for Linux. Even different distributions may have different special files, and BSD, Windows &c. may act differently.


text:
Q: Path finding Algorithms : A* Vs Jump Point Search I know that A* is better than Dijkstra's algorithm because it takes heuristic values into account, but from A* and Jump Point search which is the most efficient algorithm for finding the shortest path in an environment with obstacles? and what are the differences?

A: Jump Point Search is an improved A* based on some conditions on the graph. Thus, if you meet these conditions (uniform-cost grid mostly), JPS is strictly better than A* (same optimality, best cases can be order of magnitudes better and worse case is probably the same complexity but with
 a slightly worse constant), but if you do not meet the conditions, you cannot use it.
The improvements of JPS over A* is basically, if you have a graph with an uniform cost function (it costs the same to go from A to B and from B to C, in the same direction), you can skip some steps in some cases and go directly from A to C without expanding nodes in B.
JPS is a pruning technique over A*, you remove cases you do not need to evaluate, because you know they will be sub-optimal. You know this because  of the uniform-cost grid condition.
Conceptually, this is equivalent to using A* over a non uniform grid, where neighbouring nodes represent how far you can go in that direction without encountering an obstacle, with the cost of the jump you performed. So if you can go 10 nodes on the right without encountering an obstacle, you can reduce this (or jump directly to) a single node with a cost of 10*c, where c is the (constant) cost to go from one node to another on the right.
The original paper can be found here.


text:
Q: Command which will tell me the last time a directory or any of its sub directories have been modified? We are trying to deprecate our old Linux home folder server. We still have a few people that are actively using it though.
Our plan is to change home folders that no one has used in the last six months to read only.
We have Mac and Windows clients accessing these shares over SMB.
So my question is:
Is there a command which will tell me the last time a directory or any of its sub directories have been modified?
Or
A list of parent directories that have been modified since a certain date?
This would tell me what users are still actively using their home folders.

A: A problem you might run into is that modifying a file in a directory doesn't necessarily change the directory time stamp.  Here's an example:
paulgear@localhost:~/tmp$ echo test1 > test1
paulgear@localhost:~/tmp$ ls -la
total 4
drwxr-xr-x 1 paulgear paulgear   18 Jan 15 09:29 .
drwxr-xr-x 1 paulgear paulgear 3976 Jan 15 09:26 ..
drwxr-xr-x 1 paulgear paulgear    0 Jan 15 09:29 test
-rw-r--r-- 1 paulgear paulgear    6 Jan 15 09:29 test1
paulgear@localhost:~/tmp$ date
Wed Jan 15 09:30:07 EST 2014
paulgear@localhost:~/tmp$ echo test2 > test1
paulgear@localhost:~/tmp$ ls -la
total 4
drwxr-xr-x 1 paulgear paulgear   18 Jan 15 09:29 .
drwxr-xr-x 1 paulgear paulgear 3976 Jan 15 09:26 ..
drwxr-xr-x 1 paulgear paulgear    0 Jan 15 09:29 test
-rw-r--r-- 1 paulgear paulgear    6 Jan 15 09:30 test1

Note how the complete replacement of the contents of test1 didn't update the directory time stamp.  So your find command probably should be looking for files as well as directories, something like this:
find . -mtime +180 -print0 | xargs -0 chmod a-w

Or you might want to make the time criteria different for files and directories:
find . -type d -mtime +120 -print0 | xargs -0 chmod a-w
find . -type f -mtime +180 -print0 | xargs -0 chmod a-w

For many (most?) applications using SMB file shares, this won't apply, because they usually write their contents to a temporary file in the same directory, then delete the original file, then rename the temporary file to the original's name.  But "database" applications like Access won't do this.


text:
Q: Returning object to ajax Web Service method I can't return javascript object to web method thru ajax call like below:
var person = {"FirstName":"Foo","LastName":"Bar"};

$.ajax({
    type: "POST",
    url: url,
    data: person,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    onSuccess: function () { alert('Success!'); },
    onError: function () { alert('Error'); }
});

Invalid JSON primitive is thrown with the method above.
I'd to resort to string manipulation like this:
var person = {"FirstName":"Foo","LastName":"Bar"};
var json = '{person:' + JSON.stringify(person) + '}';

$.ajax({
    type: "POST",
    url: url,
    data: json,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    onSuccess: function () { alert('Success!'); },
    onError: function () { alert('Error'); }
});

Now, this is working fine, i can get away with this solution, but life is hard, we don't want harder! If there's a way to pass the object directly i'd love to hear it ;)

A: The reason for that is likely that this:
data: person

Actually sends this:
FirstName=Foo&LastName=Bar

because jQuery breaks down that object into a POST-friendly key/value set. The reason you second version works is because it's actually sending a real JSON string. If you were to do this:
data: JSON.stringify(person)

That would likely work.

A: var json = '{person:' + JSON.stringify(person) + '}';
did the job :)


text:
Q: What's the difference between chef app and chef repo I found there are 2 ways to generate chef repo, and be confused by their similarity. I wonder which one is the recommended way, and why chef provide those commands. Maybe they are used in different context?
$ chef generate app chef-app
$ chef generate repo chef-repo
$ diff chef-app chef-repo | colordiff
Only in chef-app: .git
diff chef-app/.gitignore chef-repo/.gitignore
1,8c1
< .vagrant
< Berksfile.lock
< *~
< *#
< .#*
< \#*#
< .*.sw[a-z]
< *.un~
---
> .rake_test_cache
10,16c3,7
< # Bundler
< Gemfile.lock
< bin/*
< .bundle/*
<
< .kitchen/
< .kitchen.local.yml
---
> ###
> # Ignore Chef key files and secrets
> ###
> .chef/*.pem
> .chef/encrypted_data_bag_secret
Only in chef-app: .kitchen.yml
Only in chef-repo: LICENSE
diff chef-app/README.md chef-repo/README.md
1c1,2
< # chef-app
---
> Overview
> ========
3c4
< TODO: Enter the cookbook description here.
---
> Every Chef installation needs a Chef Repository. This is the place where cookbooks, roles, config files and other artifacts for managing systems with Chef will live. We strongly recommend storing this repository in a version control system such as Git and treat it like source code.
4a6,66
> While we prefer Git, and make this repository available via GitHub, you are welcome to download a tar or zip archive and use your favorite version control system to manage the code.
>
> Repository Directories
> ======================
>
> This repository contains several directories, and each directory contains a README file that describes what it is for in greater detail, and how to use it for managing your systems with Chef.
>
> * `certificates/` - SSL certificates generated by `rake ssl_cert` live here.
> * `config/` - Contains the Rake configuration file, `rake.rb`.
> * `cookbooks/` - Cookbooks you download or create.
> * `data_bags/` - Store data bags and items in .json in the repository.
> * `roles/` - Store roles in .rb or .json in the repository.
>
> Rake Tasks
> ==========
>
> The repository contains a `Rakefile` that includes tasks that are installed with the Chef libraries. To view the tasks available with in the repository with a brief description, run `rake -T`.
>
> The default task (`default`) is run when executing `rake` with no arguments. It will call the task `test_cookbooks`.
>
> The following tasks are not directly replaced by knife sub-commands.
>
> * `bundle_cookbook[cookbook]` - Creates cookbook tarballs in the `pkgs/` dir.
> * `install` - Calls `update`, `roles` and `upload_cookbooks` Rake tasks.
> * `ssl_cert` - Create self-signed SSL certificates in `certificates/` dir.
> * `update` - Update the repository from source control server, understands git and svn.
>
> The following tasks duplicate functionality from knife and may be removed in a future version of Chef.
>
> * `metadata` - replaced by `knife cookbook metadata -a`.
> * `new_cookbook` - replaced by `knife cookbook create`.
> * `role[role_name]` - replaced by `knife role from file`.
> * `roles` - iterates over the roles and uploads with `knife role from file`.
> * `test_cookbooks` - replaced by `knife cookbook test -a`.
> * `test_cookbook[cookbook]` - replaced by `knife cookbook test COOKBOOK`.
> * `upload_cookbooks` - replaced by `knife cookbook upload -a`.
> * `upload_cookbook[cookbook]` - replaced by `knife cookbook upload COOKBOOK`.
>
> Configuration
> =============
>
> The repository uses two configuration files.
>
> * config/rake.rb
> * .chef/knife.rb
>
> The first, `config/rake.rb` configures the Rakefile in two sections.
>
> * Constants used in the `ssl_cert` task for creating the certificates.
> * Constants that set the directory locations used in various tasks.
>
> If you use the `ssl_cert` task, change the values in the `config/rake.rb` file appropriately. These values were also used in the `new_cookbook` task, but that task is replaced by the `knife cookbook create` command which can be configured below.
>
> The second config file, `.chef/knife.rb` is a repository specific configuration file for knife. If you're using the Opscode Platform, you can download one for your organization from the management console. If you're using the Open Source Chef Server, you can generate a new one with `knife configure`. For more information about configuring Knife, see the Knife documentation.
>
> http://docs.opscode.com/knife.html
>
> Next Steps
> ==========
>
> Read the README file in each of the subdirectories for more information about what goes in those directories.
Only in chef-repo: Rakefile
Only in chef-repo: certificates
Only in chef-repo: chefignore
Only in chef-repo: config
Common subdirectories: chef-app/cookbooks and chef-repo/cookbooks
Only in chef-repo: data_bags
Only in chef-repo: environments
Only in chef-repo: roles

A: The repo generator is a replacement for the old chef-repo skeleton that many people cloned from GitHub. The app generator is a bit of an experiment. It was envisioned as a half-way point between the old-style single repo layout and a Berkshelf-heavy every-cookbook-in-its-own-repo layout. The app layout has several closely related cookbooks together in one git repo, but still multiple repos overall and a focus on cookbooks over roles/bags.


text:
Q: What's up with the Strange Organism in Waking the Ancient? In the mission Waking the Ancient, around the middle north of the map, there's a neutral critter that burrows as soon as you get anywhere near it. It's definitely selectable; the cursor changed when I moused over it, and I think its name was "Strange Organism" or something like that.
What is it for? Is there a related achievement? Is it maybe part of an Easter egg? Or is it just a red herring?
Please spoiler your answers as appropriate.

A: That is

 Dehaka

skulking around the edges, checking you out for future activities.

You can also see him on a ledge above your base in the next mission, The Crucible. Notice the missing right arm.


text:
Q: Disable navigation on iframe outside HTML I want to use one iFrame just to show content from another page. I don't have control over that HTML displayed, so I can't change that.
I can somehow 'disable' the navigation over that page?
(I need that page because the data will be changed over there and I need to display the results on my own HTML, but don't want the user to click on it because will change to their homepage with info that doesn't mean nothing to the user)
This is what I have, but the prevent function isn't working on iframe...

Classificação Atualizada

A: Overlay the iFrame with a transparent
 of the same dimensions, but higher z-index

See this fiddle


text:
Q: Windows 7 does not recognize file system of external hard drives connected through ATA I have a couple external ATA drives (Maxtor 320G) in HD enclosures(USB) that I want to use as internal hardrives. I assumed that it would be as easy as removing them from their enclosures and installing them in my windows 7 (x64) pc. However, while the drives can be seen from windows, the contained data cannot.
I have tried running chkdisk that returns that the disks are in RAW not NTSF(or FAT32).
Does anyone know why this would be the case and have possible solutions?
Thanks in advance,

A: If you connect the hard drive back to the computer while it is in the enclosure and the data is accessible again, I would assume that the enclosure is a form of nas storage and may have a file table type that is only readable through the device itself.  If that is the case, make a backup of the hard drive to local storage.  install the drive into the system, reformat it and copy the data back to its original location.
If the data is no longer accessible even in the enclosure, connect the drive internally to the pc and start up windows.  if windows detects an issue with the drive it will force a chkdsk even on a raw partition, possibly allowing your data to be recovered.

A: Were they ever readable?
It sounds to me like you simply need to partition and/or format them.


text:
Q: Manually estimate probit model with autoregressive structure in R I would like to write an R algorithm which would perform the Maximum Likelihood estimation of a binary choice model (probit/logit, it does not really matter) with the following structure for the latent variable:

I understand the logics provided in this answer, however, I do not understand how to account for the presence of the lagged value of latent variable.


text:
Q: Segue passing uiimage and open in UIwebview I would like to passing a uiimage from one view to another view which contains a uiwebview. So that i can allow easy interaction and gestures on the image.
But i have no idea how to code in the viewdidload method should be used.
Here is my code:
//first view
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
 if ([segue.identifier isEqualToString:@"showbig"]) {
        bigpic *image = [segue destinationViewController];
        image.bigpicture1 = set11.image;
}

//new view

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSURL *url = [NSURL URLWithString:bigpicture1];
    NSURLRequest *requestURL = [NSURLRequest requestWithURL:url];
    [self.bigpicture loadRequest:requestURL];

}

A: In the destinationViewController you should have a property UIImage *imageThatIShouldDisplay
In your sourceView controller prepareForSegue method you will have something like this:
if ([segue.identifier isEqualToString:@"showbig"]) {
        YourDestiantionVC *vc = (YourDestiantionVC*)[segue destinationViewController];
        vc.imageThatIShouldDisplay = set1.image;
}

In your destiantion view controller viewDidLoad method you will have:
if(self.imageThatIShouldDisplay != nil) {
 imageViewThatHandlesImageDisplay.image = self.imageThatIShouldDisplay;
}
else {
 imageViewThatHandlesImageDisplay.image = [UIImage imageWithName:@"my_image_placeholder.png"]; // in case you want a placeholder.
}

A: You have to load the image from your bundle to load it into the UIWebView since a UIImage can't be loaded directly into a UIWebView.
Answers

A: - (void)viewDidLoad
{
    [super viewDidLoad];
    self.bigpicture.image = bigpicture1;

}

as i think


text:
Q: Как вернуть значение из анонимной функции в callback вызове Есть ajax запрос, как получить из него результат и присвоить его переменной queryResult, затем переменная queryResult должна проверится и если в ее значении что то не так то нужно выйти из addPartition() :
function addPartition(){
    var queryResult;
    $.post('controllers/handlerPartition.php',
        {'isExistPartition': true, 'partitionName':   $('#modal_win1_partition_name').val()},
        function (result) {
            return result; //Как получить это значение из вне?
        }
     );
        if (queryResult === 'false') return;
}

Пробовал так:
function addPartition(){
    var queryResult;
    $.post('controllers/handlerPartition.php',
        {'isExistPartition': true, 'partitionName':   $('#modal_win1_partition_name').val()},
        function (result) {
            queryResult = result; //Присвоение внешней переменой
        }
    );
   alert(typeof queryResult); //undefined
   if (queryResult === 'false') return;
}

Но значение queryResult не определенно. Я так понимаю это из за асинхронности?

A: Используйте Promise - его и нужно вернуть из вашей функции.
В вашем случае jQuery предоставляет свою версию:
var jqxhr = $.post( "example.php", function() {
  alert( "success" );
})
.done(function() {
  alert( "second success" );
})
.fail(function() {
  alert( "error" );
})
.always(function() {
    alert( "finished" );
});

на одно обещание можно подписаться несколько раз:
jqxhr.always(function() {
  alert( "second finished" );
});

Также обратите внимание на одну из реализаций потоков.
Статья о функциональном программировании в разработке интерфейсов.


text:
Q: How to insert emoticons in LaTeX? I know it's a long shot, but is there some package or means to insert emoticons into a LaTeX document?

A: Unicode's "miscellaneous symbols" include 3 simple emoticons: 0x2639-0x263B. You can possibly use 0x2686-0x2689 as well.
For more variation you are going to need to use images and include them somehow.
I am curious as to the circumstances which lead to this question :)

A: I know at least two partial ways:
First:
$\ddot\smile$

Second:
\usepackage{wasysym}
\smiley
\frownie

Or you can use images (as mentioned in other replies).

A: By now there also is the tikzsymbols package which has nice emoticons.

A: What's against a simple {\tt :-)}?

A: If you use xelatex or lualatex, then
\documentclass{article}
\usepackage{fontspec}
\setmainfont{Symbola}
\begin{document}

\end{document}

should produce black-and-white emoji letters in Symbola font,
which is available from http://users.teilar.gr/%7Eg1951d/
or standard package repositories in some Linux distros (e.g. Ubuntu).
The MS Windows emoji font can also be used by \fontspec{Segoe UI Emoji}[RawFeature={ccmp,dist}]
in place of \fontspec{Symbola}.
Unfortunately the color (emoji) fonts are not supported by the standard
lualatex or xelatex. harflatex and luahblatex can typeset color emojis using
\documentclass{minimal}
\usepackage{harfload}
\usepackage{fontspec}

\begin{document}
\noindent
\fontspec{Noto Color Emoji}[RawFeature={mode=harf}]
☃⛄\quad ❤
\end{document}

harflatex and luahblatex can be installed from TeXLive Contrib at
https://contrib.texlive.info/ as of July 2019.
The above is learnt from https://tex.stackexchange.com/questions/497403/how-to-use-noto-color-emoji-with-lualatex/500180
with a bit of my own investigation.

A: One solution is to use bclogo package. It contains two smileys (happy & sad), plus many other small "logos" like flags and others.


text:
Q: Avoid default values in Androids SharedPreferences SharedPreferences provide the following function to retrieve a string:
String getString(String key, @Nullable String defValue);

When storing an Int, the default-value is not-nullable:
int getInt(String key, int defValue);

I now am looking to store and retrieve a nullable Int?, e.g.:
var timerDuration: Int?
    get() = prefs.getIntOrNull(TIMER_DURATION)
    set(value) { prefs.edit { putIntOrNull(TIMER_DURATION, value) } }

Solution 1: when value is null, remove key
private fun SharedPreferences.getIntOrNull(key: String) =
    if (prefs.contains(key)) {
        getInt(key, 12345)
    } else {
        null
    }

private fun SharedPreferences.Editor.putIntOrNull(key: String, value: Int?) =
    if (value == null) {
        remove(key)
    } else {
        putInt(key, value)
    }

... but i'm not sure if i could get problems with multiple, quick accesses because of the asynchronous nature of shared preferences?

Solution 2: use the string-option for everything:
private fun SharedPreferences.getIntOrNull(key: String) =
    prefs.getString(key, null)?.toIntOrNull()

private fun SharedPreferences.Editor.putIntOrNull(key: String, value: Int?) =
    putString(key, value?.toString())

... but .toIntOrNull() feels like a lot of overhead for such a simple task?

Why would i like to do this?
I hope Kotlin Multiplattform allows me to add an iOS-Version to my existing Android-App.
My goal is a "core" module written completely in Kotlin with no plattform-specific dependencies.
The "core" then just uses this interface, which is implemented by the Android & iOS - Apps
interface SettingsStorage {

    var timerDuration: Int?

    [...]
}

And as i would not like to have duplicate default-value-logic i'd enjoy to handle that in my "core"-module

Are there any other (better) options? I'm feeling like i'm reinventing the wheel...

A: Either of your methods is fine. SharedPreferences is thread-safe. Option 1 could only really fail if you set up a service in your manifest to run in a separate process and it is modifying the preferences at the same time as the rest of your app. This isn't something you would do accidentally.
Your second method isn't any additional overhead, because under the hood, SharedPreferences are all Strings so your code is basically doing the same thing as SharedPreferences.getInt, except that returns the default value when the preference doesn't exist or cant be parsed as an Int.

A: When you store an Int to SharedPreferences, it is stored internally as a string. So for getting, just get a String and if it's a null returns it, or try parse it to an Int. For setting, just convert your Int to String and put it using putString method.
var timerDuration: Int?
    get() = try { prefs.getString(TIMER_DURATION, null)?.toInt() } catch (e: Exception) { null }
    set(value) { prefs.edit { putString(TIMER_DURATION, value.toString()) } }


text:
Q: how to request/response works in multiplayer game I newbie to forum and game programming but I have a question( probably dummy question...)
I am working on a multiplayer game like a Checkers.
My architecture goes like this:
After both client sign in to game, and ready to go,
each client, in his turn makes a 'move', and send it to server to authorize it.
After server authorize movement, it then send 2 message:
1) first one for the player which make the 'move', telling him its move is granted and it now should 'wait' for the other opponent to play.
2) second message, goes to opponent, telling him what soldier move, and that now it his 'turn' to play.... bla bla bla
my silly question is: When a each client sign-in to game, a new socket created for him for communicating with server
How can I use the socket for BOTH, sending messages to server(like movement), and also for listening to responses from server(like 'your turn', 'wait'...)
is it possible or I should create another socket for 'listening' ?
Thanks for the help

A: Ok so I feagure it how to solve the issue.
I little changed my architecture but it goes like this.
(Since its not realtime game, i decided to use TCP instead of UDP protocol, but its another discussion...)
When the server accpect 2 players, it create GameGanager(Runnable) object and pass both sockets to it.
(Then Server and goes back for listening to next game requests...)
When client applicaion succeed to connect to server it goes to 'WAIT' state.
For each socket, GamePlayer create Player instance and pass to it the relevant socket.
Player object, among other, have 2 methods: sendMessage(), waitMessage() for communicating with client application.
GameServer sends 2 messages:
 - to 'player' initiating the game: a 'TURN' state.
 - to 'opponent': a 'WAIT' state.
When 'player' made his moves, it then sendMessage() to GameServer to authenticate the move, and goes to 'WAIT' state by calling waitMessage().
GameServer 'ACK' to player, and sends message 'TURN' to opponent.
and goes on until the game finished
Hope it will help to someone.


text:
Q: Administarte gem custom getter and setter I want to convert dollars to cents without using money gem and outside the model. This attribute belongs to model that is has a dashboard in Administrate gem.
When users input 10 it should be converted to cents as 10 * 100 and saved to DB.
I was trying to do it using administrate custom Field then setup getter and setter, but it doesn't work:
class ConvertToCentsField < Administrate::Field::Base
  def to_s
    data
  end

  def buyer_fee_fixed
    @resource.buyer_fee_fixed
  end

  def buyer_fee_fixed=(value)
    @resource.buyer_fee_fixed = (value.to_f * 100).to_i
  end
end

Maybe I'm using getter and setter in the wrong place.


text:
Q: Android Dynamic button the button to be erased - Got the Solution Lastbutton.setVisibility(View.INVISIBLE);  - Solution.
And i am trying some maths calculation like below.
     4     2   8    3                   ( Displayed in Button )

     +     -   *    /                   ( Displayed in Button )

Suppose if the user presses 4 then + then 2  then like below. (1st pressed button to be removed)
          6    8   3

Suppose if the user presses 6 then * then 3  then like below. (1st pressed button to be removed)
               8  18

Suppose if the user presses 18 then -  then 8  then like below.
               10

I tried and its not working. And i am pasting my current version of the code also.
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        lm = (LinearLayout) findViewById(R.id.lm);

        // Create a LinearLayout for each row inside the outer LinearLayout.
        LinearLayout firstRow = new LinearLayout(this);
        firstRow.setOrientation(LinearLayout.HORIZONTAL);
        // Create a String array of items you want to add to the inner LinearLayout.
        String[] itemsToAddToFirstRow = { "4", "2", "8", "3"};
        createButtonsDynamically(firstRow, itemsToAddToFirstRow);

        String[] itemsToAddToSecondRow = { "+", "-", "*", "/" };
        LinearLayout secondRow = new LinearLayout(this);
        secondRow.setOrientation(LinearLayout.HORIZONTAL);
        createButtonsDynamically(secondRow, itemsToAddToSecondRow);
    }

    private void createButtonsDynamically(LinearLayout layoutToAddButtonsTo, String[] itemsToAdd) {
        for (int i = 0; i < itemsToAdd.length; i++) {
            final Button buttonToAdd = new Button(this);
            buttonToAdd.setText(itemsToAdd[i]);
            buttonToAdd.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                        Strvalue = (String) buttonToAdd.getText();
                    operation(buttonToAdd);
                }
            });
            layoutToAddButtonsTo.addView(buttonToAdd);
        }

        // In the end add all buttons inside the inner LinearLayout to the outer LinearLayout.
        lm.addView(layoutToAddButtonsTo);
    }

private void operation(Button buttonToAdd)
   {
       if (Strvalue.equals("Clear"))
       {
           buttonToAdd.setEnabled(true);
           Toast.makeText(getApplicationContext(), "I was clicked: " + Strvalue , Toast.LENGTH_SHORT).show();
       }
       else
       {
       if (Strvalue.equals("+") || Strvalue.equals("-") || Strvalue.equals("*")|| Strvalue.equals("/"))
       {
          flag = true;
          Toast.makeText(getApplicationContext(), "I was clicked: " + Strvalue , Toast.LENGTH_SHORT).show();
          Pressoperator = Strvalue;
          product1.setText("Calc Answer:  "+ Calctotal);
       }
       else
       {
           flag = false;
           if (Pressoperator.equalsIgnoreCase(Emptystr))
           {
               Calctotal = Integer.parseInt(Strvalue);
               Prevvalue = Integer.parseInt(Strvalue);
               Toast.makeText(getApplicationContext(), "I was clicked: " + Calctotal , Toast.LENGTH_SHORT).show();
               product1.setText(Integer.toString(Calctotal));
           }
           else
           {
               if (Pressoperator.equals("+")) { Calctotal = Prevvalue + Integer.parseInt(Strvalue); }
               if (Pressoperator.equals("-")) { Calctotal = Prevvalue - Integer.parseInt(Strvalue); }
               if (Pressoperator.equals("*")) { Calctotal = Prevvalue * Integer.parseInt(Strvalue); }
               if (Pressoperator.equals("/")) { Calctotal = Prevvalue / Integer.parseInt(Strvalue); }
               Toast.makeText(getApplicationContext(), "I was clicked: " + Calctotal , Toast.LENGTH_SHORT).show();
               Prevvalue = Calctotal;
               product1.setText(Integer.toString(Calctotal));
           }
           if (Calctotal == total)
           {
               Toast.makeText(getApplicationContext(), " Yureka Your Answer is Correct " , Toast.LENGTH_SHORT).show();
           }
        }
       }

   }


text:
Q: display results from array of objects This class compiles just fine:
public class Student{
//define variables
static String name;

//define constructor
public Student(String n){
    name = n;
}

//define method to display name
public static void displayStudent(){
    System.out.println("Name: " + name);
}
}

Here is the class where I am trying to call the displayStudent() method, but I am getting java.lang.NullPointerException exception coming from the for loop :
public class MyClass{

//define array of object Student
private Student[] students;

//constructor
MyClass(int size){
Student[] students = new Student[size];
}

    //define method to display the students variable
public void displayAllStudents(){
    for (int i = 0; i <= students.length; i++){
        students[i].displayStudent();
    }
}

I am trying to fixing it with Eclipse, but it says that in MyClass "the value of the local variable students is not used". Where is my mistake?

A: You are creating a local variable here
MyClass(int size){
    // only exists inside this scope.
    Student[] students = new Student[size];
}

But this is local to this constructor so you immediately throw it away. I assume you meant to set the field students
MyClass(int size) {
    students = new Student[size];
}

Note: all this does is create an array of references to Students which are all null. So what you also need is to create a Student object for each of these indexes
MyClass(int size) {
    students = new Student[size];
    for (int i = 0; i < size; i++)
        students[i] = new Student();
}

Note how the common pattern is to use < not <= Your printing loop needs to be either
for (int i = 0; i < students.length; i++){

or
for (int i = 0; i <= students.length-1; i++){

As indexes start at 0, if you have n elements, the last one will be n-1
p.s.
You probably didn't mean for the variable "name" to be static.
By making it static, all instances of "Student" will share the same name.

A: It is because of that array size
change that code into
public void displayAllStudents(){
    for (int i = 0; i < students.length; i++){
        students[i].displayStudent();
    }
}
if an array have 3 elements array.length function return 3. And you count it from 0 ,1,2,3 yaa there is 4 number . it will return array outof bound exception or nullpointer exception .

A: See the link for solution:
https://github.com/omkar-nibandhe/StackOverflowSolutions/commit/c7aa250caeeed6a3827e0579b174aae59d4f9c22
Changes are made in your class : "MyClass" for the declaration part of Student[].
-You are calling the constructor with size of array, so initialize the Student[] with size of your choice (hard-coded to 10 in this case).
Hope this helps you.

A: As we can see you are using the array of students but you are not calling the constructor of student class(with argument) and hence they contain null as stored value in name field and gives you a null pointer exception.
   class MyClass{

//define array of object Student
private Student[] students;

//constructor
MyClass(int size){
Student[] students = new Student[size];
}

    //define method to display the students variable
public void displayAllStudents(){
    for (int i = 0; i <= students.length; i++){
        students[i].displayStudent();//this will give null pointer execption because student
        // objects are not inisialised and cointains null
    }
}
}

but this code will not give null pointer exception.
    class MyClass{

//define array of object Student
private Student[] students;

//constructor
MyClass(int size){
Student[] students = new Student[size];
for(int i=0;i<size;i++){
     students[i]=new Student("the string value");
}
}

    //define method to display the students variable
public void displayAllStudents(){
    for (int i = 0; i <= students.length; i++){
        students[i].displayStudent();
    }
}
}


text:
Q: How do I get the last day of the selected month in jQuery datepicker? I want to get the last day of the selected month in jquery datepicker on onSelect
My current code is written below:
  var j = jQuery.noConflict();
  j('.epo-field-date').datepicker({
    dateFormat: "yy-mm-dd",
    minDate: 0,
    maxDate: '1m',
    firstDay: 1,
    onSelect: function(dateText, inst, dateob) {

      var chosen_month = j.datepicker._defaults.monthNames[inst.selectedMonth];
      var chosen_day = date_selected_parts[2];

      j('.chosen-month .month').text(chosen_month);

    }
  });

For example, When I click any day in the month of January, I should be able to return the value 31 or depending on the last day of the selected day of the month.
Any help is greatly appreciated.

A: Very simple, You can get selected year, month and create new date to get last date as following code below.
Here sample code for your reference:
<!DOCTYPE html>

JavaScript new Date()

A: You can use $(this).datepicker('getDate'); within the onSelect event to get the selected date as a JavaScript Date.
To get the last day of the month, you can actually advance the month by 1, and set the day of the month to 0.
For example, if you wanted the last day in December, JavaScript allows you to fetch the day before January 1 by getting January 0.
var j = jQuery.noConflict();
j('.epo-field-date').datepicker({
  dateFormat: "yy-mm-dd",
  minDate: 0,
  maxDate: '1m',
  firstDay: 1,
  onSelect: function(dateText, inst, dateob) {

    var selectedDate = $(this).datepicker('getDate');
    var selectedMonth = selectedDate.getMonth();
    var selectedYear = selectedDate.getFullYear();

    var lastDate = new Date(selectedYear, selectedMonth + 1, 0);
    var lastDay = lastDate.getDate();

    //Do something with lastDay

  }
});

An example using today's date:

var today = new Date();
var month = today.getMonth();
var year = today.getFullYear();

var lastDate = new Date(year, month + 1, 0);
var lastDay = lastDate.getDate();

console.log("Last day of the month:", lastDate.toLocaleString());
console.log("Date as number:", lastDay);