text:
Q: Precompactness of subset of function space with pointwise convergence topology I need help with proving following statement. Let $M[a, b]$ - space of real (complex) value functions with topology of pointwise convergence.  Then $$A \subseteq  M[a, b] \,\text{ is precompact } \iff  \exists g \in M[a,b], |f(t)| \leq g(t)  ,\forall t \ \in \ [a,b], \ f \in \ A$$
I know, that if functions are continuous equicontinuity and uniform boundness are needed for precompactness, but don't really know what to do in this case.

A: Assume that $\exists g \in M[a,b]$ such that $|f| \le g$ for all $f \in A$. For $x \in [a,b]$ let $\pi_x : [a,b] \to \Bbb{C}$ be the evaluation $f \mapsto f(x)$.
For every $x \in [a,b]$ we have that $\pi_x(A)$ is contained in the closed ball $\overline{K}(0,g(x))$ of radius $g(x)$ around the origin in $\Bbb{C}$.
Taking the closure yields $\overline{\pi_x(A)} \subseteq \overline{K}(0,g(x))$ and hence $\overline{\pi_x(A)}$ is compact in $\Bbb{C}$. Now we have
$$\overline{A} \subseteq \prod_{x \in [a,b]} \pi_x(\overline{A}) \subseteq  \prod_{x \in [a,b]} \overline{\pi_x(A)}$$
and the latter is a product of compact sets and hence compact. Therefore $\overline{A}$ is also compact.
Conversely, assume that $A$ is precompact. Then for every $x \in X$ since $\pi_x$ is continuous, we have that $\pi_x(\overline{A})$ is compact in $\Bbb{C}$ as an image of a compact set. In particular, $\pi_x(\overline{A})$ is bounded and then from
$$\pi_x(A) \subseteq \pi_x(\overline{A})$$
we see that is  $\pi_x(A)$ is also bounded. Hence there exists a positive real number which we can denote by $g(x)$ such that $\pi_x(A) \subseteq \overline{K}(0,g(x))$.
Hence for any $f \in A$ and $x \in [a,b]$ we have
$$f(x) = \pi_x(f) \in \pi_x(A) \subseteq \overline{K}(0,g(x)) \implies |f(x)| \le g(x).$$


text:
Q: Getting 403 trying to call Google Cloud Endpoints API hosted on App Engine Java 8, dev app server Running an App Engine Java 8 app with Google Cloud Endpoints.  I've generated the openapi.json, deployed it to my Endpoints Portal, and can see the API in my portal, with the various methods and resources listed correctly.
I'm running the dev app server locally in IntelliJ using the Cloud Code plugin.  When I run it, it opens a browser tab that gives me an Error 403, with the following stack trace (abbreviated):
SEVERE: direct send of a check request service_name: "my-project-redacted.appspot.com"
operation {
  operation_id: "11b8f9a6-c9cb-4895-95fb-8bb39176efb9"
  operation_name: "1.my_project_dot_appspot_com.MyAPI"
  consumer_id: "project:my-project"
  start_time {
    seconds: 1596075164
    nanos: 812000000
  }
  end_time {
    seconds: 1596075164
    nanos: 812000000
  }
  labels {
    key: "servicecontrol.googleapis.com/caller_ip"
    value: "127.0.0.1"
  }
  labels {
    key: "servicecontrol.googleapis.com/user_agent"
    value: "ESP"
  }
  labels {
    key: "servicecontrol.googleapis.com/service_agent"
    value: "EF_JAVA/1.0.12"
  }
}
 failed
endpoints.repackaged.com.google.api.client.http.HttpResponseException: 403
{
  "error": {
    "code": 403,
    "message": "The caller does not have permission",
    "errors": [
      {
        "message": "The caller does not have permission",
        "domain": "global",
        "reason": "forbidden"
      }
    ],
    "status": "PERMISSION_DENIED"
  }
}

    at endpoints.repackaged.com.google.api.client.googleapis.services.AbstractGoogleClientRequest.newExceptionOnError(AbstractGoogleClientRequest.java:456)
    at endpoints.repackaged.com.google.api.client.googleapis.services.AbstractGoogleClientRequest$1.interceptResponse(AbstractGoogleClientRequest.java:321)
    at endpoints.repackaged.com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1065)
    at endpoints.repackaged.com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
    at endpoints.repackaged.com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
    at endpoints.repackaged.com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
    at com.google.api.control.Client.check(Client.java:205)

It's worth noting that the API seems to work -- I have the iOS simulator connecting to my local dev app server and making Endpoints calls.  I'm just tired of seeing the 403 in my browser every time I start the dev app server, and fear it may portend some similar issue in production when I eventually push this new service.

A: This error indicates that there is something wrong with the permissions or that the Service Control API is disabled in your project, so in order to fix it you can:

*

*Make sure your service has access to servicecontrol.googleapis.com enabled by running the following command on Cloud Shell:
gcloud services enable servicecontrol.googleapis.com

*Double check ENDPOINTS_SERVICE_NAME parameter in your appengine-web.xml file, it should look like this:
<env-var name="ENDPOINTS_SERVICE_NAME" value="$PROJECT"/>

*Check if OpenAPI specs are deployed to Cloud, you can check it by running this command on Cloud Shell:
gcloud endpoints configs list --service=$PROJECT

*Double check if the Service account running your instance has the proper IAM roles.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sections aren't continuous I'm a newbie in HTML and on my page, I have the problem that my two sections aren't continuous:

.privitanie{
position: absolute;
background: url("../images/pozadie.jpg");
background-repeat: no-repeat;
background-size: 100% 100%;
width: 100%;
height: 100%;
top: 0;
z-index: 0;
}

.uvod{
position: relative;
z-index: 0;
height: 100%;
}

...

...

A: Absolutely-positioned elements are outside the document flow. Other elements end up layered above or below, depending on their position in the markup. Make both relative, or give .uvod a top margin equal to the height of .privitanie.

A: Here's an easy solution that does not require changing too much of your code:
.uvod{
    position: relative;
    margin-top: 50%;
    z-index: 0;
    height: 100%;
}

Change margin-top to whatever you prefer.


text:
Q: Text losing style (even though css shows it should have it), but not if code is stepped through on console (jsfiddles included) (I have only confirmed this to happen so far with Safari 12.1.2 on MacOS Mojave)
So I have a contenteditable div with a styled span (red) and some text inside it. Nothing weird yet.
However, when I do some operations on the text (keeping all the text still within the same styled span) some of the text loses its style even though inspecting the DOM shows it should be styled (red).

Here's a jsfiddle illustrating the issue above:
1: https://jsfiddle.net/tx71pqmv/5/

$('#editable').keypress((event) => {
    if (event.key != 'Enter' || !event.shiftKey)
        return;
    event.preventDefault()
    let sel = window.getSelection()
    let range = sel.getRangeAt(0)
    let newLine = $('<span>')
        .addClass('br')
        .attr('contenteditable', 'false')[0]
    range.startContainer.splitText(range.startOffset) // 1
    range.insertNode(newLine) // 2
})

The weird thing is that this issue happens under VERY specific conditions.
For example, if I step through the code using the debugger, or use setTimeout to delay the execution by even 1ms (see jsfiddle #2), then everything works as intended.
Or, even just getting rid of the ::before pseudo-element on the containing div (not even the styled span) fixes the issue (see jsfiddle #3). This should be totally unrelated!
Is there a cleaner solution to the problem that doesn't involve compromising on the css or using setTimeout?
Edit: Adding screenshots of the DOM structure after pressing shift+enter on the first jsfiddle, and the second. The DOM structure on both look identical, but the one on the right doesn't have styling applied to one of the text nodes:

A: Here shift+Enter and Enter behaving differently for the #editable div

*

*Enter is creating a new child (div) of #editable div
means you have more child every time you press shift enter

*but Shift + Enter is creating new line inside the child div > span
browsers behave differently for contenteditables
as MDN says
Use of contenteditable across different browsers has been painful for a long time because of the differences in generated markup between browsers.

Read this for more info:
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Editable_content
new div created using enter


text:
Q: table.findElements(By.tagName("td") failing in RemoteWebDriver/Internet Explorer I have a series of Selenium tests that are ran remotely using Selenium Grid in internet Explorer.  The tests are working fine until they get to this line:
WebElement cart = driver.findElement(By.id("cartId");
List<WebElement> rows = cart.findElements(By.tagName("tr")); <----- fails here.

The code works perfectly when running locally using Chrome, and there are several steps in the remote IE test that run before that step.  If I replace table with driver' (to see if the issue is somehowfindElements) the tests pass (at that point).  There are certainlytr` elements in the table, and the stack trace gives me no good way to figure out what is happening (which I included below). Any help would be greatly appreciated.
[TestNG] Running:
  /Users/kroe761/Documents/workspace/ecom/testng.xml

Feb 28, 2017 2:13:01 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Attempting bi-dialect session, assuming Postel's Law holds true on the remote end
Feb 28, 2017 2:13:04 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS

FAILED: MyTest
org.openqa.selenium.WebDriverException: org/openqa/selenium/remote/server/handler/FindChildElements$1
Command duration or timeout: 80 milliseconds
Build info: version: '3.0.1', revision: '1969d75', time: '2016-10-18 09:49:13 -0700'
System info: host: 'kroe761-MacBook-Pro.local', ip: '10.11.25.155', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.12.3', java.version: '1.8.0_121'
Driver info: org.openqa.selenium.remote.RemoteWebDriver
Capabilities [{browserAttachTimeout=0, ie.enableFullPageScreenshot=true, enablePersistentHover=false, ie.forceCreateProcessApi=false, ie.forceShellWindowsApi=false, pageLoadStrategy=normal, ignoreZoomSetting=false, ie.fileUploadDialogTimeout=3000, version=11, platform=WINDOWS, nativeEvents=true, ie.ensureCleanSession=false, elementScrollBehavior=0, ie.browserCommandLineSwitches=, webdriver.remote.sessionid=0a293271-4edc-428e-b845-1b5ed71c0f1d, requireWindowFocus=false, browserName=internet explorer, initialBrowserUrl=http://localhost:4747/, takesScreenshot=true, javascriptEnabled=true, ignoreProtectedModeSettings=false, enableElementCacheCleanup=true, cssSelectorsEnabled=true, unexpectedAlertBehaviour=dismiss}]
Session ID: 0a293271-4edc-428e-b845-1b5ed71c0f1d
*** Element info: {Using=tag name, value=tr}
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:216)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:168)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:635)
    at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:274)
    at org.openqa.selenium.remote.RemoteWebElement.findElements(RemoteWebElement.java:193)
    at org.openqa.selenium.remote.RemoteWebElement.findElementsByTagName(RemoteWebElement.java:270)
    at org.openqa.selenium.By$ByTagName.findElements(By.java:327)
    at org.openqa.selenium.remote.RemoteWebElement.findElements(RemoteWebElement.java:169)
    at com.company.automation.ecom.pages.checkout.Cart.getCartItemRows(Cart.java:56)
    at com.company.automation.ecom.pages.checkout.Cart.getNumOfRowsInCart(Cart.java:74)
    at com.company.automation.ecom.tests.checkout.CheckoutHelper.comparePricesOnCart(CheckoutHelper.java:59)
    at com.company.automation.ecom.tests.checkout.CheckoutCreditCard.CreditCard(CheckoutCreditCard.java:102)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:80)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
    at org.testng.TestRunner.privateRun(TestRunner.java:767)
    at org.testng.TestRunner.run(TestRunner.java:617)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
    at org.testng.SuiteRunner.run(SuiteRunner.java:240)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1198)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1123)
    at org.testng.TestNG.run(TestNG.java:1031)
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:132)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:236)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:81)
Caused by: java.lang.NoClassDefFoundError: org/openqa/selenium/remote/server/handler/FindChildElements$1
    at org.openqa.selenium.remote.server.handler.FindChildElements.call(FindChildElements.java:50)
    at org.openqa.selenium.remote.server.handler.FindChildElements.call(FindChildElements.java:35)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at org.openqa.selenium.remote.server.DefaultSession$1.run(DefaultSession.java:176)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

===============================================
    Internet Explorer
    Tests run: 1, Failures: 1, Skips: 0
===============================================

===============================================
ECOM Suite
Total tests run: 1, Failures: 1, Skips: 0
===============================================

[TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 7 ms
[TestNG] Time taken by org.testng.reporters.JUnitReportReporter@22f71333: 5 ms
[TestNG] Time taken by org.testng.reporters.SuiteHTMLReporter@7e0ea639: 11 ms
[TestNG] Time taken by org.testng.reporters.XMLReporter@7f690630: 12 ms
[TestNG] Time taken by org.testng.reporters.jq.Main@71be98f5: 34 ms
[TestNG] Time taken by org.testng.reporters.EmailableReporter@6108b2d7: 4 ms

A: According to your log this has nothing to do with Internet Explorer driver or table elements, you have classpath issues on your remote machine while executing this tests there. You are getting NoClassDefFoundError on FindChildElements class.
I don't know how your build process and project structure looks like, but see here for more details how to solve this kind of trouble.


text:
Q: Android boot completed activity not found I am trying to code a service that started when device booted.
java.lang.RuntimeException: Unable to start receiver packagename.BootReciever: android.content.ActivityNotFoundException: Unable to find explicit activity class {packagename/packagename.MainActivity$Companion}; have you declared this activity in your AndroidManifest.xml?
In my manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="packagename">

    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.INJECT_EVENTS" />
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

    <application
        android:allowBackup="false"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.AppCompat.Translucent"
        android:fullBackupContent="@xml/backup_descriptor">
        <activity android:name="packagename.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name="packagename.RemoteService">
            <intent-filter>
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            </intent-filter>
        </service>

        <receiver android:name="packagename.BootReciever"
            android:enabled="true"
            android:exported="true">
            <intent-filter android:directBootAware="true">
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" />
                <action android:name="android.intent.action.QUICKBOOT_POWERON" />
                <action android:name="android.intent.action.REBOOT"/>
            </intent-filter>

        </receiver>

    </application>

</manifest>

When i open app, it will work well, however i want to launch application when boot completed. I push it into system/app and it crushes.
    override fun onReceive(p0: Context?, p1: Intent?) {
        if(p1?.action.equals("android.intent.action.BOOT_COMPLETED")){
            Log.e("Ahmet ","START PLSSSSSSSSSSSSS")
            val startIntent = Intent(p0,MainActivity.javaClass)
            startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            p0?.startActivity(startIntent)
        }
    }
}

MainActivity
class MainActivity : Activity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        appContext = applicationContext
        ServiceModul.startServices(this)
        finish()
    }

    companion object {
        lateinit var appContext: Context
    }

}

I signed the application, it has permissions, however on boot, it could not find MainActivity. I check package names like 3-4 times. What should i do?


text:
Q: Rotation - slowing it down using willAnimateSecondHalfOfRotationFromInterfaceOrientation people, how do you actually slow down the orientation-rotation when using the  "willAnimateSecondHalfOfRotationFromInterfaceOrientation:" method?
I currently have this:
-(void) willAnimateSecondHalfOfRotationFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
                                                       duration:(NSTimeInterval)duration {
    [self positionViews];
}

And I understand that this "willAnimate2ndHalf..." method gets called automatically when the rotation does indeed happen - well where do I actually get to change its DURATION value?

A: If you want to change the overall timing of he app's rotation, it can't be done. willAnimateSecondHalfOfRotationFromInterfaceOrientation is meant for adding custom code, like setting custom coordinates, properties, things like that.


text:
Q: Get data from url with RegExp I have the list of blogpost links on page

Post One

Post Two

Post Three

Post Four

Post Five

and want to get array of all numbers between slashes from this urls
$('a').each(function (index){
    var str = $(this).attr('href');
    var a = str.search(/[0-9]+/);
    var b = str.search(/-);
    console.log(str.substring(a,b));
});

smth like 7, 32, 382, 5782, 11682
http://jsfiddle.net/sYH56/

A: Like this -
var arr = $('a').map(function (index){
   var str = $(this).attr('href');
   var a = str.search(/[0-9]+/);
   var b = str.search(/\/-/);
   return str.substring(a,b);
}).get().join(',');

http://jsfiddle.net/sYH56/3/


text:
Q: Flatpickr inside of Bootstrap modal can not type in year input I have a problem with Flatpickr rendering in a Bootstrap modal.
When I open a Flatpickr entry within a modal, everything seems to work fine except for entering a year. When I want to click on the year, the input field does not work.

Thanks for help.
Flatpickr version 4.6.9 and Bootstrap version 5.1.1

A: In order to use the month and year picker you need to use the Flatpickr option static: true. This way it will not hide behind the modal.

$(document).ready(function() {
  const flatpickr_time = $('#flatpickr_time').flatpickr({
    //static: position the calendar inside the wrapper and next to the input element*.
    static: true
  });
});
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/flatpickr/4.6.11/flatpickr.min.css" rel="stylesheet" />

      <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">Launch modal</button>

        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>

        <input id="flatpickr_time" style="width:200px;">

A: I've had the same issue and while the solution proposed by Crezzur did work, it had some side effects that I didn't want.
I was able to find that the issue was caused by bootstrap being a bit too aggressive with the focus, which means it can be fixed simply by adding bs-focus="false" to your modal.
Example:


text:
Q: How do I get the range offsets of an entire div in Javascript? I am creating a range based on a user selection using the following method:
var selection = window.getSelection();
var beginsAt = selection.getRangeAt(0).startOffset;
var endsAt = selection.getRangeAt(0).endOffset;
return [beginsAt,endsAt];

The component that calls this function does the following:
let before = text.substring(0, range[0]);
let highlighted = text.substring(range[0], range[1]);
let after = text.substring(range[1], text.length);
return(

            {before}

                {highlighted}

            {after}

)

Whenever I select my text, the range is always relative to where the highlighted span ends. So if my text is on a range between 0 and 50 and I select the range [25,26] then select the range [26,27], rather than highlighting the range [26,27] it highlights the range from [0,1] because the range was [0,1] relative to the text generated by {after}.
As long as I highlight any text rendered by {before} I have no issues, its only when I highlight something rendered in the {after} section.
How can I make these range values relative to the root of the entire text rather than relative to the blocks that they are rendered in? Is this a limitation of react or my implementation?

A: Most likely you are getting [0,1] because that is the offset in the current node. What you need is the offset within the collection of nodes in the parent node. I think this answer has what you need: https://stackoverflow.com/a/26477716/4650008

A: The issue is most certainly with the implementation and not a limitation of javascript or react (at least in the way that question is proposed here).
Rather than try and force the indexes to conform to a parent container it is much easier to simply offset them based on a previous selection.
The method that gets the selection can be modified to contain the following:
(relativityFlag) => {
    var selection = window.getSelection();
    var beginsAt = selection.getRangeAt(0).startOffset;
    var endsAt = selection.getRangeAt(0).endOffset;

    if(relativityFlag){
        beginsAt += endsAt;
        endsAt += endsAt;
    }
    return [beginsAt, endsAt]
}

Where the relativity flag is true if the selection is inside of the {after} render block.
This is one of many different ways to conform the index to a greater range but is of the simplest to implement.


text:
Q: CodeIgniter4: Like or dislike feature allows both but want to limit one vote per user I am trying to implement a like (unlike) or dislike (undislike) feature to my image upload site. I am using AJAX to accomplish this and so far I have been able to limit users to one view of each upload page but I cannot restrict users to one vote of like OR dislike. They can do both currently.
The problem is in my model ActionModel.php:
public function insertAction(array $request)
    {
        $image = new \App\Entities\Image();

        $request = $this->updateModified($request);

        switch($request['action']) {

            case 'dislike':

                $data = [
                    'action'    => 0,
                    'username'  => session()->get('username'),
                    'viewkey'   => $request['viewkey'],
                    'modified_at'  => $request['modified_at'],
                ];

                $image->setUserLiked($request['viewkey']);

                if ($image->userLiked === FALSE) {

                    $this->builder()
                        ->insert($data);

                } else {

                    $this->builder()
                        ->set($data)
                        ->where(['action' => 1, 'username' => $data['username'], 'viewkey' => $data['viewkey']])
                        ->replace();
                }

                unset($image->setUserLiked);

                break;

            case 'undislike':

                $this->builder()
                    ->where('action', 0)
                    ->delete();

                break;

            case 'like':

               $data = [
                    'action'    => 1,
                    'username'  => session()->get('username'),
                    'viewkey'   => $request['viewkey'],
                    'modified_at'  => $request['modified_at'],
                ];

                $image->setUserDisliked($request['viewkey']);

                if ($image->userDisliked === FALSE) {

                    $this->builder()
                        ->insert($data);

                } else {

                    $this->builder()
                        ->set($data)
                        ->where(['action' => 0, 'username' => $data['username'], 'viewkey' => $data['viewkey']])
                        ->replace();
                }

                unset($image->userDisliked);

                break;

            case 'unlike':

                $this->builder()
                    ->where('action', 1)
                    ->delete();

                break;

            case 'view':

               $data = [
                    'action'    => 2,
                    'username'  => session()->get('username'),
                    'viewkey'   => $request['viewkey'],
                    'modified_at'  => $request['modified_at'],
                ];

                $image->setUserViewed($request['viewkey']);

                if ($image->userViewed == FALSE) {

                    $this->builder()
                        ->insert($data);

                } else {

                    $this->builder()
                        ->set(['modified_at' => $data['modified_at']])
                        ->where(['action' => 2, 'username' => session()->get('username'),  'viewkey' => $data['viewkey']])
                        ->update();
                }

                unset($image->userViewed);

                break;

            case 'favorite':

               $data = [
                    'action'    => 3,
                    'username'  => session()->get('username'),
                    'viewkey'   => $request['viewkey'],
                    'modified_at'  => $request['modified_at'],
                ];

                $image->setUserFavorited($request['viewkey']);

                if ($image->userFavorited === FALSE) {

                    $this->builder()
                        ->insert($data);
                }

                unset($image->userFavorited);

                break;

            case 'unfavorite':

                $this->builder()
                    ->where('action', 3)
                    ->delete();

                break;

            default:

                break;
        }

        return $this->getActions($request['viewkey']);
    }

    public function getActions(string $viewkey)
    {
        $data = [];

        $image = $this->imageModel->fillImageEntity($viewkey);
        $image->setDislikeCount($viewkey);
        $image->setLikeCount($viewkey);
        $image->setViewCount($viewkey);
        $image->setFavoriteCount($viewkey);

        $data = [
            'csrfName'  => csrf_token(),
            'csrfHash'  => csrf_hash(),
            'dislikes'  => $image->dislikeCount,
            'likes'     => $image->likeCount,
            'views'     => $image->viewCount,
            'favorites' => $image->favoriteCount,
        ];

        unset($image->dislikeCount);
        unset($image->likeCount);
        unset($image->viewCount);
        unset($image->favoriteCount);

        return json_encode($data);
    }


text:
Q: How to print printer model on a PDF file How to print printer model on a PDF file when I print the file?
Anyone know the correct Javascript to obtain this result?

A: I don't think you can do this.  Once the user has a PDF open on your site, it's a bit out of your hands: they have the PDF, and when they go to print it, the dialog box to choose a printer is provided by the system--not by your site, and maybe not even by the browser, really.  I don't see how you can influence the content of the about-to-be-printed PDF between the time that the user chose to print it and the time that it actually is committed to paper.


text:
Q: proving montonity and convergence of sequence en = (1 + 1/n)^n Prove the following. What would be the summation formula be for the first part?

A: From the Binomial Theorem, we have
$$\begin{align}
e_n&=\left(1+\frac1n\right)^n\\\\
&=\sum_{k=0}^n\binom{n}{k}\left(\frac1n\right)^k\\\\
&=1+n\left(\frac1n\right)+\frac{n(n-1)}{2!}\left(\frac1n\right)^2+\cdots+\frac{(n)(n-1)(n-2)\cdots(n-(n-1))}{n!}\left(\frac1n\right)^n\\\\
&=1+1+\frac1{2!}\left(1-\frac1n\right)+\frac1{3!}\left(1-\frac1n\right)\left(1-\frac2n\right)\\\\
&+\cdots+\frac1{n!}\left(1-\frac1n\right)\left(1-\frac2n\right)\cdots\left(1-\frac{n-1}n\right) \tag 1
\end{align}$$
as was to be shown!

To show that $e_n$ is increasing we will show that $\frac{e_{n+1}}{e_n}\ge 1$.  To that end, we write
$$\begin{align}
\frac{e_{n+1}}{e_n}&=\frac{\left(1+\frac{1}{n+1}\right)^{n+1}}{\left(1+\frac{1}{n}\right)^n}\\\\
&=\left(\frac{n(n+2)}{(n+1)^2}\right)^{n+1}\left(1+\frac1n\right)\\\\
&=\left(1-\frac{1}{(n+1)^2}\right)^{n+1}\left(1+\frac1n\right) \tag 2\\\\
&\ge\left(1-\frac{1}{n+1}\right)\left(1+\frac1n\right) \tag 3\\\\
&=1
\end{align}$$
where in going from $(2)$ to $(3)$, we used Bernoulli's Inequality.  Thus, $e_n$ in monotonically increasing; and we are done!

From $(1)$ is trivial to see that $e_n\ge 2$ for $n\ge 1$.
Noting that all of the parenthetical terms are less than $1$, and $n!>2^{n-1}$ for $n\ge2$, then for $n\ge 2$, we have
$$e_n\le 1+1+\sum_{k=1}^\infty \frac{1}{2^k}=3$$
Thus, we conclude that $e_n$ is a monotonically increasing sequence that is bounded above by $3$.  Therefore, $e_n$ converges to some real number betweem $2$ and $3$.  And we are done!

A: To prove (a) and (b) use the binomial theorem. To prove (c) use the hint, that is, bound $e_n$ above by a geometric progression with ratio $1/2$.

A: Hint: Binomial theorem and
$$1-\frac{k}{n+1} > 1-\frac{k}{n}$$


text:
Q: How to fix No route matches [GET] "/pages/send_form" routing error? I am setting up so a user is able to send an email using the contact us form. I have created a file called "send_form" so once the submit button is clicked, the message automatically displays "Thanks for contacting us".
In the past, I have tried to include different routing in the routes.rb for example, "pages#send_form" and "contact#send_form".
# Example of regular route:
  get 'about' => 'pages#about'
  get 'contact' => 'pages#contact'
  get 'news' => 'pages#news'
  get 'show' => 'topics#index'
  get 'send_form' => 'pages#send_form'
  get 'new' => 'booking#new'

views/pages/contact.html:

Any enquiries:

<form name="htmlform" method="get" action="/pages/send_form">

<form id="contact_form" action="#" method="POST" enctype="multipart/form-data">

    Your Name:

    <input id="name" class="input" name="name" type="text" value="" size="30" />

    Your Email:

    <input id="email" class="input" name="email" type="text" value="" size="30" />

    Your Message:

    <textarea id="message" class="input" name="message" rows="7" cols="30"></textarea>

  <input id="submit_button" type="submit" value="Send email" />
</form>

views/pages/send_form

Thanks for contacting us,

I expect the output to be "Thanks for contacting us" once the submit button is clicked. However, I am receiving the error of "No route matches [GET] "/pages/send_form"

A: Change get 'send_form' => 'pages#send_form' to get 'pages/send_form' => 'pages#send_form'.
Or instead change the action of your form to action="/send_form"


text:
Q: chmod command to persist file permissions This is part of Ansible automation where I have to run a single chmod command and read the permission from the users. Thus,
chmod -R $fileperm <filename>
However, at times the user may not provide any fileperm thus $fileperm is empty in which case the file permissions should remain unchanged however the above command fails.
I do not wish to have two chmod commands having different when conditions.
Can you please suggest how can I accommodate whether the user provides or does not provide permissions in the same command if possible? I am currently using Ansible's command module to execute chmod.

A: Don't call chmod via command or shell. Use the file module to set permissions, see documentation. This is idempotent. The module will check the current state of the file/directory and will only change it, if necesary.
In that case, you add this task
- set_fact:
    files:
      - name: file1
        mode: 0755
      - name: file2
      - name: file3
        mode: 0644

- file:
    path: "{{ item.name }}"
    mode: "{{ item.mode | default(omit) }}"
  loop: "{{ files }}"

I'm not sure, what you mean with "at times the user may not provide". Ansible is nothing interactice. So I'm not sure, what you mean. Also you're talking about bash vars like $fileperm. Ansible has no "bash vars". They are facts and uses Jinja to evaluate them.


text:
Q: Users get logged out when they click on a hyperlink C# application users gets logged out whenever they click on a hyperlink (not the logout button). The application is tied in with MS Sql closely and whenever the user click link 1, they get logged out from the application, log back in, click link 1 again, and get logged out.
In addition, it is not always the same link. Other times it changes to a different link. Also, it sometimes happen to two users at the same time. Sometimes they both have issue clicking on one of the links. Other times, one have issue with link 1 and another have issue with link 2.
I had all users use CCleaner to clear up all of their cache and what not. It fixes it for an hour or so then it comes back. It also happens in incognito/private mode. Happens on multiple browsers.
The application and database is hosted on Hostgator windows shared server (trying to move out but owner doesn't want to pay the money).
I uploaded the same application to a GoDaddy server and so far so good, minus the constant log out after 10-15 minutes. I haven't heard of anyone getting logged out because they clicked on a hyperlink.
Those links open in the same page. Not a new tab. The database isn't that big. About 2 GB. There are about 400 records in our most used table.
I googled this for few days now and I haven't read of anyone having the exact issue or similar to what I have.
Also, the application have been working well and never experienced this until recently.
Anyone have any idea what's going on? I don't think it is a problem within the application because I didn't make any changes when it comes to sessions. It just started doing it after hostgator server went down last week. I talked with hostgator and they said it is an issue with my cache, which is part of truth.

A: Unfortunately you got a Serious Problem.
To that link as you've said kindly check the code i suspected it 100% it has an action its either your session expired, directing to other page with session expired or logout function called, or maybe its in your javascript html there's various of causes why it is triggering.
Just giving you some possible cases.
Hope it helps.


text:
Q: Dollar Object intricacies I am reading Kent Beck's book "Test Driven Development: By Example." In his book, there is a coding example:
public class Dollar
{
    public int _amount;
    public Dollar(int amount)
    {
        _amount = amount;
    }
    public Dollar Times(int multiplier)
    {
        return new Dollar(_amount *= multiplier);
    }
}

[TestMethod]
public void TestMethod2()
{
    Dollar five = new Dollar(5);
    Dollar product = five.Times(2);
    Assert.AreEqual(10, product._amount);
    product = five.Times(3);
    Assert.AreEqual(15, product._amount);
}

According to Kent, a second Dollar object: "product," is necessary in order to preserve the original "five" dollar object; however, the second assertion returns false because product._amount is equal to 30. I have been unable to find any errata on this text. How would Kent's code above need to change in order to have the second assertion equal true or 15 == 15? Is the book's example flawed? Why does product._amount in the second assertion not equal 15?

A: As has been said in the comments, this:
public Dollar Times(int multiplier) {
    return new Dollar(_amount *= multiplier);
}

Should be:
public Dollar Times(int multiplier) {
    return new Dollar(_amount * multiplier);
}

In its original form, the *= operator modifies the _amount variable of the instance of the Dollar class that Times is called on.  Removing the = changes the operation so that it only reads the value of the _amount variable and uses it in the calculation.


text:
Q: Script tag is missing when printing a javascript escaped text

<!DOCTYPE html>

Click the button to trigger a function that will output "Hello World" in a p element with id="demo".

<button onclick="myFunction()">Click me</button>

Im setting "demo" elements innerHtml to the escaped version of Python Auto  alert("JavaScript alert"); .
If you run this html and click on the "Click me" button. You can see the result as "Python Auto". The script tag is missing. Why this is happening ? How come the script tag and the content of it is missing ?

A: Need to use &lt for <, &gt for >, and \" for ". Everything else should be fine to use the actual characters, see below.

<!DOCTYPE html>

Click the button to trigger a function that will output "Hello World" in a p element with id="demo".

<button onclick="myFunction()">Click me</button>

A: !!!Please see the comment below, also, please make your question a bit more clear!!!
Instead of using \x3C you can use &#x3C because somehow it is escaping rest of the string,
<!DOCTYPE html>

Click the button to trigger a function that will output "Hello World" in a p element with id="demo".

<button onclick="myFunction()">Click me</button>


text:
Q: Should a File Delete Operation Throw an Exception if the File Doesn't Exist The answer may be context dependent or this may not be the right place, so let me know if https://softwareengineering.stackexchange.com/ is a more suitable site.
We're re-working all of the file I/O in our app to be programmed to an interface instead of the existing tightly coupled System.IO implementation.  The current code has lots of File.Exists() checks before calling File.Delete().  We have the opportunity to put the File.Exists() check in the implementation that deals with the System.IO and remove them from the consuming code, so something like
private IFileSystem fileSystem;

void methodName()
{
    string filePath = "c:\\file.txt";
    if (fileSystem.Exists(filePath)
        fileSystem.Delete(filePath);
}

could simply become:
private IFileSystem fileSystem;

void methodName()
{
    string filePath = "c:\\file.txt";
    fileSystem.Delete(filePath);
}

The question is, is there any reason that fileSystem.Delete() should throw an exception if the file doesn't exist?  We can't think of a good reason for our domain, but it seems strange to not throw an exception when we're so used to the framework API behaving a certain way.  We aren't a super experienced bunch with different languages and platforms, so we don't much to compare this to.
It would be nice, from the code consumer's perspective, to just delete the file and not have to check every time.  That seems like a win.  But are there any known dangers with this line of thinking?
EDIT*
I should add that the whole point of the operation is to allow us to talk to Azure BLOB storage, where the APIs are different.  So staying close to .NET conventions in System.IO isn't essential.

A: Plenty of reasons for File.Delete() to throw, particularly when you try to delete a file in the C:\ directory.  But no, not because it doesn't exist.
Pretty important to understand why it works this way.  From the way your snippet looks, you are making a huge mistake by relying on File.Exists() too much.  Which is a very weak guarantee on a multi-tasking operating system.  All that you know is that a file did/didn't exist at the moment in time that Exists() ran.  It says absolutely nothing about the file state after that.  Another process may well delete or create the file a microsecond later.  By not needing the check, you can safely delete the file without that race condition crashing your program.
Note that File.Exists() is evil in many other cases as well.  Like only opening a file after checking that it exists.  That just can't work reliably for the same reason, another process may of course delete the file right between the check and the attempt to open it.  The only way to be sure is by opening it without checking.  If it wasn't there then the exception tells you about it.
If this sounds a lot like a thread race problem then you're right, that's exactly what it is.  But usually without a way to use anything like a lock statement to ensure that another process doesn't screw you up.  It is possible, you could use a named Mutex to arbitrate access to file.  The typical problem is that you'll have to deal with a process that doesn't know beans about it.

A: The caller might want to know whether a file existed or not. Return this information in a status enum or a bool. Exceptions are for unexpected errors or even usage errors. This is a totally expected case.
I think the .NET file system APIs get this wrong a lot. They do not pass on all the information that Win32 makes available. Often, you cannot even find out what error occurred without parsing the exception text.

A: Why would you swallow potentially critical information?
What if the delete was throwing an UnauthorizedAccessException because the program was being run under different credentials?
What if the file had a lock that was preventing the delete?
Don't assume bad unexpected stuff is not going to happen.


text:
Q: DataStax opscenterd won't start on Ubuntu 15.04 x64 Issue:

sudo service opscenterd start
  Failed to start opscenterd.service: Unit opscenterd.service failed to load: No such file or directory.
  (ERROR)-(Exit Code 6)-(Unknown error code)
sudo service opscenterd status
  opscenterd.service
     Loaded: not-found (Reason: No such file or directory)
     Active: inactive (dead)

Config

[webserver]
  port = 8888
  interface = 0.0.0.0

I tried another port and ip (localhost)

*

*Cassandra installed and running (dsc21, cassandra 2.1.10)

*no log files been generated in /var/log/opscenter/

*opscenter installed via apt-get (5.2)

Please help me to resolve this issue

A: I have the same issues as you, seems like OpsCenter could not run as service on Ubuntu 15, I went running it as background process and it works,
try:
$ sudo your_opscenter_install_path/bin/opscenter
hope helpping


text:
Q: GWT - Avoid to listen to events I'm using SliderBar widget from Google Web Toolkit Incubator. By default, this widget listens to some keyboard events, e.g. left arrow. I'd like to know if there's a way to avoid the widget listens to those events.
I'm using UiBinder and tried to use the function unsinkEvents but nothing happens. Here's the snippet of code:
@UiField(provided = true)
    SliderBar slbRotate;
public NewViewImpl() {
    slbRotate = new SliderBar(-180,180);
    slbRotate.setStepSize(10);
    slbRotate.setCurrentValue(0);
    slbRotate.setWidth("478px");
    slbRotate.setHeight("22px");
    slbRotate.unsinkEvents(Event.KEYEVENTS);
    initWidget(binder.createAndBindUi(this));

}

I also used KeyCodes.KEY_LEFT in the argument of the unsinkEvents function, but doesn't work either.
Thanks.

A: With the
unsinkEvents

function.
I created  a short example to show the basics:
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.TextBox;

public class ExtendedTextBox extends TextBox {
    public ExtendedTextBox() {
        sinkEvents(Event.KEYEVENTS);
    }

    @Override
    public void onBrowserEvent(Event event) {
        Window.alert("keypress");
    }

    public void unSinkKeyEvent(){
        unsinkEvents(Event.KEYEVENTS);
    }
}

This example creates a TextBox and whenever you press a key two MessageBoxes (one for the keydown one for the keyup) pop up. If you call the unSinkKeyEvent function this behafios stops.
So if you don't want to have speciffic behavior on SliderBar widget you just have too call the unsinkEvents function an specify the event you don't want to have (just look at the help)
Regards,
Stefan


text:
Q: Can i export BUS routes from OpenStreetMap as shapefiles to work on ArcMap? The OSM has all the routing for the buses in my city, even showing the ID of the bus if you zoom close enough. I know how to download the shapefiles with the roads, rails, etc., from Geofabrik, but the bus routing isn't included there.
If I can't get access to this routes in ArcMap, I'll have to draw them one by one, which doesn't make that much sense since that work has already been done. Please, can someone help me?

A: When you need some kind of special or selective data from openstreetmap it's always a good idea to reach them via overpass. Here is a piece of code to get lines of route=bus
<osm-script output="json" timeout="25">
  <union>
    <query type="relation">
      <has-kv k="route" v="bus"/>
      <bbox-query {{bbox}}/>
    </query>
    <recurse type="relation-way"/>
    <recurse type="way-node"/>
  </union>
  <print mode="body"/>
  <print mode="skeleton" order="quadtile"/>
</osm-script>

This link will take you stright to the site with filled query - all you have to do is scroll the map to desired area, run the query and export results to file.


text:
Q: how to use the extension RealURL I wanted to use the extension RealURL in my website,I installed it in the extensions, and this is my configuration file:
    <?php
$GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl'] = array (
    '_DEFAULT' => array (
        'init' => array (
            'enableCHashCache' => '1',
            'appendMissingSlash' => 'ifNotFile',
            'enableUrlDecodeCache' => '1',
            'enableUrlEncodeCache' => '1',
            'emptyUrlReturnValue' => '/',
        ),
        'redirects' => array (
//          'de/aerzte.html' => '/?id=51&L=3',
        'support.html' => 'go/support-active'
        ),
        'preVars' => array (
            '0' => array (
                'GETvar' => 'no_cache',
                'valueMap' => array (
                    'nc' => '1',
                ),
                'noMatch' => 'bypass'
            ),
            '1' => array (
                'GETvar' => 'L',
                'valueMap' => array (
                    'de' => '3',
                    'en' => '0',
                    'fr' => '6',
//                    '_DEFAULT' => '0',
                ),
                'noMatch' => 'bypass',
            ),
        ),
        'pagePath' => array (
            'type' => 'user',
            'userFunc' => 'EXT:realurl/class.tx_realurl_advanced.php:&tx_realurl_advanced->main',
            'spaceCharacter' => '-',
            'languageGetVar' => 'L',
            'expireDays' => '7',
            'rootpage_id' => 3,
        ),
        'fixedPostVars' => array (
        ),
        'postVarSets' => array (

            '_DEFAULT' => array (

        // EXT:news start
        'news' => array(
                array(
                        'GETvar' => 'tx_news_pi1[action]',
                ),
                array(
                        'GETvar' => 'tx_news_pi1[controller]',
                ),
                array(
                        'GETvar' => 'tx_news_pi1[news]',
                        'lookUpTable' => array(
                                'table' => 'tx_news_domain_model_news',
                                'id_field' => 'uid',
                                'alias_field' => 'title',
                                'addWhereClause' => ' AND NOT deleted',
                                'useUniqueCache' => 1,
                                'useUniqueCache_conf' => array(
                                        'strtolower' => 1,
                                        'spaceCharacter' => '-',
                                ),
                                'languageGetVar' => 'L',
                                'languageExceptionUids' => '',
                                'languageField' => 'sys_language_uid',
                                'transOrigPointerField' => 'l10n_parent',
                                'autoUpdate' => 1,
                                'expireDays' => 180,
                        ),
                ),
        ),
        // EXT:news end

            ),
        ),
        'fileName' => array (
//
// if you don't want .html-URLs set the following to "false" (e.g. 'defaultToHTMLsuffixOnPrev' => false,)
// then you get http://www.yourdomain.com/imprint/ instead of http://www.yourdomain.com/imprint.html
//
            'defaultToHTMLsuffixOnPrev' => false,
            'index' => array (
                'rss.xml' => array (
                    'keyValues' => array (
                        'type' => '100',
                    ),
                ),
                'rss091.xml' => array (
                    'keyValues' => array (
                        'type' => '101',
                    ),
                ),
                'rdf.xml' => array (
                    'keyValues' => array (
                        'type' => '102',
                    ),
                ),
                'atom.xml' => array (
                    'keyValues' => array (
                        'type' => '103',
                    ),
                ),
            ),
        ),
    ),

);

$domains = array(
    '_DEFAULT' => '3',
);
foreach ($domains as $domain=>$pid) {
    $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl'][$domain] = $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl']['_DEFAULT'];
    $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl'][$domain]['pagePath']['rootpage_id'] = $pid;
}
//$GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['realurl']['www.****.com']['pagePath']['rootpage_id'] = 3;
?>

I excluded the pages i don't want in the url, and i deleted all the entries, i noticed the urls were changed, but the pages are not openeing anymore.
I flushed the three caches.
Thank you in advance.
edit: this was my url
https://www..com/en/blog/blog/article/
i went to the first blog and exluded it from speaking url
and the second one i set it to override the whole page path
and in article i excluded it also from speaking URL
then i went to articles entries and deleted all of them
then this link worked fine:
https://www..com/en/blog/article/
but this not:
https://www.***.com/en/blog
I got this in the extension in both blog pages :
URL conflict detected: 'en/blog/' is also used on page(s): 865 (/Home/Blog)
URL conflict detected: 'de/blog/' is also used on page(s): 722 (/Home/Blog/Blog)

A: For use TYPO3 RealURL extension you need to use below configuration.
add below typoscript in setup.ts.
config.simulateStaticDocuments = 0
config.tx_realurl_enable = 1

If .htaccess file not present in your root directory then add it.
check your apache configuration and if mod_rewrite is not enable then enable it.
Enable mod_rewrite  use below command for linux.
a2enmod rewrite
service apache2 restart

Use Below realURL configuration.
'fixedPostVars' => array(
    'newsDetailConfiguration' => array(
        array(
          'GETvar' => 'tx_news_pi1[action]',
          'valueMap' => array(
            'detail' => '',
          ),
          'noMatch' => 'bypass'
        ),
        array(
          'GETvar' => 'tx_news_pi1[controller]',
          'valueMap' => array(
            'News' => '',
          ),
          'noMatch' => 'bypass'
        ),
        array(
          'GETvar' => 'tx_news_pi1[news]',
          'lookUpTable' => array(
            'table' => 'tx_news_domain_model_news',
            'id_field' => 'uid',
            'alias_field' => 'title',
            'addWhereClause' => ' AND NOT deleted',
            'useUniqueCache' => 1,
            'useUniqueCache_conf' => array(
              'strtolower' => 1,
              'spaceCharacter' => '-'
            ),
            'languageGetVar' => 'L',
            'languageExceptionUids' => '',
            'languageField' => 'sys_language_uid',
            'transOrigPointerField' => 'l10n_parent',
            'expireDays' => 180,
          )
        )
    ),
    'blog-page-id' => 'newsDetailConfiguration',
),


text:
Q: Filter object key not working Note: I already read and try all answers inside this question. Unfortunately, it's not working for me and I got no luck.
I create a simple Angular app to play around with CurrencyLayer API. My app is working great but only 1 thing didn't work.
I couldn't filter the currency key. What I want is, when user type in their currency inside the search box, the currency is filtered out in the ul div.
filter:{key:searchCurrency} is not working for me.
This is my code:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Angular Currency Converter</title>

    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">

Base currency: {{sourceCurrency}}

                Amount
                <input type="number" ng-model="amount" class="form-control" />

                Search
                <input ng-model="searchCurrency" class="form-control" placeholder="Search currency"/>

searchCurrency: {{searchCurrency}}

{{amount}} {{sourceCurrency}} is equavalent to:

{{key.slice(3,6)}}: {{quote * amount | number : 2}}

Sample JSON data like inside this Gist.
Plunker
How to make the search filter works?


text:
Q: ksh "getopts" -- Unsetting an Option I use the "getopts" ksh built-in to handle command-line options, and I'm looking for a clean/standard way to "unset" an option on the command line. I don't know if this is a technical question about getopts or more of a style/standards question. Anyway, I understand that getopts processes its args (by default $*) from left to right, and I'm hoping to use that to allow a second specification of an option to "turn off" an option.
For options that take an option argument, this isn't a problem. In my getopts processing case statement I just say, for the "-x" option, for example:
x ) x_arg=$OPTARG
    ;;

and the last instance of "-x" on the command line wins, which is what I want.
The problem comes in with options that don't take an option argument. If the option is just a switch/flag then my case statement would just have something like:
x ) x_specified=1
    ;;

With an option like this all I can really do is add "-x" again on the command line, and the same thing just happens: "x_specified=1" is executed again. What's the best/easiest/simplest/standardest way to "unset x_specified"? That's my question.
I had hoped to invoke the getopts functionality that allows either "+" or "-" to precede option letters, but it seems there's no way to tell within the getopts processing loop whether "+" or "-" was used. If there were a way to tell then I could adopt the standard that "+" means to turn off the setting. The other thing I could do is something like:
x ) if [[ -z $x_specified ]] ; then
        x_specified=1
    else
        unset x_specified
    fi
    ;;

Now the "-x" option would be a toggle; each time it's seen on the command line the setting changes. However, I'd like a way on the command line to say, "turn off the -x setting," and not just "toggle the -x setting." I could also pick some other letter, e.g. "X", as the way to turn it off, but many of my scripts already use both the upper case and lower case versions of the same letter to mean different things, and if I have to pick some other random letter to mean "turn off -x" then that's not very mnemonic, and my scripts are hard enough to learn how to use already.
Finally, you may ask, "If you want -x off on the command line, why are you turning it on in the first place?" Option processing in my scripts goes through a multi-step process. Command-line options are checked, and also a config file is checked for options, and there's a precedence between the two. This all works fine for options that take an option argument, but the scheme falls apart for options that don't.

A: I've got ksh93, and it allows + options if the the optstring starts with "+":
while getopts +abc opt; do
    echo "have option '$opt'"
done

Running this:
$ ./args.ksh -a -b -c +b -b foo
have option 'a'
have option 'b'
have option 'c'
have option '+b'
have option 'b'
$ ksh --version
  version         sh (AT&T Research) 93u+ 2012-08-01

One ambiguity I see in the man page: it says that the ":" option must also be the "leading" character in the optstring.
http://linux.die.net/man/1/ksh93


text:
Q: Mongoose - Does where cause a extra query? For MongoDB and Mongoose, does this cause 2 queries because of the where clause? Like findAndModify does because it returns the whole document before modifying?
Model.where({ _id: id }).update({ title: 'words' })

A: Nope, but neither does findAndModify, as in both cases the entire command is executed atomically by the MongoDB server.
To confirm, you can see the commands that Mongoose is executing by adding the following to your code:
mongoose.set('debug', true);


text:
Q: Can an Anti nuclear atom be synthesised so it can neutralise the effect of nuclear atom as we have studied that if the number of electron becomes equal to number of proton then that particle becomes neutral. so what will the energy or procedure required to break the chain reaction  in that nuclear process so that it can never resume back.

A: I'm not sure if I understand your question correctly, but here is some background.
Most atoms are neutral because they do have an equal number of protons and electrons. However, the electrons only control chemical reactions, not nuclear ones. Nuclear reactions happen in the nucleus, i.e. the neutrons and protons. In a nuclear fission bomb, the uranium and plutonium atoms are neutral - until the energy of the explosion strips the electrons of the atoms. In a fusion bomb, a fission reaction is used to first remove the electrons, so that the nuclei of the fissionable material (deuterium and tritium) can get into contact with each other and fuse.


text:
Q: How to enumerate the USB devices attached to a hub in Windows I want to get a list of all the USB devices attached to a Windows machine. The following program does this perfectly except that it only finds the USB devices attached directly to the PC including hubs but not the devices attached to the hubs:
void MainWindow::getConnectedUSB()
{
    GUID GUID_DEVINTERFACE_USB_HUB={ 0xf18a0e88, 0xc30c, 0x11d0, {0x88, 0x15, 0x00, 0xa0, 0xc9, 0x06, 0xbe, 0xd8} };
    GUID GUID_DEVINTERFACE_USB_DEVICE ={ 0xA5DCBF10L, 0x6530, 0x11D2, { 0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED } };
    GUID GUID_DEVINTERFACE_USB_HOST_CONTROLLER={ 0x3abf6f2d, 0x71c4, 0x462a, {0x8a, 0x92, 0x1e, 0x68, 0x61, 0xe6, 0xaf, 0x27}};
    getConnectedUSB(&GUID_DEVINTERFACE_USB_DEVICE);
    getConnectedUSB(&GUID_DEVINTERFACE_USB_HUB);
    getConnectedUSB(&GUID_DEVINTERFACE_USB_HOST_CONTROLLER);
}

void MainWindow::getConnectedUSB(GUID *ClassGuid)
{
    HDEVINFO                         hDevInfo;
    SP_DEVICE_INTERFACE_DATA         DevIntfData;
    PSP_DEVICE_INTERFACE_DETAIL_DATA DevIntfDetailData;
    SP_DEVINFO_DATA                  DevData;

    DWORD dwMemberIdx = 0;
    DWORD dwSize;

    hDevInfo = SetupDiGetClassDevs(ClassGuid, NULL, 0, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);

    if (hDevInfo != INVALID_HANDLE_VALUE)
    {
        DevIntfData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);

        SetupDiEnumDeviceInterfaces(hDevInfo, NULL, ClassGuid, dwMemberIdx, &DevIntfData);

        while(GetLastError() != ERROR_NO_MORE_ITEMS)
        {
            DevData.cbSize = sizeof(DevData);
            SetupDiGetDeviceInterfaceDetail(hDevInfo, &DevIntfData, NULL, 0, &dwSize, NULL);
            DevIntfDetailData = reinterpret_cast<PSP_DEVICE_INTERFACE_DETAIL_DATA>(HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwSize));
            DevIntfDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);

            if (SetupDiGetDeviceInterfaceDetail(hDevInfo, &DevIntfData, DevIntfDetailData, dwSize, &dwSize, &DevData))
            {
                QString devicePath = QString::fromWCharArray(DevIntfDetailData->DevicePath);
                qDebug() << devicePath;
                if (devicePath.startsWith("\\\\?\\usb#vid"))
                        m_connectedUSB.push_back(devicePath);
            }

            HeapFree(GetProcessHeap(), 0, DevIntfDetailData);
            SetupDiEnumDeviceInterfaces(hDevInfo, NULL, ClassGuid, ++dwMemberIdx, &DevIntfData);
        }

        SetupDiDestroyDeviceInfoList(hDevInfo);
    }
}

It uses a little bit of QString magic to collect the DevicePath data into m_connectedUSB which is a QStringList but otherwise it is all regular Windows system calls. What more do I need to do get it to iterate around the devices attached to hubs (and hubs attached to hubs and so forth - I'd like it to get everything)?

A: This isn't a great answer since all it does is call PowerShell to get the work done. However it is much better than nothing, and because it returns the data as a JSON string it should be fairly robust.
int MainWindow::getConnectedPNP()
{
    QProcess process;
    QString program = "PowerShell";
    QStringList arguments;
    // PowerShell -Command "& {Get-PnpDevice | Select-Object Status,Class,FriendlyName,InstanceId,Manufacturer,Present | ConvertTo-Json}"
    arguments << "-Command" << "& {Get-PnpDevice | Select-Object Status,Class,FriendlyName,InstanceId,Manufacturer,Present | ConvertTo-Json}";
    process.start(program, arguments);
    if (!process.waitForStarted()) return __LINE__;
    if (!process.waitForFinished()) return __LINE__;
    QByteArray result = process.readAll();
    QJsonDocument jsonDoc = QJsonDocument::fromJson(result);
    if (jsonDoc.isNull()) return __LINE__;
    if (!jsonDoc.isArray()) return __LINE__;
    QJsonArray jsonArray = jsonDoc.array();
    for (auto &&it : jsonArray)
    {
        if (!it.isObject()) continue;
        QJsonObject obj = it.toObject();
        if (obj["Status"].toString() != "OK") continue;
        if (obj["Present"].toBool() != true) continue;
        m_connectedPNPClass.push_back(obj["Class"].toString());
        m_connectedPNPFriendlyName.push_back(obj["FriendlyName"].toString());
        m_connectedPNPInstanceId.push_back(obj["InstanceId"].toString());
        m_connectedPNPManufacturer.push_back(obj["Manufacturer"].toString());
    }
    if (m_connectedPNPClass.size() == 0) return __LINE__;
    return 0;
}

It returns a big list of all the PNP devices registered on the system and in this code I am just adding the returned strings to QStringLists. If you don't do the Select-Object you get an even bigger JSON string with even more information. To get the USB devices you just have to look at the InstanceId string because it starts with USB. It is not absolutely ideal because it seems to return multiple lines for some devices, and of course it depends on PowerShell being on the path. On the plus side, the FriendlyName value is a handy thing.


text:
Q: Specify columns while appending Snowpark Python Dataframe to table So right now, I have a Dataframe created using the session.createDataFrame() in Python. The intention is to append this Dataframe to an existing table object in Snowflake.
However the schema of the source dataframe doesn't match exactly with the schema of the target table. In Snowpark Scala, the DataFrameWriter object has the method option() Saving/Appending Dataframe to a table that allows the specification of column order, and hence allows for skipping columns from the dataframe as the columns could be matched by their names.
However, Snowpark Python lacks the option() for DataframeWriter at the moment. This forces Snowflake to look for the schemas and the count of columns (between source and target ) to match, else an error is thrown.
Not sure when Snowpark for Python would receive this feature, but in the interim, is there any alternative to this (apart from hardcoding columns names in the INSERT query) ?

A: You are right that Snowpark does not make inserting novel records easy. But it is possible. I did it with the Snowpark Java SDK that lacked any source/docs just banging my head on the desk until it worked.
I first did a select against the target table (see first line), then got the schema, then created a new Row object with the correct order and types. Use column "order" mode not the column "name" mode.  It's also really finicky about types - doesn't like java.util.Dates but wants Timestamps, doesn't like Integers but need Longs, etc.
Then do an "append"->"saveAsTable". By some miracle it worked. Agreed it would be fantastic if they accepted a Map<String, Object> to insert a row or let you map columns using names. But they probably want to discourage this given the nature of warehouse performance for row based operations.
In Java...
DataFrame dfSchema = session.sql("select * from TARGET_TABLE limit 1");
StructType schema = dfSchema.schema();
System.out.println(schema);
Row[] rows = new Row[]{Row.fromArray(new Object[]{endpoint.getDatabaseTable(), statusesArr, numRecords, Integer.valueOf(filenames.size()).longValue(), filenamesArr, urlsArr, startDate, endDate})};
DataFrame df = session.createDataFrame(rows, schema);
System.out.println(df.showString(0, 120));
df.write().mode("Append").saveAsTable("TARGET_TABLE");

A: In the save_as_table method, use the parameter column_order="name". See Snowflake save_as_table docs. This should match the columns by name and allow you to omit missing columns without the column number mismatch error.
It's also good practice to include a schema when creating your session. See Snowflake create_dataframe docs on using the StructType class.


text:
Q: Grant access to google calendar to all users Using the google calendar API, can I make one user's single calendar event visible to all other users who visit their page or account?

A: You have to modify the Access Control List of a resource
https://developers.google.com/calendar/v3/reference/acl
Specifically the scope.type property.
To one of the following
"default" - The public scope. This is the default value.
"user" - Limits the scope to a single user.
"group" - Limits the scope to a group.
"domain" - Limits the scope to a domain.

and then the scope.value -    The email address of a user or group, or the name of a domain, depending on the scope type. Omitted for type "default".
an example would be
PUT https://www.googleapis.com/calendar/v3/calendars/calendarId/acl/ruleId

read more here


text:
Q: Uncaught TypeError: Cannot read properties of undefined (reading 'Hobbies') I am running into an interesting issue that is throwing me for a loop. I am doing a Sharepoint RestAPI call that returns data correctly, when I run a for loop over the data it builds out the html but still tosses the error that I used as the title. Code is below. If I console log each loop it will return the value. The HTML also works fine. The issue is that error still comes up.
function getSlideData() {
    var query = "$expand=AttachmentFiles&$select=Title,Team,State,Location,Hobbies,Favorite,Askme,GreatPlace,imageFact,ImageText,Attachments,AttachmentFiles&$expand=AttachmentFiles&$top=1000&$orderby=Created desc&$filter=Display eq 'Active'";
    var svcUrl = SITE_URL + "_api/web/lists/getbytitle('"+LIST_NAME+"')/items?"+query;
    var employeeData;

    $.ajax({
        url: svcUrl,
        type: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
        async: false,
        success: function (data) {
            employeeData = data.d.results;
        },
        error: function (xhr) {
            alert("Can't get list items.", xhr.status + ": " + xhr.statusText);
        }
    });

    return employeeData;
}

function buildSlides() {
    var slideData = getSlideData();
    var sliderWrapper = $('#slider-wrapper');
    var sliderWrapperContent = "";

    for(i=0;i<=slideData.length;i++) {
        sliderWrapperContent += '

'+slideData[i].Hobbies+'

';
        sliderWrapper.html(sliderWrapperContent);
    }
}

A: The error is that you are trying to access an index that does not exist in the array because of <= in the for loop, try to use < when you use .length of an array.


text:
Q: angularjs : ng-view encoding issue I have an issue with my web application.
I'm using AngularJs v1. When I'm wrinting
In my index.html I have :
<meta charset="utf-8" />
[...]
<button class="btn btn-success">Enregister les préférences</button>

I have this render on my browser (chrome or firefox) :

Enregister les préférences

But, with the same  in my template HTML which replace the ng-view, I have :

Enregister les pr�f�rences

How to extends the charset of index.html to ng-view ?
Thanks.

A: If you add meta tag for each of the template HTML, then it works. For ex. below code
  <head>
  <meta charset="utf-8">
  </head>

However I think your question is about inheritance of meta tag inside template html. Not sure if its supported by w3

A: You can specify language
<html lang="en">

or
Check these links

*

*http://blog.novanet.no/creating-multilingual-support-using-angularjs/

*https://docs.angularjs.org/guide/i18n

*https://angular-translate.github.io

A:  I had the very same problem in an Angular app. In my case I needed to do the following sequence:
 1. Add meta tag for UTF-8:
<head>
    <meta charset="utf-8" />
</head>

 2. Open the html file e.g. in Notepad++, select all text and and convert it to UTF-8 without BOM (if there are other files connected with this html e.g. .css, .js or .tss do the same with them)
 3. Restart your IDE (in my case VS2017) because your files might be cached and rebuild the project:


text:
Q: How to get full url from  tag using jquery I have a notification div. When someone clicks one of the links, the number of notification will be changed and after that the user will be redirected to the link that he clicked. Here is the php script inside the div.
<?php
 while($row = stmt->fetch(PDO::FETCH_OBJ))
 {
 echo "
".$title."
";
 }
?>

I am using the following Jquery inside the div:

Number of the notification changes successfully but when trying to redirect, the value of n_url shows undefined.

A: I think you have a problem of scope when using this. You can do something like this to fix the problem. Get the n_url before making the ajax request.
$('p').click(function (event) {
    event.preventDefault();
    var n_url = $('a', this).attr('href');

    $.ajax({
        type: "POST",
        url: "http://www.example.com/change_notification.php"
    }).done(function (msg) {

        $("#changed_notification_value").text(msg);
        window.location.href = n_url;
    });
});

A: try this
var n_url = $(this).find('a').attr('href');

A: Try this:
   var n_url = $(this).find("a").attr('href');
     window.location.href = n_url;

A: this does not work like it does in other languages. When not inside a function (think global space) this refers to the Window object of the current browser. By default, new functions are created as children of Window.
For example;
function foo() {
    return this;
}

Is actually the same as Window.foo = function() { return this; } (unless browser is in strict mode).
So when you call foo() the following is true.
foo() === window;   // True, because foo() returns this which is window.

Since by default this refers to the object the function is bound to. You can change the default value of this by binding the function to a different object.
var o = {
    x: 99,
    foo: function() {
        return this.x;
    }
};

console.log(o.foo());   // will output 99

It doesn't matter when you bind the function to an object. As in this example.
var a = {
    x: 99
};

var b = {
    x: 77
};

function foo() {
    return this.x;
}

a.f = foo;
b.f = foo;

console.log(a.f());   // will output 99
console.log(b.f());   // will output 77

In the above example the function foo is the same, but this changes depending on which bound object reference was used to call it.
So what is going on with DOM events?
The function is bound to the DOM element, and that's a Javascript object. So this refers to the object that triggers the event. Even if the same function is bound to multiple elements. this always refers to the one that triggered the function.
So now back your source code and problem. Your using this inside the .done(function(msg){....}) function. jQuery has bound the ajax object to the function so that this refers to that object.
You can change what this refers too by using the bind() function. bind lets you change what object is bound to the function so that this refers to that object instead.
$('p').click(function(event){
    event.preventDefault();
    $.ajax({
        type: "POST",
        url: "http://www.example.com/change_notification.php"
    }).done(function( msg ) {
        $("#changed_notification_value").text( msg );
        var n_url = $('a', this).attr('href');
        window.location.href = n_url;
    }.bind(this));
});

Above, I didn't change your source code but just added .bind(this) to the end of your function(msg){...}.bind(this).  The object this refers to outside the function is the DOM element that triggered the event, and by binding it to your callback function for done your source code should now work.


text:
Q: How to split a queue into two queues? Problem
Given a queue, split the queue into two queues:

*

*one containing odd numbers and the other even numbers.

*The relative order of elements must be maintained in both the queues.

*Return an array containing the two queues, the 0th index should
contain the queue of odd numbers and the 1st index should contain the
queue of even numbers.

Code
Here is what I've tried so far. I am currently getting empty queue.
class Queue {

private int front;
private int rear;
private int maxSize;
private int arr[];

Queue(int maxSize) {
    this.front = 0;
    this.rear = -1;
    this.maxSize = maxSize;
    this.arr = new int[this.maxSize];
}

public boolean isFull() {
    if (rear == maxSize - 1) {
        return true;
    }
    return false;
}

public boolean enqueue(int data) {
    if (isFull()) {
        return false;
    } else {
        arr[++rear] = data;
        return true;
    }
}

public void display() {
    if(isEmpty())
        System.out.println("Queue is empty!");
    else {
        for (int index = front; index <= rear; index++) {
            System.out.println(arr[index]);
        }
    }
}

public boolean isEmpty() {
    if (front > rear)
        return true;
    return false;
}

public int dequeue() {
    if (isEmpty()) {
        return Integer.MIN_VALUE;
    } else {
        int data = arr[this.front];
        arr[front++] = Integer.MIN_VALUE;
        return data;
    }
}

public int getMaxSize() {
    return maxSize;
}
}

class Main {

public static void main(String[] args) {

    Queue queue = new Queue(7);
    queue.enqueue(2);
    queue.enqueue(7);
    queue.enqueue(9);
    queue.enqueue(4);
    queue.enqueue(6);
    queue.enqueue(5);
    queue.enqueue(10);

    Queue[] queueArray = splitQueue(queue);

    System.out.println("Elements in the queue of odd numbers");
    queueArray[0].display();

    System.out.println("\nElements in the queue of even numbers");
    queueArray[1].display();

}

// function to split the queue into two queues;
    // 1. one even. one odd.
    // 2. relative elements must be maintained in both queues.
    // 3. 0th index returns queue of odd numbers
    // 4. 1st index returns queue of even numbers
public static Queue[] splitQueue(Queue queue) {

    // create queue array for 0th index for odd and 1st index for even
    Queue[] numberArr = new Queue[2];

    // create two queues - odd and even queue
    Queue oddQueue = queue;
    Queue evenQueue = queue;

    // seperate odd and even
    while (!oddQueue.isEmpty()) {
        // start dequeue
        int val = queue.dequeue();

        // check even odd
        if (val % 2 == 0) {
            System.out.println(val + " - Even");
            evenQueue.enqueue(val);
        }
        else {
            System.out.println(val + " - Odd");
            oddQueue.enqueue(val);
        }
    }
    evenQueue.display();
    oddQueue.display();

    // assign odd numbers queue to 0th index of array
    numberArr[0] = oddQueue;
    // assign even numbers queue to 1th index of array
    numberArr[1] = evenQueue;

    if ((!oddQueue.isEmpty() && !evenQueue.isEmpty())) {
        return numberArr;
    }
    return null;
}
}

I am currently doing a queue exercise and am currently stuck on this implementation. I would appreciate any help for this.
Edit: I've provided my solution on what I've tried so far.

A: in while loop check for the formal parameter "queue" empty or not=>
while(!queue.isEmpty())

A: public static Queue[] splitQueue(Queue queue) {
       //Implement your code here and change the return value accordingly
    Queue[] numberArr = new Queue[2];
      //create two queues - odd and even queue
    Queue oddQueue=new Queue(queue.getMaxSize() );
    Queue evenQueue=new Queue(queue.getMaxSize());
    // seperate odd and even
   while(!(queue.isEmpty()))
   {
       int val=queue.dequeue();
       //System.out.println(val);
       if(val%2==0)
       {
           evenQueue.enqueue(val);
       }else
       {
           oddQueue.enqueue(val);
       }
   }
    // assign odd numbers queue to 0th index of array
    numberArr[0] = oddQueue;
    // assign even numbers queue to 1th index of array
    numberArr[1] = evenQueue;
    return numberArr;

    }

I worked on your code and I got your errors
1] in while condition use the condition like (!queue.isEmpty())
2] you are not creating the new queues .it will be created by new keyword only
like,
Queue oddQueue=new Queue(queue.getMaxSize() );


text:
Q: Implementing a shifter with only multiplexers This is my homework question, I would appreciate any hints to help me get started.

A shifter is used to shift a string of 0's and 1's to the left or
  right by a fixed number of positions. The vacated positions(s) is/are
  filled by 0. For example, if 0011 is shifted left by one position the
  result is 0110; if 0011 is shifted right by one position the result is
  0001.
Two control signals, S1 and S0, are used to specify the various
  actions, as given below.
S1 = 0 and S0 = 0: No change, that is, pass input string to output
S1 = 0 and S0 = 0: Shift right one bit position
S1 = 1 and S0 = 0: Shift right two bit positions
S1 = 1 and S0 = 1: Shift left one bit position
Using a number of appropriate multiplexers without any additional
  logic gate, implement a shifter that accepts a 4-bit string ABCD, and
  generates the required 4-bit string WXYZ depending on the control
  signals S1 and S0. Complemented literals are not available. You must
  label your multiplexers, inputs and outputs clearly.

I researched online about the shifting operation and found out that it actually coincide with arithmetic operations, i.e., so "shift right one bit position" is actually division by 2, and "shift left one bit position" is multiplication by 2. However, I have no idea what "shift right two bit" means, is it division by 5? I tested with 1111 binary code (15) and the result is 0011 (3).
So basically since the shifting operations is just arithmetic operations, should I use the multiplexers to implement the latter? Yet I don't know how to go about it with only two control signals S1 and S0. Do I need 4 multiplexers since the output is 4 bits?

A: This isn't a direct answer to your homework, but a response to your analysis of what shifting means numerically.
Yes, shifting a binary number left is a multiplication by 2.  In general, shifting a number left by one digit multiplies it by the number base.  That is because each digit to the left has a weight of the number base times higher.  In decimal, shifting left one digit multiplies the number by ten, in binary by two.
No, shifting right by two does not divide by 5.  By the same logic as above, shifting right one digit divides the number by the number base.  In binary, this means it gets divided by 2.  Shifting two bits right divides by 4.  The reason you are not seeing this in you example is because you lost some of the digits.
You started with 1111 binary and shifted it right by two bits.  This yields 11.11 binary.  Add the weights from each of the digits and you get

  2**1 + 2**0 + 2**-1 + 2**-2
=    2 +    1 +    .5 +   .25
= 3.75
Which is exactly 15/4 as expected.  The problem is that you ignored the fraction digits and were therefore only left with 3.  In this case, that happened to look like the shift divided by 5.
If you do a integer shift, then shifting by one bit right really does
trunc(N / 2)
where N is the original number and TRUNC simply sets all fraction bits to 0 (truncates them).  Note that trunc(15/2) does equal 3.


text:
Q: InvalidCastException while Mapping types MyType to MyType I'm using AutoMapper 2.2.1 to map different business objects to view models. Now I'm getting a InvalidCastExceptions if I try to map objects which have a property of type CustomList (see code below).
The exception says that CustomList cannot be casted to IList. Which is correct because CustomList implements IReadOnlyList and not IList.
So why automapper tries to cast it in this manner and how to fix/workaround this?
I have these types:
public class MyViewModel : SomeModel { //... some addtional stuff ...}

public class SomeModel {
public CustomList DescriptionList { get; internal set; }
}

public class CustomList : ReadOnlyList<SomeOtherModel> {}

public abstract class ReadOnlyList<TModel> : IReadOnlyList<TModel> {}

//map it
//aList is type of SomeModel
var viewList = Mapper.Map<List<MyViewModel>>(aList);

A: Having your class implement from IReadOnlyList is most likely causing the problem.  Automapper doesn't know how to map a read-only list to a read-only list.  It creates new instances of objects, and there is no add method or collection initializer for IReadOnlyList.  Automapper needs to be able to access the underlying list the readonly list is wrapping around.  This can be done using the ConstructUsing method.
Updated List Model:
public class CustomList : IReadOnlyList<string>
{
    private readonly IList<string> _List;

    public CustomList (IList<string> list)
    {
        _List = list;
    }

    public CustomList ()
    {
        _List = new List<string>();
    }

    public static CustomList CustomListBuilder(CustomList customList)
    {
        return new CustomList (customList._List);
    }
}

Updated automapper config
Mapper.CreateMap<CustomList, CustomList>().ConstructUsing(CustomList.CustomListBuilder);

This is a simple example but I was able to get it to map properly as well as not throw an exception.  This isn't the best code, doing this would result in the same list being referenced by two different readonly lists (depending on your requirements, that may or may not be okay).  Hopefully this helps.


text:
Q: Handling Multiple Forms on the Same Page in Django without Django's default model form I am trying to develop a webpage with two forms on the same page with Django. Anyone will able to fillup any single form and submit it, then that data will be saved in the database. Here I try to avoid Django's default model form and any type of js stuff also.
My HTML:

<!DOCTYPE html>

    <title></title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.0.0/animate.min.css"/>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

    <link rel="stylesheet" type="text/css" href="#">

Multiple form in one page

Employee Profile

                <form class="#" method="POST" id="EmployeeProfile">

                        Ranks
                        <input type="text" class="form-control" name="ranks" placeholder="Enter ranks">

                        salary
                        <input type="text" class="form-control" name="salary" placeholder="Enter salary">

                        <button type="submit" class="btn btn-primary m-2">Submit</button>

                </form>

Inspector Profile

                <form class="#" method="POST" id="InspectorProfile">

                        Ranks
                        <input type="text" class="form-control" name="ranks" placeholder="Enter ranks">

                        Your email
                        <input type="email" class="form-control" name="email" placeholder="email">

                        <button type="submit" class="btn btn-primary m-2">Submit</button>

                </form>

Here how can I code my views.py with function based view to get data from this form? and how to determine which form sent me that data.

A: You can do that by setting different form action and by making different view for perticular form like this
inside your template :
 <form method="POST" action="{% url 'form1' %}">
    ........all input fields
    </form>

    <form method="POST" action="{% url 'form2' %}">
    ........all input fields
    </form>

inside your views.py :
def form1(request):
  if request.method == "POST":
      ...get all values
      return render(request,'forms.html')

def form2(request):
  if request.method == "POST":
      ...get all values
      return render(request,'forms.html')


text:
Q: Loading Android Kernel modules After weeks of mucking around i have (i think) successfully compiled g_hid.ko (USB Gadget HID module) for my Samsung Galaxy S3 but have been unable to test it. If i try and use insmod from the directory it is stored in i get insmod: can't insert 'g_hid.ko': No such device I'm new to this but i think this means that i should have loaded something else that g_hid is dependent on first. Any one know what this would be or how i can find out?
Also when trying to use rmmod i receive the following error rmmod: chdir(/system/lib/modules): No such file or directory which is true, that directory doesnt exist, as far as i can tell, my modules are stored in /lib/modules but this is a read only file system so i cant add my modle there. I also get the same error if i try and use modprobe. Any help you can offer would be greatly appreiated.
Thanks
Adrian

A: I eventually got this to work. The continual discussion on the topic is at Is it possible to program Android to act as physical USB keyboard? and http://forum.xda-developers.com/showthread.php?t=1871281 When i have some free time in a few weeks (after uni) i intend to write up how i did every thing as there appears to be a lot of interest.

A: Regarding the inability to place the module into system/lib/modules...  You must first connect to the device and issue the commands:
  adb root
  adb remount
After issuing these commands you can place your .ko into the correct directory and the "read only file system" problem will go away.


text:
Q: Java histogram in 2 windows from JFileChooser this code at the moment allows me to select multiple text files which are then analysed into a bar chart, my problem is when for example 2 files are selected from the JFileChooser the bar charts are opened one after another, so first one will open then when OK is pressed the second will open, i need them both to open simultaneously side by side? If anyone can give me any pointers it would be really appreciated.
if ("Analyze Text File".equals(command)) {
    JFileChooser chooser = new JFileChooser();
    chooser.setMultiSelectionEnabled(true);
    if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
        File[] files = chooser.getSelectedFiles();
        for (File file : files) {
            try {
                BufferedReader reader = new BufferedReader(new FileReader(file));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                String text = sb.toString();
                Map<Integer, Integer> counts = getCounts(text);
                int width = counts.size() * BAR_WIDTH;
                int max = maxCount(counts);
                int height = max * INCREMENT + 100;
                int horizon = height - 25;
                HistogramPanel panel = new HistogramPanel(width, counts, height, horizon);
                JOptionPane.showMessageDialog(null, panel);
                reader.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
}

A: JOptionPane is intended for blocking popups. Things like error messages etc. For your purpose, you should probably rely on modeless JDialogs.

A: As Ray suggested just use JDialogss so you can control the modality. Remember JDialog works just like JFrame, so if you know how to make a JFrame, then JDialog should be easy. But with JDialog you get to control the modality.
for (File file : files) {
    try {
        ...
        HistogramPanel panel = new HistogramPanel(width, counts, height, horizon);
        JDialog dialog = new JDialog();
        dialog.setModal(false);        <---- very important
        dialog.setLayout(new BorderLayout());
        dialog.add(panel);
        dialog.pack();
        dialog.setLocationByPlatform(true);
        dialog.setVisible(true);
    } catch (...)
}


text:
Q: Slideshow Image not scalling with browser window I have a slideshow in my website that will not scale to the browser.
What happens: When the browser is reduced to 414 px it renders
correctly. When I drag the browser window larger the slideshow image
size remains the same. Refreshing the browser makes it render correctly.
Also during the increase in browser size it's not a smooth transition.
You can see it here. http://comrefhvac.com
Thank you in advance.
RichM

A: How to fix the issue is a different question, and one that requires that we look at your code. If you simply want to know why, then it's because the styling for the slideshow is dynamically applied via javascript and it looks like the author of the plugin only considered the initial page load and no the window.resize event.

A: I'm cool with that. Try this, go to my website then take the browser down to 414 px and you will see a gap between the slideshow and the text below. Then refresh the page and it will render as it should. Then maximize the browser and you will see that the slideshow container does not expand to the proper size which is set in my css at 440 x 800 px. Thanks for being honest, hope your head doesn't hurt this AM Jeff. RichM


text:
Q: How can I filter out a div from two select options? Here is my Fiddle to the example
$('select#classes').on('change', function() {
    var classSearch = $(this).val();
    $('.col-sm-6:not(:contains(' + classSearch + '))').hide();

    $('select#subjects').on('change', function() {
        var subjectsSearch = $(this).val();
        $('.col-sm-6:contains(' + classSearch + '))').show();
        $('.col-sm-6:not(:contains(' + subjectsSearch + '))').hide();
    });

});

A: I strongly suggest the use of values html attribute instead of the text itself for options, otherwise the value of the select will be the selected text (not very useful).
And a little explanation of how you structured your page could have been great, so we wouldn't have to go through the whole code and try to understand what it does and how it is built: what should we display ? when ?
About your problem (with a general structure):
HTML:
Class:
  <select id="select_category" class="selectSome">
    <option value="null">Please select...</option>
    <option value="c1">Class 1</option>
    <option value="c2">Class 2</option>
    <option value="c3">Class 3</option>
  </select>

Subject:
  <select id="select_subject" class="selectSome">
    <option value="null">Please select...</option>
    <option value="s1">Subject 1</option>
    <option value="s2">Subject 2</option>
    <option value="s3">Subject 3</option>
  </select>

Subject 1 for Class 1

Subject 2 for Class 1

Subject 1 for Class 2

Subject 2 for Class 2

Subject 3 for Class 2

Subject 3 for Class 3

CSS:
.row {
  display: none;
}

JS:
$().ready(function() {
  $('.selectSome').on('change', function() {
    showHide();
  });
});

function showHide() {
  // hide all rows
  $('.row').hide();
  // show good row only
  if ($('#select_category').val() != 'null' && $('#select_subject').val() != 'null') {
      $('#row_' + $('#select_subject').val() + '_' + $('#select_category').val()).show();
  }
}

http://jsfiddle.net/g5cryt31/

A: You can do it using parents and not
$('select#classes').on('change', function() {
    var classSearch = $(this).val();
$('.col-sm-6 *').not('.' + classSearch).hide();

 $('select#subjects').on('change', function() {
    var subjectsSearch = $(this).val();
    $('.'+classSearch).parents('.col-sm-6').show();
    $('.col-sm-6 *').not('.' + subjectsSearch).hide();
  });
});


text:
Q: When is Java variable created in memory? I am wondering when is Java creating variables during runtime (when a function is called). Please see the examples below and answer whether those are one the same.
void function someFunction(boolean test) {
    if (!test) {
        return;
    }
    int[] myVar = new int[1000000];
    ...
}

void function someFunction(boolean test) {
    int[] myVar = new int[1000000];
    if (!test) {
        return;
    }
    ...
}

I wouldn't like so spend time allocating memory only for it to be deallocated moments later, so I need to know whether Java will allocate memory needed for a certain variable (or array) needed by a function at the very beginning of that function, regardless of where the declaration happened, or will it allocate memory when it reaches the point of declaration.
EDIT:
I'm terribly sorry for confusion I'm causing. When I say variable I mean object.

A: Probably at the point of method entry. It is a common compiler optimization to allocate a stack frame large enough to contain all locals.  If that's so, it's pretty much a single subtraction to allocate space for them all. But you'd have to examine the bytecode to be sure.
However, in this:
int[] myVar = new int[1000000];

the 'variable' is a single reference, taking up 4 or 8 bytes. The object to which the variable refers is allocated at the point the initialization is encountered in execution, by the execution of the 'new' operator.
I suspect you need to read up on the distinction between variables and objects.

A: In general, the Java compiler is a bit dumb in its compilation since it leaves the optimization up to the runtime JVM. As such, the compilation is mostly a straightforward translation of source code into bytecode.
https://godbolt.org/z/5xT3KchrW
In this case with the OpenJDK 17.0.0 compiler, the allocation of the array is done roughly at the same point in the bytecode as where the source code indicates.
However, the local variable of the pointer to the array is "allocated" at the time the method is called via registers. While the JVM uses a stack frame in a way very similar to C/C++, on Android's Dalvik they instead use registers to hold local variables so it isn't ever actually "allocated" at all in memory (a design decision due to the focus on ARM -- with it's plentiful registers -- rather than x86 -- which is infamous for its lack of registers.