text:
Q: Google BigQuery Trying to run a TABLE_RANGE_DATE i am building a partition based table in a dataset and i am trying to query those partitions using a date range.
Here is an example of the data:
Dataset:
logs
Tables:
logs_20170501
logs_20170502
logs_20170503
i am trying first the TABLE_RANGE_DATE
SELECT count(*) FROM TABLE_DATE_RANGE([logs.logs_],
                    TIMESTAMP("2017-05-01"),
                    TIMESTAMP("2017-05-03")) as logs_count
i am keep getting : "ERROR:Error evaluating subsidiary query"
i tried those options as well:
single comma:
SELECT count(*) FROM TABLE_DATE_RANGE([logs.logs_],
                    TIMESTAMP('2017-05-01'),
                    TIMESTAMP('2017-05-03')) as logs_count
Add Project ID:
SELECT count(*) FROM TABLE_DATE_RANGE([main_sys_logs:logs.logs_],
                    TIMESTAMP('2017-05-01'),
                    TIMESTAMP('2017-05-03')) as logs_count
And it didn't worked.
So i tried to use TABLE_SUFFIX
SELECT
  count(*)
FROM [main_sys_logs:logs.logs_*]
WHERE _TABLE_SUFFIX BETWEEN '20170501' AND '20170503'
And i got this error :

Invalid table name:'main_sys_logs:logs.logs_*
i have been switching SQL Dialect between legacy SQL ON/Off and i just got different errors on the table name part.
Is there any tips or help for this matter ?
maybe my table name is build wrong with the "_" at the end and this is causing the problem ? thanks for any help.

A: So i tried this Query and it worked :
SELECT count(*) FROM TABLE_DATE_RANGE(logs.logs_,
                    TIMESTAMP("2017-05-01"),
                    TIMESTAMP("2017-05-03")) as logs_count
it started to work after i run this query , i don't know if this is the reason .. but i just query the TABLES data for the dataset
SELECT *
FROM logs__TABLES__


text:
Q: How to create interaction between two android applications I have 2 applications with their source codes. When I press button in application one, I need to background "press" button in application 2 (start specific action from it, not MainActivity). So, for example, do command like
send "press_button2" -> APP2

What is the best way to do it?

A: That's quite a generic question but you'll have to use an implicit intent from your "APP1" and read the intent action in your "APP2".
The steps will be:

*

*Define the implicit intent in your APP1, something like

val sendIntent: Intent = Intent().apply {
    action = Intent.ACTION_SEND
    putExtra(Intent.EXTRA_TEXT, "press_button2")
    type = "text/plain"
}
startActivity(sendIntent)

*In your APP2, set up your manifest to receive the specified action in an activity of your choice, using an intent filter:

<activity android:name="ClickActivity">
    <intent-filter>
        <action android:name="android.intent.action.SEND"/>
        <category android:name="android.intent.category.DEFAULT"/>
        <data android:mimeType="text/plain"/>
    </intent-filter>
</activity>

*In your "APP2" handle the incoming intent in your activity, something like:

@SuppressLint("MissingSuperCall")
    override fun onCreate(savedInstanceState: Bundle?) {
        when {
            intent?.action == Intent.ACTION_SEND -> {
                if ("text/plain" == intent.type) {
                    intent.getStringExtra(Intent.EXTRA_TEXT)?.let {
                        // Update UI to reflect text being shared
                        if (it == "press_button2"){
                            myButton.performClick()
                        }
                    }
                }
            }

        }
    }

Be aware that also other apps would be able to manage your "send text action", so android will show an app chooser to the user, you'll not be able to switch between the two apps seamlessly.
Reference here

redpajama_set_name: RedPajamaStackExchange


text:
Q: !Unknownsymbol! when writing java class for sonarqube Hi StackOverflow community,
I am new to writing custom rules for java in SonarQube.
I am writing a custom rule to detect certain interfaces being in used via maven. However, during testing, "!unknownSymbol!" came out instead of the Interface classes being implemented by the test case.
In my test case, I have written a class which implements 2 interfaces: -
- java.util.List
- org.osgi.framework.BundleActivator
The test can detect both interfaces, but when I convert it into a symbolTree then use the method fullyQualifiedName(), it returns "!unknownSymbol!". However, when I am doing a simple toString() it returns the interface name.
I would like to know how to correctly convert it into a symbolTree object and get the correct interface without encountering "!unknownSymbol!"
Thank you very much.
The code:
package org.sonar.samples.java.checks;

import com.google.common.collect.ImmutableList;
import org.sonar.check.Priority;
import org.sonar.check.Rule;
import org.sonar.plugins.java.api.IssuableSubscriptionVisitor;
import org.sonar.plugins.java.api.tree.ClassTree;
import org.sonar.plugins.java.api.tree.ListTree;
import org.sonar.plugins.java.api.tree.Tree;
import org.sonar.plugins.java.api.tree.TypeTree;

import java.util.List;

@Rule(
        key = "AvoidInterfaceClass",
        name = "No Interfaces",
        description = "Not allowed to implement any interface(s)",
        priority = Priority.MAJOR
)

    public class AvoidSuperInterfacesRule extends IssuableSubscriptionVisitor {

    public static final List<String> SUPER_INTERFACE_AVOID = ImmutableList.of("org.osgi.framework.BundleActivator","java.util.List");

    @Override
    public List<Tree.Kind> nodesToVisit() {
        return ImmutableList.of(Tree.Kind.CLASS);
    }

    public void visitNode(Tree tree){

        //System.out.println("Here");

        ClassTree treeClass = (ClassTree) tree;

        if (treeClass.superInterfaces().isEmpty()) {
            return;
        }

        ListTree<TypeTree> superInterfaceNames = treeClass.superInterfaces();

        System.out.println(superInterfaceNames.size()); //Number of interfaces
        System.out.println();

        for (TypeTree t:superInterfaceNames){

            String name = t.symbolType().fullyQualifiedName();

            System.out.println(name);
            System.out.println(t.toString());

            System.out.println();

            if (SUPER_INTERFACE_AVOID.contains(name)){
                reportIssue(t, "This interface is not allowed to be implemented.");
            }
        }

    }
}

The output:
09:18:36.332 [main] INFO org.sonar.squidbridge.ProgressReport - 1 source files to be analyzed
09:18:36.439 [main] DEBUG org.sonar.java.bytecode.ClassLoaderBuilder - ----- Classpath analyzed by Squid:
09:18:36.439 [main] DEBUG org.sonar.java.bytecode.ClassLoaderBuilder - C:\Users\attanyg1\Desktop\Sonarqube\java-custom-rules\target\test-jars\commons-collections4-4.0.jar
09:18:36.439 [main] DEBUG org.sonar.java.bytecode.ClassLoaderBuilder - C:\Users\attanyg1\Desktop\Sonarqube\java-custom-rules\target\test-jars\javaee-api-6.0.jar
09:18:36.439 [main] DEBUG org.sonar.java.bytecode.ClassLoaderBuilder - C:\Users\attanyg1\Desktop\Sonarqube\java-custom-rules\target\test-jars\spring-context-4.3.3.RELEASE.jar
09:18:36.440 [main] DEBUG org.sonar.java.bytecode.ClassLoaderBuilder - C:\Users\attanyg1\Desktop\Sonarqube\java-custom-rules\target\test-jars\spring-web-4.3.3.RELEASE.jar
09:18:36.440 [main] DEBUG org.sonar.java.bytecode.ClassLoaderBuilder - C:\Users\attanyg1\Desktop\Sonarqube\java-custom-rules\target\test-jars\spring-webmvc-4.3.3.RELEASE.jar
09:18:36.440 [main] DEBUG org.sonar.java.bytecode.ClassLoaderBuilder - C:\Users\attanyg1\Desktop\Sonarqube\java-custom-rules\target\test-classes
09:18:36.440 [main] DEBUG org.sonar.java.bytecode.ClassLoaderBuilder - -----

2 -> Number of Interfaces

!unknownSymbol! -> symbolType.getFullyQualifiedName()
BundleActivator -> toString()

!unknownSymbol! -> symbolType.getFullyQualifiedName()
List            -> toString()

09:18:36.798 [Report about progress of Java AST analyzer] INFO org.sonar.squidbridge.ProgressReport - 1/1 source files have been analyzed


text:
Q: Redisson for JCache Session persistence on WebSphere-Liberty: how to pass redisson-jcache.yaml? Hello Open Liberty experts,
As an R&D effort, I am trying to enable Liberty session persistence backed by
Redis via JCache/Redisson. I observe the CLASSPATH seems to be
correctly configured via <library> and <httpSessionCache libraryRef> syntax,
but the config file is not being passed
to org.redisson.jcache.JCacheManager.createCache(). This method is an implementation of javax.cache.CacheManager.createCache()
Here is my server.xml:
<?xml version="1.0" encoding="UTF-8"?>
<server description="defaultServer">
    <!-- Enable features -->
    <featureManager>
        <feature>cdi-2.0</feature>
        <feature>jaxb-2.2</feature>
        <feature>jsf-2.3</feature>
        <feature>jaxrs-2.1</feature>
        <feature>ejbLite-3.2</feature>
        <feature>sessionCache-1.0</feature>
    </featureManager>

    <!-- Define http & https endpoints -->
    <httpEndpoint id="defaultHttpEndpoint" host="*"
        httpPort="9080" httpsPort="9443" />

    <library id="jCacheVendorLib">
      <fileset dir="${shared.resource.dir}" includes="*"/>
      <folder dir="${shared.resource.dir}" />
    </library>

    <!-- trust JDK's default truststore -->
    <ssl id="defaultSSLConfig"  trustDefaultCerts="true" />

    <httpSessionCache libraryRef="jCacheVendorLib"
                      uri="file:${shared.resource.dir}/redisson-jcache.yaml" />

    <!-- Automatically expand WAR files and EAR files -->
    <applicationManager autoExpand="true" />

    <!-- Define web application with its context root and location -->
    <webApplication id="javaee-cafe" contextRoot="/"
        location="${server.config.dir}/apps/javaee-cafe.war">
    </webApplication>
</server>

Regardless of what value I set as
uri="file:${shared.resource.dir}/redisson-jcache.yaml" I still get
this exception at startup time for Liberty.
{
    "host": "javaee-app-simple-cluster-85b47b866c-h5mk4",
    "ibm_datetime": "2021-05-05T02:49:04.369+0000",
    "ibm_messageId": "SESN0307E",
    "ibm_sequence": "1620182944369_0000000000017",
    "ibm_serverName": "defaultServer",
    "ibm_threadId": "0000002a",
    "ibm_userDir": "/opt/ol/wlp/usr/",
    "loglevel": "ERROR",
    "message": "SESN0307E: An exception occurred when initializing the cache. The exception is: java.lang.IllegalStateException: Default configuration hasn't been specified!
  at org.redisson.jcache.JCacheManager.createCache(JCacheManager.java:118)
  at com.ibm.ws.session.store.cache.CacheHashMap.cacheInit(CacheHashMap.java:182)
  at com.ibm.ws.session.store.cache.CacheHashMap.lambda$new$0(CacheHashMap.java:134)
  at com.ibm.ws.session.store.cache.CacheHashMap$$Lambda$90/0000000000000000.run(Unknown Source)
  at java.security.AccessController.doPrivileged(AccessController.java:678)
  at com.ibm.ws.session.store.cache.CacheHashMap.<init>(CacheHashMap.java:133)
  at com.ibm.ws.session.store.cache.CacheStore.<init>(CacheStore.java:33)
  at com.ibm.ws.session.store.cache.CacheStoreService.createStore(CacheStoreService.java:316)
  at com.ibm.ws.session.SessionContext.createStore(SessionContext.java:337)
  at com.ibm.ws.session.SessionContext.createCoreSessionManager(SessionContext.java:254)
  at com.ibm.ws.session.SessionContext.<init>(SessionContext.java:157)
  at com.ibm.ws.webcontainer.session.impl.HttpSessionContextImpl.<init>(HttpSessionContextImpl.java:62)
  at com.ibm.ws.webcontainer31.session.impl.HttpSessionContext31Impl.<init>(HttpSessionContext31Impl.java:37)
  at com.ibm.ws.webcontainer31.session.impl.SessionContextRegistry31Impl.createSessionContextObject(SessionContextRegistry31Impl.java:40)
  at com.ibm.ws.webcontainer.session.impl.SessionContextRegistryImpl.createSessionContext(SessionContextRegistryImpl.java:83)
  at com.ibm.ws.webcontainer.session.impl.SessionContextRegistryImpl.getSessionContext(SessionContextRegistryImpl.java:304)
  at com.ibm.ws.webcontainer.WebContainer.getSessionContext(WebContainer.java:699)
  at com.ibm.ws.webcontainer.VirtualHost.getSessionContext(VirtualHost.java:188)
  at com.ibm.ws.webcontainer.webapp.WebGroup.getSessionContext(WebGroup.java:156)
  at com.ibm.ws.webcontainer.webapp.WebApp.createSessionContext(WebApp.java:1313)
  at com.ibm.ws.webcontainer.webapp.WebApp.commonInitializationStart(WebApp.java:1296)
  at com.ibm.ws.webcontainer.osgi.webapp.WebApp.commonInitializationStart(WebApp.java:254)
  at com.ibm.ws.webcontainer.webapp.WebApp.initialize(WebApp.java:1014)
  at com.ibm.ws.webcontainer.webapp.WebApp.initialize(WebApp.java:6683)
  at com.ibm.ws.webcontainer.osgi.DynamicVirtualHost.startWebApp(DynamicVirtualHost.java:470)
  at com.ibm.ws.webcontainer.osgi.DynamicVirtualHost.startWebApplication(DynamicVirtualHost.java:465)
  at com.ibm.ws.webcontainer.osgi.WebContainer.startWebApplication(WebContainer.java:1178)
  at com.ibm.ws.webcontainer.osgi.WebContainer.access$100(WebContainer.java:109)
  at com.ibm.ws.webcontainer.osgi.WebContainer$3.run(WebContainer.java:975)
  at com.ibm.ws.threading.internal.ExecutorServiceImpl$RunnableWrapper.run(ExecutorServiceImpl.java:239)
  at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
  at java.util.concurrent.FutureTask.run(FutureTask.java:266)
  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
  at java.lang.Thread.run(Thread.java:823).",
    "module": "com.ibm.ws.session.store.cache.CacheHashMap",
    "type": "liberty_message"
}

I tried setting a completely bogus value for
uri="file:${shared.resource.dir}/redisson-jcache.yaml" and I still
get the same result: IllegalStateException as shown above. What am
I missing?
Thanks,
Ed

A: Looking at Open Liberty source code, it looks like the uri is supplied to the CachingProvider when obtaining a CacheManager,
cacheManager = cachingProvider.getCacheManager(uri, null, vendorProperties);

It will be helpful to see the value that code is supplying here for the uri to ensure that it is getting through correctly and that the variable expansion is working and it isn't corrupted.  To do that, you could turn on the following trace:
<logging traceSpecification="*=info:com.ibm.ws.session.store.cache.*=all"/>

which ought to include, among other things, entry/exit from JCache methods.
The trace output should appear in /logs/trace.log under your server output folder.

A: Sadly solution to this problem is fairly simple, working out the problem was more complicated. There was a typo in the redisson-jcache.yaml file. Since I know Ed we have been talking off stack overflow and we discovered the redisson-jcache.yaml file contained this:
clusterServerConfig:
  password: ${clusterServerConfig.password}
  nodeAddresses:
  - ${clusterServerConfig.nodeAddresses}

it turns out that it should have been:
clusterServersConfig:
  password: ${clusterServerConfig.password}
  nodeAddresses:
  - ${clusterServerConfig.nodeAddresses}

note the correct form has server as plural.
So what went wrong, it turns out that if the reddison yaml file doesn't parse for any reason it proceeds as if no configuration was provided with no error message to indicate what the problem processing the configuration was. It then throws a cryptic exception saying no configuration was provided.
Inserting a printStackTrace call into the right place in the Redisson code base resulted in a useful error message that said:
Unrecognized field "clusterServerConfig" (class org.redisson.config.Config), not marked as ignorable (23 known properties: "eventLoopGroup", "maxCleanUpDelay", "nettyHook", "keepPubSubOrder", "nettyThreads", "threads", "transportMode", "singleServerConfig", "sentinelServersConfig", "reliableTopicWatchdogTimeout", "useScriptCache", "minCleanUpDelay", "connectionListener", "executor", "codec", "replicatedServersConfig", "clusterServersConfig", "useThreadClassLoader", "masterSlaveServersConfig", "addressResolverGroupFactory", "lockWatchdogTimeout", "cleanUpKeysAmount", "referenceEnabled"])

So the conclusion here is to make absolutely sure your redisson yaml is correct. Having fixed that everything worked.


text:
Q: Assigning Numeric values to text input I want to assign a specific integer value to a text type input in python for further indexing.
Example- I input 'sap' as text and i want it to be assigned as 1.
P.s I'm new to coding so spare me for wrong technical terms

A: You could do this via a dict and the below function in example
my_index = {}

def add_element(index,el):
    my_index[index] = el

add_element(0,"sap")
add_element(1,"spam")

print(my_index)

OUT: {0: 'sap', 1: 'spam'}

A: Two ways:
1: You can assign a value to a string with a dictionary, like so:
text = input("Input your text: ")
value = int(input(f"Input the value of {text}:"))
d = {text: value}

Output:
Input your text: hi
Input the value of hi: 6
# {'hi': 6}

2: Or, if you want to keep the text as a variable:
text = input("Input your text: ")
value = int(input(f"Input the value of {text}:"))
locals()[text] = value

Output:
Input your text: hi
Input the value of hi: 6
# hi = 6


text:
Q: Determining if this relation is an equivalence relation $$R=\left\{(f,g)\,\Bigg|\, \exists c\in\Bbb Z,\forall x\in\Bbb Z, \frac{f(x)}{g(c)}\le 2\right\}$$
I can show that this relation is reflexive by showing that $(f,f)$ is in $R$
and so $f(x)/f(c) \le 2$, for $c=x$
But i can't seem to find a way to show this relation is also symmetric and transitive.
Any help would be appreciated!
Thanks.

A: As Brian pointed out, $R$ is not an equivalence relation because it is not reflexive.
To see why $R$ is not symmetric either, consider the constant functions where for all $n\in \mathbb{Z},\text{ }f(n)=1$ and $g(n)=3$. Then certainly we know that $(f,g) \in R$; for example, if we choose $c=7$, then for all $x \in \mathbb{Z}, \dfrac{f(x)}{g(c)}=\dfrac{f(x)}{g(7)}=\dfrac{1}{3}\le2$. Yet we have $(g,f) \notin R$ since for all $c\in \mathbb{Z}$, there exists an $x \in \mathbb{Z}$ (for example, $x=9$) such that $\dfrac{g(x)}{f(c)}=\dfrac{g(9)}{f(c)}=\dfrac{3}{1}>2$.
To see why $R$ is not transitive either, consider the constant functions where for all $n\in \mathbb{Z},\text{ }f(n)=4,\text{ }g(n)=2,$ and $h(n)=1$. Then since $\dfrac{4}{2}=\dfrac{2}{1}=2\le2$, we know by a similar argument from above that $(f,g),(g,h) \in R$. Yet we have $(f,h) \notin R$ since no matter what values of $c$ and $x$ are chosen, $\dfrac{f(x)}{h(c)}=\dfrac{4}{1}=4>2$.


text:
Q: Why am I being displayed "TypeError: a float is required"? My main issue is this error being displayed:
TypeError: a float is required

I haven't tried much as I don't really know what I'm doing, being very new to coding and all, so I would appreciate some patient advice on the matter.
from math import sqrt

n = raw_input('Type number here: ')

def square_root(n):
  """Returns the square root of a number."""
  square_rooted = sqrt(n)
  print "%d square rooted is %d." % (n, square_rooted)
  return square_rooted

square_root(n)

I want to be able to type in a number and it display the square root of it.

A: Some issues/fixes for your code

*

*You need to cast the string you got from raw_input

*To display float, use %f string formatting
So the code will change to
from math import sqrt
#Convert string obtained from raw_input to float
n = float(raw_input('Type number here: '))
def square_root(n):
  """Returns the square root of a number."""
  square_rooted = sqrt(n)
  print "%f square rooted is %f." % (n, square_rooted)
  return square_rooted

square_root(n)

And the output will look like
Type number here: 4.5
4.500000 square rooted is 2.121320.

A: Change your codes to convert string to float. Input results into a string format.
square_rooted = sqrt(float(n))

Also; change your code in displaying the values. Use %s instead of number (%d)
"%s square rooted is %s."

Sample:
Type number here: 81
81 square rooted is 9.0.

A: As mentioned above perhaps python3 is the better python version to be using if you are new but the python 2 solution would look like below. Where we use %f to indicate our number is a float. In addition on line 2 we wrap the raw_input() statement in a float() function. This allows the python interpreter to understand we expect a float value.
from math import sqrt

n =float(raw_input('Type number here: '))

def square_root(n):
  """Returns the square root of a number."""
  square_rooted = sqrt(n)
  print "%f square rooted is %f." % (n, square_rooted)
  return square_rooted

square_root(n)

The python 3 version would be below just a few minor edits. The input line would now become input() not raw_input()... Also the print statement would use parentheses on the sides:
from math import sqrt

n =float(input('Type number here: '))

def square_root(n):
  """Returns the square root of a number."""
  square_rooted = sqrt(n)
  print("%f square rooted is %f." % (n, square_rooted))
  return square_rooted

square_root(n)

A: This worked for me, had to fix syntax based on my version of python-
from math import sqrt

n = input('Type number here: ')

n = float(n)

def square_root(n):

   #"""Returns the square root of a number."""

   square_rooted = sqrt(n)

   print("%d square rooted is %d." % (n, square_rooted))
   return square_rooted

square_root(n)


text:
Q: How can I pass a tag`s value to a javascript function after an event? How can I pass a tag`s value to a javascript function?
this works:
onclick="submit(this.value)"

but this dosnt work:
onclick="submit(document.getElementById("ShortcutID").value)"

A: If you want to include quote characters in an attribute value delimited with the same kind of quote characters, you have to represent them with character references.
onclick="submit(document.getElementById("ShortcutID").value)"

Alternatively, use a different kind of quote character.
onclick="submit(document.getElementById('ShortcutID').value)"

… but try to avoid using intrinsic event attributes and bind your JavaScript event handlers with JavaScript instead. See Unobtrusive JavaScript

A: there is syntax error.
ShortcutID should be enclosed in this 'ShortcutID'
Change this
onclick="submit(document.getElementById("ShortcutID").value)"

to this
onclick="submit(document.getElementById('ShortcutID').value)"

A:
but this dosnt work: onclick="submit(document.getElementById("ShortcutID").value)"

Because you're using double quotes both to delimit the onclick attribute and also inside to delimit the JavaScript string. Try:
onclick="submit(document.getElementById('ShortcutID').value)"

This is why JavaScript allows both single and double quotes for quoting strings.
You can also do it with entities, because remember that the content of an attribute is HTML text just like anything else in the HTML, so:
onclick="submit(document.getElementById("ShortcutID").value)"

The fact that the content is HTML text tends to be problematic when you're doing something non-trivial, which is one reason not to use onclick="code" style event handling but rather hooking up the event in code instead.

A: The problem you have in your code is you are using two sets of double quotes.  To fix this, try this: onclick="submit(document.getElementById('ShortcutID').value)"


text:
Q: dynamically update data value in android In my first activity have to develop login form(username,password and button) via soap calling..it is worked successfully.
In 2nd activity have to listview using xml parsing...it is also worked well.
In 3rd activity have to displayed detail description of particular order.(if i have to click the any order in 2nd activity means that order detail description is displayed in 3rd activity)...it is also worked good.also in this activity have one button(change order status)..if i have to click the button means it is go to 4th activity..
In 4th activity have to display one field spinner(status)...here the spinner value is updated via soap calling in 4th activity...but is worked below query means UPDATE xcart_orders set status = '"+Status+"',orderid = '"+Orderid+"' where orderid = '12'...
but it is not worked for this query
UPDATE xcart_orders set status = '"+Status+"',orderid = '"+Orderid+"' where orderid = '"+Orderid+"'...
so I wish to need to use above query and click the any order in 2nd activity means it is go to 3rd activity...now i have to click the change status order button means it is go to 4th activity..the fourth activity i have to change the status means that status is updated in that particular orderid..please how can i do develop this....please help me...how is manage the code here...
Refer my code here:SingleMenuItemActivity(SingleMenuItemActivity)
http://pastie.org/4656261InsertionExample) http://pastie.org/4656262(update)

A: You can't update like this because you are updating same value on which you are putting where condition.
Suppose you want to update orderid 12 to 13 then your query should like this
String orderid1 = 13;
String orderid2 = 12;
"UPDATE xcart_orders set status = '"+Status+"',orderid = '"+Orderid1+"'  where orderid = '"+Orderid2+"'"
But in your case you are using same variable at both places, It will work if upcoming values exists in your database but there is no meaning for executing that query in that case.
If you still have any doubt revert back.


text:
Q: automating download of files with urllib2 and or wget I was trying to figure out how to download files from a web hosting site like zippy share. I saw this post How to download in bash from zippyshare? that shows how to use wget, and manually add in the cookie from the browser and add that to the header in wget. That works. But I want to use python, and get the cookie and then execute wget, so that I can do this programmatically(example: scraping a bunch of download links).
I came up with this hacky script to get the cookie and execute the wget command but it seems that the cookie is not good because I get a 302 redirect:
import urllib2, os
class HeadRequest(urllib2.Request):
    def get_method(self):
        return "HEAD"

url = "http://www67.zippyshare.com/d/64003087/2432/Alex%20Henning%2c%20Laurie%20Webb%20-%20In%20Your%20Arms%20%28Joy%20Kitikonti%20Remix%29%20%5bquality-dance-music.com%5d.mp3"
referer = "http://www67.zippyshare.com/v/64003087/file.html"
response = urllib2.urlopen(HeadRequest(url))

headers = response.info()
jcookieString = headers['Set-Cookie'].split(';')[0] #[11:]
# print headers
print "jcookie string " + jcookieString

wgetString = "wget " + url + " --referer=" + referer + " --cookies=off --header \"Cookie: " + jcookieString + "\"" + "--user-agent=\"Mozilla/5.0 (Windows NT 6.0) Gecko/20100101 Firefox/14.0.1\""
os.system(wgetString)

I also tried using python's cookielib, but got the same behavior of the 302 redirect. Thanks.
EDIT: using requests here is the code now persisting the cookie that comes from the referer request because I am using the session to make the request...yet still no go:
looking at the response.history shows that the 302 redirect is still happening for some reason.
import requests

downloadUrl="http://www67.zippyshare.com/d/3278160/42939/Andre%20Nazareth%20-%20Bella%20Notte%20%28Original%20Mix%29%20%5bquality-dance-music.com%5d.mp3"
referer= "http://www67.zippyshare.com/v/3278160/file.html"
header={"user-agent": "\"Mozilla/5.0 (Windows NT 6.0) Gecko/20100101 Firefox/14.0.1\"", 'referer': referer}
refererSession = requests.Session()
refererSession.get(referer)

downloadResponse = refererSession.get(downloadUrl, headers=header)
print downloadResponse.request.headers
print downloadResponse.status_code
if downloadResponse.status_code == 200:
    mp3Name = "song2.mp3"
    song = open(mp3Name, "wb")
    song.write(downloadResponse.content)
    song.close()

A: Using a system call from within python should really be left for situations where there is no other choice. Use the requests library, like so:
import requests
header={"user-agent":\"Mozilla/5.0 (Windows NT 6.0) Gecko/20100101 Firefox/14.0.1\"",
'referer': referer}
cookies = dict(cookie_name='cookie_text')
r = requests.get(url, header=header, cookies=cookies)

If it doesn't work, maybe the settings itself aren't suitable for what you are trying to do. I am perplexed why you both set the cookie and have cookies=off in the wget statement.


text:
Q: How I unit test with Entity Framework and Moq when using a repository pattern with Interface? I am new to testing and have been tasked at work to setup some simple CRUD test on a MVC EF Core Repository for some code that I wrote using MSTest.
One of get the methods eager loads a list using include, other wise it basic CRUD.
However I keep running into a discussion about either using in-memory db  or mocking the ef core db and dbsets? What would be the best way to test an MVC EF Core Repository pattern with CRUD operations in a unit test?
 public DbSet<ResourceTags>? ResourceTags { get; set; }

 public class ResourceTags
 {

    [ForeignKey(nameof(ResourceRequest))]
    [Key]
    [Column(Order = 0)]
    public byte[] ResourceId { get; set; }

    [Key]
    [Column(Order = 1)]
    public string Tag { get; set; }

    public ResourceRequest ResourceRequest { get; set; }
}

   public ResourceTags? AddResourceTags(ResourceTags resourceTag)
   {
        try
        {
            var entity = this.prismContext.ResourceTags;

            if (entity != null)
            {
                var response = entity.Add(resourceTag);
                this.prismContext.SaveChanges();
                return response.Entity;
            }
        }
        catch
        {
            throw new Exception();
        }

        return null;
    }

    [TestMethod]
    public void AddResourceTagsSavesAResourceTagsViaContext()
    {
        Random rnd = new Random();
        var id = new byte[32];
        rnd.NextBytes(id);
        var text = "tagtext";
        string convertedId = Convert.ToBase64String(id);

        var mockResourceTag = new Mock<DbSet<ResourceTags>>();
        var mockPrismContext = new Mock<PrismContext>();

        mockPrismContext.Setup(m => m.ResourceTags).Returns(mockResourceTag.Object);

        var azureRepository = new AzureRepository(mockPrismContext.Object);
        var tag = new ResourceTags()
        {
            ResourceId = id,
            Tag = text,
        };

        var response = azureRepository.AddResourceTags(tag);
        Assert.IsNotNull(response);
    }

A: If you only use simple CRUD queries, and your queries do not depend on specific DB functions, e.g., EF.Functions, then you should use InMemory Database, or SQLite with in-memory mode, which has better compatibility with real DBs.
Mocking the DbSet will result in poor testing because your test may pass but when EF tries to translate your LINQ query to SQL at runtime, it may throw an exception, and you want to ensure that your translations work.
A third option would be to test against a docker container, i.e., if you use SQL Server, you test against an SQL Server instance running in docker. This way you remove any compatibility issues between DBs.
Sources:

*

*Testing EF Core Applications

*Testing against your production database system


text:
Q: Oracle times ten embedded in a java application Can someone point to me some documentation on how to run the Oracle times ten database in an embedded mode within a java application?
I would like to run times-ten as a replacement for HSQLDB.

A: Oracle does not as far as I know have an embedded mode for Java programs.  What you most likely want is the Oracle JDBC driver to talk to a Oracle server "somewhere".
Another approach which might be valid for you, is running your code inside the JVM running in most modern Oracle installations.

A: While the Oracle TimesTen In-Memory Database 11g Overview mentions the word "embedded":

Oracle TimesTen In-Memory Database is
  a memory-optimized relational database
  that empowers applications with the
  instant responsiveness and very high
  throughput required by today's
  real-time enterprises and industries
  such as telecom, capital markets, and
  defense. Deployed in the application
  tier as an embedded or standalone
  database, Oracle TimesTen In-Memory
  Database operates on databases that
  fit entirely in physical memory using
  standard SQL interfaces. It can also
  be used as an in-memory database cache
  for the Oracle database to enhance the
  response time and throughput of user
  applications.

I couldn't find obvious instructions in the product documentation. I'll let you dig it deeper :)


text:
Q: Return order by Ecom express shipping method Magento2 In Magento 2, I am using Ecom express shipping method and it working fine.
But I have to use same shipping method for return order as well.
Please anybody have worked on it or have any useful document or any idea ?
Thank you,


text:
Q: How to delete files from Dropbox with PHP api First of all, I can properly upload and download files from Dropbox with the PHP api.
This is how I upload files:
// Upload files
$file = fopen("default.png", "rb");
$size = filesize("default.png");

$client->uploadFile("/default.png", Dropbox\WriteMode::add(), $file, $size);

This is how I download files:
// Download Files

$client->getFile("/default.png", fopen("default.png", "wb"));

Is there a api call to delete files from within the folder your app created. For example, my app creates a folder called Crave Crap. Inside, that folder is an image. That user only has access to that image within the folder Crave Crap within their Dropbox account for a short amount of time.
Is this possible?
EDIT - What API am I using?
I'm not the best at answering this question. I have been following a video series here. I downloaded the api by using the terminal directly on composer.json.
Composer.json
{
  "require": {
    "dropbox/dropbox-sdk": "1.1.*"
  }
}

Code in Terminal
composer install

A: It looks like you're using the Dropbox PHP Core SDK. To delete a file or folder using that SDK, you can use the delete method.
Using it would look like:
$client->delete("/default.png");


text:
Q: intelliJ: option+return to import not working If place my selection on an unresolved variable (roles in below image) and press option+return I'm supposed to get suggestions on imports that I can add to resolve the variable.

As you can see in the screenshot, I don't get the import suggestions anymore. I think this broke two updates ago, for me.
Adding imports on the fly still works. Import suggestions when I add imports by typing still works.
Any idea on what is wrong with my settings? I'm developing in Javascript using IntelliJ Ultimate.

A: Please make sure that  Missing import statement inspection is enabled in Preferences | Editor | Inspections JavaScript | General.
Please also check the JavaScript | General | Unresolved JavaScript function and JavaScript | General | Unresolved JavaScript variable inspections


text:
Q: Influxdb(single node) scaling to ~200 writes per second What is the maximum number of points that can be written to influxdb (single node) per second? Is it feasible to scale influxdb without going for the paid cluster? And should I consider elasticsearch instead of influxdb for time series data (~3000 bytes/sec/user) if I am expecting around 60 concurrent users?

A: Depends on hardware.
Limiting factors are

*

*Cardinality of series in the DB (total unique series)

*WAL disk throughput (this could be put on tmpfs if you don't have SSD)

*Data disk throughput (use SSD for best results)

*RAM (more is better)

*CPU for ingestion, indexing and queries

How far a single node can go largely depends on these and on the workload.
For write-heavy workloads of low cardinality, CPU generally tends to run out faster than anything else, assuming SSDs are used and disk I/O has been optimised accordingly.
After that, cardinality is the biggest limiting factor. Schema design plays a huge role, much bigger than number of nodes.
From some benchmarks I have done, a single node easily scales to ~70K series per second, with CPU being the limiting factor. This was on an old version though, likely higher than that now. Again, largely depends on data and schema design.
It is feasible to scale it without paid cluster by adding separate nodes, but not if you want to keep a homogeneous view (single source of all your data). Scaling vertically (more CPU, RAM) works only as long as cardinality remains consistent, meaning more data points for roughly same number of series.
InfluxDB suggest up to 250K writes / second with 25 queries per second on up to 1M unique queries is feasible on a single node. See hardware guidelines.
For the amount of data you have single node is more than enough - size of data does not matter, number of series does. Avoid elasticsearch for time series data - needs much more infrastructure to handle same amount of data.


text:
Q: Android: ViewGroup Overlapping When Adding Children within Activity My situation is as follows:
In my layout xml, I have a general LinearLayout serving as a master container and I want to populate the contents based on a paging system all contained within the single activity.
My Java Code is as follows:
private void goToPage(int pageNum){
    LinearLayout layout = (LinearLayout)this.findViewById(R.id.layoutRadioGroups);

    //Clear Views
    layout.removeAllViews();

    //Figure out array positions based on page number
    if (pageNum < this.PAGE_NUM)
        this.LAST_QUESTION_START -= this.NUM_PER_PAGE[pageNum];
    else{
        if (pageNum > 0)
            this.LAST_QUESTION_START += this.NUM_PER_PAGE[pageNum - 1];
        else
            this.LAST_QUESTION_START = 0;
    }
    this.PAGE_NUM = pageNum;

    //Grab my array values, create a TextView, and add it to the layout
    for (int i=this.LAST_QUESTION_START; i < this.LAST_QUESTION_START + this.NUM_PER_PAGE[pageNum]; i++){
        TextView tv = new TextView(layout.getContext());
        tv.setText(this.QUESTIONS[i]);
        tv.setId(i);
        layout.addView(tv);
    }
}

So it clears all views (which would be only TextView's), figures out the correct array values that will formulate the TextView objects, then adds them to my layout.
Now Page 0 displays correct, when I click my next button, page 1 displays correctly as well. But when I go to page 2, the contents from page 1 are still there, and the contents from page 2 are overlayed on top.
I'm fairly new to Android Development so I'm not sure I'm not refreshing something or invalidating something, but I'm puzzled. Any ideas folks?
Thanks!

A: Figured out the problem.
This overlap issue only happens if you have the android:windowBackground set to @null for the application.
This overlap issue would even happen if you're just setting the text of a textview to the array values. You don't have to actually add views to a layout or anything.
Moral of the story, set things up properly at the beginning.
That being said, does anyone have any idea why this would be happening?


text:
Q: Add ROI to 1D image (intensity plot etc.) Try to add ROI of determined position to 1D image (intensity plot, or line scan proflie).  It does not work, could not find the function by google, is there correct codes?
number d0, d1
image spc:=getFrontImage()
spc.getSize(d0,d1)

imagedisplay imgdisp = spc.ImageGetImageDisplay(0)

ROI roi_1 = NewROI()

ROISetRectangle( roi_1, 0, 100,d1 , 200 )

imgdisp.ImageDisplayAddROI( roi_1)

imagedisplaysetroiselected(imgdisp, roi_1,1)

A: The exact error message when running your code is:

This very accurately tells you the problem: Not all types of ROIS (Rectangle, Line, Lasso, Point,...) are suitable for all kind of displays. In particular, you can't draw a rectangle-ROI on a LinePlot display.
In fact, LinePlot displays support a single type of ROI: Range-ROIs.
So, the code for you problem is:
image spc:=getFrontImage()
imagedisplay imgdisp = spc.ImageGetImageDisplay(0)

ROI roi_1 = NewROI()

ROISetRange( roi_1, 100, 200 )

imgdisp.ImageDisplayAddROI( roi_1)

imagedisplaysetroiselected(imgdisp, roi_1,1)


text:
Q: Tailwind transition width I'm having trouble understanding how I can use TailwindCSS transition utilities to perform a simple width transition in this Angular component.  For example, the button below usually displays an SVG icon.  However, occasionally, it displays a text message.  When the text message is displayed instead of the SVG icon, the width of the button changes.  I would like to add a transition to the width change (in both directions) but I cannot figure out how.  Any help appreciated!
<button class="bg-green-600 text-green-100 ring-green-400 p-4 rounded-full focus:outline-none">
  <span *ngIf="buttonText" class="font-semibold">{{buttonText}}</span>
  <svg *ngIf="!buttonText" xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
  </svg>
</button>

A: I think you need the transition-duration css property which corresponds to a transition-{number} tailwind class https://tailwindcss.com/docs/transition-duration. You can also use a transition timing function https://tailwindcss.com/docs/transition-timing-function
EDIT
The problem isn't with tailwind, but rather with css itself take a look at this css-trick https://css-tricks.com/using-css-transitions-auto-dimensions/ Sorry I didn't notice this earlier.
One way to fix this issue is to set the width css property to it's actual computed width.


text:
Q: How do you query MongoDB by pairs of keys using pymongo I have a list of pairs of things, of the form e.g. [['A', 'B'], ['C', 'D']]. I want to query MongoDB for records in a specific collection which have properties matching both of these things.
For example, here is what I would want to get back:
[{'_id': ObjectId('...'),
  'first_property': 'A',
  'second_property': 'B'
 },
 {'_id': ObjectId('...'),
  'first_property': 'C',
  'second_property': 'D'
 }]

How do I query simultaneous properties using pymongo?

A: I got pretty good performance out of the following pattern:
client.find({'$or': [{'property_a': value_a, 'property_b': value_b} for value_a, value_b in some_list_of_two_element_tuples]}

This creates a very long $or statement out of our requested tuples.


text:
Q: How to change the integral variable and integral upper/lower limit? I am dealing with the symbolic operation of taking the antiderivative, e.g., Integrate[f, x]  (where $f$ represents  a  complicated function which cannot return integral value directly)
I want to change the integral variable $x \mapsto x+a$,so I simply % /. x-> y + a. The result was that the form of integral seemly change to Integrate[f, y + a]
But this produces the error:

Invalid integration variable or limit(s) in y + a.

So I have two questions:

*

*How do I tell Mathematica to deal with the change of integral variable automatically? That is, how produce the change of $d(y + a)$ to $dy$.

*In a definite integral, is there some ways to change the integral upper and lower limits automatically in the same way as I want to change the integral variable?

A: A simple replacement of the variable won't do if you want to perform general integration by substitution. We can define a function like the following for this task:
intSub[x_ -> g_, y_][expr_] :=
 expr /. {Integrate[f_, x] :> Integrate[(f /. x -> g) D[g, y], y],
   Integrate[f_, {x, a_, b_}] :>
    Integrate[(f /. x -> g) D[g, y],
     Prepend[y /. Solve[g == x, y][[1]] /. {{x -> a}, {x -> b}}, y]]}

Applications:
Integrate[f[x], x] // intSub[x -> y + a, y]

$\int f(a+y) \, dy$
Integrate[f[x], x] // intSub[x -> -y, y]

$-\int f(-y) \, dy$
Integrate[f[x], {x, a, b}] // intSub[x -> g[y], y]
Solve::ifun: Inverse functions are being used by Solve, so some solutions may not be found; use Reduce for complete solution information.

$\int_{g^{(-1)}(a)}^{g^{(-1)}(b)} f(g(y)) g'(y) \, dy$
Note that the change of upper and lower limits only works as expected if Solve[g == x, y][[1]] works out the correct inverse of x = g(y).

A: If I understand the question correctly, the following should work.  Beginning with
int = Integrate[f[x], {x, b, c}];

Then,
int /. {f[x] -> f[x - a], {x, b, c} -> {x, b + a, c + a}}
(* Integrate[f[-a + x], {x, a + b, a + c}]  *)

shifts x by a while leaving the value of the integral unchanged.  For instance,
Integrate[Sin[x], {x, b, c}]
(* Cos[b] - Cos[c] *)

Unevaluated[Integrate[Sin[x], {x, b, c}]] /. {Sin[x] -> Sin[x - a],
    {x, b, c} -> {x, b + a, c + a}}
(* Cos[b] - Cos[c] *)

as expected.  (Unevaluated is used to prevent this simple integral from being evaluated before the change of argument and limits.)  If changing the argument and limits independently is desired, then use something like
int /. {f[x] -> f[x - a], {x, b, c} -> {x, b + u, c + v}}

or whatever is desired.


text:
Q: Difference between Game1.GraphicsDevice and graphics.GraphicsDevice In XNA 4.0, what's the difference between the GraphicsDevice property of my game class and the GraphicsDevice property of the "graphics" variable? BTW, "graphics" is of type GraphicsDeviceManager.
I'm using Visual Studio 2010 if that matters.

A: Nothing. Try it yourself:
Console.WriteLine(ReferenceEquals(graphics.GraphicsDevice, this.GraphicsDevice));

Put that somewhere like inside LoadContent. You will find that it outputs true. They both refer to the same object.
For the sake of readability, you should generally use Game.GraphicsDevice.

The underlying behaviour is that GraphicsDeviceManager is an IGraphicsDeviceService (which provides a GraphicsDevice member). When you create GraphicsDeviceManager, it adds itself to Game.Services in its constructor (see how you pass a reference to your Game into its constructor).
Game sets its GraphicsDevice member from any IGraphicsDeviceService in its Services list. That way, you can replace GraphicsDeviceManager with your own class that implements IGraphicsDeviceService - if you happen to be crazy ;)
GraphicsDeviceManager is also a IGraphicsDeviceManager, which Game uses in a similar way (through Game.Services) to manage creating the graphics device.

A: GraphicsDeviceManager manage GraphicsDevice and you shouldn't use GraphicsDevice directly. It could be changed so instead of it just use GraphicsDeviceManager.GraphicsDevice property if you need.


text:
Q: Choose the correct option: Consider the function $f (z) = z +2z^2 +3z^3 +··· = \sum_{n≥0} nz^n$ defined on the open disk $\{z ||z| < 1\}$. Choose the
correct option:
(a) f is not injective but attains every complex value at least once.
(b) f is injective but does not attain every complex value.
(c) f is injective and attains every complex value.
(d) None of the above.
My Try: $f(z)=z +2z^2 +3z^3 +··· =z(1+2z+3z^2+...)=z\frac{d}{dz}\frac{1}{1-z}=\frac{z}{(1-z)^2}.$
For injectivity, Consider the equation.
$f(a)=f(b)\implies a(1-b)^2=b(1-a)^2\implies (a-b)(ab-1)=0$. So, when the product of two numbers is 1. then also, above equation satisfies. So, It is not injective. For surjectivity, I consider the equation $c\in \mathbb C$ $c=\frac{z}{(1-z)^2} $. I got $z$ in terms of $c$. So, (a) is the apt answer for this question. Am I judging correctly?

A: This is the famous Koebe function which is the maximal univalent function - or Riemann map if one wishes - on the disc in many ways (under the usual normalizations, $f(0)=0, f'(0)=1$) - eg for coefficients (Bieberbach conjecture/de Branges Theorem), for integral means (Baernstein theorem) etc; its image omits the part of the negative axis that starts at $-\frac{1}{4}$ and goes to $-\infty$ which can be seen by looking at the image of the unit circle under it or even simpler, noting that $4K(z)=(\frac{1+z}{1-z})^2-1$ and then the function inside the square root is the Mobius transform of the unit disc onto the right half-plane, squaring means the image of the disc omits only the negative axis, then subtract $1$, we omit the part from $-1$ to $-\infty$ and then dividing by $4$ etc; injectivity on the unit disc follows trivially from this representation too


text:
Q: hql Left Outer Join with join table can I use left outer join with a join table?
i have player entity and member and member_player(join table),i want to store the result in a new object so i do that but i have a path exception join because no relationship between player and member_player
SELECT  new table (p.playerName_ar,p.playerName_fr,p.playerName_en, p.playerImage,preference_player.identifier)
FROM Player as  p
LEFT OUTER JOIN preference_player  ON  p.playerId = preference_player.playerId"


text:
Q: Full Text Search: find similar software names I'm looking for a full text search algorithm that will allow to find similar program names, for example "Mozilla Firefox" and "Firefox 3.5, or "Adobe Reader" and "Adobe Acrobat Reader v10". The Levenshtein distance is too inefficient in this case, since spelling doesn't change.
It has to use serial scanning (not indexing).
I need maximum precision and minimum errors. What would you recommend?
Thanks!

A: Pattern comparison
I used the following to auto-correct some domain names.
The idea is to look at small patterns, for instance 2 chars sequences. Each time that such a sequence is found, the "score" is incremented for the compared sequence.
The highest scores are likely to look similar.
Ex:
Mozilla Firefox
 => ['mo', 'oz', 'zi', 'il', 'll', 'la', 'a ', ' f', 'fi', 'ir', 're', 'fo', 'ox']
Results:

*

*'Firefox 3.5' => 5,

*'Adobe Reader' => 0,

*'Adobe Acrobat Reader v10' => 1

Automatic classification using compression
This one is not full-text based.
The idea here, expressed in this document, is to compare the compression of the concatenation of two items with the concatenation of the compressed items.
Let c be the function that returns the size of the compressed item:
d = c(A) + c(B) - c(A+B)
The smaller d is, the closer A and B are.
An interesting property is that the principle is type-independent and can be used with binaries like music, pictures, videos etc.
Another link, easier to read but in French.
Use SGDB full text functionalities
I am a bit rusty on SQL Server but SQLite or MySQL offer a full text search.
The results include a "rank" value, which can be considered as a similarity score.
In MySQL:
SELECT
  t.*,
  MATCH(my_field) AGAINST 'Mozilla Firefox' as relevance
FROM
  table t
WHERE
  MATCH(my_field) AGAINST 'Mozilla Firefox'
ORDER BY relevance DESC
LIMIT 100


text:
Q: Put Regular Expression "." on keypress of Textbox Hi I have a Javascript code of Key press where I want to put "." and numbers on the text box. I am able to put numbers but not ".". I have the Javascript and HTMl and also Fiddle link. Can anyone help me with that?
<script>
    var aa_zChar = new Array(' ');
    var aa_maxphonelength = 8;
    var aa_phonevalue1;
    var aa_phonevalue2;
    var aa_cursorposition;
    function aa_ParseForNumber1(object){
      aa_phonevalue1 = aa_ParseChar(object.value, aa_zChar);
    }
    function a_ParseForNumber2(object){
      aa_phonevalue2 = aa_ParseChar(object.value, aa_zChar);
    }
    function aa_up(object,e) {
      if(e){
        e = e
      } else {
        e = window.event
      }
      if(e.which){
        var keycode = e.which
      } else {
        var keycode = e.keyCode
      }
      aa_ParseForNumber1(object)

        aa_ValidatePhone(object)

    }
    function aa_down(object,e) {
      if(e){
        e = e
      } else {
        e = window.event
      }
      if(e.which){
        var keycode = e.which
      } else {
        var keycode = e.keyCode
      }
      aa_ParseForNumber2(object)
    }

    function aa_ValidatePhone(object){
      var p = aa_phonevalue1
      p = p.replace(/[^\d]*/gi,"")
        object.value=p

    }

    function aa_ParseChar(sStr, sChar)
    {
      if (sChar.length == null)
      {
        aa_zChar = new Array(sChar);
      }
        else aa_zChar = sChar;
      for (i=0; i<aa_zChar.length; i++)
      {
        sNewStr = "";
        var iStart = 0;
        var iEnd = sStr.indexOf(sChar[i]);
        while (iEnd != -1)
        {
          sNewStr += sStr.substring(iStart, iEnd);
          iStart = iEnd + 1;
          iEnd = sStr.indexOf(sChar[i], iStart);
        }
        sNewStr += sStr.substring(sStr.lastIndexOf(sChar[i]) + 1, sStr.length);
        sStr = sNewStr;
      }
      return sNewStr;
    }
    </script>

HTML
<input name="name" type="text" maxlength="100" id="name" value="" onKeyDown="aa_down(this,event);" onKeyUp="aa_up(this,event);" />

http://jsfiddle.net/4emDC/2/

A: Almost there. You just need to change the regex so that it accepts . alongwith numbers.
One of the correct regular expressions would be /[^\d.]/gi


text:
Q: How to retrieve list of different object types from Firebase? I'm facing a problem that I have a list of different object types and I'm fetching that list using AddClildEventLitener(), so the problem is to retrieve those objects I should give specific object to "getValue(SpecificObject.class)".
So, How can I achieve this step?
Example of realtime DB structure:
-List
 -random id1(Object)
  -title
  -description

 -random id2(Object)
  -first name
  -last name

 -random id3(Object)
  -title
  -image

 -random id4(Object)
  -title
  -description
  -image

A: I'm pretty sure I've answered this not too long ago, but I'll try again.
The getValue(SpecificObject.class) method maps the properties from the DataSnapshot to an instance of the SpecificObject class.
If you have multiple different object types in your database, you will:

*

*Have a separate Java/Kotlin class for each object type.

*Need to include an indication of each object's class in the database.

*Read that indicator (typically a property) first, and then...

*Call getValue(...) with the correct class for that type.

Also see:

*

*How to retrieve correct subtype from firebase android getValue() for an example of the condition and call in step 3 and 4.


text:
Q: How to Scrape data from list I'm trying to scrape data from [https://www.idealista.com/maps/madrid-madrid/][1]
I'm not getting the whole content of the page. I used BeautifulSoup python library. what I need is the list of the streets available on the webpage.
I'm a beginner to web scraping, Can anyone help on how to proceed or which libraries to use to get this done?


text:
Q: How to overlap a CSS background over an  tag? I have an  tag inside an  tag:

The  tag has the "contain-video" class, so I want to overlap a background image over the actual image:
//css file
.contain-video img {
    background: url('images/contain-video.png') no-repeat !important;
    z-index: 1;
}

but the background image is not shown. Any idea of how to achieve it?

A: To overlap an element on top of a child element, using css only, you can use the pseudo-elements :before or :after
http://jsfiddle.net/LpkwH/2/
.image-link {
    position:relative;
    display:inline-block;
    padding:0;
    margin:10px;
}

.contain-video:after{
    content:'';
    display:block;
    position:absolute;
    top:0;
    left:0;
    right:0;
    bottom:0;
    z-index:1;
    background-repeat:no-repeat;
    background-position:center;
    background-image:url(http://www.labiennale.org/img/play_icon.png);
}

HTML:

A: You could supply an overlay div with image background inside the anchor tag, with position: relative for the tag and position: absolute for the inner div and making the inner div fit its parent (as long as the a is set to display: block, as that's normally an inline element and thus it does not expand to contain the img, which is providing the size for the overlay).
See this fiddle for an example (hovering over the overlay div shows what's below): http://jsfiddle.net/wz7mx/3/
Note that there is no need to explicitly set z-index.


text:
Q: php-Auto Subtract from Multiple Join Table I created a table from these 2 tables using LEFT JOIN :

*

*Input (code, name, quantity1)

*Output (code, name, quantity2)

What I'm trying to do is to subtract those quantity (total=quantity1-quantity2), so the final table will have structure like this (code, name, quantity1, quantity2, total).

        Code
        Name
        Quantity In
        Quantity Out
        Total

    <?php
       include "koneksi.php";
       $query = "SELECT A.`code` , A.`name` , A.`quantity1` , B.`quantity2` FROM `input` AS A LEFT JOIN `output` AS B ON B.`code` = A.`code`";
       $sql = mysqli_query($connect, $query);
       while($data = mysqli_fetch_array($sql)){

       echo "
";
       echo "".$data['code']."	";
       echo "".$data['name']."	";
       echo "".$data['quantity1']."	";
       echo "".$data['quantity2']."	";
       echo "".$data['total']."	";
       echo "
";
       }
    ?>

I knew how to do Auto Sum/Substract if only the input in text type (the quantity input manually), but in this case the quantity come from two another tables. I'm quite new on this, hope anyone can help me. Thanks.


text:
Q: Unable to clear the table in RCP I am new in RCP. I have created one table and using TableEditor for some columns for putting Label and Progress bar.
But For some cases I want to clear the table. For textual content table.removeAll(); is working but its not clear the Label and Progress bar;
public void createPartControl(Composite parent) {
        toolkit = new FormToolkit(parent.getDisplay());
        compositeObj = toolkit.createComposite(parent, SWT.NONE);
        GridLayout layout = new GridLayout();
        compositeObj.setLayout(layout);

        GridData gridData = new GridData();
        gridData.verticalAlignment = GridData.FILL;
        gridData.horizontalSpan = 4;
        gridData.grabExcessHorizontalSpace = true;
        gridData.grabExcessVerticalSpace = true;
        gridData.horizontalAlignment = GridData.FILL;

        myTable = new Table(compositeObj,
                SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER | SWT.CHECK);
        myTable .setLayoutData(gridData);

        final int[] bounds = { 30, 80, 100, 80, 100, 50, 100, 50, 50, 70, 50, 50 };
        for (int i = 0; i < titles.length; i++) {
            TableColumn tblColumn = new TableColumn(btsTable, SWT.NONE);
            tblColumn.setText(titles[i]);
            tblColumn.setWidth(bounds[i]);
            tblColumn.setResizable(true);
            tblColumn.setMoveable(true);
            tblColumn.pack();
        }
        myTable.setHeaderVisible(true);
        myTable.setLinesVisible(true);

        for (int i = 0; i < receiverViewDataProvider.size(); i++) {
            items[i] = new TableItem(btsTable, SWT.NONE);
        }
       fillData();
}

Table Filling Method
{
        items[cntIndex].setText(1, sID);

        items[cntIndex].setText(2, sName);

        editor[cntIndex] = new TableEditor(myTable);
        signalStrengthLabel1[selCnt] = toolkit.createLabel(myTable, sText, SWT.CENTER);
        editor[cntIndex].grabHorizontal = true;
        if (bIsAllow == true)
            editor[cntIndex].setEditor(nameLabel1[selCnt], items[cntIndex], 3);

        editor[cntIndex] = new TableEditor(myTable);
        pbReverse[selCnt] = new ProgressBar(myTable, SWT.HORIZONTAL);
        pbReverse[selCnt].setMinimum(0);
        pbReverse[selCnt].setMaximum(30);
        signalStrengthLabel1[selCnt].setText("" + iLevel + "");
        pbReverse[selCnt].setSelection(iLevel);
        editor[cntIndex].grabHorizontal = editor[cntIndex].grabVertical = true;
        if (bAllow == true)
            editor[cntIndex].setEditor(pbReverse[selCnt], items[cntIndex], 4);
}

Tried
   for (int Index = 0; Index < Cnt; Index++) {
    nameLabel1[btsIndex].setText("");
pbReverse[selIndex].setMaximum(0);
    pbReverse[Index].setVisible(false);
    editor[Index].dispose();
}
myTable.removeAll();

I am getting below result but want to clear the whole table


text:
Q: Angular 2 and Firebase SDK I've been trying to get the Angular2 quickstart app to work with Firebase (see this repository). I've installed the latest version of Firebase, attempted to load firebase using SystemJS (see systemjs.config.js) and tried importing firebase and using the function initializeApp (see app.component.ts). However, I keep getting the error firebase.initializeApp is not a function in the browser console. Am I using SystemJS correctly to load firebase.js?
Note: To replicate the error, you should just be able to do npm install followed by npm start.

A: One change: from
import * as firebase from 'firebase';

to
import {firebase} from 'firebase';

is enough to make your example work with firebase 3.6.
However, I'd say it's working by accident. firebase.js does not look like a module at all, it does not use module.exports or amd define, it just creates global variable firebase with the following properties:
INTERNAL: Object
Promise: Promise()
SDK_VERSION: "3.6.4"
User: (a, b, c)
__esModule: true
app: a(a)
apps: (...)
get apps: ()
auth: (c)
database: (c)
default: Object
initializeApp: (a, c)
messaging: (c)
storage: (c)
__proto__: Object

Probably, it's the presence of __esModule that makes SystemJS to wrap it in another object - if you look in the debugger at the result of import * as firebase from 'firebase' it contains single property also named firebase which is the actual module that you need.
Interestingly, the firebase.d.ts is written in such a way that
import {firebase} from 'firebase';

firebase.initializeApp(...);

works, but seemingly equvalent
import * as firebase from 'firebase';

firebase.firebase.initializeApp(...);

does not typecheck.

A: There is a workaround for this issue here and, with it, I was able to get a plunk working with the latest versions of Firebase (3.6.7) and AngularFire2 (2.0.0-beta.7).
How it works, I have no idea, as I only use SystemJS with Plunker, but it involves replacing this:
firebase: {
    main: 'firebase.js'
}

with this:
firebase: {
    defaultExtension: 'js',
    main: './firebase-browser.js'
}

in the packages property of the configuration that's passed to System.config.


text:
Q: How to dismiss an AlertDialog in Flutter? I have a utility class that shows an alert dialog to which I'm passing a VoidCallback which usually contains Navigator.of(context).pop() to dismiss the alert dialog. However it throws a _CastError (Null check operator used on a null value) on button press.
class CustomAlertDialog {
  static void show(
    BuildContext context, {
    Key? key,
    required VoidCallback onPress,
  }) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        content: ElevatedButton(
          onPressed: onPress,
          child: const Text(
            "test",
          ),
        ),
      ),
    );
  }
}

If I explicitly pass Navigator.pop(context,true) to the onPress method it works just fine, however I need this to be a reusable static method with different onPress functionalities that does more than just pop the dialog.
class CustomAlertDialog {
  static void show(
    BuildContext context, {
    Key? key,
    required VoidCallback onPress,
  }) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        content: ElevatedButton(
          onPressed: () {
            return Navigator.pop(context, true);
          },
          child: const Text(
            "test",
          ),
        ),
      ),
    );
  }
}

A: Your Parent Context does not contain the CustomAlertDialog.
You should pass the context provide by the builder into the onPress function and call navigator.pop with the context provided in the builder function in showDialog.
class CustomAlertDialog {
  static void show(
    BuildContext context, {
    Key? key,
    required void Function(BuildContext context) onPress,
  }) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        content: ElevatedButton(
          onPressed: (){ onPress(context) },
          child: const Text(
            "test",
          ),
        ),
      ),
    );
  }
}

A: you can try this :
void show(BuildContext context, String title, {Function callback})

 onPressed: () {
          if (callback != null) {
                   Navigator.pop(context, true);
                   callback();
            } else {
                      Navigator.pop(context, true);

            }
         },


text:
Q: C++ 11 How to reference class methods in other classes or source files I'm back to C++ after a lapse of several years with a proof of concept.  I have a hpp file that defines a class, a cpp file with the class methods, and a main.cpp for testing.  I'm attempting to create a tcp server that runs in its own thread (only called once).  I started with all the code in the same cpp file and got it to work but I get compile errors now that I've put the class and the methods in their own files.
I've searched but not found anything that works.  I've tried using extern, the 'singleton' method, etc. which all result in various error messages.  I know that I'm not providing a correct reference to the methods.
tcpserver.hpp:
#ifndef __TCP_SERVER_HPP_INCLUDED__
#define __TCP_SERVER_HPP_INCLUDED__

#include <string>

class Server {
    public:

        static void *tcp_server(void * dummy);
        static void hello();
        static int parseCmd(const char *cmd, char *reply);
        static int copystring(char *reply, const char *msg);

    private:

};

#endif

tcpserver.cpp, with class methods as stubs:
#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <unistd.h>
#include <cstring>      // Needed for memset
#include <sys/socket.h> // Needed for the socket functions
#include <netdb.h>      // Needed for the socket functions
#include <string.h>

#include "tcpserver.hpp"

int Server::parseCmd(const char *cmd, char *reply) {
   //does stuff
}

int Server::copystring(char *dst, const char *src) {
    // does stuff
    return (int) ((std::string) dst).length();
}

void Server::hello() {
    std::cout << "Server says 'hello'." << std::endl;
}

void *Server::tcp_server(void * dummy) {
    const char *port = "5555";
    // does a lot of stuff
}

main.cpp:
#include <iostream>
#include <pthread.h>

#include "tcpserver.hpp"

int main() {
    Server server;
    server.hello();  // 'Canary' method FIRST ERROR

    // Initialize and set thread joinable
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

    pthread_t serverthread;
    int rc;
    // **** tcp_server method must be static ****
    rc = pthread_create(&serverthread, NULL,  server.tcp_server, NULL);
        if (rc){
          std::cout << "Error:unable to create thread," << rc << std::endl;
          exit(-1);
        }
    std::cout << "Main() started thread."  << std::endl;
    pthread_attr_destroy(&attr);
    void *status;
        rc = pthread_join(serverthread, &status);
        if (rc){
          std::cout << "Error:unable to join," << rc << std::endl;
          exit(-1);
        }

    return 0 ;
}

makefile:
all :  main.o tcpserver.o
    g++ -std=c++11 -o tcpserver main.o tcpserver.o

tcpserver.o: tcpserver.cpp tcpserver.hpp
    g++ -std=c++11 tcpserver.hpp

main.o  : main.cpp tcpserver.hpp
    g++ -std=c++11 main.cpp -lpthread

clean:
    rm -f tcpserver.o main.o tcpserver

A: Your object file compilation is incorrect:
tcpserver.o: tcpserver.cpp tcpserver.hpp
    g++ -std=c++11 tcpserver.hpp

main.o  : main.cpp tcpserver.hpp
    g++ -std=c++11 main.cpp -lpthread

These rules don't indicate that you're building object files, they both say that they're independently building and linking applications. That's why you're getting linker errors - you're not actually linking the result of compiling main.cpp with tcpserver.o.
You need to provide -c to tell gcc that you don't want to link, that you're just compiling. You also need to provide -o to tell it where to output the results. Lastly, you're trying to compile tcpserver.hpp instead of tcpserver.cpp:
tcpserver.o: tcpserver.cpp tcpserver.hpp
    g++ -std=c++11 -c tcpserver.cpp -o tcpserver.o

main.o  : main.cpp tcpserver.hpp
    g++ -std=c++11 -c main.cpp -o main.o

Or, shorter:
%.o : %.cpp tcpserver.hpp
    g++ -std=c++11 -c $< -o $@

Also, this rule is bad:
all :  main.o tcpserver.o
    g++ -std=c++11 -o tcpserver main.o tcpserver.o

The target of the rule is all, but it's actually making a file named tcpserver. So if you keep rerunning make, it'll keep rebuilding tcpserver since the file all will continue to not exist. Change the target to match the actual target. And this is where your linker flags go:
tcpserver :  main.o tcpserver.o
    g++ -std=c++11 -o tcpserver $^ -lpthread

Additionally, the include guard you're using (__TCP_SERVER_HPP_INCLUDED__) is a reserved name for the C++ standard library. Any name which contains a double underscore or starts with an underscore followed by a capital letter should not be used in your code.

A: As stated before, this is a compilation problem, with -lpthread at the wrong place.
I recommand using a simpler Makefile, taking advantage of default rules, dependancies, etc. and also setting all sorts of warnings
CXXFLAGS = -std=c++11 -Wall -Wextra -pedantic
LDFLAGS = -lpthread

tcpserver: main.o tcpserver.o
    $(LINK.cc) $^ -o $@

clean:
    rm -f tcpserver.o main.o tcpserver

# DO NOT DELETE

main.o: tcpserver.hpp
tcpserver.o: tcpserver.hpp

Note: the last 4 lines (starting with DO NOT DELETE) about dependancies were automagically added to the Makefile by the command
makedepend -Y *.cpp

These warnings will be helpful to fix errors:
 tcpserver.cpp: In static member function 'static int Server::parseCmd(const char*, char*)':
    tcpserver.cpp:14:1: warning: no return statement in function returning non-void [-Wreturn-type]
 }
 ^
tcpserver.cpp: At global scope:
tcpserver.cpp:12:34: warning: unused parameter 'cmd' [-Wunused-parameter]
     int Server::parseCmd(const char *cmd, char *reply) {
                                      ^
tcpserver.cpp:12:45: warning: unused parameter 'reply' [-Wunused-parameter]
     int Server::parseCmd(const char *cmd, char *reply) {
                                             ^
tcpserver.cpp:17:47: warning: unused parameter 'src' [-Wunused-parameter]
     int Server::copystring(char *dst, const char *src) {
                                                   ^
tcpserver.cpp: In static member function 'static void* Server::tcp_server(void*)':
tcpserver.cpp:29:17: warning: unused variable 'port' [-Wunused-variable]
     const char *port = "5555";
                     ^
tcpserver.cpp:31:1: warning: no return statement in function returning non-void [-Wreturn-type]
     }
     ^
tcpserver.cpp: At global scope:
tcpserver.cpp:28:33: warning: unused parameter 'dummy' [-Wunused-parameter]
     void *Server::tcp_server(void * dummy) {


text:
Q: Get model index inside ActiveDataProvider, Yii2 I try to get my model position inside dataProvider.
I have a listview with pager:
 Pjax::begin();
                echo ListView::widget([
                    'dataProvider' => $dataProvider,
                    'itemOptions' => ['class' => 'item'],
                    'itemView' => 'tree_part',

                    'pager' => [
                        'class' => ScrollPager::className(),
                         'enabledExtensions'=> [ScrollPager::EXTENSION_SPINNER],
                          'spinnerSrc'=> Yii::$app->request->baseUrl.'/images/spinner.gif',
                        ]
               ]);
Pjax::end();

I know i can access$model, $widget, $index in my partial view tree_part.php, but I cannot figure out how to get current $model index inside the data.
My dataprovider:
 $dataProvider = new ActiveDataProvider([
        'query' => $query,
        'sort'=> ['defaultOrder' => ['creation_date'=>SORT_DESC]],
        'pagination' => [
            'pageSize' => 12,
        ],
    ]);

So if thepagesize is 12, $index variable will only show the value of 0-11. What I need is to get "global" index out of the total count of models.
Any advice would be highly appreciated.

A: Possible solution:
 $mindex = $index + ($widget->dataProvider->pagination->pageSize * $widget->dataProvider->pagination->page);

Anyways, looking for better one.


text:
Q: How to suppress function output in Bash? I wrote a little helper to start an Android emulator which looks like this:
# START ANDROID EMULATION
android-sim () {
  if [[ -z "$1" ]]; then
    echo "No Android device supplied as argument!"
    return 1
  fi

  if [[ -d "$ANDROID_HOME" ]]; then
    cd "$ANDROID_HOME/emulator" &>/dev/null
    ./emulator "@$1" &>/dev/null &
    cd - &>/dev/null
  else
    echo "The variable ANDROID_HOME is not set to a correct directory!"
  fi
}

I tried to suppress all the generated output with &>/dev/null. For the emulator itself I also tried to put the execution in the background.
But when I run the function I still get the following output:
# before exeuction
[09:11:48] sandrowinkler:~ $ android-sim pixel-29
[1] 23217

# after execution, I closed the emulator via GUI
[09:11:55] sandrowinkler:~ $
[1]+  Done                    ./emulator "@$1" &> /dev/null
(wd: /usr/local/share/android-sdk/emulator)
(wd now: ~)

According to this superuser post and this unix post I used the right way to silence the output. So what am I doing wrong here?
PS: I would also appreciate tips to improve my Bash code.

A: You've done it correctly. That output is not from your script, but from the shell, displaying information about the background process (the PID, the done message and the working directory when in ends).
If you redirect the input externally, like this:
andoroid-sim foo > log.txt

and after execution you open log.txt, you'll see what actually your program outputed (and those messages won't be there, even if they appear in the console).

A: If the monitoring of the background job is not needed the double fork may be a solution.
 ( ./emulator "@$1" &>/dev/null & )

when the parent exit before the child process the child process is attached to process 1 so no more monitored by current shell.
also looking at the script, cd - could be avoided changing directory in the sub shell:
(
    cd "$ANDROID_HOME/emulator"
    ./emulator "@$1" &
) &>/dev/null

because current shell will not be affected by subshell change directory


text:
Q: Logical expression Is there any difference between the below statements:

*

*if(newValue && newValue != '') and

*if(newValue != '')
I have observed expression 1 in many scripts but always got confused.
Please assist!

A:
if(newValue && newValue != '').

This guards against a value of null or undefined.
Out of the possible '', 0, false, undefined and null, only the last two are not equal to '' (using !=), requiring the extra condition.
console.log(null && null != '') // null -> falsy
console.log(null != '') // truthy

var undef = void 0;

console.log(undef && undef != '') // undefined -> falsy
console.log(undef != '') // truthy

A: Answer is no,
1) for (newValue && newValue != ''),it checks whether newValue exist(non false values) and its not empty
2) for if(newValue != ''),it only checks whether newValue is not empty

A: Just one more thin I thought worth adding to the answers already posted.
As you, the OP, say: you've seen the first expression in existing code many times, so you've probably seen things like this:
if (foo && foo.bar)
{
    foo.bar();
}

In this case, this is to avoid errors in certain browsers. In most modern browsers accessing somehting like localStorage.doesNotExist won't raise errors, but not all browsers support this so we: first check if the localStorage object exists, and if so, if the property can be resolved to a non-falsy value.
The same logic applies to methods of objects, that may be different in various browsers:
var domElement = document.getElementById('foobar');//might not exist, though
if (domElement && domElement.addEventListener)
{//does element exist && does it have a method called addEventListener
    domElement.addEventListener('click', functionRef, false);
}
else if (domElement && domElement.attachEvent)
{
    domElement.attachEvent('onclick', functionRef);
}

if you were to omit the first domElement in the if statement, and simply write domElement.addEventListener, that could be the same as writing null.addEventListener which throws a TypeError (because you're trying to access a property on a primitive value)


text:
Q: Negative location for TFLite detection results Using custom model, I'm trying to locate some object on a bitmap but I get negative values for location box
e.g. my bitmap size:
myBitmap.getHeight() = 129
myBitmap.getWidth() = 202

but the results are:
item (91,4%) RectF(-0.48639297, 5.0847816, 321.28015, 190.07951)
item (10,9%) RectF(9.338188, 86.65706, 315.48764, 350.3579)

where the location is sometimes a negative number and even if it's not, the location has has values that make no sense to me. (Value result.bottom is 321, while my bitmap's height is only 129.
What am I doing wrong here? Is it the model's problem or am I interpreting the results wrong?
EDIT:
Okay, I figured out that the difference in scale probably comes from the fact that results are in pixel but bitmap height and width are in dp.
But what about negative results?

A: You're not doing anything wrong, just need to find the correct coordination:
imH, imW are your image's height and width
ymin = int(max(1,(RectF[0] * imH)))
xmin = int(max(1,(RectF[1] * imW)))
ymax = int(min(imH,(RectF[2] * imH)))
xmax = int(min(imW,(RectF[3] * imW)))


text:
Q: How to get the week number of the current quarter in Python? I've been through every question and every third party library trying to figure out a way to do this where I don't have to manually map dates.
I'm trying to get the week number of the current fiscal quarter.
Each quarter starts on the 1st of either January, April, July or October.
Given a date (string or object, it doesn't matter), I need to be able to calculate the week number of the fiscal quarter that it's in.
To make matters a little more complicated, the Fiscal year starts in April.
So for example, today, July 9th 2020 is week 2 of this Fiscal quarter (Q2), because the quarter starts in April. Similarly, the 29 and 30th of June 2020 are week 14 of quarter 1.
Most time formatting libraries and even the standard library ones have methods like ISO date where I can extract the week number fine. But it's the week number from the 1st day of the year.
I can't use arithmetic to simply remove the number of weeks to the current date as there are a different number of weeks in each quarter. Quarters can have 12, 13 or 14 weeks depending on the year.
The closest I've gotten is using the FiscalYear library which is great as it has a Fiscal Quarter class with it. Unfortunately, the inherited method isoformat() doesn't apply to it. Only the FiscalDate class, which doesn't give me the quarter which I need.
Has anyone run into this? Can someone point me in the right direction?
I'd post code snippets but it's just the 100 ways there are in Python to get the current week number (as of today, that's 28).
I've tried using rrules and deltas in dateutils but the closest I can get is the week number of the 1st quarter using offsets. The second quarter, it falls apart.
I'm happy to use pandas or any other 3rd party library if it will help me avoid hard coding the quarter dates or, god forbid, the week number to dates mappings.
Any help in the right direction would be very much appreciated.

Edit: All three answers below solved this issue for me in different ways. I struggled with which one to give the correct answer to, but I gave it to @Paul's answer as it was the one that I could follow most as someone who isn't a senior. It was also the answer that fit in with my personal use case (that I didn't mention), which was receiving a datetime object and getting the results. So that gave it the edge. Sorry to the others who provided amazing answers. I'm thrilled to have gotten the code what all I was hoping for was a nudge in the right direction. Thank you all.

A: Unless this is a very common way to reckon week numbering, I don't know if you are going to find a library that will do this exactly for you, but it's easy enough to accomplish using dateutil's relativedelta and a little logic. Here's a simple implementation that returns a tuple (quarter, week). Since you said that Q1 starts April 1st, I am assuming that the period from January 1st to April 1st is called Q0:
from datetime import date, datetime, timedelta
import typing

from dateutil import relativedelta

NEXT_MONDAY = relativedelta.relativedelta(weekday=relativedelta.MO)
LAST_MONDAY = relativedelta.relativedelta(weekday=relativedelta.MO(-1))
ONE_WEEK = timedelta(weeks=1)

def week_in_quarter(dt: datetime) -> typing.Tuple[int, int]:
    d: date = dt.date()
    year = d.year

    # Q0 = January 1, Q1 = April 1, Q2 = July 1, Q3 = October 1
    quarter = ((d.month - 1) // 3)
    quarter_start = date(year, (quarter * 3) + 1, 1)
    quarter_week_2_monday = quarter_start + NEXT_MONDAY

    if d < quarter_week_2_monday:
        week = 1
    else:
        cur_week_monday = d + LAST_MONDAY
        week = int((cur_week_monday - quarter_week_2_monday) / ONE_WEEK) + 2

    return quarter, week

Which returns:
$ python week_in_quarter.py
2020-01-01: Q0-W01
2020-02-01: Q0-W05
2020-02-29: Q0-W09
2020-03-01: Q0-W09
2020-06-30: Q1-W14
2020-07-01: Q2-W01
2020-09-04: Q2-W10
2020-12-31: Q3-W14

If I've misunderstood the first quarter of the calendar year, and it's actually the case that January 1–April 1 of year X is considered Q4 of year X-1, then you can change the return quarter, week line at the end to this (and change the return type annotation):
if quarter == 0:
    year -= 1
    quarter = 4

return year, quarter, week

Which changes the return values to:
$ python week_in_quarter.py
2020-01-01: FY2019-Q4-W01
2020-02-01: FY2019-Q4-W05
2020-02-29: FY2019-Q4-W09
2020-03-01: FY2019-Q4-W09
2020-06-30: FY2020-Q1-W14
2020-07-01: FY2020-Q2-W01
2020-09-04: FY2020-Q2-W10
2020-12-31: FY2020-Q3-W14

If this is something that is a speed bottleneck, it should probably be easy to write an optimized version of this that does not use dateutil.relativedelta, but instead calculates this based on day of week, day of year and whether or not this is a leap year (calendar calculations in Python usually go faster if you can turn it into integer operations as early in the process as possible), but I suspect that in most cases this version should be the easiest to read and understand.
If you would like to avoid the dependency on dateutil, you can replace NEXT_MONDAY and LAST_MONDAY with simple functions:
def next_monday(dt: date) -> date:
    weekday = dt.weekday()
    return dt + timedelta(days=(7 - weekday) % 7)

def last_monday(dt: date) -> date:
    weekday = dt.weekday()
    return dt - timedelta(days=weekday)

In which case you would assign the two _monday variables as quarter_week_2_monday = next_monday(quarter_start) and cur_week_monday = last_monday(dt), respectively.
As a note: if I were writing this function, I'd probably not have it return a bare tuple of integers, but instead use attrs or a dataclass to create a simple class for the purpose, like so:
import attr

@attr.s(auto_attribs=True, frozen=True, slots=True)
class QuarterInWeek:
    year: int
    quarter: int
    week: int

    def __str__(self):
        return f"FY{self.year}-Q{self.quarter}-W{self.week:02d}"

(Note that slots=True is optional, and I think not available if you use dataclasses.dataclass instead — it's just that this is a simple struct and I tend to use slots classes for simple structs).

A: I think this does what you need (or at least a very good start):
import datetime as dt

def quarter(date):
    return (date.month-1)//3 + 1

def week_in_q(d):
    year=d.year
    soq={1:dt.date(year,1,1),
         2:dt.date(year,4,1),
         3:dt.date(year,7,1),
         4:dt.date(year,10,1)}
    for i, sow in enumerate(soq[quarter(d)]+dt.timedelta(weeks=x) for x in range(5*3)):
        if sow>=d:
            return i+1
date=dt.date(2020, 1, 1)

for d in (date+dt.timedelta(weeks=x) for x in range(53)):
    print(f"date: {d}, quarter: {quarter(d)}, week in that quarter: {week_in_q(d)}")

Prints:
date: 2020-01-01, quarter: 1, week in that quarter: 1
date: 2020-01-08, quarter: 1, week in that quarter: 2
date: 2020-01-15, quarter: 1, week in that quarter: 3
date: 2020-01-22, quarter: 1, week in that quarter: 4
date: 2020-01-29, quarter: 1, week in that quarter: 5
date: 2020-02-05, quarter: 1, week in that quarter: 6
date: 2020-02-12, quarter: 1, week in that quarter: 7
date: 2020-02-19, quarter: 1, week in that quarter: 8
date: 2020-02-26, quarter: 1, week in that quarter: 9
date: 2020-03-04, quarter: 1, week in that quarter: 10
date: 2020-03-11, quarter: 1, week in that quarter: 11
date: 2020-03-18, quarter: 1, week in that quarter: 12
date: 2020-03-25, quarter: 1, week in that quarter: 13
date: 2020-04-01, quarter: 2, week in that quarter: 1
date: 2020-04-08, quarter: 2, week in that quarter: 2
date: 2020-04-15, quarter: 2, week in that quarter: 3
date: 2020-04-22, quarter: 2, week in that quarter: 4
date: 2020-04-29, quarter: 2, week in that quarter: 5
date: 2020-05-06, quarter: 2, week in that quarter: 6
date: 2020-05-13, quarter: 2, week in that quarter: 7
date: 2020-05-20, quarter: 2, week in that quarter: 8
date: 2020-05-27, quarter: 2, week in that quarter: 9
date: 2020-06-03, quarter: 2, week in that quarter: 10
date: 2020-06-10, quarter: 2, week in that quarter: 11
date: 2020-06-17, quarter: 2, week in that quarter: 12
date: 2020-06-24, quarter: 2, week in that quarter: 13
date: 2020-07-01, quarter: 3, week in that quarter: 1
date: 2020-07-08, quarter: 3, week in that quarter: 2
date: 2020-07-15, quarter: 3, week in that quarter: 3
date: 2020-07-22, quarter: 3, week in that quarter: 4
date: 2020-07-29, quarter: 3, week in that quarter: 5
date: 2020-08-05, quarter: 3, week in that quarter: 6
date: 2020-08-12, quarter: 3, week in that quarter: 7
date: 2020-08-19, quarter: 3, week in that quarter: 8
date: 2020-08-26, quarter: 3, week in that quarter: 9
date: 2020-09-02, quarter: 3, week in that quarter: 10
date: 2020-09-09, quarter: 3, week in that quarter: 11
date: 2020-09-16, quarter: 3, week in that quarter: 12
date: 2020-09-23, quarter: 3, week in that quarter: 13
date: 2020-09-30, quarter: 3, week in that quarter: 14
date: 2020-10-07, quarter: 4, week in that quarter: 2
date: 2020-10-14, quarter: 4, week in that quarter: 3
date: 2020-10-21, quarter: 4, week in that quarter: 4
date: 2020-10-28, quarter: 4, week in that quarter: 5
date: 2020-11-04, quarter: 4, week in that quarter: 6
date: 2020-11-11, quarter: 4, week in that quarter: 7
date: 2020-11-18, quarter: 4, week in that quarter: 8
date: 2020-11-25, quarter: 4, week in that quarter: 9
date: 2020-12-02, quarter: 4, week in that quarter: 10
date: 2020-12-09, quarter: 4, week in that quarter: 11
date: 2020-12-16, quarter: 4, week in that quarter: 12
date: 2020-12-23, quarter: 4, week in that quarter: 13
date: 2020-12-30, quarter: 4, week in that quarter: 14

A: Here is a simple solution using python's isocalendar library to find the week number:
Note: Week starts on Monday.
from datetime import datetime

FISCAL_QUARTERS = [4, 7, 10, 1]  # April, July, October, January
FISCAL_PERIOD = 3

def _calc_quarter_week(day, month, year):
    fiscal_quarter = None
    # Find which quarter the given date falls in
    for fiscal_index in range(len(FISCAL_QUARTERS)):
        f_month = FISCAL_QUARTERS[fiscal_index]
        if month >= f_month and month < f_month + FISCAL_PERIOD:
            fiscal_quarter = fiscal_index + 1
            break

    quarter_start_day = datetime(
        year=year, month=FISCAL_QUARTERS[fiscal_quarter-1], day=1)
    # Quarter week number
    _, q_week_no, _ = quarter_start_day.isocalendar()

    given_date = datetime(year=year, month=month, day=day)
    # Given week number
    _, given_week_no, _ = given_date.isocalendar()

    return fiscal_quarter, given_week_no - q_week_no + 1

day, month, year = map(int, input('Day Month Year\n').strip().split())
fiscal_quarter, week_count = _calc_quarter_week(day, month, year)
print('Fiscal quarter: {}, Week: {}'.format(fiscal_quarter, week_count))

Outputs:
Day Month Year
29 6 2020
Fiscal quarter: 1, Week: 14

Day Month Year
9 7 2020
Fiscal quarter: 2, Week: 2


text:
Q: Exceptions in python. Given the definition, how to call it inside code? In a library the following exception is defined:
exception paramiko.ssh_exception.AuthenticationException
Exception raised when authentication failed for some reason. It may be possible to retry with different credentials. (Other classes specify more specific reasons.)

In my code if i write:
except AuthenticationException:

I get an error.
If I write:
except paramiko.AuthenticationException:

It works.
Why not:
except paramiko.ssh_exception.AuthenticationException:

How do I know what to write given the definition?
The library paramiko is obviously imported:
import paramiko

A: I guess paramiko package has following __init__.py:
from .ssh_exception import *

Then if you import paramiko, you will have all stuff under paramiko without additional subbranches


text:
Q: mi pagina no aparece en vista previa en whatsapp, facebook, twitter He diseñado una página en angular y todo funciona muy bien, pero al hacer una vista previa no aparece nada en WhatsApp, Facebook, Twitter, en este momento estoy haciendo pruebas de socialsharepreview y me sale un error https://socialsharepreview.com/?url=https://yoelijo.com.co/
Aquí está el index.html de mi página
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Yo Elijo</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="assets/images/yoelijo.png">
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
  <link rel="preconnect" href="https://fonts.gstatic.com">
  <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <!-- HTML Meta Tags -->
<meta name="description" content="Haga click para responder la encuesta">

<!-- Facebook Meta Tags -->
<meta property="og:url" content="https://yoelijo.com.co/poll/">
<meta property="og:type" content="website">
<meta property="og:title" content="Responde la Encuesta">
<meta property="og:description" content="Haga click para responder la encuesta">
<meta property="og:image" content="https://yoelijo.com.co/assets/images/yoelijo.png">
<!-- Twitter Meta Tags -->
<meta name="twitter:card" content="summary_large_image">
<meta property="twitter:domain" content="">
<meta property="twitter:url" content="https://yoelijo.com.co/poll/">
<meta name="twitter:title" content="Responde la Encuesta">
<meta name="twitter:description" content="Haga click para responder la encuesta">
<meta name="twitter:image" content="https://yoelijo.com.co/assets/images/yoelijo.png">

</head>
<body class="mat-typography">
  <app-root></app-root>
</body>
</html>

Agradezco su colaboración

A: Dentro de la etiqueta HEAD de tu html te faltan cabeceras para poder realizar lo que quieres, que salga como una especie de carta cuando compartas por facebook, tweeter, whatsapp, etc...
<!-- FACEBOOK Open Graph === -->
<meta property="og:type" content="website" />
<!-- <meta property="og:type" content="article" />  PARA ARTÍCULOS  -->
<meta property="og:title" content="Titulo" />
<meta property="og:description" content="Descripcion" />
<meta property="og:image" content="Ruta de una imagen"/>
<meta property="og:image:width" content="800" /><!-- Importante -->
<meta property="og:image:height" content="418" /><!-- Importante -->
<meta property="og:url" content="url de la web" />
<meta property="og:site_name" content="site name" />

<meta property="fb:app_id" content="330307617951079"/>

<!-- TWITTER Open Graph === -->
<meta name="twitter:card" value="summary">
<meta name="twitter:title" content="title"/>
<meta name="twitter:description" content="descripcion" />
<meta name="twitter:image" content="ruta de una imagen"/>
<meta name="twitter:image:src" content="ruta de una imagen"/>

<meta property="og:title" content="title"/>
<meta property="og:type" content="website" />
<meta property="og:url" content="url de la web" />
<meta property="og:image" content="imagen"/>
<meta property="og:description" content="Descripcion." />

<meta name ="twitter:card" content="summary_large_image">
<meta name="twitter:url" content="url de la web" />
<meta name="twitter:site" content="@Nombre de la cuenta de twitter">

Espero que te haya sido de ayuda. Donde pongo url de la web quiero decir la url entera, https://myweb.com/


text:
Q: Sequence of tenses with while Are the sentences grammatically correct?

He hadn't been cleaning Suzi's room while she was ill.
He wasn't cleaning Suzi's room while she was ill.

PS: I think I should have added a request for context. Could you come up with contexts in which they can be used?

A: As I know they are because with when while (that already emphasize simultaneous reference) you can ignore sequence of tenses


text:
Q: Using Thermocouple with Raspberry Pi running Windows IoT I am planning to develop a temperature monitoring system for sub zero temperatures. I have done a bit of research and decided the best way forward is to use the Raspberry Pi 3 with the Windows 10 IoT operating system, combined with a Thermocouple and the MAX31855 thermocouple amplifier.
I am new to development on the Raspberry Pi and I am struggling to find any tutorials on how to use the thermocouple with windows 10 IoT effectively. There are countless tutorials on using the thermocouple and MAX31855, but I am unsure if i will be able to use the librarys and processing code that these tutorials offer due to the operating system that I am using.
Is it advisable/suitable to continue with this plan of development or should I use a different operating system.
The main reason I am using Windows 10 IoT is that I am going to connect the Raspberry Pis to Azure using the IoT hub.
Thank you in Advance, any input is appreciated.

A: I think you're on the right path.
For the record, if your purpose is to connect to Azure IoT hub, you don't necessarily use Windows IoT Core. the Azure IoT SDK has various platform support, you can easily cross-build for embedded Linux as well.
Back to MAX31855 for IoT, the link CSharpRocks provides has somehow unofficial library for this sensor using SPI bus connection. If you want to use it with Windows IoT Core, you need to port the library. To be specific, you need to replace every call with spi controller with the SpiController UWP provides, which shouldn't be much work though.
To sum up, two options,

*

*Use Linux distribution(raspbian etc...), the library for MAX31855, and compile/cross-compile iot-hub-sdk, you can find tutorial for cross-compiling on the repository.

*Use Windows IoT Core, so that you have native support for Azure IoT Hub, but you need to port the library for MAX31855 for windows platform.


text:
Q: Generating a migration using a custom rails generator I took some time to learn how rails generators works and I managed to create one that copies some files and changes others. I call it this way:
rails generate menu test

But I need to make it generate a migration too, to create a table and add fields to it, something like:
rails generate menu test content:text

The number of arguments may vary, but it is a given that it'll always have an ID and a title column.
How can I accomplish this?

A: If you want:
$ rails generate scaffold test content:text

then have a look this Rails guide. It provides information such as:

[...] notice that we are inheriting from Rails::Generators::NamedBase instead of Rails::Generators::Base. This means that our generator expects at least one argument, which will be the name of the initializer, and will be available in our code in the variable name.
We can see that by invoking the description of this new generator (don't forget to delete the old generator file):
$ rails generate initializer --help
Usage:
    rails generate initializer NAME [options]


text:
Q: HTML Table Filter I am using HTML Table Filter to filter my tables from a SQL query using PHP ( http://tablefilter.free.fr ) for a ticket system.
As I am getting more than 4000 rows now, the page is really slow.
Is there a way to load the rows using AJAX without breaking the search and pagination functionalities?

A: I prefer to use the DataTables plugin for jQuery.
You can initialize the table and put in the rows dynamically using ajax calls.
If you don't want to load all the data in one request, you can use the Deferred loading of data feature.