text:
Q: How can I Access/extract raw(headless) audio data from a caf file on iPhone? I am working on a project that requires me to send raw headerless ulaw or linear pcm data to a server.
I am using the AVAudioRecorder and I can save out audio files to the phone quite easily, but the problem is that it no matter what I try and do, they get wrapped in a caf file or stamped with some kind of header.
It's my understanding that a caf file is just a wrapper file for raw audio data and that this audio data can be in various formats including linear pcm and ulaw.
So my questions are, how can I generate a raw audio file without the caf wrapper to begin with (ie just the headerless raw audio stuffed into a file) or if I record a caf that contains the raw Ulaw or linear pcm audio data, how can I easily go in and extract just the raw audio data from the caf file and leave everything else behind.

A: If the audio data in the CAF is already in the format you need it in, I'd use the AudioFile API to grab the caf file's audio data and write them to a headerless/RAW file before uploading to my server.
If you need to convert the CAF's data, use the ExtAudioFile API instead. Either way, pretty straightforward.
http://developer.apple.com/library/ios/#documentation/MusicAudio/Reference/AudioFileConvertRef/Reference/reference.html
http://developer.apple.com/library/ios/#documentation/MusicAudio/Reference/ExtendedAudioFileServicesReference/Reference/reference.html

A: If you use the Audio Queue API for recording, instead of AVAudioRecorder, you will have access to raw PCM sample buffers, and can write those out to a flat file for later sending to your server.


text:
Q: How to modify the "View all posts in category" title attribute I'm tyring to change the "View all posts in category" tooltip you see when you hover over a category link in wordpress. Until now I've always done it in the Wordpress core file named category-template.php  - however I'm searching for a method to do it in the functions.php so I don't have to change it after every Wordpress update.
I could only find this code to remove the "View all posts in category" title attribute alltogether, but I have no idea how to modify it:
add_filter( 'the_category', 'remove_category_title' );
function remove_category_title( $category ) {
return preg_replace( '/\s* title=\s*".*?"/i', '', $category );
}

I just want to change the text "View all posts in" and "View all posts filed under"

A: Found something that works fine:
add_filter( 'the_category', 'remove_category_link_prefix' );
add_filter( 'wp_list_categories', 'remove_category_link_prefix' );

function remove_category_link_prefix($output) {
    $replace = array(
            'View all posts in',
            'View all posts filed under'
    );

    return str_replace( $replace, 'Text you want to show up', $output);
}

found here: http://kaspars.net/blog/wordpress/remove-view-all-posts-filed-under-category-widget

redpajama_set_name: RedPajamaStackExchange


text:
Q: Click on element in dropdown with Selenium and Python With Selenium and Chrome webdriver on MacOS need to click dropdown element. But always have an error that can't find. Have this html code on a page where it located:
<select id="periodoExtrato" name="periodoExtrato" class="EXTtexto" onchange="enviarExtrato(document.formperiodo.periodoExtrato[document.formperiodo.periodoExtrato.selectedIndex].value);">
<!--<option value="01" >Último dia</option>-->
<option value="03" selected="true">Últimos 3 dias</option>
<option value="05">Últimos 5 dias</option>
<option value="07">Últimos 7 dias</option>
<option value="15">Últimos 15 dias</option>
<option value="30">Últimos 30 dias</option>
<option value="X">Data específica (até 60 dias)</option>
<option value="D">Mês completo (desde 2002)</option>
</select>

I need to choose Últimos 15 dias, so i have this code:
self.driver.find_element_by_xpath('//[@id="periodoExtrato"]/option[4]').click()

But have an error:
Traceback (most recent call last):
  File "olxscrape.py", line 120, in <module>
    main()
  File "olxscrape.py", line 117, in main
    b = Bot()
  File "olxscrape.py", line 12, in __init__
    self.navigate()
  File "olxscrape.py", line 106, in navigate
    self.driver.find_element_by_xpath('//*[@id="periodoExtrato"]/option[4]').click()
  File "/Users/Lutchenko/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 293, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)
  File "/Users/Lutchenko/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 752, in find_element
    'value': value})['value']
  File "/Users/Lutchenko/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 236, in execute
    self.error_handler.check_response(response)
  File "/Users/Lutchenko/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 192, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="periodoExtrato"]/option[4]"}
  (Session info: chrome=55.0.2883.95)
  (Driver info: chromedriver=2.27.440174 (e97a722caafc2d3a8b807ee115bfb307f7d2cfd9),platform=Mac OS X 10.12.2 x86_64)

A: I would suggest not using xpath here. Try, instead, something like this:
 select = Select(self.driver.find_element_by_id('periodoExtrato'))
 option_indexes = range(1, len(select.options))
 for index in option_indexes:
    select.select_by_index(index)
    ......

A: A problem is that element goes after </head> in <frameset>, so selenium  can't find it. After adding this string problem solved.
browser.switch_to_frame('name')

And after that
self.driver.find_element_by_xpath('//[@id="periodoExtrato"]/option[4]').click()


text:
Q: How can I publish an exectuable file to my Azure Function from Visual Studio? I have a Function App solution with multiple functions that I usually publish from my Visual studio to the cloud. I now need to add an executable file to my Function App so my differents functions can call it. I was able to add the exe file with its dll to the solution and call it locally. Then when I publish my solution, i do not see the executable in any path (siteroot/home....) or the Kudu. The only way I was able to make run an executable in the cloud, was by creating a new Function App and upload directly the exec and code the function in the cloud editor.

A: Right click on your file in Visual Studio and check its properties.

Set Copy to Output directory to Copy if newer.
Or, you could verify your Project's csproj file and include it manually using:
<ItemGroup>
  <None Update="{filename}">
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
  </None>
</ItemGroup>

EDIT:
To customize the destination path or even the file name, you could use build events in Visual Studio. In the Post-build event command line box, specify the following:
copy /Y "$(SolutionDir){sourceFilename}.{extension}" "$(TargetDir){destinationFilename}.{extension}"

There are various macros available for post-build events that you can choose from:


text:
Q: Work out height of heap from elements I am trying to work out the height of a heap given there are 210 elements.
I have tried using the log(n+1) -1 formula however I am getting a weird answer. I also tried drawing it the heap out and that way I get that it would be a height of 8.
Thanks in advance.

A: İf your heap is binary, the formula is like that, otherwise you can look at https://cs.stackexchange.com/questions/9914/finding-the-height-of-a-d-ary-heap.
height = ⌈log(base2)(n+1)⌉-1

height = ⌈log(base2)(200+1)⌉-1

height = ⌈7,..⌉-1

height = 8-1

height = 7


text:
Q: CMake and CPack. Install path in config file Is there a way to create install and package (I need a deb package) targets using CMake, where install path is read from some configuration file (e.g. /etc/myconfig.cfg) in install-time. I can do it using shell scripts, but I'd like to use CMake's and CPack's possibilities. I'd like a generated deb package to read myconfig.cfg in install time
A very simple example of start CMakeLists.txt:
cmake_minimum_required(VERSION 2.8.11 FATAL_ERROR)
project("My project")
add_executable(a.out main.cpp)

/etc/myconfig.cfg:
set(INSTALL_PATH "/var/path1")

or:
INSTALL_PATH = /var/path1

or something similar.

A: Why not use CMAKE_INSTALL_PREFIX? For example:
cmake -DCMAKE_INSTALL_PREFIX=/usr/boob ..

A: I realise this question is as old as the hills...
What you're proposing isn't possible with Apt (or RPM, or numerous other package types) - and so cpack can't provide the facilities either.
The reasoning being that the package is supposed to describe the things it will install into the system - and most critically, the things it'll remove if the package is uninstalled, or if a subsequent version of it no longer include files in the older version. You can understand that this wouldn't be possible if a config file could alter the way the package landed on the system because after install the config could change, making the on-going maintenance of files impossible.
What you're asking for is somewhat "non standard" for a package, and somewhat problematic for running systems. Instead, you have a number of options...

*

*Make a package for each installation variant you expect

*Make a single package, and then use a post-install Bash script to do all the path creation/adjustments you need

*Use a package to "centrally" put files in place, and then use Configuration Management (Ansible, Puppet, Chef etc) to do the remaining work.

Personally, I'd recommend option 3. Option 1 is a lot of work, Option 2 is "messy" in so much as the administrator will be left with a load of files and directories which aren't owned by any package, making uninstall difficult. It also encourages the creation of a handful of Bash scripts which are hard to maintain and most likely won't do what they're supposed to in all the places your package gets deployed.
The Third option leaves the sysadmin in control, and they'll have the knowledge of what's on their system, what to remove if they need to, etc.


text:
Q: Will QTimer with mutex cause program to exit unexpectedly? What we know:

*

*QTimer without the single-shot option will emit a timeout signal at a specific interval.

*Timeout will call a function when emitted.

*A mutex will lock a variable from being modified by another thread.

My question is:
Say I have a very timing consuming function F1 uses a variable A with a mutex in one thread. And, QTimer is running a loop calling function F2 which also uses A with a mutex in another thread. If F1 is running and A is locked, then F2 will wait for A to be unclocked. Will the QTimer stack a lot of F2 calls when F1 runs indefinitely?

A: It seems that Pyqt will handle it. Here are two example threads:
class test_thread(QThread):
    timer = QTimer()

    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.timer.timeout.connect(self.start)

    def run(self):
        print("call")
        global mutex
        global n
        mutex.lock()
        n = n + 1
        print(n)
        mutex.unlock()

    def process(self):
        self.timer.start(1000)

class test_thread1(QThread):
    def __init__(self, parent=None):
        super().__init__(parent=parent)

    def run(self):
        global mutex
        mutex.lock()
        while True:
            global  n
            n = n - 1
            print(n)
            time.sleep(1)
        mutex.unlock()

Two situations are tested:

*

*test_thread1 without time.sleep(1)
The "call" in test_thread will never be printed and the n is counting down.

*test_thread1 with time.sleep(1)
The "call" only showed up once and the n is counting down as well.


text:
Q: Parameterization of curves for line integrals The question asks to find the following line integral $$\int |y|ds$$ along the curve $$C: (x^2+y^2)^2=8^2(x^2-y^2)$$ I used the parameterization $$x=\sec m; y=\tan m$$ and solved it further to get $$\sec^2m+\tan^2m=8$$, which is $$x^2+y^2=8$$. Then I parameterize once again using $$x=\cos t, y=\sin t$$ and the final answer I get is 16. However, I don't have the answer to this question so I am not sure if what I have done is correct.

A: HINT: Here's a correct way to parametrize the curve. Start with polar coordinates: $x=r\cos t$, $y=r\sin t$. Substitute to obtain
$$r^2 = 8^2 \cos 2t\,.$$
Note that this limits $t$ to the intervals where $\cos 2t\ge 0$, i.e., $|t|\le \pi/4$ and $-3\pi/4\le t\le 5\pi/4$.
So we have the parametrization
\begin{align*}
x(t) &= 8\sqrt{\cos 2t}\cos t \\
y(t) &= 8\sqrt{\cos 2t}\sin t
\end{align*}
on these intervals.

EDIT: By symmetry, the integral is $4$ times what we get integrating from $0$ to $\pi/4$, so we get (you should check that $ds/dt = 8/\sqrt{\cos 2t}$)
$$4\cdot 64\int_0^{\pi/4} \sqrt{\cos 2t}\sin t\frac1{\sqrt{\cos 2t}}\,dt = 256\big(1-\frac1{\sqrt2}\big)\,.$$


text:
Q: What does it mean by a library of code? And how do I access one? http://troy.spunak.com/TAPsDoc/html/index.html
Here is an example of .cpp and .h files that someone has written and made as a library.

How do I gain access to his functions and classes (Which directory do I place them in after downloading, and if I have to compile them?
How do I compile them?)?
Do I have to create a main function and run my code or does the library come with a
main  function and I use the one provided?

A: A library is a reusable module that is used precompiled in particular system configurations.
How you use a library depends on your particular development environment, but with some versions of C++ you tell the linker where the library is (*.dll or *.lib, say) and tell it to incorporate the library in your executable (static linking) or use it as it needs (dynamic linking).
To use a particular library, the library designer may have included an IDE project file or a makefile so that you can build the library from source.  Or, they might just provide the library as a binary.  In either case, they might provide instructions on using the library, or show some examples.  Actually, this one does:
http://troy.spunak.com/TAPsDoc/html/ex_c_d_r__fns_8cpp-example.html
Hope this helps.


text:
Q: Objective Lower Bound command? Using PULP with COIN_CMD/CBC/CLP I'm using PULP to solve an LP with CBC with a fracgap(epgap) of 0.01 (99.99%).  Is there a command to return the best lower bound found after the solver finishes?  So, whatever the solver is comparing the objective value to in order to know its within 0.01 and it can stop.

A: Sorry but Pulp does not return the best bound of the solution, with COIN_CMD().
I think it is printed to stdout if msg=1 is used if you just what to see what it is.


text:
Q: Regex to match string starting with particular number and ending in semicolon I have some string with pattern:
15764_Coordinator/Principal Investigator, Curator;44504_Database Manager, Architect;43401_Scientific Expert;43701_Scientific Expert;

The delimiter in this pattern is a semicolon ;. Provided that I have any starting number say 44504, I want to delete the string part starting with this number up until the semicolon ;. The string after deleting will be:
15764_Coordinator/Principal Investigator, Curator;43401_Scientific Expert;43701_Scientific Expert;

How can I achieve this?

A: You need to to use string.replaceAll function.
string.replaceAll("(?m)(?<=^|;)44504[^;]*;", "")

*

*(?m)  Multiline modifier. It's necessary when you're dealing with multi-line input where your regex contain anchors (^, $)

*(?<=^|;) Positive lookbehind which asserts that the match must be preceded by a semi-colon or start of the line.

*[^;]* negated character class which matches any character but not of ;, zero or more times.
Example:
String s = "15764_Coordinator/Principal Investigator, Curator;44504_Database Manager, Architect;43401_Scientific Expert;43701_Scientific Expert;";
System.out.println(s.replaceAll("(?<=^|;)44504[^;]*;", ""));

Output:
15764_Coordinator/Principal Investigator, Curator;43401_Scientific Expert;43701_Scientific Expert;

A: try this..
string.replaceAll("(?<=\;)44504.*?\;", "")


text:
Q: validation login with data stored on localStorage the code i made only reads the last index from localStorage for login validation, can someone help to login using all existing data?
$('#btnlogin').click(function(){
        var usernamelogin = $('#usernamelogin').val()
        var passwordlogin = $('#passwordlogin').val()
        var data_user1 = JSON.parse(localStorage.getItem('data_user'))

        for(var i in data_user1){
        var entry = data_user1[i]
        }

        if(usernamelogin == entry.username && passwordlogin == entry.password){
            alert("Log in successfull")
            window.location.href = "curhat.jsp"
        }else{
            alert("wrong username or password")
            }
        //console.log(data_user1)
        //console.log('username = ' + entry.username)

    })


text:
Q: Tool for taking a bunch of data and guessing its statistical distribution? If I have a large sample of data (a vector of 10000 numbers or so), is there some tool that will look at the data and try to fit a number of common statistical distributions to the data and report on how good a fit each one is? If I have to specify the list of possible distributions myself, that's ok.

A: If you are looking for Statistics tools ...
R would probably be the first choice - have a look at: www.r-project.org
Grab RStudio as an IDE install package Deducer and off you go with your analysis.
Ah, and by the way it's all Open-Source / Freeware ...
Greetings, Walter


text:
Q: Validate GridView with CheckBox (at least one checked) c# window application i am working on a c# window application. i am phasing an issue regarding on button save. How to Validate GridView with CheckBox (at least one checked) in c# windowform application on save button? kindly show with example
{
 //  var checkbox = Convert.ToBoolean(this.dgvPurchaseOrder.Rows[0].Cells["checkBoxColumn"].Value);
   for (int i = 0; i < dgvPurchaseOrder.Rows.Count; i++)
   {
       var checkbox = Convert.ToBoolean(this.dgvPurchaseOrder.Rows[0].Cells["checkBoxColumn"].Value);
       if)
       {
           MessageBox.Show("Alteast Check one record to save");
       }
       else
       {
           proceed
       }

   }

A: Use foreach for better performance,

    string message = "Alteast Check one record to save";
    int i=0;
        foreach (DataGridViewRow row in dgvPurchaseOrder.Rows)
        {
            bool isSelected = Convert.ToBoolean(row.Cells["checkBoxColumn"].Value);
            if (isSelected)
            {
                message  = "YES";
                i++;
            }
        }
    if(message!="YES")
          MessageBox.Show(message);
    else
          MessageBox.Show(i.ToString()+" Items Selected");


text:
Q: How can I remove the search bar at footer added to top? I want to move the search bar which is at bottom of the data table in admin template to top ..
as this is defined in javascript .. any suggestion pls..

A: Taking this piece of code from the link you provided.
/*
* Set DOM structure for table controls
* @url http://www.datatables.net/examples/basic_init/dom.html
*/
sDom: '<"block-controls"<"controls-buttons"p>>rti<"block-footer clearfix"lf>',

Here you can see this sDom right. Thats the option in datatable used to set the Table structure and to place the sections accordingly. I would suggest you to take a look at Datatables Dom Settings
The letters you see in the settings are p , r,t, i, l, f. They actually mean

*

*p - pagination control

*r - processing display element

*t - The table!

*i - Table information summary

*l - length changing input control

*f - filtering input

So by replacing this Dom settings you should be able to place the items as you wish.
So what you would need is .
sDom: 'lftir'

Add the div's and styling accordingly as explained in the Markup and Styling in the above provided link.


text:
Q: Does the return value of an abstract method can be of generic type the first part of my project is to construct an hypergraph
This is a quickly-drew UML  diagram
The vertex class
    public abstract class Vertex <T>{

int vertexId ;
T vertexValue ;

public  abstract <T> T setVertexValue();

    }

The imageVertex class
   public class ImageVertex extends Vertex<Map<String, Instance>>{

@Override
public <T> T setVertexValue() {
    // TODO Auto-generated method stub
    return null;
}}

I has thought that Type will be inferred automatically as i define it for the imageVertex Map
and later for tagVertex as String
had I  wrongly used the generics?

A: It seems that you are trying to write:
public abstract class Vertex<T> {

    int vertexId;
    T vertexValue;

    public abstract T setVertexValue(); // NOTE: no <T>
}

public class ImageVertex extends Vertex<Map<String, Instance>> {

    @Override
    public Map<String, Instance> setVertexValue() {
        return null;
    }
}

In your code, the <T> in
public abstract <T> T setVertexValue();

is a completely separate generic parameter that shadows the T in Vertex<T>.

A: Remove the <T> for Vertex.setVertexValue:
public abstract T setVertexValue();

A: You've redefined the type T on setVertexValue. Use this.
public abstract class Vertex <T>{

int vertexId ;
T vertexValue ;

public  abstract T setVertexValue();

}

It uses the generic properly
public class ImageVertex extends Vertex<Map<String, String>>
{

    @Override
    public Map<String, String> setVertexValue()
    {
        // TODO Auto-generated method stub
        return null;
    }

}

A: Your setVertexValue() has a type parameter <T> itself; that means it redefines the type parameter <T> of your class. Your method declaration should look like
public  abstract T setVertexValue();

(Note the absence of the <T>)

A: Something like this must work for you.
public abstract T setVertexValue();

Remove <T>


text:
Q: Pandas to_dict() converts datetime to Timestamp In my pandas DataFrame, I have some date values which I converted from a timestamp to datetime, using the datetime module. Printing out the DataFrame looks good, but when I convert the DataFrame to a dictionary using to_dict(), the datetime values appear to be of the pandas Timestamp type.
My question is similar to this question, but I have no pandas Timestamp object at the beginning and I want to keep the datetime I created in the first place. The proposed solutions did not work for me either, as the output was still a pandas Timestamp, but of dtype object.
Input:
import pandas as pd
from datetime import datetime

list_in = [
    {"name": "a", "created": 1574947970000},
    {"name": "b", "created": 1581322065000},
    {"name": "c", "created": 1578929177000}
]

Then I create a DataFrame and convert each timestamp to a datetime format. (Division by 1000 is necessary, because the timestamp is in milliseconds and should be seconds)
df = pd.DataFrame(list_in)
df["created"] = [datetime.fromtimestamp(x / 1000) for x in df["created"]]
print(df)

Output:
  name             created
0    a 2019-11-28 14:32:50
1    b 2020-02-10 09:07:45
2    c 2020-01-13 16:26:17
name               object
created    datetime64[ns]
dtype: object

This output shows the correct date values as datetime objects. In my project I do some other magic on the DataFrame which is irrelevant for this topic. But at the end I want to convert the DataFrame back to a list of dictionaries like this:
list_out = df.to_dict(orient="records")

Final output:
[{'name': 'a', 'created': Timestamp('2019-11-28 14:32:50')},
{'name': 'b', 'created': Timestamp('2020-02-10 09:07:45')},
{'name': 'c', 'created': Timestamp('2020-01-13 16:26:17')}]

Final desired output:
[{'name': 'a', 'created': datetime.datetime(2019, 11, 28, 14, 32, 50)},
{'name': 'b', 'created': datetime.datetime(2020, 2, 10, 9, 7, 45)},
{'name': 'c', 'created': datetime.datetime(2020, 1, 13, 16, 26, 17)}]

So my question is actually, why does the to_dict() return the datetime values as pandas Timestamp objects? And how can I prevent that from happening?

A: The why can be found here.
I don't know how to prevent it from happening but you could convert the Timestamps to datetime64 aftwards:
for rec in list_out:
    rec['created'] = rec['created'].to_datetime64()


text:
Q: How to insert records to a many to many relationship table on an sql database using php? I just started PHP and am encountering a problem with php where the sql command shown below does not execute (inserts records into a many to many relationship table) when calling it with php while it works perfectly when manually inserting it with mysql command line interface.
I am using $ds and $da (manual inputs) instead of making use of sessions to make sure that the command is executed. Noting that I have other mysql queries and work perfectly fine when executed through php using the same database connection as the one shown hereunder.
$connectionStatua = connect_db();
mysqli_query($connectionStatus, $sql);

$username = $_SESSION["username"];
$ds = "dekna";
$da = "dsa.jpg";
$query="INSERT INTO `tbl_users_files` (`user_ID`, `file_ID`)
SELECT `u.id`, `f.id` FROM `users` as `u` CROSS JOIN `tbl_uploads` as `f`
WHERE `username` = '$ds' AND `file` = '$da'";
mysqli_query($connectionStatus, $query);

Please take a look at the structure of my tables:
mySql tables structure
Also, evidence that the command works perfectly in mysql cli can be viewed here: ("dekna" has id 1 while dsa.jpg has id 44 - hence take a look at the last record):
mySql cli - Command

A: Step 1> Get (Select) id of the user from the users table:
Step 2> Get (Select) id of the file from tbl_uploads table:
Step 3> Insert user_ID (from step 1) and file_ID (from step 2) to tbl_users_files table:

$connectionStatua = connect_db();
mysqli_query($connectionStatus, $sql);

$username = $_SESSION["username"]; //or $ds = "dekna";
$da = "dsa.jpg";

$user_ID = $file_ID = null;

//STEP 1
$query1="SELECT id FROM 'users' WHERE username = '$username'";
$result1 = mysqli_query($connectionStatus, $query1);

if( mysqli_num_rows($result1 ) > 0)
  {
    while ($row = mysqli_fetch_array($result1)) {
     $user_ID = $row['id'];
    }

  }
//STEP 2
$query2="SELECT id FROM 'tbl_uploads' WHERE file = '$da'";
$result2 = mysqli_query($connectionStatus, $query2);

if( mysqli_num_rows($result2 ) > 0)
  {
    while ($row = mysqli_fetch_array($result2)) {
     $file_ID = $row['id'];
    }

  }
//STEP 3
$query3 ="INSERT INTO tbl_users_files (user_ID, file_ID) values('$user_ID' , '$file_ID')";

mysqli_query($connectionStatus, $query3);


text:
Q: Get Current Active Tab through JS. I want to display the current tab as active in BOOTSTRAP.

Elementary Lower

Elementary Advance

Secondary

I want to get the current tab active through jQuery? Is there a way to do this?

A: Try
$('.nav-tabs .active').text()

A: Use this JS Code.
$(function(){
var url = window.location.pathname,
urlRegExp = new RegExp(url.replace(/\/$/,'') + "$");
$('ul.nav-tabs li a').each(function(){
if(urlRegExp.test(this.href.replace(/\/$/,''))){
$(this).addClass('active');
}
});
});

Use CSS:Attach Active class to
ul.nav-tabs a.active{color:#000;}

A: If you want to run JavaScript code whenever the current tab changes, see show and shown events in the tabs plugin documentation.


text:
Q: Deductive closure from Completeness the prompt asks to show that if $\Sigma$ is complete, then it is deductively closed.
I know that deductive closure means $\Delta \vdash \sigma$  implies that $\sigma \in \Delta$.
and that since $\Sigma$ is complete it is closed. but I'm not positive on how to write this into a proof.


text:
Q: How Can I Schedule custom cron in every 5 minutes.?
cron_groups.xml

<?xml version="1.0"?>
<group id="custom_crongroup">
    <schedule_generate_every>5</schedule_generate_every>
    <schedule_ahead_for>10</schedule_ahead_for>
    <schedule_lifetime>15</schedule_lifetime>
    <history_cleanup_every>10</history_cleanup_every>
    <history_success_lifetime>60</history_success_lifetime>
    <history_failure_lifetime>600</history_failure_lifetime>
    <use_separate_process>1</use_separate_process>
</group>

crontab.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Cron:etc/crontab.xsd">
    <group id="custom_crongroup">
        <job name="monthly_commission" instance="Rewamp\Promotion\Cron\Run" method="execute">
            <schedule>*/5 * * * *</schedule>
        </job>
    </group>

This cusotm cron is working correctly when i run the cron,

php bin/magento cron:run

from terminal. But i need to run the cron automatically in every 5 minutes. how can i implement this?.

A: If it's successfully working from terminal, then you need to set up the actual server cron job to run the command.
Have the cron command run every 1 minute. You're custom cron job however will still only run every 5 minutes because Magento knows when it should be ran.
Below is documentation from the Magento themselves instructing how to do so:
http://devdocs.magento.com/guides/v2.0/config-guide/cli/config-cli-subcommands-cron.html

A: Maybe this is your idea.

*

*Check cronjob installed in your environment

crontab -i
You can install cronjob in ubuntu with command
sudo apt install cron

*Install magento cronjob

Go to magento workspace and run command line:
php bin/magento cron:remove
php bin/magento cron:install

*Check Magento cron is installed in the environment

crontab -l

*Open Mysql and check cron is worked

SELECT * FROM `cron_schedule`

A: 1. Open terminal
2. write a command crontab -e
3. write below command

* * * * * /usr/bin/php /var/www/html/magento2/bin/magento cron:run 2>&1 | grep -v "Ran jobs by schedule" >> /var/www/html/magento2/var/log/magento.cron.log
* * * * * /usr/bin/php /var/www/html/magento2/update/cron.php >> /var/www/html/magento2/var/log/update.cron.log
* * * * * /usr/bin/php /var/www/html/magento2/bin/magento setup:cron:run >> /var/www/html/magento2/var/log/setup.cron.log

Note :- check your php and magento 2 folder path according to your project.

A: <job instance="Vendor\Module\Cron\Filename" method="execute" name="file_functionality">
  <schedule>*/5 * * * *</schedule>
</job>

You can use this to setup cron in every 5 min.


text:
Q: Calling javascript in my android webview app I've got a mobile site that use a .JS file to adapt image, font etc.
On browser it works well, but when I use my app I need to reload a page 3 times to see my site correctly. I don't understand the reason.
I think that javascript doesn't work well in my app.
this is my Mainactivity.js
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.Menu;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.parse.Parse;
import com.parse.ParseInstallation;
import com.parse.PushService;

public class MainActivity extends Activity {

    private WebView mWebView;

     /**
      * Dichiariamo l'attributo di classe url in cui
      * salviamo l'indirizzo web che aprirà la webview
      */
    private String url = "http://www.bestparty.altervista.org/Mobile";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //carichiamo la webview dentro il layout specificato

        mWebView = (WebView) findViewById(R.id.webview);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setLoadsImagesAutomatically(true);
        //carichiamo finalmete la url
        mWebView.setWebViewClient(new WebViewClient());
        mWebView.loadUrl(url);

    }

}

this is my func.js (in my site)
    $(document).ready( function(){
 if ($(window).width() > 1001 && $(window).width() < 10000 )
    {
     $("#menubar").css("font-size", ((($(window).height()*8)/100)));
     $(".fotoevento").css("height", ((($(window).height()*45)/100)));
     $(".fotoevento").css("width", ((($(window).height()*100)/100)));
      $(".pub").css("margin-left", ((($(window).height()*13)/100)));
      $(".testievento").css("font-size", ((($(window).width()*3)/100)));
      $("#footer").css("font-size", ((($(window).width()*1)/100)));

              //MOBILE
     $(".logonavig").css("height", ((($(window).height()*3)/100)));
     $(".logonavig").css("width", ((($(window).width()*19)/100)));

     }

 else if ($(window).width() < 1000)
    {
     $("#menubar").css("font-size", ((($(window).height()*3)/100)));
     $(".fotoevento").css("height", ((($(window).height()*35)/100)));
     $(".fotoevento").css("width", ((($(window).width()*90)/100)));
      $(".pub").css("margin-left", ((($(window).height()*13)/100)));
      $(".testievento").css("font-size", ((($(window).width()*5)/100)));
      $(".imamgineeventocompleta").css("margin-top", ((($(window).height()*9)/100)));
      $("#footer").css("font-size", ((($(window).width()*2.4)/100)));

      //MOBILE
     $(".logonavig").css("height", ((($(window).height()*3)/100)));
     $(".logonavig").css("width", ((($(window).width()*47)/100)));

     }

  else {
          $("#menubar").css("font-size", ((($(window).height()*3)/100)));
          $(".fotoevento").css("height", ((($(window).height()*60)/100)));
          $(".fotoevento").css("width", ((($(window).height()*110)/100)));
          $(".pub").css("margin-left", ((($(window).height()*60)/100)));
              $(".testievento").css("font-size", ((($(window).width()*5)/100)));

              //MOBILE
     $(".logonavig").css("height", ((($(window).height()*3)/100)));
     $(".logonavig").css("width", ((($(window).width()*35)/100)));
        }

})


text:
Q: Object reference not set to an instance of an object in winform when binding a datatable You may laugh at me stupid, you may vote down. But it is okay. I have struggled this simple question for several days. Basically I want to display a table through datagridview in windows form. The table is got from a stored procedure.
BindingSource bsource = new BindingSource();
    DataSet ds = new DataSet();
    private SqlDataAdapter da;
    DataTable table1 =  some subroutine

Then table does exists.

Then after run the code below I got an exception "Object reference not set to an instance of an object.".
ds.Tables.Add(table1);
            da.Fill(table1); // here catch an error.
            bsource.DataSource = table1;
            datagridview1.DataSource = table1;

A: Unless you are initializing da somewhere, between this:
private SqlDataAdapter da;

and this:
da.Fill(table1);

you will of course get an NPE because it's not pointing to anything. I think you meant:
private SqlDataAdapter da = new SqlDataAdapter();

A: You are not initializing SqlDataAdapter
private SqlDataAdapter da = // Initialize adapter here.


text:
Q: pass the value of the query too PHP from java script I am building an application. The main purpose of my work is to change an object in the php page according to the database entries.
I have one php file ajax.php. It will query the database table and return the value to my other file main.php
The main page uses ajax to query the database. And depending on the database return it will show some images to some positions in the php page.
Example: if the return value from the database query is 2: it will show image at (x1,y1) position and it will blink, and open one small window.
If the return value from the database query is 3: it will show image at (x2,y2) position and it will blink and open one window2
I am not being able to pass the ajax query value to my php portion. Only if I want to ptint the value in  then it is possible.
But I want to do something like
if ($returnvalue == 1)
 window.open("window1");
 blink_image1();

if ($returnvalue == 2)
 window.open("window2");
 blink_image2();

Please help me.
Following are the code snippet:
ajax.php
<?php
$q = intval($_GET['q']);

$con = mysqli_connect('localhost','user','password','database');
if (!$con)
{
    die('Could not connect: ' . mysqli_error($con));
}

mysqli_select_db($con,"ajax_demo");

$sql='SELECT id FROM table_name order by timedate asc' ;

$result = mysqli_query($con,$sql);

while($row = mysqli_fetch_array($result))
{
    $value = $row['id'];

}
echo $value;
mysqli_close($con);
?>

main.php

    <?php

/*
    I need the return value here.. So that I can do
    if ($return_val == 1)
    Blink_image1();
    open_window1();
    .

    if ($return_val == 2)
    Blink_image2();
    open_window2();
 */
    ?>

Please help me..

A: It looks like you're trying to pass back the AJAX request to the PHP file as the page is still loading. That will not work. PHP executes on the server, but javascript executes in the user's browser. That means you can't have javascript generated by a file send back information to the file that's generating it, because there is no way for the result to get there.
Think of it like sending a boat across a river: if you get to the other side, you may notice that you don't have a rope to tie the boat up with. However, you can't then add the rope to the boat, because it's already there with you; you need to either plan ahead ("I should really bring a rope with me") or send for another boat to bring you a rope.
What you can do instead is one of three things, in the order in which I would recommend them:

*

*Since you want the information displayed at pageload anyway, you can simply put the code in the same page as you want it to appear. So in your code, where you put your comment about "here's where I need this to happen," put your database call and logic there, rather than in a separate ajax.php file.

*Put the logic for what to display inside ajax.php, so that instead of sending the number to the browser, you're sending what it is you want to display.

*Put the logic for what to display inside your javascript function.


text:
Q: How to get image file name in php let say i have this folder to store captcha image
$directory = "http://localhost/test/wp-content/plugins/test/captcha/";

i try alot of codes like opendir, glob() etc trying together my image file name from the directory above but fail.
image file name is captcha.jpeg.
i have no choice but to use static url as shown below. but my captcha will be generating images with random (name).jpeg that is why i need a dynamic way to get image file whereby *.jpeg
$directory="http://localhost/test/wpcontent/plugins/test/captcha/captcha.jpeg";

i wants to get the whole image url return as json. Please anyone have resource to help me thanks.
return array("image url" => $image_url);

A: Did you try it?
$path_parts = pathinfo('http://localhost/test/wpcontent/plugins/test/captcha/captcha.jpeg');

$returnArray = ['image url' => $path_parts['basename']];

return json_encode($returnArray);

It return:
{
    "image_url" : "captcha.jpeg"
}

Pathinfo() PHP Manual


text:
Q: Show or list newest file in directory. I'm using Windows 7. I'm looking for a graphical way to show the newest (most recently created or modified) file in a directory, including it's subfolders. I have a parent directory, with a couple thousand subdirectories within. I need to find the newest file within those subdirectories. I am willing to pay for an application that can display this information easily. I am trying to avoid applications that show me every file in each subdirectory, as there are several thousand.
Any suggestions would be great. Thank you!

A: I think Windows already has these information, so you don't need an external application to do this task. What you need to do is switch Window explorer view to Detail mode. Example my computer window:

You can see your needed information in Date modified tab and Date created tab. When you click to these tab, Windows will sort files (folders) for you in ascending or descending order of date. So, you can get the newest or oldest files, folders as you need.
If you don't see these tabs in your computer, right click on this bar and select them

Hope this help.


text:
Q: Add or remove a character at specified location in file For example, I've a text file having following lines (no. 423 and 424):
    //printf("%d\t %d\t %d\t %d\t %d\t %d\t %d\t %d\t %d\t %d\n",i,c1,c2,c3,c11,c12,c21,c22,c31,c32); //testcells
    printf("%d\t %d\t %d\t %d\t %d\t %d\t %d\t %d\t %d\t %d\t %d\t %d\t %d   \n",i,r1,r2,r3,r11,r22,r33,r44,r55,r66,r77,r88,r99); //testnodes

Now, suppose I want to remove // in the 423th line i.e characters of column 5 and 6 form 423th line. And simultaneously, suppose I want to add // in 424th line in columns 5 and 6 such that expected output should be
    printf("%d\t %d\t %d\t %d\t %d\t %d\t %d\t %d\t %d\t %d\n",i,c1,c2,c3,c11,c12,c21,c22,c31,c32); //testcells
    //printf("%d\t %d\t %d\t %d\t %d\t %d\t %d\t %d\t %d\t %d\t %d\t %d\t %d   \n",i,r1,r2,r3,r11,r22,r33,r44,r55,r66,r77,r88,r99); //testnodes

How do I do that? (preferably with sed or awk)

A: One way:
sed -e '423s!//!!; 424s!printf!//&!' < input > output

This assumes that the first // on line 423 is the one you want to remove, and that it's the printf on line 424 that you want to comment out.
To specifically update based on the columns:
sed -e '423s!^\(....\)//!\1!; 424s!^\(....\)!\1//!' < input > output


text:
Q: How exactly works this cross components comunication "pattern" in this Angular 2 application? I am very new in Angular 2 and I have a doubt about  how exactly works this use of the cross component comunication using services.
In my application I have this RecipeService service class:
@Injectable()
export class RecipeService {

  // Hold a Recipe object to be emitted to another component to implement cross component comunication:
  recipeSelected = new EventEmitter<Recipe>();

  // List of all recipes (maybe later can be obtained by a web service)
  private recipes: Recipe[] = [
    new Recipe(
      'Tasty Schnitzel',
      'A super-tasty Schnitzel - just awesome!',
      'https://upload.wikimedia.org/wikipedia/commons/7/72/Schnitzel.JPG',
      [
        new Ingredient('Meat', 1),
        new Ingredient('French Fries', 20)
      ]),
    new Recipe('Big Fat Burger',
      'What else you need to say?',
      'https://upload.wikimedia.org/wikipedia/commons/b/be/Burger_King_Angus_Bacon_%26_Cheese_Steak_Burger.jpg',
      [
        new Ingredient('Buns', 2),
        new Ingredient('Meat', 1)
      ])
  ];

  // Inject a sub service:
  constructor(private slService: ShoppingListService) {}

  /**
   * Return a copy of the reipes array.
   * @returns {Recipe[]}
   */
  getRecipes() {
    return this.recipes.slice();
  }

  addIngredientsToShoppingList(ingredients: Ingredient[]) {
    this.slService.addIngredients(ingredients);
  }
}

This class is used by 2 different components to implement the cross component comunication by this emitter:
recipeSelected = new EventEmitter<Recipe>();

From what I have understood (correct me if I am doing wrong assertion) this recipeSelected emit event that holds the information contained into a Recipe object (it contains some string fields).
Then I have this RecipeItemComponent component (it represents a recipe and it views show the information related a specific recipe):
@Component({
  selector: 'app-recipe-item',
  templateUrl: './recipe-item.component.html',
  styleUrls: ['./recipe-item.component.css']
})
export class RecipeItemComponent implements OnInit {
  @Input() recipe: Recipe;

  // Inkect the RecipeService to use it in this component:
  constructor(private recipeService: RecipeService) { }

  ngOnInit() {
  }

  /**
   * When a specific recipe is selected in the page it emit the selected recipe to comunicate
   * with another component
   */
  onSelected() {
    this.recipeService.recipeSelected.emit(this.recipe);
  }

}

When the user click on a link into the view related to this RecipeItemComponent the onSelected() method of this class is performed.
From what I know it simply emit an event related to this Recipe object. So I think that it is shooting to someone else the content of this object, where someone else should be another component (so it is implemented the cross components comunication concept).
Then I have this other RecipesComponent component class:
@Component({
  selector: 'app-recipes',
  templateUrl: './recipes.component.html',
  styleUrls: ['./recipes.component.css'],
  providers: [RecipeService]
})
export class RecipesComponent implements OnInit {
  selectedRecipe: Recipe;

  /**
   * Inject the RecupeService to use it in this component
   * @param recipeService
   */
  constructor(private recipeService: RecipeService) { }

  /**
   * Subscribe on the event emitted when a recipe is selected:
   */
  ngOnInit() {
    this.recipeService.recipeSelected
      .subscribe(
        (recipe: Recipe) => {
          this.selectedRecipe = recipe;
        }
      );
  }

}

From what I can understand I am  registering the "listener" (is it a listerner?) for this kind of events into the ngOnInit() method, by:
  ngOnInit() {
    this.recipeService.recipeSelected
      .subscribe(
        (recipe: Recipe) => {
          this.selectedRecipe = recipe;
        }
      );
  }

So, in practice, every time that the RecipeItemComponent component emit an event containing a Recipe object, this information is received by the RecipesComponent component that use it. Is it?
Then I have a doubt about this sintax:
(recipe: Recipe) => {
    this.selectedRecipe = recipe;
}

What exactly means? I think that recipe: Recipe is the content of the received event. It is something like an implicit way to declare a function? (I came from Java and I am not so into this kind of syntax).
Another doubt is: why this code is declared into the ngOnInit()? My idea is that so it declare a listener when this component is created and then this listener react to events that could come in a second time. Is it?

A: An EventEmitter should not be used in a service.
See this post: What is the proper use of an EventEmitter?
From that post:
Use by directives and components to emit custom Events.

Not for use in services. As @Pablo mentioned, even for components it is recommended that you use @Output to expose your event.
For a service, normally Angular's change detection will handle changes to the service data. So all you need to do is expose that data. I have an example here:
https://blogs.msmvps.com/deborahk/build-a-simple-angular-service-to-share-data/
And a corresponding plunker here: https://plnkr.co/edit/KT4JLmpcwGBM2xdZQeI9?p=preview
import { Injectable } from '@angular/core';

@Injectable()
export class DataService {
  serviceData: string;
}

So this:
@Injectable()
export class RecipeService {

  recipeSelected = new EventEmitter<Recipe>();

Becomes this:
@Injectable()
export class RecipeService {

  recipeSelected: Recipe;

And this:
  onSelected() {
    this.recipeService.recipeSelected.emit(this.recipe);
  }

Becomes this:
  onSelected() {
    this.recipeService.recipeSelected=this.recipe;
  }

And this:
export class RecipesComponent implements OnInit {
  selectedRecipe: Recipe;

  ngOnInit() {
    this.recipeService.recipeSelected
      .subscribe(
        (recipe: Recipe) => {
          this.selectedRecipe = recipe;
        }
      );
  }

}

Becomes this:
export class RecipesComponent implements OnInit {
  get selectedRecipe(): Recipe {
     return this.recipeService.recipeSelected;
  };
}

Every time the recipeSelected changes, the Angular change detection will be notified and the UI will rebind to the current value of selectedRecipe.

A: I think you have nailed the description of that piece of code. I think I would not use a service to emit a recipe, but just an @Output attribute, but anyway your analysis is correct.
About the arrow notation, I recommend you to read the MDN documentation.
And about the ngOnInit(): Usually in Angular the constructor is used to inject dependencies only, because the main initialization logic is set in the ngOnInit method just because all the attributes decorated with @Input are initialized just before calling this method, so the visual "construction" of the component won't be done before this method is called.


text:
Q: Динамические данные в iOS Здравствуйте.
Простой для вас но сложный для меня.
Есть приложение -> онлайн магазин
Где правильно хранить добавленные товары в корзину, формата - [IDтовара : количество] ?
Имею в распоряжении:

*

*NSUserDefaults

*core data

*чтение.запись в обычный plist

*SQLite
Сам думаю использовать 3 вариант
Подскажите, пожалуйста
A: NSUserDefaults - bplist.
Если нужен полный контроль над plist/bplist, используй NSPropertyListSerialization.
SQLite - это готовая эффективная структура данных для поиска, вставки, удаления.
Зависит от того, какие цели преследуются при сохранении покупки.
A: CoreData - просто, эффективно и хорошо документировано.
A: Я бы просто добавил к "ЮзерМенеджер"у массив "корзина" и туда добавлял данные с типом  "Товар".


text:
Q: This web page is supposed to have a lemon dropping and bouncing but I seam to have made mistakes and I can not find them Here is the code.
I think the main problems are just things I can not see because I have been staring at it for too long. I've been looking at the logic of it and it all looks fine but I know I must have made some errors somewhere (I'm guessing the errors are mostly in the second script not the first.

Click on the screen to drop lemon

A: You are working with an old version of javascript that your browser probably isn't using.
There were two errors in the console when I copied it over to my machine.
Uncaught SyntaxError: Unexpected token {

file:///home/tkrg/lemon.png Failed to load resource: net::ERR_FILE_NOT_FOUND

For the first error, it seems like () was not written for the function. It said
function generateGravity {

Should say
function generateGravity() {

For the second error, I think it is safe to assume that you have the picture of the lemon.
There were two other things that did not work:
parseint()

is now
parseInt()

and this:
getElementId()

is now
getElementById()

The full code

Click on the screen to drop lemon


text:
Q: Will a ContextVar leak memory in async logic if not reset after Exception? If I have a structure in an async webserver like
import contextvars
...
my_context_var = contextvars.ContextVar("var")

@app.route("/foo")  # decorator from webserver
async def some_web_endpoint():
    local_ctx_var = my_context_var.set(params.get("bar"))  # app sets params
    await some_function_that_can_raise()
    local_ctx_var.reset()

Will it leak memory if I don't wrap the ContextVar in a finally: block and some_function_that_can_raise() raises an Exception?
(without such a case, .reset() would never be called)
    try:
        await some_function_that_can_raise()
    finally:
        local_ctx_var.reset()

.. or is it safe to assume the value will be destroyed when the request scope ends?
The async example in the upstream docs doesn't actually bother .reset()-ing it at all!
In such a case, .reset() is redundant as it happens right before the context is cleaned up anyways.

To add some more context (ha), I'm recently learning about ContextVars and I assume the second is the case.
local_ctx_var is the only name which refers to the Token (from .set()), and as the name is deleted when the request scope ends, the local value should become candidate for garbage collection, preventing a potential leak and making .reset() unnecessary for short-lived scopes (hooray)
..but I'm not absolutely certain, and while there's some very extremely helpful information on the subject, it muddles the mixture slightly

*

*What happens if I don't reset Python's ContextVars? (implies it'll be GC'd as one would expect)

*Context variables in Python (explicitly uses finally:)

A: Yes - the previous value of the context_var is kept in the token object in this case. There is this rather similar question, where one of the answers run a simple benchmark to assert that calling context_var.set() multiple times and discarding the return value does not consume memory, when compared to, say, create a new string and keeping a reference to it.
Given the benchmark, I made some further experimentation and concluded there is no leak - in fact, in code like the above, calling reset is indeed redundant - it is useful if you'd have to restore the previous value inside a loop construct for some reason.
The new var is set, on top of the last saved context,  the value set in the current version of the context is simply discarded along the way: the only references to it are the one left in the tokens, if any.  In ohtther words: what preserves the previous values in a "stack like" way are calls to contextvars.run and contextvars.copy_context only, not Contextvar.set.


text:
Q: How do I calculate the slope of a line knowing one intersection point and the intersection point of that line after two reflection angles?
When a point starting at $O(0,0)$ intersects a side of the square $ABCO$, it reflects so the original angle and reflecting angle are equal. In the bottom side of the square ($AO$), we know the point intersects at $M\left(\dfrac12, 0\right)$.
What is the value of $m$ so that the line $y = mx$ intersects with the top of the square ($BC$) and right side of the square ($AB$) before intersecting with the bottom of the square ($AO$) at $M$?
I'm able to prove that the angle between each line and the sides of the square is $45^\circ$ and that the angle between two reflecting lines is $90^\circ$. But I haven't been able to use that to find the value of $m$.
I also see that if I continue drawing the line from $M$ so it reflects off the left and top of the square, it will intersect with $A(1,0)$, making a symmetric diagram if I draw a line from $M\left(\dfrac12, 0\right)$ to $\left(\dfrac12, 1\right)$. I believe there must be a way to prove that the two intersections with the top of the square must be at $\left(\dfrac12,1\right)$ and $\left(\dfrac34,1\right)$ (which would make the value of $m = \frac34$). But I don't see how to prove that.

A: Let $P$ and $Q$ be the points of intersection of the trajectory with $BC$ and $AB$, respectively. It's not hard to see that $\triangle OCP \sim \triangle PBQ \sim \triangle MAQ$.
From $\triangle PBQ \sim \triangle MAQ$, we get:
$$\frac{BP}{BQ} = \frac{AM}{AQ} \Longrightarrow BP = BQ \cdot \frac{AM}{AQ} = (1-AQ)\frac{AM}{AQ} = \frac{AM}{AQ}-AM$$
But from similarity $\triangle OCP\sim \triangle MAQ$, we get $\displaystyle{\frac{AM}{AQ} = \frac{CP}{OC} = CP}$.
So we have that $BP = CP - AM$. But $AM = \frac{1}{2}$, and $BP = 1 - CP$, so $CP = \frac{3}{4}$. Hence, $P = \left(\frac{3}{4},1\right)$, and $m = \frac{4}{3}$.
Edit:
To prove that $\triangle OCP \sim \triangle MAQ$, we just need to do some angle chasing. Since $AO \parallel BC$, we have that $\angle AOP = \angle CPO$. Due to the reflection of the trajectory conditions, we also have that $\angle CPO = \angle BPQ$. Hence $\triangle OCP \sim \triangle PBQ$ by the $AA$ criterion (they are also both right triangles). Again by the reflection condition, $\angle BQP = \angle AQM$, and since they are both right triangles, $\triangle PBQ \sim \triangle MAQ$, which proves that the three triangles are similar.

A: Let $D$ and $E$ be the reflection points at $BC$ and $AB$, respectively. Then:
$$CD=\frac{1}{m}, AE=\frac{m}{2},$$
because:
$$m=\tan \measuredangle CDO=\tan \measuredangle AME=\tan \measuredangle BDE.$$
From triangle $BDE$:
$$m=\tan \measuredangle BDE=\frac{BE}{BD}=\frac{1-\frac{m}{2}}{1-\frac{1}{m}} \Rightarrow \\
m=\frac43.$$

A: I think I came up with an answer.
As I wrote in the question, I continued drawing the line from $M$ so it reflects off the left and top of the square. It must intersect with $A(1,0)$ because all the angles are the same as on the other side of the square.

I then drew a horizontal (dashed) line intersecting with the intersection of the angled lines touching the left and right of the square and vertical lines down from the intersections at the top of the square and a vertical line up from the intersection at $M$.
That vertical line must intersect with the crossing point of the two diagonal lines that intersect the top of the square, because the the angles of the other two angles within the triangles they form are the same. In fact, all 8 triangles formed along the top of the square must be identical because the angles must be all the same and the lengths of two of the sides are the same. So the lengths of the sides of the four triangles with sides along the top of the square must be the same. So each of those four sides must be $\frac14$.
So $y = mx$ becomes $1 = m\frac34$ and so $m = \frac43$.


text:
Q: Validation Formik js I have implement formik with react native.
I use formik : 2.1.4, yup: 0.29.1 and react native: 0.62.
I use validation with yup, but the validation only trigger on blur.
How to trigger validation on change text?
  <Formik
      enableReinitialize
      initialValues={{
        phoneNumber: props.phoneNumber,
      }}
      onSubmit={values => {
        console.log('Login Submit');
      }}
      validateOnMount={true}
      validationSchema={yup.object().shape({
        phoneNumber: yup
          .string()
          .required()
          .min(8)
          .matches(regexPhoneNumber, 'Phone number is not valid'),
      })}>
      {({
        // values,
        handleChange,
        errors,
        setFieldTouched,
        touched,
        isValid,
        handleSubmit,
      }) => (
          <View style={styles.form}>
            <View style={styles.subContainer}>
              <View style={styles.containerTitle}>
                <Text style={styles.textTitle}>+62</Text>
              </View>
              <View style={styles.containerPhoneNumber}>
                {renderFocus()}
                <TextInput
                  onFocus={() => props.setFocus(true)}
                  value={props.phoneNumber}
                  style={styles.subContainerPhoneNumber}
                  placeholderStyle={styles.placeholder}
                  placeholder={'Type your phone number'}
                  onChangeText={(value) => {
                    handleChange('phoneNumber');
                    props.changePhoneNumber(value);
                  }}
                  keyboardType={'numeric'}
                  onBlur={() => setFieldTouched('phoneNumber', true)}
                />
              </View>
            </View>
            {touched.phoneNumber && errors.phoneNumber && (
              <View style={styles.containerError}>
                <Text style={styles.textError}>Phone number is not valid</Text>
              </View>
            )}
            <View style={styles.containerButton}>
              <TouchableOpacity
                disabled={!isValid}
                id={'nextButton'}
                accessible={true}
                accessibilityLabel={'nextButton'}
                // eslint-disable-next-line react-native/no-inline-styles
                style={{
                  backgroundColor: isValid ? color.thema : color.grey,
                  paddingHorizontal: responsiveWidth(8.3),
                  paddingVertical: responsiveHeight(2.2),
                  justifyContent: 'center',
                  alignItems: 'center',
                  borderRadius: 5,
                }}
                onPress={() => handleSubmit}>
                <Text style={styles.textButton}>Next</Text>
              </TouchableOpacity>
            </View>
          </View>
        )}
    </Formik>

With this code, the validation on trigger on blur text input.
I need to trigger validation on change text.

A: Put setFieldTouched('phoneNumber', true) line also in onChangeText.
...
...
<TextInput
  onFocus={() => props.setFocus(true)}
  value={props.phoneNumber}
  style={styles.subContainerPhoneNumber}
  placeholderStyle={styles.placeholder}
  placeholder={'Type your phone number'}
  onChangeText={(value) => {
    setFieldTouched('phoneNumber') // add here also
    handleChange('phoneNumber');
    props.changePhoneNumber(value);
  }}
  keyboardType={'numeric'}
  onBlur={() => setFieldTouched('phoneNumber')}
/>
...
...


text:
Q: YoloV3 Result Giving Zero confidence in every class I Am Doing Implementation Of Yolo v3 for multi class object detection
yolo is algorithm based region proposal
and the region proposal with max confidence treated as prediction of yolo
for more you can read it about here
for this particular task i refer to this murtuza tutorial that guided me from scratch
now as the complex network architecture requires hours of training
i prefer to use transfer learning as using pretrained network and weighs(parameters)
both of this link you can find here

Architecture configuration:cfg
Network Parameters(weights):weights
i used here yolov3 tiny as i required higher frame rates to process a video
but afterall it not giving promising
result as the tutorial shows
i don't where i am lacking
but even changing the network cfg and weight file to the orignal yolov3(320)does not giving true result
as i am getting all 5 spatial data as  coordinate and confidence
[cx,cy,h,w,confidence] but all 80 classes probality is still zero vector[0.0,0.0,0.0---0.0]
even changing the video source and choosing another video resulting into zero vector
which was  in tutorial working fine
Implementation Code:
# YOLO Algorithm
# Network Weights and configuration Files

yolov3_tiny_cfg='/root/Downloads/ML TASK/yolov3-tiny.cfg' # configuration file
yolov3_tiny_weights='/root/Downloads/ML TASK/yolov3-tiny.weights' # weights
coco_names='/root/Downloads/ML TASK/coco.names' # coco classes
# for yolo genral 320 architecture
# put paths to directory
yolov3_cfg='/root/Downloads/ML TASK/yolov3.cfg'
yolov3_weights='/root/Downloads/ML TASK/yolov3.weights'

# Test Videos
Test_video_1='/root/Downloads/ML TASK/mn.mp4'
Test_video_2='/root/Downloads/ML TASK/bg.mp4'

# Dependencies
import cv2
import numpy as np

# Dataset Classes:
# there are around 80 classes in the coco dataset so manually writing them would not be right choice so instead of them we are getting them from a file name coco.names stored in drive
# getting list of classes
classes=[] # empty list intialization
with open(coco_names,'r')as f:
  classes=f.read().splitlines()
# viewing the multiclass list around 80 classes in coco dataset

# Loading the yolov3 using configuration file and weights
network=cv2.dnn.readNetFromDarknet(yolov3_cfg,yolov3_weights)
network.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV)# to use opencv CPU as backend
network.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU)

#NOTE: The network won't feed directly the image we have to First Preprocess it To match the input shape of network also the type i.e. Blob it genrally refers to a mathematical form of binary Images Like Bitmap
Width,Height=320,320 # sqaure image so the network grid should be n*n equal on both dimension
Confidence_Threshould=0.5 # minimum problity for claiming the prediction
NMS_Threshould=0.3

cap=cv2.VideoCapture('game.mp4')
fps = cap.get(cv2.CAP_PROP_FPS)
timestamps = [cap.get(cv2.CAP_PROP_POS_MSEC)]

# function to find objects on captured video stream
def findObjects(outputs,image):
  h,w,c=image.shape
  bound_box=[] # for feeding through function
  classIds=[]
  confidence=[]

  for output in outputs: # getting o/p from 2 layers(v3 tiny) 3 if use yolov3 320
    for detection in output:
      scores=detection[5:]  #slice first five values cause we are gonnause them in bounding
      classId=np.argmax(scores)
      confs=scores[classIds]

      # filtering object putting them as final prediction only when its breaches the minimum threshould of confidence
      if confs > Confidence_Threshould:
        w,h=int(detection[2]*Width),int(detection[3]*Height)              # to convert % into pixel
        x,y=int((detection[0]*Width)-(w/2)),int((detection[1]*Height)-(h/2))
        bound_box.append([x,y,w,h])
        classIds.append(classId)
        confidence.append(float(confs))
  print(len(bound_box))

  # to downsample the no. of boxes on frame we use nms boxes it give indices by which spatial info to keep
  indices=cv2.dnn.NMSBoxes(bound_box,confs,Confidence_Threshould,NMS_Threshould)
  for i in indices:
    i=i[0]
    box=bound_box[i]
    x,y,w,h=box[0],box[1],box[2],box[3]
    cv2.rectangle(image,(x,y),(x+w,y+h),(255,0,0),2)
    cv2.puttext(image,f'{classes[classIds[i]]}{int(confidence[i]*100)}%',
    (x,y-10),cv2.FONT_HERSHEY_PLAIN,0.6,(0,255,0),2)
    cv2.puttext(image,f'FPS:{fps}',(0,150),cv2.FONT_HERSHEY_PLAIN,0.6,(0,255,0),2)
    cv2.puttext(image,f'TIMESTAMPS:{timestamps}',(150,0),cv2.FONT_HERSHEY_PLAIN,0.6,(0,255,0),2)

while True:
  success,image=cap.read()
  # coverting image into blob for network i/O processing
  try:
   blob=cv2.dnn.blobFromImage(image,1/255,(Width,Height),[0,0,0],crop=False)
  except:
   continue

  # I/P
  network.setInput(blob) # Setting Input

  # O/P
  # As Yolo Architecture Produces Three O/p[Genral Architecture] From The Respective Layer And By Summarize The Max Of Confidence to Decide Final Predictions
  # But here only 2 o/p of network as we are using the tiny version for higher frame rates
  # In Order to Get The Outputs We Have To Know the Name Of the Respective Layers #i.e. Not Names Actually But Getting indexes(starting from 1 Not zero) Here By Use Of getUnconnectedOutLayers Function
  layers_names=network.getLayerNames()
  #print(network.getUnconnectedOutLayers()) #36th and 48th indexes
  #looping over as we are traversing multiple values of OutLayers
  outputNames=[layers_names[i[0]-1]for i in network.getUnconnectedOutLayers()] #-1 cause the index are starting from one not zero
  #print(outputNames) # for v3 tiny its 16 and 23  are layer name

  # forwading the image to network
  outputs=network.forward(outputNames)

  # finding objects
  # print(outputs[0].shape)=>(300,85) 300=>no.of boxes 85=>[cx,cy,height,width,confidence,probablity of 80 classes]
  # using the cx,cy,h,w we are gonna determine the bounding box
  # print(outputs[1].shape)=>(1200,85) 1200 boxes this shape present in m*n format i.e. matrix faishion  where 1200 rows of boxes map with 85 vector details explained aboved
  #print(outputs[0][0])

  findObjects(outputs,image)

  cv2.imshow('Window',image)

  if cv2.waitKey(15) & 0xFF == ord('q'):
        break
  cap.release()
  cv2.destroyAllWindows()

A: You have many problems with your code.

*

*You have to use the h,w that you got from the image and not your default width and height that you use to blob the image for the YoloV3.

change
    w,h=int(detection[2]*Width),int(detection[3]*Height)

    x,y=int((detection[0]*Width)-(w/2)),int((detection[1]*Height)-(h/2))

to
    w,h = int(det[2]*w) , int(det[3]*h)
    x,y = int((det[0]*w)-Width/2) , int((det[1]*h)-Height/2)

*You confused a lot between confs and confidence and that's make a mess, you can check with the murtaza tutorial but it will take some time.

There may be a few more small mistakes I missed.
---------------------------------- Final Solution: ----------------------------------
To save your time Here is the correct code style of your project that works.
Note 1: I changed the coco.names labels loading method a little bit, your method didn't work well on my Macbook Pro.
Note 2: In my code you have to change the file paths back to your paths like in your original code.
yolov3_cfg='/root/Downloads/ML TASK/yolov3.cfg'
yolov3_weights='/root/Downloads/ML TASK/yolov3.weights'
import cv2 as cv
import numpy as np

cap = cv.VideoCapture("video.mp4")
whT = 320
confThreshold =0.5
nmsThreshold= 0.2

#### LOAD MODEL
## Coco Names
classesFile = "coco.names"
classNames = open(classesFile).read().strip().split("\n")
print(classNames)
## Model Files
modelConfiguration = "yolov3.cfg"
modelWeights = "yolov3.weights"
net = cv.dnn.readNetFromDarknet(modelConfiguration, modelWeights)
net.setPreferableBackend(cv.dnn.DNN_BACKEND_OPENCV)
net.setPreferableTarget(cv.dnn.DNN_TARGET_CPU)

def findObjects(outputs,img):
    hT, wT, cT = img.shape
    bbox = []
    classIds = []
    confs = []
    for output in outputs:
        for det in output:
            scores = det[5:]
            classId = np.argmax(scores)
            confidence = scores[classId]
            if confidence > confThreshold:
                w,h = int(det[2]*wT) , int(det[3]*hT)
                x,y = int((det[0]*wT)-w/2) , int((det[1]*hT)-h/2)
                bbox.append([x,y,w,h])
                classIds.append(classId)
                confs.append(float(confidence))

    indices = cv.dnn.NMSBoxes(bbox, confs, confThreshold, nmsThreshold)

    for i in indices:
        i = i[0]
        box = bbox[i]
        x, y, w, h = box[0], box[1], box[2], box[3]
        # print(x,y,w,h)
        cv.rectangle(img, (x, y), (x+w,y+h), (255, 0 , 255), 2)
        cv.putText(img,f'{classNames[classIds[i]].upper()} {int(confs[i]*100)}%',
                 (x, y-10), cv.FONT_HERSHEY_SIMPLEX, 0.6, (255, 0, 255), 2)

while True:
    success, img = cap.read()
    blob = cv.dnn.blobFromImage(img, 1 / 255, (whT, whT), [0, 0, 0], 1, crop=False)
    net.setInput(blob)
    layersNames = net.getLayerNames()
    outputNames = [(layersNames[i[0] - 1]) for i in net.getUnconnectedOutLayers()]
    outputs = net.forward(outputNames)
    findObjects(outputs,img)

    cv.imshow('Image', img)
    cv.waitKey(1)


text:
Q: Parsing JSON response I am using AFJSONRequestOperation to request a remote API:
 NSURLRequest *request = [NSURLRequest requestWithURL:url];
    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {

        //Remove the SVProgressHUD view
        [SVProgressHUD dismiss];

        //Check for the value returned from the server

        NSData *jsonData = [JSON dataUsingEncoding:NSUTF8StringEncoding];//This line cause crash
        NSArray *arr = [NSJSONSerialization JSONObjectWithData:jsonData
                                                       options:0
                                                         error:nil];
        loginDic=[[NSDictionary alloc]init];
        loginDic=[arr objectAtIndex:0];
        NSLog(@"%@",loginDic);

    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {

        NSLog(@"Request Failed with Error: %@", [error.userInfo objectForKey:@"NSLocalizedDescription"]);
    }];
    [operation start];
    [SVProgressHUD showWithStatus:@"Loading"];

However, the app crashes and I am getting this error:
[__NSCFDictionary dataUsingEncoding:]: unrecognized selector sent to instance

Here is an NSLog for the JSON object returned:
 Result =     (
                {
            operation = 5;
            result = 1;
        }
    );

Am I missing something, because I think that I am not parsing correctly the JSON object. Please correct me.

A: The object you get in the success block is already parsed by AFJSONRequestOperation.
In your case you get a NSDictionary object.
You can check the class of the object using the isKindofClass-method:
if ([JSON isKindOfClass:[NSDictionary class]]) {
   NSDictionary* dict = (NSDictionary*)JSON;
   ...
}

A: It looks like AFJSONRequestOperation is deserializing JSON to a dictionary for you, and then you're trying to do it again. JSON is an NSDictionary but you're calling an NSString method.
Remove all of this code:
NSData *jsonData = [JSON dataUsingEncoding:NSUTF8StringEncoding];//This line cause crash
NSArray *arr = [NSJSONSerialization JSONObjectWithData:jsonData
                                                   options:0
                                                     error:nil];
loginDic=[[NSDictionary alloc]init];
loginDic=[arr objectAtIndex:0];

And replace it with:
loginDic = [[JSON objectForKey:@"Result"] lastObject];

(That'll work safely without checking array bounds, but assumes that there's only one element in the array.)


text:
Q: Adding new static scopes to existing Azure AD app registration My AD tenant has user consent disabled, i.e., all permissions added to AD app registration need an admin consent.
For an application using static permissions/scopes (v1.0 OAuth/OpenId endpoint), is it possible to add new permissions such that until the admin consent is granted, users can continue using features which require only the existing consented scopes?
Microsoft docs say: "The app needs to know all of the resources it would ever access ahead of time. It was difficult to create apps that could access an arbitrary number of resources." Does it mean that for my scenario, all users need to wait for admin consent before they can access the app?
I receive the below error when a user tries logging in to the app using the Open ID Connect flow. For reference, my login URL is similar to https://login.microsoftonline.com/{tenant}/oauth2/authorize?response_type=id_token&client_id=b8ad6a99-cd23-40a6-a1b4-1184af990aa2&redirect_uri=https%3A%2F%2Flocalhost%2F&state=13ccfb84-cfd1-4cb0-bfe3-bb2c227e19f7&client-request-id=4d76947a-0000-48af-aeff-7bc2d5e40000&x-client-SKU=Js&x-client-Ver=1.0.17&nonce=ef1caa16-d3fe-4523-a9c9-000000000000

A: When you add the new scopes, the app will keep working, but it will only be able to access the old scopes until the admin consents to the new scopes.
Thanks!
Alex Simons

A:
is it possible to add new permissions such that until the admin consent is granted, users can continue using features which require only the existing consented scopes?

Yes, you can.
When the admin consent the API permission of an AD App(App registration), the permissions essentially will be given to the service principal(Enterprise application) in your AAD tenant. Actually if you use the AD App in your tenant, the permissions are essentially from the service principal.
You could refer to the screenshot below, there are four permissions, the two permission has been granted.

Navigate to the Overview, click the option Manage application in local directory.

Then in the Permissions, you will find the two permissions which have been consent.


text:
Q: what is WOW effect in music o/p configuration? Windows Media Player and some other well known players give an option of setting up WOW effect, what is the abbreviation of WOW? and how it matters in alteration of sound effects?

A: From the website for SRS who are the creators of the technology:

SRS WOW HD™ - greatly expands the size
  of the audio image, retrieves
  information lost in the mixing process
  and creates deep, rich bass response
  for a more natural audio experience.

I was not able to determine what WOW stands for, but it might also just be "'wow', that sounds good" for all I know.

A: From Toshiba's Glossary:

SRS® WOW™ consists of three separate sound expanding systems, which work together to extract"buried" highs and lows. The three systems are, SRS® 3D, TruBass™, and FOCUS™. SRS® 3D creates a three dimensional sound field from just two speakers, thus giving the listener the feeling of hearing a multi speaker surround sound system. TruBass™ produces a powerful, yet low, frequency sound by utilizing a process called psychoacoustics. From only two small speakers, TruBass™ will give the effect of an expensive sub bass woofer that will leave the listener amazed by the quality of the sound. FOCUS was added to direct the energy from the speakers of the televisio

In lay-person speak, it's a technology comprising of three separate techniques to improve the bass & treble output from speakers - allowing for 3-dimensional sound effects from 2 speakers


text:
Q: SQL Server concatenate ignore null value I am currently working on a query which join multiple columns in to 1 string with comma (,) as a separator between each other. I'm unable to figure out how to deal with null values.
DECLARE
    @item1 nvarchar(max) = 'a',
    @item2 nvarchar(max) = 'b',
    @item3 nvarchar(max) = 'c'

SELECT CONCAT(
    ISNULL(NULLIF(@item1, '') + ', ', ''),
    ISNULL(NULLIF(@item2, '') + ', ', ''),
    ISNULL(NULLIF(@item3, ''), '')
)

--@item1 = 'a', @item2 = 'b', @item3 = 'c'
--Output : a, b, c

--@item1 = 'a', @item2 = NULL, @item3 = 'c'
--Output : a, c

--@item1 = NULL, @item2 = 'b', @item3 = 'c'
--Output : b, c

With the code above it works well when @item1 or @item2 even both are NULL value, but there is a problem if @item3 is NULL value, it will have an extra comma(,) at the end,
--@item1 = 'a', @item2 = 'b', @item3 = NULL
--Output : a, b,

--@item1 = 'a', @item2 = NULL, @item3 = NULL
--Output : a,

I know this is because I hard coded the comma(,) on the NULLIF statement for @item1 and @item2, but I can't figure out there is any other better way to do this.
Any advise or a better solution for this problem?

A: The STUFF method is probably the better option here:
STUFF(CONCAT(',' + NULLIF(@item1, ''),',' + NULLIF(@item2, ''),',' + NULLIF(@item3, '')),1,1,'')

A: CONCAT_WS(', ', NULLIF(@item1,''), NULLIF(@item2,''), NULLIF(@item3,''))

A: Here you can use, the concat operator,
for the first variable don't pass concat separator, from second variable onwards pass the concat variable (separator) before variable...
declare @a varchar(10)='a'
declare @b varchar(10)='b'
declare @c varchar(10)=null
select isnull(@a,'')+isnull(','+@b,'')+isnull(','+@c,'')


text:
Q: Test Boot from PXE server w/o DHCP by specifying PXE server to use? Is it possible to test a PXE client by directly expressing the pxe server to use?
I'd like to preferably specify this in grub or from a test VM with CentOS installed. This isn't meant as a production methodology by any means, I just would like to do some testing, but don't have access to our environments DHCP server.

A: Grub has an ifconfig command that lets you manually configure the network.
grub> ifconfig --address=<IP for this host> --mask=<network mask> --server=<TFTP server address>

Once you've set up the network interface, set the root disk to the network device (nd), point Grub to the kernel/initrd images, then boot it.
grub> root(nd)
grub> kernel /path/to/kernel/image
grub> initrd /path/to/initrd/image
grub> boot


text:
Q: Compass - Get Individual number from sprite-position I need to make retina images available. I will be using the same sprite generated, but I need to halve its height, width and background-position. I would like to know how can I obtain the separated units from sprite-position($icon-map, $icon-name) to get the units I need to halve them (as obtaining them like so sprite-position($icon-map, $icon-name) / 2 doesn't work ).

A: If I understand right, this mixin can help you: https://gist.github.com/thulstrup/2140082


text:
Q: Issue in Loading Shipping Price in Order Summary at Checkout I am working on a Magento2 project and its behaviors is little bit annoyed.
Please see the attached image and see that shipping price is not loading right side Order Summary area while its fine at bottom of the page.
Further, I would like to share that we have installed following shipping extensions:

*

*Amasty_ShippingTableRates

*Magento_Multishipping

*Magento_OfflineShipping

*Magento_Shipping

Please guide in this regard.


text:
Q: Forcing SSL across all pages of a site I purchased EV Certificates for my websites and I'm attempting to force HTTPS whenever a user types in:

*

*mycoolwebsite.com

*www.mycoolwebsite.com

*http://mycoolwebsite.com

*http://www.mycoolwebsite.com
Currently I have this code in my htaccess file:
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

However, it does not seem to be working properly. It only forces SSL on my homepage and no other pages on the site.
I did a bit of research and found this block of code:
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://example.com/$1 [R=301,L]

I'm wondering are these doing the same thing?

A: Rewrite rules are evaluated in the order they're written.
RewriteRule A B
RewriteRule C D
RewriteRule E F

For every single incoming HTTP request, this will first rewrite A to B, then C to D, then E to F.
If any rule ends with [L] ("Last"), that means all following rules shall be ignored if the [L] rules matches.
In your case, you have some such rules which are checked first and which apply, so your HTTPS redirect is not evaluated.
Put such fundamental rules first. For every incoming HTTP request, you want to start by asking "Are we speaking the correct protocol?" and fix that if necessary, before going on to check more in-depth rules and do internal rewrites.


text:
Q: how to insert new row into a specific section by tapping on cell of that section : I want layout like iPhone edit contact screen swift uitablview Blockquote
enter image description here
this is what I have achieved so far in this regard and my ultimate goal is to design screen like image shared below. one thing I would like to mention is that it works well when I click on mobile cell and it inserts  a new row custom row above it but whenever I add code for below too fields it throws an exception
enter image description here
just have a look at picture this is what I want to achieve whenever I click on add email cell i could insert new row into that section and when I click on add phone I can insert new row above that cell which is of phone type
         func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
                _ = indexPath.row
                // print(indexPath)
                //myTableView.selectRow(at: indexPath, animated: true, scrollPosition: .top)
               myTableView.deselectRow(at: indexPath, animated: true)
                if(indexPath.section == 1) {
                   // print(indexPath)
                    print("hello")
                    myTableView.setEditing(true, animated: true)
                    _ = setEditing(true, animated: true)
                   // myTableView.deselectRow(at: indexPath, animated: true)
                   //phone.insert("Company", at: indexPath.row)
                     //   myTableView.beginUpdates()
                        //  _ = tableView.dequeueReusableCell(withIdentifier: //"ContactMenuTableViewCell", for: indexPath) as! ContactMenuTableViewCell

                              //  myTableView.insertRows(at: [IndexPath(row: 0, section: 1)], with: .automatic)
                              //myTableView.endUpdates()
                    }
               else if(indexPath.section == 2){
                    print("oye hoye")
                    myTableView.setEditing(true, animated: true)
                    print("maan bhi jao")
                _ = setEditing(true, animated: true)

                }
               else if(indexPath.section == 3){

                  myTableView.setEditing(true, animated: true)
                  _ = setEditing(true, animated: true)
                     // myTableView.deselectRow(at: indexPath, animated: true)
                  //  if selectedIndexPath == indexPath.row {
                   /* address.insert(" new country", at: indexPath.row)
                         myTableView.beginUpdates()
                        //  let datePickerCell = Bundle.main.loadNibNamed("PhoneTableViewCell", owner: self, options: nil)?.first as! PhoneTableViewCell
                     myTableView.insertRows(at: [IndexPath(row: 0, section: 3)], with: .automatic)
                         myTableView.endUpdates()
                     */
                    }

              //set editing function  used to perform editing on cells
            }override func setEditing(_ editing: Bool, animated: Bool) {
            super.setEditing(editing, animated: animated)
            if editing{
                    print("12345")
                if isEditing{
                    self.myTableView.setEditing(true, animated: true)
                      myTableView.beginUpdates()
                      myTableView.insertRows(at: [IndexPath(row: phone.count ,section: 1)], with: .automatic)
                    myTableView.endUpdates()}
                print("missing u ")
            } else if editing  {
                    print("heloo guys how u  doing g")
                    self.myTableView.setEditing(true, animated: true)
                      myTableView.beginUpdates()
                      myTableView.insertRows(at: [IndexPath(row: email.count ,section: 2)], with: .automatic)
                              myTableView.endUpdates()
                } else if editing {
                    print("hurra g")
                   // self.myTableView.setEditing(true, animated: true)
                      myTableView.beginUpdates()
                      myTableView.insertRows(at: [IndexPath(row: address.count ,section: 3)], with: .automatic)
                              myTableView.endUpdates()
                }

                else{
                    self.myTableView.setEditing(false, animated: true)
                    myTableView.beginUpdates()
                    self.myTableView.deleteRows(at: [IndexPath(row:phone.count, section: 1)], with: .automatic)
                    self.myTableView.endUpdates()
                }
            }
        // editing style function
        func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {

               if editingStyle == .delete{
                   self.fields.remove(at: indexPath.row)
                   self.myTableView.beginUpdates()
                       myTableView.deleteRows(at :[IndexPath(row : 0 , section: 0)], with: .fade)
                       self.myTableView.endUpdates()

               }else if editingStyle == .insert {
                    if indexPath.section == 1{
                        print("i am new")
                    self.myTableView.beginUpdates()
                    self.phone.insert("company", at: 1)
                        myTableView.insertRows(at: [IndexPath(row:0, section: 1)], with: .automatic)
                        self.myTableView.endUpdates()
                    } else if indexPath.section == 2{
                        print("dekho")
                        self.myTableView.beginUpdates()
                        self.email.insert("home", at: 0)
                        myTableView.insertRows(at: [IndexPath(row: 0, section: 2)], with: .automatic)
                        self.myTableView.endUpdates()
                    }
                    else if indexPath.section == 3{
                        self.myTableView.beginUpdates()
                        self.address.insert("home", at: 0)
                        myTableView.insertRows(at: [IndexPath(row: 0, section: 3)], with: .automatic)
                        self.myTableView.endUpdates()
                    }
                }

                }
        // different section with custom cells
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
                switch indexPath.section{
                case 0:
                    let TextCell = tableView.dequeueReusableCell(withIdentifier: "TextTableViewCell", for: indexPath) as! TextTableViewCell
                                     TextCell.placeHolder.placeholder = fields[indexPath.row]
                                     TextCell.selectionStyle = .none
                                         return TextCell
                case 1:
                    if  indexPath.row == self.phone.count && self.isEditing == true{
                                  print(indexPath.row)
                                let hellocell  = tableView.dequeueReusableCell(withIdentifier: "ContactMenuTableViewCell", for: indexPath) as! ContactMenuTableViewCell
                               hellocell.newcontact.text = "Insert a new cell"
                                  return hellocell
                               }
                     let phoneCell = tableView.dequeueReusableCell(withIdentifier: "PhoneTableViewCell", for: indexPath) as! PhoneTableViewCell
                               // phoneCell.configure(with: "Add Phone", imageName: "gear")
                 phoneCell.addPhone.text = phone[indexPath.row]
                                return phoneCell
               case 2:
                if  indexPath.row == self.email.count && self.isEditing == true{
                   print(indexPath.row)
                 let insertCell = tableView.dequeueReusableCell(withIdentifier: "TextTableViewCell", for: indexPath) as! TextTableViewCell
                 //insertCell.emailInsert.placeholder = fields[indexPath.row]
                                             insertCell.selectionStyle = .none
                                                 return insertCell
                }
               if  indexPath.row == self.email.count && self.isEditing == true{
                           print(indexPath.row)
                         let hellocell  = tableView.dequeueReusableCell(withIdentifier: "ContactMenuTableViewCell", for: indexPath) as! ContactMenuTableViewCell
                        hellocell.newcontact.text = "Insert a new cell"
                           return hellocell
                        }
                    let emailCell = tableView.dequeueReusableCell(withIdentifier: "EmailTableViewCell", for: indexPath) as! EmailTableViewCell
                emailCell.emaillabel.text = email[indexPath.row]
                    return emailCell
                case 3:

                   let addressCell = tableView.dequeueReusableCell(withIdentifier: "AddressTableViewCell", for: indexPath) as! AddressTableViewCell
                   addressCell.addressLabel.text = address[indexPath.row]
                   return addressCell
                default:
                    return UITableViewCell()
                }

           // number of rows function
         func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            if section == 1{
                if self.isEditing{
                     return phone.count + 1
                }else{
                    return phone.count
                }
            }  else if section == 2{
                if self.isEditing{
                     return email.count + 1
                }else{
                    return email.count
                }
            } else if section == 3{
                return address.count
            }else{
               return  fields.count
            }

            }

    // how to insert new row into specific section of tableview by tapping on existing cell of that section
    // also how to disable set editing function on other section while inserting row
    // how to achieve insert cell functionality
    // i am designing a layout of edit contact like your iOS contact screen
    // if anybody have code please help me out
// any help would be appreciated
//tableview cells
//inserting new rows
// swipe to delete row
//swift
// uitableview

//A UITableViewCell object is a specialized type of view that manages the content of a single table row. You use cells primarily to organize and present your app's custom content, but UITableViewCell provides some specific customizations to support table-related behaviors, including:
Applying a selection or highlight color to the cell.
Adding standard accessory views, such as a detail or disclosure control.
Putting the cell into an editable state.
Indenting the cell's content to create a visual hierarchy in your table.
Your app's content occupies most of the cell's bounds, but the cell may adjust that space to make room for other content. Cells display accessory views on the trailing edge of their content area. When you put your table into edit mode, the cell adds a delete control to the leading edge of its content area, and optionally swaps out an accessory view for a reorder control.


text:
Q: App building for a beginner in Smalltalk I am a newbie to Smalltalk technology. My experience in programming is with C and C++. I would like to understand the design methodology of smalltalk. Could any one suggest some simple real-time apps developed in smalltalk which can help a beginner like me to explore into avenues of smalltalk.
Currently I am experimenting my smalltalk learning on Pharo.

A: One of the best resources for learning Smalltalk is almost endless browsing of the Smalltalk image under your finger tips using class browser. Almost whole language and IDE implementation is available for browsing, end even debugging. At the beginning it can be overwhelming, at least it was for me, but it is well worth of effort. Just do not expect to groak it whole in few evenings.  And if you are really curious, in Pharo and Squeak you can even browse and hack your own VM.
As for other resources, if you can get hold of "Smalltalk Design Patterns" by Kent Beck, I whole heartily recommend it. Stephane Ducase has compiled collection of free Smalltalk books: http://stephane.ducasse.free.fr/FreeBooks.html . Although not updated for quite some time, late David N. Smith Smalltalk faq is still brilliant in exposing many not so obvious angles to new comers, and also to some less sharp regulars like me.
For real time apps, I do not think there are some hard core real time apps like driving the ignition of combustion engine. But there are many close to real time apps, for instance I have worked on stock exchange trading system written in Smalltalk, but it I am afraid it is proprietary. As for very simple examples, I think Seaside includes Comet counter demo, and I think Dolphin Smalltalk still includes chat example.
As closing remarks, you will find that everything in Smalltalk is, well small. From methods to design. So small that in the first moment you start to wonder ok, everything is simple and obvious but where is the "real stuff"? It takes time to accept that in Smalltalk the real stuff is in that small stuff an its interaction. It is a bit of a stretch but Smalltalk is to extent Haiku like :)
Good luck and keep it small!

A: I'd guess that Pharo is by now most widely used for building web apps, and as a research platform. Check out Seaside, to see how to build web apps with Pharo. Download Seaside's one click image, and look at the Sushi store inside.
If you're intending to build more traditional GUI apps, that's possible. But it's becoming increasingly niche. Here's how to deploy apps built in Pharo.

A: I recently started using Pharo myself. Just find something you'd like to do, that's reasonably simple, and figure out how to do it with the tools at your disposal. For instance, I started rendering fractals and animating image transitions with the help of (for example) the Form and Matrix classes.
You might also want to join one of the Pharo listservs because they are awfully nice to beginners like ourselves, and just as helpful.
Also: start reading Pharo by Example. And realize that a lot of Squeak documentation carries over into Pharo, because Pharo forked from Squeak. (Too bad they don't have Complex numbers in Pharo yet.)

A: I reccomend getting yourself a copy of Squeak. While "Squeak" is a dialect of Smalltalk, I'd highly reccomend going through the free to download pdf book Squeak By Example. One more book which is perhaps the "Daddy" is Smalltalk 80, aka "the Blue Book". CHEERS


text:
Q: How to access the variable permalink in this JavaScript function? Good I have this function that I need to access the contents of the variable called permalink using console.log()
but I can not get it
I jump that the variable permalink is not defined. But when I take away the! of! function
If I can access permalink, I'm new to this, thank you in advance for your help and comments that may be useful to me.
This I need to do without editing the function since it is from an external source
This is my code.

!function(PriTwo, document) {
  var DocumentProtocol =
    document.location.protocol != 'https:' &&
    document.location.protocol != 'http:'
      ? 'https:'
      : document.location.protocol;
  var permalink = DocumentProtocol + '//google.com';
  var permalink_two = DocumentProtocol + '//facebook.com';
};

console.log(permalink);

I need that console.log is out of the function, it can not be inside.
Any ideas?

A: you have created Immediately-Invoked Function Expression (IIFE) but still, you are not adding parenthesis in the end so function not called yet. for more information about IIFE read this.
also, you can not access a local variable declared inside a function you either need to specify permalink  as a global variable. here is a link for a scope in js
For more about Self-executing anonymous function click here.
Try this.

    var permalink='';
    var permalink_two='';
    !(function() {
    console.log('dd');
    var DocumentProtocol =
        document.location.protocol != 'https:' &&
        document.location.protocol != 'http:'
          ? 'https:'
          : document.location.protocol;
          console.log('a');
      permalink = DocumentProtocol + '//google.com';
      permalink_two = DocumentProtocol + '//facebook.com';

    })();

    console.log(permalink);
    console.log(permalink_two);

or you can return the array from inside the simple function, and access array using the key.
function PriTwo() {
            var DocumentProtocol = (document.location.protocol != "https:" && document.location.protocol != "http:") ? "https:" : document.location.protocol;
            var permalink=[];
            permalink.push(DocumentProtocol + '//google.com');
            permalink.push(DocumentProtocol + '//facebook.com');
             return permalink;
   }
  var link = PriTwo();
  console.log(link[0]);
  console.log(link[1]);


text:
Q: Correct Format of Harvest API OAuth2 Redirect URL in iOS Application What is the correct format for a redirect URL when authenticating with OAuth2 and the Harvest API from an iOS application?
oauth.com states that a redirect URL for a native application can look like myapp://callback. Problem is, Harvest doesn't accept such a redirect URL. It seems to require prefixing it with http/https, which causes problems when redirecting back to the iOS application at the end of the authentication flow. I don't seem to find anything relevant in the Harvest API documentation.
I have added a URL Type in Xcode where I set the Identifier value to com.example.myapp and the URL Schemes value to MyApp. No matter what redirect URL I specify (given the format mentioned above) in Harvest the authentication flow always complains that Safari cannot open the page because the server cannot be found. I am able to open the app manually with the appname:// URL from the

A: It sounds like you're looking for the URL to use regarding redirection from a web call.  I'm not certain on oath2, but on SAML it is something like
https://where you are signing in/SSOpage?RelayState=https://where you are going
I hope this helps get you to your answer.

A: If anyone else has this issue, the identifier and URL Schemes should not be com.example.myapp and MyApp, respectively. You only need to set the URL Scheme to com.example.myapp