text:
Q: Free module finite generated with a submodule not finite generated. Anyone knowns an example of a R-module finite genereted with a submodule not finite generated?
I find the following example: Taking the set of function $f:[0,1]\rightarrow\mathbb{R}$ seen as module of it self. This is finite generated. If we take the subset of functions $f$ such that $f(x)=0$  for all $x\in[0,1]$ except a finite numbers of points then we will get a submodule wich is not finite generated. Why?
This is a different example of the others I saw.
Thanks a lot!!!

A: Let $R$ be the ring of function $f:[0,1]\to\mathbb R$. Let $M$ be the $R$-module of functions $f$ such that $f(x)=0$ for all $x\in[0,1]$ except for a finite numbers of points.
Assume on contrary that $M$ is finitely generated with generators $g_1,\ldots,g_n$.
For each $a\in [0,1]$ let
$\chi_a(x)=
\begin{cases}
1&x=a,\\
0&x\neq a.
\end{cases}
$
The functions $\chi_a,a\in[0,1]$ clearly generates $M$.
Thus each $g_i$ is a linear combination of the $\chi_a$.
Then there exists $a_1,\ldots,a_m\in[0,1]$ such that each $g_i$ is linear combination of $\chi_{a_1},\ldots,\chi_{a_m}$.
Consequenlty $\chi_{a_1},\ldots,\chi_{a_m}$ generates $M$.
Let $a\in[0,1]$ distinct from each $a_j$.
Since $\chi_a$ is not a linear combination of $\chi_{a_j},j$ this lead to a contradiction.

A: Another example is $$A = \lbrace f: \mathbb{R} \to \mathbb{R} \rbrace$$ as module over itself, and the submodule generated by the functions $f$ with compact support, which can't be finitely generated.

A: Let $R=k[x_1,x_2,\ldots,x_n,\ldots ]$. Now $R$ as a module over itself is finitely generated, but clearly $I=(x_1,x_2,\ldots,x_n,\ldots )$ is not finitely generated.


text:
Q: kineticjs - click event is also fired on dblclick I am working with "dblclick" event and if I register a click and dblclick event for a shape, click event is called twice before calling the dblclick event code. This behaviour is making my code go crazy. Since I have some actions for click and different set of actions for dblclick. I am not sure whether this is a bug in kineticjs or this is a expected behaviour. I need help incase of handling this probelm. I need to help in making dblclick to work without calling the click event. Kindly suggest.

A: Seems like this is not a Kinetic issue, but just DOM events in general.
Prevent click event from firing when dblclick event fires

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't understand inversion counting inside Merge sort algorithm (C#, Algorithms) I have a problem to understand the process of counting inversions using Merge sort algorithm (https://gist.github.com/dvorobiov/2038501).
In line 43,
inversions += leftList.Count - i;

why don't just do
inversions++

A: This line is executed when (leftList[i] > rightList[j]).
This fact means that rightList[j] is smaller than all the right piece of the leftlist - so such case reveals leftList.Count - i new inversions


text:
Q: Failing to build Symfony 5 Encore project in production with npm I'm trying to manage the deployment of my Symfony 5 app, using Encore for the first time.
I'm facing 2 problems that might be linked, or maybe not i don't really know.

*

*All of my Js files including JQuery are working fine in dev mode,
but none of it does in prod mode. I can't read any of my checking
console.logs and i have this error message for the JQuery $ variable
not found.

*My scripts, defined in the webpack.config.js, are not working and
i have an error message when trying to npm run build on prod
server, here is the complete log:

0 info it worked if it ends with ok
1 verbose cli [
1 verbose cli '/opt/alt/alt-nodejs14/root/usr/bin/node',
1 verbose cli '/opt/alt/alt-nodejs14/root/usr/bin/npm',
1 verbose cli 'run',
1 verbose cli 'build'
1 verbose cli ]
2 info using npm@6.14.17
3 info using node@v14.20.1
4 verbose run-script [ 'prebuild', 'build', 'postbuild' ]
5 info lifecycle @~prebuild: @
6 info lifecycle @~build: @
7 verbose lifecycle @~build: unsafe-perm in lifecycle true
8 verbose lifecycle @~build: PATH: /opt/alt/alt-nodejs14/root/usr/lib/node_modules/npm/node_modules.bundled/npm-lifecycle/node-gyp-bin:/home2/ewrt9829/mercstation/node_modules/.bin:/opt/alt/alt-nodejs14/root/usr/bin:/home2/ewrt9829/nodevenv/mercstation/14/bin:/opt/alt/alt-nodejs14/root/usr/bin:/home2/ewrt9829/nodevenv/mercstation/14/lib/bin/:/usr/local/cpanel/3rdparty/lib/path-bin:/usr/local/cpanel/3rdparty/lib/path-bin:/usr/local/cpanel/3rdparty/lib/path-bin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/opt/cpanel/composer/bin:/home2/ewrt9829/.local/bin:/home2/ewrt9829/bin
9 verbose lifecycle @~build: CWD: /home2/ewrt9829/mercstation
10 silly lifecycle @~build: Args: [ '-c', 'encore production --progress' ]
11 info lifecycle @~build: Failed to exec build script
12 verbose stack Error: @ build: `encore production --progress`
12 verbose stack spawn ENOENT
12 verbose stack at ChildProcess.<anonymous> (/opt/alt/alt-nodejs14/root/usr/lib/node_modules/npm/node_modules.bundled/npm-lifecycle/lib/spawn.js:48:18)
12 verbose stack at ChildProcess.emit (events.js:400:28)
12 verbose stack at maybeClose (internal/child_process.js:1088:16)
12 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:296:5)
13 verbose pkgid @
14 verbose cwd /home2/ewrt9829/mercstation
15 verbose Linux 4.18.0-372.19.1.lve.el7h.x86_64
16 verbose argv "/opt/alt/alt-nodejs14/root/usr/bin/node" "/opt/alt/alt-nodejs14/root/usr/bin/npm" "run" "build"
17 verbose node v14.20.1
18 verbose npm v6.14.17
19 error code ELIFECYCLE
20 error syscall spawn
21 error file sh
22 error errno ENOENT
23 error @ build: `encore production --progress`
23 error spawn ENOENT
24 error Failed at the @ build script.
24 error This is probably not a problem with npm. There is likely additional logging output above.
25 verbose exit [ 1, true ]

Here's the webpack.config.js :
const Encore = require('@symfony/webpack-encore');

// Manually configure the runtime environment if not already configured yet by the "encore" command.
// It's useful when you use tools that rely on webpack.config.js file.
if (!Encore.isRuntimeEnvironmentConfigured()) {
    Encore.configureRuntimeEnvironment(process.env.NODE_ENV || 'dev');
}

Encore
    // directory where compiled assets will be stored
    .setOutputPath('public/build/')
    // public path used by the web server to access the output path
    .setPublicPath('/build')
    // only needed for CDN's or subdirectory deploy
    //.setManifestKeyPrefix('build/')
    .copyFiles({
        from: './assets/images',

        // optional target path, relative to the output dir
        to: 'images/[path][name].[ext]',

        // if versioning is enabled, add the file hash too
        //to: 'images/[path][name].[hash:8].[ext]',

        // only copy files matching this pattern
        //pattern: /\.(png|jpg|jpeg)$/
    })
    /*
     * ENTRY CONFIG
     *
     * Each entry will result in one JavaScript file (e.g. app.js)
     * and one CSS file (e.g. app.css) if your JavaScript imports CSS.
     */
    .addEntry('app', './assets/app.js')

    // enables the Symfony UX Stimulus bridge (used in assets/bootstrap.js)
    .enableStimulusBridge('./assets/controllers.json')

    // When enabled, Webpack "splits" your files into smaller pieces for greater optimization.
    .splitEntryChunks()

    // will require an extra script tag for runtime.js
    // but, you probably want this, unless you're building a single-page app
    .enableSingleRuntimeChunk()

*    /*
     * FEATURE CONFIG
     *
     * Enable & configure other features below. For a full
     * list of features, see:
     * https://symfony.com/doc/current/frontend.html#adding-more-features
     */
    .cleanupOutputBeforeBuild()
    .enableBuildNotifications()
    .enableSourceMaps(!Encore.isProduction())
    // enables hashed filenames (e.g. app.abc123.css)
    .enableVersioning(Encore.isProduction())

    // configure Babel
    // .configureBabel((config) => {
    //     config.plugins.push('@babel/a-babel-plugin');
    // })

    // enables and configure @babel/preset-env polyfills
    .configureBabelPresetEnv((config) => {
        config.useBuiltIns = 'usage';
        config.corejs = '3.23';
    })

    // enables Sass/SCSS support
    //.enableSassLoader()

    // uncomment if you use TypeScript
    //.enableTypeScriptLoader()

    // uncomment if you use React
    //.enableReactPreset()

    // uncomment to get integrity="..." attributes on your script & link tags
    // requires WebpackEncoreBundle 1.4 or higher
    //.enableIntegrityHashes(Encore.isProduction())

    // uncomment if you're having problems with a jQuery plugin
    //const $ = require('jquery');
    // autoProvidejQuery()
;

module.exports = Encore.getWebpackConfig();

and the package.json :
{
    "devDependencies": {
        "@babel/core": "^7.17.0",
        "@babel/preset-env": "^7.16.0",
        "@hotwired/stimulus": "^3.0.0",
        "@swup/debug-plugin": "^1.0",
        "@swup/fade-theme": "^1.0",
        "@swup/forms-plugin": "^1.0",
        "@swup/slide-theme": "^1.0",
        "@symfony/stimulus-bridge": "^3.2.0",
        "@symfony/ux-swup": "file:vendor/symfony/ux-swup/assets",
        "@symfony/webpack-encore": "^4.0.0",
        "core-js": "^3.23.0",
        "file-loader": "^6.0.0",
        "regenerator-runtime": "^0.13.9",
        "sass": "^1.57.1",
        "sass-loader": "^13.0.0",
        "swup": "^2.0",
        "webpack": "^5.74.0",
        "webpack-cli": "^4.10.0",
        "webpack-notifier": "^1.15.0"
    },
    "license": "UNLICENSED",
    "private": true,
    "scripts": {
        "dev-server": "encore dev-server",
        "dev": "encore dev",
        "watch": "encore dev --watch",
        "build": "encore production --progress"
    },
    "dependencies": {
        "@swup/js-plugin": "^1.0.5"
    }
}

**
What's the trick for Encore in prod mode ? **
I've tried to include const $ = require('jquery'); global.$ = global.jQuery = $; in the app.js, but it's preventing JQuery to work even in dev. Same with .autoProvidejQuery() enabled in webpack.config.js


text:
Q: How to call a component onClick of a button in a functional component with MaterialUI Button I'm using Material UI for a button and want to render a different functional component onClick of a button.
I'm doing this all in a functional component as well. ( is the component I want to trigger)
const driveAction=props =>{
    return <SharedDriveAction/>;
}

const Vehicle = ({vehicle}) => {
const classes = useStyles();

return (
<Button
    onClick= {() => { driveAction }}
    size="small"
    color="secondary"
    className={classes.button}
    >
  Drive
 </Button>
);
}

export default Vehicle;

A: It looks like you want to leverage some state to conditionally render the button.
If you want to control whether or not the button is visible based on a click action, keep track of which component should render in state, then toggle that state with the onClick handler.
If what I am suspecting is true, then this should do the trick for you.

const Vehicle = ({vehicle}) => {

    const classes = useStyles();

  // Controls whether the drive action is rendered or not
  const [showDriveAction, setShowDriveAction] = React.useState(false)

  return showDriveAction ?
    <SharedDriveAction/> :
    <Button
      onClick= {() => setShowDriveAction(true)}
      size="small"
      color="secondary"
      className={classes.button}
    >
      Drive
    </Button>
}

export default Vehicle;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

A: You can use conditional render with react state.
and if you want to toggle use Something like that:
const Vehicle = ({ vehicle }) => {

  const classes = useStyles();
  const [showDrive, setShowDrive] = React.useState(false)

  return (
    <div>
     {showDriveAction ?
       <SharedDriveAction/> :
       <Button
         onClick= {() => setShowDriveAction(!showDriveAction)}
         size="small"
         color="secondary"
         className={classes.button}
       >
         Drive
       </Button>}
    </div>
  )
}

A: More simply speaking, have your overarching component have a state variable of open for the conditional render. OnClick, hook this.setState (for class components) to toggle the open variable. Inline conditional rendering can be handled quite easily in the below example.
{  props.open ? <Component/> : null }


text:
Q: Выделяемая память в Си Есть программа, которая переводит число в двоичное представление в виде строки. Нужно, чтобы не было начальных нулей, которые не используется. Преподаватель сказал, что нужно использовать что то с log числа, которое переводим по основанию 2, и округлить его в большую сторону (так можно узнать количество выделяемой памяти конкретно под нужные цифры без нулей в начале).
Если можете, объясните, пожалуйста! Просто интересно что он имел в виду
#include <stdio.h>
#include <stdlib.h>
#define MAX sizeof(c) * 8 + 1

void ltoab(long num, char s[]){
    int i;
    s[MAX] = '\0';
    for(i = MAX - 1; i >= 0; i--){
        s[i] = (num & 1) + '0';
        num >>= 1;
    }

    printf("%s\n", s);
}

int main(void){
    long c;
    int b, a;
    int mas[100];
    char *s = (char*)malloc(33 * sizeof(char*));
    printf("Skolko chisel ");
    scanf("%d", &a);
    for(b = 0; b < a; b++){
        scanf("%d", &c);
        mas[b] = c;
    }

    for(b = 0; b < a; b++)
        ltoab(mas[b], s);
}

A: Если до понимания логарифмов ещё далеко, то можно пойти обратным путём. Числа от двух до трёх представляется двумя цифрами: 2 = 10(2), 3 = 11(2). От четырёх до семи тремя: 4 = 100(2), 7 = 111(2). С восьмёркой прибавляется ещё один разряд. Здесь закономерность - при достижении новой степени основания системы счисления у числа появляется новый разряд. Отсюда получается, что можно находить количество разрядов узнавая "пройденную" степень основания.
Здесь как раз пригождается логарифм. Его следует понимать как функцию, для которой верно следующее утверждение: log_x_(y) = z => x^z = y. То есть, логарифм от восьми по двум равен трём - в эту степень нужно возвести двойку для получения восьми:
log_2_(8) = 3 => 2^3 = 8
На практике можно обойтись такой функцией, которая возвращает количество цифр числа в двоичном представлении:
int binDigitNumber(int x) {
    int k = 1;
    while (x > 0) {
        x /= 2;
        k++;
    }
    return k;
}

По сути, это целочисленный логарифм по основанию 2 с единицей.
UPD.
Сейчас выделяется память одна на все числа:
char *s=(char*)malloc(33*sizeof(char*));

Если же это действие перенести в тело метода (что вообще правильнее), то выделять память на строку можно будет под конкретную длину числа; также это избавит от страшного использования локальной переменной в define:
void ltoab (long num){
    // количество символов = количество цифр + символ конца строки
    int symbols = binDigitNumber(num) + 1;
    char *s = (char*)malloc(symbols * sizeof(char*));
    s[symbol - 1] = '\0';
    for(int i = 0; i < symbols - 1; i++){
        s[i] = (num & 1) + '0';
        num = num >> 1;
    }
    printf("%s\n", s);
}


text:
Q: Residue Xvnc process after exiting Windows Remote Desktop Connection to an Ubuntu machine I connected to my server's  Ubuntu 14.04 VM via Windows Remote Desktop Connection.
After logging out of the session I checked the processes running with top command in a putty session and saw Xvnc processes still running on the system.
Following command
ps -ef | grep Xvnc

outputs:
zebi2    63444     1  0 12:57 ?        00:00:00 Xvnc :10 -geometry 1364x768 -depth 24 -rfbauth /home/zebi2/.vnc/sesman_zebi2_passwd -bs -ac -nolisten tcp -localhost -dpi 96
zebi2    64981 37219  0 13:00 pts/16   00:00:00 grep --color=auto Xvnc

First line is what I am actually concerned about. I run RDC many times a day and it creates an additional process every time. I don't want to kill the process every time I logout of RDC, also I cannot leave the process since it will increase cpu utilization . Any help or solution is appreciated

A: Turns out it was session cache history which might have been saved previously.

*

*Unticked 'automatically save session' in 'Session and Startup' in XRDP
  desktop settings

*Cleared $HOME/.cache/sessions/xfce4-session-* (all of the previously
  saved session data).

*And restarted xrdp service

This link helped
https://forum.xfce.org/viewtopic.php?id=6580


text:
Q: sorry, this video cannot be played in videoview? freinds,
i am using following code to display a mp4 video in my application
and facing following problems
i have seen so many posts related to this issue on google and stackoverflow but every one giving his own suggestions and there is no common answer.
1) i cannot see video in emulator
2) in different phone sometime rarly video is played and most of the time it give above message.
my code
VideoView myVideoView = (VideoView)findViewById(R.id.videoview);

      String viewSource ="http://dev.hpac.dev-site.org/sites/default/files/videos/about/mobile.mp4";

      myVideoView.setVideoURI(Uri.parse(viewSource));
      myVideoView.setMediaController(new MediaController(this));
      myVideoView.requestFocus();
      myVideoView.start();

any one guide me what is the solution to this problem
any help would be appreciated.

A: you can make a output stream using your file and get absolute path of stream then put path  to video view
    private String getDataSource(String path) throws IOException {
    if (!URLUtil.isNetworkUrl(path)) {
        return path;
    } else {
        URL url = new URL(path);
        URLConnection cn = url.openConnection();
        cn.connect();
        InputStream stream = cn.getInputStream();
        if (stream == null)
            throw new RuntimeException("stream is null");
        File temp = File.createTempFile("mediaplayertmp", "dat");
        temp.deleteOnExit();
        String tempPath = temp.getAbsolutePath();
        @SuppressWarnings("resource")
        FileOutputStream out = new FileOutputStream(temp);
        byte buf[] = new byte[128];
        do {
            int numread = stream.read(buf);
            if (numread <= 0)
                break;
            out.write(buf, 0, numread);
        } while (true);
        try {
            stream.close();
        } catch (IOException ex) {
            Log.e(TAG, "error: " + ex.getMessage(), ex);
        }
        return tempPath;
    }
}

and
public void initVideo() {
    try {

        if (!mVideoView.isPlaying()) {

            if (url > playList.size() - 1) {
                url = 0;
            }
            String[] playurl = (playList.get(url)).split("\\.");
            String urlExtention = playurl[playurl.length - 1];

            if (urlExtention.equals("mp4")) {
                playVideo(playList.get(url));
            } else if (urlExtention.equals("jpg")
                    || urlExtention.equals("jpeg")) {

                Intent intentShedule = new Intent(Default_Player.this,
                        ImagePlayer.class);

                intentShedule.putExtra("imagePath", playList.get(url));
                intentShedule.putExtra("urlValue", url);
                intentShedule.putExtra("playlistType", playlistType);
                intentShedule.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                startActivity(intentShedule);
                finish();
            } else {
                Intent intentShedule = new Intent(Default_Player.this,
                        WebContentView.class);

                intentShedule.putExtra("webPath", playList.get(url));
                intentShedule.putExtra("urlValue", url);
                intentShedule.putExtra("playlistType", playlistType);
                intentShedule.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                startActivity(intentShedule);
                finish();
            }

        }

        mVideoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {

            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                System.out.println("set on error listner");

                //do somthing if alert this video can not be played

                return false;
            }
        });

        mVideoView
                .setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

                    public void onCompletion(MediaPlayer vmp) {

                        playnew();
                    }
                });

    } catch (Exception e) {

    }

    // TODO Auto-generated method stub

}

use on error listner if alert this video can not be played

A: in eclipse emulator video not displayed that link from website(internet).
if you want to play a specific video. then make raw folder and give following path
String path1="android.resource://your package name/"+ R.raw.video name;
Uri uri=Uri.parse(path1);
 videoView.setVideoURI(uri);


text:
Q: flex-basis: auto doesn't work in IE11 I have 3 divs with different width that I want to shrink to container using flexbox.
Made a fiddle:https://jsfiddle.net/easyNick/1m8ude39/14/
CSS looks like this:
.child {
 order: 0;
 flex-grow: 0;
 flex-shrink: 1;
 flex-basis: auto;
 min-height: auto;
 min-width: auto;
 align-self: auto;
 position: relative;
 display: block;
 padding: 0 0.25rem;
}

Works great in Chrome ets.

But IE 11 sees flex-basis as width and last div doesn't even fit to container:
.child {
 order: 0;
 flex-grow: 0;
 flex-shrink: 1;
 width: auto;
 min-height: auto;
 min-width: auto;
 align-self: auto;
 position: relative;
 display: block;
 padding: 0 0.25rem;
}

I've found some advices to set flex-basis to some percentage number. But 100% doesn't make what I need.

Setting particular values makes layout not flexible.
Any ideas of what may help?

A: Flex-basis wont work on the IE11.

But you can target flex-basis property using this CSS rule. Try this one

_:-ms-fullscreen, :root .IE-FlexAuto {
  flex-basis: auto;
}


text:
Q: Verify the Firebase authentication token of a user's request on an Google App Engine NodeJS server? So I've found this piece of doc on how to integrate Firebase authentication with Google App Engine, but it was written for Python, and it seems old, as I've found some inconsistencies in the code. I didn't find a corresponding tutorial for NodeJS.
From I understood, the sequence of the process should be the following:
STEP 1

*

*User logs in through client code (firebase JS SDK) and I get its JWT userIdToken by using user.getIdToken()
STEP 2

*

*Fetch my GAE server URL with the following header:

headers: {
  'Authorization': 'Bearer ' + userIdToken
}

Then the tutorial indicates that I should use a Google Auth library, in order to validate the JWT userIdToken.

Before the client can access server data, your server must verify the token is signed by Firebase. You can verify this token using the Google Authentication Library for Python. Use the authentication library's verify_firebase_token function to verify the bearer token and extract the claims:

Therefore, for a NodeJS server, I should use the following library, correct?
google-auth-library
Or instead, can I use firebase-admin to validate the userIdToken as indicated in the following doc?
https://firebase.google.com/docs/auth/admin/verify-id-tokens
I guess that the firebase-admin seems to be the way to go on this case. But if I choose that path, should I still pass the token using the 'Authorization': 'Bearer ' header? Or is there a better way of handling this?

A: You can pass the ID token to your backend any way you want.  It's customary and standard to use the Authorization header as you see in the documentation, but not required.  The code examples should make it clear that what you really just need is to pass that token to be verified with the Firebase Admin SDK.


text:
Q: jQuery && Google Chrome This script works perfectly in all the browsers, except Google Chrome.
$(document).ready(function(){
    $(".banners-anim img").each(function(){
        var hover_width = $(this).width();
        var hover_height = $(this).height();
        var unhover_width = (hover_width - 30);
        $(this).width(unhover_width);
        var unhover_height = $(this).height();
        $(this).closest("li").height(unhover_height);
        var offset = "-" + ((hover_height - unhover_height)/2) + "px";
        $(this).closest("span").css({'position':'absolute', 'left':'0', 'top':'25px', 'width':'100%'});
        $(this).hover(function(){
            $(this).animate({width: hover_width, marginTop: offset}, "fast")
        },function(){
            $(this).animate({width: unhover_width, marginTop: 0}, "fast")
        });
    });
});

Chrome doesn't recognize changed image attributes.
When width of the img changes, height also changes. Even not in Chrome..
$(this).width(unhover_width);
var unhover_height = $(this).height();

unhover_height gives 0.
Full code of this script (html included) - http://jsfiddle.net/BsqTe/
Please help to fix this.
Thanks.

A: If you're doing things with images from within the jQuery ready function, you need to remember that the images may not be loaded yet. The purpose of the jQuery ready function is to fire as soon as the DOM is ready, even if images are still loading. If you want to do something when all images have finished loading, use window's load event instead:
$(window).load(yourFunctionHere);

A: You might want to notice that images too have onload functions.  Furthermore, some IE versions have a peculiarity where if the image is already loaded, it will not fire any onload functions attached to the event after the fact.  So this little snippet should always insure that some function DoResize is called after the image has loaded
var DoResize = function() { ... }
var img = $(".find .your img");
img.bind('load', DoResize);
img.bind('error', DoResize); // in case picture fails to load, still resize
if (img.get(0).complete) { DoResize(); }


text:
Q: what is the best way to create a comment model for my rails social app I have a user model using devise as its authentication, a post model and are both associated with belongs_to and has_many. I want to include a third model which allows users to comment on posts.
  Is it best to create this with act_as_commentable gem or should i create this from scratch using rails version 4.2?


text:
Q: Android Custom MapView I am trying to create an extended version of MapView.
The problem is when extended version of MapView is defined, mapview does not pan.
I am implementing an onTouchListener Inside my custom map view.
I also want to know is there any methods from where I can pan the mapview.
The problem does not persist when stock version of MapView is used with same source code.
EDIT
MyMapView source:
public class MyMapView extends MapView{

    public MyMapView(Context context, String apiKey) {
        super(context, apiKey);

    }
    public MyMapView(Context context, AttributeSet attrs) {
        super(context, attrs);

    }
    public MyMapView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(event.getAction()==MotionEvent.ACTION_DOWN){
            Log.v("MyMapView","Touched");
        }

        return false ;
    }

}

my onCreate() from MapActivity
protected void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.mapper);
    mMapView=(MyMapView) findViewById(R.id.mapper_map);
    mMapView.setSatellite(false);

}

A: Your onTouchEvent() should return false, otherwise it will consume the event.
You can also instantiate a MapController and use it to change the view.  Here's a code snippet from an app I'm working on:
    @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mapview);

    myMapView = (MapView) findViewById( R.id.myMapView );
    myMapView.setBuiltInZoomControls( true );
    myMapController = myMapView.getController();

    myPoint = new GeoPoint(0, 0);
    myMapController.setCenter( myPoint );
    myMapController.zoomToSpan( 360 * MILLION, 360 * MILLION );
}

A: I was casting it wrong.
mMapView=(MyMapView) findViewById(R.id.mapper_map);

should be
mMapView=(MapView) findViewById(R.id.mapper_map);

This solves the issue.
Thankx anyways.


text:
Q: String Deduplication with Flatbuffers in Java The Cpp API references a CreateSharedString function to perform String deduplication. It seems there is also a specific shared attribute in the flatbuffers DSL.
Unfortunately, I cannot find an equivalent in the Java API nor any documentation about the shared attribute.
Is it possible to create shared strings with the Java API? if yes, how to do?
Should I maintain a map of Strings and their offset for calls to FlatBufferBuilder#createString and perform a check against this map, or is flatbuffers providing a better mean in Java?

A: Yes, you can do this yourself, if need be. If you serialize an offset you get from createString in 2 or more places, you are using sharing. Using your own map to see if you have already serialized a string and reusing its offset is fine.
Sadly of course this makes the serialization process slower (and use more memory), but this may be worth it if you have a lot of repeating strings.


text:
Q: What's the difference between "mutilate" and "amputate"? I've searched about these words but didn't find a useful result. Here are definitions from Cambridge dictionary :

*

*Mutilate : to damage something severely, especially by violently removing a part

*Amputate : to cut off a part of the body
Please write the differences between these words .

A: Mutilate: To significantly damage or deminish structure, function and/or sensorium of a normal anatomical region, usually an appendage. Amputation, crushing trauma injury and serious burns are examples of mutilation.
Amputation (virtually always deliberate and performed by means of some type of blade) is the removal of an anatomical appendage. Limb, earlobe, eyelid and external genitalia are examples of appendages.

A: Amputation is the removal of a limb. That is pretty complete mutilation or ruining of a limb as far as body's utility goes. The limb may still be unmutilated as it sits in the doctor's take-out bag.
To mutilate is to "mess up" the limb. To break, cut bruise or otherwise mangle the limb. If it stays attached it may heal in time but mutilate usually refers to permanent damage.


text:
Q: Java Embedded Static Interfaces I ran into some Java code at work today :
public interface A {

    public static interface AObj {
         String toXml();
         int getCode();
    }

    public static interface AMap {
         String toXml();
         int blah();
    }
    ...
}

I have not encountered having static interfaces embedded in an existing interface before.  It doesn't make much sense.  Can someone comment on :
a) Is this good design practice
b) What the benefits are to this vs Having individual interface files.
c) This was written by a c++ programmer, i get the impression they're trying to re-create namespaces.  If that's the case, why not just use packages ?
Any comments most welcome.
Regards,
Alistair.

A: Good/bad practice can be debatable. Typically one would nest interfaces if the nested interface is an inseparable entity in relation to its parent.
Take a look at the source code of java.util.Map. It merrily embeds Map.Entry inside it. The author is Josh Bloch, who is definitely not an inexperienced Java developer. So I'm sure there must be a valid reasoning behind designing the interface that way.
Here is what it looks like (JavaDoc and comments stripped).
public interface Map<K,V> {
    int size();
    boolean isEmpty();
    boolean containsKey(Object key);
    boolean containsValue(Object value);
    V get(Object key);
    V put(K key, V value);
    V remove(Object key);
    void putAll(Map<? extends K, ? extends V> m);
    void clear();
    Set<K> keySet();
    Collection<V> values();
    Set<Map.Entry<K, V>> entrySet();

    interface Entry<K,V> {
        K getKey();
        V getValue();
        V setValue(V value);
        boolean equals(Object o);
        int hashCode();
    }

    boolean equals(Object o);
    int hashCode();
}

A: First of all, you don't have to type public or static as adarshr stated (see comment). Regarding inner interfaces: everything depends on the context in which they are used- for example GWT requires to expose interface describing application styles for cell lists. I have one interface for general devices, and inner interfaces extending it for some specific devices (android, iphone and so on). It's a less messy in my opinion, especially that all these interfaces for specific devices contains one method overriding default behavior.
However, if interfaces are not so tighly coupled as in the example mentioned above, I'd rather put them in a separate files. Of course, it's your choice depending on design.


text:
Q: sed statement to change/modify CSV separators and delimiters I have some CSV files which contains comma seperated values and some of the column values can contain characters like ,.<>!/\;&
I am trying to convert the CSV to be a comma separated, quote enclosed CSV
Example Data:
DateCreated,DateModified,SKU,Name,Category,Description,Url,OriginalUrl,Image,Image50,Image100,Image120,Image200,Image300,Image400,Price,Brand,ModelNumber
2012-10-19 10:52:50,2013-06-11 02:07:16,34,Austral Foldaway 45 Rotary Clothesline,Home & Garden > Household Supplies > Laundry Supplies > Drying Racks & Hangers,"Watch the Product Video            Plenty of Space to Hang a Family Wash  Austral's Foldaway 45 rotary clothesline is a folding head rotary clothes hoist beautifully finished in either Beige or Heritage Green.  Even though the Foldaway 45 is compact, you still get a large 45 metres of line space, big enough for a full family wash.  If you want the advantage of a rotary hoist, but dont want to lose your yard, then the Austral Foldaway 45 is the clothesline for you.   Installation Note: A core hole is only required when installing into existing concrete, e.g. a pathway. Not required in the ground(grass/soil).  To watch video on YouTube, click the following link: Austral Foldaway 45 Rotary Clothesline                   //           Customer Video Reviews            ",https://track.commissionfactory.com.au/p/10604/1718695,http://www.lifestyleclotheslines.com.au/austral-foldaway-45-rotary-clothesline/,http://content.commissionfactory.com.au/Products/7228/1718695.jpg,http://content.commissionfactory.com.au/Products/7228/1718695@50x50.jpg,http://content.commissionfactory.com.au/Products/7228/1718695@100x100.jpg,http://content.commissionfactory.com.au/Products/7228/1718695@120x120.jpg,http://content.commissionfactory.com.au/Products/7228/1718695@200x200.jpg,http://content.commissionfactory.com.au/Products/7228/1718695@300x300.jpg,http://content.commissionfactory.com.au/Products/7228/1718695@400x400.jpg,309.9000 AUD,Austral,FA45GR

And the output I'm trying to achieve is
"DateCreated","DateModified","SKU","Name","Category","Description","Url","OriginalUrl","Image","Image50","Image100","Image120","Image200","Image300","Image400","Price","Brand","ModelNumber"
"2012-10-19 10:52:50","2013-06-11 02:07:16","34","Austral Foldaway 45 Rotary Clothesline","Home & Garden > Household Supplies > Laundry Supplies > Drying Racks & Hangers","Watch the Product Video            Plenty of Space to Hang a Family Wash  Austral's Foldaway 45 rotary clothesline is a folding head rotary clothes hoist beautifully finished in either Beige or Heritage Green.  Even though the Foldaway 45 is compact, you still get a large 45 metres of line space, big enough for a full family wash.  If you want the advantage of a rotary hoist, but dont want to lose your yard, then the Austral Foldaway 45 is the clothesline for you.   Installation Note: A core hole is only required when installing into existing concrete, e.g. a pathway. Not required in the ground(grass/soil).  To watch video on YouTube, click the following link: Austral Foldaway 45 Rotary Clothesline                   //           Customer Video Reviews            ","https://track.commissionfactory.com.au/p/10604/1718695","http://www.lifestyleclotheslines.com.au/austral-foldaway-45-rotary-clothesline/","http://content.commissionfactory.com.au/Products/7228/1718695.jpg","http://content.commissionfactory.com.au/Products/7228/1718695@50x50.jpg","http://content.commissionfactory.com.au/Products/7228/1718695@100x100.jpg","http://content.commissionfactory.com.au/Products/7228/1718695@120x120.jpg","http://content.commissionfactory.com.au/Products/7228/1718695@200x200.jpg","http://content.commissionfactory.com.au/Products/7228/1718695@300x300.jpg","http://content.commissionfactory.com.au/Products/7228/1718695@400x400.jpg","309.9000 AUD","Austral","FA45GR"

Any assistance is GREATLY appreciated.

A: First, lets try the trivial (and "not good enough") solution that just adds a double quote to each field (including those that already have double quotes! Which isn't what you want)
sed -r 's/([^,]*)/"\1"/g'

Great, the first part looks for sequences with no commas in them, the second part adds double quotes around them, the final 'g' means doing it more than once per line
This will turn
abc,345, some words ,"some text","text,with,commas"

into
    "abc","345"," some words ",""some text"",""text","with","commas""
A few things to note:

*

*it correctly surrounds "some words" with space between them, BUT also surrounds the initial and final spaces. I assume that's OK but if not it can be fixed

*If the field already had quotes, it will be quoted again, which is BAD. Needs to be fixed

*if the field already had quotes AND the inner text had commas (which shouldn't be considered field separators) these commas are also quoted. This too needs to be fixed
So we want to match two different regexps - either there was a quoted string or a field with no commas:
sed -r 's/([^,"]*|"[^"]*")/"\1"/g'

The result would now be
"abc","345"," some words ",""some text"",""text,with,commas""

As you can see, we have a double quote on the originally quoted text. This we will have to remove with a second sed command:
sed -r 's/([^,"]*|"[^"]*")/"\1"/g' | sed 's/""/"/g'

Which results in
"abc","345"," some words ","some text","text,with,commas"

YAY!

A: It sounds like you want every line in a file to begin and end with a double quote.  If so this should work:
sed -i.bak 's/^\(.*\)$/"\1"/' filename

A: Try this perl solution. It's superior to my previous awk, because now I use a parser that handles those commas inside fields correctly. It's neccesary the module Text::CSV_XS to work:
#!/usr/bin/env perl

use strict;
use warnings;
use Text::CSV_XS;

die qq|Usage: perl $0 <csv-file>\n| unless @ARGV == 1;

open my $fh, '<', shift or die qq|ERROR: Could not open input file\n|;

my $csv = Text::CSV_XS->new( {
        always_quote => 1,
} );

while ( my $row = $csv->getline( $fh ) ) {
        $csv->print( *STDOUT, $row );
        print "\n";
}
$csv->eof;
close $fh;


text:
Q: Origin of "quid" in its sense of a sovereign or guinea What is the etymological origin of quid in its sense of a sovereign or guinea?
While preparing the question Origin of "not for quids" phrase I noticed that  etymonline's quid entry merely says

"one pound sterling," 1680s, British slang, possibly from quid "that which is" (c.1600, see quiddity), as used in quid pro quo (q.v.)

Of this usage OED1 says, in part,

[Of obscure origin] 1, A sovereign; a guinea.
  (Pl. usually without -s, as two quid, a few quid, etc.).
  1688 SHADWELL Sqr. Alsatia III. i, Let me equip thee
  with a Quid.

In previous questions where quid is prominent (1) or peripheral (2, 3) I've seen nothing about the origin of the term.  In a comment to my previous question, MετάEd asserts that "Quid" (money) is widely believed to derive from "quid pro quo" anyway."  But what evidence is available about the origin of quid in its sense of a sovereign or guinea?

A: According to Milroy J. and Milroy. L, "Authority in Language" (1985),

[...] quid pro quo probably gave rise to the slang "quid", a unit of money which varies with the context in which it is used.

And the plural is often the same as the singular. (same reference)

A: The OED is less confident than some other sources:

Origin uncertain; perhaps [from] classical Latin quid 'what',
  reinterpreted within English to refer to (monetary) means or
  wherewithal. (My emphasis.)

A: My mother told me that another use for quid was as a term for a lump of phlegm coughed up. That it was green and, so she seemed to infer, squarish, connected it it to a pond note. Which came first, though, though, I don't know.


text:
Q: zurb-foundation: Vertical-align container to bottom of section I do need a little help. I would like to align a .row to the bottom of a section. The three containers you see on the image below need to be at the bottom. I cannot use "fixed" or "sticky" because they should not be. I use fullpage.js to scroll from section to section. The "menu" is in the third section at the end of the page.
When I use position: absolute, the containers will not be centered in the columns any more.
When I use display: table I get a 1px gab between the second and the third column.
Does anybody have an Idea How I can solve this?
Thank you in advance!
Here is how it looks now

This is what I want it to look like.

Here is the html i have used.

IM GEIST
WIE
GLADIATOREN

KARRIERE

GELÄNDESPORT

KREIDLER

SUZUKI

ALLES IN
EINEM
FINGERHUT

RK 67

TECHNIK

RENNER
UND
ROMANTIKER

SCHORSCH

LEBEN & FAMILIE

BUCH

KONTAKT


text:
Q: Restarting gnome-shell - KDE programs look ugly I needed to restart my gnome-shell. I did this on the tty1 via
export DISPLAY=:0.0
gnome-shell --replace
This helps to keep all the open programs, but all KDE program have a different (e.g. ugly) window decorations. Then I tried kwin --replace which looked pretty cool for 5 secs and then I found out, this won't work :)
Is there a way to get back the former looks?
(QT and XUL programs still look fine, firefox and others)

A: Just restart the shell as you did in the TTY using
export DISPLAY=:0.0
gnome-shell --replace

(An alternative for the second line would be gnome-shell --replace & disown so then you can close the TTY)
Then you can restart it from the shell by pressing Alt+F2 and entering r -  this should resolve problems with the theme.


text:
Q: Extract number + letter combination from string I'm intrested in extracting c8127c6ea6a44c109b5e35ce61cd4b0096a9c6dc from a string that looks like this:
?t=c8127c6ea6a44c109b5e35ce61cd4b0096a9c6dc'
Here is my attempt at capturing the result in to a group.
?t=([a-e]\d+)'
Could anyone point me in the right direction, since this obviously isn't working?
http://regexr.com?383s6

A: You wanna put the \d in the [a-e] block and escape the ?:
\?t=([a-f\d]+)'

(and I assume you're looking for hexadecimal so it should be a-f?)

A: You can use this regex:
\?t=([a-e0-9]+)'

OR usig negation:
\?t=([^']+)'

A: In Ruby language you can try Rubular tool online to test your regular expressions.
\?t=(\w+)'

should do the match.


text:
Q: How Can I get data from database by specific id range like id(1-3) in a table? Actually I need some specific data from a table, ID in range 1 - 5. How can I get this?
$products = Products::with('products_images')
                      ->select(['id', 'title','price', 'slug'])
                      ->where('id', 1,2,3)
                      ->get();

A: Generally in SQL it works like this:
SELECT * FROM `tablename` WHERE `id` > 1000 AND `id` < 2000

Regards Tom


text:
Q: On solving an RC circuit Given the following RC circuit:

it's required to calculate how the electric current varies and how the other electrical quantities vary.
Based on that request, I was wondering if it was correct to consider this other RC circuit:

therefore, as usual, distinguish between:

*

*charge process: $i(t) = \frac{\Delta V}{R_{eq}}e^{-\frac{t}{R_{eq}\,C}}$ and $q(t) = C\,\Delta V\left(1 - e^{-\frac{t}{R_{eq}\,C}}\right)$;

*discharge process: $i(t) = -\frac{\Delta V}{R_{eq}}e^{-\frac{t}{R_{eq}\,C}}$ and $q(t) = C\,\Delta V\,e^{-\frac{t}{R_{eq}\,C}}$;
or is this simplification not correct and it's necessary to solve the initial circuit through differential equations?
In the latter case if I was given some help on how to do it I would be happy, thanks!

EDIT:
Thanks to the clear answers of @Ritam_Dasgupta and @Señor O, I managed to write the associated Cauchy problem:
$$
\begin{cases}
\epsilon = R_1\,\dot{q}_1(t) + \frac{q(t)}{C} \\
\epsilon = R_2\,\dot{q}_2(t) + \frac{q(t)}{C} \\
\epsilon = R_3\,\dot{q}_3(t) + \frac{q(t)}{C} \\
\dot{q}(t) = \dot{q}_1(t) + \dot{q}_2(t) + \dot{q}_3(t) \\
q(0) = q_1(0) = q_2(0) = q_3(0) = \overline{q}
\end{cases}
$$
which can be declined in the two classic cases:

*

*charge process: $\epsilon = \Delta V$, $\overline{q} = 0$, then:
$$
\begin{aligned}
& q(t) = C\,\Delta V\left(1 - e^{-\frac{t}{R_{eq}\,C}}\right),
\quad \quad \quad \,
i(t) = \frac{\Delta V}{R_{eq}}\,e^{-\frac{t}{R_{eq}\,C}}\,; \\
& q_k(t) = r_k\,q(t),
\quad \quad \quad \quad \quad \quad \quad \quad \quad
i_k(t) = r_k\,i(t)\,; \\
& U_{vs} = \frac{q^2(t)}{C}\,,
\quad \quad
U_C = \frac{q^2(t)}{2\,C}\,,
\quad \quad
U_R = \frac{q^2(t)}{2\,C}\,; \\
\end{aligned}
$$

*discharge process: $\epsilon = 0$, $\overline{q} = C\,\Delta V$, then:
$$
\begin{aligned}
& q(t) = C\,\Delta V\,e^{-\frac{t}{R_{eq}\,C}},
\quad \quad \quad \quad \quad \quad \quad \quad
i(t) = -\frac{\Delta V}{R_{eq}}\,e^{-\frac{t}{R_{eq}\,C}}\,; \\
& q_k(t) = (1 - r_k)\,C\,\Delta V + r_k\,q(t),
\quad \quad \quad \,
i_k(t) = r_k\,i(t)\,; \\
& U_{vs} = 0\,,
\quad \quad \quad \quad
U_C = \frac{q^2(t)}{2\,C}\,,
\quad \quad \quad \quad
U_R = \frac{q^2(t)}{2\,C}\,; \\
\end{aligned}
$$
where $r_k = \frac{R_{eq}}{R_k}$ and $R_{eq} = \left(\begin{aligned}\sum_{k = 1}^3\end{aligned} \frac{1}{R_k}\right)^{-1}$.
I hope I haven't made any mistakes, in case I will correct.

A: Yes, what you did is most certainly correct. Now if you have to find out currents in individual branches you just have to notice that since potential difference across each resistor is the same the current passing through a resistor would be inversely proportional to its resistance.
You can verify this by writing the differential equation itself. Consider the current in the branches to be $i_1$, $i_2$ and $i_3$ respectively such that $i_{eq}=i_1+i_2+i_3$. Now the differential equations for different paths would be:
$$ V-\frac {q_{eq}} {C}- i_1R_1=0$$
$$V-\frac {q_{eq}}{C}-i_2R_2=0$$
$$V-\frac {q_{eq}}{C}-i_3R_3=0$$
To proceed you should divide these $3$ equations with $R_1$, $R_2$, and $R_3$ respectively and add.
We have, $\frac {1}{R_{eq}}=\frac {1}{R_1}+\frac {1}{R_2}+\frac {1}{R_3}$
Hence, we get:
$$\frac {V}{R_{eq}}-\frac {q}{R_{eq}C}-i_{eq}=0$$
Since we have $\frac {dq}{dt}=i_{eq}$, all that remains is to integrate, and you'll obtain the required result.

A: Yes you can do all the operations as if it were a circuit with the equivalent resistor.
The reason for this can be seen if you break down what's happening across each of the 3 split wires. The currents all add up while the voltage drops are the same:
$ I_1 + I_2 + I_3 = I \\
 V_1 = V_2 = V_3 = V$
The differential equation is based off of using $I = \frac{\partial Q}{\partial t}$. For each wire you get a separate differential equation:
$  V = R_i \frac{\partial Q_i}{\partial t} + \frac{Q}{C}$
Where $\frac{\partial Q_1}{\partial t} = \frac{\partial Q}{\partial t} - \frac{\partial Q_2}{\partial t} - \frac{\partial Q_3}{\partial t}$ and so on. Tediously, you can do algebra this system of equations to get to a differential equation only in terms of the total current$\frac{\partial Q}{\partial t}$ without reference to the current on the individual wires $\frac{\partial Q_i}{\partial t}$.
You'll then see that you get an easily solveable diff eq where the coefficient in the exponent is exactly the same as $R_{eq}$.


text:
Q: while and if condition within a case statement t-sql I am trying to implement a while loop and if condition (with a function call) in a case statement. Basically, I am trying to do this:
begin
    case
       when (condition1 and condition 2 and ncolumn_num between 6 and 9)
          then
             while @i < 10
             begin
                 if(hsip.Is_numeric( hsip.getTempResponseById(@cregion, @cState_code, @nFY, @nReport_id, @nsection_id, @nquestion_number, @ndisplay_number, @nquestion_number, @nquestion_part_number, @suser_id, @nrow_number, i, @suser_id)))

@nrunningtotal = @nrunningtotal + hsip.getTempResponseById(@cRegion, @cState_code, @nFY, @nReport_id, @nsection_id, @nquestion_number, @ndisplay_number, @nquestion_number,
    @nquestion_part_number, @suser_id, @nrow_number, @ncolumn_number, @suser_id)

        end if
end

Can I implement while loop and if condition within case statement. My business logic requires me to total the columns from 6 to 9 and have final total in col:10.
I have 2 functions: gettempresponsebyid: which returns response string and isnumeric function which converts to number.
Can someone please suggest a better way of doing this. I get this error:

INCORRECT SYNTAX NEAR IF AND INCORRECT SYNTAX NEAR RUNNINGTOTAL.

A: Q: Can I implement while loop and if condition within case statement.
A: No. CASE is not a T-SQL statement. It's an expression.
https://msdn.microsoft.com/en-us/library/ms181765.aspx
In the posted code, one big syntax problem starts right here:
BEGIN CASE ...
      ^

Use the IF / ELSE statement to conditionally control flow in T-SQL.
https://msdn.microsoft.com/en-us/library/ms182717.aspx
For a start, replace the invalid usage of the CASE expression with an IF statement.
BEGIN
  IF (condition1 AND condition2 AND ncolumn_num between 6 and 9)
    BEGIN
      ...
    END;
  END IF;
END;

But even with that change, it's still not clear what you are attempting to achieve or what problem you are trying to solve. There is likely a much better way to do what you are trying to do, but we'd just be throwing out guesses at what you are trying to do.


text:
Q: Is 1 / 0 = 0 according to Isabelle? The following lemma:
lemma "(1::real) / 0 = 0" by simp

goes through because of theorem division_ring_divide_zero
I find this very disturbing since if I want to show that some fraction is non-zero I have to show that the numerator is non-zero AND the denominator is non-zero, which might make sense but confuses two different problems into one.
Is there a way of separating the well-definition of a fraction and its non-zeroness?

A: Isabelle/HOL is a logic of total functions, so there is no built-in notion of a fraction or any other function application being undefined. That is, a / b is defined for all a and b, and it returns their quotient except when b is zero. But then it still has a value.
In the library, the decision was made to complete the function in such a way that x / 0 = 0. This decision simplifies many proofs, since you have to deal with less side conditions. Unfortunately it also sometimes confuses people who expect something else.


text:
Q: Fragment not being replaced when pressing a button I made a fragment that looks like the standard drawer layout from Android Studio to be able to switch Fragments. The thing is, it's not switching fragments when I'm pressing a button. The buttons are referred and made. But nothing is happening when I press the button
This is the "Course list" fragment. Don't mind the names that has Activity in them, it should be named as a fragment.
package com.example.project_b_open_day_application;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

public class CoursesActivity extends Fragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //returning our layout file
        //change R.layout.yourlayoutfilename for each of your fragments
        return inflater.inflate(R.layout.fragment_courses, container, false);
    }

    public void selectCourse(int itemId) {
        //creating fragment object
        Fragment fragment = null;

        //initializing the fragment object which is selected
        switch (itemId) {
            case R.id.informaticaOpleiding:
                fragment = new InformaticaActivity();
                break;
            case R.id.technischeinformaticaOpleiding:
                fragment = new TechnischeinformaticaActivity();
                break;
            case R.id.communicatieOpleiding:
                fragment = new CommunicatieActivity();
                break;
            case R.id.cmgtOpleiding:
                fragment = new CmgtActivity();
                break;
        }
        //replacing the fragment
        if (fragment != null) {
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            ft.replace(R.id.content_frame, fragment);
            ft.commit();
        }
    }
}

fragment_courses.xml
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="491dp"
        android:alpha=".7"
        android:background="@android:color/background_light"
        android:lineSpacingExtra="10sp"
        android:scrollbars="vertical"
        android:text="@string/courseSelectie"
        android:textAppearance="@style/TextAppearance.AppCompat.Medium"
        android:textSize="15sp" />

    <Button
        android:id="@+id/cmgtOpleiding"
        android:layout_width="210dp"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="98dp"
        android:layout_marginLeft="98dp"
        android:layout_marginTop="567dp"
        android:text="CMGT" />

    <Button
        android:id="@+id/informaticaOpleiding"
        android:layout_width="210dp"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentBottom="true"
        android:layout_marginStart="98dp"
        android:layout_marginLeft="98dp"
        android:layout_marginTop="159dp"
        android:layout_marginBottom="373dp"
        android:text="Informatica" />

    <Button
        android:id="@+id/technischeinformaticaOpleiding"
        android:layout_width="210dp"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="95dp"
        android:layout_marginLeft="95dp"
        android:layout_marginTop="400dp"
        android:text="Technische Informatica" />

    <Button
        android:id="@+id/communicatieOpleiding"
        android:layout_width="210dp"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="98dp"
        android:layout_marginLeft="98dp"
        android:layout_marginTop="486dp"
        android:text="Communicatie" />

    </RelativeLayout>

A: Your layout XML file does not feature any content_frame element you refer to. Unless you posted incorrect layout file, it's common practice to use FrameLayout as empty fragment container.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/content_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
<FrameLayout/>

A: You should use the Navigation Component https://developer.android.com/guide/navigation
this will simplify your Fragment handling .


text:
Q: mui5 - TypeError: Cannot read properties of undefined (reading '__emotion_styles') I copied this code from official example:https://mui.com/material-ui/react-stepper/
import { styled } from '@mui/material/styles';
    import { StepConnector, stepConnectorClasses } from '@mui/material/StepConnector';
        const QontoConnector = styled(StepConnector)(({ theme }) => ({
          [`&.${stepConnectorClasses.alternativeLabel}`]: {
            top: 10,
            left: 'calc(-50% + 16px)',
            right: 'calc(50% + 16px)',
          },

but I get the error
TypeError: Cannot read properties of undefined (reading '__emotion_styles')

A: The problem lies in your second line.
Change it to this:
import StepConnector, { stepConnectorClasses } from '@mui/material/StepConnector';


text:
Q: Cannot import .tflite model on android module I have to import a .tflite model on my android project, in particular inside a library module.
Following the official documentation (https://www.tensorflow.org/lite/guide/android) I right-clicked on my library module, then New > Other > TensorFlow Lite Model. So, I have selected the .tflite model I wanted to import and checked the option "Automatic add build feautres and dependencies to build gradle"
But when I try to sync my library build.gradle file I get the following error

Could not create task ':MyLibrary:compileDebugAndroidTestKotlin'.
Cannot query the value of this property because it has no value available.

After some attempts I have found out that this related to the following lines in my library build.gradle file:
buildFeatures {

    mlModelBinding true

}

but I don't know why, also because when I do the exact same procedure in my app module (instead of my library module), everything works fine.

A: I am not sure about your my library module.
You may try the existing app like this, and replace the tflite model in assets. Usually, you can adapt a model from a working example.


text:
Q: Enumerating devices and display modes for OpenGL rendering I'm currently writing an OpenGL renderer and am part-way through writing some classes for enumerating display adaptors, devices and modes for use in drop-down lists.
I'm using EnumDisplayDevices to get the adaptors and then EnumDisplaySettings for each device, giving me bpp, width, height and refresh rate.  However I'm not sure how to find out which modes are available full-screen (there doesn't appear to be a flag for it in the DEVMODE structure).  Can I assume all modes listed can in-principle be instantiated full-screen?
As a follow up question, is this approach to device enumeration generally the best way of getting the required information on Windows?

A: OpenGL has not this distinction between windowed and fullscreen mode. If you want an OpenGL program to be fullscreen you just set the window to be toplevel, borderless, without decoration, stay on top and maximum size.

A: The above is actually a dumb question.  By definition windowed mode must be the current display settings.  All other modes must be available full-screen (provided the OS supports them, i.e. 640x480 not advisable in Vista/7).

A: Hmmph, not correct at all, and with an attitude too. You have variety of functions that can be used.
SetPixelFormat, ChoosePixelFormat, ChangeDisplaySettings.
The PixelFormat functions will let you enumerator available modes. ChangeDisplaySettings with allow you to set whatever screen mode (including bit depth) your app wants. Look them up in MSDN.


text:
Q: UI scaling - XNA (Sorry if I missed the answer)
So I just started out making an XNA game for windows.
And while designing the UI, I was wondering how to scale the UI at different resolutions.
So, imagine that I make a UI for a 1920*1080 screen, how do I make sure this is displayed correctly on a smaller 4*3 screen?
Thanks in advance!
Simon.

A: Usually one designs the GUI in a way that will be usable in the lowest resolution your game offers (traditionally 800x600), then you are sure everything fits correctly at all resolutions.
This is usually why games at higher resolutions seem to have a lot more space for the "playfield" and less for UI than at smaller resolutions.
You could scale the UI once the resolution is higher as well, as easy as using the scale parameter on SpriteBatch.Draw, or you could do it a bit more smartly, by having your assets 9-sliced and aligned to WIDTH/HEIGHT constant percentages.


text:
Q: Using GCP Connection objects in Google Cloud Composer Airflow DAG python operator I have a series of python scripts that draw data from Google Sheets using the gspread library authorized using a json service account keyfile through the oauth2client library:
import gspread
from oauth2client.service_account import ServiceAccountCredentials

scopes = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name(gcp_config_yaml_path,scopes)
client = gspread.authorize(creds)
cur = config['tables_to_load'][i]

sheet = client.open_by_url(cur['spreadsheet_url']).worksheet(cur['sheet_name'])
df=pd.DataFrame(sheet.get_all_records())

I need to convert this into an Airflow DAG using Google Cloud Composer and I would like to take advantage of the connections functionality of Airflow (https://cloud.google.com/composer/docs/how-to/managing/connections#creating_a_connection_to_another_project).
I've uploaded the json keyfile object and created the connection object in the Airflow UI (per. option 'i' in step 'd - iv' in '#2 create a new connection') and I'm able to reference that object in my code using:
client = BaseHook.get_connection('google_cloud_default')

But that's about as far as I can get. Each time I try to call an argument in the connection, I get an error that the argument doesn't exist (keyfile_json, keyfile_dict, scopes, keyfile_path, client, spreadsheets, etc.) and I can't seem to find any documentation on what attributes should be available in the object: (https://airflow.readthedocs.io/en/latest/_api/airflow/gcp/hooks/base/index.html#airflow.gcp.hooks.base.CloudBaseHook).
Any insight on methods for authorizing a Google Sheets connection in a GCP Cloud Composer Airflow environment would be a HUGE help!
Thanks so much in advance!


text:
Q: How can I check if the brackets in a string is balanced? I need to check if a string have balanced brackets using stack but one of my test case is wrong as the brackets is not even but it's returning True.
class Stack:
    def __init__(self):
        self.list = []

    def is_empty(self):
        if len(self.list) == 0:
            return True
        else:
            return False
    def push(self, item):
        self.list.append(item)
    def pop(self):
        return self.list.pop()
    def peek(self):
        return self.list[-1]

def balanced_brackets(text):
    s = Stack()
    opening = '(<'
    closing = ')>'
    mapping = dict(zip(opening, closing))

    for letter in text:
        if letter in opening:
            s.push(mapping[letter])
        elif letter in closing:
            if not s or letter != s.pop():
                return False
    return True

'''
print(balanced_brackets('(<x>)(())()'))#this test case is correct
print(balanced_brackets('(((((((xyz))))))'))#but this is wrong

'''

A: You can use the collections.Counter object to just count the amount of brackets present and compare those numbers to determine balance:
from collections import Counter

cnt = Counter('(((((((xyz))))))')
if cnt['('] != cnt[')']:
    print('unbalanced')

I think you get the idea and can build on it.

A: You must check your stack at the end of the for loop:
def balanced_brackets(text):
    s = Stack()
    opening = '(<'
    closing = ')>'
    mapping = dict(zip(opening, closing))

    for letter in text:
        if letter in opening:
            s.push(mapping[letter])
        elif letter in closing:
            if s.is_empty() or letter != s.pop():
                return False
    if not s.is_empty():
        return False
    return True

output:
print(balanced_brackets('(<x>)(())()'))
print(balanced_brackets('(((((((xyz))))))'))

True
False


text:
Q: Create txt with full paths to files and some additional text I have a bunch of files, in many folders and I wanted to create txt file with full paths to this files and with space and name of the directory they are in. something like:
halva/foo/bar/1/something.jpg 1
halva/foo/bar/2/another.jpg 2
halva/foo/bar/2/anotheranother.jpg 2

Creating a list of paths is something like
find `pwd` -name *.jpg

But I don't know how to add space and directory name after the path.
I'm trying to categorize stuff for school project.

A: $ find .  -name *.jpg -exec bash -c 'd=${1%/*}; d=${d##*/}; printf "%s %s\n" "$1" "$d"' Out {} \;
./halva/foo/bar/1/something.jpg 1
./halva/foo/bar/2/another.jpg 2
./halva/foo/bar/2/anotheranother.jpg 2

For every file found by find, we run the bash script d=${1%/*}; d=${d##*/}; printf "%s %s\n" "$1" "$d" where the first argument, $1, is the file name.
We use suffix removal, d=${1%/*}, to obtain the directory name from the full file name.  We then use prefix removal, d=${d##*/}, to remove all but the name of the last directory from d.  Lastly, printf is used to print the output.
The string Out in the above command is not used unless there is an error in the bash command in which case it functions as the effective command name, $0.
Saving the output to a file
To save the output to a file, we use redirection:
find .  -name *.jpg -exec bash -c 'd=${1%/*}; d=${d##*/}; printf "%s %s\n" "$1" "$d"' Out {} \; >SchoolProject.txt

The > symbol redirects stdout to the file name which follows it.


text:
Q: Value of type 'name' has no dynamic member 'name' using key path from root type 'name' I am learning MVVM and applying it to a simple converter app. The problem arises when I try to pass the array into a picker with ForEach.
Here is my code:
Model:
struct UserOptions {
    var userOption = 0.0
    var userChoseInput = "Meters"
    var userChoseOutput = "Feets"
    var userUnits = ["Meters", "Kilometers", "Feets", "Yards"]
}

ViewModel:
class ViewModel: ObservableObject {
@Published var options = UserOptions()
var finalResult: Double {...calculations here...}
}

View:
struct ContentView: View {

@StateObject private var viewModel = RulerViewModel()

var body: some View {
    Form {
        Section {
            Picker("What is your input?", selection: $viewModel.userChoseInput) {
                ForEach($viewModel.userUnits, id: \.self) { _ in //Value of type 'ObservedObject<ViewModel>.Wrapper' has no dynamic member 'userUnits' using key path from root type 'ViewModel'
                    Text($viewModel.userChoseOutput)
                }
            }
            .pickerStyle(.segmented)
        } header: {
            Text("Choose your input")
        }
        .textCase(nil)

        Section {
            TextField("Your number", value: $viewModel.userOption, format: .number)
                .keyboardType(.decimalPad)
                .focused($userValueIsFocused)
        }
        Section {
            Picker("What is your output?", selection: $viewModel.userChoseOutput) {
                ForEach($viewModel.userUnits, id: \.self) { _ in
                    Text(viewModel.userChoseOutput)  //Value of type 'ObservedObject<ViewModel>.Wrapper' has no dynamic member 'userUnits' using key path from root type 'ViewModel'
                }
            }
            .pickerStyle(.segmented)
        }

A: Use
$viewModel.options.userUnits

And
viewModel.options.userChoseOutput

As for your loop something like this would let you access the unique values
ForEach(viewModel.options.userUnits, id: \.self) { unit in
    Text(unit)
}

I suggest you also look into Measurement it will save you a lot of time when working with conversions.


text:
Q: Getting Ngram frequency from a a large corpus of txt. files I need to develop a code for counting Ngram (1,2,3,4,5,6) frequencies in a large txt corpus using NLTK. I have two problems:
1: I have the following code to import the files as bulk:
from nltk.corpus import PlaintextCorpusReader

Corpus_root = 'C/x/x/Myfolder'
files = PlaintextCorpusReader(corpus_root, '.*')
files.fileids()

gives me an output of all my files read into NLTK.
My first problem is how to connect the corpus reader to the upcoming code to count the ngrams?
My problem in the next step is what module of code should I use to count bigram, trigram and four & five gram and their frequencies which is efficient and fast?
I have 300 txt files and want to use them to get ngram frequency.

A: You use your new corpus the same way as the built-in nltk corpora, like the Brown or Reuters corpus: By calling the methods words() or sents() as needed. Both methods accept a filename argument; if used, you'll only get the words of that file. I recommend using it to process the files one at a time, otherwise some of your ngrams will start in one file and end in another. (Do you want ngrams that fall across sentence boundaries? You must decide and proceed accordingly).
The NLTK book has functions nltk.bigrams, nltk.trigrams, and nltk.ngrams (which accepts a second argument n specifying the ngram size).
for fname in files.fileids():
    lots_of_bigrams = nltk.bigrams(files.words(fname))
    # count them however you want

Chapter 2 of the NLTK book shows how to use words() and sents(), and even has a section on ngrams. Take a good look.


text:
Q: Docker in a Parallels' Virtual Windows 10 Pro Machine
*

*I have a 2013 Mac Pro running the latest Parallels Desktop Pro v
12.2.0 (41591)

*On it, is a Windows 10 Pro virtual with Docker Version 17.03.1-ce-win10 (11972)

Docker can only run with 'windows containers' because when trying to fire up the 'MobyLinux' instance in Hyper-V, it never fires up always bombing at:
tsc: Fast TSC calibration failed
I understand this to be some time dependent sync that has to happen at boot time or such failure occurs. I bought a WD 1TB SSD on a Thunderbolt dock to speed up the run/boot time of the virtual. (it was on my platter RAID cage before) to no avail. No diff.
Parallels IS set to 'enable nested virtualization' and I have started a virtual in Hyper-V on the win 10 Pro VM just fine, no errors. I have checked and unchecked 'PMU Virtualization' which I understand will provide statistics to the host but slow the VM.
I tried:

*

*reducing the number of assigned cores to the VM as suggested by
another post to no avail (2-6 cores tried)

*Reducing the cores to '1' for Docker (and mixing with above attempt)

*increasing the number of cores to docker

*adding/reducing memory to VM/Docker

*playing with the
C:\Program
   Files\Docker\Docker\resources\MobyLinux.ps1
file that loads the VM whereas in another post I changed something to

*verifying that "C:\Users\Public\Documents\Hyper-V\Virtual hard disks\MobyLinuxVM.vhdx" is teh correct location for the .vhdx

*verifying that the .iso is at "C:\Program Files\Docker\Docker\Resources\mobylinux.iso"

*uninstalling Hyper-v/reinstalling Hyper-v manually and letting Docker do it automatically
...

I am at wit's end. I specifically bought this machine so I could do my MS/Visual Studio development along with iOS development on the same box. I have done so, this way, for the past 5-6 years with a 2009 Mac Pro before and now my 2013 MP, but never with Docker before...
So, I need one of two solutions:

*

*a way to make Visual Studio 2015/2017 'look' at my host Mac's Docker instance in order to debug/move on to development

*a way to make this 'MobyLinux' Docker vm run.

A: I was having the same issues and I had initially set the memory to the highest levels allotted and Docker just flat would not run in the Windows box. After tinkering with it for a while I realized that in the Windows box I had not done any of the updates so I ran all those and logged back in, and was getting the same issues of docker not running. That is when I moved over to Parallels and made the changes shown below. Hopefully that helps!
result of docker version:
https://a.cl.ly/kpumLPz4
hyper v:
https://a.cl.ly/jkunldkm
settings in parallels:
https://a.cl.ly/QwuGKq1D
additional settings in parallels that I changed:
https://a.cl.ly/9ZuNElnb
command that I ran for hello_world:
docker run --rm busybox echo hello_world
windows docs on Linux containers 10
docker docs on windows install


text:
Q: Efeito Toggle jQuery de página externa via require ou include PHP Estou criando um menu de usuários, ele fica em uma página a parte que é incorporada a outras páginas como index e home por exemplo. Ele assume o papel de um widget que só é mostrado se houver sessão (usuário logado) porém ele é mostrado com efeito toggle do jQuery para mostrar e esconder.
Na página do script o efeito toggle funciona normalmente más nas páginas que ele é exibido via include ou require ele expande e recolhe automaticamente ou seja abre e fecha.
Como posso solucionar isto, já pesquisei na API mas sem sucesso já usei "perventDefault()" também sem sucesso.
Grato por qualquer ajuda!

A: A sua descrição do problema "ele expande e recolhe automaticamente ou seja abre e fecha" dá-me ideia que está a carregar duas vezes o mesmo código.
Da primeira ele dá ordem para abrir e da segunda para fechar. Uma vez que isso acontece sem interação ou seja automáticamente quando a página abre, presumo ser esse o problema.
Dê uma olhada no código renderizado e veja se tem o script presente mais do que uma vez. Caso "sim" corrija isso, para não carregar o mesmo script mais do que uma vez.


text:
Q: Vue CLI 3 with Axios - Proxy Server is not working I have a VueCLI frontend application running on http://localhost:8080 in the development mode. I attempted to call api services offered by http://localhost:36856, so there would be a CORS problem. Then I set up proxy server configuration in vue.config.js but it's not working. Here are some code below...
// vue.config.js
module.exports = {
  devServer: {
    proxy: 'http://localhost:36856',
  }
}

I create a new instance of axios with a custom config in Api.js
// Api.js
import axios from 'axios'

export default (baseURL = process.env.VUE_APP_DATA_SERVICE_URL) => {
    return axios.create({
        baseURL: baseURL,
        withCredentials: false,
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
        },
    })
}

// .env.development
VUE_APP_DATA_SERVICE_URL=http://localhost:36856

This is an example how I built an api service which is ready to be called
// UserService.js
import apiClient from './Api'

export default {
    getUser (initial) {
        return apiClient().get(`/api/users/${initial}`)
    },
}

A: As you have already proxied your API service, your VUE_APP_DATA_SERVICE_URL should be set to your Vue server :
// .env.development
VUE_APP_DATA_SERVICE_URL = http://localhost:8080


text:
Q: How to delete same row across 2 sheets in Gsheets? I have a Gsheet where if I need to delete a row that contains the text 'none' on Sheet1, it will also delete the same row (or range of rows) on Sheet2.
I've tried the following code which will delete the row on Sheet1, but I can't get it to delete the corresponding row on Sheet2
function sort() {
  var sheet = SpreadsheetApp.getActive().getSheetByName('Sheet1')
              SpreadsheetApp.getActive().getSheetByName('Sheet2')
  var rows = sheet.getDataRange();
  var numRows = rows.getNumRows();
  var values = rows.getValues();
  var rowsDeleted = 0;

  for (var i = 0; i <= numRows - 1; i++) {
    var row = values[i];
    if (row[9] == 'none') {
      sheet.deleteRow((parseInt(i)+1) - rowsDeleted); rowsDeleted++;
    }
  }
};

The expected result is to delete the same row on both sheets, but at the moment it is only deleting on Sheet1.
Thanks!
And if the 'none' text was in a different column on Sheet1 than Sheet2, what would I do? I tried this but it doesn't seem to work:
function sort() {
  var sheet1 = SpreadsheetApp.getActive().getSheetByName('Sheet1');
  var sheet2 = SpreadsheetApp.getActive().getSheetByName('Sheet2');

  var rows = sheet1.getDataRange();
  var numRows = rows.getNumRows();
  var values = rows.getValues();
  var rowsDeleted = 0;

  for (var i = 0; i <= numRows - 1; i++) {
    var row = values[i];
    if (row[9] == 'none') {
      sheet1.deleteRow((parseInt(i)+1) - rowsDeleted);
    if (row[10] == 'none') {
      sheet2.deleteRow((parseInt(i)+1) - rowsDeleted);
      rowsDeleted++;
    }
  }
};}

A: I would create two seperate variables for the two seperate sheets:
function sort() {
  var sheet1 = SpreadsheetApp.getActive().getSheetByName('Sheet1');
  var sheet2 = SpreadsheetApp.getActive().getSheetByName('Sheet2');

  var rows = sheet1.getDataRange();
  var numRows = rows.getNumRows();
  var values = rows.getValues();
  var rowsDeleted = 0;

  for (var i = 0; i <= numRows - 1; i++) {
    var row = values[i];
    if (row[9] == 'none') {
      sheet1.deleteRow((parseInt(i)+1) - rowsDeleted);
      sheet2.deleteRow((parseInt(i)+1) - rowsDeleted);
      rowsDeleted++;
    }
  }
};


text:
Q: Filter element json WCF Data Services In my code here, I consume WCF rest using dataGridView, and by the code below, I want to filter conditions to show only events in last 5 days, so I need to add filter in the link, but I don't know how.
My problem :
* how add filter to show event last 5 days.
My code:
public void  button1_Click(object sender, EventArgs e)
    {
        try
        {
            dataGridView1.DataSource = GetRESTData("http://localhost:55495/EventService.svc/GetAllEvents");
        }
        catch (WebException webex)
        {
            MessageBox.Show("Es gab so ein Schlamassel! ({0})", webex.Message);
        }
    }

    private JArray GetRESTData(string uri)
    {
        var webRequest = (HttpWebRequest)WebRequest.Create(uri);
        var webResponse = (HttpWebResponse)webRequest.GetResponse();
        var reader = new StreamReader(webResponse.GetResponseStream());
        string s = reader.ReadToEnd();
        return JsonConvert.DeserializeObject<JArray>(s);
    }

Image of dataGridView

A: If you can see the inside of the array you can use linq to filter
I think your best bat would be to create a class and bind it to class
but you can try this
JObject eventob= JObject.Parse(s);

var events =
       (from p in (JArray)eventob["ParentObjectYouHave"]
        orderby (DateTime?)p.["Start_Date"] descending
        select p).Take(5);

A: because I am working with WCF, and there is a quety that give me the result, so I modify the query and I get my result
DateTime today = DateTime.Today.AddHours(+12);
DateTime lastday = DateTime.Today.AddDays(-5);
var query = (from a in se.Events
                     where a.start_date <= today && a.start_date >= lastday || a.end_date <= today && a.end_date >= lastday
                     orderby a.start_date
                     select a).Distinct();


text:
Q: CRM Online 2015 API via PHP - securityToken issue I have to implement some code dealing with Microsoft Dynamics CRM 2015 usin PHP language and, since I'm totally new to dynamics CRM and microsoft services, it's pretty tricky for me since there's not a great documentation for non .NET languages.
What I need to do is creating PHP APIs reading and adding rows to Dynamic CRM 2015's "contacts" and "account" tables.
By googling I found out that the main part of the auth part should be done in four main steps (taken from Girish Raja's Blog):
1 - Pass in the device credentials and get a PUID. The device credentials is a randomly generated string that satisfies Live ID schema. You can generate one from this tool: Create CRM 2011 Beta Device
    POST login.live.com/ppsecure/DeviceAddCredential.srf
    Get the PUID from response

2- Pass the device credentials
    POST login.live.com/liveidSTS.srf
    Get the device CiperData (BinaryDAToken)

3- Pass the WLID username, password and device BinaryDAToken
    POST login.live.com/liveidSTS.srf
    Get the security tokens (2 CipherValues) & X509SubjectKeyIdentifier

4- Do CRUD with the web service by passing X509SubjectKeyIdentifier, 2 CipherValues and the SOAP request (with data payload)
    POST yourorganization.api.crm.dynamics.com/XRMServices/2011/Organization.svc
    Get the result from the CRUD response and parse XML to get the data you need

I successfully got through the first point and obtain from DeviceAddCredential.srf a puid, but seems there's no way to afford the second point. I keep getting the "The  entered and stored passwords do not  match".
I'm actually using Ben Speakman's dynamicsClient class and, since it's a 2011 class, my guess is that maybe there's something wrong with its login procedure (for example I had to fix another issue in the code upgrading CURLOPT_SSLVERSION).
Here's the getBinaryDAToken function that tries to obtain device credentials. What I'm not sure about is the url is using, https://login.live.com/liveidSTS.srf. My guess is that maybe auth services moved from login.live.com and there's a similar service for office 365 products I should call instead of login.live.com.
Some other script around use the login.microsoftonline.com/extSTS.srf but looks an even older URL.
Can you please help me with this auth procedure?
Thanx a lot!
private function getBinaryDAToken(){

        $deviceCredentialsSoapTemplate = '
        <s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing" xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
            <s:Header>
                <a:Action s:mustUnderstand="1">http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue</a:Action>
                <a:MessageID>
                    urn:uuid:'.$this->messageid.'
                </a:MessageID>
                <a:ReplyTo><a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address></a:ReplyTo>
                <VsDebuggerCausalityData xmlns="http://schemas.microsoft.com/vstudio/diagnostics/servicemodelsink">uIDPoy9Ez+P/wJdOhoN2XNauvYcAAAAAK0Y6fOjvMEqbgs9ivCmFPaZlxcAnCJ1GiX+Rpi09nSYACQAA</VsDebuggerCausalityData>
                <a:To s:mustUnderstand="1">https://login.live.com/liveidSTS.srf</a:To>
                <o:Security s:mustUnderstand="1" xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
                    <u:Timestamp u:Id="_0">
                        <u:Created>'.$this->currentTime.'Z</u:Created>
                        <u:Expires>'.$this->nextDayTime.'Z</u:Expires>
                    </u:Timestamp>
                    <o:UsernameToken u:Id="devicesoftware">
                        <o:Username>'.$this->deviceUserName.'</o:Username>
                        <o:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">
                            '.$this->devicePassword.'
                        </o:Password>
                    </o:UsernameToken>
                </o:Security>
            </s:Header>
            <s:Body>
                <t:RequestSecurityToken xmlns:t="http://schemas.xmlsoap.org/ws/2005/02/trust">
                    <wsp:AppliesTo xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy">
                        <a:EndpointReference>
                            <a:Address>http://passport.net/tb</a:Address>
                        </a:EndpointReference>
                    </wsp:AppliesTo>
                    <t:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</t:RequestType>
                </t:RequestSecurityToken>
            </s:Body>
        </s:Envelope>';

        return $this->doCurl("/liveidSTS.srf" , "login.live.com" , "https://login.live.com/liveidSTS.srf", $deviceCredentialsSoapTemplate);

    }

UPDATE: thanx to Campey new login url is https://login.microsoftonline.com/RST2.srf solved the second step problem

A: CRM Online has changed from the old authentication method (Windows Live) which required the Device Credentials and now uses Office 365 instead which (in my opinion) makes things easier and its definitely faster.
I have written a blog about this:-
http://crmtroubleshoot.blogspot.com.au/2013/07/dynamics-crm-2011-php-and-soap-using.html
http://crmtroubleshoot.blogspot.com.au/2013/07/dynamics-crm-2011-php-and-soap-calls.html
Also Jason Lattimer wrote a blog more recently which will provide a library you can try and implement and would work with on-premise (mine does not)
http://jlattimer.blogspot.com.au/2015/02/soap-only-authentication-using-php.html


text:
Q: Is it possible to use media queries with a php file? I am trying to make my site responsive and my media query was working but now it isn't. I made some changes and didn't use version control because I'm an idiot. Now I've taken out all the changes and the old media query isn't working, can anyone see why? I've included my css and the html I'm applying it to.
.contact_form {
    margin: auto auto auto 27%;
}

.slides p {
    margin: 2%;
    text-align: center;
}

.slides h2 {
    text-align: center;
    font-size: 1.5em;
}

.required {
    color: red;
}

.privacy p {
    width: 60%;
    text-align: center;
    margin: auto;
}

@media screen and (max-width: 500px) {
    .slides h2 {
        text-align: center;
        font-size: 1em;
        margin: 10% auto auto auto;
    }
    .slides h1 {
        text-align: center;
        font-size: 2em;
        margin: auto;
    }

    .contact_form {
        margin: 2%;
    }

    .privacy p {
        width: 90%;
        text-align: center;
        margin: auto;
    }

    .tablet_content {
        display: none;
    }
}

Html

Laura Pohl Web Solutions

User Based Web Design

  Home

            <button class="dropbtn">About</button>

                My Story
                Mascots

            <button class="dropbtn">Portfolio</button>

                Custom Web Design
                Wordpress

  FAQ
  Contact

Contact Questionnaire

If you'd like to work with me, I can't wait to get started! Your first step is to fill out the custom form below.

                    <form name="form4" action="Contact Us.php" method="post">
                        <input type = "hidden" name ="recipient" value ="1">
                        <input type = "hidden" name ="subject" value ="Contact Survey">
                        <input type = "hidden" name ="print_blank_fields" value ="1">
                        <input type="hidden" name="_pid" value="154040">
                        <input type="hidden" name="_fid" value="A7QPIZEA">

                                        Name:*
                                        <input name="sender" id="name" type="text" maxlength="30" class ="input_text_box required" title="Please type your name." required>

                                        Email:
                                        <input name="senderEmail" type="text" maxlength="30" class ="input_text_box">

                                        Phone:
                                        <input name="senderPhone" type="text" id="textfield2" maxlength="30"class ="input_text_box">

                                        Preferred Method of Contact?
                                        <input type="radio" name="preferredContact" value="phone" id="PreferredContact_0">
                                        Phone

                                        <input type="radio" name="preferredContact" value="email" id="PreferredContact_2">
                                        Email

                                        Would you like a response?*
                                        <input type="radio" name="Response" value="Yes" id="PreferredContact_2">
                                        Yes

                                        <input type="radio" name="Response" value="No" id="PreferredContact_3">
                                        No

                                        What would you like to talk about?*
                                        <input type="radio" name="topic" value="web_design">
                                        Website Design

                                        <input type="radio" name="topic" value="re_design">
                                        Website Re-Design

                                        <input type="radio" name="topic" value="consultation">
                                        Schedule a Consultation

                                        <input type="radio" name="topic" value="quote">
                                        Request a Quote

                                        <input type="radio" name="topic" value="suggestions">
                                        Suggestions

                                        <input type="radio" name="topic" value="problems">
                                        Site Problems

                                        <input type="radio" name="topic" value="something_else">
                                        Something Else

                                        Message Text:

                                            <textarea rows = "5" name="message" maxlength="800" id="Comments" class ="input_text_box" required></textarea>

                                        <input name="submit" type="submit" id="submit" title="Submit" value="Submit" style = "float:left">

                                        <input type="reset" name="reset" id="reset" value="Reset" style = "float:right">

                    </form>

I take your privacy seriously. I will never share any of your
                        information with anyone outside legal requirements. You will never be spammed or marketed
                        to by any of my partners.

            © November 30, 2020 · Laura Pohl · Billerica, MA


text:
Q: Adding custom Roles to Azure Mobile Services User (Google, Twitter, Facebook, Microsoft) I have an .NET Azure Mobile Services project with some controllers I want to secure with the typical Authorize attribute.  I can create a Roles table and a UserProfiles table and associate the various users authenticated through Google, Facebook, etc. with Roles in my Roles table.
My question is:  How do a add the Roles claims to the ServiceUsers after the authentication is complete but before the Authorize filter's OnAuthorize method runs?  Is this even possible?
Example of what I want to do:
[Authorize(Roles = "admin")]
public async Task<IHttpActionResult> Put(int id, MyDto dto){...}

Rough table examples:
Roles
id | name
1  | user
2  | admin

UserProfiles
id | externalLoginId         | favoriteColor
1  | Google:<ServiceUser.Id> | blue

UserRoles (Linking Table)
roleId | userId
2      | 1

Edit:
One option might be to create my own action filter overriding the Authorize filter attribute and in the OnAuthorize method I could query the UserProfiles and Roles tables to get the roles for the current user, then check against the roles specified in the Authorize object's Roles property to determine if the user has access.  But somehow, it feels like there should be a place earlier in the pipeline that I can intercept to just add the Roles claims to the current user.

A: I found the solution.  It involves:

*

*Creating my own ServiceTokenHandler and overriding the CreateServiceUser method to add logic after the call to base.CreateServiceUser(claimsIdentity) that tries to find the roles in my UserProfile table that are linked to the user specified in the claimsIdentity.  If it finds roles, it adds new Role Claims to the Claims collection of the claimsIdentity.
public class RolesServiceTokenHandler : ServiceTokenHandler
{
    public RolesServiceTokenHandler(HttpConfiguration config) : base(config)
    {

    }

    public override ServiceUser CreateServiceUser(ClaimsIdentity claimsIdentity)
    {
        var serviceUser = base.CreateServiceUser(claimsIdentity);

        if (serviceUser != null && serviceUser.Identity.IsAuthenticated)
        {
            var dataContext = new AllergenDerivativesContext();
            var userId = serviceUser.Id;
            var userProfile = dataContext.UserProfiles.Include(u => u.Roles).FirstOrDefault(u => u.ExternalUserId == userId);

            if (userProfile == null)
            {
                //If the user profile does not exist, then create it and assign it to the User role by default.
                userProfile = new UserProfile();

                //Set the ExternalUserId for the UserProfile to the current User's External Login Id.
                userProfile.ExternalUserId = userId;

                //Get the "User" Role Entity.
                var userRole = dataContext.Roles.FirstOrDefault(r => r.Name == Roles.User);

                //Initialize the roles collection for the new UserProfile
                //And add the existing role to the collection.
                userProfile.Roles = new List<Role> { userRole };

                //Add the new UserProfile to the database and save the changes.
                dataContext.UserProfiles.Add(userProfile);
                dataContext.SaveChanges();
            }

            //Get the roles for the UserProfile and add role claims to the ServiceUser's primary Identity.
            foreach (var role in userProfile.Roles)
            {
                ((ClaimsIdentity)serviceUser.Identity).AddClaim(new Claim(ClaimTypes.Role, role.Name));
            }
        }

        return serviceUser;
    }
}

*Register the new RolesServiceTokenHandler with autofac as the IServiceTokenHandler so that when the app requests an IServiceTokenHandler, autofac returns the new RolesServiceTokenHandler.
Inside the WebApiConfig.cs file's static Register method, change the call to ServiceConfig.Initialize so that it looks like:
    HttpConfiguration config = ServiceConfig.Initialize(new ConfigBuilder(options, (httpConfig, autofac) =>
            {
                 autofac.RegisterType<RolesServiceTokenHandler>().As<IServiceTokenHandler>();
            }));

A: You can add the Role Claim to the user Principal, with something like:
new ClaimsIdentity(new Claim[]
{
  new Claim(ClaimTypes.NameIdentifier, loginName),
  new Claim(ClaimTypes.Role, "admin"),
};

but then would you rely on just validating the claims information that gets in for providing role based authorization?
You need to handle anyway the authorization and validation via AuthorizeLevelAttribute, or some other custom attribute instead, to decorate your methods; and that you need to program the behavior that needs to be in place to validate user's role. How you validate the role membership then needs to be done there, in the OnAuthorization method override, and it's up to you: you can query your Db, Graph API, or else. I don't think there are, in this moment, other options of managing authorization, and the documentation and samples point also in this way
Here some good reference:

*

*Get started with custom authentication

*Field Engineer Sample

*This session registration: Building Microsoft Azure Mobile Services with Visual Studio (from about minute 28)


text:
Q: Collection Sort I have this code, comparator for sorting values:
public static Comparator<Partikel> getFFsorted() {
    Comparator comp = new Comparator<Partikel>() {
        @Override
        public int compare(Partikel s1, Partikel s2) {
            if(s1.ff>s2.ff)
            {
                return 1;
            }
            else
            {
                return -1;
            }
        }
    };
    return comp;
}

but I have an error like this  :

Exception in thread "main" java.lang.IllegalArgumentException:
  Comparison method violates its general contract!   at
  java.util.TimSort.mergeHi(TimSort.java:868)
at java.util.TimSort.mergeAt(TimSort.java:485)
at java.util.TimSort.mergeCollapse(TimSort.java:410)
at java.util.TimSort.sort(TimSort.java:214)
at java.util.TimSort.sort(TimSort.java:173)
at java.util.Arrays.sort(Arrays.java:659)
at java.util.Collections.sort(Collections.java:217)

How do I fix it?

A: Your method doesn't handle the case of equal ff.
As a result compare(s1,s2) and compare(s2,s1) will both return -1 when s1.ff == s2.ff. This violates the contract of compare, which requires that sgn(compare(x, y)) == -sgn(compare(y, x)) for all x and y.
    public int compare(Partikel s1, Partikel s2) {
        if(s1.ff > s2.ff) {
            return 1;
        } else if (s1.ff < s2.ff) {
            return -1;
        } else {
            return 0;
        }
    }

A: those ff members in the Partikel class look like something numeric to me...
so it would be better that you implement the static method from the wrapper class..
something like:
@Override
public int compare(Partikel p1.ff, Partikel p2) {
    return Integer.compare(p1.ff, p2.ff);
    //or
    return Double.compare(p1.ff, p2.ff);
    //or
    return Long.compare(p1.ff, p2.ff);
    //or
    return Float.compare(p1.ff, p2.ff);
}

A: This will happen  if you have any NaN values in your comparator
For example:
public class Demo
{
    public static void main(String[] args) {
        double a = Double.NaN;
        double b = Double.NaN;

        System.out.println(a < b);
        System.out.println(a > b);

}
    }
All of these print false. So you could end up in a situation where two non-NaN values were both deemed "equal" to NaN, but one was greater than the other. Basically, you should work out how you want to handle NaN values. Also check that that really is the problem, of course... do you really want NaN values for your Partikel?
And also the default comparator has implementation to compare for three cases i.e
     1.Greater than
     2. Less than
     3. Equal to

Since you are taking only two ,so try to segregate into three as follows :
 public int compare(Partikel s1, Partikel s2) {
    if(s1.ff>s2.ff)
        return 1;
    else if(s1.ff<s2.ff)
        return -1;
 //for equality
  else
        return 0;
}

A: You don't handle the case where the values are equal.
Java has builtin functions to correctly compare primitive data types in the wrapper class for each primitive data type (Integer, Long, Float, Double, etc) which you can use:
Comparator comp = new Comparator<Partikel>() {
    @Override
    public int compare(Partikel s1, Partikel s2) {
        return Integer.compare(s1.ff, f2.ff);
        // Or Long.compare, Float.compare, Double.compare, etc.
        // depending on the datatype of the field "ff".
    }
};