text:
Q: Failed to fetch update on Ubuntu 14.04 LTS (Trusty Tahr) While running the update at Ubuntu 14.04 LTS (Trusty Tahr). The following error is being encountered:
W: Failed to fetch http://us.archive.ubuntu.com/ubuntu/dists/trusty-updates/universe/binary-amd64/Packages  Hash Sum mismatch

W: Failed to fetch http://us.archive.ubuntu.com/ubuntu/dists/trusty-updates/multiverse/binary-amd64/Packages  Hash Sum mismatch

W: Failed to fetch http://us.archive.ubuntu.com/ubuntu/dists/trusty-updates/main/binary-i386/Packages  Hash Sum mismatch

W: Failed to fetch http://us.archive.ubuntu.com/ubuntu/dists/trusty-updates/universe/binary-i386/Packages  Hash Sum mismatch

W: Failed to fetch http://us.archive.ubuntu.com/ubuntu/dists/trusty-updates/multiverse/binary-i386/Packages  Hash Sum mismatch

W: Failed to fetch http://us.archive.ubuntu.com/ubuntu/dists/trusty-updates/main/i18n/Translation-en  Hash Sum mismatch

W: Failed to fetch http://us.archive.ubuntu.com/ubuntu/dists/trusty-updates/universe/i18n/Translation-en  Hash Sum mismatch

E: Some index files failed to download. They have been ignored, or old ones used instead.

command used:
sudo apt-get update

A: Enter the following commands in a Terminal:
sudo rm -vf /var/lib/apt/lists/*
sudo apt-get update


text:
Q: Subsetting a dataframe according to a list of vectors I have a list of vectors of characters, called l. For example:
set.seed(42)  ## for sake of reproducibility
genes <- paste("gene",1:20,sep="")
tot=data.frame(term=sample(genes,30, replace=T), num=sample(1:10, 30, replace=T), stringsAsFactors =
FALSE)
s1<-sample(genes,2, replace=F)
s2<-sample(genes,4, replace=F)
s3<-sample(genes,3, replace=F)
s4<-sample(genes,2, replace=F)
s5<-sample(genes,2, replace=F)
s6<-sample(genes,3, replace=F)
l=list(s1,s2,s3,s4,s5,s6)

By considering tot[tot$term%in%l[[1]],], I obtain:
      term num
 1  gene17   4
 3   gene1   6
 7  gene17   2
 26  gene1   6

and I put
 df=tot[tot$term%in%l[[1]],]
 sum(df$num)

I can obtain the total values of second column, i.e. 18. For the other elements of the list I obtain, respectively: 32 13 19 17 29. This can be achieved by a for loop:
v<-vector()
for (j in 1:length(l)) {
  df=tot[tot$term%in%l[[j]],]
  v<-c(v,sum(df$num))
}

I would like to know if there is a more simple way of doing this.

A: It can be simplified with sapply
v2 <- sapply(l, function(j) sum(tot$num[tot$term %in% j]))

-checking with OP's loop output
identical(v, v2)
#[1] TRUE

Or a more compact way with map
library(purrr)
map_dbl(l, ~ sum(tot$num[tot$term %in% .x]))

Or with tidyverse
library(dplyr)
stack(setNames(l, seq_along(l))) %>%
  group_by(ind) %>%
  summarise(Sum = tot %>%
                    filter(term %in% values) %>%
                    pull(num) %>%
                    sum) %>%
  pull(Sum)

A: Here is one tidyverse way :
library(tidyverse)

enframe(l, value = 'term') %>%
  unnest(term) %>%
  left_join(tot, by = 'term') %>%
  group_by(name) %>%
  summarise(num = sum(num, na.rm = TRUE))

#   name   num
#* <int> <int>
#1     1    18
#2     2    32
#3     3    13
#4     4    19
#5     5    17
#6     6    29

redpajama_set_name: RedPajamaStackExchange


text:
Q: Parsing Api Response Django Module I am using this magic the gathering api in django. Instead of using requests to call the url I can use the built in functions. But the response is confusing me.
When I call
cards = Card.where(page=50).where(pageSize=500).all()

Then print out cards
I get data that looks like this in my terminal.
mtgsdk.card.Card object at 0x10696bcc0>, <mtgsdk.card.Card object at 0x10696bcf8>, <mtgsdk.card.Card object at 0x10696bd30>, <mtgsdk.card.Card object at 0x10696bd68>, <mtgsdk.card.Card object at 0x10696bda0>]

I was thinking I maybe need to decode it and it's a dict but I basically throwing darts blindly and have no clue if I am getting any closer.
Someone please shed some light here. What format is this response in and how would I handle it?
def graphs(request):
    data = []
    cards = Card.where(page=50).where(pageSize=500).all()
    mtg_data = str(cards)
    print(mtg_data)
    data.append(cards)
    return render(request, 'graphs/graphs.html', {'data': data})

Then I am trying to access the card in the template like this, but I get nothing.

                {% for cards in data %}

                {% endfor %}

API HERE
GITHUB

A: You've appended the list of cards to an empty list, so now data is a list consisting of a single item, which is itself a list. Instead, you just want to send the cards list itself to the template.
return render(request, 'graphs/graphs.html', {'data': cards})


text:
Q: Is QGIS aspect analysis description mistaken? I've been checking the Aspect analysis tool and several sources indicate that aspect is measured from 0 to 360, starting North and going counter-clockwise. Nevertheless, I've been testing it on several regions, some of which I know quite well and the measurement is actually being done clockwise.
Am I right? Are the descriptions and tutorials that state the direction as being counterclockwise mistaken?


text:
Q: Override Interface in Magento 2 I have uncovered a defect in my Magento 2.1.3 install and have narrowed it down to a key relationship in my database that is an open ticket within the Magento community.
Long story short, the only way I can seemingly fix the issue is by changing a constant within a core Magento file. Because Magento 2 uses dependency injection, I am trying to overwrite an interface that has the constant that I need to change.
My problem lies in that I have been trying to override that interface, as I have with Models, Layouts, etc for other modifications, yet nothing has seemingly worked. Below is the few files that I believe are relevant to this issue. I have also search high and low to understand better what an interface is in PHP and how it relates to the Magento 2 ecosystem but nothing has helped.
Note: I pulled out our vendor name and replaced with [vendorname] for some privacy. Also I have the needed registration.php file in place and setup:upgrade runs without errors.
app/code/[vendorname]/[vendorname]Customer/Api/AddressMetadataInterface.php
namespace Magento\Customer\Api;

/**
 * Interface for retrieval information about customer address attributes metadata.
 * @api
 */
interface AddressMetadataInterfaceRev extends MetadataInterface
{
const ATTRIBUTE_SET_ID_ADDRESS = 6;

const ENTITY_TYPE_ADDRESS = 'customer_address';

const DATA_INTERFACE_NAME = 'Magento\Customer\Api\Data\AddressInterface';
}

app/code/[vendorname]/[vendorname]Customer/etc/di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
      <preference for="Magento\Customer\Api\AddressMetadataInterface" type="[vendorname]\[vendorname]Customer\Api\AddressMetadataInterface" />
</config>

With this code. I get the following error when trying to run setup:di:compile
Fatal error: Cannot declare interface Magento\Customer\Api\AddressMetadataInterface, because the name is already in use in /Users/[username]/Sites/[sitename]/app/code/[vendorname]/[vendorname]Customer/Api/AddressMetadataInterface.php on line 13
Any help would be greatly appreciated.

A: It looks like you need to change the namespace of your preference class to match your module's namespace instead of Magento's namespace. Then you should make your class extend the original (\Magento\Customer\Api\AddressMetadataInterface) so you only need to override the constants that need changed:
app/code/[YourVendor]/[ModuleName]/Api/AddressMetadataInterface.php
namespace [YourVendor]\[ModuleName]\Api;

/**
 * Interface for retrieval information about customer address attributes metadata.
 * @api
 */
interface AddressMetadataInterface extends \Magento\Customer\Api\AddressMetadataInterface
{
    const ATTRIBUTE_SET_ID_ADDRESS = 2;

    const ENTITY_TYPE_ADDRESS = 'customer_address';

    const DATA_INTERFACE_NAME = 'Magento\Customer\Api\Data\AddressInterface';
}

Important Note
Due to the nature of constants and how you can access their values without instantiating the class (\Magento\Customer\Api\AddressMetadataInterface::DATA_INTERFACE_NAME), I don't know if this is going to solve your problem since every use case I just mentioned references the original class and not your override. As far as I knew class preferences only work when a class name is requested through the object manager or via Dependency injection. Might be worth some investigating.


text:
Q: SonarQube - Is there basic example/explanation of how coverage issues can be resolved? I'm very new to using SonarQube/Cloud (so please be gentle!) and am trying to work out how to improve the '0% coverage on new code' that my code has.
Here's an example:
I added the code:
    validation_errors = []

    for field in required:
        if field not in request.POST:
            validation_errors.append("field '{0}' missing".format(field))

    if len(validation_errors) > 0:
        return JsonResponse({'errors': validation_errors}, status=400 )

and I have a (Django) test for this:
def test_required_params(self):
        # no username
        response = self.client.post(self.url, { 'password': 'secret', 'media_file': self.video_file })
        self.assertRaises(forms.ValidationError)
        self.assertEqual(response.status_code, 400)

But when I run the sonar-scanner, in the online report, I get the message that these lines are not covered (see: https://sonarcloud.io/component_measures?id=django_oppia&metric=new_coverage&selected=django_oppia%3Aapi%2Fmedia.py)
I'm sure I must have some very basic mis/non-understanding of what the coverage metric actually means.
I'd really appreciate if someone could explain to me what I need to add/update in my code (just the specific example above), so the SonarCloud analysis doesn't continue to flag this as not covered.
Thanks for your help - if you need any extra info on code/platform/versions etc, just let me know.
Edit
The sonar-scanner command that I'm running:
sonar-scanner \
  -Dsonar.projectKey=django_oppia \
  -Dsonar.organization=alexlittle-github \
  -Dsonar.sources=. \
  -Dsonar.host.url=https://sonarcloud.io \
  -Dsonar.login=xxxxxxxxxx \
  -Dsonar.exclusions=docs/_build/**/*

I run this from the root of my source code, and I haven't specified/edited anything in the sonar/conf/sonar-scanner.properties file (it's just the default installed version)

A: Thanks to the comments post above by @metalisticpain, I've now got this working.
The issue was due to me missing out creating the coverage report.
For anyone else having the same issue, here's how I resolved it...
First I ran the coverage tool (from the root of my project directory):
coverage erase
coverage run --branch --source=oppia
coverage xml -i

Then pointed the sonar-scanner to this coverage.xml file:
sonar-scanner \
  -Dsonar.projectKey=django_oppia \
  -Dsonar.organization=alexlittle-github \
  -Dsonar.sources=. \
  -Dsonar.host.url=https://sonarcloud.io \
  -Dsonar.login=xxxxxxxxxx \
  -Dsonar.exclusions=docs/_build/**/*,tests/**/*,oppiamobile/settings_secret.py \
  -Dsonar.python.coverage.reportPath=./coverage.xml

I added some extra exclusions, but what actually made the difference was adding the reportPaths to the coverage.xml


text:
Q: do i need to translate information coming from wordpress like author name the post title, post content etc making a translation ready wp theme i am developing a wordpress theme for themeforest and i want to ask that is it my responsiblity to translate the information coming from wordpress like the the post title, post content or the author name etc as making a translation ready theme or does wordpress handles this on its own. i don't want my theme to be soft rejected from themeforest because i didn't translated the information coming from wordpress. as its there requirement to translate all of your strings if making a translation ready theme. also obviously i am using wordpress function to get that information i.e post title, post content or the author name etc

A: No, the content returned by the functions get_the_title() or the_content() are proper to the content of the site, this content should not be translated by the theme, the website administrator should provide the different languages of its content.
To translate the theme you can use the tool: POEDIT
following the recommendations given in the WordPress Handbook Internationalization


text:
Q: How to delete a file (deep) in a ZIP folder in Python? I'm writing a script that is extracting 2 JSON files from deep (3 folders down) in a ZIP Folder, modifying its contents, and writing those files back into that same folder. The only issue is that when I write the JSON Files back into the folder where they were initially pulled from, they do not overwrite so now I have 4 files named (product, product, package, package). I wish to delete or overwrite the non-modified files but don't know how.
I have looked up how to do it on other threads and it says it's not supported but I was hoping by now someone had addressed this without having to do the "rewrite the entire directory minus the old files into a new ZIP" routine. I've also tried writing to the zip file with 'w' mode but that just deletes the whole other contents of the zip file.
This is how I'm writing each file back into the ZIP file
zf = zipfile.ZipFile(ZipName, 'a')
zf.write('package.json',addressBook[0],compress_type = zipfile.ZIP_DEFLATED
zf.write('product.json',addressBook[1],compress_type = zipfile.ZIP_DEFLATED


text:
Q: Error in stored procedure Null value is eliminated by an aggregate or other SET operation I m trying following query to be execute but it gives me warning Null value is eliminated by an aggregate or other SET operation.
select
  s.CurrentDate,
  s.game_id,
  s.Searchstring,
  sm.type_of_game,
  case when(count(t.game_id)>0) then 'Y' else 'N' end as scorestatus,
  case when(count(i.game_id)>0) then 'Y' else 'N' end as scorestatusindividual,
  sm.image_path,g.datetime,'' as score_keeper
from dbo.Search s  with(nolock)
left outer join dbo.TeamGameResult t  with(nolock) on s.game_id = t.game_id
left outer join dbo.IndividualGameResult i  with(nolock) on i.game_id = s.game_id
join dbo.Game g  with(nolock) on g.game_id=s.game_id
join  dbo.AdditionalDetails ad on ad.AdditionalDetails_id = g.AdditionalDetails_id
join dbo.SportMaster sm  with(nolock) on  sm.SportsMaster_id = ad.SportsMaster_id
where (( Searchstring+' '+ convert(nvarchar(500),s.CurrentDate,101) Like '%01/15/2013%'
  and Searchstring+' '+ convert(nvarchar(500),s.CurrentDate,101) Like '%Soccer%'))
  and convert(varchar(10),g.datetime,101) in ('01/15/2013','01/14/2013')
group by s.game_id,
         s.Searchstring,
         sm.type_of_game,
         s.CurrentDate,
         sm.image_path,
         g.datetime
order by g.datetime desc

A: It just warns you because you are using
... when(count(i.game_id)>0) then 'Y' else 'N' end ...

Count is an aggregate function and can't counts values where game_id is null. You may use ISNULL function (http://msdn.microsoft.com/en-GB/library/ms184325.aspx) for example:
count(ISNULL(i.game_id, 0))

But then it calculates all the NULL values too. So  if you do not want it you need to add additional check to the WHERE section


text:
Q: Подложка (картинка) из CSS в админку WP На первом экране сайта, как подложка лежит картинка. Она затянута не через HTML, а через CSS.
.header-bg { background: url(../img/sec1/sec1_bg.jpg) no-repeat; background-size: cover; height: 100vh; width: auto; }

Вопрос: Можно ли ее как привязать в админку Wordpress, используя плагин, например, ACF? Из html (php) я знаю как вытягивать, а вот из сss - нет.

A: Регистрируете в functions.php опцию в кастомайзере(Внешний вид - Настроить):
function my_customizer( $wp_customize ) {
    $wp_customize->add_setting( 'theme_header_bg' );
    $wp_customize->add_control(
        new WP_Customize_Image_Control(
            $wp_customize,'theme_header_bg',array(
                'label' => 'Header Background Image',
                'section' => 'title_tagline',
                'settings' => 'theme_header_bg',
                'priority' => 2
            )
        )
    );
}
add_action( 'customize_register', 'my_customizer' );

Заполняете опцию в настройках в том же functions.php. Затем добавляете инлайн стили к свои стилям темы ('your-styles-name' - нужно заменить на название ваших стилей):
function my_styles_method() {
    wp_enqueue_style( 'your-styles-name', get_template_directory_uri() . '/css/custom_script.css' );
    $bg = get_theme_mod( 'theme_header_bg' ) ?? '../img/sec1/sec1_bg.jpg';
    $custom_css = "
        .header-bg{
            background: url({$color});
        }";
    wp_add_inline_style( 'your-styles-name', $custom_css );
}
add_action( 'wp_enqueue_scripts', 'my_styles_method' );


text:
Q: How to notice that a message sent to dialogflow is longer than 256 characters? I made a facebook chatbot with dialogflow. My problem is that some users write messages to my bot that are longer than 256 characters.
Dialogflow just throws an error that the character size exceeded. As the result, the user has no answer.
I don't expect dialogflow to process the input. I just want to get this information in my backend, so I can send the user to the live chat.
Please, say me it is possible (and how ;) ).

A: By following this you will be able to set the custom webhook => Webhook setup
Make this server live with Ngrok with temporary later on you can migrate to your server
Now you will get event in which you will find your message sent from facebook messenger.
you can write simple JS function to send only 256 character to Dialogflow Functions
str.substring(0,255)
and send it to detectIntent in dialogflow function.


text:
Q: Displaying pages for only signed in users I have created a membership system and only signed in users can enter comments. But, without signing in, everyone can access every pages by typing the name of the PHP file in the link bar.How can i redirect non-registered users to the homepage?
Thanks

A: You have to create a session if a user has succesfully logged in:
session_start(); // best to put this at the top of the first php file that's called, preferably on every page
// check user credentials
if (!valid credentials) {
    header('Location: login.php');
    exit();
}

$_SESSION['user'] = 'username';

And in the php file where you want to check:
session_start(); // best to put this at the top of the first php file that's called, preferably on every page

if (!isset($_SESSION['user'])) {
    header('Location: login.php');
    exit();
}

A: That's just as easy as an if statement :
if(login_check())
{
  // Show the page
}
else
{
  header('Location: adresse');
  exit();
}

A: That depends on how you identify logged in users, is it a session? a cookie? You should use those methods to test for the logged in status. If the user is not logged in, you should send a Location header to redirect him to the home page.
header('Location: index.php'); die();

You die(); afterwards to prevent the rest of the code from running.
Note: You must send it BEFORE any output is sent, otherwise it won't work.


text:
Q: thread.start_new_thread: transfer exception to main-thread
Possible Duplicate:
Catch a thread's exception in the caller thread in Python

I have a given code and there is a
thread.start_new_thread()

As I just read in python doc: "When the function terminates with an unhandled exception, a stack trace is printed and then the thread exits (but other threads continue to run)."
But I want to terminate also the main-thread when the (new) function terminates with an exception - So the exception shall be transfered to the main-thread. How can I do this?
edit:
here is part of my code:
def CaptureRegionAsync(region=SCREEN, name="Region", asyncDelay=None, subDir="de"):
    if asyncDelay is None:
        CaptureRegion(region, name, subDir)
    else:
        thread.start_new_thread(_CaptureRegionAsync, (region, name, asyncDelay, subDir))

def _CaptureRegionAsync(region, name, asyncDelay, subDir):
    time.sleep(max(0, asyncDelay))
    CaptureRegion(region, name, subDir)

def CaptureRegion(region=SCREEN, name="Region", subDir="de"):
    ...
    if found:
        return
    else:
        raise Exception(u"[warn] Screenshot has changed: %s" % filename)

CaptureRegionAsync(myregion,"name",2)

A: UPD: It is not the best solution as your question is different from what I thought it is: I expected you were trying to deal with an exception in thread code you can not modify. However, i decided not to delete the answer.
It's hard to catch an exception from another thread. Usually it should be transferred manually.
Can you wrap a thread function? If you wrap the worker thread that crashes into try...except, then you may perform actions needed to exit main thread in except block (sys.exit seems to be useless, though it's a surprise to me, but there is thread.interrupt_main() and os.abort(), though you may need  something more graceful like setting a flag the main thread is checking regularly).
However, if you can not wrap the function (can not modify the third-party code calling start_new_thread), you may try monkey patching the thread module (or the third-party module itself). Patched version of start_new_thread() should wrap the function you worry about:
import thread
import sys
import time

def t():
    print "Thread started"
    raise Exception("t Kaboom")

def t1():
    print "Thread started"
    raise Exception("t1 Kaboom")

def decorate(s_n_t):
    def decorated(f, a, kw={}):
        if f != t:
            return s_n_t(f, a, kw)
        def thunk(*args, **kwargs):
            try:
                f(*args, **kwargs)
            except:
                print "Kaboom"
                thread.interrupt_main() # or os.abort()
        return s_n_t(thunk, a, kw)
    return decorated

# Now let's do monkey patching:
thread.start_new_thread = decorate(thread.start_new_thread)

thread.start_new_thread(t1, ())
time.sleep(5)
thread.start_new_thread(t, ())
time.sleep(5)

Here an exception in t() causes thread.interrupt_main()/os.abort(). Other thread functions in the application are not affected.


text:
Q: How to reinstall all installed packages with zypper How do I tell zypper to reinstall all currently installed packages?

A: I would add --no-recommends as option, to not install additional packages.
zypper in --no-recommends -f $(rpm -qa --qf '%{NAME} ')

also consider --download-in-advance , to avoid missing availability causing the install to interrupt.
zypper in --no-recommends --download-in-advance -f $(rpm -qa --qf '%{NAME} ')

A: You can reinstall all currently installed packages by this command:
zypper in -f $(rpm -q -a --qf '%{NAME} ')

Maybe this information will be useful.


text:
Q: How can I store perforce P4V password? I have to use this software and I need to store password, because it disconnects regularly. How can I do that, there is no checkbox to save password.
Thanx a lot!

A: If you are an administrator (or can convince your admin to do this), you can create a group, put yourself in it, then edit the group permissions to prevent your session from ever timing out.
In P4V group management is done via Tools->Administration->Permissions tab->Groups tab

Set the "Duration before login session times out" to "unlimited".
You can also do it from the command line:
p4 group <group name>

When the group specification opens in a text editor, set the PasswordTimeout: property to unlimited.


text:
Q: Text wrap with shapepar (insert image between text) How do insert image between text and text wrap with shapepar or other package?

A: Here is a similar play-by-play of what was described by @KarlOveHufthammer in his excellent answer regarding the coat-of-arms construction using Xfig. I'm running Windows 7 with Cygwin/X, and is therefore also able to use Xfig (version 3.2.5b). I also have transfig (version 3.2.5c-1, also called fig2dev) installed as part of the Cygwin/X distribution setup:

*

*Open Xfig and set up a comfortable view/zoom level that is detailed enough. It does not have to be perfect, since LaTeX will resize the paragraph shape as specified using \shapepar to match whatever text you want to put into it.

*Draw the outer shape of the paragraph. In this case I used the rectangle tool to draw a square.

*Once complete, edit the rectangle and add the comment "+" (without the quotes).

*Now draw the interior cut-out shape. In this case I used the circle tool.

*Once complete, edit the rectangle and add the comment "-" (without the quotes).

*Save the image in Xfig format as (say) myshape.fig.

The Xfig file looks like this:
#FIG 3.2  Produced by xfig version 3.2.5b
Landscape
Center
Inches
Letter
100.00
Single
-2
1200 2
# -
1 3 0 1 0 7 50 -1 -1 0.000 1 0.0000 3000 3000 1500 1500 3000 3000 4500 3000
# +
2 2 0 1 0 7 50 -1 -1 0.000 0 0 -1 0 0 5
     0 0 6000 0 6000 6000 0 6000 0 0

*Execute:
fig2dev -L shape -n myshape myshape.fig myshape.shape

The flag -L sets the output language used to shape (that conforms to shapepar). Other languages also exist, but this option should be specified first. The flag -n sets the name to be used within the output file myshape.shape. So, using -L shape -n <name> will create \<name>par. The output myshape.shape from myshape.fig now contains the  newly-created macro \myshapepar{<par>} where the paragraph definition in "shape language" is given by \myshapeshape:
\def\myshapepar#1{\shapepar{\myshapeshape}#1\par}
\def\myshapeshape{%
{25.0833}%
{0.0833333}b{0.0833333}\\%
{0.0833333}t{0.0833333}{50}\\%
{12.5833}t{0.0833333}{25}st{25.0833}{25}\\%
{12.6667}t{0.0833333}{23.3333}t{26.75}{23.3333}\\%
{13.0833}t{0.0833333}{21.6667}t{28.4167}{21.6667}\\%
{13.5833}t{0.0833333}{20}t{30.0833}{20}\\%
{14.4167}t{0.0833333}{18.5}t{31.5833}{18.5}\\%
{15.4167}t{0.0833333}{17.0833}t{33}{17.0833}\\%
{16.5833}t{0.0833333}{15.8333}t{34.25}{15.8333}\\%
{17.8333}t{0.0833333}{14.75}t{35.3333}{14.75}\\%
{19.3333}t{0.0833333}{13.9167}t{36.1667}{13.9167}\\%
{20.9167}t{0.0833333}{13.25}t{36.8333}{13.25}\\%
{22.5}t{0.0833333}{12.75}t{37.3333}{12.75}\\%
{24.25}t{0.0833333}{12.5}t{37.5833}{12.5}\\%
{25.9167}t{0.0833333}{12.5}t{37.5833}{12.5}\\%
{27.6667}t{0.0833333}{12.75}t{37.3333}{12.75}\\%
{29.25}t{0.0833333}{13.25}t{36.8333}{13.25}\\%
{30.8333}t{0.0833333}{13.9167}t{36.1667}{13.9167}\\%
{32.3333}t{0.0833333}{14.75}t{35.3333}{14.75}\\%
{33.5833}t{0.0833333}{15.8333}t{34.25}{15.8333}\\%
{34.75}t{0.0833333}{17.0833}t{33}{17.0833}\\%
{35.75}t{0.0833333}{18.5}t{31.5833}{18.5}\\%
{36.5833}t{0.0833333}{20}t{30.0833}{20}\\%
{37.0833}t{0.0833333}{21.6667}t{28.4167}{21.6667}\\%
{37.5}t{0.0833333}{23.3333}t{26.75}{23.3333}\\%
{37.5833}t{0.0833333}{25}jt{25.0833}{25}\\%
{50.0833}t{0.0833333}{50}\\%
{50.0833}e{50.0833}%
}

*Create and compile your TeX file:
\documentclass{article}
\usepackage{shapepar}% http://ctan.org/pkg/shapepar
\usepackage{lipsum}% http://ctan.org/pkg/lipsum
\input{myshape.shape}% Contains \myshapepar{<par>}
\begin{document}
\myshapepar{\lipsum*[1-3]}
\end{document}

As mentioned, the size of the shape is not necessary. If you supply \lipsum*[1] instead (a shorter paragraph text), the output resembles:

Also note the use of \lipsum*. \shapepar does not allow the use of \par. Line breaking is achieved using \\.
Image insertion is achieved with an overlay, by moving the image to appropriate position using horizontal/vertical skips or otherwise.

A: Use package cutwin and run the example with xelatex because I use an eps image as vector graphic which has no background. Using a png image with clipping may also be possible.
\documentclass{article}

\usepackage{cutwin,graphicx,pstricks,lipsum}
\begin{document}

\opencutcenter
\newcommand\Margins{%
0.4\textwidth, 0.4\textwidth,
0.35\textwidth, 0.35\textwidth,
0.32\textwidth, 0.32\textwidth,
0.3\textwidth, 0.3\textwidth,
0.28\textwidth, 0.28\textwidth,
0.26\textwidth, 0.26\textwidth,
0.26\textwidth, 0.26\textwidth,
0.28\textwidth, 0.28\textwidth,
0.3\textwidth, 0.3\textwidth,
0.32\textwidth, 0.32\textwidth,
0.35\textwidth, 0.35\textwidth,
0.4\textwidth, 0.4\textwidth}
\renewcommand\putstuffinpic{%
  \rput(0,-5\normalbaselineskip){%
    \includegraphics[width=0.38\textwidth]{tiger}}}
\begin{shapedcutout}{2}{12}{\Margins}% 2 normal lines, 12 shaped lines
\lipsum[1]
\end{shapedcutout}

\end{document}


text:
Q: Confused about SQL Server trigger that does an UPDATE (strange UPDATE statement format) The crux of my question is the following style of UPDATE statement in a trigger:
update ActualTableName
    set X=Y
from inserted

I would have thought that this is a syntax error... the table "ActualTableName" does not appear in the "from" clause.
So... is this just some sort of funky automatic alias "unwind" (i.e. it knows "inserted" is an alias for ActualTableName? This seems unlikely because of a later query (see below).
Or... is there something more... like the query is expanded to:
update ActualTableName
    set X=Y
from ActualTableName
    cross join inserted

This also gets a bit stranger with a more complicated UPDATE that references both the inserted and deleted tables:
update ActualTableName
    set [... some assignments ...]
from
    inserted
        left outer join deleted
            on inserted.Id = deleted.Id
               and inserted.SomeField > deleted.SomeField
where
    inserted.Id <> ActualTableName.Id and

This query appears to be updating records in ActualTableName that are not part of the inserted table... and this leads me to think that the actual query is:
update ActualTableName
    set [... some assignments ...]
from
    ActualTableName
        cross jon inserted
        left outer join deleted
            on inserted.Id = deleted.Id
               and inserted.SomeField > deleted.SomeField
where
    inserted.Id <> ActualTableName.Id and

The books online are a bit opaque about this, and says this:

If the object being updated is the same as the object in the FROM
  clause and there is only one reference to the object in the FROM
  clause, an object alias may or may not be specified. If the object
  being updated appears more than one time in the FROM clause, one, and
  only one, reference to the object must not specify a table alias. All
  other references to the object in the FROM clause must include an
  object alias.

So... can anyone provide clarity as what is going on?

A: I'm not sure if you are aware of the fact that Inserted or Deleted in the above mentioned queries are not alias but special tables used by the SQL server to track insertion, update or deletion of data within triggers. Here is more information:
http://msdn.microsoft.com/en-us/library/ms191300.aspx


text:
Q: fragment is not responding the second time opened I have a viewPager that contains two fragments (B,C) inside a fragment (A), when you open the app for the first time, the FirebaseRecyclerOptions is working good in fragments B,C and you can see the items in the fragments (B,C) inside the ViewPager.
The problem starts when you exit the fragment (A) when it pauses and destroys, and then returns to it (A) again, then, it is not showing the items inside the ViewPager, fragments(B,C).
I looked at the logs, and on the second time opening fragment (A), the fragments(B,C) are not attach, create, start, resume nothing.
the main fragment (A) (in this fragment there is the viewPager)
public class myEventsFragment extends Fragment {

public myEventsFragment() {}

public static myEventsFragment newInstance(String param1, String param2) {
    myEventsFragment fragment = new myEventsFragment();

    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    return inflater.inflate(R.layout.fragment_my_events, container, false);
}

@Override
public void onStart() {
    super.onStart();
    Log.i(TAG,"dStart");

}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    viewPager=(ViewPager) view.findViewById(R.id.swiperList);

    myFragmentChoseOne=view.findViewById(R.id.myEventsFragmentChose);
    myFragmentChoseTow= view.findViewById(R.id.joinedEventsFragmentChose);
    userName.setText(myuser.getName()+" "+myuser.getLname());
    ProductRef= FirebaseDatabase.getInstance().getReference().child("Events").orderByChild("email").equalTo(StaticValues.getUser().getEmail());
    ProductRef2 =FirebaseDatabase.getInstance().getReference().child("EventJoiners").orderByChild("userId").equalTo(StaticValues.getUid());

    FirebaseDatabase database = FirebaseDatabase.getInstance();
    Query myRef = database.getReference().child("Events").orderByChild("email").equalTo(StaticValues.getUser().getEmail());
    myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            eventNum=(int)snapshot.getChildrenCount();
            eventNumber.setText(Integer.toString(eventNum));
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }

    });

    myFragmentChoseOne.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            viewPager.setCurrentItem(0);
        }
    });

    myFragmentChoseTow.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            viewPager.setCurrentItem(1);
        }
    });

    pagerViewAdepter=new PagerViewAdepter(getFragmentManager());
    viewPager.setAdapter(pagerViewAdepter);
    viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });
}
}

Fragment(B) (inside the ViewPager)
public class FragmentMyEventSwiper extends Fragment {

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_myevent_swiper,null);
    }

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    recycleView= view.findViewById(R.id.recycleView_myEvents);
    //recycleView.setHasFixedSize(true);
    layoutManager=new LinearLayoutManager(getActivity());
    ProductRef= FirebaseDatabase.getInstance().getReference().child("Events").orderByChild("email").equalTo(StaticValues.getUser().getEmail());
    ProductRef2 =FirebaseDatabase.getInstance().getReference().child("EventJoiners").orderByChild("userId").equalTo(StaticValues.getUid());
    recycleView.setLayoutManager(layoutManager);

    //FirebaseDatabase database = FirebaseDatabase.getInstance();
    FirebaseDatabase database= FirebaseDatabase.getInstance();

    ProductRef2.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            for(DataSnapshot myrow:snapshot.getChildren()){
                eventCode.add(String.valueOf(myrow.child("eventCode").getValue()));
          sCode.add(String.valueOf(myrow.child("sCode").getValue()));
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }
    });

    for (int i=0;i<sCode.size();i++){

        String s=sCode.get(i);
        Query ff2=FirebaseDatabase.getInstance().getReference().child("Schedule").orderByChild("eventCode").equalTo(s);
        ff2.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {

                for(DataSnapshot myrow:snapshot.getChildren()){
                    String st=String.valueOf(myrow.child("date").getValue().toString());
                    dateList.add(st);
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
            }
        });
    }

    final FirebaseRecyclerOptions<Event> options=
            new FirebaseRecyclerOptions.Builder<Event>()
                    .setQuery(ProductRef,Event.class)
                    .build();

    FirebaseRecyclerAdapter<Event, myEventsViewHolder> adapter=
            new FirebaseRecyclerAdapter<Event, myEventsViewHolder>(options) {
                @Override
                protected void onBindViewHolder(@NonNull final myEventsViewHolder holder, int position, @NonNull final Event model) {

                    Query query=db2.getReference().child("Events").orderByChild("uploadDate").equalTo(model.getUploadDate());

                    query.addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot snapshot) {

                            for(DataSnapshot myrow:snapshot.getChildren()){
                                stt=myrow.getKey();
                            }

                            holder.uploadDate.setText(model.getUploadDate());
                            holder.movieName.setText(model.getMovieName());
                            splitStr = Arrays.asList(model.getPic().split(","));

                           }

                        @Override
                        public void onCancelled(@NonNull DatabaseError error) {

                        }
                    });
                }

                @NonNull
                @Override
                public myEventsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                    View view =LayoutInflater.from(parent.getContext()).inflate(R.layout.myevents_events_cardview,parent,false);
                    myEventsViewHolder holder=new myEventsViewHolder(view);
                    return holder;
                }
            };
    recycleView.setAdapter(adapter);
    adapter.startListening();
}
}

ViewPager
 public class PagerViewAdepter extends FragmentStatePagerAdapter {
public PagerViewAdepter(@NonNull FragmentManager fm) {
    super(fm);
}

@NonNull
@Override
public Fragment getItem(int position) {
    Fragment fragment=null;

    switch (position){

        case 0:
             fragment=new FragmentMyEventSwiper();
        break;
        case 1:
            fragment=new FragmentJoinersEventSwiper();
            break;
    }
    return fragment;
}

@Override
public int getCount() {
    return 2;
}
}

XML Fragment (A)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/Black"
android:id="@+id/fragment_my_events"
android:orientation="vertical"
tools:context=".Fragments.myEventsFragment">

<androidx.constraintlayout.widget.ConstraintLayout
    android:id="@+id/constrant_layout_myEvente_top"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

        <LinearLayout
            android:id="@+id/linearLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:orientation="horizontal"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent">

            <TextView
                android:id="@+id/myEventsFragmentChose"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center"
                android:text="My Events"
                android:textColor="@color/white"
                android:textSize="25dp" />

            <TextView
                android:id="@+id/joinedEventsFragmentChose"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center"
                android:text="Joined Events"
                android:textColor="@color/white"
                android:textSize="25dp" />

        </LinearLayout>

        <androidx.viewpager.widget.ViewPager
            android:id="@+id/swiperList"
            android:layout_width="match_parent"

            android:layout_height="450dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/linearLayout" />

    </androidx.constraintlayout.widget.ConstraintLayout>

XML Fragment inside ViewPager(B)
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment_myevent_swiper"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recycleView_myEvents"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    />

</androidx.constraintlayout.widget.ConstraintLayout>

The main problam is that the fragment B,C are working good at the first time, but when you go out fragment A and return they dont even get called. please help i have been stack on this problam a lot of time. thanks


text:
Q: Using java to input SQL Query with backslash I have a java program which connects to a database in Oracle SQL Developer.
I need data from the database to export to a .csv file. I can do this directly in SQL Developer using spooling as shown
spool D:\fileLocation\fileName.csv
select /*csv*/ * from Table;
spool off

I need to be able to input that to SQL Developer FROM the java program. I can input a query from java to sql using code below
Statement SumLevel = connection.createStatement();
    try{
        SumLevel.executeQuery("SQL Query");
        System.out.println("Succesfuly Entered Data");

    }catch(SQLException e){
        System.out.println(e);
    }finally{
        if(CompareLevel != null){
            CompareLevel.close();
        }
    }

Obviously the \ in java is not just a character so if I try the first line of the spooling in java it will try to do \f  which is a separate function.
Using \\ prints out the desired code but when it inputs into sql it says there is an error "java.sql.SQLSyntaxErrorException: ORA-00900: invalid SQL statement".
I believe this is due to SQL reading the code showing \\ rather than \
spool D:\\fileLocatoin\\fileName.csv
select /*csv*/ * from Table;
spool off

How would I be able to input the sql spooling code into a java program.
Thanks

A: Short answer You can't run spool command from Java.
Explanation.
Java is not connects to Oracle SQL Developer it connects to Oracle database.
Oracle database can run SQL queries.
spool command is not part of SQL. It  is command of Oracle SQL Developer command language.
Solution
Either you run your SQL query (select * from Table, note that it doesn't allow comment in it) and then process result and write to file using some CSV lib.
Or you continue to use Oracle SQL Developer tool.


text:
Q: Why to avoid biginteger instantiation in Java There is a PMD rule saying one should avoid to instantiate BigInteger or BigDecimal if there is a predefined constant.
BigInteger.ZERO

// instead of

new BigInteger(0)

Would there be any other advantage than saving a few bytes?

A: it avoids the allocation of those few bytes and the need to collect them back later
in a tight loop that can matter

A: Yes, saving a few JVM instructions.

A: Possibly performance, if you are instantiating a lot of 0s.  An alternative for long/int argument is
BigInteger.valueOf(0)
which returns BigInteger.ZERO when argument is 0

A: Instead of creating a new object with new BigInteger you'd better use one static object which is created once when the BigInteger class is loaded. It is also true for using valueOf of all wrapper types.

A: By using cached values, it is likely to yield significantly better space and time performance.


text:
Q: Delete row by content I need a function (or some other way) to delete all rows that has NULL as content. Example:
   A        B
1 Name     ID
2 John    123456
3 Marie   789012
4 Phil    NULLL

So row 4 should be deleted.

A: If you want code, please provide your framework. The SQL would be:
DELETE * FROM DB.TableName WHERE A IS NULL OR B IS NULL


text:
Q: How to get the checked items from a multi choice item in a Alert.Builder? Is there a way to get some infomation about the checked items in the next Alert.Builder? I need to save some booleans in SharedPreferences when somebody clicked the positive button. Those booleans are from the choices the user made in the alert. How can I get them?
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final SharedPreferences preferences = getSharedPreferences("type_settings", MODE_PRIVATE);

        boolean[] selectedTypes = getSelectedTypes(preferences);

        builder.setIcon(R.drawable.menu_type)
                .setTitle(R.string.list_dialog_title)
                .setMultiChoiceItems(R.array.select_type_items, selectedTypes,
                        new DialogInterface.OnMultiChoiceClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton, boolean isChecked) {
                            }
                        })
                .setPositiveButton(R.string.types_save, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        SharedPreferences.Editor prefEditor = preferences.edit();
                    }
                })
                .setNegativeButton(R.string.types_cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.cancel();
                    }
                })
                .create();
        builder.show();

A: I managed to resolve the problem in some way, but i don't know if it's a good practice. Here is the code:
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final SharedPreferences preferences = getSharedPreferences("type_settings", MODE_PRIVATE);

        final String[] availableTypes = getResources().getStringArray(R.array.select_type_items);
        final boolean[] selectedTypes = getSelectedTypes(preferences, availableTypes);

        builder.setIcon(R.drawable.menu_type)
                .setTitle(R.string.list_dialog_title)
                .setMultiChoiceItems(R.array.select_type_items, selectedTypes,
                        new DialogInterface.OnMultiChoiceClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton, boolean isChecked) {
                                selectedTypes[whichButton] = isChecked;
                            }
                        })
                .setPositiveButton(R.string.types_save, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        SharedPreferences.Editor prefEditor = preferences.edit();
                        saveSelectedTypes(prefEditor, availableTypes, selectedTypes);
                    }
                })
                .setNegativeButton(R.string.types_cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.cancel();
                    }
                })
                .create();
        builder.show();

A: You could use getCheckedItemIds() or getCheckedItemPositions () to get a list of checked items from the listview. You should use AlertDialog.getListView() to get the dialog's listview first.
mAlert.getListView().getCheckedItemPositions ();

A: For storage efficiency, you could convert the boolean array to an integer before storing it as a preference. But beware, the boolean array that initializes the AlertDialog list has the reverse order of the boolean array results from the AlertDialog. (Seems to be a consistent reversal: happens on OS 2.3.6 and 4.2.2 ... I haven't checked any other versions.)


text:
Q: Single expression for two variables where one is a function of the other Or... Can this be solved in a single expression?
My sense is I will need to tackle this programmatically with some sort of goal-seeking algorithm, but I wanted to check there wasn't a single expression that would solve the problem.
I want my imaginary company to operate at $5\%$ profitability. That is my net profit expressed as a percentage of my revenue should be $5\%$.
For the sake of example, let's say…

*

*My current revenue is $40,000$

*My current gross profit is $10,000$

*My current overheads are $8,500$

*(Therefore) my current net profit is $1,500$

That gives me a profitability of $1,500 / 40,000 = 0.0375$ or $3.75\%$
The problem: I want to know how much extra gross profit I need to get to my target of $5\%$
One very simple approach is:
$x = (n / p \cdot t) - n$
Where:

*

*$x$ is the extra gross profit I need

*$n$ is my current net profit

*$p$ is my current profitability level

*$t$ is my target

So, based on the above:
$(1,500 / 3.75 \cdot 5) – 1,500 = 500$
This checks out. If I had an extra $500$ then…

*

*My current revenue is still $40,000$ (more on this shortly!)

*My current gross profit is now $10,500$

*My current overheads are still $8,500$

*(Therefore) my current net profit is now $2,000$

This gives me a profitability of $2,000 / 40,000 = 0.05$ or $5\%$!
Hooray! Apart from the fact that is rather simple approach makes two assumptions:

*

*Adding gross profit doesn't affect add overheads

*Adding gross profit doesn't affect the revenue

Assumption #1 is fine. Overheads don't change as GP increases.
Assumption #2 is not. As I add GP, I also add revenue. In this model, I assume a margin of $26.5\%$. Sales are made at all sorts of margins, but $26.5\%$ is my historical average. So, for every $1$ of GP I make $3.77$ (calculated from $1$ / $0.265$) times the revenue.
So, my problem now is that when I calculate how much GP to add to get me to my $5\%$ target I need to adjust it upward to account for the fact that adding that GP will also increase my revenue and thus take me further away from my target!
I can't shake the sense I am missing something simple and the extra GP I need can be the result of evaluating a single expression rather than having to design an algorithm.
Please help!

A: In the formula
$$x=(n/p⋅t)−n$$
$n/p$ represents the current revenue, which is then multiplied by the desired profitability. Right off the bat, what we're doing is wishing more profit. Things aren't like that in the real world; we need to sell more in order to make more profit.
Let's note that GP is $25\%$ of revenue. This give current GP a value of $\frac{n}{4p}$. Our desired GP would be $\frac{n}{4p}+x$, and desired NP would be $\frac{n}{4p}+x-8500$. Desired revenue would be 4 times that of desired GP, or $\frac{n}{p}+4x$. So the following relationship must hold.
$$
\frac{\text{desired NP}}{\text{desired revenue}}=\frac{\frac{n}{4p}+x-8500}{\frac{n}{p}+4x}=t
$$
I'm assuming, of course, that "overhead" does not include any variable costs and that variable costs are linearly related to revenue.
So the extra GP becomes
$$x = \frac{8500}{1-4t}-\frac{n}{4p}$$

A: Managed to solve this myself:
$x$ = ($m$ * (-$g$ + $e$ * $o$ + $r$ * $t$)) / ($m$ - $t$)
If using decimal fractions for $t$ and $m$
and
$x$ = ($m$ * ($g$ - $e$ * $o$ - (($r$ * $t$) / 100))) / ($t$ - $m$)
If using percentage figures for $t$ and $m$


text:
Q: exim mail server error "process_client_hello:version too low" I need to connect a mail account to some device, it is not possible to change the protocol settings or update the firmware on the client device.
Exim version 4.94.2
When connecting to the mail in the log I get an error:
2022-10-05 14:40:43 TLS error on connection from [ip] I=[ip]:465 (SSL_accept (SSLv3)): error:1420918C:SSL routines:tls_early_post_process_client_hello:version too low
2022-10-05 14:40:47 no host name found for IP address 212.45.14.158
2022-10-05 14:40:47 TLS error on connection from [ip] I=[ip]:465 (SSL_accept (SSLv3)): error:1420918C:SSL routines:tls_early_post_process_client_hello:version too low
2022-10-05 14:40:51 no host name found for IP address 212.45.14.158
2022-10-05 14:40:51 TLS error on connection from [ip] I=[ip]:465 (SSL_accept (SSLv3)): error:1420918C:SSL routines:tls_early_post_process_client_hello:version too low

I think the client is trying to use the old version of ssl, how to resolve it?
Tried setting the parameter
openssl_options = +no_sslv2 +no_sslv3 +no_tlsv1 +no_tlsv1_1

did not help.
There are devices that connect, but they have more recent firmware and apparently the current version of ssl
tried editing the file to

https://askubuntu.com/questions/1233186/ubuntu-20-04-how-to-set-lower-ssl-security-level

did not help


text:
Q: MathJax 2.7.7 not centering formula properly on web page when there are line breaks I have something like this on a web page:

The "Theorem" and the block part from "Step 1" to "Step 2" are which MathJax is rendering. I was using version 2.3, but to avoid the vertical line that appears on the right I upgraded it to 2.7.7. But now the formulas are not centered when they include line breaks; they are aligned to the left:

In the HTML code I have this configuration:
<!DOCTYPE html>

        ...


text:
Q: Drastic change in footer I wrote a footer using aura components ,the footer looks good in chrome but when it comes to ie11 it is behaving differently.
The complete footer faded out.Let me know if any one can help on this issue
Attached is the screen shot of my footer[ie 11

A: This may be a waste of your efforts. Per the Release Notes, support for IE11 ends with SU16 release. I wouldn't recommend putting effort into solving an issue that won't have any Salesforce support a short time from now.

*

*Existing orgs will be able to continue to use IE11 until Dec 17th, 2016.

*Users of new orgs created after Summer '16 can't use IE11 to access Lightning Experience. Instead, IE11 users are automatically redirected to Salesforce Classic.

*It isn't clearly stated in the release notes, but I believe the redirection to Salesforce Classic is what will happen to users in existing orgs after Dec 17th 2016.

For more details about this change, see Retirement of Support for Accessing Lightning Experience and Salesforce1 Using Internet Explorer 11.


text:
Q: Diophantine equation about the automorphism group of lattice by constraints Fixed $\sigma_x=\left(
\begin{array}{cc}
 0 & 1 \\
 1 & 0 \\
\end{array}
\right)$ and $K=\left(
\begin{array}{ccc}
 3 & 32 & -64 \\
 1 & 32 & -32 \\
 -2 & -32 & 64 \\
\end{array}
\right),$
I want to find $n$ such that, $K_n=\sigma_x  \oplus \sigma_x  \oplus \cdots\oplus\sigma_x  \oplus K$.
and the corresponding $W \in GL(2n+3,\mathbb{Z})$ such that $W^{T}K_n^{-1}W=K_n^{-1},$ the only constraints for $W$ the downright corner should be $\left(
\begin{array}{cc}
 8 & -5 \\
 5 & 13 \\
\end{array}
\right).$ For example, if $n=1,$ I manage to find a $W$ looks like $W= \begin{bmatrix}
a_1 & a_2 & a_3 & a_4 & a_5 \\
b_1 & b_2 & b_3 & b_4 & b_5 \\
c_1 & c_2 & c_3 & c_4 & c_5 \\
d_1 & d_2 & d_3 & 8 & -5 \\
e_1 & e_2 & e_3 & 5 & 13
\end{bmatrix} $ such that:
\begin{equation}
W^{T}K_1^{-1}W=K_1^{-1}.
\end{equation}
I try to use Mathematica and find no solutions.
Then I try $n=2$ and I still can not find the solution. But I don't know how to prove there is no solution for $W^{T}K_n^{-1}W=K_n^{-1}.$ for any $n$. I believe there should be $1$.
My comment about this problem:
1 I can not find much literature about the diophantine equation solution of integer quadratic form (at least for $4 \times 4$). But my imagination is that when $n$ grows, there should be more freedom and more variables. So one should be able to find a solution or at least prove the solution exists.
2 Since $K_n \oplus \sigma_x$ is an indefinite matrix so that there is no computational system to find that automorphism group of $K_n$. See related question here. An indefinite matrix will lead to an infinite automorphism group so the capacity of the automorphism group should be large enough to capture such $W$.
3 Notice that the smith normal form for $=\left(
\begin{array}{ccc}
 1 & 0 & 0 \\
 0 & 32 & 0 \\
 0 & 0 & 32 \\
\end{array}
\right). $ So for any $K_n$ it always has two nontrivial components $32$. So this is why there is a constraint for $2 \times 2$ corner for $W$.
My research has a problem related to this type of question given $K$ and $W$ (restrict $W$ for the right down corner and claim that one can find large enough $K$ (enlarge $K$ and $W$) with the same and nontrivial Smith normal ($\neq 1$) form and satisfy $W^{T}K_1^{-1}W=K_1^{-1}.$ )
Any comments and results are very welcome, thanks a lot.


text:
Q: (UEFI) Chainloading GRUB from GRUB Terminology: ESP = my FAT32 EFI partition.
I want to:

*

*Have a self-contained GRUB install on my ESP that chainloads another GRUB bootloader on my distro root filesystem (/). I currently have several distros without GRUB installed on my partitions. Each is installed completely on their own ext4 /. I want them all to have their own secondary bootloader.

*Also acceptable is for the primary ESP GRUB to restart/reload with a grub.cfg from the OS. Effectively chainloading itself.

What I've tried:

*

*Examples I've found include booting GRUB legacy from GRUB2 and vice versa but they don't use UEFI and .efi files. The GNU GRUB documentation doesn't even mention UEFI, and the Arch/Ubuntu/Gentoo wikis provide the bare minimal info to set up a basic (non-chainloading) install.

So far:

*

*I've installed GRUB onto my ESP using grub-install and
grub-mkconfig.Test boot works. This means my /boot/grub folder is empty, and my ESP doesn't need to be mounted during/after boot.

*I've tried installing a second grub into /boot/efi/ and /boot/grub/, but the EFI part won't install, grub-install complains the target is not an EFI partition. But since I already have a primary GRUB installed, it shouldn't matter that my secondary GRUB is on the ext4 rootfs right? Grub can read ext4. I tried the --force option too.

So it seems I need to find some way of convincing the installer that it is OK to install grubx64.efi under /boot/EFI...
If anyone is curious about how I installed the primary GRUB, it was just a matter of using the right options in grub-install with respect to my ESP.

A: I've found out how to manually install the .efi on each of my /'s. Referring to the secondary GRUB chainloader from the primary config is simple:
menuentry "GRUB chainloader" {
 #Load grub on partition 7 of a gpt formatted drive.
 #It will reference its own modules and config.
 chainloader (hd0,gpt7)/path/to/bootloader/on/myOS/core.efi
}

To create this secondary .efi  I used grub-mkimage because grub-install didn't let me write to a non-FAT filesystem. The syntax is very picky and it doesn't give errors if you use a wrong path, so check the arguments carefully:
grub-mkimage -o /path/to/mounted/targetOS/efidir/core.efi --format=x86_64-efi '--prefix=(hd0,gpt7)/boot/grub' ext2 part_gpt

I tried leaving out the GPT or ext2 filesystem modules but that didn't work, those two modules were the absolute minimum requirement for my system (ext2 works for ext2/3/4).
The prefix directory is where the secondary bootloader will look for its modules folder and config file. So I have manually created a /boot/grub/ for each OS that includes a x86_64-efi/ folder (copied from /usr/lib/grub) and a grub.cfg I can modify using grub-mkconfig with OS-probing disabled (or just manually edit it).
I originally installed each OS without GRUB. This method allowed me to install secondary GRUB bootloaders on all operating systems using a first OS or LiveCD with GRUB. I can change the boot configuration of each OS independently, no risks for contamination because the ESP is never mounted.

A: I am trying to do a similar thing for i386-pc grub, and chainloader of the the core.img file would not work, giving "error: invalid signature"
But I had learned that the grub core.img file is multiboot compliant, so I was able to boot core.img like:
multiboot (hd0,7)/core.img
boot

and successfully get the new grub, it's modules and initial configuration.
I suppose your chainloader command fails on an efi for a non-efi grub, so this failrue can be detected and fall-back to multiboot on core.img before the boot command.

A: There's another way: you can create a menu entry that tells GRUB to load another secondary grub.cfg, such as one from another Linux distro.
For example, I started with Gentoo Linux from which I installed GRUB2 into the MBR (the machine is too old for EFI).
I then installed NixOS, which I configured to generate grub.cfg in it's own /boot (separate from Gentoo's /boot) but without installing GRUB.
To clarify, grub-install was executed from Gentoo but not from NixOS.
Next, to be able to boot NixOS, I added this to /etc/grub.d/40_custom in Gentoo:
#!/bin/sh
exec tail -n +3 $0
# This file provides an easy way to add custom menu entries.  Simply type the
# menu entries you want to add after this comment.  Be careful not to change
# the 'exec tail' line above.

menuentry 'NixOS' --class gnu-linux --class gnu --class os $menuentry_id_option 'nixos-0aca58bc-8fdb-4a07-aa2f-56406bcf19b7' {
        set root='hd0,msdos4'
        configfile /nixos/root/boot/grub/grub.cfg
}

The key is the configfile /nixos/root/boot/grub/grub.cfg line. It tells GRUB to load another grub.cfg. I then ran grub-mkconfig from Gentoo to apply the changes.
Now, when I boot and select NixOS the entire GRUB interface refreshes to reflect the NixOS grub.cfg, from which I can boot the OS. Unlike chainloading, this configuration utilizes a single installation of GRUB; it simply uses a second configuration.


text:
Q: Security Policy Error Calling Java Web Service From .Net I am trying to call a Java web service, over Http not Https, using .Net. The only hint I got from the web service team is to pass the credential either in SOAP message or in the endpoint settings.
I have created a simple console application and added a service reference to the web service. The following is the generated binding (I see that there is warning about unrecognized policy but cannot figure what it means or whether it is relevant or not):
<customBinding>
    <binding name="CurrencyInformationServiceSoapBinding">
        <!--    WsdlImporter encountered unrecognized policy assertions in ServiceDescription 'http://www.openuri.org/':    -->
        <!--    <wsdl:binding name='CurrencyInformationServiceSoapBinding'>    -->
        <!--        <ns1:SupportingTokens xmlns:ns1="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200512">..</ns1:SupportingTokens>    -->
        <textMessageEncoding maxReadPoolSize="64" maxWritePoolSize="16"
            messageVersion="Soap11" writeEncoding="utf-8">
            <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                maxBytesPerRead="4096" maxNameTableCharCount="16384" />
        </textMessageEncoding>
      <!--<security authenticationMode="UserNameOverTransport" allowInsecureTransport="true"/>-->
      <httpTransport manualAddressing="false" maxBufferPoolSize="524288"
            maxReceivedMessageSize="65536" allowCookies="false" authenticationScheme="Anonymous"
            bypassProxyOnLocal="false" decompressionEnabled="true" hostNameComparisonMode="StrongWildcard"
            keepAliveEnabled="true" maxBufferSize="65536" proxyAuthenticationScheme="Anonymous"
            realm="" transferMode="Buffered" unsafeConnectionNtlmAuthentication="false"
            useDefaultWebProxy="true" />
    </binding>
</customBinding>

Here are my trials:
Trail #1:
-----------
Using the following code:
CurrencyInformationServiceClient client = new CurrencyInformationServiceClient();
foreignCurrencyDTO[] results = client.getAllForeignCurrencies();

or supplying the credentials in Windows property
CurrencyInformationServiceClient client = new CurrencyInformationServiceClient();
client.ClientCredentials.Windows.ClientCredential = new System.Net.NetworkCredential("crmuser", "welcome1");
foreignCurrencyDTO[] results = client.getAllForeignCurrencies();

or supplying the credentials in UserName property
CurrencyInformationServiceClient client = new CurrencyInformationServiceClient();
client.ClientCredentials.UserName.UserName = "someuser";
client.ClientCredentials.UserName.Password = "somepassword";
foreignCurrencyDTO[] results = client.getAllForeignCurrencies();

resulted in
 System.ServiceModel.FaultException: Error on verifying message against security policy Error code:1000

Trail #2:
-----------
As per one comment I have seen, I have tried to add the following tag in the binding and call the web service by passing the credentials in UserName property of ClientCredentials
<security authenticationMode="UserNameOverTransport" allowInsecureTransport="true"/>

but the result was
System.ServiceModel.Security.MessageSecurityException: Security processor was unable to find a security header in the message. This might be because the message is an unsecured fault or because there is a binding mismatch between the communicating parties. This can occur if the service is configured for security and the client is not using security.

Trail #3:
-----------
I have tried to use WSHttpBinding instead of the CustomBinding generated by VS as follows:
WSHttpBinding binding = new WSHttpBinding();
binding.Security.Mode = SecurityMode.Message;
binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
EndpointAddress ea = new EndpointAddress("http://someurl/CurrencyInformationService.jws");
CurrencyInformationServiceClient client = new CurrencyInformationServiceClient(binding, ea);
client.ClientCredentials.UserName.UserName = "someuser";
client.ClientCredentials.UserName.Password = "somepassword";
foreignCurrencyDTO[] results = client.getAllForeignCurrencies();

but the result was
System.ServiceModel.ProtocolException: Content Type application/soap+xml; charset=utf-8 was not supported by service http://someurl/CurrencyInformationService.jws.  The client andservice bindings may be mismatched. ---> System.Net.WebException: The remote server returned an error: (415) Unsupported Media Type.

Update:
-----------
I have received a working request from the vendor and tried it in soapUI and it gave a correct response.
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <soap:Header>
                <wsse:Security soap:mustUnderstand="1">
                        <wsse:UsernameToken wsu:Id="SecurityToken-35598fb7-5aa2-4623-b07b-3277c6578beb" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
                                <wsse:Username>someuser</wsse:Username>
                                <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">somepassword</wsse:Password>
                        </wsse:UsernameToken>
                </wsse:Security>
        </soap:Header>
        <soap:Body>
                <getAllForeignCurrencies xmlns="http://www.openuri.org/">
                </getAllForeignCurrencies>
        </soap:Body>
</soap:Envelope>

Can someone give me a hint how to generate such a SOAP request?

A: I was facing the same issue while consuming a java web service using .Net, and this thread helped me partially in being able to consume web service.
But, somehow I came across this post and it worked as a final solution for me : http://weblog.west-wind.com/posts/2012/Nov/24/WCF-WSSecurity-and-WSE-Nonce-Authentication
Below settings worked fine for me:
<?xml version="1.0"?>
<configuration>
  <system.serviceModel>
    <bindings>
      <customBinding>
        <binding name="CustomSoapBinding">
          <security includeTimestamp="false"
                    authenticationMode="UserNameOverTransport"
                    defaultAlgorithmSuite="Basic256"
                    requireDerivedKeys="false"
                    messageSecurityVersion="WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10">
          </security>
          <textMessageEncoding messageVersion="Soap11"></textMessageEncoding>
          <httpsTransport maxReceivedMessageSize="2000000000"/>
        </binding>
      </customBinding>
    </bindings>
    <client>
      <endpoint address="https://notrealurl.com:443/services/RealTimeOnline"
                binding="customBinding"
                bindingConfiguration="CustomSoapBinding"
                contract="RealTimeOnline.RealTimeOnline"
                name="RealTimeOnline" />
    </client>
  </system.serviceModel>
  <startup>
    <supportedRuntime version="v4.0"
                      sku=".NETFramework,Version=v4.0"/>
  </startup>
</configuration>

A: If you use SSL use this:
<basicHttpBinding>
                <binding name="NewBinding0">
                    <security mode="TransportWithMessageCredential" />
                </binding>
</basicHttpBinding>

If no SSL then use CUB.


text:
Q: Not able to get full url in php I know this question has been already asked before but I couldn't find my solution.
If it possible can I get this url
https://fileflix.net/#file?getFile=2&title=test2&ftype=pdf&thumb=https%3A%2F%2Ffileflix.net%2Fapi%2F%3FgetThumb%26filePath%3D%2Ffiles%2Ftest%2Ftesttest21540699674%26s%3D300

in php? I've already tried $_SERVER['REQUEST_URI']
echo '<script>console.log("url: '.$_SERVER['REQUEST_URI'].'")</script>';

and this is get logged to console
url: /

Please explain me if it is not possible.
Thank you so much for helping me out.

A: You have the hash in the wrong place in the URL. It needs to be after all the parameters that get sent to the server.
https://fileflix.net/?getFile=2&title=test2&ftype=pdf&thumb=https%3A%2F%2Ffileflix.net%2Fapi%2F%3FgetThumb%26filePath%3D%2Ffiles%2Ftest%2Ftesttest21540699674%26s%3D300#file

Your code will then print
/?getFile=2&title=test2&ftype=pdf&thumb=https%3A%2F%2Ffileflix.net%2Fapi%2F%3FgetThumb%26filePath%3D%2Ffiles%2Ftest%2Ftesttest21540699674%26s%3D300

To get the hostname you should print $_SERVER['HTTP_HOST'].
You can't print #file in PHP because the hash is only used on the client, it's not sent to the server.


text:
Q: Android apps problems i have been trying to develop an app. But when i declare any object of say class Button or even any other Class then it says "Unfortunately the app has stopped" when i run it. Please Help.
The xml file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button3"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/timePicker1"
        android:layout_centerVertical="true"
        android:layout_marginRight="17dp"
        android:text="Set" />

    <AnalogClock
        android:id="@+id/analogClock1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="24dp" />

    <TimePicker
        android:id="@+id/timePicker2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/timePicker1"
        android:layout_below="@+id/analogClock1" />

    <TimePicker
        android:id="@+id/timePicker1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

The Main java file
package com.example.quiet;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.Button;
public class MainActivity extends Activity {
int hour;
int minute;
Button btn1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btn1=(Button)findViewById(R.id.button3);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}
The Log
   02-28 17:06:42.917: E/AndroidRuntime(18977): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.quiet/com.example.quiet.MainActivity}: java.lang.ClassCastException: android.widget.TimePicker cannot be cast to android.widget.Button
02-28 17:06:42.917: E/AndroidRuntime(18977):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
02-28 17:06:42.917: E/AndroidRuntime(18977):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
02-28 17:06:42.917: E/AndroidRuntime(18977):    at android.app.ActivityThread.access$600(ActivityThread.java:123)
02-28 17:06:42.917: E/AndroidRuntime(18977):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
02-28 17:06:42.917: E/AndroidRuntime(18977):    at android.os.Handler.dispatchMessage(Handler.java:99)
02-28 17:06:42.917: E/AndroidRuntime(18977):    at android.os.Looper.loop(Looper.java:137)
02-28 17:06:42.917: E/AndroidRuntime(18977):    at android.app.ActivityThread.main(ActivityThread.java:4424)
02-28 17:06:42.917: E/AndroidRuntime(18977):    at java.lang.reflect.Method.invokeNative(Native Method)
02-28 17:06:42.917: E/AndroidRuntime(18977):    at java.lang.reflect.Method.invoke(Method.java:511)
02-28 17:06:42.917: E/AndroidRuntime(18977):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817)
02-28 17:06:42.917: E/AndroidRuntime(18977):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
02-28 17:06:42.917: E/AndroidRuntime(18977):    at dalvik.system.NativeStart.main(Native Method)
02-28 17:06:42.917: E/AndroidRuntime(18977): Caused by: java.lang.ClassCastException: android.widget.TimePicker cannot be cast to android.widget.Button
02-28 17:06:42.917: E/AndroidRuntime(18977):    at com.example.quiet.MainActivity.onCreate(MainActivity.java:22)
02-28 17:06:42.917: E/AndroidRuntime(18977):    at android.app.Activity.performCreate(Activity.java:4470)
02-28 17:06:42.917: E/AndroidRuntime(18977):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
02-28 17:06:42.917: E/AndroidRuntime(18977):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
02-28 17:06:42.917: E/AndroidRuntime(18977):    ... 11 more

A: I'm guessing it's because of btn1.setText(hour);
Since hour is an int, setText will look for a resource with the ID you passed. Try passing a string to your setText.

A: You are calling setText(0) this causes exception instead call like something setText("12:00");

A: Try:
btn1.setText("" + hour);

So to solve the int to string issue

A: These lines look suspicious. (Disclaimer - this may or may not be the primary issue).
    android:layout_alignRight="@+id/timePicker1"

    ....

    android:layout_alignLeft="@+id/timePicker1"

You are using the "@+id/" nomenclature for the layout relation. Remove the + sign such that you aren't trying to define an ID. Such as the following:
   android:layout_alignRight="@id/timePicker1"

    ....

   android:layout_alignLeft="@id/timePicker1"

Do however, keep the @+id/ tag for resource IDs on the widget they are being declared for:
<TimePicker
    android:id="@+id/timePicker1"

I'm not sure if the resource ID is your core problem, and the Android resource compiler can likely deal with it as you have it.  But it looked suspicious enough for me to call out.


text:
Q: How portable is an if clause on a parallel directive? This is related to How to disable OMP in a translation unit at the source file?. The patch I am working on has the following due to benchmarking results. It appears we need the ability to turn off OMP on the translation unit:
static const bool CRYPTOPP_RW_USE_OMP = true;
...

ModularArithmetic modp(m_p), modq(m_q);

#pragma omp parallel sections if(CRYPTOPP_RW_USE_OMP)
{
    #pragma omp section
        m_pre_2_9p = modp.Exponentiate(2, (9 * m_p - 11)/8);
    #pragma omp section
        m_pre_2_3q = modq.Exponentiate(2, (3 * m_q - 5)/8);
    #pragma omp section
        m_pre_q_p = modp.Exponentiate(m_q, m_p - 2);
}

The patch also applies to a cross platform library (Linux, Unix, Solaris, BSDs, OS X and Windows), and it supports a lot of older compilers. I need to ensure that I don't break a compile.
Question: how portable is the #pragma omp parallel sections if(CRYPTOPP_RW_USE_OMP)? Will using it break compiles that used to work with just #pragma omp parallel sections?
I tried looking at past OpenMP specifications, like 2.0, but I can't see where its allowed in the grammar (see Appendix C). The closest I could find is the parallel-directive production (line 22), which leads to parallel-clause (line 24) and then unique-parallel-clause.
And looking at documentation for platforms I can't test on, its not clear to me if its available. For example, Microsoft's documentation for Visual Studio 2005 appears to only allow it on a loop.

A: In the very document you link, page 8, section 2.2 parallel Construct. if is among the available clauses (the first one). It is part of the standard, so portable across all conforming compilers.
In your MSDN link:

if applies to the following directives:
parallel
for (OpenMP)
sections (OpenMP)


text:
Q: Why does this code output before even reading input? My code below outputs 0, the value of max_explode, before even reading in my input.  Why is this happening?
#include <iostream>
#include <vector>
#include <algorithm>
#define MAX 100
using namespace std;

int N,cnt=0;
vector<int> arr;
bool seen[MAX+1];
int main()
{
  for (int i = 0; i < N; i++) seen[i]=false;
  int max_explode=0;
  for (int i = 0; i < N; i++)
  {
    int cow;
    cin >> cow;
    arr.push_back(cow);
  }
  sort(arr.begin(),arr.end());
  cout << max_explode << "\n";
  return 0;
}

A: You read input in a loop:
for (int i = 0; i < N; i++)
{
  int cow;
  cin >> cow;
  arr.push_back(cow);
}

However, N is never explicitly initialized.  Since it's a global variable, it's automatically initialized to 0, and your loop never runs.

A: There's a small issue in your 7th line to be specific. You have defined the variable N but haven't initialized a value to it.


text:
Q: Working with django and sklearn enormous models I'm working on a django project that uses sklearn SVR models. The training part takes a lot of time and I need to use it relatively fast, so I'm trying to do the training part offline and store it in db / filesystem, and then the online just load it and use the models.
Problem is, when I try to use cPickle to serialize the data, I end up with over 500MB at best (and sometimes couple of GBs at worse). I can't load so much data online fast enough, it will make requests very slow.
So my question is, whats the recommended way to use sklearn SVR with django, when I want high performance? Should I use cPickle to serialize / deserialize or something else? Should I zip it? And what about loading, obviously I can't load this whole data per request, so is the way to go is putting it in cache?
Thanks,


text:
Q: Xcode 11 from App Store says app can't be installed I have faced problem when installing app to simulator. Xcode says it is successfully built. but then it shows this error:

A: Swapping the simulator target to an older device made that error no longer appear for me.
In my case an iPhone 5s - 10.3.1 rather than an iPhone 11 - 13.0


text:
Q: end event is not fired when piping to stream transformer In the following code the end event of read stream is fired properly.
const frs = createReadStream("./file.txt", {
  encoding: "utf8"
});

frs
  .on("data", chunk => {
    console.log(chunk);
  })
  .on("error", err => {
    throw err;
  })
  .on("end", () => {
    doSomething()
  });

But why the end event is not fired when piping to Transform streams.
frs
  .pipe(transform1)
  .pipe(transform2)
  .on("error", err => {
    throw err;
  })
  .on("end", () => {
    doSomething()
  });

In the second case (piping) how to call doSomething when stream is ended?

A: You can perform actions in 'finish' event.
Just replace 'end' on 'finish'
frs
.pipe(transform1)
.pipe(transform2)
.on("error", err => {
  throw err;
})
.on("finish", () => {
  doSomething()
});


text:
Q: Sudo chmod gets permissions denied When I run ls -l, the file I want to change permissions of is:
-rw-r--r-- 1 82176 1491 193716029663 Feb 16  2019 cfdna_hc_bam.bam

First try: chmod 775 cfdna_hc_bam.bam.
Result: chmod: changing permissions of 'cfdna_hc_bam.bam': Permission denied
Second try: sudo chmod 775 cfdna_hc_bam.bam. It asks for my password, I provide it and the Results: chmod: cannot access 'cfdna_hc_bam.bam': Permission denied.
When I enter cd .., ls -l, to see the permissions on the directory in which my file is, this is the result: drwxrwsr-x 1 93501 1491    8192 Sep 28 14:24  bam_files.
The only question I found similar is (Sudo chmod +x leads to "cannot access [file] permission denied"), and it had to do with a mounted image problem, which isn't my case here.
EDIT:

*

*I created a file in this directory, and changed its permissions, and
it worked:
touch a
chmod 755 a

This works.

*Then I did the same thing using 'sudo', and it didnt:
touch a
sudo chmod 755 a I get: `chmod: cannot access 'a': Permission denied`.

*Also, when I run the command id I get:
uid=1004(yonatan) gid=1005(yonatan) groups=1005(yonatan),27(sudo),132(docker)

*Trying to run sudo chown yonatan:yonatan -R <dir> on the directory in which the file is (and also in above directories), results in: chown: cannot access 'bam_files': Permission denied.

A: *

*The directory was received from another user on the remote machine.

*You are not the owner of that machine so i suspect that the directory is "secured" from sudo command.

*Try to contact the user that you received the directory from and the root of the remote machine and ask them to run this commands:

*

*chown -R yonatan:yonatan <filename> or chown -R 1004:1005 <filename> (wich is the same command).

*if the root run the command he can run it directly on the file you have received.

*if the user that sent you the directory running the commands he needs to run that on a copy in his own "home file" and then sent it to you with your uid and gid permissions.

*After you will be the owner of the directory try to run again the chmod command with the permissions you want.

*

*for an example chmod 775 <filename>

*Remarks:

*

*in your own specific case 93501 is the user that own the directory and 1491 is the group that own the directory.

*another option for a solution is to add your own user to 1491 (by the root), but then if other group 1491 users have access to your directory they will still have permissions to the file.

*i recommend to use this calculator as "permissions calculator" http://permissions-calculator.org/

*if the following answer is failing to solve the problem please let me know on the comments so we can keep try to solve that out.


text:
Q: Passport Js Stuck After Calling Callback Url I tried to implement twitter strategy using PassportJS for my ExpressJS application. However, it always stuck when calling the callback URL. Twitter actually called the callback route (I tried replacing passport.authenticate() with res.json()) but somehow when I put passport.authenticate() it got stuck. What could be the problem?
server
const express = require("express");
const cors = require("cors");
const session = require("express-session");
const csrf = require("csurf");
const compression = require("compression");
const helmet = require("helmet");
const MongoStore = require("connect-mongo");

const router = require("./routes/api.routes");
const passport = require("./middlewares/passport.middleware");

const app = express();

app.use(
  cors({
    origin: [
      "https://api.twitter.com",
    ],
    credentials: true,
  })
);
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(
  session({
    secret: process.env.SECRET,
    resave: true,
    rolling: true,
    saveUninitialized: true,
    store: MongoStore.create({
      mongoUrl: process.env.MONGODB_URI,
    }),
    cookie: {
      // 1 hour
      maxAge: 1000 * 60 * 60 * 1,
      httpOnly: true,
    },
  })
);
app.use(passport.initialize());
app.use(passport.session());
app.use(csrf());
app.use(helmet());
app.use(compression());
app.use(router);

// error handler
app.use(function (err, req, res, next) {
  if (err.code === "EBADCSRFTOKEN") {
    // handle CSRF token errors here
    return res.status(403).send({ message: "form tampered with" });
  }

  res.status(err.status || 500);
});

module.exports = app;

routes
// OAuth 1
router.route("/auth/twitter").get(passport.authenticate("twitter"));

router
  .route("/auth/twitter/callback")
  .get(passport.authenticate("twitter", { failureRedirect: "/error" }), (req, res) => {
    // it never reached here
    res.status(200).send({ msg: "success!" });
  });

router.route("/error").get((req, res) => {
  res.status(403).send({ msg: "authentication failed" });
});

passport config
passport.use(
  new TwitterStrategy(
    {
      consumerKey: process.env.TWITTER_CONSUMER_KEY,
      consumerSecret: process.env.TWITTER_CONSUMER_SECRET,
      callbackURL: "http://127.0.0.1:5000/auth/twitter/callback",
      passReqToCallback: true
    },
    async function (token, tokenSecret, profile, cb) {
      try {
        const user = await users.upsertUser(profile.id);
        return cb(null, user);
      } catch (err) {
        return cb(err);
      }
    }
  )
);

passport.serializeUser((user, cb) => {
  cb(null, user.email);
});

passport.deserializeUser(async (username, cb) => {
  try {
    const user = await users.findUserBy("email", username);
    // filter out data
    cb(null, user);
  } catch (err) {
    cb(err);
  }
});


text:
Q: How to configure Vimeo-Service-module in Silverstripe Forgive me for my English
I am new in PHP. And I'm building a site using Silverstripe and trying to configure Vimeo-Service-module. I'd follow the steps from this link
https://github.com/r0nn1ef/Silverstripe-Vimeo-Service-module
I did everything that mentions in the article. And created a page in admin panel of VimeoGallery page type and set the parameters on Videos tab to grab the videos for display.
After created page, I visited my and clicked on video menu but then all I see is no videos returned. It is showing blank page and no any error messages.
Is that I've done anything wrong. Please guide me...
Thanks in advance.

A: OK, I think I see the issue here. You are calling VimeoService::setAPIKey() however accessing the method like that is deprecated in the new version (the 2.0 branch - I was incorrect in my comment when I mentioned master) of the module.
The module instead uses the Site Config in the CMS to set the API key and a few other settings.
Now just remove VimeoService::setAPIKey() from your _config.php file, run /dev/build and set the API key through the CMS.
EDIT
On line 142 of VimeoGalleryPage.php, there is a function called flushCache. Replace the code in that function with the following:
public function flushCache($persistent = true) {
    parent::flushCache($persistent);
    unset($this->_cachedVideos);
}

Basically, the code in the 2.0 branch for this function does not correctly extend the same named function in SiteTree.


text:
Q: Java jsr310: difference between dates and times There are a plethora of SO questions that deal with calculating the difference between two dates or two times in Java. Many answers point out the problems with the core Java Date classes, and suggest using Jodatime, but AFAIK, there are none that suggest how to do this using jsr310.
So, are there any methods to calculate the difference between two dates or two times in jsr310?

For reference, the following questions handle this issue:
In core Java:

*

*milliseconds between two datetimes
In Jodatime:

*

*days betweens two dates

*Interval between two datetimes

A: Answering wrt to the final JDK1.8 version.
There are two amount classes - Duration and Period. Duration is time-based (nanos) and Period is date-based (year/month/day).
The amount of time between two temporal objects of the same type can be easily calculated in one of two ways (I prefer the first):
long days = ChronoUnit.DAYS.between(start, end);
long days = start.until(end, ChronoUnit.DAYS);

The Duration between two temporal objects of the same type can be calculated as follows:
Duration d = Duration.between(start, end);

The Period between two LocalDate objects can be calculated as follows:
Period p = Period.between(start, end);

A: How to do this depends on what date or datetime classes are being used.
If you are operating in real time (i.e. with time zones etc. so the datetime can be pinpointed to an exact Instant on the time-line), you can use the Duration class (javadoc) - e.g.
Duration diff = Duration.between(InstantProvider startInc, InstantProvider endInc);

where an InstantProvider is able
Alternatively, if you are operating in hypothetical time (i.e. without time zones etc.), you can use the Period class (javadoc) to get the difference between two instances of LocalDate - e.g.
// diff in days, months and years:
Period diff = Period.between(LocalDate start, LocalDate end);

// diff in days:
Period diff = Period.daysBetween(LocalDate start, LocalDate end);

However, I'm not aware of any convenient methods for getting the difference between two LocalDateTimes or LocalTimes. But... this could be done using Period as follows:
// diff between LocalDateTimes:
public static Period between(LocalDateTime start, LocalDateTime end){
  return Period.of(
    end.getYear()-start.getYear(),
    end.getMonthOfYear().getValue()-start.getMonthOfYear().getValue(),
    end.getDayOfMonth()-start.getDayOfMonth(),
    end.getHourOfDay()-start.getHourOfDay(),
    end.getMinuteOfHour()-start.getMinuteOfHour(),
    end.getSecondOfMinute()-start.getSecondOfMinute(),
    end.getNanoOfSecond()-start.getNanoOfSecond()
  );
}

// diff between LocalTimes:
public static Period between(LocalTime start, LocalTime end){
  return Period.of(0, 0, 0,
    end.getHourOfDay()-start.getHourOfDay(),
    end.getMinuteOfHour()-start.getMinuteOfHour(),
    end.getSecondOfMinute()-start.getSecondOfMinute(),
    end.getNanoOfSecond()-start.getNanoOfSecond()
  );
}


text:
Q: Close Window without code-behind in WPF Is it possible to bind a Button to Close the Window without adding a code-behind event?
<Button Content="OK" Command="{Binding CloseWithSomeKindOfTrick}" />

Instead of the following XAML:
<Button Content="OK" Margin="0,8,0,0" Click="Button_Click">

With the code-behind:
private void Button_Click(object sender, RoutedEventArgs e)
{
    Close();
}

Thanks!

A: If you want close the dialog Window, you can add for Button IsCancel property:
<Button Name="CloseButton"
        IsCancel="True" ... />

This means the following MSDN:

When you set the IsCancel property of a Button to true, you create a Button that is registered with the AccessKeyManager. The button is then activated when a user presses the ESC key.

Now, if you click on this Button, or press Esc then dialog Window is closing, but it does not work for the normal MainWindow.
To close the MainWindow, you can simply add a Click handler which has already been shown. But if you want a more elegant solution that would satisfy the MVVM style you can add the attached behavior:
public static class ButtonBehavior
{
    #region Private Section

    private static Window MainWindow = Application.Current.MainWindow;

    #endregion

    #region IsCloseProperty

    public static readonly DependencyProperty IsCloseProperty;

    public static void SetIsClose(DependencyObject DepObject, bool value)
    {
        DepObject.SetValue(IsCloseProperty, value);
    }

    public static bool GetIsClose(DependencyObject DepObject)
    {
        return (bool)DepObject.GetValue(IsCloseProperty);
    }

    static ButtonBehavior()
    {
        IsCloseProperty = DependencyProperty.RegisterAttached("IsClose",
                                                              typeof(bool),
                                                              typeof(ButtonBehavior),
                                                              new UIPropertyMetadata(false, IsCloseTurn));
    }

    #endregion

    private static void IsCloseTurn(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        if (e.NewValue is bool && ((bool)e.NewValue) == true)
        {
            if (MainWindow != null)
                MainWindow.PreviewKeyDown += new KeyEventHandler(MainWindow_PreviewKeyDown);

            var button = sender as Button;

            if (button != null)
                button.Click += new RoutedEventHandler(button_Click);
        }
    }

    private static void button_Click(object sender, RoutedEventArgs e)
    {
        MainWindow.Close();
    }

    private static void MainWindow_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Escape)
            MainWindow.Close();
    }
}

And in MainWindow use this Behavior like as:
<Window x:Class="MyProjectNamespace.MainWindow"
        xmlns:local="clr-namespace:MyProjectNamespace">

    <Button Name="CloseButton"
            local:ButtonBehavior.IsClose="True" ... />


text:
Q: How can I reuse return values in a Python class without rerunning the function every time? I'm having a problem when reusing a function inside a class. I would like to get the return value of a function without rerunning it every time I use it. What is the best way of doing this inside a class?
Thank you!
class Test():

    def __init__ (self):
        # self.my_list = my_list()

        pass

    @staticmethod
    def my_list():
        set_list = [1, 2, 3, 4, 5, 6]
        print ('you are not refrencing')

        return set_list

    @staticmethod
    def func_test():
        func_list = Test.my_list()
        return func_list

    @staticmethod
    def func_test2():
        func_list = Test.my_list()
        return func_list

    @staticmethod
    def print_func():
        print Test.my_list()
        print Test.func_test()
        print Test.func_test2()

        return

Test.print_func()

here is my current result:
you are not referencing
[1, 2, 3, 4, 5, 6]
you are not referencing
[1, 2, 3, 4, 5, 6]
you are not referencing
[1, 2, 3, 4, 5, 6]

I would get this result instead
you are not referencing
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]

A: If your functions are pure (no side effects/same inputs always produce the same outputs), you can use memoization with @functools.lru_cache, which caches the output for a given set of inputs. (This is backed by a dict, so the arguments must be hashable.)
If the function is not pure (like your example with the print() call inside) then adding this decorator will change the behavior: the side effects will be skipped on the following calls. Also be very careful when you return a mutable value (like a list) because the same cached object will be returned, even if anything has mutated it, which might not be what you expect.

A: import functools

class Test():

    def __init__ (self):
        # self.my_list = my_list()

        pass

    @staticmethod
    @functools.lru_cache(maxsize=128, typed=False)
    def my_list():
        set_list = [1, 2, 3, 4, 5, 6]
        print ('you are not refrencing')

        return set_list

    @staticmethod
    def func_test():
        func_list = Test.my_list()
        return func_list

    @staticmethod
    def func_test2():
        func_list = Test.my_list()
        return func_list

    @staticmethod
    def print_func():
        print (Test.my_list())
        print (Test.func_test())
        print (Test.func_test2())

        return

Test.print_func()

you can try this code if you are in python 2.7
from repoze.lru import lru_cache

@lru_cache(maxsize=500)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)


text:
Q: Normalizing the dogs API I was looking to get some practice using Normalizer and though I would give a shot with the dogs API at https://dog.ceo/dog-api/documentation/
Listing all breeds looks like this
{
    "message": {
        "affenpinscher": [],
        "african": [],
        "airedale": [],
        "akita": [],
        "appenzeller": [],
        "australian": [
            "shepherd"
        ],
        "basenji": [],
        "beagle": [],
        "bluetick": [],
        "borzoi": [],
...

What should the normalized data structure look like and how would you use Normalizer to get that?
The docs work for their simple example but I want to know how to deal with in the wild APIs that you have no control over modifying.