text:
Q: I have an error when I try to install Discord canvas easy During my free time I develop a discord bot, but when I try to install discord-canvas-easy. Error. Someone have a solution ?
I'm on MacBook Pro M1 Pro (intel chip)
luca@MBP-M1Pro-Luca IweZix-2.1 % npm i discord-canvas-easy@3.2.0
npm WARN deprecated @discordjs/collection@0.7.0: no longer supported
npm WARN deprecated @discordjs/builders@0.16.0: no longer supported
npm ERR! code 1
npm ERR! path /Users/luca/Library/CloudStorage/OneDrive-Personnel/IweZix-2.1/node_modules/canvas
npm ERR! command failed
npm ERR! command sh -c node-pre-gyp install --fallback-to-build --update-binary
npm ERR! Failed to execute '/Users/luca/.nvm/versions/node/v16.14.0/bin/node /Users/luca/.nvm/versions/node/v16.14.0/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js configure --fallback-to-build --update-binary --module=/Users/luca/Library/CloudStorage/OneDrive-Personnel/IweZix-2.1/node_modules/canvas/build/Release/canvas.node --module_name=canvas --module_path=/Users/luca/Library/CloudStorage/OneDrive-Personnel/IweZix-2.1/node_modules/canvas/build/Release --napi_version=8 --node_abi_napi=napi --napi_build_version=0 --node_napi_label=node-v93' (1)
npm ERR! node-pre-gyp info it worked if it ends with ok
npm ERR! node-pre-gyp info using node-pre-gyp@1.0.10
npm ERR! node-pre-gyp info using node@16.14.0 | darwin | arm64
npm ERR! node-pre-gyp http GET https://github.com/Automattic/node-canvas/releases/download/v2.10.2/canvas-v2.10.2-node-v93-darwin-unknown-arm64.tar.gz
npm ERR! node-pre-gyp ERR! install response status 404 Not Found on https://github.com/Automattic/node-canvas/releases/download/v2.10.2/canvas-v2.10.2-node-v93-darwin-unknown-arm64.tar.gz
npm ERR! node-pre-gyp WARN Pre-built binaries not installable for canvas@2.10.2 and node@16.14.0 (node-v93 ABI, unknown) (falling back to source compile with node-gyp)
npm ERR! node-pre-gyp WARN Hit error response status 404 Not Found on https://github.com/Automattic/node-canvas/releases/download/v2.10.2/canvas-v2.10.2-node-v93-darwin-unknown-arm64.tar.gz
npm ERR! gyp info it worked if it ends with ok
npm ERR! gyp info using node-gyp@9.3.0
npm ERR! gyp info using node@16.14.0 | darwin | arm64
npm ERR! gyp info ok
npm ERR! gyp info it worked if it ends with ok
npm ERR! gyp info using node-gyp@9.3.0
npm ERR! gyp info using node@16.14.0 | darwin | arm64
npm ERR! gyp info find Python using Python version 3.9.10 found at "/opt/homebrew/opt/python@3.9/bin/python3.9"
npm ERR! gyp info spawn /opt/homebrew/opt/python@3.9/bin/python3.9
npm ERR! gyp info spawn args [
npm ERR! gyp info spawn args   '/Users/luca/.nvm/versions/node/v16.14.0/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py',
npm ERR! gyp info spawn args   'binding.gyp',
npm ERR! gyp info spawn args   '-f',
npm ERR! gyp info spawn args   'make',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   '/Users/luca/Library/CloudStorage/OneDrive-Personnel/IweZix-2.1/node_modules/canvas/build/config.gypi',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   '/Users/luca/.nvm/versions/node/v16.14.0/lib/node_modules/npm/node_modules/node-gyp/addon.gypi',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   '/Users/luca/Library/Caches/node-gyp/16.14.0/include/node/common.gypi',
npm ERR! gyp info spawn args   '-Dlibrary=shared_library',
npm ERR! gyp info spawn args   '-Dvisibility=default',
npm ERR! gyp info spawn args   '-Dnode_root_dir=/Users/luca/Library/Caches/node-gyp/16.14.0',
npm ERR! gyp info spawn args   '-Dnode_gyp_dir=/Users/luca/.nvm/versions/node/v16.14.0/lib/node_modules/npm/node_modules/node-gyp',
npm ERR! gyp info spawn args   '-Dnode_lib_file=/Users/luca/Library/Caches/node-gyp/16.14.0/<(target_arch)/node.lib',
npm ERR! gyp info spawn args   '-Dmodule_root_dir=/Users/luca/Library/CloudStorage/OneDrive-Personnel/IweZix-2.1/node_modules/canvas',
npm ERR! gyp info spawn args   '-Dnode_engine=v8',
npm ERR! gyp info spawn args   '--depth=.',
npm ERR! gyp info spawn args   '--no-parallel',
npm ERR! gyp info spawn args   '--generator-output',
npm ERR! gyp info spawn args   'build',
npm ERR! gyp info spawn args   '-Goutput_dir=.'
npm ERR! gyp info spawn args ]
npm ERR! /bin/sh: pkg-config: command not found
npm ERR! gyp: Call to 'pkg-config pixman-1 --libs' returned exit status 127 while in binding.gyp. while trying to load binding.gyp
npm ERR! gyp ERR! configure error
npm ERR! gyp ERR! stack Error: `gyp` failed with exit code: 1
npm ERR! gyp ERR! stack     at ChildProcess.onCpExit (/Users/luca/.nvm/versions/node/v16.14.0/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:325:16)
npm ERR! gyp ERR! stack     at ChildProcess.emit (node:events:520:28)
npm ERR! gyp ERR! stack     at Process.ChildProcess._handle.onexit
{...}

I try to update node, update npm, install latest discord-canvas-easy


text:
Q: Ruby Sinatra throwing wrong number of arguments (2 for 1) in const_get I have installed sinatra gems on local machine(Ruby 2.x) and server(Ruby 1.8.x). It worked well in my local machine but failing in server. Please help me in resolving this if anyone else encountered this before.
require 'rubygems'
require 'sinatra'

get '/' do
  'Hello world!'
end

ruby --version

ruby 1.8.7 (2013-06-27 patchlevel 374) [x86_64-linux]

gem list
rack (1.6.4)
rack-protection (1.5.3)
sinatra (1.4.6)
tilt (2.0.1)

Exception

ruby/1.8/gems/rack-1.6.4/lib/rack/handler.rb:22:in const_get': wrong
  number of arguments (2 for 1) (ArgumentError)     from
  \\..gem/ruby/1.8/gems/rack-1.6.4/lib/rack/handler.rb:22:inget'  from
  \..gem/ruby/1.8/gems/sinatra-1.4.6/lib/sinatra/base.rb:1777:in
  detect_rack_handler'     from
  \\..gem/ruby/1.8/gems/sinatra-1.4.6/lib/sinatra/base.rb:1775:ineach'
    from \..gem/ruby/1.8/gems/sinatra-1.4.6/lib/sinatra/base.rb:1775:in
  detect_rack_handler'     from
  \\..gem/ruby/1.8/gems/sinatra-1.4.6/lib/sinatra/base.rb:1437:inrun!'
    from \..gem/ruby/1.8/gems/sinatra-1.4.6/lib/sinatra/main.rb:25

A: Ruby 1.8.7:
const_get(sym) => obj

Ruby 2.1.0:
const_get(sym, inherit=true) → obj

So, even though Sinatra claims that it supports ruby 1.8.7, Rack apparently does not. You can try downgrading Rack to last version supporting 1.8.7 (I have no clue which would that be). But why would you use 1.8.7 in 2015 anyway?

A: For ruby 1.8.7 and sinatra 1.4.6.
update the Gemfile.lock update rack version.
rack (1.6.1)
bundle install

redpajama_set_name: RedPajamaStackExchange


text:
Q: Вывести только уникальные значения У меня есть база данных. В ней содержится:
ID | TAG
1  | Valera
2  | Andrey
3  | Anna
4  | Valera
5  | Anna

Мне нужно получать только 1 значение TAG не взирая на дубликаты:
1 | Valera
2 | Andrey
3 | Anna

A: Существует оператор distinct для получения уникальных значений:
SELECT DISTINCT `TAG` FROM `table`


text:
Q: Shell - Sed REGEXP capture from a word till an eventual comma and the end of line I am struggling with regex using sed
I am reading a file with lines
word1 word2 myword word4 word5 word6,
lorem ipsum dolor amet myword asinus es
salut comment ca va myword c'est comme ca,

I want to get
word1 word2,
lorem ipsum dolor amet
salut comment ca va,

This is only a portion of my file, that's why I need to work only line by line.
All I could find was :
echo $line | sed -e 's/\(myword.*\)\(,\)$/\2/g'

But I only get
word1 word2,
lorem ipsum dolor amet myword asinus es
salut comment ca va,

I cannot capture if there is a last comma or not. Can anyone help me ?
The question is more : I want to get everything before "myword" and keep the last comma if I have one using sed regexp
Thanks

A: Just get rid of everything from " myword" up to a comma or end of line:
$ sed 's/\(.*\) myword[^,]*/\1/' file
word1 word2,
lorem ipsum dolor amet
salut comment ca va,

A: You could make use of a label.  Check if the line ends in a comma and act accordingly:
sed -e '/,$/{s/\( myword.*\)\(,\)$/\2/; ba}' -e 's/\( myword.*\)//' -e :a inputfile

For your input, produces:
bla bla bla,
ble ble ble
blo blo blo,

A: This might work for you (GNU sed):
sed 's/ myword[^,]*//' file

Which deletes from the first space before myword to the first following , or end of line, or:
sed 's/ myword.*\([^,]\|\(,\)\)$/\2/' file

Which deletes from the first space before myword to the end of line or the , before the end of line.


text:
Q: The application and the screen stop when running the code I am a beginner in programming, and I found it difficult to overcome this problem, which is represented in the Android application that runs the Python code
The code works fine. But when I add while Ture, the screen stops. What is the cause of the problem? Thank you
script python
Is there a suggestion about this problem?

def main(CodeAreaData):
file_dir = str(Python.getPlatform().getApplication().getFilesDir())

filename = join(dirname(file_dir), 'file.txt')

try:

    original_stdout = sys.stdout

    sys.stdout = open(filename, 'w', encoding = 'utf8', errors="ignore")

    exec(CodeAreaData) # it will execute our code and save output in file

    sys.stdout.close()

    sys.stdout = original_stdout

    output = open(filename, 'r').read()

    sys.stdout.close()
except Exception as e:

    sys.stdout = original_stdout

    output = e

return str(output)

my code kotlin
```kotlin

val py = Python.getInstance()

//here we call our script with the name "myscirpt

//here we call our script with the name "myscirpt
val pyobj = py.getModule("myscript") //give python script name

//and call main method inside script...//pass data here

//and call main method inside script...//pass data here
val obj = pyobj.callAttr("main", editor.text.toString())
println(obj)

A: If you're adding a while true statement, then the screen should stop. That will lead to an infinite loop. A while loop runs until the condition evaluates to false. Here is more info about that:
https://www.geeksforgeeks.org/how-to-use-while-true-in-python/


text:
Q: Multiple titles and images for the same Object on Facebook Graph API Im working in a new web app, i created an action and an object in my facebook developers page.
All the users do the same, they "drop" an "object". The thing is, the name of the object is variable, so the same happens whit the link that i want to send them when they click in the facebook post.
There is a way to do this, or when every user drop an "object", to publish, i have to create a new facebook custom object in my app?


text:
Q: How to get rows with values of a column matching the same sequence of another sequence For example there's a DataFrame df. And I want sort the rows based on the sequence s in order to get df_target. What's the correct way to achieve this purpose?
import pandas as pd
df = pd.DataFrame({'a': [3,4,2,5], 'b':['apple', 'orange', 'pear',
'grape']})

s = [4,5,2,3]
df_target = pd.DataFrame({'a': [4,5,2,3], 'b':['orange', 'grape',
'pear', 'apple']})

A: You could temporarily set the index to a and then index using the list:
In[209]:
df.set_index('a').loc[s].reset_index()
Out[209]:
   a       b
0  4  orange
1  5   grape
2  2    pear
3  3   apple


text:
Q: How does The Flash move without being seen? In the second episode of the CW Flash TV show, Barry runs around Iris so fast and speaks so quickly that to her it appears that he was standing in front of her the whole time(She doesn't even notice a blur). How fast would Barry be moving and speaking that he would A: have the pitch of his voice be moved into the ultrasonic range and B: be red-shifted out of the visible light specturm. I'm assuming he would have to move very close to or faster than the speed of light and speak nearly as fast. However, I was wondering if someone has a more specific answer as well as possibly another explanation because during this time his maximum speed ever reached is 700 mph in the first episode. Thanks for any help.

A: It's less about "redshifted out of the visible spectrum" (which doesn't really make much sense anyway) and more about the density of the blur.
Suppose that Barry was standing in the same place for 0.08 seconds, then ran a circle in 0.02 seconds (just plausible within the 700 mph limit), then standing in the same place for 0.08 seconds again, and so on. Then what would be visible for normal humans is 4/5 of Barry being stationary (nearly indistinguishable from standing all the time) and 1/5 of Barry stretched all over as a blur; that 1/5 is total over the entire circle, so would have tiny density.
(Actually, due to the way human vision works, it might well be possible for Barry to spend an even bigger part of the time circling and still end up with a well visible standing shape and an invisible blur. But this 4:1 ratio is definitely safe enough.)
As for the voice, assuming that Barry's voice is sped up by the same factor as his running is, we get a factor of about 50-100 (I'm assuming Barry is not a particularly fast runner from his perspective). This means that his voice must have been over 200-400 Hz from his perspective to be shifted into ultrasound; this is around countertenor territory (i.e. a bit high for a male but not too unlikely).
(Note: I have never seen the show in question; I'm just trying to figure out how the situation described could make sense. If the answer is wrong due to that, sorry.)


text:
Q: Is there a way to know how many times my jar (in public Maven repository) is downloaded through Maven? For statistical reasons, we need to know how often our library (jar) is used. When users download the jar from our website, we have a built-in script that counts the downloads. We have recently also included the jar in the Maven public repository. Is there a way to get statistics on how often the jar is actually downloaded through Maven?

A: You're not alone, see MNG-3615. But as explained in the same issue, this is not part of Maven's job. In other words, apart from using grep and wc on a (possibly) aggregated access.log (yeah, mirrors) of the central repository, I don't see how you could get a count (and obviously, not anybody can do this).
Funnily, Jazon Van Zyl also blogged about this in Nexus: Improving Maven Central and Supporting the Maven Ecosystem a few months ago:

Next we're thinking about ways to make statistics for a given project's artifacts available to the project's developers.  We have already implemented user signup in Nexus and we are currently working on project signup as well. What this means is that projects can register with a given groupId, or set of groupIds, and optionally be provisioned a repository which can be operated by a set of users. Once a project registers we will know what slice, or slices, of the statistics they need to see.   Our initial thought is that project statistics, number of downloads should only be made available to the public with the permission of each individual project. Brian and I along with Greg Luck and Dain Sundstrom have been working on a simple statistics mechanism that we hopefully can provide to projects early this year.

Why not leaving a comment to get some update?


text:
Q: How to assign a variable the current output of a select tag I'm having some trouble with a select tag.
I want to assign a value to a variable depending on which name is shown on the select tag:
<%= select('product', 'name' , @products.map { |s| [s.name, s.id] }, {}, {:class => "form-control"}) %>

The values display correctly, but I want to assign the currently selected value to a variable so that it can be used later on the same page to display content with the relevant details of the selected product.
For example:
@product = currently_displayed_name

Is this possible with Rails and how to do it? Or do I might need to use another resource?

A: Props to the comments, the answer is that Rails does not give you a way to do that. Depending on what you need to manipulate when user changes select value, you might be able to find a JavaScript library for it.
Otherwise, you can load the default variable on the page, and then handle the rest with an onchange handler:
$('#product_name').change(function() {
  // perform actions on the page with javascript
});


text:
Q: How to render a variable inside another? I want to place the variable $all right in the middle of $code, which is HTML code that I gathered from another file. My current code is like this.
ob_start();
---code here---
$all = ob_get_clean();
$code = file_get_contents("file.txt");
echo $code;

file.txt would look a little something like this.
<html>
<head>
<title>Title</title>
</head>
<body>
---HTML code here---
$all
---More HTML code---
</body>
</html>

What should I do so that when I echo $code, $all is rendered inside it?

A: Use str_replace to replace $all with the value.
$code = str_replace('$all', $all, $code);

A: OP got his solution, but I thought this was worth mentioning as well.
If you don't have a placeholder in the HTML file, but you know that you want to insert $all after something specific, you could do something like this:
$all = ob_get_clean();
$code = file_get_contents("file.txt");
$after = "<input type=\"hidden\" value=\"something\" />";

$code = substr_replace($code, $all, strpos($code, $after)+strlen($after), 0);

This will find $after in $code, move to the end of it, and then insert $all.

A: Try to use RegEx.
You could replace 'body' tag by 'body' tag + your var.
Like :
echo preg_replace('/<body>/',"<body>$all",$code);

But you have to be sure that one and only one <body> tag is present in $code


text:
Q: Using dice as a kids game and summing random list of ints while excluding specific values from the final sum The game begins with the player 'rolling 5 dice.' Then the player gets a score of the combined numbers of the dice excluding 2's and 5's. Any 2's or 5's rolled results in dice "stuck in the mud." So say you roll a [1, 3, 4, 5, 2] the score should be: 8. Then the player rolls the remaining 3 dice, again you rolled [6,3,2] the score should then be 17. So on and so forth until the player runs out of dice and the code returns a final score.
import random

print("One round of Stuck in the Mude")
game = input("Enter r to roll the dice or q to quit: ")

diceC = 5
while game == "r" and game != "q" and diceC > 0:

    dice = [random.randint(1,6) for i in range(diceC)]

    score = 0
    for d in dice:
        # the rules for getting a score
        if d==2 or d==5:
            diceC -= 1
            pass
        else:
            score = score + d

    print('dice rolls:', dice)
    print('score', score)
    game = input("Enter r to roll the dice or q to quit: ")

A: The attempt that you made was okay, but there was overuse of the lists (which probably confused you). In light of your comments, this would be a good clean solution to work from.

*

*need one variable for the number of rolls.

*only need one list (for the dice rolls).

*for loop over the list to generate the score.

(You never needed to append the lists, but in any event, one needs to be careful appending lists that they are iterating through as it risks going out of range).
Here is the code:
import random

number_rolls = 5
dice = [random.randint(1,6) for i in range(number_rolls)]

score = 0
for d in dice:
    # the rules for getting a score
    if d==2 or d==5:
        pass
    else:
        score = score + d
        print('current score:', score)

print('---end---')
print('dice rolls:', dice)
print('final score', score)

result:
current score: 3
current score: 9
current score: 12
current score: 15
---end---
dice rolls: [3, 6, 3, 3, 5]
final score 15

A: i add a new answer based on the comments to the last answer.
it appears that the OP requires this:

when a 2 or 5 is rolled, the dice is removed from the game and the
other dice continue to be rolled until there are no dice left.

We can reduce the dice list with a list comprehension.
This keeps playing the game until there are no dice left.
Here is the code:
import random

score = 0
games_played = 0
number_rolls = 5

while True:
    games_played += 1
    if games_played > 100:
        print('more than 100 games played: you won !!!')
        break

    # user input:
    play_game = input("Enter r to roll the dice or q to quit: ")
    if play_game == 'q':
        break

    dice = [random.randint(1,6) for i in range(number_rolls)]
    print('dice rolled:', dice)
    dice = [d for d in dice if d in [1,3,4,6]]  # remove 2 & 5
    number_rolls = len(dice)

    if len(dice) == 0:
        break

    for d in dice:
        score = score + d
        print('current score:', score)

print('---end---')
print('games played:', games_played)
print('final score', score)

example result:
Enter r to roll the dice or q to quit: r
dice rolled: [6, 6, 6, 3, 2]
current score: 6
current score: 12
current score: 18
current score: 21
Enter r to roll the dice or q to quit: r
dice rolled: [3, 3, 4, 5]
current score: 24
current score: 27
current score: 31
Enter r to roll the dice or q to quit: r
dice rolled: [6, 5, 4]
current score: 37
current score: 41
Enter r to roll the dice or q to quit: r
dice rolled: [5, 5]
---end---
games played: 4
final score 41


text:
Q: Subgroups of the integers mod n I have the following 2 questions:

*

*What are the subgroups of $\mathbb{Z}/6\mathbb{Z}$?

*Why are $\{[0]\}$ and $\mathbb{Z}/7\mathbb{Z}$ the only subgroups of $\mathbb{Z}/7\mathbb{Z}$?
For 1, I'm not sure whether the answer is $\{[0]\}$, $\mathbb{Z}/2\mathbb{Z}$, $\mathbb{Z}/3\mathbb{Z}$, and $\mathbb{Z}/6\mathbb{Z}$ (aren't $\{[0]\}$ and $\mathbb{Z}/6\mathbb{Z}$ the same?), or if it's all $\{[0],[1],[2],[3],[4],[5]\}$. Could someone provide some clarity on this? I'm not sure I even know what these mean.
For 2, I'm thinking because 7 is prime, its only divisors are 1 and itself, 7, so its only subgroups are the groups that divide it. If this is the case, then for question 1, it would make sense that my first guess was right, but I feel like I've seen $\{[0],[1],[2],[3],[4],[5]\}$ as the subgroups for the integers mod 6 before.

A: It seems you misunderstood the concept of subgroups. Therefore, you should definitely  check the definition again. But as a short input for you to think about:
1: $\{[0]\}$ is a subgroup of $\mathbb{Z}/6\mathbb{Z}$. Why? If you add $[0]+[0]$ you get $[0]$. That means that this set is closed under addition, you have a neutral element and an inverse for every element because you only have that one element which satisfies the conditions for a subgroup. Now check the same conditions for every other set. For example: $\{[0],[2],[4]\}$ or $\{[0],[1],[3],[5]\}$. (Hint: One of them is the other is not a subgroup)
2: You already have the right intuition. However the phrase

because 7 is prime, its only divisors are 1 and itself, 7, so its only subgroups are the groups that divide it

seems a bit odd. A subgroup cannot really divide any number. A subgroup is a subset of another group with an operation. The elements inside that subgroup however can. And that is the answer you are looking for. When talking about $\mathbb{Z}/n\mathbb{Z}$ the subgroups are those sets whose elements are every multiple of those which divide $n$. In the case of $7$ that is $\{[7]\}=\{[0]\}$ and $\{[0],[1],[2],[3],[4],[5],[6]\}$.


text:
Q: Describe the algorithm of currency conversion CurrencyConversion that offers the user the choice of converting US Dollars into British Pounds or the other way around. (You may assume that 1 US Dollar = 1.64 Pounds.)
// Import scanner
import java.util.Scanner;

public class MoneyConversion {

    public static void main (String[] args) {

        // Declare variable
        final double RATE  = 1.64;

        // Declare currency
        double dollar;
        double Pounds;

        // Call scanner from keyBoard
        Scanner fromKeyboard = new Scanner(System.in);

        // Ask user to enter the amount of pounds
        System.out.print("Please write number of pounds");

        // Read the value into variable
        Pounds = fromKeyboard.nextDouble();

        // Write the method for currency conversion
        dollar = Pounds * RATE;

        System.out.println("The number of dollars is "  +  dollar);

    } // End of main

} // End currency conversion

A: Make different classes for different currency conversions as follows:
public static void main(String[] args) {
        Scanner fromKeyboard = new Scanner(System.in);
        System.out.print("Please write number of pounds");
        System.out.println("The number of dollar is "  +  convertToDollar(fromKeyboard.nextDouble()));
    }

public static double convertToDollar(double pound){
        double rate  = 1.64;
        double Pounds;
        return( pound * rate);
    }


text:
Q: MPMoviePlayerViewController Support landscape iOS 4.3 to 6.1 I have one query regarding orientation and play video,
My application support portrait mode but when i start any video it will run only landscape mode then after when video have completed it automatically come portrait mode.
Below of the code I'm using
**MyMovieViewController.h**

#import <MediaPlayer/MediaPlayer.h>

@interface MyMovieViewController : MPMoviePlayerViewController

@end

**MyMovieViewController.m**

@implementation MyMovieViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{

    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (BOOL)shouldAutorotate
{
    return NO;
}

-(NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskLandscapeRight | UIInterfaceOrientationMaskLandscapeLeft;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationLandscapeRight;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationLandscapeRight || interfaceOrientation == UIInterfaceOrientationLandscapeLeft);
}

@end

But above of the code only working in iPhone 4.3 simulator and My application support 4.3 to 6.1.
So please can you help me out.

A: -(NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskLandscapeRight | UIInterfaceOrientationMaskLandscapeLeft;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationLandscapeRight;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationLandscapeRight || interfaceOrientation == UIInterfaceOrientationLandscapeLeft);
}

These few methods only return YES when your device is in landscape. Then it wont support portrait mode.


text:
Q: How to make dynamic slideshow using php, mysql, css and html? I wanna make dynamic slideshow with css and HTML. Image will be took by id from tb_image.
id int
image_name varchar (100)
image_path (100)

How to make dynamic slideshow using php, mysql, css and html?
or Can get image by id?
include "connnection.php";
$result = mysql_query("select * from slider");
?>

    <?php
        $i=1;
    while($row = mysql_fetch_array($result)){
    ?>

                    <img src="../img/<?php echo $i;?>.jpg" alt="" width="640" border="320"/> //I tried use this codes but it's error

                        Slide 2

                        <img src="img/<?php echo $_GET['id']=2;?>.jpg" alt="" width="640" border="320"/>

                        Slide 3

                        Slide 4

                        Slide 5

            <?php } ?>

A: Not knowing exactly what you get back from your query, here's a guess:
Replace any of your s with
<img src="../img/<?php echo $row['id']?>.jpg" alt="" width="640" border="320"/>

To "debug" your data, you can replace your while loop with
while($row = mysql_fetch_array($result)){
  print_r($row);
}

This will print out any data found in each row.
You might also want to replace the deprecated mysql_* functions with mysqli or PDO.


text:
Q: How to validate regex using the bolt compiler I am trying to validate a field that will receive a URL. I need to validate it using an appropriate regex, but what I got from the Firebase documentation itself is not working. The compiler bolt neither compiles, causing the error:
bolt:37:3: Invalid property or method: 'validate() { this.test((/^(ht|f)tp(s?):\\/\\/[0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*((0-9)*)*(\\/?)([a-zA-Z0-9\\-\\.\\?\\'.
bolt:37:3: Invalid property or method: '\\'\\/\\\\+&=%\\$#_]*)?$/) '.
bolt: Fatal errors: 2

My code:

type Category {
  categoryName: String,
  isAvailable: Boolean,
  createdAt: Number,
  photoUrl: LinkURL,
  subcategories: Object | Null
}

type LinkURL extends String {
  validate() { this.test((/^(ht|f)tp(s?):\\/\\/[0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*((0-9)*)*(\\/?)([a-zA-Z0-9\\-\\.\\?\\,\\'\\/\\\\+&=%\\$#_]*)?$/) }
}

A: I believe you have an extra "(" at the start of the regex
try this
type LinkURL extends String {
  validate() { this.test(/^(ht|f)tp(s?):\/\/[0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*((0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&=%\$#_]*)?$/) }
}


text:
Q: Get Google Sheets Last Edit date using Sheets API v4 (Java) I'm using the Google Sheets API v4 in Android.
https://developers.google.com/sheets/api/quickstart/android
I need to know when the last modification to the sheet was made (including by user); I need this guy:

I'd like to do something like this:
    Spreadsheet spreadsheet = sheetsService.spreadsheets().get(spreadsheetId).setIncludeGridData(true).execute();
    Date date = spreadsheet.getProperties().getLastEditDate();

But, of course, no such getLastEditDate() property method exists. Is there a parameter or another API method to call to get this data?
Even better would be to get the modified date for each cell... but I'd settle for the date of the entire spreadsheet or sheet.

A: It looks like this cannot be done with Sheets API v4.
However...it does look like it can be done with the compatible Google Drive API v3.
Note: the best part about this solution was that I could use the same method of authentication and credential gathering for both APIs. E.g., once I had the code for getting the credentials, I could use it for both API's interchangeably and consecutively.
Here's what I did:
Added this to my build.gradle (shown below my Sheets API declaration)
compile('com.google.apis:google-api-services-sheets:v4-rev468-1.22.0') {
    exclude group: 'org.apache.httpcomponents'
}
compile('com.google.apis:google-api-services-drive:v3-rev69-1.22.0') {
    exclude group: 'org.apache.httpcomponents'
}

I was already using the EasyPermissions method for getting account and credentials. Great example here.
Then...
import com.google.api.services.drive.Drive;

...
protected Drive driveService = new Drive.Builder(transport, jsonFactory, credential)
            .setApplicationName("My Application Name")
            .build();

... async:
private DateTime getSheetInformation() throws IOException {

    String spreadsheetId = settings.getSpreadsheetId();
    Drive.Files.Get fileRequest = driveService.files().get(spreadsheetId).setFields("id, modifiedTime");
    File file = fileRequest.execute();
    if (file != null) {
        return file.getModifiedTime();
    }
    return null;
}

A: This is not available in the Sheets API, but you may be able to use the Drive API's files.get method, which includes a 'modifiedTime' in the response.  (Note that by default it will not include the modified time, you have to explicitly ask for it in the 'fields' parameter.)

A: The sheets api v3 will be deprecated in March 2020, when that happens, your best bet is to use the drive API.
https://developers.google.com/drive/api/v3/reference/files/list
you can pass


text:
Q: No highlight when clicking rapidly on an element Is there a way to prevent from text in other elements to not get highlighted when you click rapidly?
I am creating a game in HTML5 canvas which involvs clicking fast and I think it's really unprofessional and annoying if text from other elements start to get highlighted. How could I prevent this?

A: CSS3 selection should help you out,
::selection {
  color: #fff;
}

More here.


text:
Q: Quick way to access first element in Numpy array with arbitrary number of dimensions? I have a function that I want to have quickly access the first (aka zeroth) element of a given Numpy array, which itself might have any number of dimensions.  What's the quickest way to do that?
I'm currently using the following:
a.reshape(-1)[0]

This reshapes the perhaps-multi-dimensionsal array into a 1D array and grabs the zeroth element, which is short, sweet and often fast.  However, I think this would work poorly with some arrays, e.g., an array that is a transposed view of a large array, as I worry this would end up needing to create a copy rather than just another view of the  original array, in order to get everything in the right order.  (Is that right?  Or am I worrying needlessly?)  Regardless, it feels like this is doing more work than what I really need, so I imagine some of you may know a generally faster way of doing this?
Other options I've considered are creating an iterator over the whole array and drawing just one element from it, or creating a vector of zeroes containing one zero for each dimension and using that to fancy-index into the array.  But neither of these seems all that great either.

A: a.flat[0]

This should be pretty fast and never require a copy. (Note that a.flat is an instance of numpy.flatiter, not an array, which is why this operation can be done without a copy.)

A: You can use a.item(0); see the documentation at numpy.ndarray.item.
A possible disadvantage of this approach is that the return value is a Python data type, not a numpy object.  For example, if a has data type numpy.uint8, a.item(0) will be a Python integer.  If that is a problem, a.flat[0] is better--see @user2357112's answer.

A: ## y -- numpy array of shape (1, Ty)

if you want to get the first element:
use y.shape[0]
if you want to get the second element:
use   y.shape[1]
Source:
https://docs.scipy.org/doc/numpy/reference/generated/numpy.take.html
You can also use the take for more complicated extraction (to get few elements):

numpy.take(a, indices, axis=None, out=None, mode='raise')[source] Take
  elements from an array along an axis.

A: np.hsplit(x, 2)[0]

Source: https://numpy.org/doc/stable/reference/generated/numpy.dsplit.html
Source:
https://numpy.org/doc/stable/reference/generated/numpy.hsplit.html


text:
Q: Receiving an exception in overloaded operator >> section So I've overloaded an operator ">>" for my class MyString. It was supposed to read information from text file to a custom-made string, however I'm getting an exception when I'm trying to fill string char by char. Text.txt contains simply "xyz"
Main.cpp:
#include "MyString.h"
#include <fstream>
#include <iostream>
//TO-DO 1 CharArr for all
int main() {

    MyString NewString;
    ifstream In("Text.txt");
    In >> NewString;

    cout << NewString << endl;
    system("pause");
    return 0;
}

Constructors:
MyString::MyString() {
    StringLength = 0;
    Pointer = nullptr;
}

MyString::MyString(const char* String) {
    for (int i = 0; String[i]; i++)
    StringLength++;
    Pointer = new char[StringLength + 1];
    char *Source = (char *)String;
    char *Destination = (char *)Pointer;
    for (int i = 0; i < StringLength + 1; i++)
    Destination[i] = Source[i];
}

Operator:
istream &operator>>(istream &In, MyString &String) {
    int FileStringLength = 0;
    char Character;
    if (String.Pointer != nullptr)
        delete[] String.Pointer;
    while (In.get(Character) && Character != '\n')
        FileStringLength++;
    if (FileStringLength < 1000 && FileStringLength != 0) {
        String.StringLength = FileStringLength;
        In.clear(), In.seekg(0, ios::beg);
        for (int i = 0; In.get(Character) && Character != '\n'; i++)
                String.Pointer[i] = Character; // I get an exception here
    }
    else if (!FileStringLength) {
        cout << "File is empty." << endl;
    }
    else {
        cout << "File contains too many characters." << endl;
    }

    return In;
};

A: if (String.Pointer != nullptr)
    delete[] String.Pointer;

freed the storage that
String.Pointer[i] = Character; // I get an exception here

was going to use.
Solution:
Don't delete[] the storage. Instead write over it until the storage is full, then allocate a new, larger buffer for storage, copy the old buffer into the new buffer, and then free the old buffer.


text:
Q: Jetpack Compose: Nested weight in custom component Say that I have a button that expands when tapped the first time to reveal text, and performs an action on the second tap--thus acting as a sort of confirmation before performing the action.
@Compose
fun ExpandingConfirmButton(onConfirm: () -> Unit) {
    // expanded state of the button
    val (expanded, setExpanded) = remember { mutableStateOf(false) }
    // animating weight. make the button larger when it is tapped once
    val weight = animate(if (expanded) 10F else 2F)

    Button(onClick = {
        // only fire the action after two taps
        if(expanded) {
            onConfirm()
        }
        setExpanded(!expanded)
    }) {
        Icon(Icons.Dfault.Delete)
        // only show the text if the button has already been clicked once,
        //  otherwise just show the icon
        if(expanded) {
            Text(text = "Delete", softWrap = false)
        }
    }
}

And I would use that button like so:
@Composable
fun PersonList(people: List<Person>) {
    // some database service exposed via an ambient
    val dataService = DataService.current

    LazyColumnFor(items = people) {
        Row() {
            Text(text = it.firstName, modifier = Modifier.weight(10F))
            // on the first tap, the button should take up half of the row
            ExpandingConfirmButton(onConfirm = { dataService.deletePerson(it) })
        }
    }
}

This all seems pretty straight-forward. Indeed, before I had split the ExpandingConfirmButton into it's own component and instead had the Button() it wraps directly in my PersonList component, it worked flawlessly.
However, it seems that the Row doesn't quite know what to do with the button when the weight changes when it is inside it's own component. The text inside the button displays, but the size does not change. Does this have to do with the Row's RowScope not getting utilized by the Modifier on the Button component inside ExpandingConfirmButton? If so, how do I go about using it?

A: What I ended up doing is basically just using the .animateContentSize() modifier.
@Compose
fun ExpandingConfirmButton(onConfirm: () -> Unit) {
    // expanded state of the button
    val (expanded, setExpanded) = remember { mutableStateOf(false) }

    Button(
        modifier = Modifier.animateContentSize(), // do this
        onClick = {
        // only fire the action after two taps
        if(expanded) {
            onConfirm()
        }
        setExpanded(!expanded)
    }) {
        Icon(Icons.Default.Delete)
        // only show the text if the button has already been clicked once,
        //  otherwise just show the icon
        if(expanded) {
            Text(text = "Delete", softWrap = false)
        }
    }
}

It really is just that easy. No messing with manual widths, weights, or anything like that.


text:
Q: While creating div in HTML it is returning Undefined Below is my HTML Code, the alert Message returns Undefined i.e the "div_" is not created.
Please help to resolve this:
var piediv = document.createElement('div');
piediv.id = "div_" ;
alert($('#div_').attr('id'));

A: You need to append the div as body's child first.

var piediv = document.createElement('div');
piediv.id = "div_" ;
document.body.appendChild(piediv);
alert($('#div_').attr('id'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

A: You have to set attribute of div  try this 100% worked .
1st Method :

var piediv = document.createElement('div');
        piediv.setAttribute("id", "div_");
        $("body").append(piediv);
        alert($('#div_').attr('id'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

2nd Method as suggested by @mplungjan :

var pieDiv = $("<div/>",{"id":"div_"}).appendTo("body");

           alert($('#div_').attr('id'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


text:
Q: How do I get the computertemp applet working? This is a little different than the common Natty temperature applet question. I've given Unity a shot and have reverted back to Ubuntu Classic. The one thing that is still not working is the temperature panel indicator (on 2 different laptops). It reports 'No Thermal Monitor Support' and shows a big red 'X'. The temperature sensors are working as GKrellM can still report temperature properly. Does anyone have a solution?
The specific applet is the 'computertemp' applet. After Jorge asked for more details, I tried the other one, the 'sensors-applet', and it actually works correctly.

A: Your first port of call should be the application help page


text:
Q: swagger: file path in path parameter Here is my api requirement
GET http://localhost:8080/filePath/{path}

For example:
curl http://localhost:8080/filePath/home/users/user/one.txt

Here is yaml config:
parameters:
        - name: path
          in: path
          description: Todo description
          type: string
          required: true

But I'm getting 404 error. How can I use file path in path parameter?

A: OpenAPI 2.0 (Swagger 2.0), 3.0, and 3.1 do not allow you to use slashes in path parameters, so you can't do that. There's an open feature request for this:
https://github.com/OAI/OpenAPI-Specification/issues/892


text:
Q: Can I autoselect a drop down menu? I am taking text from a table via an autocomplete to pre-load information that was set to the table the last time the user was in it.  I can get the information without any problem.  Here is the jquery/javascript code that I am having the hard time with:
    $('#type').val(ui.item.type);
    var t = $("#type").val();
    $('#types').text(t);

Here is the HTML code for the drop down menu:
    *Tournament Type
        <select name="type" id="type">
        <option value="">Please select...</option><?
                                                    while ($type = mysql_fetch_array($types)) {
        $TID = $type['ID'];
        $name = htmlspecialchars($type['Type']);
        echo("<option value = '$name'>$name</option>\n");
                                                    }?>
        </select>

What I am trying to accomplish here is to make the displayed item on my drop down menu equal to what was previously selected while still maintaining the functionality of the drop down menu in case the information needs to be changed.  I have not been able to get this to work thus far.  Can I do this or is there another method I should be using to accomplish this?

A: Did you try
echo("<option selected value = '$name'>$name</option>\n")

on the one you want
or use jQuery after:
$("#type").val("someval")


text:
Q: How to find all ring structures over $C_2\times C_2$?
$C_2$ denotes the cyclic group of order 2. How to find all ring structures over $C_2\times C_2$?

The question is equivalent to give a full list of  all essentially different bilinear 2-operations over the abelian group $C_2\times C_2$ that is associative. I don't require those ring structures being unital, and two operations $\cdot$ and $\circ$ are said to be essentially different if there is no additive automorphism $f:C_2\times C_2\to C_2\times C_2$ such that $\forall x,y\in C_2\times C_2,\ x\cdot y=f(x)\circ f(y)$.
By the way, I've found that there are exactly three unital ring structures: $\mathbb F_4,\ \mathbb F_2\times\mathbb F_2$ and $\mathbb F_2\left[x\right]/\left(x^2\right)$.
It will help a lot if someone can tell me if there is any systematic method to determine such a list.

A: Hint: For singly generated ring structures $C_2\times C_2$, express them as a (non-unital) subrings of quotients of $\mathbb F_2[X]$. And for non-singly generated ring, express them as  (not necessarily unital) subrings of $M_2(\mathbb F_2)$.


text:
Q: Convert a single hex character to its byte value in java I have a single hexadecimal character, say
char c = 'A';

What's the proper way of converting that to its integer value
int value =??;
assert(a == 10);

Doesn't matter really for now if a is an int or a byte.

A: int value;
try {
    value = Integer.parseInt(Character.toString(c), 16);
}
catch (NumberFormatException e) {
    throw new IllegalArgumentException("Not a hex char");
}

A: Found it myself though.
int i = Character.digit('A',16);

A: i don't see why you should have to convert to string... in fact this is what parseInt uses:
public static int digit(char ch, int radix)
int hv = Character.digit(c,16);
if(hv<0)
    //do something else because it's not hex then.

A: (byte)Integer.parseInt("a", 16)

A: Take a look at Commons Codec and in particular the Hex class.
http://commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Hex.html
You should be able to convert a hex char array or string to an int value using the toDigit() method:
protected static int toDigit(char ch, int index)

You'll need to catch DecoderException though.
try {
    int i = Hex.toDigit('C');
} catch (DecoderException de) {
    log.debug("Decoder exception ", de);
}

There's also methods there to convert a char[] or String to the corresponding byte array as well.


text:
Q: JQuery $.post doesn't like datatype parameter I am trying to make a JQuery call to a PHP script that is returning a JSON multi-row data set. When I use $.post, the call doesn't get made:
$.post("my_query.php", {search_filter: "the search text"}, function(data, status) {
           alert(data);
},"json");

When I leave the fourth parameter out, it works, but it returns everything in one row.
Using $.ajax works, so it's not a problem on the PHP side:
$.ajax({
    url : "my_query.php",
    type : "POST",
    data: {search_filter: "the search text"},
    dataType: "json",
    success: function(data, status) {
        alert(data);
    }
});

This has only been tried on the latest version of Firefox.
Is there some bug with $.post, possibly limited to certain browsers?


text:
Q: Unable to wait for a response that just hangs I am runing a node script that processes an array of string with a package called string-strip-html. Some urls have some content that the package is unable to process it does not error out it just gets stucked and the CPU goes to 100%.
// Long sting of html that the package struggles to process
const string = `a long string of html`

try {
 // The package gets stuck here
 const clean = stripHtml(string).result
} catch(err) {
 // This never runs
 console.log(err)
}

When this happens I want to be able to skip it after a few seconds, should I use a setTimeout of a setInterval?


text:
Q: Scala modify value of nested column I need to conditionally modify a value of a nested field in a Dataframe (or create a new field with the nested values).
I would like to do it without  having to use UDF, but I really would want to avoid RDD/map since the production tables can have many hundred millions of records and map in that condition dosen't ring as efficient/fast to me.
Bellow is the test case:

case class teste(var testID: Int  = 0, var testDesc: String = "", var testValue: String = "")

val DFMain = Seq( ("A",teste(1, "AAA", "10")),("B",teste(2, "BBB", "20")),("C",teste(3, "CCC", "30"))).toDF("F1","F2")
val DFNewData = Seq( ("A",teste(1, "AAA", "40")),("B",teste(2, "BBB", "50")),("C",teste(3, "CCC", "60"))).toDF("F1","F2")

val DFJoined = DFMain.join(DFNewData,DFMain("F2.testID")===DFNewData("F2.testID"),"left").
        select(DFMain("F1"), DFMain("F2"), DFNewData("F2.testValue").as("NewValue")).
        withColumn("F2.testValue",$"NewValue")

DFJoined.show()

This will add a new column, but I need that F2.testValue to be equal to the value of NewValue inside the Struct when its above 50.
Original Data:
+---+------------+
| F1|          F2|
+---+------------+
|  A|[1, AAA, 10]|
|  B|[2, BBB, 20]|
|  C|[3, CCC, 30]|
+---+------------+

Desired Result:
+---+------------+
| F1|          F2|
+---+------------+
|  A|[1, AAA, 10]|
|  B|[2, BBB, 50]|
|  C|[3, CCC, 60]|
+---+------------+

A: Could you please try this.
case class teste(var testID: Int  = 0, var testDesc: String = "", var testValue: String = "")
val DFMain = Seq( ("A",teste(1, "AAA", "10")),("B",teste(2, "BBB", "20")),("C",teste(3, "CCC", "30"))).toDF("F1","F2")
DFMain.show(false)

+---+------------+
|F1 |F2          |
+---+------------+
|A  |[1, AAA, 10]|
|B  |[2, BBB, 20]|
|C  |[3, CCC, 30]|
+---+------------+

val DFNewData = Seq( ("A",teste(1, "AAA", "40")),("B",teste(2, "BBB", "50")),("C",teste(3, "CCC", "60"))).toDF("F1","F2")

val DFJoined = DFMain.join(DFNewData,DFMain("F2.testID")===DFNewData("F2.testID"),"left").
        select(DFMain("F1"), DFMain("F2"), DFNewData("F2.testValue").as("NewValue"))
  .withColumn("F2_testValue",$"NewValue")

DFJoined.show

+---+------------+--------+------------+
| F1|          F2|NewValue|F2_testValue|
+---+------------+--------+------------+
|  A|[1, AAA, 10]|      40|          40|
|  B|[2, BBB, 20]|      50|          50|
|  C|[3, CCC, 30]|      60|          60|
+---+------------+--------+------------+

DFJoined.printSchema

root
 |-- F1: string (nullable = true)
 |-- F2: struct (nullable = true)
 |    |-- testID: integer (nullable = false)
 |    |-- testDesc: string (nullable = true)
 |    |-- testValue: string (nullable = true)
 |-- NewValue: string (nullable = true)
 |-- F2_testValue: string (nullable = true)

DFJoined.withColumn("f2_new", expr(" case when F2_testValue>=50 then concat_ws('|',F2.testID,F2.testDesc,F2_testValue) else concat_ws('|',F2.testID,F2.testDesc,F2.testValue) end "))
.withColumn("f2_new3",struct(split($"f2_new","[|]")(0),split($"f2_new","[|]")(1),split($"f2_new","[|]")(2) ) )
.show(false)

+---+------------+--------+------------+--------+------------+
|F1 |F2          |NewValue|F2_testValue|f2_new  |f2_new3     |
+---+------------+--------+------------+--------+------------+
|A  |[1, AAA, 10]|40      |40          |1|AAA|10|[1, AAA, 10]|
|B  |[2, BBB, 20]|50      |50          |2|BBB|50|[2, BBB, 50]|
|C  |[3, CCC, 30]|60      |60          |3|CCC|60|[3, CCC, 60]|
+---+------------+--------+------------+--------+------------+

f2_new3 is the desired output.
The reason for the workaround is the below one is not working.
DFJoined.withColumn("f2_new", expr(" case when F2_testValue>=50 then struct(F2.testID,F2.testDesc,F2_testValue) else struct(F2.testID,F2.testDesc,F2.testValue) end ")).show()

A: In addition to stack0114106 answer, I also found this solution for the problem, they are more or less alike:

val DFFinal = DFJoined.selectExpr("""
        named_struct(
          'F1', F1,
          'F2', named_struct(
            'testID', F2.testID,
            'testDesc', F2.testDesc,
            'testValue', case when NewValue>=50 then NewValue else F2.testValue end
            )
        ) as named_struct
      """).select($"named_struct.F1", $"named_struct.F2")


text:
Q: "No module named Django" Problem on MacOS Mojave I'm using Python3.7.1 and Django 2.0 has been installed successfully through pip3 command on Terminal on MacOS Mojave. Pip list indicates that there is actually an installed Django on my computer.
However, when I run the code import django, an error is raised: ModuleNotFoundError: No module named django. I've tried reinstall django through pip but everything stays the same. Other packages like matplotlib, xlrd and etc. installed by pip3 are all imported successfully.
This is really confusing me.


text:
Q: codeignigter use rest to pass data to external site OK in plain PHP I use the following to pass data to a GET
file_get_contents('https://ws.mysite.com/some.svc/here?userID=' . $session_id . '&score=' . $percentilescore . '&assessmentID=' . $testID . '&assessmentTitle=some');

I now want to apply this same piece of code to my CI project.
This Is how I have tried.
private function getResults()
    {

        $score = $this->actions->getSentEmailCount();
        $percentilescore = $percentile = $this->actions->getPercentile($score);
        $testID = '134';
        $percentile = $this->actions->getPercentile($score);
        $time = $this->input->get('time');
        $timemath = 60000;
        $timeinmseconds =  $time * $timemath;

        $adddata = array(
            'uniID' => '5',
            'testName' => 'some',
            'testID' => $testID,
            'total' => '10',
            'correct' => $score = $this->actions->getScore(),
            'percent' => $score = $this->actions->getScore(),
            'dateTaken' => date('Y-m-d H:i:s'),
            'timeSpent' => $timeinmseconds,
            'userID' => $session_id,
        );

        $this->actions->add_record($adddata);
        return $this->load->view('client/results', $data);

        file_get_contents('https://ws.mysite.com/123.svc/some?userID=' . $session_id . '&score=' . $percentilescore . '&assessmentID=' . $testID . '&assessmentTitle=some');

    }

It is not posting the data any idea why and how I should do it in CI ?

A: return should be the last statement in the function because it's immediately ends execution of the current function. Just put file_get_contents before return:
file_get_contents('https://ws.mysite.com/123.svc/some?userID=' . $session_id . '&score=' . $percentilescore . '&assessmentID=' . $testID . '&assessmentTitle=some');

$this->actions->add_record($adddata);
return $this->load->view('client/results', $data);


text:
Q: Standard Deviation After Subtracting One Mean From Another I've got two sets of data from some fluorescent cells.
The first set is when the cells don't have their fluorescence switched on, but they are still faintly glowing.
The second set is when they do have their fluorescence switched on.
I ran each of the two experiments three times, so n=3, and I therefore have a mean for each dataset and a SD.
I need to subtract the non-switched on set from the switched on set in order to determine the amount of fluorescence that arises as a result of being switched on.
How do I then calculate the SD of the final value?
I know that for discrete random variables,
$$ E[X+Y] = E[X] + E[Y] $$
So I assume that holds true for subtraction as well, but I can't find the rules for continuous random variables, as these are.
Example data for one data point:
         ON            OFF
MEAN:  33956.6666    3835.66667
SD:    457.47301     38.0905

A: Basic properties of expectation and variance give us:
$$E[aX+bY] = aE[X]+bE[Y]$$
$$\text{Var}[aX+bY] = a^2\text{Var}[X]+b^2\text{Var}[Y]+2ab\text{Cov}[X,Y]$$

a) With $a=1,\,b=-1$ and assuming independence, we have
$$E[X-Y] = E[X]-E[Y]$$
$$\text{Var}[X-Y] = \text{Var}[X]+\text{Var}[Y]$$
Taking square roots yields the result for the standard deviation.
b) With $a=1,\,b=-1$ in the presence of dependence, we have
$$E[X-Y] = E[X]-E[Y]$$
$$\text{Var}[X-Y] = \text{Var}[X]+\text{Var}[Y]-2 \text{Cov}[X,Y]$$
It's not clear to me how the dependence is operating (your description doesn't make it clear which observations are correlated).
If two sets of means are dependent (as "pairs of means"), you could treat the means as paired data.
(Outside of that you might need to look at random effects/mixed effects models.)


text:
Q: Mongoose embedded documents / Object { size: {} } has no method cast I like to Embedded a document in another document.
here my first mongoose document witch include the second one "grille":
chp_bat.js
var mongoose = require('mongoose')
  , Schema = mongoose.Schema
  , ObjectId = Schema.ObjectId
  , Grille = require('../models/grille');

function validatePresenceOf(value) {
  return value && value.length;
}

var Chp_bat = new Schema({
  name : { type: String, validate: [validatePresenceOf, 'a chp_bat is required'] },
  avatar : { type: String },
  description : { type: String },
  grille : [Grille],
  created_at : Date,
  updated_at : Date
});
var Chp_bat = mongoose.model('Chp_bat', Chp_bat);
module.exports = mongoose.model('Chp_bat', Chp_bat);

My second document: grille.js
mongoose = require('mongoose');
Schema = mongoose.Schema;
ObjectId = Schema.ObjectId;

function validatePresenceOf(value) {
  return value && value.length;
}

var Grille = new Schema({
  name : { type: String, validate: [validatePresenceOf, 'a grille is required'] },
  avatar : { type: String },
  description : { type: String },
  size : { x: Number, y: Number },
  created_at : Date,
  updated_at : Date
});
var Grille = mongoose.model('Grille', Grille);
module.exports = mongoose.model('Grille', Grille);

my routes:
var User = require('../../models/user')
  , Chp_bat = require('../../models/chp_bat')
  , Grille = require('../../models/grille');

module.exports = function (app){

/*
 * GET New chp_bat.
 */
  app.get('/chp_bat_new', ensureAuthenticated, function (req, res){
      Grille.find({}, function (err, docs) {
        res.render('chp_bat/new', {
          docs: docs,
      user : req.user,
      title : ' Que voulez vous créer Maitre Du Jeu'
        });
      });
    });

/*
 * POST New chp_bat.
 */
  app.post('/maitre-chp_bat-new', ensureAuthenticated, function (req, res){
    var chp_bat = new Chp_bat();
    chp_bat.name = req.body.name;
    chp_bat.avatar = req.body.avatar;
    chp_bat.description = req.body.description;
    chp_bat.grille.push(req.body.grille);
    chp_bat.created_at = new Date();
    chp_bat.save(function (err) {
      if (!err) {
        res.redirect('/maitre-chp_bat-new');
        console.log(req.body);
      }
      else {
        res.redirect('/maitre-chp_bat-new');
      }
    });
    });

};

I obtain this error: Object { size: {} } has no method 'cast'
I thought I was good, making same things like mongoose docs and I dont understand what I didn't do well.
====
So, like always when you post the question the answer come.
I write it for other people:
When you write the doc embedded include the _id like this:
grille: [Grille._id],

So easy.

A: for chaining your docs together consider doing something like this:
app.js
var express = require('express'),
    app = express(),
    require('./routes')(app);
}
console.log('Listening on port 8888');

routes/index.js
module.exports = function(app){
    var Users = require('../controllers/users')(app);
    app.get('/logout',Users.profile);
}

controllers/users.js
module.exports = function(app){
    var User = require('../models/users')(app),

    return {
        profile: function (req, res) {
            User.findOne(
                {'email' : 'your@email.com'},
                '_id name email modifiedOn',
                function(err, user) {
                    if (!err) {
                        //do something with user
                    } else {
                        res.send({"error": "some error happened"});
                    }
                }
            );
        },
        login: function(req,res){
            //login to login here.  you know like req.body.email and req.body.password etc.
        }
    }
}

models/users.js
module.exports = function(app){
var db = require('../lib/db')(app);

var userSchema = new db.Schema({
    first_name: {
        type: String,
        required: true
    },
    last_name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        unique: true,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    createdOn: {
        type: Date,
        default: Date.now
    },
    modifiedOn: {
        type: Date,
        default: Date.now
    },
    lastLogin: {
        type: Date,
        default: Date.now
    }
});
db.model( 'User', userSchema);

return db.model('User');
}

lib/db.js
module.exports = function(app){
    var mongoose = require('mongoose');
    var uri = 'mongodb://'+app.get('db_host')+':'+app.get('db_port')+'/'+app.get('db_database');
    var options = {}
    mongoose.connect(uri,options);

    mongoose.connection.on('connected', console.log.bind(console, 'Mongoose connected to ' + uri));
    mongoose.connection.on('error',console.error.bind(console, 'connection error:'));
    mongoose.connection.on('disconnected', console.log.bind('Mongoose disconnected'));

    process.on('SIGINT', function() {
        mongoose.connection.close(function () {
            console.log('Mongoose disconnected through app termination');
            process.exit(0);
        });
    });
    return mongoose;
}

Note that in this example I am using config items for db_host, port, and database.  Personally this setup works great for me.  Comes in handy when your app gets larger too.

A: you are getting this error because of
chp_bat.grille.push(req.body.grille);


text:
Q: Does dlang install some signal handlers by default I have infinite loop program written in D:
$ cat dprog.d
import std.stdio;
import core.thread;

void main()
{
  while(1){
    Thread.sleep(dur!("seconds")(1));
  };
}

When I build and run this program on Linux (Ubuntu), kill -10 $PID has no effect on it. And indeed, it does catch a bunch of signals by default:
$ cat /proc/$PID/status | grep SigCgt
SigCgt: 0000000180000a00

Signal 10 is a SIGUSR1 signal, for which the default action is process termination (consult man 7 signal).
Equivalent program, written in C terminates on kill -10 $PID and its cat /proc/$PID/status | grep SigCgt is SigCgt:    0000000000000000.
Equivalent program, written in Rust also terminates on kill -10 $PID, however its cat /proc/$PID/status | grep SigCgt is SigCgt:   0000000180000440.
My question is: does D (Rust) compiler register default signal handlers? If yes, why? Also, is this documented somewhere?

A: The docs for core.thread.thread_setGCSignals tell us that, on Posix systems, SIGUSR1 and SIGUSR2 are used for the runtime to control suspending and resuming threads for GC purposes.
This function allows you to change which signals are used, in case there are different signals you don't need.


text:
Q: How to implement Navigator.push action after loading file (using CircularProgressIndicator() during the process)? What is the "best practice" way to implement a background downloading of a file while displaying the CircularProgressIndicator() and using the  Navigator.pushNamedAndRemoveUntil afterwards on successful file loading?
This is a sample of my code:
class Downloader extends StatefulWidget {
  const Downloader({Key? key}) : super(key: key);

  @override
  DownloaderState createState() => DownloaderState();
}

class DownloaderState extends State<Downloader> {
  Future<Directory?>? _appDocumentsDirectory;
  bool _isDownloaded = false;

  @override
  void initState() {
    super.initState();
    _initDownloader();
  }

  _initDownloader() async {
    setState(() {
        _appDocumentsDirectory = getApplicationDocumentsDirectory();
      });
  }

  Future<void> _downloadJson(String localPath) async {
    if ( === WE CHECK FOR CREDENTIALS HERE === ) {
      FTPConnect ftpConnect = FTPConnect(
          BaseAPI.ftpServerAddress,
          port: BaseAPI.ftpServerPort,
          user: _login,
          pass: _passwd);
      try {
        String fileName = 'filename.json';
        String localFileName = localPath + "/filename.json";

        print(" localFileName: $localFileName");

        await ftpConnect.connect();
        await ftpConnect.changeDirectory('ftp');
        bool res = await ftpConnect.downloadFileWithRetry(
            fileName, File(localFileName));
        await ftpConnect.disconnect();

        print("is downloaded? $res");

      } catch (e) {

        print("=== ERROR ===\n${e.toString()}");

      }
      _isDownloaded = true;

    } else {
      _isDownloaded = false;
    }
  }

Widget _buildDirectory(
      BuildContext context, AsyncSnapshot<Directory?> snapshot) {
    Text text = const Text('');
    if (snapshot.connectionState == ConnectionState.done) {
      if (snapshot.hasError) {
        text = Text('Error: ${snapshot.error}');
      } else if (snapshot.hasData) {

        String _s = snapshot.data!.path + "/filename.json";
        String _z = "File downloaded";

        _downloadJson(snapshot.data!.path);    //////////////  <= downloading here

        if (!_isDownloaded) {
          _z = "Failed to download file";
        }
        text = Text('Path to a file: \n$_s\n\npath: \n${snapshot.data!.path}\n\nFile downloaded: $_isDownloaded');

      } else {
        text = const Text('path unavailable');
      }
    }
    return text;
  }

@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Loading data"),
        foregroundColor: Colors.black,
        backgroundColor: Colors.redAccent,
      ),
      body: Center(
        child: Column(
              children: <Widget>[
                FutureBuilder<Directory?>(
                  future: _appDocumentsDirectory,
                  builder: _buildDirectory,
/// I need to redirect to another page here
                ),
              ],
            ),
        ),
      );
  }
}

So my main problems are:

*

*How to properly 'catch' the moment when file is downloaded? I can only see in console (Android Studio) when "is downloaded? true" is printed but I fail to understand how to catch this moment and link some actions to it...

The workflow, as far as I understand, is like that:
1. initialize the `_appDocumentsDirectory`;
2. on initialization start the `FutureBuilder` logic:

 2.1 - checking if `_appDocumentsDirectory` has data and

 2.2 - calling the `_downloadJson`

*Can (or should) I wrap the logic inside the _downloadJson function in the FutureBuilder too?

*If I will resolve somehow first and second questions - how do you usually perform the required  Navigator.pushNamedAndRemoveUntil() when needed?

A: First to answer the following question,
How to display a CircularProgressIndicator while the file is downloading, you can simply introduce a variable isDownloading like below,
bool isDownloading = false;

And while downloading i.e.,
setState(() => isDownloading = true);
bool res = await ftpConnect.downloadFileWithRetry(
        fileName, File(localFileName));
setState(() => isDownloading = false);

and since setState once called will rebuild the body, in the body use something like this,
Scaffold(
  body: isDownloading ? CircularProgressIndicator() : ..[your code],
);

Next to get the local push notification you can simple use the flutter_local_notifications: ^9.5.3+1
This should definitely resolve the issue


text:
Q: Create valid json file that contains an array of json using json.dump mcve :
d1 = {"a":1}
d2 = {"b":2}
import json
with open('test2.json','w+') as file:
     for d in [d1,d2]:
             json.dump(d,file)

test2.json content :
{"a": 1}{"b": 2}
Desired Result :
[{"a": 1},{"b": 2}]
How can I achieve it?

A: d1 = {"a":1}
d2 = {"b":2}
import json

array = [json.dumps(d) for d in [d1,d2]]

Then write array to file

A: Create a list instead, and dump that list directly.
with open('test2.json','w+') as file:
     d = [d1, d2]
     json.dump(d,file)

A: try this
d1 = {"a":1}
d2 = {"b":2}
import json
tab = [d1, d2]
with open('test2.json','w+') as file:
    json.dump(tab ,file)

A: Use list and append both the dictionary into list and then write list into the file.
d1 = {"a":1}
d2 = {"b":2}
import json
with open('test2.json','w+') as file:
     for d in [d1,d2]:
             list1 = []
             list1.append(d1)
             list1.append(d2)
             json.dump(list1,file)

A: Try this
d1 = {"a":1}
d2 = {"b":2}
import json
with open('test2.json','w+') as file:
    json.dump([d1,d2],file)

A: A list of dictionaries is a json serializable ofject already, so just serialize the whole object you need:
import json
with open('test2.json','w+') as file:
    json.dump([{"a":1}, {"b":2}],file)


text:
Q: static function output varies from ordinary fn output When I use a
static int CompareFunction(const void* _g1, const void* _g2);

the input to qsort is right
but using
int CompareFunction(const void* _g1, const void* _g2);

the input to qsort is wrong. and the error is :
error: argument of type 'int (<namespace>::<ClassName>::)(const void*, const void*)' does not match '__compar_fn_t {aka int (*)(const void*, const void*)}'
How can static change the behavior in such a way ? I mean the all I am doing is just changing a function in a class to be static which means it now lacks this pointer. There is no more change I am making.

A: A static member function is a regular function, but a non-static member function is something different.  The need to have the extra hidden "this" parameter is what makes the difference.

A: A non-static function can only be called on an instance of an object. There is no instance of an object to call the function on inside qsort (it just has pointers that it considers opaque), so it cannot invoke a member function.


text:
Q: Есть ли опасность в Callback API Вконтакта? Просто есть план заказать мобильное приложение для одной группы вконтакта,
и оно должно коннектится к Callback API,
и дать заказ фрилансеру -
нет ли опасности, что фрилансер что-нибудь такого накодит, от чего будет вред?
И вообще, используя API Вконтакта, можно ли навредить паблику?

A: Прямая угроза от Callback API отсутствует, поскольку доступ там только на чтение. Возможна утечка данных - но у вас и так паблик.
Если же говорить о API Вконтакта в целом - то, разумеется, навредить можно сотней разных способов, ведь через API можно делать почти все то же самое, что можно делать через веб-интерфейс.
PS не забывайте о главной угрозе, исходящей от фрилансеров - они могут накодить неработающее приложение.

A: Мобильное приложение, вероятно, подразумевает и какую-то серверную часть – ведь именно сервер будет подключен к Callback API и станет получать от ВК уведомления о событиях в группе. Если сервер не под вашим контролем, а фрилансера, то вы не контролируете, кто имеет доступ к данным. Возможна утечка данных о событиях в группе.
В частности, конкурентам может быть интересна ваша свежая аудитория – те, кто только что вступил в вашу группу, а значит, живой аккаунт, проявляющий интерес к вашей тематике. «Угон» свежих вступивших – довольно распространённая механика. Многими средствами можно находить тех, кто недавно вступил в любой паблик. Далее им пишут ЛС с предложением со скидкой купить то же, или вступить в другой паблик, или поливают негативом исходную группу и их бизнес.
Callback API – самый быстрый способ перехватить свежего вступившего, ведь событие передаётся на сервер мгновенно, как только человек вступает в группу. Но т.к. этот API доступен только владельцам группы, конкурентам обычно сложно до него добраться. В случае с непонятным фрилансером и его сервером эта задача облегачается (теоретически).
Вероятно, одним чтением данных приложение не ограничится. Будут задействованы и другие методы API – отправка сообщений пользователям, модерация комментариев. В этой области тоже могут быть косяки – если, например, всем обратившимся с сообщением в сообщество будет уходить ответ с дурным содержанием )
Наконец, худший возможный косяк, что приложение удалит всех подписчиков, запостит нелегальный контент, что приведёт к постоянной блокировке сообщества. Теоретически такое тоже возможно.
Это всё теории. По-моему самая реальная угроза, как и написал Pavel Mayorov, – это фрилансер, получивший деньги, и исчезнувший, так ничего толком и не сделав.


text:
Q: insert data into database with jsp i have to inser data from a form into DB, i tried this code it was work but now it doesnt work. i want to know where is the problem with this code
this is the code
Connection con =null;
    try{

        String driveName = "com.mysql.jdbc.Driver";

        Class.forName(driveName).newInstance();

        } catch(java.lang.ClassNotFoundException e) {
        System.err.print("ClassNotFoundException: ");
        System.err.println(e.getMessage());
        }
        try{
        con = DriverManager.getConnection("jdbc:mysql://localhost:3306/onlinequiz","root","root");
       Statement statement =con.createStatement();

    //  int id=Integer.parseInt(request.getParameter("T1"));
       int quizID = Integer.parseInt(request.getParameter("quizID"));

String take2=request.getParameter("question_type");
           String course=request.getParameter("course");
      String level=request.getParameter("level");
int duration=Integer.parseInt(request.getParameter("duration"));
String Title=request.getParameter("Title");
String Description=request.getParameter("Description");
statement.executeUpdate("insert into quiz (course,Tiltle,Description,quizID,question_type,duration,level) values('"+course+"','"+Title+"','"+Description+"','"+quizID+"','"+take2+"','"+duration+"','"+level+"')");
 %>
<%

        statement.close();

    } catch ( Exception e ) {
        out.println( "Exception: " + e.getMessage() );
    }
        // execute the statements even if the exception occurs
        finally{

        }
        %>

i tried and edit this code and its work, i made some changes , i want according what the user choose in the question type which is drop down box that conatain multiple choice or true false , should i write if statement that forward the user to his choice.

A: Does the code above throw an exception when it is executed? If so, can you copy/paste the exception message in the post?
Also, you should not directly add the user input to your insert query, it is prone to SQL injection attacks. Use prepared statements instead and consider using a proper Model-View-Control architecture by using a data access layer for all database transactions.


text:
Q: jQuery Mobile - How to resize my image from server to fit in listview image box When I call and load an image from the server into my listview, it turns out that the desired image does not fit the picture box. Images obtained from different servers have different sizes.
My HTML :

My jQuery :
$.ajax({
   type : 'GET',
   url : 'http://api.bacaberita.com/app/bacaberita/utama.html',
   async: true,
   dataType : 'json',
    success : function(result){
       allData = result.items;
       $.mobile.loading( "hide" );
       $.each(allData, function(i, data) {
           $('#listdata').append(
               '
' +
                   '' +
                       '' +
                       '
'+ data.Title +'
' +
                       '
'+ data.Post +'
' +
                   '' +
               '
'
           );
       });
       $("#listdata").listview("refresh");
    },
    error: function(jqXHR, exception) {
        alert('Connection trouble [Error Code : initApp]');
    }
});

Result :

Size of my picture about ex: 600x300.
How do I get jQuery Mobile can easily create 80x80 sizes in order to fit the image

A: If your images are square, they will be automatically resized to 80x80 and will fit nicely.
If they are rectangular and of different length to width ratios, they will be resized, but won't line up nicely.  In this case you can play with CSS to center the re-sized images horizontally and vertically, so at least they line up nicely.

Here is a DEMO

Give the
 a class that can be used in the CSS (has-odd-thumb). In the
, I have created a container for the thumbnail image that can be absolutely positioned and have the image centered:

Food

600 x 300 sized icon

The CSS then positions the thumbnail container on the left, centers the image using margin: auto and padds the anchor so that text does not overlap the image.
.has-odd-thumb li a {
    padding-left: 90px !important;
}
.thumbContainer {
    position: absolute;
    left: 0; top: 0; bottom: 0;
    width: 90px;
}
.thumbContainer img {
    bottom: 0; left: 0;
    top: 0; right: 0;
    margin: auto;
    position: absolute;
    max-width: 80px;
    max-height: 78px;
}


text:
Q: Count how many rows have a specified value when the value changes with each row When I was querying a table by a specific id I would also count how many rows in that table shared the same name:
SELECT *, COUNT(name) FROM table WHERE id = 24601

Now I'm no longer querying a table by a specific id, instead getting all of the table's output. Is there a way I could still get that count for each row?
SELECT *, COUNT(this specific row's name) FROM table

A: If you want to get the count of rows per name, then use GROUP BY:
SELECT name, COUNT(*) AS count
FROM table
GROUP BY name

You'll get one row per distinct value of name, with a second column that has the integer count.
If you also need the other columns for each row, you should write that as a separate query. Don't combine aggregated results with non-aggregated results in the same query.


text:
Q: Implementation of Line Drawing Algorithm doesn't work properly First question, I have tried to calculate the expression, di+1=di+2*Δy−2*Δx(yi+1−yi) for the four quadrants. Irrespective of the quadrant, the expression was found to be the same, including signs.
Am I right, or, there has been some mistakes in my calculations (hence, I am wrong)?
Second question, if this expression is only applicable for the first octet, how can I apply this to other octets? To me, there is no way to determine which octet I am working on. Coz, the value of m always represent two opposite octets. For example, if 0<m<1, it represents 1st and 5th octet. Right?
Thirdly, how can we determine the initial/starting value of di?
#include <iostream>
#include "utils.h"

void BresenhamLine(double x1, double y1, double x2, double y2, int color)
{
    if(x1>x2 || y1>y2)
    {
        Swap(x1, x2);
        Swap(y1, y2);
    }
    double x = x1;
    double y = y1;
    double dx = x2 - x1;
    double dy = y2 - y1;
    double dt = 2 * (dy - dx);
    double ds = 2 * dy;
    double d = 2*dy - dx;

    PlotPixel(x, y, color);

    if(dx>=dy)
    {
        while(x<=x2)
        {
            x++;
            if(d<0)
            {
                d = d + ds;
            }
            else
            {
                y++;
                d = d + dt;
            }
            PlotPixel(x, y, color);
        }
    }
    else
    {
        while(y<=y2)
        {
            y++;
            if(d<0)
            {
                x++;
                d = d + dt;
            }
            else
            {
                d = d + ds;
            }
            PlotPixel(x, y, color);
        }
    }
}

int main()
{
int gm = DETECT;
int gd = DETECT;

initgraph(&gm, &gd, "");

double x1 = 0;
double y1 = 0;
double r = 50;
double x2 = 0;
double y2 = 0;
double signx = 0;
double signy = 0;

for(int theta=0 ; theta<=360 ; theta++)
{
    x2 = r * cos(DegreeToRad((double) theta));
    y2 = r * sin(DegreeToRad((double) theta));

    x1 = 5 * cos(DegreeToRad((double) theta));
    y1 = 5 * sin(DegreeToRad((double) theta));

    BresenhamLine(x1, y1, x2, y2, YELLOW);
}

getch();
closegraph();
return 0;
}

The lines that go through 2nd and 4th quadrant are not showing up.
How to fix that with some minor changes in my code?

A: With this input: x1: 100 y1: -100 x2: -100 y2: 100
this logic:
if(x1>x2 || y1>y2)
{
    Swap(x1, x2);
    Swap(y1, y2);
}

fails.

A: This page is a good place to start. It shows code as well for 1 of the octants:
http://www.cs.helsinki.fi/group/goa/mallinnus/lines/bresenh.html
I think you need to swap the x if x1 > x2 and swap the y if y1 > y2 but not swap both if only 1 of those is true.
The external links section of the Wikipedia page contains several links to ready-made implementations that you can study.

A: Try this:
void BresenhamLine( double x1, double y1, double x2, double y2, int color )
{
  const bool steep = (std::abs(y2 - y1) > std::abs(x2 - x1));
  if(steep)
  {
    std::swap(x1, y1);
    std::swap(x2, y2);
  }

  if(x1 > x2)
  {
    std::swap(x1, x2);
    std::swap(y1, y2);
  }

  double dx = x2 - x1;
  double dy = std::abs(y2 - y1);

  double error = dx / 2;
  int ystep = (y1 < y2) ? 1 : -1;
  int y = (int)y1;

  int maxX = (int)x2;

  for(int x=(int)x1; x<maxX; x++)
  {
    if(steep)
    {
        PlotPixel(y, x, color);
    }
    else
    {
        PlotPixel(x, y, color);
    }

    error -= dy;
    if(error < 0)
    {
        y += ystep;
        error += dx;
    }
  }
}

I got this by slightly modifying the code here:http://rosettacode.org/wiki/Bitmap/Bresenham's_line_algorithm#C.2B.2B


text:
Q: Daemon::Generic locks disappearing upon daemonization on Solaris I'm trying to use Daemon::Generic, and it seems to be exactly what I need, except on Solaris it seems that locking the pid file doesn't work. As a result, status always reports the process is dead, even when it is quite clearly alive.
For example, the following:
use Daemon::Generic;

sub gd_run
{
  sleep (60);
}

sub gd_preconfig
{
  return ();
}

newdaemon(pidfile => "/tmp/myproc.pid");

... always reports the process is dead.
Note that /tmp is mounted locally, so it seems like that should avoid issues with locks over network drives.
Any ideas how to get this to work?
Edit:
On closer investigation, by putting sleep 60 commands at various points in Generic.pm, that it seems the lock is lost somewhere in the function gd_daemonize. Do locks not survive forks on Solaris? Is there a way to ensure the lock survives the daemonize process?


text:
Q: How to listen the contents of div is being updated in vue? I have a list created by v-for and wrapped by md-scrollbar.
<md-content class="md-scrollbar">
  <div v-for="(msg, index) of list" :key="index">
    {{msg}}
  </div>
</md-content>

After list changed, I wish the scrollbar scroll to the bottom.
So need to listen to element updated event or the scrollbar scrollHeight changed event. How to listen to certain DOM element's property is changed?
BTW I can't move the scroll after list changed logic because the new element hasn't been rendered at that moment yet, the height of md-scrollbar didn't update.

A: Since you need the updated dom, you could use Vue.nextTick (after list data update) :
Vue.nextTick(function () {
  // DOM updated
})

A: use watch to watch list and react accordingly
e.g.
var vm = new Vue({
  data: {
    c: {
        b: 2
    },
  },
  watch: {
    c: {
      handler: function(val, oldVal) {
        window.scrollTo(0,document.body.scrollHeight);
      },
      deep: true
    }
  }
});


text:
Q: Best wsgi service for handling webhooks with few resources Currently working on a Virtual server with 2 CPU's 4GB of ram. I am running a Flask + uwsgi + nginx to host the webserver. I need the server to be capable of accepting about 10 out of 2500-ish the requests a day. The requests that don't pass average about 2ms yet the queue is consistently backed up. The issue I have been encountering lately is both speed and duplication when it does work. As the accepted webhooks are sent to another server and I will get duplicates or completely miss a bunch.
[uwsgi]
module = wsgi

master = true
processes = 4
enable-threads = true
threads = 2

socket = API.sock
chmod-socket = 660
vacuum = true

harakiri = 10
die-on-term = true

This is my current .ini file I have messed around with harakiri and have read countless hours through the uwsgi documentation trying different things it is unbelievably frustrating.
Picture of Systemctl status API
The check for it looks similar to this redacted some info.
@app.route('/api', methods=['POST'])
def handle_callee():
    authorization = request.headers.get('authorization')
    if authorization == SECRET and check_callee(request.json):
        data = request.json
        name = data["payload"]["object"]["caller"]["name"]
        create_json(name, data)

        return 'success', 200
    else:
        return 'failure', 204

The json is then parsed through a number of functions. This is my first time deploying a wsgi service and I don't know if my configuration is incorrect. I've poured hours of research into trying to fix this. Should I try switching to gunicorn. I have asked this question differently a couple of days ago but to no avail. Trying to put more context in hopes someone could point me in the right direction. I don't even know in the systemctl status whether the | req: 12/31 is how many it's done thus far and what's queued for that PID. Any insight into this situation would make my week. I've been unable to fix this for about 2 weeks of trying different configs increasing working, processes, messing with the harakiri, disabling logging. But none of this has proved to get the requests to process at a speed that I desire.
Thank you to anyone who took the time to read this, I am still learning and have tried to add as much context as possible. If you need more I will gladly respond. I just can't wrap my head around this issue.

A: You would need to take a systematic approach in figuring out:

*

*How many requests per second can you handle

*What are your apps bottlenecks and scaling factors

Cloudbees have written a great article on performance tuning for uwsgi + flask + nginx.
To give an overview of the steps to tune your service here is what it might look like:
First, you need to make sure you have the required tooling, particularly a benchmarking tool like Apache Bench, k6, etc.

*

*Establish a base. This means that you configure your application with the minimum setup to run i.e. single thread and single process, no multi-threading. Run the benchmark and record the results.

*Start tweaking the setup. Add threads, processes, etc.

*Benchmark after the tweaks.

*Repeat steps 2 & 3 until you see the upper limits, and understand the service characteristics - are you CPU/IO bound?

*Try changing the hardware/vm, as some offerings come with penalties in performance due to shared CPU with other tenants, bandwidth, etc.

Tip: Try to run the benchmark tool from a different system than the one you are benchmarking, since it also consumes resources and loads the system further.
In your code sample you have two methods create_json(name, data) and check_callee(request.json), do you know their performance?
Note: Can't comment so had to write this as an answer.


text:
Q: .NET & gRPC, how to keep certain connection based on client choice? I have a gRPC remote service (.NET 6) and a desktop client app (.NET6/WinForms).
The remote service needs to work with 3 different SQL databases that are 1:1 clones (same structure, different data).
The client app allows users to choose which database to work with based on simple client combobox selection (only once at first run time).
I want to make it work in a way, where the service will always know that any request coming from client X needs to be processed on database Y (previously selected in the client on initial run).
What would be the best way / practice to achieve this kind of functionality?


text:
Q: Order of the smallest group containing subgroups isomorphic with all groups of order $n$ Seems similar to this question, but I want to calculate it for $n = 1\ldots6$. I know that for $n=1$ it is trivial as the only group of order 1 is the trivial subgroup of $\{e\}$, but which groups should I consider for larger $n$ and how do I know I have considered all possibilities?

A: For $n=4$, it is easy to check that the correct group is
$$\mathbb{Z}_4\times\mathbb{Z}_2\ ,$$
which has order $8$.

There are two groups of order $6$: the cyclic group $\mathbb{Z}_6$ and the symmetric group $S_6$. The biggest cyclic subgroup of $S_6$ is a copy of $\mathbb{Z}_3$ (e.g. generated by $(123)$). It follows that the smallest group containing all the groups of order $6$ as subgroups cannot have order smaller than $12$. We take the group
$$G=S_3\times\mathbb{Z}_2\ ,$$
then obviously $S_3$ is a subgroup, and we see $\mathbb{Z}_6$ as the subgroup generated by $((123),1)$. This group has order $12$.

The other cases are trivial.


text:
Q: How to set a single line inside textfield at the bottom? This the code i have used inside textfield category:
That line only shown when users touches the textField.
 @implementation UITextField (textField)

            -(void)textBottomLine:(UITextField *)textField
            {
                CALayer *border = [CALayer layer];
                CGFloat borderWidth = 2;
                border.borderColor = [UIColor colorFromHexString:@"#ffc400"].CGColor;
                border.frame = CGRectMake(0, textField.frame.size.height - borderWidth, textField.frame.size.width, 4);
                border.borderWidth = borderWidth;
                [textField.layer addSublayer:border];
                textField.layer.masksToBounds = YES;
         }

but nothing i got,please anybody help me to find out solution.

A: you need to create a custom TextField class and also set delegate in that class. Like this
.h FIle
@interface CustomTextField : UITextField<UITextFieldDelegate>
@propery(strong)CALayer *border;
@end

.m File
@implementation CustomTextField
@synthesis border;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.delegate = self;
    }
return self;
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    border = [CALayer layer];
    CGFloat borderWidth = 2;
    border.borderColor = [UIColor colorFromHexString:@"#ffc400"].CGColor;
    border.frame = CGRectMake(0, textField.frame.size.height - borderWidth, textField.frame.size.width, 4);
    border.borderWidth = borderWidth;
    [textField.layer addSublayer:border];
    textField.layer.masksToBounds = YES;
    return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField{
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
    return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField{
 [border removeFromSuperlayer];
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    return YES;
}
- (BOOL)textFieldShouldClear:(UITextField *)textField{
    return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    return YES;
}
@end

wherever you need the text field you can use:
CustomTexTField *textField = [[CustomTextField alloc] initWithFrame:customFrame];
[self.view addSubView:textField];

May be it will help you.

A: You can create custom class as per Bhumika's answer for UITextField and also use category as below.
I've created category UITextField+Extended
@interface UITextField (Extended)
-(void)addBottomLine;
-(void)removeBottomLine;
@end

in .m file
@implementation UITextField (Extended)
-(void)addBottomLine
{
    CALayer *border = [CALayer layer];
    CGFloat borderWidth = 2;
    border.name = @"bottomLine";
    border.borderColor = [UIColor redColor].CGColor;//[UIColor colorFromHexString:@"#ffc400"].CGColor;
    border.frame = CGRectMake(0, self.frame.size.height - borderWidth, self.frame.size.width, 4);
    border.borderWidth = borderWidth;
    [self.layer addSublayer:border];
    self.layer.masksToBounds = YES;
}
-(void)removeBottomLine
{
    [[self.layer.sublayers copy] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        CALayer * subLayer = obj;
        if(([[subLayer name] isEqualToString:@"bottomLine"])){
            [subLayer removeFromSuperlayer];
        }
    }];
}
@end

and In Your view controller simple import class and call this method to add/remove layer using delegate.
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [txtTemp resignFirstResponder];
    return YES;
}
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    [txtTemp addBottomLine];
}
-(void)textFieldDidEndEditing:(UITextField *)textField
{
    [txtTemp removeBottomLine];
}

Hope this will help you.

A: First place your UITextField in UIViewController. Then select that placed UITextField and go to is property on right hand side of Xcode, from there you will find Control in that you can see alignment option in that there are two more option->Horizontal and Vertical. In vertical you can see select one which you can see in screen shoot. By clicking on that option your text data will be displayed in UITextField bottom part.