text:
Q: Make library imports in tests compatible with two different packages that contain the library I have a pretty weird scenario and goal. I need to make exact same tests work without any changes against a library that might be imported from two different packages.
There is a GIT repo with a big python package big_sdk and inside it there is a small library big_sdk.small_lib.
I'm extracting the small_lib library into a separate GIT repo and separate package small_package.small_lib.
The code will be living in both places for some time, so I want the code to be exactly the same in both places. (This allows significantly easier GIT workflow without any history merging problems.)
There is no problem with the small_lib library itself - it only uses relative imports inside, so the exact same code can live and work in a different package and repo.
The problem is with tests. The tests live in big_sdk/tests/small_lib_tests and use absolute imports:
from big_sdk import small_lib
from big_sdk.small_lib import some_module
from big_sdk.small_lib import some_func

When extracting the test code to the small repo, this has to be changed to
from small_package import small_lib
from small_package.small_lib import some_module
from small_package.small_lib import some_func

This is problematic due to breaking GIT history.
I want to find a different way.
Requirements:

*

*The goal is to make all code in big_sdk/tests/small_lib_tests/ and small_package/tests/ directories exactly the same. (There might be different files outside of those dirs though).

*The code in big_sdk/* should not mention small_package. This rules out a simple try/except approach with multiple import sources.

I have tried to switch the tests to import from a separate module small_library.py that imports big_sdk.small_lib in one repo and small_package.small_lib in another repo. It did not work for deeper imports like from big_sdk.small_lib import some_module. I then tried to use hacks that modified sys.modules['component_library'] = big_sdk.small_lib, and it partially worked, but required "registering" all sub-modules (sys.modules['component_library.*']) which was not easy and too hacky.

A: I think I'll just make the small_lib dir and the small_lib_tests dir siblings.
Before:
big_sdk/small_lib/*
tests/small_lib_tests/*

after:
big_sdk/small_lib/*
big_sdk/small_lib_tests/*

This looks somewhat ugly, but it allows relative imports from the test code.
from .. import small_lib
from ..small_lib import some_module
from ..small_lib import some_func

This way big_sdk and small_package are never mentioned in the code.


text:
Q: API level mismatch in ionic cordova to get APK I have Created the android application using ionic and angularjs.when i try to build and get apk following error appers.!{this is the error}]1. to resolve this error i have done some changes
1.in config file i change the minsdk and trget sdk values to api level 23
2.in gradle.build file change the sdkversion to api level 23.
but nothing changes.i need to get apk for apilevel 23(MAshmillow).
how to solve this error..?

A: Find the sql path and execute the following

./sdkmanager.bat --licenses
After this you can review each license and accept them accordingly.
Edit: To add api version do the following:
<preference name="android-minSdkVersion" value="23" />

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to calculate mean of multiple measures after removing outliers in R I have three independent measures of a variable, and they are subject to a lot of noise and sporadic sources of error that can be quite large. I would like to discard the value furthest away from the others, remember which one is discarded, and then calculate the mean with the remaining two. For example,
a   b   c
15  6   7
11  10  3
5   12  6

would become
a   b   c   ave     discard
15  6   7   6.5     15
11  10  3   10.5    3
5   12  6   5.5     12

A: You question is underspecified. Say the three values are 1000, 2000 and 3000. Which would you discard? Should the answer be 1500 or 2500?
If all you're looking for is a robust measure of central tendency, the median might be a good start (?median in R).

A: Try:
ddf
   a  b c
1 15  6 7
2 11 10 3
3  5 12 6

ddf$ave = apply(ddf[1:3], 1, function(x) {
 x = sort(x)
 ifelse(abs(x[1]-x[2]) > abs(x[2]-x[3]), mean(x[2:3]), mean(x[1:2]))
 }
 )

ddf$discard = apply(ddf[1:3], 1, function(x) {
 x = sort(x)
 ifelse(abs(x[1]-x[2]) > abs(x[2]-x[3]), x[1], x[3])
 }
 )

ddf
   a  b c  ave discard
1 15  6 7  6.5      15
2 11 10 3 10.5       3
3  5 12 6  5.5      12


text:
Q: Help needed with a proof Let z: R-> R be a differentiable function such that z(x)>x^2. Prove that z'(x) is not bounded. I tried assuming that z'(x) is bounded and attempted to derive a contradiction, but now I am stuck.

A: Let $x>z(0)>0$ be arbitrary.  Then $z(x) - z(0) > x^2 - z(0) > x^2-x$.  By the mean value theorem, there is some $c \in (0,x)$ such that $\displaystyle z^\prime(c) = \frac{z(x)-z(0)}{x-0} > \frac{x^2-x}{x} = x-1$.  Since $x$ can be as large as we like, it follows that $z^\prime(c)$ can be as large as we like, so $z^\prime$ is not a bounded function.
You can also do this by using the fundamental theorem of calculus and contradiction.  Suppose for contradiction that $z^\prime(x) < M$ for some $M>0$.  Then $\displaystyle z(a)-z(0) = \int_0^a z^\prime(x)\ dx \leq \int_0^a M = Ma$, so $z(x) \leq Mx+z(0)$.  As $z(0) > 0$, we get $(M+z(0))^2 > M(M+z(0)) + z(0) \geq z(M+z(0))$, a contradiction.


text:
Q: How to efficiently pick a line on a grid which passes through certain points Suppose I have a 30 x 30 grid and four (x,y) coordinates on them which represent goblins.
I want to place a line that is 1 x 10 wide and long that passes through as many goblins as possible.
What is an efficient way that gets you one answer?
It was too expensive to test every combination of source to target line so I need something that gives me a decent answer, doesn't have to be perfect.

A: Just to add some details on @GilbertLeBlanc answer:
"Take any two of the four goblins and connect them with a line."
If you choose them randomly:

*

*if no three are on the same line, then you have the best answer;

*if all four are on the same line, then you have the best answer;

*if three are aligned and one is not, your probability to get the best answer is 1/2.

All in all, already quite good.


text:
Q: How to highlight a row in a table on certain occasions I am not familiar with css or javascript and I am wondering how to have a notification highlight similar to the case when a person commented on a Facebook post, and upon clicking, you will be directed to the said comment with temporary highlight.
Thanks in advance

A: You can use the CSS3 animation property. Just make sure to add the -webkit- vendor prefix for it to work in all major browsers. The vendor prefixes you need for other CSS3 properties can be found at caniuse.com.
The trick is to add a special class to the element you want highlighted, and applying the animation to that class with CSS.
Try it:

.post{
    padding: 1em;
    margin: .2em;
    background: #ffffff;
    border: 1px solid #eceded;
}

.post.highlighted {
    -webkit-animation: highlight 6s ease;
    animation:  highlight 6s ease;
}

@-webkit-keyframes highlight {
    from { background: #ddddff }
    to   { background: #ffffff }
}
@keyframes highlight {
    from { background: #ddddff }
    to   { background: #ffffff }
}

This is just a regular post

But this one's new!

A: It looks like you have a few problems you need to solve. I'll walk you through the logic behind each problem. Some of these problems already have solutions posted online, so in those cases I've linked you to the appropriate pages.
1) Respond to a click on an element
http://clubmate.fi/detect-click-with-pure-javascript/
2) Scroll to a specific part of the page
Smooth scroll to specific div on click
3) Highlight an element
This involves changing attributes of an html element, for example the background color. This can be done by changing the class with javascript, and using css to style the element differently when it has the right class
CSS:
.element {
    background-color: #0000ff; /* A blue background by default */
}
.element.highlighted {
    background-color: #ff0000; /* A red background when the element is highlighted */
}

JS:
document.getElementsByClassname('element')[0].setAttribute('class', 'element highlighted');

Now you just have to run that line of javascript at the appropriate time (after the scrolling has ended - step 2 should give insight on how to do this)
4) Remove the highlighting after a delay
Take advantage of javascript's setTimeout function to remove the highlight class after a delay:
JS:
setTimeout(function() {
    document.getElementsByClassname('element')[0].setAttribute('class', 'element'); // Replace "element highlighted" with just "element"
}, 1000); // 1000 means a one-second delay


text:
Q: Conceptual understanding for pressure inside incompressible fluid I'm was thinking about incompressible fluid and how pressure effects it and I came across this idea that I'm not sure if it's correct. I would like some correction along with my current understanding. Thank you in advanced.
From what I know so far (which may be wrong) is when you have a object placed in water, the bouyancy is equal to the weight of water deplaced by that object. If we then have a cup with water (let's say height h) when we place an object inside the water that doesn't fully drown, it will make the water level from the cup a bit higher (say h+a). I feel like if this is possible the reverse should also be possible. If our object is a rectangle, I think by putting a cover that has a hole that's size of rectangle's side area and pushing on water will make the water level go down (until it reaches original height h) and make the rectangle float up.
Now, is this possible? If it is, can I get more explanation about how the pressure outside of water can affect this? Is it possible that the atmospheric is so high that human can walk on water?

A: Since water is incompressible, it's volume is constant. This means, if your cover has the area $A_c$ and the area of the bottom side of the cuboid is $A_o$, then pushing the cover down by $a$ means decreasing the volume beneath it by $aA_c$. In order to conserve volume, the cuboid has to rise by $aA_c/A_o$, so what you describe will indeed happen. The nice thing about this is, that one does not even have to think about force or pressure; this is a purely geometric problem.
Now about the outside pressure. The thing one needs to keep in mind is that in most situations, it will impose a force both on the cover and the cuboid. As a consequence, it won't be possible to walk on water, unless most mass of the atmosphere is concentrated below your shoulders (in which case the pressure would probably crush you), because it pushes you downward just (almost) as much as the water.
Remark: Actually, at very high pressures, water can of course be further compressed, however those pressures are normally not encountered in everyday life.


text:
Q: Is there a way to run the trigger in separate thread in MySQL? I have a PHP web application and when inserted in a table, I have written a trigger to calculate some scores and this takes time. My PHP application waits till the trigger completes.
Can this trigger run in a separate thread such that my application will not wait for the completion of the trigger?

A: No.
But as Bill Clinton would have said, "and I'll tell you why."
One of the big advantages of a trigger is that the actions of the trigger are contained within the transaction of the original statement that fired the trigger.  This is a Good Thing from the Relational mindset because we like ACID compliance.
Now if you do not need that ACID compliance, and it is ok for the triggered actions to take effect "eventually", then remove the trigger and make an 'actions' table.  Then either the trigger can drop something into the actions table or your PHP code might do it.  You can have a job querying this table once/second or so, and if it finds anything it executes it.  Don't worry about performance on the daemon, a once/second query of a table that is usually empty is nothing.


text:
Q: Is there an off-the-shelf database solution similar to asihollywooddatabase.com or imdb? What off-the-shelf database solutions would allow me to do the same thing as asihollywooddatabase or something similar to IMDB without having to write the software from scratch.
I have little knowledge of html or website design so something without these requirements would be preferred.

A: What are you going to actually do with the data, if you just want to save it to look at yourself and run simple(r) queries then microsoft access as part of office suite is a great tool, if your building a website, mysql is free to use and has alot of help and guidance available on the internet.
either way dont try and do it all yourself, if you get stuck, google is your friend ;)


text:
Q: RTP AAC timestamps issue I'm trying to stream AAC audio to Wowza server via RTP. I managed to make it work but I hear alternately the sound very fast and then a 1s blank. Sample rate is 22050 and frames per packet is 1024.
Currently my timestamps are generated like that :
long _timestamp;

//--- called each time I have to send a new AAC packet ---//
-(void) updateTimestamp{
    if(! _timestamp)
        _timestamp = random();
    else
        _timestamp += 1024;
    rtptime = big_endian(_timestamp);
}

is it correct ? I don't know why the output is that weird ans any help would be apreciated :)

A: Yes, the logic is correct, but instead of long, use unsigned long, so that it takes care of rounding when unsigned long reaches max value.


text:
Q: Convergence in probability of the sum of random variables Let $\{\xi_t\}$ be i.i.d random variables (may not have expectation in general) and $\{z_t^{n}\}$ - i.i.d. Bernoulli random variables ($t\in \mathbb{Z}_+$) such that
$$
z_t^{n} =
\begin{cases}
0 \ \mbox{with probability} \ (1-\frac{1}{\sqrt{n}}),\\
1  \ \mbox{with probability} \frac{1}{\sqrt{n}},
\end{cases}
$$
$\{z_t^n\}$ and $\{\xi_t\}$ are independent of each other. So obviously random variables $z_t^{n}\xi_t$ would be $o_p(1)$.
But can we say that
$$
\frac1n \sum_{t=1}^nz_t^{n}\xi_t \stackrel{P}\rightarrow 0, \ n\to \infty?
$$
Thanks in advance!

A: Let $\varphi$ denote the characteristic function of $\xi_t$.
The computation of the characteristic function $\varphi_n$ of $\frac 1n\sum_{t=1}^nz_t^n\xi_t$ gives
$$\varphi_n(s)=\left(1-\frac 1{\sqrt n}+\frac 1{\sqrt n} \varphi(s/n)\right)^n.$$
Hence $\frac 1n\sum_{t=1}^nz_t^n\xi_t\to 0$ in distribution under some assumptions on the moments of $\xi_t$, and since the limit is constant, in probability.
Actually, by a symmetrization argument, one can see that a necessary and sufficient condition for $\frac 1n\sum_{t=1}^n\xi_tz_t^n\to 0$ in probability to hold is
$$\quad \forall s\in\Bbb R,\quad \lim_{n\to \infty}\sqrt n\left(\left|\varphi\left(\frac sn\right)\right|-1\right)=0.$$


text:
Q: Want to turn off "note" level messages in GCC When I compile a C (no pluses) program using GCC, there are several levels of messages possible, like warning, error, and note.  The note messages are useless and distracting.  How do I make them go away using the command line?  (I don't use any sort of IDE.)
Example: /home/user/src9/AllBack3.c:129:9: note: each undeclared identifier is reported only once for each function it appears in.

A: Pass the -fcompare-debug-second option to gcc.

gcc's internal API has a diagnostic_inhibit_note() function which turns any "note:" messages off, but that is only serviceable via the unexpected -fcompare-debug-second command line switch, defined here.
Fortunately, turning notes off is its only effect, unless the -fcompare-debug or the -fdump-final-insns options are also used, which afaik are only for debugging the compiler itself.

A: You can use -w which also suppresses warnings.
For GCC, -w will not suppress the note you mentioned, probably because it is shown instead of another error. clang's -w on the other hand suppresses that too.


text:
Q: Use MySQL to create .htaccess file URL rewrite parameters I have a website with about a 100 pages for which the sample .htaccess file has
RewriteRule    ^1/?$    page1.php    [NC,L]
RewriteRule    ^2/?$    page2.php    [NC,L]
RewriteRule    ^3/?$    page3.php    [NC,L]

The problem is these pages get a lot of redirection between one another and while adding
header("location: page1.php");

works, I wish to populate this using MySQL.
I can instead hard code is to
header("location: /1");

but if one of the entries in the .htaccess file changes, I have to change in many places.
So my question is can this be controlled by MySQL, like if I have a simple table of
(id,page) values (1,page1.php)

and .htaccess gets populated based on this MySQL table.
What would be the best way to achieve this, if its possible.
Thanks.

A: You should use RewriteMap.
It uses text file that is mentioned in .htaccess and can be used for mapping 'something' to 'something' in RewriteRule.
Something like this:
RewriteMap p2f txt:/path/to/map.txt
RewriteRule ^([^/]+)/?$ /{p2f:$1|notfound.php} [L]

map.txt would be:
1 page1.php
2 page2.php
...

Apache monitoring the file changes and re-loaded it automatically.
You will need to change your process so when something updated in database, the text file is updated (SELECT INTO OUTFILE can be used for this).
It is possible to query database directly, however when I did testing long time ago it was faster with the file.


text:
Q: Android preferences issue I'm trying to make a preference screen for my android application, but I'm failing completely. I'm following this guide. When I try to install the application, I get this error message, and it won't install the app on my phone:
[2012-04-10 12:54:45 - AndroidCurrencyConverter] ------------------------------
[2012-04-10 12:54:45 - AndroidCurrencyConverter] Android Launch!
[2012-04-10 12:54:45 - AndroidCurrencyConverter] adb is running normally.
[2012-04-10 12:54:45 - AndroidCurrencyConverter] Performing ValutaConverter.namespace.AndroidValutaConverterActivity activity launch
[2012-04-10 12:54:45 - AndroidCurrencyConverter] Automatic Target Mode: using device '3134BC2BBCA800EC'
[2012-04-10 12:54:45 - AndroidCurrencyConverter] Uploading AndroidCurrencyConverter.apk onto device '3134BC2BBCA800EC'
[2012-04-10 12:54:46 - AndroidCurrencyConverter] Installing AndroidCurrencyConverter.apk...
[2012-04-10 12:54:49 - AndroidCurrencyConverter] Success!
[2012-04-10 12:54:49 - AndroidCurrencyConverter] Starting activity ValutaConverter.namespace.AndroidValutaConverterActivity on device 3134BC2BBCA800EC
[2012-04-10 12:54:52 - AndroidCurrencyConverter] ActivityManager: Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=ValutaConverter.namespace/.AndroidValutaConverterActivity }
[2012-04-10 12:54:52 - AndroidCurrencyConverter] ActivityManager: java.lang.SecurityException: Permission Denial: starting Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=ValutaConverter.namespace/.AndroidValutaConverterActivity } from null (pid=11486, uid=2000) requires android.permission.INTERNET
[2012-04-10 12:54:52 - AndroidCurrencyConverter] ActivityManager: at android.os.Parcel.readException(Parcel.java:1327)
[2012-04-10 12:54:52 - AndroidCurrencyConverter] ActivityManager: at android.os.Parcel.readException(Parcel.java:1281)
[2012-04-10 12:54:52 - AndroidCurrencyConverter] ActivityManager: at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:1631)
[2012-04-10 12:54:52 - AndroidCurrencyConverter] ActivityManager: at com.android.commands.am.Am.runStart(Am.java:433)
[2012-04-10 12:54:52 - AndroidCurrencyConverter] ActivityManager: at com.android.commands.am.Am.run(Am.java:107)
[2012-04-10 12:54:52 - AndroidCurrencyConverter] ActivityManager: at com.android.commands.am.Am.main(Am.java:80)
[2012-04-10 12:54:52 - AndroidCurrencyConverter] ActivityManager: at com.android.internal.os.RuntimeInit.finishInit(Native Method)
[2012-04-10 12:54:52 - AndroidCurrencyConverter] ActivityManager: at com.android.internal.os.RuntimeInit.main(RuntimeInit.java:238)
[2012-04-10 12:54:52 - AndroidCurrencyConverter] ActivityManager: at dalvik.system.NativeStart.main(Native Method)

What I understood from this code was that when it tries to start the Intent, it fails because it requires android.permission.INTERNET. But this is already defined in my manifest file.
I had the app working at some point, but I added a few things to my activity, added another activity, and some XML files. After this, it won't install the app on the phone. What I added was:
In the activity class:
addPreferencesFromResource(R.xml.preferences);

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    menu.add(Menu.NONE, 0, 0, "Show current settings");
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case 0:
        startActivity(new Intent(this, ShowSettingsActivity.class));
        return true;
    }
    return false;
}

If you need any other information about the code or the likes of that, I will gladly post some of it.
Help!

A: It should be,
<uses-permission
        android:name="android.permission.INTERNET" />
 <application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <activity
        android:configChanges="orientation|keyboardHidden|screenSize"
        android:label="@string/app_name"
        android:name=".AndroidValutaConverterActivity"
        android:theme="@android:style/Theme.DeviceDefault" >
        <intent-filter >
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".ShowSettingsActivity"/>
</application>

remove it from activity tag in your manifest file.

A: Indeed, but your are not allowing the INTERNET permission in the manifest (instead, you explictely say that the activity requires the INTERNET permission).
You should have a <permission> element at the root of the manifest, as explained in the doc.

A: Two things to check.

*

*Your activity is extending PreferenceActivity, and

*That your layout has a default ListView with the id android:list
<ListView
    android:id="@+id/android:list"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

Also you may want to think about implementing OnSharedPreferenceChangeListener in your activity if you need to  handle preference changes.


text:
Q: $(document).on click handler and standard click handler behaving differently on iOS I generally bind click handlers using the form,
$(document).on('click', 'element', function() { ... });

to avoid issues with elements being loaded later. This was working correctly on desktop browsers (and Chrome emulating iPhone), but on an actual iPhone this was not working (and I tried solutions like 'cursor: pointer;')
I noticed that another button was working, using the standard click handler. I changed my new button to use
$('element').click(function() { ... });

and it started working. Why are these two methods of applying a click handler operating differently on iOS?

A: I looked at the jquery source code, and they are the same (both .click and on('click') use the same function which is the .on.
.click
jQuery.each( ( "blur focus focusin focusout resize scroll click dblclick " +
    "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
    "change select submit keydown keypress keyup contextmenu" ).split( " " ),
    function( i, name ) {

    // Handle event binding
    jQuery.fn[ name ] = function( data, fn ) {
        return arguments.length > 0 ?
            this.on( name, null, data, fn ) :
            this.trigger( name );
    };
} );

as you can see, $.click will eventually call .on (or .trigger if no arguments are present which is not your case)

A: I think this is happening due to 300ms delay for mobile browsers.
According to Google:

...mobile browsers will wait approximately 300ms from the time that
  you tap the button to fire the click event. The reason for this is
  that the browser is waiting to see if you are actually performing a
  double tap.

I faced same issue for one of my client project and for this I had used https://github.com/ftlabs/fastclick library for eliminating the 300ms delay between a physical tap and the firing of a click event on mobile browsers.
You can also try https://github.com/dave1010/jquery-fast-click
In same project I also faced double tap issue for dropdown menus and that was also due to 300ms delay.
Double tap issue was appearing in android browsers/devices so I detected the user agent and applied the a custom function to handle that issue this might be helpful for you.
<?php
 if (user_agent() == 'android') {
    $handleClick = "onclick=\"checkClicks('$base_url/index.php')\"";
    $homePage = "#";
} else {
    $handleClick = " ";
    $homePage = "index.php";
}
?>

You can also try some available plugins to handle this issue if you face.
https://github.com/dachcom-digital/jquery-doubleTapToGo
https://github.com/zenopopovici/DoubleTapToGo
This might be helpful for you as well.
Edited
The event handler is bound to an element higher up the DOM tree (in this case, the document) and will be executed when an event reaches that element having originated on an element matching the selector.
This is possible because most DOM events bubble up the tree from the point of origin. If you click on the #id element, a click event is generated that will bubble up through all of the ancestor elements (side note: there is actually a phase before this, called the 'capture phase', when the event comes down the tree to the target). You can capture the event on any of those ancestors.
The second example binds the event handler directly to the element. The event will still bubble (unless you prevent that in the handler) but since the handler is bound to the target, you won't see the effects of this process.
By delegating an event handler, you can ensure it is executed for elements that did not exist in the DOM at the time of binding. If your #id element was created after your second example, your handler would never execute. By binding to an element that you know is definitely in the DOM at the time of execution, you ensure that your handler will actually be attached to something and can be executed as appropriate later on.
It's probably not working due to one of:

*

*Not using recent version of jQuery

*Not wrapping your code inside of DOM ready

*or you are doing something which causes the event not to bubble up to the listener on the document.

To capture events on elements which are created AFTER declaring your event listeners - you should bind to a parent element, or element higher in the hierarchy.
For example:
$(document).ready(function() {
    // This WILL work because we are listening on the 'document',
    // for a click on an element with an ID of #test-element
    $(document).on("click","#test-element",function() {
        alert("click bound to document listening for #test-element");
    });

    // This will NOT work because there is no '#test-element' ... yet
    $("#test-element").on("click",function() {
        alert("click bound directly to #test-element");
    });

    // Create the dynamic element '#test-element'
    $('body').append('
Click mee
');
});

In this example, only the "bound to document" alert will fire.
JSFiddle with jQuery 1.9.1


text:
Q: Ubuntu 14.04 How do I fix the imaplib.readonly error? I'm trying to use an imap script to view emails from a server. My script is able to log in fine, I get the 'OK Logged in' message, it's able to list the mailvoxes and dump untagged responses. After this, the message is as follows:
  File "imap_email.py", line 134, in <module>
    mailbox = get_mailbox(connection)
  File "imap_email.py", line 98, in get_mailbox
    rv, data = connection.select(EMAIL_FOLDER)
  File "/usr/lib/python2.7/imaplib.py", line 671, in select
    raise self.readonly('%s is not writable' % mailbox)
imaplib.readonly: INBOX is not writable

I was earlier getting an error that stated that imaplib couldn't parse the X-Original-To header. I removed that by adding "enable_original_recipient = no" to my postfix's main.cf.
Can somebody explain to me what this error is and possible causes for it? IMAP, SMTP, Postfix and Dovecot are all new to me, I'm a newbie.
My current setup involves a client and server VM, both running Ubuntu 14.04 and identical in every way. I have 1 user setup on each named client1 and server1 respectively, they are the ones receiving/sending emails. I should also note that I'm able to send (smtp) emails fine and examine my mailbox through curl commands.


text:
Q: Having a confusion about "to be" verbs! We know "am/is/are/was/were" are "to be" verb but some people say those verb are "be verb".which is correct? I think "to be" sounds like infinitive.Am I wrong?

A: Infinitives in English are sometimes described as 'to infinitives' (eg "I like to run in the park.") and 'infinitives without to' (eg "The teacher made us run in the park."). These are sometimes called 'full infinitives' and 'base infinitives' respectively.
As you can see from the comments to your question, some people regard the stem "to" as not being part of the infinitive, whereas others regard it as being an integral part of the infinitive. I am not qualified to enter into that discussion. However, this is the reason that some people say that the verb is "to be" and others say that the verb is "be." So, "No", you are not wrong, you are simply inexplicably involved in a grammatical debate that has not yet been fully resolved.


text:
Q: Requiring a package is causing an error Each time I am bundling scripts, I have following error:
ERROR in ./resources/assets/scripts/main.js
Module not found: Error: Can't resolve 'datatables.net-colreorder-bs4' in '/home/vagrant/sites/laravel/resources/assets/scripts'
 @ ./resources/assets/scripts/main.js 12:23-63

My webpack config js:
var path = require('path');
var webpack = require('webpack');

module.exports = {
    entry:  './resources/assets/scripts/main.js',
    output: {
        path: path.resolve(__dirname, './public/js'),
        filename: 'mainBundle.js'
    },
    module: {
        loaders: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: 'babel-loader',
                query: {
                    presets: ['env']
                }
            }
        ]
    },
    stats: {
        colors: true
    },
    node: {
        fs: 'empty'
    },
    devtool: 'source-map'
};

And my main js file looks like this (no other modules are causing any problems).
var jszip = require('jszip');
var pdfmake = require('pdfmake');
var netBs4 = require('datatables.net-bs4')();
var netButtonsBs4 = require('datatables.net-buttons-bs4')();
var buttonsHtml5 = require('datatables.net-buttons/js/buttons.html5.js')();
var buttonsPrint = require('datatables.net-buttons/js/buttons.print.js')();
var netColreorderBs4 = require('datatables.net-colreorder-bs4')();
var netReponsiveBs4 = require('datatables.net-responsive-bs4')();

I checked the path and it is ok, I also changed the path to absolute but it did not have any effect.
package json:
"dependencies": {
        "add": "^2.0.6",
        "babel-core": "^6.26.0",
        "babel-loader": "^7.1.2",
        "chart.js": "^2.7.1",
        "datatables.net-bs4": "^1.10.16",
        "datatables.net-buttons-bs4": "^1.5.1",
        "datatables.net-colreorder-bs4": "^1.4.1",
        "datatables.net-responsive-bs4": "^2.2.1",
        "gulp-changed": "^3.2.0",
        "gulp-debug": "^3.2.0",
        "jquery": "^3.2.1",
        "jquery-ui": "^1.12.1",
        "jszip": "^3.1.5",

This question is still not resolved, for some reason 'datatables.net-colreorder-bs4' will not be found when using npm... I decided to load it as a ready to use bundle instead of webpacking it...

A: The only thing that may be missing is resolve but I'm not sure if webpack looks in node_modules by default:
module.exports = {
  entry:  './resources/assets/scripts/main.js',
  output: {
      path: path.resolve(__dirname, './public/js'),
      filename: 'mainBundle.js'
  },
  resolve: {
    modules: [
      resolve("./node_modules/")
    ]
  },

Would be strange if that is the case because other modules are found.

A: To use pdfmake in client side mode, you need to use build version directly:
window.pdfMake = require('pdfmake/build/pdfmake.js');
var vfs = require('pdfmake/build/vfs_fonts.js');
window.pdfMake.vfs = vfs.pdfMake.vfs;


text:
Q: Non-cyclical keyboard layout changes in Ubuntu How do I use non-cyclical keyboard layout changes in Ubuntu 22?

I've tried using Gnome-tweaks to no avail.
Using toggle shortcuts works. E.g. if I bind Caps Lock (grp:caps_toggle in setxkbmap-speak) it works as expected - cycles through layouts. But when I use Left Ctrl to first layout; Right Ctrl to last layout those key combos do nothing.
What I want:

*

*press key or key combination A - get layout A

*press key or key combination A - no layout change, still layout A

*press key or key combination B - get layout B

I assume setxkbmap options below (which are selectable in Gnome Tweaks too) are a way to get what I want
grp:shift_caps_switch Caps Lock to first layout; Shift+Caps Lock to last layout
grp:win_menu_switch  Left Win to first layout; Right Win/Menu to last layout
grp:lctrl_rctrl_switch Left Ctrl to first layout; Right Ctrl to last layout
grp:lctrl_lwin_rctrl_menu Left Ctrl+Left Win to first layout; Right Ctrl+Menu to second layout

Please, help me find the answer

A: I'm still searching for a solution that will allow me to use combos like Left Ctrl + Left Super.
Meanwhile, if you're OK with using a more limited shortcut possibility space, here's a variant solution, using default tools:
Note: it will break your default layout cycling.

*

*Press Super (win)

*Type keyboard, go to Keyboard settings

*Scroll down, go to Keyboard shortcuts

*Scroll down, go to Custom shortcuts

*Add a custom shortcut

*

*Name: anything you like

*Command: setxkbmap -layout us (change us to the layout you want)

*Shortcut: set a shortcut you like

*Repeat adding shortcuts for as many layouts as you like


text:
Q: Opening a PDF file stored in a jar file with the desktop's default app I'm nearing the end of a program development for my computer science course. However, one of the requirements is to have a user manual within the app. I saved the user manual as a PDF inside Eclipse's workspace.
It is stored under "/Documents/PDF Manual.pdf". I originally used this code:
URL url = getClass().getResource( fileSeparator + "Documents" + fileSeparator + "PDF Manual.pdf");
           //fileSeparator = '/' on mac, & '\\' on windows
        File userManual = new File (url.toURI());
        if (userManual.exists())
        {
            Desktop.getDesktop().open(userManual);
        }

This works fine while running the project from eclipse, however URI returns a non hierarchical exception (as expected) when the program is exported to a jar file. I thought of playing around with url.toString(), using substring and replaceAll() to get rid of unwanted characters (%20 for the space), however this gave weird results and of course the code wouldn't work properly when it wasn't a jar file.
I looked at InputStream, however this is only used to read from a file and I cannot open the file using a desktop app.
Due to the process of submission, the pdf HAS to be saved inside the project folders.
Also, my code has to be platform independent (or at the very least, work on windows and mac) and thus manipulating file names becomes a lot more complicated. Any suggestions?
Edit:
After @SubOptimal 's help, this is the code I am now using:
String inputPdf = "Documents" + fileSeparator + "PDF Manual.pdf";
        InputStream manualAsStream = getClass().getClassLoader().getResourceAsStream(inputPdf);

        Path tempOutput = Files.createTempFile("TempManual", ".pdf");
        tempOutput.toFile().deleteOnExit();

        Files.copy(manualAsStream, tempOutput, StandardCopyOption.REPLACE_EXISTING);

        File userManual = new File (tempOutput.toFile().getPath());
        if (userManual.exists())
        {
            Desktop.getDesktop().open(userManual);
        }

This works on mac. However, on windows manualAsStream is null for some unknown reason.

A: Full working example. Tested in Windows environment.
file structure
.\REPL.java
.\doc\manual.pdf
.\manifest.mf

REPL.java
package sub.optimal;

import java.io.InputStream;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.awt.Desktop;

public class REPL {

    public static void main(String[] args) throws Exception {
        String inputPdf = "doc/manual.pdf";
        Path tempOutput = Files.createTempFile("TempManual", ".pdf");
        tempOutput.toFile().deleteOnExit();
        System.out.println("tempOutput: " + tempOutput);
        try (InputStream is = REPL.class.getClassLoader().getResourceAsStream(inputPdf)) {
            Files.copy(is, tempOutput, StandardCopyOption.REPLACE_EXISTING);
        }
        Desktop.getDesktop().open(tempOutput.toFile());
    }
}

manifest.mf
Main-Class: sub.optimal.REPL

compile
javac -d . REPL.java

create JAR
mkdir dist\
jar cvfm dist/REPL.jar MANIFEST.MF sub/optimal/REPL.class doc/manual.pdf

execute JAR
cd dist\
java -jar REPL.jar

A: Use getResourceAsStream instead of getResource
To write in the temp directory use createTempFile


text:
Q: How do I write an equivalent pyspark code for the following staement?     X_train[var] = np.where(X_train[var].isin(frequent_ls), X_train[var], 'Rare')

How can I replace numpy with pyspark sql function?

A: You define an udf function
from spark.sql import function as F
from pyspark.sql.types import StringType()

def dictonnary(x):
    if x in frequent_ls:
        return x
    else:
        return "rare"

replace = F.udf(lambda x: dictionnary(x), StrungType())

Xtrain = xtrain.withColumn("var2", replace(F.col("var")))

A: You can simply use the .isin operator:
import pyspark.sql.functions as F

X_train = (X_train
           .withColumn(var, F.when(X_train[var].isin(frequent_ls), X_train[var]).otherwise('Rare'))


text:
Q: Calculating cordanates with angles So basically I have the starting vectors and the angels but the code I'm working with only updates my angle and I'm trying to get to another vector.
var start_x = 0;
var start_y = 0;
var speed = 200;
var current_x; //This needs to be calculated
var current_y; //This needs to be calculated
var current_angle = 53;

How could I calculate the current X vector and Y vector using the speed and the starting positions? I've browsed around this site and others but I cant seem to find an answer.

A: Okay there you
Firstly you have speed, so you need to take a time frame too so let us assume we need the co-ordinates after 1s. The formula to measure Speed is V = S/T
where V is velocity(speed in a direction) S is distance and T is time.
Therefore S = VxT
According to your speed 200, Distance travelled in 1 second is 200M
now we have the angle too which you gave it as 53deg.
Hence we can draw an imaginary triangle to find (x,y) the new co-ordinates which are unknown.
To know x,y the formula is
y= sin(theta) x Distance
x = cos(theta) x Distance

where theta is equal to 53deg and distance is 200
hence (x,y) = ()
To be a bit more descriptive, in our imaginary triangle y is opposite and x is adjacent, and x,y are nothing but distances from 0,0 . There is a formula in trigonometry, which states that
Sin(theta) = opposite/Hypotenuse
 hence 53 = unknown/200
similarly
Cos(theta) = Adjacent/Hypotenuse
 hence 53 = unknown/200
 So after calculating we get the result (120.36,159.72)

So in java script you can use
// since Math.cos takes input in radians you  have to convert it into degrees.

    var speed = 200;
    var time = 1;
    var angle = 53;
    x = (Math.cos(angle*(Math.PI/100))* (speed*time);
    y = (Math.sin(angle*(Math.PI/100))* (speed*time);

We have calculated using radians not degrees, so you might need necessary conversion into  degrees but thats not difficult just interchange (x,y) to (y,x) which would be the result with degrees.

A: Vector math is hard so I would write a little class to do all the heavy lifting:

function LameVector(x,y) {
  this.startx = this.x = x;
  this.starty = this.y = y;
  this.angle = false;
  this.mag = 0;

  this.moveXY = function (x, y) {
    this.x += x;
    this.y += y;
    this.angle = Math.atan2(this.y - this.starty, this.x - this.startx) * 180 / Math.PI;
    this.mag = Math.sqrt(Math.pow(this.y - this.starty, 2) + Math.pow(this.x - this.startx, 2));
  }

  this.move = function (speed, angle) {
    var ang = angle / 180 * Math.PI;
    this.moveXY(speed * Math.cos(ang), speed * Math.sin(ang));
  }
}
var o = document.getElementById("out");
var vec1 = new LameVector(0, 0); // starting position 0,0
o.innerHTML += "start x " + vec1.x + ", start y " + vec1.y + "
";

vec1.move(200, 53); // move 200 units at angle 53 deg
o.innerHTML += "move1 x " + vec1.x + ", move1 y " + vec1.y + "
";

vec1.move(200, 27); // move 200 more units at angle 27 deg
o.innerHTML += "move2 x " + vec1.x + ", move2 y " + vec1.y + "
";

// can also get the angle and length
o.innerHTML += "final angle " + vec1.angle + ", magnitude " + vec1.mag + "
";

A: I've came across this problem before (Calculate the position of an orbiting object) and used the following.
You'll be using Math.cos() and Math.sin() methods and they take angles in radians as a parameter. So
var start_x = 0;
var start_y = 0;
var speed = 200;
var current_x; //This needs to be calculated
var current_y; //This needs to be calculated
var current_angle = 53;

// converting degrees to radian
var angleInRad = current_angle * (Math.PI / 180);

var time = 1; // second
var distance = speed * time;

// calculate the x and y values
current_x = Math.cos(angleInRad) * distance;
current_y = Math.sin(angleInRad) * distance;

console.log(current_x, current_y); // 120.36, 159.72


text:
Q: How to copy file in the server to another folder with putty I would like to copy or move some file a.xml from /tmp to another folder in the same server /var/lib/myfolder.
I tried the following with putty:
user@server:/tmp$ mv a.xml /var/lib/myfolder

I get the error message, that this operation is not allowed.
How can I copy or move this file to another folder?
Update:
Error message:

mv a.xml is not possible: The operation is not allowed

A: Try cp and then rm the source file.
cp a.xml /var/lib/myfolder
rm -f a.xml

A: The solution is to, as my comment, write this command:
sudo mv a.xml /var/lib/myfolder


text:
Q: npm -install error ,I can't install appium I'm Appium new user I have some error ,when I use the NPM command (linux),I have update my ("nvm" and "npm" )version.
I'm follow Click [here](How to setup Appium in Ubuntu for android " to setup my appium.
How can I do for next step!
 root@hauying-yoga-linux:/home/hauying# npm install -g grunt-cli
 npm ERR! TypeError: Cannot read property 'match' of undefined
 npm ERR!     at Unpack.extractOpts.filter
 (/usr/share/npm/lib/utils/tar.js:245:19)
 npm ERR!     at Unpack.[consumeHeader]
 (/usr/lib/nodejs/tar/lib/parse.js:134:48)
 npm ERR!     at Unpack.[consumeChunkSub]
 (/usr/lib/nodejs/tar/lib/parse.js:385:30)
 npm ERR!     at Unpack.[consumeChunk]
 (/usr/lib/nodejs/tar/lib/parse.js:362:30)
 npm ERR!     at Unpack.write
 (/usr/lib/nodejs/tar/lib/parse.js:309:25)
 npm ERR!     at Unzip.ondata (_stream_readable.js:667:20)
 npm ERR!     at Unzip.emit (events.js:189:13)
 npm ERR!     at addChunk (_stream_readable.js:284:12)
 npm ERR!     at readableAddChunk (_stream_readable.js:265:11)
 npm ERR!     at Unzip.Readable.push (_stream_readable.js:220:10)
 npm ERR! If you need help, you may report this *entire* log,
 npm ERR! including the npm and node versions, at:
 npm ERR!     <http://github.com/npm/npm/issues>

 npm ERR! System Linux 4.19.37-5rodete4-amd64
 npm ERR! command "/usr/bin/node" "/usr/bin/npm" "install" "-g"
 "grunt-cli"
 npm ERR! cwd /home/hauying
 npm ERR! node -v v10.15.2
 npm ERR! npm -v 1.4.21
 npm ERR!
 npm ERR! Additional logging details can be found in:
 npm ERR!     /home/hauying/npm-debug.log
 npm ERR! not ok code 0
 root@hauying-yoga-linux:/home/hauying#

A: I'm fixed.
because my node and npm version too old , I'm update my document will install in my computer.


text:
Q: How to read the WFG of a deadlock from a oracle 11g Rac trace file?
* 2013-10-26 21:33:16.156
Submitting asynchronized dump request [28]. summary=[ges process stack dump (kjdglblkrdm1)].
Global blockers dump end:-----------------------------------
Global Wait-For-Graph(WFG) at ddTS[0.2c75] :
BLOCKED 0xb5fa75090 5 wq 2 cvtops x1001 TX 0x370009.0x5ac02(ext 0x4,0x0)[46D000-0002-0000542E] inst 2
BLOCKER 0xb5fa74950 5 wq 1 cvtops x28 TX 0x370009.0x5ac02(ext 0x4,0x0)[335000-0002-000178BA] inst 2
BLOCKED 0xb5fa75260 5 wq 2 cvtops x1001 TX 0x34001e.0x4ea93(ext 0x4,0x0)[335000-0002-000178BA] inst 2
BLOCKER 0xb5fa74028 5 wq 1 cvtops x28 TX 0x34001e.0x4ea93(ext 0x4,0x0)[46D000-0002-0000542E] inst 2

*

*Cancel deadlock victim lockp 0xb5fa75090

  kjddt2vb: valblk  [0.2c76] > local ts [0.2c75]

First, I know what is a deadlock.
My question is:
In a LINE of this WFG, what's the meaning of every part?
Especially, Which part is XID?


text:
Q: Camera permission Xcode 13 I need to access the camera. This used to be managed in the info.plist, but this file is not as it was. I have looked in targets->Info but I can't seem to find where to set the permission.

A: In Xcode 13, you edit the Info.plist by editing the app target and going into the Info pane. There you see a short list of keys and values. Add the privacy key for the camera.


text:
Q: Angular template with ng-repeat, could not able to track the value within it I do have a angular template which populates the list of value in the search button.

when i print the match from above repeat i get below JSON object, pasted just first index of the json array:
{"id":"typeahead-97-1116-option-0",
 "label":"Card/Key Request Informational Guide",
 "model":{
     "short_description":"Card/Key Request Informational Guide",
     "linkToPage":"dea5792147132100ba13a5554ee4902d",
     "published":"06-10-2019",
     "label":"Card/Key Request Informational Guide",
     "type":"kb","query_location":0,"publishedUTC":"06-10-2019",
     "url":"?id=kb_article&sys_id=29ae0b3edbb9fb407ebed77648961951",
     "sys_id":"29ae0b3edbb9fb407ebed77648961951",
     "number":"KB0010366","score":335.9009,"glyph":"file-text-o",
  }
}

based on the type i want to give the list a title. for example set of kb type under "Knowledge article" and type "sc" with title Service Catalog. The list i get is already ordered by bases on type.
Please let me know how to handle this requirement.

A: You can use a ternary operator to determine the value of match.model.type and then set the title depending on that value.

    {{match.model.type === 'kb' ? 'Knowledge article' : match.model.type === 'sc' ? 'Service Catalog' : ''}}

A: Create a hash for lookup:
$scope.typeLookup = {
    'kb': 'Knowledge article',
    'sc': 'Service Catalog',
    // ...
});

Use that hash in the template:

    {{typeLookup[match.model.type]}}


text:
Q: CNAME already taken Today I created a repository with CNAME "www.mywebsite.com" with some source files e.g (index.html) etc and everything works like a charm... my all source files are available on my custom domain name.
Then I deleted my account also the repository that contains the CNAME file "www.mywebsite.com" and few hours later I created a new account and wanted to create a new repository with same CNAME "www.mywebsite.com" that I previous used on my old account, when I created a new CNAME file that contains my previous website URL "www.mywebsite.com" I get an automated message that this CNAME is already taken-
But I deleted my old account with a repository that contains CNAME file "www.mywebsite.com" now why am i receiving this message that your CNAME is already taken?
So,
Hope you understand what I'm trying to say... what should I do now ?
Thanks so much and waiting for your response.


text:
Q: terminating java applet thread on page unload I have got a problem here in terminating the threads. The problem is that I am using applet thread to access JS DOM and manipulate innerHTML of a span to right the Thread Name as the innerHTML. It works fine until I keep refreshing the page but if I dont give it a sleep of like 200ms and go to another page which dont have any applet on it, it will give me an error in firebug console:
document.getElementById("userName") is null

What I am suspecting is, although I send an interrupt on stop and I have also tried the same by setting a flag variable of running in run while loop, the thread executes much faster than the time JVM takes to unload it and I get my page changed in browser but applet is still trying to find an element with id userName.
Is that true?
Is there any work around of it?
Is there any way to know how many threads are running at the moment?
Is there any kill all command to send on destroy()?
I have searched a lot, seen all the API of java threads and applets, couldn't get this to work.
Below is the code:
import java.applet.Applet;
import netscape.javascript.*;

//No need to extend JApplet, since we don't add any components;
//we just paint.
public class firstApplet extends Applet {
    /**
     *
     */
    private static final long serialVersionUID = 1L;
    firstThread first;
    boolean running = false;

    public class firstThread extends Thread{
        JSObject win;
        JSObject doc;
        firstThread second;

        public firstThread(JSObject window){
            this.win = window;
        }
        public void run() {
            try{
                System.out.println("running... ");

                while (!isInterrupted()){

                    doc = (JSObject) win.getMember("document");
                    String userName = Thread.currentThread().getName();
                    //String userName = "John Doe";
                    String S = "document.getElementById(\"userName\").innerHTML = \""+userName+"\";";
                    doc.eval(S);
                    Thread.sleep(5);
                }
            }catch(Exception e){
                System.out.println("exception in first thread... ");
                e.printStackTrace();
            }
        }
    }

    public void init() {
        System.out.println("initializing... ");
    }

    public void start() {
        System.out.println("starting... ");
        JSObject window = JSObject.getWindow(this);

        first = new firstThread(window);
        first.start();
        running = true;
    }

    public void stop() {
        first.interrupt();
        first = null;
        System.out.println("stopping... ");
    }

    public void destroy() {
        if(first != null){
            first = null;
        }
        System.out.println("preparing for unloading...");
    }
}

Thanks

A: Can't you just check if document.getElementById("userName") is null and only try and set it if it's not...?

A: This problem was solved, using JS variables to control Java applet execution, the complete solution is here: http://ciitronian.com/blog/programming/time-efficiency-controlling-java-applet-from-javascript-especially-if-you-make-round-trips-to-the-web-page-from-applet/


text:
Q: Pygal: Change dot type/ symbol I want to change the dots in my pygal chart from the default circles to rectangles (sounds weird but makes sense in my case) and be able to define the size of the rectangles. I couldn't find a solution in the docs. With the config module I can show/ hide the dots and change the dots size but as far as I can see I can't change the dot icon. I also coulndn't find a solution in the style module.
Is there an easy way to do it?
Thanks a lot

A: There's no way to achieve this using styles or configuration: the circular dots are hard-coded into the function that renders line charts.  But, you can easily extend the line chart class and override this function to create a chart with any shape of dot.
If you view the source code of the Line class you will see the following code in the line function:
alter(
    self.svg.transposable_node(
        dots,
        'circle',
        cx=x,
        cy=y,
        r=serie.dots_size,
        class_='dot reactive tooltip-trigger'
    ), metadata
)

This creates a circle for each dot and adds it to the SVG data that will be used to generate the chart.
Copy the whole function into your new class and replace those lines with the following code.  This will add squares instead of circles, using the dots_size configuration to determine the width and height:
alter(
    self.svg.transposable_node(
        dots,
        'rect',
        x=x - serie.dots_size / 2,
        y=y - serie.dots_size / 2,
        width=serie.dots_size,
        height=serie.dots_size,
        class_='dot reactive tooltip-trigger'
    ), metadata
)

The complete class would look something like this (it looks like a lot of code, but most of it is copy-pasted):
from pygal.util import alter, decorate

class SquareDots(pygal.Line):

    def __init__(self, *args, **kwargs):
        super(SquareDots, self).__init__(*args, **kwargs)

    def line(self, serie, rescale=False):
        serie_node = self.svg.serie(serie)
        if rescale and self.secondary_series:
            points = self._rescale(serie.points)
        else:
            points = serie.points
        view_values = list(map(self.view, points))
        if serie.show_dots:
            for i, (x, y) in enumerate(view_values):
                if None in (x, y):
                    continue
                if self.logarithmic:
                    if points[i][1] is None or points[i][1] <= 0:
                        continue
                if (serie.show_only_major_dots and self.x_labels
                        and i < len(self.x_labels)
                        and self.x_labels[i] not in self._x_labels_major):
                    continue
                metadata = serie.metadata.get(i)
                classes = []
                if x > self.view.width / 2:
                    classes.append('left')
                if y > self.view.height / 2:
                    classes.append('top')
                classes = ' '.join(classes)
                self._confidence_interval(
                    serie_node['overlay'], x, y, serie.values[i], metadata
                )
                dots = decorate(
                    self.svg,
                    self.svg.node(serie_node['overlay'], class_="dots"),
                    metadata
                )
                val = self._format(serie, i)

                # This is the part that needs to be changed.
                alter(self.svg.transposable_node(
                        dots,
                        'rect',
                        x=x - serie.dots_size / 2,
                        y=y - serie.dots_size / 2,
                        width=serie.dots_size,
                        height=serie.dots_size,
                        class_='dot reactive tooltip-trigger'
                    ), metadata
                )

                self._tooltip_data(
                    dots, val, x, y, xlabel=self._get_x_label(i)
                )
                self._static_value(
                    serie_node, val, x + self.style.value_font_size,
                    y + self.style.value_font_size, metadata
                )
        if serie.stroke:
            if self.interpolate:
                points = serie.interpolated
                if rescale and self.secondary_series:
                    points = self._rescale(points)
                view_values = list(map(self.view, points))
            if serie.fill:
                view_values = self._fill(view_values)
            if serie.allow_interruptions:
                sequences = []
                cur_sequence = []
                for x, y in view_values:
                    if y is None and len(cur_sequence) > 0:
                        sequences.append(cur_sequence)
                        cur_sequence = []
                    elif y is None:
                        continue
                    else:
                        cur_sequence.append((x, y))
                if len(cur_sequence) > 0:
                    sequences.append(cur_sequence)
            else:
                sequences = [view_values]
            if self.logarithmic:
                for seq in sequences:
                    for ele in seq[::-1]:
                        y = points[seq.index(ele)][1]
                        if y is None or y <= 0:
                            del seq[seq.index(ele)]
            for seq in sequences:
                self.svg.line(
                    serie_node['plot'],
                    seq,
                    close=self._self_close,
                    class_='line reactive' +
                    (' nofill' if not serie.fill else '')
                )

Your new class can then be used like any other pygal chart.
chart = SquareDots(dots_size=50)
chart.add("line", [1, 2, 3, 4, 3, 2])
chart.render_to_png("chart.png")


text:
Q: How can I use the GitHub Rest API to update a repository that is part of an organization? I have a large number of GitHub repositories that have been sorted into various organizations.  I wish to change the visibility of the repos by batch to public using the following API call:
curl -u {user}:{pat} -H "Accept: application/vnd.github.v3+json"  -X PATCH https://api.github.com/repos/{user}/angular.powershifter -d '{"private":false}'

Which as best as I can tell is the API call (see github docs). The {user] and {pat} in the sample above are real values, and the {pat} has every option selected.  The {user} is both the owner of the repo and the organization.
What I get in response is is a 404 with the following body.
{
  "message": "Not Found",
  "documentation_url": "https://docs.github.com/rest/reference/repos#update-a-repository"
}

*

*Is it possible to set the properties of repositories under an organization using the API?

*What is the API call?

*Bonus points if you can point me to the documentation!
Thanks.

A: Use Bearer Token based authentication. Github is deprecating password based authentications.
curl \
 -H 'Authorization: Bearer ${GITHUB-TOKEN}' \
 -X PATCH \
 -H "Accept: application/vnd.github.v3+json" \
 https://api.github.com/repos/${OWNER}/${repo} \
 -d '{"private":"false"}'

Link for the github documentation
https://docs.github.com/en/free-pro-team@latest/rest/overview/other-authentication-methods

A: *

*Yes it is possible.

*I've had some issues with this too.
Short answer use bearer token (As @shek said), and change false to "false":
curl -v -H "Authorization: Bearer ${GITHUB_TOKEN}"
-X PATCH https://api.github.com/repos/${ORGANIZATION}/${REPO}
-H "Accept: application/vnd.github.v3+json" -d '{"private": "false"}';
Notice that your token has full control of private repositories when creating the token:
full control of private repositories image
The link is quite confusing, because if for example you need to get all the repositories from GitHub you'll have to use:
https://api.github.com/orgs/${ORGANIZATION}/repos?${parameters}

Also when you need to change permissions you'll need to use:
https://api.github.com/orgs/${ORGANIZATION}/teams/${TEAM}/repos/${ORGANIZATION}/${REPO}

(Notice the orgs, which is missing in the PATCH command).

*GitHub repositories documentation:
https://docs.github.com/en/rest/reference/repos#update-a-repository
GitHub auth methods (From @shek):
https://docs.github.com/en/free-pro-team@latest/rest/overview/other-authentication-methods


text:
Q: C# asp dotNet - Convert Datetime field to Date/String I find myself unable to change the stored procedure, which produces a datetime field (among other fields) , but I want to display the datetime field in my gridview as either Date (MM/DD/YYYY) or a string in the same format (similar to SQL's: CONVERT(VARCHAR,[datetimeField],101)).
I have pulled the dataset but don't see any way to convert it for this specific field after pulling it, so it shows the time too. I welcome any advice. Here are pieces from my code:
aspx.cs:
    DataSet ds = RunSQLString("SplitItemsDesc_Get '" + ddlSearchItem.Text + "', 'C7'", lsreplenDBConnection);
    if (ds != null && ds.Tables[0].Rows.Count > 0)
    {
        GridView2.DataSource = ds.Tables[0];
        GridView2.DataBind();
        GridView2.Visible = true;
        btnReset.Visible = true;
    }

aspx gridview:
  <asp:gridview id="GridView1" autogeneratecolumns="False" EmptyDataText="Saved Record(s) not found" runat="server"
     Font-Size="10pt" Font-Names="Verdana" cellpadding="3" CellSpacing="0" BorderWidth="2" BorderColor="#5F6366" HeaderStyle-BackColor="#D8E0E2" ForeColor="#0A2D3B"
     OnRowDeleting="GridView1_RowDeleting">
       <columns>
          <%--other fields here--%>
          <asp:TemplateField headertext="End Date">
                <ItemTemplate>
                    <asp:label id="endDate"
                                Text= '<%# Eval("end_date") %>'
                                runat="server"
                                Width="378px"/>
                </ItemTemplate>
          </asp:TemplateField>
       </columns>
</asp:gridview>

A: Of course after I post it, after searching for answer prior, I find the solution:
Text='<%# Eval("end_date", "{0:MM/dd/yyyy}") %>'

We're good. Rubber Ducky debugging has concluded.


text:
Q: Backspace doesn't work inside running bash script I'm running very simple script which reads line by line and prints entered line back to terminal:
while read CMD; do
    echo $CMD
done

It works fine, but when I'm trying to edit line with backspace character it prints ^?instead of deleting character. And when I press Ctrl + backspace the output is ^H. How could this behavior be fixed so backspace removes character instead of adding these characters?
I tried stty erase '^?' command but not successfully.

A: The problem is that there are many ways to represent a backspace, but the read command doesn't understand all of them. You should be able to configure what exactly is sent when pressing the ← Backspace key in your terminal emulator's settings.
Assuming you're using gnome-terminal as emulator, open the Edit manu and click on Profile preferences. Switch to the Compatibility tab and you should get these options:

Now you can change the Backspace key generates: setting. You have these five options below available to chose from. I added in braces how they behave on my system:

*

*Automatic (works)

*Control-H (prints ^H instead)

*ASCII DEL (default, works)

*Escape sequence (prints ^[[3~ instead)

*TTY Erase (works)

A: I had the same problem, using bash in Gnome-Terminal.
Note that on the command line, the backspace works as expected, but when my program (a simple TCP socket based chat client) is reading from stdin, the backspace character prints (echoes back to the screen) ^?instead of deleting the last character.
Use # stty icanon to allow the "canonical (cooked) mode".  See some explanation here https://unix.stackexchange.com/questions/131105/how-to-read-over-4k-input-without-new-lines-on-a-terminal
Some more background to my problem/solution: I had a problem where I need to paste more than 4k characters. And during that research, I was led to the above link.  I used # stty -icanon to disable the 4k limit, but lost the ability to use backspace (erase).


text:
Q: Changing neopixels randomly between 3 colors, on each pixel randomly So I currently have 2x 12 Pixel Neopixel rings, running from a pi zero W.
The LEDs all work as expected, going through level shifter etc. and all react as expected.
Total noob with python but I can control the pixels and get them to do what I want, however I'm currently wanting to have each pixel on each ring randomly switch between 3 set colors at random times. Basically to have a flickering effect but only in that color range.
Currently I'm just changing each pixel manually in a function, that gets called from my script, that loops for a certain amount of time. It works ok but is a little inelegant.
def Lights_Flicker():

    pixels[0] = (255, 0, 0,0)
    pixels.show()
    time.sleep(.02)

    pixels[12] = (255, 0, 0,0)
    pixels.show()
    time.sleep(.02)

    pixels[6] = (122, 100, 0,0)
    pixels.show()
    time.sleep(.02)

    pixels[23] = (122, 100, 0,0)
    pixels.show()
    time.sleep(.02)

Using this to loop through the function for x seconds. (While Sound is playing)
while time.time() < t_end:
            Lights_Flicker()

I'm happy with the timing portion its just the color flickering. If someone knows how to do this a little more cleanly that would be amazing.
Thanks for looking

A: I believe something like this should do what you're asking...
from random import randint

colors = [ (255,0,0,0), # put all color tuples here
           (122,100,0,0),
         ]

pixel_num = [ 0, # put all pixels here
              6,
              12,
              23,
            ]

while time.time() <= t_end:
    rand_pixel = randint(0, len(pixel_num)-1)
    rand_color = randint(0, len(colors)-1)

    new_pixel = pixel_num[rand_pixel]
    new_color = colors[rand_color]

    pixels[new_pixel] = new_color
    pixels.show()

    time.sleep(0.02)


text:
Q: Time complexity of gcd algorithm in terms of big theta notation. Here n>m.
I have analyzed the worst case when n = fibonacci Nth term and m = fiboncci (N-1)th term.In this case total work will be proportinal to N or time complexity will be O(N).But I am interested in finding time complexity(theta notation) in terms of n.But I am not getting how to find relation between n and N or the upper and lower bound in terms of n.
int gcd(int n, int m) {
        if (n%m ==0) return m;
        if (n < m) swap(n, m);
        while (m > 0) {
            n = n%m;
            swap(n, m);
        }
        return n;
}

Please help.

A: I would try to analyse how m changes after two iterations of the loop. One iteration might change n very little, for example (1001, 1000) -> (1000, 1). m might also change very little, for example (1999, 1000) -> (1000, 999). So analysing how either changes in a single iteration gives you very little. However, if you have two iterations then you will always have a big change.
So analyse this: If r = n/m, how does m change after two iterations of the algorithm, depending on r? By which factor does it decrease at least? (By the way, what is r for Fibonacci numbers? Does that explain the worst case? )

A: You might find this interesting.
It tries to explain Lamé's theorem for the number of steps of the GCD algorithm. The worst case is when the 2 numbers are consecutive Fibonacci numbers.


text:
Q: OAuth 2.0 in php using curl I need to get my access_token and refresh_token for OAuth 2.0 to Access Google APIs, the php script below should return a json with access_token, refresh_token like this:
{
  "access_token" : "####",
  "token_type" : "Bearer",
  "expires_in" : 3600,
  "refresh_token" : "####"
}

but, the php script return me only this error message:
{
"error" : "invalid_request",
"error_description" : "Client must specify either client_id or client_assertion, not both"
}

I tried to remove client_secret/client_id and use only client_id/client_secret, but still get the same error.

PHP script
$client_id = '###.apps.googleusercontent.com';
$redirect_uri = 'http://localhost/phpConnectToDB/csv/refreshFusionTable.php';
$client_secret = '###';

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://accounts.google.com/o/oauth2/token");

$code = $_REQUEST['code'];

curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'code' => $code,
'client_id' => $clientID,
'client_secret' => $clientSecret,
'redirect_uri' => $redirect_uri,
'grant_type' => 'authorization_code'
));

$data = curl_exec($ch);

var_dump($data);

Although curl in cmd works and returns me access and refresh token without any errors.
curl --data "code=###&client_id=###.apps.googleusercontent.com&client_secret=###&redirect_uri=http://localhost/phpConnectToDB/csv/refreshFusionTable.php&grant_type=authorization_code" https://accounts.google.com/o/oauth2/token

I don't understand why I get the missing scheme error, although the .php script exists and it's located on the given path. Could you help me please ?
EDIT Problem with "Invalid parameter value for redirect_uri: Missing scheme" solved, I just replaced 'redirect_uri' => urlencode($redirect_uri), with this 'redirect_uri' => $redirect_uri, in CURLOPT_POSTFIELDS.

A: Wow, stupid mistake, I should have a rest.
The variables names don't match.
I defined:
    $client_id = '###.apps.googleusercontent.com';
    $client_secret = '###';

But here I used an non-existing clientID and clientSecret :
    curl_setopt($ch, CURLOPT_POSTFIELDS, array(
    'code' => $code,
    'client_id' => $clientID,
    'client_secret' => $clientSecret,
    'redirect_uri' => $redirect_uri,
    'grant_type' => 'authorization_code'
    ));

Fixed and working PHP script
    $client_id = '###.apps.googleusercontent.com';
    $redirect_uri = 'http://localhost/phpConnectToDB/csv/refreshFusionTable.php';
    $client_secret = '###';

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, "https://accounts.google.com/o/oauth2/token");

    curl_setopt($ch, CURLOPT_POST, TRUE);

    $code = $_REQUEST['code'];

    // This option is set to TRUE so that the response
    // doesnot get printed and is stored directly in
    // the variable
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    curl_setopt($ch, CURLOPT_POSTFIELDS, array(
    'code' => $code,
    'client_id' => $client_id,
    'client_secret' => $client_secret,
    'redirect_uri' => $redirect_uri,
    'grant_type' => 'authorization_code'
    ));

    $data = curl_exec($ch);

    var_dump($data);

But I have to say that google provides a little misleading error message here, because I hadn't defined client_id nor client_secret and the error message was:
    {
    "error" : "invalid_request",
    "error_description" : "Client must specify either client_id or client_assertion, not both"
    }


text:
Q: Javascript Function to be called in PHP I have this javascript function which allows me to create my custom alerts by calling it using this
Javascript:
";

It doesn't work at all. Any ideas?
UPDATE
Here's the php code:
<?php

if(isset($_POST['btn_sample'])){
  echo "";
}

I added this on the html:
<form action = "" method = "post">
  <input type = "submit" name = "btn_sample" value = "sample">
</form>

A: Check this ,

*

*I think you are execute the php script before document load .

*Or php included html not containing the link of the this js script file.

And call the Js function after window.onload like this.They will prevent the first one
echo "";

A: Your render function relies on the elements "dialogoverlay", "Dialogbox", etc. already existing, which they don't if you call the function above your HTML.
You need to either bind your Alert.render() call to the DOMContentLoaded event or just put your scripts at the bottom of your body, which tends to be the preferred practice nowadays.


text:
Q: Salesforce EventLogs for Field & Validation changes does anybody know if salesforce eventlogs picks up logs for whenever a user adds and new field or makes changes to a field on application? Would this show in transaction logs?
Here's an example:
Bob creates a new input field for his salesforce app, later on he decides to change that field, or even change how the validation on this field works. Will SalesForce event logs capture these activities in a audit log somewhere?

A: In your case assuming Bob is an admin, you can use Monitor Setup Changes to track these type of activities in your Org. These type of activities are tracked in the Audit Trail.

Setup Audit Trail tracks the recent setup changes that you and other admins have made to your org. Audit history is especially useful in orgs with multiple admins.

You can take a look at the documentation for more details as what you can track vs. not.


text:
Q: Product of Borel algebras is Borel algebra of the product
Let $(X_1, d_1), \dots, (X_n, d_n)$ be separable metric spaces. Endow $X = \prod\limits_{i=1}^n X_i$ with the metric $d$ given by $d(u, v) = \sqrt{\sum\limits_{i=1}^n d_i(u_i, v_i)^2}.$ For a topological/metric space $A,$ let $\mathcal{B}(A)$ denote the Borel algebra on $A,$ i.e. the smallest sigma algebra containing all open sets of $A.$ Prove that $R = \mathcal{B}(X) = \prod\limits_{i=1}^n \mathcal{B}(X_i) = T$ (letters introduced for the purpose of making the following discussion easier to read).

Attempt: Let $Y_i$ be a countable dense subset of $X_i.$ Then $Y = \prod\limits_{i=1}^n Y_i$ is a countable dense subset of $X.$ I used the density of $Y$ to show that any open set $U \subseteq X$ can be written as a countable union of balls centered at points of $Y.$ Thus, $\mathcal{B}(X) = \sigma(\{B_d(y,\epsilon) : y \in Y\}) \, (*).$ Now suppose $Z = Z_1 \times \dots \times Z_n$ where $Z_i \in \mathcal{B}(X_i).$ We need to show that $Z \subseteq R.$
I don't see how we're supposed to continue. I strongly suspect that among the statements $R \subseteq T, T \subseteq R,$ one is supposed to be trivial and the other is shown using separability, but I don't know which one is trivial and which one to use separability on. I used separability to show $(*),$ but this doesn't seem to lead anywhere.
My original plan was to consider $S = \sigma(U_1 \times \dots \times U_n : U_i \subseteq X_i \text{ open})$ and show that $R = S = T.$ We clearly have $S \subseteq R,$ and if we show $\sigma(T) = T$ then it follows $S \subseteq T,$ leaving only $T \subseteq S, R \subseteq S.$ I thought that maybe $R \subseteq S$ follows from separability although I couldn't figure out exactly how, and had no idea how to show $T \subseteq S.$
The biggest obstacle to working with $T$ is that there is no mechanism for taking the union, complement, or intersection of elements of the product of Borel algebras. What is $(Z_1 \times Z_2) \cup (Z_3 \times Z_4)$ where $Z_i \in \mathcal{B}(X_{2-(i \bmod 2)})$? It's just $\{(a,b) : a \in Z_1, b \in Z_2 \text{ or } a \in Z_3, b \in Z_4\}.$ Not very helpful. What exactly is $\sigma(U_1 \times X_2 : U_1 \subseteq X_1 \text{ open})$? Unfortunately, it's just $\mathcal{B}(X_1) \times \{X_2\}.$ Any hints, approaches, or ideas on how to use separability properly and how to deal with products of Borel algebras?
Note: I was given the hint that you need to imitate the proof that $\mathcal{B}(\mathbb{R}) = \sigma(\{(a,b)\}).$ The analogue of open intervals for metric spaces is open balls, and I did just that to show $(*).$ The issue is that I have no idea how to prove $\sigma(\{B_d(y,\epsilon) : y \in Y\}) = T.$
Update: I have almost solved the problem. Let $\pi_i : X \to X_i$ be the projection mapping onto $X_i$ and let $A_i = \{U \subseteq X_i : \pi_i^{-1}(U) \in R\}.$ Then $A_i$ is a sigma algebra since $R$ is and $$\pi_i^{-1}(U^c) = \pi_i^{-1}(U)^c, \pi_i^{-1}(\bigcup\limits_i U_i) = \bigcup\limits_i \pi_i^{-1}(U_i).$$ Furthermore, $A_i$ contains all open subsets of $X_i$ since $\pi_i^{-1}(U) = X_1 \times \dots \times U \times X_{i+1} \times \dots \times X_n$ is an open subset of $X$ whenever $U$ is open.
It follows $\mathcal{B}(X_i) \subseteq A_i \Rightarrow \pi_i^{-1}(\mathcal{B}(X_i)) \subseteq R \Rightarrow T = \bigcup\limits_{i=1}^n \pi_i^{-1}(\mathcal{B}(X_i)) \subseteq R.$
I've shown that if $U \subseteq X$ is open, then $U$ is a countable union of products of balls. To finish the proof, I need to show $T$ is a sigma algebra, which would imply this countable union is in $T,$ hence $U \subseteq T,$ hence $R = \sigma(\{U\}) \subseteq \sigma(T) = T.$
Last update: $T$ is a sigma algebra by definition, completing the proof.


text:
Q: powershell - MS-Word document parsing - Get a table's caption text I am parsing a word 2007 using powershell. I would like get each table's caption and print it to screen.
Here is an idea of what I would like to do, but the print caption line does not work.
$wd = New-Object -ComObject Word.Application
$wd.Visible = $true
$doc = $wd.Documents.Open($filename)
foreach ($table in $doc.Tables)
{
      #print table caption
      Write-Host $table.Caption.Range.Text #This does not work

      #Print Table contents
      foreach ($row in $table.Rows)
      {
          Write-Host $row.Range.Text
      }
}

Is it possible to get the caption associated with a table?

A: Captions aren't properties of table objects, they're just text. You could do something like this for finding table captions, though:
$style = $doc.Styles | ? { $_.NameLocal -eq 'Caption' }
$wd.Selection.Find.Style = $style
$wd.Selection.Find.Text  = 'Table'  # if table captions are labeled "Table"
$wd.Selection.Find.Execute()

Since wildcard matches are non-greedy in Word, you may have to do something like this:
$style = $doc.Styles | ? { $_.NameLocal -eq 'Caption' }
$wd.Selection.Find.Style = $style
$wd.Selection.Find.Wrap  = 0
while ($wd.Selection.Find.Execute()) {
  if ($wd.Selection.Text -like 'Table*') {
    # do stuff
  }
  $wd.Selection.MoveRight()
}

The above matches just by style, so it should select the entire caption. The MoveRight() unselects the caption afterwards, so the next iteration will find the next match until the end of the document, where the search stops (.Find.Wrap = 0).


text:
Q: Can't see WiFi SSID I have installed 12.04.1 on Dell Latitude E6510
At work I could able connect to WiFi and it is OK
At home I use DSL WiFi modem router which works fine and I can connect thru Windows, Android phone etc. But Ubuntu doesn't even see SSID name. Only "my" SSID name :( I can see others

03:00.0 Network controller: Broadcom Corporation BCM43224 802.11a/b/g/n (rev 01)

My wifi settings are WPA/WPA2 PSK
Thanks

A: I recently had this problem and solved it changing the CHANNEL of my wifi router to 10, Looks like there were too many ssid's in my previous channel...


text:
Q: MongoDB or MySQL I am working on a website which would be having all the restaurant related details for a particular country. I was considering which DB would be best suitable for this kind of scenario,very similar to this.
I was considering to use MongoDB just because it would provide me with flexible schema and Simple queries for data retrieval. I am rethinking over my decision as neither my data is going to be too large as of my now so there wont be nay blockage for me w.r.t data size in MySQL.
What would be best way to choose between the 2.

A: It depends truly on whether you want data integrity and ACID features of a Relational Database. If a Relational Database is built correctly using the Relational Model and E.F Codd's rules, you will never have a problem with having duplicate data, inconsistencies, and other maladies.(This is assuming you use a RDBMS that is worth its salt, like oracle or SAP ASE)
However, you also have the option of MongoDB, which as you pointed out, is very flexible. However, through my experience, you will have to do a lot more manual work ensuring data accuracy and integrity.
However, certain things are easier in it, and it is by no means not successful. I use Mongo as a data back end for simulation servers I run, and it performs beautifully. Where mongo truly exceeds is with its atomic documents, and that's where Mongo pulled ahead of other NoSQL systems like CouchDB.
What it truly comes down to is what kind of data you are storing. If you are storing relational data, use a RDBMS. If it is more document based, use Mongo or a similar data storage engine. I do not like the idea of choosing a data storage engine by what is popular or what is new. Use what fits your data.
I hope this answers you question satisfactorily, if not please comment below.


text:
Q: HTTPS headers showing cleartext passwords I have just set up a SelfSigned Open SSL certificate on my server. I am monitoring the network traffic in Chrome' network inspector. Under the Form Data header I can see all of the information in cleartext, is this normal? I would think it would be encrypted. I have a very basic form:
<!DOCTYPE html>
<html>
    <head>

    </head>

<body>
    <form method="post" action="EncoreCMS/test.php">
        <label>Username</label><input type="text" name="userName" />
        <input type="submit" value="Submit" />
    </form>
</body>

</html>

I have never used SSL before so maybe I am doing something wrong?

A: Chrome knows what the plaintext is, obviously, so it shows it to you. If you're using https the stuff on the wire is encrypted.


text:
Q: cindyjs how can i set an function just between 2 segment points I can't figure out how i could make a function just between 2 points with thats cindyjs script (2nd graph on the right side with point {1}v{m_{i} and {2}v{m_{i}) or P1[you can choose one of them] who are binded on 2 other lines t_1 and t_2 or the single point free in space. i tried to figgure it out how i could handle that with an matrix, like in the 58_Interpolation.html, but its my first time and so i am here to ask you for an solution. i need an logatithmic and exponential function like log(x), exp(x) or an normal sin(x)+cos(x) functions between that points, where the start and the endpoint has to be the 2 points on the lines or the 2nd one free in space. oh at least. for all other peoples. thats an full functional graph. take it if you need it :) thx for help

A: I think you are looking for the start and stop modifiers of the plot function, as documented at https://doc.cinderella.de/tiki-index.php?page=Function+Plotting.


text:
Q: If a socket is identified by the quartet, what is quartet information of a listening socket? I was trying to understand what does it mean that accept() creates a new socket and the accepted answer of this question was very helpful. My question comes from the comment section of the accepted answer as I believe it deserves to be a separate question. My understanding is this

*

*(source ip, source port, destination ip, destination port, protocol) defines a socket.

*A socket descriptor is an integer that works as an identifier of a socket  (source ip, source port, destination ip, destination port, protocol)
Now apart from the question asked I also want to know whether my understanding "different socket descriptors returned by accept() and socket() points to the same socket (source ip, source port, destination ip, destination port, protocol)
 but represent different state of the same socket (listening state, connected to client state) just like same file can be in read mode/write mode" is correct or not.

A: The server's listening socket is listening on a given IP:port, but is not connected to anyone, so it is identifiable only by the listening IP:port.
When a client connection is established, accept() returns a new socket that is connected to a specific client, so it is identifiable by both server IP:port and client IP:port.
A socket represents a particular endpoint, which may be part of an underlying connection or not.  A socket descriptor is just how the app refers to a given socket.  A listening socket has 1 endpoint, whereas a connected socket has 2 endpoints.  That is why accept() has to return a new socket that is different than the listening socket which accept() was called on.

A: There isn't any. A listening socket is identified by a 2-tuple: IP address and port.

(source ip, source port, destination ip, destination port, protocol) defines a socket.

No. It defines a connection.

A socket descriptor is an integer that works as an identifier of a socket

Correct.

(source ip, source port, destination ip, destination port, protocol)

No, see above.


text:
Q: ¿Cómo se puede localizar con firebug el archivo HTML que contiene este label para traducirlo? Utilizando firebug, no soy capaz de saber dónde está el archivo que contiene este label que mediante filezilla quiero traducir al español manualmente. ¿Cómo deberí hacerlo?

Gracias! ;)


text:
Q: Managing two types of user accounts in same session There are two kinds of users in my system. The admin and normal users. Here i am planning to use session variable to redirect according to their user groups after logging in. Currently Admin has access to unique features(admin dashboard etc). Normal users are having a profile. I need to give the admin possibility to switch between admin dashboard and the user profile without logging in or out more than once. Can anybody give a rough idea how can i implement this?

A: The better practice is to have groups (which it sounds like you do) and to have levels assigned to each group.
For example, say normal users are 1 and admin users are 2.
Then if your page wants to show content to both normal users and admins you can say so long as the logged in user is >= 1 then show the content.
Likewise if your page wants to show content to only admin users you can say so long as the logged in user is >= 2 then show the content.
This is just a rough example since you didn't provide much context or any examples.

A: This is not an answer but have you tried considering much simpler and just making exceptions in your code on the regular users page for the admin?
Example, lets take 1 for admin and 2 for regular user:
admin.php can only be accessed if the $row['privilege'] == 1 vice versa for regular user: $row['privilege'] == 2.
Why not do on the regular users page something like:
<?php
if ($row['username'] == "admin" && $row['privilege'] == "1") {
// let admin access page
} else {
// don't let anyone access page
}
?>

I mean it looks to me like something like that would be the easiest way?
That's my opinion but someone else may have a better solution

A: Though the question is pretty vague. I will try to explain the normal process of managing the user roles, authentication and authorization in a normal web application.
DB Model:
1. Table: User
Columns: id, username, password, ..

2. Table: Roles
Columns: roleId, RoleName

3. Table: UserRoles
Columns: userId, roleId

When user authenticates itself in your AuthController, upon successful authentication, you need fetch the roles, user is associated with. And then you need to put this information in the session.
On your views, you need check the conditions like below, based on your business conditions.
View1.php
if(role in session is 'ADMIN' )
Show the data

View2.php
if(role in session is 'USER' )
Show the data


text:
Q: Unable to start redis I get the following error in Redis 2.8:
FATAL CONFIG FILE ERROR
redis-server[31954]: Reading the configuration file, at line 103
redis-server[31954]: 'logfile /var/log/redis/redis.log'
redis-server[31954]: Can't open the log file: Permission denied
systemd[1]: redis.service: main process exited, code=exited,      status=1/FAILURE
redis-shutdown[31956]: Could not connect to Redis at 127.0.0.1:6379:   Connection refused
systemd[1]: redis.service: con`enter code here`trol process exited, code=exited status=1
systemd[1]: Unit redis.service entered failed state.
systemd[1]: redis.service failed.

What is causing this?

A: Check the line 103 from your Redis configuration file. You should find the logfile configuration in that line. Then, make sure the the user running the redis process/service has the appropriate permissions (read and write/modify) on that file/folder.


text:
Q: Intellij code indentation for builders Currently if I write use the following builder class Intellij will indent the following way
SomeClass.create()
    .someMethod()
    .someOtherMethod();

What I would like it to do is indent like this:
SomeClass.create()
         .someMethod()
         .someOtherMethod();

Does anybody know how to set this up?

A: *

*Code Style => Java => Wrapping and Braces => Chained Method Calls

*Align when multiline

Produces the following when reformatting source:


text:
Q: panda DataFrame.value_counts().plot().bar() and DataFrame.value_counts().cumsum().plot() not using the same axis I am trying to draw a frequency bar plot and a cumulative "ogive" in the same plot. If I draw them separately both are shown OK, but when shown in the same figure, the cumulative graphic is shown shifted. Below the code used.
df = pd.DataFrame({'Correctas': [4,6,5,4,7,2,8,3,5,6,9,6,6,7,5,5,8,10,4,8,3,6,9,5,11,5,12,7,7,5,4,6]});

df['Correctas'].value_counts(sort = False).plot.bar();
df['Correctas'].value_counts(sort = False).cumsum().plot();

plt.show()

The frequency data is
2      1
3      3
4      7
5     14
6     20
7     24
8     27
9     29
10    30
11    31
12    32

So the cumulative shall start from 2 and it starts from 4 on x axis.
image showing the error

A: This has to do with bar chart plotting categorical x-axis.  Here is a quick fix:
df = pd.DataFrame({'Correctas': [4,6,5,4,7,2,8,3,5,6,9,6,6,7,5,5,8,10,4,8,3,6,9,5,11,5,12,7,7,5,4,6]});

df_counts = df['Correctas'].value_counts(sort = False)
df_counts.index = df_counts.index.astype('str')

df_counts.plot.bar(alpha=.8);
df_counts.cumsum().plot(color='k', kind='line');

plt.show();

Output:


text:
Q: How do I list word count in multiple files? Say I need to find out how many words are in each file that has the word 'work' in its name.
I know that to find files with 'work' in the name, it would be ls work. And to figure out the number of words in a file it would be wc -w.
However I tried the following and it seems to be just displaying the number of files, not the number of words combined in all files (which I need):
ls work | wc -w

So say if there are 14 files that have 'work' in the name, it would display 14, not the number of words.

A: You can run wc with multiple files and then use shell built-in * which adds every non hidden files in working directory to wc's parameters.
wc -w *work*

A: The syntax is wc -w [FILE]. If you don't use FILE but pipe in the output of ls work it will only count what it will read on stdin.
You need to pipe in the text itself:
cat *work* | wc -w

Alternative you could execute wc with find -exec. But be aware that this could show multiple "total" sums as find will call wc multiple times if there are lots of files.
find ./ -type f -name "*work*" -exec wc -w {} +

A: There are some good answers here but for this I like to use:
ls | grep work | xargs wc -w


text:
Q: JPA Group by with multiple field I am getting following error while using named query blog.findBlogs
"Your select and having clauses must only include aggregates or values that also appear in your grouping clause."
In select clause I have used b.id so it must allow to perform this query without error. I also tried same query from mysql workbench and its working perfectly fine.
@NamedQueries( value = {
        @NamedQuery (name = "blog.findBlogs", query = "SELECT " +
                            "NEW com.vo.Blog(b.id, b.blogId, b.createDate, b.tags, b.url, COUNT(r.emotion)) " +
                            "FROM Blog b JOIN b.rates r " +
                            "GROUP BY b.id")
})

regards, Amit J.

A: In general, a GROUP BY query in SQL must obey a rule that everything which appears in the SELECT clause must either appear in the GROUP BY clause or be inside an aggregate function, such as COUNT.

I also tried same query from mysql workbench and its working perfectly fine.

It turns out that MySQL is one of a few databases which does not enforce this rule.  But JPA appears to not allow this, so it fails for you running from JPA even though the underlying database is a lax version of MySQL.
Here is how you can modify your code to run without error:
@NamedQueries( value = {
    @NamedQuery (name = "blog.findBlogs", query = "SELECT " +
                        "NEW com.vo.Blog(b.id, COUNT(r.emotion)) " +
                        "FROM Blog b JOIN b.rates r " +
                        "GROUP BY b.id")
})

If you're wondering what the logical problem with your original query was, it is that, for a given b.id value, JPA cannot figure out which blog, date, and tags value to choose for that group.


text:
Q: Only One Type of Downvote is not sufficient There are some very well asked questions but the answer can be easily found. On the other hand, a very poorly asked question might contain some very interesting points in it.
Consider the question:

What is the result of 21+12+8?
I am struggling with my cousin's math homework. To find the answer to
  the following question,   "There are three people named Alice, Bob and
  Charlie. Their ages are 21, 12 and 8 respectively. A fourth person,
  Dave's age is the average of the ages of Alice, Bob and Charlie. How
  old is Dave?"   I need to find the answer to 21+12+8. I know that the plus operator sums the left-hand-side and right-hand-side numbers. But there are three numbers and two operators. How do I find the answer?

And this question:

How can I prevent SQL-injection in PHP?
Note: This is a real top question from SO.
   I don't want my site to get hacked. Please help me to overcome SQL-Injections.

First one is asked properly, shows a research effort. Second one is asked poorly, but when properly asked, it is one of the best questions in SO.
Now, my proposal is:
There should by more than one downvote. I'm not talking about flags. Not every question that deserves a downvote deserves a close flag as well. If so, why is there a downvote button? Only upvotes and flags would be enough.
Moreover, a big problem of the community is, so called "experts" downvote the questions because of XY problem. This might be a downvote choice as well.
For instance:

*

*Standard downvote

*XY Problem

*Bad wording

*Improperly written code

could be four choices for downvotes.

A: What you are describing here are close reasons:

*

*XY problem -> vote to close as "unclear what you are asking".

*Improperly written code -> vote to close as "This question was caused by a problem that can no longer be reproduced or a simple typographical error"

*Bad wording -> vote to close as "unclear what you are asking".

The other courses of action are posting a comment asking for clarification etc. or editing the question into shape (thanks Lance).
No need to complicate things with different types of down-vote.


text:
Q: How can I create a list of all email addresses by Industry? I'm just trying to create a list of all names and email addresses for everyone within a given market sector defined by the field Industry.
The standard reports don't offer it, so I am looking for help with just pulling out all the email addresses for all of our customers (tens of thousands in many different market sectors) so we can reach out to them by email.

A: In order to create a new report type you need admin access. If you do not have this, you should contact your admin or developer to create the report for you. It sounds like you are just looking to add fields to an existing report type (Contacts?). If you do have access, follow these steps (different for lightning):

*

*Click on Setup in the upper right corner next to your name.

*In the quick find box on the left type Report Types

*Click Report Types

*Under the label column click Contact (not edit)

*In the Fields Available for Reports section at the bottom, click Edit Layout

*The list of all fields for on the Contact object are in a pane on the right hand side. You can drag any of these fields into the main area and they will become available in the Contacts report.

If you are looking to use a field on a related object you can do this two ways:

*

*Add a formula field to the contact object that looks up value from the related object. Then follow the steps above to add it to the report type.

*You can create a new report type and use two related objects to create a joined report.

Option 2 is best when creating reports on objects that may have a one-to-many relationship such as Contacts with Cases. You may, for example, want to pull a list of contacts' email addresses only if the contact has an closed case so that you could send them a satisfaction survey about the case. Salesforce allows you to join up to four related objects in a single report type.


text:
Q: Detect browser when site is accessed Is there anyway to detect browser version in symfony prior to loading any pages and then run a corresponding action?  I was thinking of using modernizr, but I was hoping to not have to rewrite all my views.
Basically what I was hoping I could accomplish is that before the framework attempts to match the url to a route it would first check to see if the user has a particular browser version and if not run another controller instead of the the controller defined in the route.

A: I think what your suggesting is not a "best practice". I'm assuming you want to route a mobile request to a unique Action method in a Controller. You really shouldn't have a separate controller based client device. This is the job of the (V)view in MVC.
Modernizr is a client side solution with css,js but if youre using symfony, i would prefer server side and that requires the title of this question.. "Detecting browser on request".
While you can custom configure your app to detect the device(and its not to hard), there's also an easier option. Try this bundle. https://github.com/suncat2000/MobileDetectBundle . It does everything and allows for you to make both controller modifications or make twig aware of the browser so you can make smaller changes.


text:
Q: Concatenate Strings in Alphabetical Order I am trying to concatenate strings from two separate columns. The trouble is, I need the first string in the concatenation to be the first alphabetically.
For Example:
Column 1        Column 2        Concatenation
def             abc             abcdef
abc             def             abcdef

Is there any way to do this within Access? SQL Server may also be an option, but it would be much easier for me to stay within Access.

A: For two strings, you can stay in Access:
select iif(column1 < column2, column1 & column2, column2 & column1) as concatenation

If you had more than two strings in the row, then SQL Server would be a much better option.

A: Sql Server version
create table a
(col1 nvarchar(100)
 ,col2 nvarchar(100)
 )
 insert into a values('abc','def')
 insert into a values('def','abgggccz')
 insert into a values('xyzabc','def')
 insert into a values('def','xyzabc')
 insert into a values('axyzabc','def')
 insert into a values('adef','acxyzabc')
 insert into a values('abcd','x')

Query
select
case when
LOWER(col1)>LOWER(col2)
then col2+''+col1
else
col1+''+col2
end
from a

result
abcdef
abgggcczdef
defxyzabc
defxyzabc
axyzabcdef
acxyzabcadef
abcdx

note : if you are using sql server then you can do the same if you want to concatenate more than 2 strings