text:
Q: Is this a suitable sine wave osc? how would I control the frequency? Overview-
I'm making a bank of analog sine wave oscillators and I'm interested in keeping the design compact.
I've started by making a Wien Bridge oscillator. As I'm working from a single power supply and I'm trying to keep the design small, I've been using the LM386n-1 IC.
I'll be using the oscillators to do some additive audio synthesis, maybe some FM and I'll probably need some of the oscillators as LFOs.
My questions are-
Is this a suitable approach for making a compact analog sine wave oscillator?
Also, how would you suggest I control the frequency, which component value should be changed to achieve this? - I've tried messing with all the resistors to change the pitch, but they all seem to be interdependent.
Here is the circuit I've been working from, it's from the National Semiconductor LM386 Low Voltage Audio Power Amplifier datasheet-

And this is what my implementation looks like, I don't have a suitable incandescent bulb so I've just replaced it with a 1KΩ pot. I'm still not sure what I'll use in the final circuit as AGC, suggestions are welcome.

A: The reason for using a small incandescent lamp is that it has a positive temperature coefficient (PTC), which the oscillator needs to stabilize the amplitude. The potmeter won't do.
The negative feedback resistor should be at least twice the resistance of the PTC.
The oscillator frequency is determined by the two resistors and two capacitors on the non-inverting pin, and the schematic seems to have an error: both resistors should be equal (either 4k7 or 47k), as should the capacitors. The frequency is

\$f = \dfrac{1}{2 \pi R C}\$

So you can control the frequency by using a stereo potmeter for the resistors. Both channels should have good tracking.
Following suggestions I made a separate answer about DDS, so the comments about it actually refer to that answer.

A: A few people suggested that I add a separate answer about the DDS. So I extracted it from my other answer.
Olin's answer is a sensible one: this is the digital age. Like he says your signal will be much more stable (crystal precision), but using a microcontroller is not the solution; your sine lookup table is fixed, and the frequency steps may be too coarse.
A better solution is DDS, Direct Digital Synthesis. This is often done with special DDS ICs, like AD9851, and allows for a very high level of frequency control (depending on the clock up to milliHertz resolution). You'll need a microcontroller to control the sysnthesizer, so it won't be the most simple application, nor the cheapest. But there are good alternatives: Jesper Hansen designed a simple DDS implementation based on an AVR controller.

A: This doesn't answer what you asked, but I think relevantly addresses the problem.
Nowadays doing this in analog is silly except perhaps for some very specialized or high frequency applications.  You mentioned this is a audio application, so I can't imagine a good reason for all the analog.  Your first sentence mentions you want a whole bank of these things, and you want the design compact.  The analog approach will definitely not be compact.  Another problem with the analog approach is that the frequencies and amplitudes will drift.
A much better way to do this is to generate all the sine waves in a processor and add them up digitally.  They can all use the same 1/4 wave sine table, just index into it at different increments per sample to get the different frequencies.
This is well within the capability of even low end DSPs, like the Microchip dsPIC line.  A dsPIC33F sounds like a good fit.  At 40 MIPS, you have 1000 instruction cycles every sample at 40 kHz sample rate.  That's a lot, and will allow lots of different sines to be added each sample.  The DSP multiply-accumulate hardware will allow each contribution to be added with its own gain easily.
Digitally derived signals like that won't drift in frequency or amplitude, and will have better signal to noise ratio.  With 16 bit numbers you get 96 dB.  That's doable in analog if you're careful.  However, the accuracy of the digital signal will be far greater.  There is no chance at all the analog sine generators can be within 1 part in 65000 each sample just due to amplitude unpredictability alone.  The frequency of the digital signals can also be set very accurately, and the digital sine synthesizer won't need a few cycles to stabalize before its output is what you expect.
Edit: Clarification on Sine Generation
I see some drawbacks of table lookup sine generation mentioned in other answers that are incorrect, so I'm adding more clarification of the method here.  Two objections were brought up, accuracy and frequency resolution.
First let me explain the normal structure of a sine lookup.  Note that a sine wave is four-way symmetric.  You therefore only need to store 1/4 cycle.  The basic first quadrant waveform is repeated either reversed, negated, or both in the remaining three 1/4 cycles.  A nice trick to make this easy is to express the angle such that a full circle is a power of two, preferably using the whole word of whatever machine is running the code.  That means angle additions and subtraction wrap around the circle automatically without explicit code for that purpose if you do the angle math in unsigned integer arithmetic.  This representation also makes the lookup into the 1/4 wave table very easy.
The two high bits of the angle indicate the quadrant, so only the remaining lower bits are used to index into the table.  If the highest angle bit is set, then the table result is negated.  If the next highest bit is set, then the table is indexed backwards.  That is as simple as complementing the remaining low bits before using them as the index.  The table need not be the size such that all the low bits can be used as the index.  For example on a 16 bit machine like a dsPIC, it would be natural to use 16 bits for the angle.  That leave 14 bits to index into the table, which would be a very large table.  Typically, and in this case, such a large table is not needed.  A reasonable size might be 1024 segments, which would use 10 index bits.  The remaining 4 index bits (in this example) can either be ignored or used to interpolate between adjacent entries.  The table would actually have 1025 entries, which means 1024 segments.  A sine wave approximated with 4096 (the table gets used 4 times over the whole sine wave) steps would be quite good.  If the extra bits are used to interpolate between adjacent table entries, it's even better.  Imagine a sine wave approximated with 4096 linear segments per cycle.  It would be very difficult to see any error.
As for accuracy, do the math.  A sine wave changes most rapidly at zero angle, so it's easy to compute the worst case error from just a dumb lookup into a 1024 point table.  The first table value would be 0, and the second sine(Pi/2048) = .00153.  The worst case error is therefore half that, or .000767.  That amounts to a signal to noise ratio of 62 dB, and that is just from picking a table value without interpolation.  Using the remaining 4 index bits to interpolate increases the signal to noise ratio to 86 dB.  If that's not good enough, use a wider number for the angle and interpolate using the extra bits.
Frequency resolution is also not a issue.  Apparently some are thinking the angle increment per sample must be a multiple of the angle step per table entry.  That's not true at all.  Using just a 16 bit angle and a 1024 segment table already gives you 16 times more angle resolution than each table entry.  In practise I'd probably use two words (32 bits in this example) for the angles and angle increments.  That provides very high frequency resolution, and also gives you more interpolation bits to get the signal to noise ratio up.  At a 40 kHz sample rate, a 20 Hz tone (the worst case) would require a angle increment of 1/2000 circle per sample.  That's one part in 33 is using 16 bit angles.  That alone could be good enough for many applications.  If using a 32 bit angle, the frequency resolution at 20 Hz is over 1 part in 2 million.
So let's not dismiss lookup-based sine generation in firmware so quickly.  At least let's not dismiss it for the wrong reasons.  Note that none of the things I described would be difficult for a dsPIC to do.  This includes interplation since a dsPIC can do a 16 x 16 into 32 bit multiply in a single instruction cycle.

A: I would second (or third) Steven's and Olin's arguments. Whilst it is perfectly possible to build an analog synthesiser it poses significant challenges. Top of the list is temperature stability - having to frequently retune oscillators is no fun and I write from personal experience in building a traditional (subtractive) synthesiser with just two oscillators some years ago.
And if you're keen on additive synthesis, forget it! You will be juggling far too many oscillators and you won't be able to keep up with the frequency drift. Now I know some people still prefer analog synthesisers to digital for their fat, free-phase sound but I'm not convinced.
There is a guy called Doug Curtis who founded a company called Curtis Electromusic Specialities in 1979 to produce dedicated ICs for the traditional functions of VCOs, VCFs etc and these probably extended the life of analog synthesiser designs by a few years by being far less prone to drift (and making designs cheaper), but even he succumbed to the digital revolution by 1988. There is still old stock of his chips around which go for premium prices on eBay!
On the subject of FM sound synthesis, this was the subject of my BSc dissertation in 1981 and whilst I managed to develop an analog FM sound 'engine', my conclusions were that it couldn't match a digital synthesis engine - and that was 30 years ago!

A: Here is a software DDS approach I've used, based on Jesper Hansen's MiniDDS, which generates a sine wave up to 200 kHz or so. Filtering would be useful in some applications.


text:
Q: I get an error while trying to create superuser I am new to Django and i am trying to create a superuser ( i'm on Linux mint) and everytime i get a very weird error that i did not get with other Django projects. The error is the following : ( I did not modify anything in the django project besides adding my app in the installed apps list and the url of the app in urls.)
  File "/home/user/.local/lib/python3.6/site-packages/django/urls/resolvers.py", line 538, in url_patterns
    iter(patterns)
TypeError: 'module' object is not iterable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 21, in <module>
    main()
  File "manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "/home/user/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
    utility.execute()
  File "/home/user/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/user/.local/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/user/.local/lib/python3.6/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 59, in execute
    return super().execute(*args, **options)
  File "/home/user/.local/lib/python3.6/site-packages/django/core/management/base.py", line 332, in execute
    self.check()
  File "/home/user/.local/lib/python3.6/site-packages/django/core/management/base.py", line 364, in check
    include_deployment_checks=include_deployment_checks,
  File "/home/user/.local/lib/python3.6/site-packages/django/core/management/base.py", line 351, in _run_checks
    return checks.run_checks(**kwargs)
  File "/home/user/.local/lib/python3.6/site-packages/django/core/checks/registry.py", line 73, in run_checks
    new_errors = check(app_configs=app_configs)
  File "/home/user/.local/lib/python3.6/site-packages/django/core/checks/urls.py", line 13, in check_url_config
    return check_resolver(resolver)
  File "/home/user/.local/lib/python3.6/site-packages/django/core/checks/urls.py", line 23, in check_resolver
    return check_method()
  File "/home/user/.local/lib/python3.6/site-packages/django/urls/resolvers.py", line 398, in check
    warnings.extend(check_resolver(pattern))
  File "/home/user/.local/lib/python3.6/site-packages/django/core/checks/urls.py", line 23, in check_resolver
    return check_method()
  File "/home/user/.local/lib/python3.6/site-packages/django/urls/resolvers.py", line 397, in check
    for pattern in self.url_patterns:
  File "/home/user/.local/lib/python3.6/site-packages/django/utils/functional.py", line 36, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/user/.local/lib/python3.6/site-packages/django/urls/resolvers.py", line 545, in url_patterns
    raise ImproperlyConfigured(msg.format(name=self.urlconf_name))
django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'pleasework' from '/home/user/example.com/attempt/pleasework/__init__.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.

Can you please tell me what am i doing wrong? I tried creating a virtual enivronment but it did not work.

A: Please add more detailed code so I could try to help better, in any case, try the following -

*

*Use the --username flag instead of directly passing a username:

python manage.py createsuperuser --username yourusername

*Make sure you imported the model correctly in the admin.py file.

*Check that this row appears in the INSTALLED_APPS:

'django.contrib.admin',

*Try migrating the changes and then run createsuperuser.

I hope one of them solves the problem.

A: *

*To check migrations, run python3 manage.py migrate.

*Check the row appears in <project_root>/<project>/settings.py's INSTALLED_APPS list.

Then using python3 manage.py createsuperuser should work properly. It should prompt you:
Username (leave blank to use '<user>'):
E-mail:
Password:

where <user> is your computer's user name.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Render then append new component after click Is it possible to render and append a new component after click? I have my calendar component
return (
  select(day)}>{number}
);

onClick I want to render my jsWindow Component
render(){
    return (

        {console.log(this.props)}
            <Icon icon={close} className="closeBtn" size={24} onClick={(e)=>e.target.parentNode.parentNode.remove()}/>
            {this.props.children}

    )
}

After click close icon I want remove JsWindow.

A: You can use conditional rendering:
{ condition && <Component /> }

A: Put the selected day in component state and render your component based on that. On click you set or reset the state, which will trigger a rerender.
Basic example to get you started:
state = {
    day: undefined
}

selectDay = day => {
    this.setState({day});
};

resetDay = () => {
    this.setState({day: undefined});
};

render(){
    const day = this.state.day;
    return  day ? (

                <Icon icon={close} className="closeBtn" size={24} onClick={this.resetDay}/>
                {this.props.children}

        ) : (
            this.selectDay(day)}>{number}
        )
    )
}


text:
Q: MySQL and word boundary in regex How can I use regex word boundary in a MySQL query?
For instance, I want to match either 'product' or 'newsletter',
It works fine with OR,
IF(? = 'product' OR ? = 'newsletter', ... , ...)

But how about a regex? I assume it would be something like this below?
IF(? REGEXP '^('product'||'newsletter')+$', ..., ... )

A: SELECT *
FROM tbl
WHERE description REGEXP '[[:<:]]red[[:>:]]|[[:<:]]blue[[:>:]]'

or, as a select expression:
SELECT IF(description REGEXP '[[:<:]]red[[:>:]]|[[:<:]]blue[[:>:]]', 1, 0) AS is_matched, tbl.*
FROM description

You can use RLIKE as a synonym but REGEXP seems to be more popular [citation needed].
Case Sensitivity
From the MySQL manual for REGEXP:
REGEXP is not case sensitive, except when used with binary strings.
mysql> SELECT 'a' REGEXP 'A', 'a' REGEXP BINARY 'A';
        -> 1  0

A: Use REGEXP or RLIKE.
Regular expressions in MySQL
In your case, you could use MATCH() ... AGAINST fulltext search with MyISAM storage engine.
Or you could use IN() as @Wiseguy mentioned


text:
Q: Formatted Date in mysql database How can i extract the date stored in database? Example this date is stored in database 2012-01-02 and i want to get the month the day
and year.
year = 2012
month = 01
day = 02

A: SELECT MONTH(date_col) AS month
     , YEAR(date_col) AS YEAR
     , DAYOFMONTH(date_col) AS day
  FROM tablename
...

Year()
month()
dayofmonth()

A: Simply read it out of the database into a date object and use the date objects methods to get the information you are wanting


text:
Q: Tables vs Divs for page layout I know there are a lot of articles concerning the topic at hand.
My mission is to achieve a fixed-fluid 2 column layout with sticky header and footer. After reading several articles, people claim that divs are better for building page layouts. I agree with that in certain cases. Can anyone tell me if what I am trying to accomplish, would be better with divs than a table. Can anyone give me a more simple solution with DIVs than the attached code using a TABLE.
CSS
   html,body{
     height:100%;
     width:100%;
     margin : 0;
   }

   table{
    height:100%;
    width:100%;
    border-collapse: collapse;
    border-spacing: 0
   }

   #top{
     height:100px;
     background-color:black;
   }

   #bottom{
     height:100px;
     background-color:blue;
   }

   #left{
     width:250px;
     background-color:blue;
   }

HTML

A: If your code is for non-tabular data, then without even looking at your code I can tell you that the div element is better for layout than table.
For more information this SO article is quite useful:
Why not use tables for layout in HTML?

Can anyone give me a more simple solution with DIVs than the attached
  code using a TABLE

It's not about what's the simplest to code. Plus div layout is more scalable. In the long-run you will run into less roadblocks with divs.

A: In my opinion, tables should only ever be used for tabular data - but that's my opinion.  The point of using divs is that they're much easier to manipulate with CSS and don't come with built-in formatting that you then need to override.  For fluid layouts, it's the hive-mind opinion that divs are better because they are inherently fluid while tables are not.  But, really, it comes down to personal preference; in your case, you can do it whichever way your heart desires!


text:
Q: Access JWT payload variables (tuupola in Slim Framework) I am successfully authenticating my users against my API using Slim Framework 4.
I do so using a middle ware that looks like this:
$app->add(new \Tuupola\Middleware\JwtAuthentication([

    "algorithm" => ["HS512"],
    "logger" => $logger,
    "secret" => getenv('JWT_SECRET'),
    "rules" => [
        new Tuupola\Middleware\JwtAuthentication\RequestPathRule([
            "path" => "/v2"
        ])
    ]
]));

This works like a breeze except one thing. The payload contains a string that I need to pass to the database so I need to read the token in the API when it is sent back to the API (It is in the http headers).
How could I automatically set a PHP variable that contains the string coming from the payload?
The token arrives back to the API in the Authorization header.
The payload when sent back to the API looks like this:
{
  "jti": "1PD0vKUwqlBocToxmZgeJA",
  "iat": 1580575309,
  "exp": 1580577109,
  "stk": "KsdL5WxiGkYIkFeduiQkMR8nTwOZ56ik"
}

I am interrested in accessing the value of "stk" :)
I am not an advanced PHP developer so please forgive me if my question is a bit simple.
Thanks a lot in advance for your precious answers.

A: So,
The answer is Here.
It is passed as a attribute and easily accessed as any attribute later on.


text:
Q: how to constraint the Type parameter to a certain interface only Would it be possible to constraint a Type parameter to only allow caller to pass in class type that implements a certain interface?  Take below as example:
public void RegisterProcessors(params Type[] types)

As it is now, caller can pass in any class type to this method.  For example:
RegisterProcessors(typeof(string));

But what I really want is to only allow caller to pass in type that implements the IProcessor interface.  Is that possible?  Something like below, of course, below is syntactically wrong
public void RegisterProcessors(params Type<IProcessor>[] types)

A: No, basically. If you were using generics, you could use
public void RegisterProcessor<T>() where T : IProcessor

But you can't combine that with params, so the caller would need to invoke it once per type. Which might be fine.


text:
Q: Falling Image with Delay Guys I need to know how can I show a image falling 7 seconds up to down after game load?
This is my current code:
on .h file
IBOutlet UIImageView *CloudDrop;
NSTimer *timer;

-(void)CloudDropCode;

on .m file
-(void)CloudDropCode{
    // Drop Cloud Images Animation
    CloudDrop.animationImages = [NSArray arrayWithObjects:
                            [UIImage imageNamed:@"CloudDrop2.png"],
                            [UIImage imageNamed:@"CloudDrop.png"],
                            [UIImage imageNamed:@"CloudDrop2.png"],
                            [UIImage imageNamed:@"CloudDrop.png"],
                            [UIImage imageNamed:@"CloudDrop2.png"],
                            [UIImage imageNamed:@"CloudDrop.png"],
                            [UIImage imageNamed:@"CloudDrop2.png"],
                            [UIImage imageNamed:@"CloudDrop.png"],nil];

    [CloudDrop setAnimationRepeatCount:1];
    CloudDrop.animationDuration = 0.1;
    [CloudDrop startAnimating];

    // Drop Cloud Ramdom Position
    CloudDrop.center = CGPointMake(CloudDrop.center.x, CloudDrop.center.y +2);
    if (CloudDrop.center.y > 590){
        ramdomPosition = arc4random() %266;
        ramdomPosition = ramdomPosition +54;

        CloudDrop.center = CGPointMake(ramdomPosition, -40);
        dropCloudUsed = NO;

    // Time to Drop Cloud Down Again
        [[NSRunLoop currentRunLoop]runUntilDate:[NSDate dateWithTimeIntervalSinceNow:7.0]];

        CloudDrop.hidden = NO;
    }
}

And this in the viewDidLoad:
- (void)viewDidLoad
    timer = [NSTimer scheduledTimerWithTimeInterval:0.03 target:self selector:@selector(CloudDropCode)userInfo:nil repeats:YES];

Right now, the image falls when the game are load. I'm trying to fall the image 10 seconds after game load. Any Idea or suggestion? Thanks

A: define variables:
CloudDrop.animationImages = [NSArray arrayWithObjects:
                        [UIImage imageNamed:@"CloudDrop2.png"],
                        [UIImage imageNamed:@"CloudDrop.png"],nil];

NSUInteger currentIndex = 0;

Repeat next method 7 times
[UIView animateWithDuration:1.0 delay:0.0 options:UIViewAnimationOptionCurveEaseIn animations:^{
    //Update there. get next image by index and realize animation
} completion:^(BOOL finished) {
    if (currentIndex == 0)
        currentIndex++;
    else
        currentIndex = 0;
}];

Implementing alternate function call for its completion by yourself.


text:
Q: FATAL EXCEPTION: main on Android 4.x but not Android 2.X I am getting some errors when trying to run my android app on an emulator that is running any version of Android 4.x but it works fine on any version of Android 2.X.
package com.EXCLUDED_FOR_PRIVACY.EXCLUDED_FOR_PRIVACY;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.ImageView;
import android.graphics.Color;

public class EXCLUDED_FOR_PRIVACY extends Activity {

    public int WebView1Bool=0;
    public int WebView2Bool=0;
    public int WebView3Bool=0;
    public int WebView4Bool=0;
    private TabHost tabs;

    private void setupTabHost() {
        tabs = (TabHost) findViewById(R.id.my_tabhost);
        tabs.setup();
    }

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        setupTabHost();
        tabs.getTabWidget().setDividerDrawable(R.drawable.tab_divider);

        setupTab(new ImageView(this), 1);
        setupTab(new ImageView(this), 2);
        setupTab(new ImageView(this), 3);
        setupTab(new ImageView(this), 4);

        WebView mWebView1;
        mWebView1 = (WebView) findViewById(R.id.webview1);
        mWebView1.setBackgroundColor(Color.parseColor("#a3a3a3"));
        mWebView1.setBackgroundColor(0);
        mWebView1.getSettings().setJavaScriptEnabled(true);
        mWebView1.setWebViewClient(new MobileClient());
        mWebView1.loadUrl("EXCLUDED_FOR_PRIVACY");
        WebView1Bool=1;

        tabs.getTabWidget().getChildAt(0).setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v){
                tabs.setCurrentTab(0);
                if(WebView1Bool==0){
                    WebView mWebView1;
                    mWebView1 = (WebView) findViewById(R.id.webview1);
                    mWebView1.setBackgroundColor(Color.parseColor("#a3a3a3"));
                    mWebView1.setBackgroundColor(0);
                    mWebView1.getSettings().setJavaScriptEnabled(true);
                    mWebView1.setWebViewClient(new MobileClient());
                    mWebView1.loadUrl("EXCLUDED_FOR_PRIVACY");
                    WebView1Bool=1;
                }
            }
        });

        tabs.getTabWidget().getChildAt(2).setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v){
                tabs.setCurrentTab(1);
                if(WebView2Bool==0){
                    WebView mWebView2;
                    mWebView2 = (WebView) findViewById(R.id.webview2);
                    mWebView2.setBackgroundColor(Color.parseColor("#a3a3a3"));
                    mWebView2.setBackgroundColor(0);
                    mWebView2.getSettings().setJavaScriptEnabled(true);
                    mWebView2.setWebViewClient(new MobileClient());
                    mWebView2.loadUrl("EXCLUDED_FOR_PRIVACY");
                    WebView2Bool=1;
                }
            }
        });

        tabs.getTabWidget().getChildAt(4).setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v){
                tabs.setCurrentTab(2);
                if(WebView3Bool==0){
                    WebView mWebView3 = (WebView) findViewById(R.id.webview3);
                    mWebView3.setBackgroundColor(Color.parseColor("#a3a3a3"));
                    mWebView3.setBackgroundColor(0);
                    mWebView3.getSettings().setJavaScriptEnabled(true);
                    mWebView3.setWebViewClient(new MobileClient());
                    mWebView3.loadUrl("EXCLUDED_FOR_PRIVACY");
                    WebView3Bool=1;
                }
            }
        });

        tabs.getTabWidget().getChildAt(6).setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v){
                tabs.setCurrentTab(3);
                if(WebView4Bool==0){
                    WebView mWebView4;
                    mWebView4 = (WebView) findViewById(R.id.webview4);
                    mWebView4.setBackgroundColor(Color.parseColor("#a3a3a3"));
                    mWebView4.setBackgroundColor(0);
                    mWebView4.getSettings().setJavaScriptEnabled(true);
                    mWebView4.setWebViewClient(new MobileClient());
                    mWebView4.loadUrl("EXCLUDED_FOR_PRIVACY");
                    WebView4Bool=1;
                }
            }
        });
    }

    private class MobileClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }

    private void setupTab(final View view, final int i) {
        View createTabView_view = LayoutInflater.from(tabs.getContext()).inflate(R.layout.tabs_bg, null);
        ImageView createTabView_tv = (ImageView) createTabView_view.findViewById(R.id.tabsImage);
        if(i==1){
            TabSpec tabSpec = tabs.newTabSpec("EXCLUDED_FOR_PRIVACY");
            createTabView_tv.setImageResource(R.drawable.ic_discounts);
            tabSpec.setIndicator(createTabView_view);
            tabSpec.setContent(R.id.webview1);
            tabs.addTab(tabSpec);
        } else if(i==2){
            TabSpec tabSpec = tabs.newTabSpec("EXCLUDED_FOR_PRIVACY");
            createTabView_tv.setImageResource(R.drawable.ic_specials);
            tabSpec.setIndicator(createTabView_view);
            tabSpec.setContent(R.id.webview2);
            tabs.addTab(tabSpec);
        } else if(i==3){
            TabSpec tabSpec = tabs.newTabSpec("EXCLUDED_FOR_PRIVACY");
            createTabView_tv.setImageResource(R.drawable.ic_directory);
            tabSpec.setIndicator(createTabView_view);
            tabSpec.setContent(R.id.webview3);
            tabs.addTab(tabSpec);
        } else if(i==4){
            TabSpec tabSpec = tabs.newTabSpec("EXCLUDED_FOR_PRIVACY");
            createTabView_tv.setImageResource(R.drawable.ic_membership);
            tabSpec.setIndicator(createTabView_view);
            tabSpec.setContent(R.id.webview4);
            tabs.addTab(tabSpec);
        }
    }
}

Here are the errors I am seeing
09-24 13:11:25.329: E/Trace(1151):              error opening trace file: No such file or directory (2)
09-24 13:11:25.539: D/dalvikvm(1151):           GC_FOR_ALLOC freed 43K, 4% free 8316K/8583K, paused 42ms, total 45ms
09-24 13:11:25.549: I/dalvikvm-heap(1151):      Grow heap (frag case) to 8.829MB for 691216-byte allocation
09-24 13:11:25.669: D/dalvikvm(1151):           GC_CONCURRENT freed <1K, 4% free 8990K/9287K, paused 75ms+6ms, total 124ms
09-24 13:11:25.829: D/gralloc_goldfish(1151):   Emulator without GPU emulation detected.
09-24 13:11:26.209: I/Choreographer(1151):      Skipped 42 frames!  The application may be doing too much work on its main thread.
09-24 13:11:26.379: I/Choreographer(1151):      Skipped 44 frames!  The application may be doing too much work on its main thread.
09-24 13:11:27.509: I/Choreographer(1151):      Skipped 54 frames!  The application may be doing too much work on its main thread.
09-24 13:11:28.319: D/AndroidRuntime(1151):     Shutting down VM
09-24 13:11:28.319: W/dalvikvm(1151):           threadid=1: thread exiting with uncaught exception (group=0x40a13300)
09-24 13:11:28.379: E/AndroidRuntime(1151):     FATAL EXCEPTION: main
09-24 13:11:28.379: E/AndroidRuntime(1151):     java.lang.RuntimeException: Unable to start activity ComponentInfo{com.EXCLUDED.EXCLUDED/com.EXCLUDED.EXCLUDED.EXCLUDED}: java.lang.NullPointerException
09-24 13:11:28.379: E/AndroidRuntime(1151):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
09-24 13:11:28.379: E/AndroidRuntime(1151):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
09-24 13:11:28.379: E/AndroidRuntime(1151):     at android.app.ActivityThread.access$600(ActivityThread.java:130)
09-24 13:11:28.379: E/AndroidRuntime(1151):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
09-24 13:11:28.379: E/AndroidRuntime(1151):     at android.os.Handler.dispatchMessage(Handler.java:99)
09-24 13:11:28.379: E/AndroidRuntime(1151):     at android.os.Looper.loop(Looper.java:137)
09-24 13:11:28.379: E/AndroidRuntime(1151):     at android.app.ActivityThread.main(ActivityThread.java:4745)
09-24 13:11:28.379: E/AndroidRuntime(1151):     at java.lang.reflect.Method.invokeNative(Native Method)
09-24 13:11:28.379: E/AndroidRuntime(1151):     at java.lang.reflect.Method.invoke(Method.java:511)
09-24 13:11:28.379: E/AndroidRuntime(1151):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
09-24 13:11:28.379: E/AndroidRuntime(1151):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
09-24 13:11:28.379: E/AndroidRuntime(1151):     at dalvik.system.NativeStart.main(Native Method)
09-24 13:11:28.379: E/AndroidRuntime(1151):     Caused by: java.lang.NullPointerException
09-24 13:11:28.379: E/AndroidRuntime(1151):     at com.EXCLUDED.EXCLUDED.EXCLUDED.onCreate(EXCLUDED.java:85)
09-24 13:11:28.379: E/AndroidRuntime(1151):     at android.app.Activity.performCreate(Activity.java:5008)
09-24 13:11:28.379: E/AndroidRuntime(1151):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
09-24 13:11:28.379: E/AndroidRuntime(1151):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
09-24 13:11:28.379: E/AndroidRuntime(1151):     ... 11 more
09-24 13:11:30.289: I/Process(1151):            Sending signal. PID: 1151 SIG: 9

I apologize if this is something really simple that any java developer would know, I have to admit I barely know what I am doing in Java but am under the gun to get this built. Thank you very much for any help.

A: Get rid of all the tabs.getTabWidget().getChildAt(...).setOnClickListener() crap, replacing it with a single TabHost.OnTabChangeListener that you register with your TabHost, to find out when the user changes tabs. Your existing code assumes a particular internal structure of a TabWidget, and that assumption is unreliable, as you are discovering.


text:
Q: Close a tab in Lightning Console in a visualforce page I am trying to have console app work in both SFDC Classic and Lightning. I'm trying to close a sub tab via some JavaScript code. With Classic Console I did the following:
sforce.console.closeTab(id, callback);

The above method written in JS is invoked from apex:commandbutton with oncomplete attribute.
As per the documentation provided in Console Developer guide, closeTab() and getEnclosingTabId() methods are supported in both Classic and Lightning and no additional considerations are required to make the methods work in Lightning. But I see that the closeTab() functionality is not working as expected when accessed in Lightning experience.
I see there are some equivalent method which are supported only in Lightning Console here.
But this is called from within a Lightning component. How can I do that from a VisualForce page?

A:

var callCloseTab= function callCloseTab(result) {
    sforce.console.closeTab(result.id);
}

function closeTab() {
    sforce.console.getEnclosingTabId(callCloseTab);
}

closeTab();
</script>


text:
Q: How to fill holes inside a polygon in QGIS? I need to fill/delete the lines inside the polygon. I have tried the dissolve and delete holes tools, but did not work for me.
Any ideas and thoughts to delete the holes?

A: Have you try the geometry tools repair from processing menu. Seems invalid geometry ?
If it's not working try to use GRASS in the processing menu : v.clean (break, snap, rmdangle and rmsa) with a snap tolerance to 0.001. If not working, then try 0.01 or 0.1 (try to find the best threshold).


text:
Q: Bar graph is not rendering I'm trying to duplicate this code found on bl.ocks.org, but I can't get my bar graph to render.  I'm pulling from a csv instead of a tsv, but I don't think that would made a difference.  There aren't any errors written to the console.  Where am I going wrong?
<script type="text/javascript">
    $( document ).ready(function() {
        loadChart();
    });

    function loadChart() {
        var svg = d3.select("svg");
        var margin = { top: 20, right: 20, bottom: 30, left: 40},
            width = +svg.attr("width") - margin.left - margin.right,
            height = +svg.attr("height") - margin.top - margin.bottom;

        var x = d3.scaleBand().rangeRound([0,width]).padding(0.1),
            y = d3.scaleLinear().rangeRound([height, 0]);

        var g = svg.append(g).attr("transform", "translate(" + margin.left + "," + margin.top + ")");

        d3.csv("Data/data.csv", function(d) {
            d.NumProducts = +d.NumProducts;
            return d;
        }, function(error, data) {
            if (error) throw error;

            x.domain(data.map(function(d) { return d.Category; }));
            y.domain([0, d3.max(data, function(d) { return d.NumProducts; })]);

            g.append("g")
                .attr("class", "axis axis--x")
                .attr("transform", "translate(0," + height + ")")
                .call(d3.axisBottom(x));

            g.append("g")
                .attr("class", "axis axis--y")
                    .call(d3.axisLeft(y).ticks(10))
                .append("text")
                    .attr("transform", "rotate(-90)")
                    .attr("y", 6)
                    .attr("Dy", "0.71em")
                    .attr("text-anchor", "end")
                    .text("Number of Products");

            g.selectAll(".bar")
                .data(data)
                .enter().append("rect")
                    .attr("class" , "bar")
                    .attr("x", function(d) { return x(d.Category); })
                    .attr("y", function(d) { return y(d.NumProducts); })
                    .attr("width", x.bandwidth())
                    .attr("height", function(d) { return height - y(d.NumProducts); });
        });
    }
</script>

The csv:
Category,NumProducts
Beverages,12
Condiments,12
Confections,13
Dairy Products,10
Grains/Cereals,7
Meat/Poultry,6
Produce,5
Seafood,12

A: The main issue that you have is down to missing speech marks.
 var g = svg.append(g)

Should read:
 var g = svg.append("g")

If you were to inspect your DOM you would see
<svg>
    <undefined transform="translate(40,20)">
    ... (correct DOM)
    </undefined>
</svg>

The reason that nothing renders after this point, is because the browser doesn't know how to render an <undefined> element, therefore it stops trying to render.
This immediately indicated that one of the append calls wasn't working because the DOM didn't understand the type of element given to it. Making the change produces this:


text:
Q: Is this a virus? C:\Users\username\AppData\Local\Temp\FyNtEw.exe Rfter updating my computer Windows 11 & restarted the system, the following warning popups again and again:
"Do you want to allow this app to make changes to your computer?"
(CMD logo here) Windows Command Processor
Programme location: "C\Windows\System32\cmd.exe" /k START""
"C:\Users\username\AppData\Local\Temp\FyNtEw.exe" & EXIT

Even if I clicked on No and Yes, it pops back up again and again. Any help?
See the picture below I took from my phone

A: It's telling you where the file is.  It's probably a malware.  If it wasn't malware or virus, it wouldn't have an obscure name.  Go to that path and delete it.
If it won't let you delete it then rename it to FyNtEw.txt so it cant get executed and then reboot your PC.
And then install a virus or malware scanner.


text:
Q: Transform sequence of lines into python list, using Vim? Using Vim, in a file containing strings on successive lines:
bear
fox
jackie chan

What's a good, repeatable way to make a python list of strings:
['bear', 'fox', 'jackie chan']

Tried a kludgy sequence of regexs over the range (such as :1,3s/^/'/, :1,3s/$\n/', /, followed by pesky hand edits.

A: ggcG                           change the whole buffer

<C-r>=string(split(@"))<CR>    insert a string representation of
                               the content of the unnamed register

<Esc>                          leave insert mode

A: I'd go with a macro:
qq0i'^[$a',^[

This wrap the line into a '...',
You can select all your lines and apply the macro with:
:normal! @q

Then you can add a [ before the first line, a ] after the last one and
vipJ

A: You can use multiple substitutions and :join to accomplish this:
:%s/^\s*\zs.*/'&',/|'[,']j|s//[&]/

This will yield:
['bear', 'fox', 'jackie chan',]

Personally I like the trailing comma, but you can remove it with another substitution or :normal command:
%s/^\s*\zs.*/'&',/|'[,']j|s//[&]/|s/,]$/]
%s/^\s*\zs.*/'&',/|'[,']j|exe "norm! $x"|s//[&]/

For more help see:
:h :s
:h \zs
:h :j
:h :norm
:h :exe
:h :bar
:h :range
:h '[

A: Solution
:s/\(.*\)\n\(.*\)\n\(.*\)/['\1', '\2', '\3']/

A: With my Join plugin (https://github.com/sk1418/Join), you can join lines with separator. For the given example, you can do:
:%s/^\|$/'/g|%J ','

then manually add the [' and '] to BOL and EOL
or just
:%J "','"

then manually add [' and '] to BOL and EOL


text:
Q: Use types from one module for another I'm using Babylonjs with the Rollupjs together with typescript.

Babylonjs has typings bundled with the package so when I import it like this:
import { ArcRotateCamera, Engine, SceneLoader, Vector3 } from "babylonjs";

I get all of the typing information and type-checking from typescript, however, due to (I think) how babylon.js is bundled - Rollup cannot bundle it throwing errors:

1: import { ArcRotateCamera, Engine, SceneLoader, Vector3 } from "babylonjs";
2: import "babylonjs-loaders";
3: import React from "react";
Error: 'Engine' is not exported by node_modules/babylonjs/babylon.js

To fix rollup bundling I need to change imports to:
import { ArcRotateCamera, Engine, SceneLoader, Vector3 } from "babylonjs/es6";

but then I lose all of the typing information...
So my quickest solution to that would be to somehow instruct typescript that babylon.d.ts applies also to babylonjs/es6.js.
P.S
these named import are all correct and working because component works when I use it with @storybook (which loads it with webpack).

A: You'll notice how the babylonjs module is declared in babylon.d.ts:
declare module 'babylonjs' {
    export = BABYLON;
}
declare module BABYLON {
    // Many declarations...
}

To associate the same declarations with the babylonjs/es6 module name, all you have to do is follow the same format and add a module declaration to a new file in your project:
declare module 'babylonjs/es6' {
    export = BABYLON;
}

(Adding this code inside another module file will not work because then it will be treated as a module augmentation instead of a module declaration.)
Consider filing an issue to have this change made in the original babylonjs package.


text:
Q: Let $\mu,\nu$ be two finite positive measures. Show that, there is a set $E$ such that $\mu_E\ll\nu_E$ and $\mu_{E^c}\perp\nu_{E^c}$
Let $\mu,\nu$ be two finite positive measures on $(X,\mathfrak{M})$. For $E\in\mathfrak{M}$, we define $\mu_E(A):=\mu(A\cap E)$ and similarly $\nu_E$. Show that, there is $E\in\mathfrak{M}$ such that $\mu_E\ll\nu_E$ and $\mu_{X\setminus E}\perp\nu_{X\setminus E}$

We define the signed measure $\lambda=\mu-\nu$. By John Hahn Decompostition, $\lambda=\lambda^+-\lambda^-$ and there are $E,F\in\mathfrak{M}$ which are disjoint, $E\cup F=X$ such that $\lambda^+=\lambda_E$ and $\lambda^-=\lambda_F$.
So, $\lambda^+=\mu_E-\nu_E$ and $\lambda^-=\mu_F-\nu_F$. We have $\lambda^+\perp\lambda^-\implies \mu_E-\nu_E\perp \mu_F-\nu_F\implies \mu_E\perp\nu_F$ and $\mu_F\perp\nu_E$. But this is obvious, because $\lambda_E$ and $\nu_F$ are concentrated on $E$ and $F$ respectively and they are disjoint. I have to find $E$ such that $\mu_E\perp\nu_E$.
And I am not having any way out for the absolute continuity case? Can anyone help me to solve the problem?
Thanks for your help in advance.

A: Hint: Let $\lambda =\mu +\nu$. Be Radon Nikodym Theorem we can  write $\mu(A)=\int_A f d\lambda$ and $\nu(A)=\int_A g d\lambda$. Let $E=\{x: f(x)g(x)>0\}=\{x: f(x)>0\}\cap \{x: g(x)>0\}$ and $F=\{x: f(x)g(x)=0\}$. It is fairly easy to see that this meets the requirements.


text:
Q: Simple method to display a popup message from within an Apex Class We have a ProcessBuilder that is triggered when a certain checkbox is checked on a Contact. The processbuilder calls an @Invokable Apex function that creates an object and performs some other tasks. We want to display a user friendly message (rather than the system generated error message) if the object creation throws an error. I have been searching but can't seem to find a simple approach. We are just using the standard Salesforce page. Any help here would be much appreciated.

A: As you have designed it, this can't be done.

*

*The Process Builder starts on a DML action which is at the database layer of the application. Thus, PB automation occurs regardless of input stimulus - UX, REST API, scheduled job, scheduled flow, Data Loader, Bulk API, etc.  The PB-caught error offers no opportunity for "friendlificaton" although the invocable Apex's catch block can help somewhat by throwing a new error with a clearer message.

To show a friendly message to the user you have to:

*

*Use some form of code that wraps the UX initiation such as a VF, Aura, LWC or screen flow driven off a button/quick action

*The controller/client-side logic catches the error and displays the message to the user


text:
Q: blank page using Vite React Electron I use Vite Bundler for an react App with Electron. There is the link : https://github.com/electron-vite/electron-vite-react
Before, I use Electron React Boilerplate and I did the migration for Electron-Vite-React. But, when I launch my project, there is juste a white page, and no error in the IDE terminal. I search everywhere but no solutions.
I don't know what to show, but there is my package.json
{
  "version": "0.0.1",
  "private": true,
  "debug": {
    "env": {
      "VITE_DEV_SERVER_URL": "http://127.0.0.1:7777/"
    }
  },
  "scripts": {
    "dev": "vite",
    "build": "tsc && vite build && electron-builder",
    "preview": "vite preview",
    "pree2e": "vite build --mode=test",
    "e2e": "playwright test"
  },
  "devDependencies": {
    "@playwright/test": "^1.31.0",
    "@types/react": "^18.0.28",
    "@types/react-beautiful-dnd": "^13.1.3",
    "@types/react-dom": "^18.0.11",
    "@vitejs/plugin-react": "^3.1.0",
    "electron": "^23.1.1",
    "electron-builder": "^23.6.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "sass": "^1.58.3",
    "typescript": "^4.9.5",
    "vite": "^4.1.4",
    "vite-electron-plugin": "^0.8.2",
    "vite-plugin-electron": "^0.11.1",
    "vite-plugin-electron-renderer": "^0.12.1"
  },
  "engines": {
    "node": "^14.18.0 || >=16.0.0"
  },
  "dependencies": {
    "@emotion/react": "^11.10.6",
    "@emotion/styled": "^11.10.6",
    "@mui/icons-material": "^5.11.9",
    "@mui/material": "^5.11.10",
    "@mui/x-data-grid": "^5.17.25",
    "react-beautiful-dnd": "^13.1.1",
    "react-hook-form": "^7.43.2",
    "react-router-dom": "^6.8.1"
  }
}


text:
Q: What is the best practice to update 2 million rows data in MySQL? What is the best practice to update 2 million rows data in MySQL?
As update by primary id, I have to update 1 by 1. It is so slow.
Like below
UPDATE table SET col1=value1 WHERE id=1;
UPDATE table SET col1=value2 WHERE id=2;
UPDATE table SET col1=value3 WHERE id=3;

UPDATE table SET col1=valueN WHERE id=N;

A: Assuming table is innodb (look at SHOW CREATE TABLE table output) one of the reasons its slow is an insufficient innodb_buffer_pool_size.
I also assume its in the default auto_commit=1 mode meaning each SQL line is a single transaction.
Its generally best to avoid processes that need to change every row in a table.
You could split this into a number of threads doing updates and that should get though the list quicker. If the table is MyISAM it won't scale this way.

A: Good way to update many rows in one query with INSERT statement with condition ON DUPLICATE KEY UPDATE. The statement will update the old row if there is a duplicate value in a UNIQUE index or PRIMARY KEY. See documentation.
INSERT INTO table (id, col1, col2, col3)
VALUES (%s, %s, %s, %s)
ON DUPLICATE KEY UPDATE
    col1 = VALUES(col1),
    col2 = VALUES(col2),
    col3 = VALUES(col3);

To update really big amount of date like 2 millions rows try to separate you data to several queries by several thousand rows.
Also notice optimization tips: Optimizing INSERT Statements and Bulk Data Loading for InnoDB Tables


text:
Q: simple way to display data in a .txt file on a webpage? Working on a project, one of the webpages will display a list of people (specifically, a list of people from a graduation class that haven't been located yet).
Instead of manually updating these lists in tables which is a boneheaded Web 1.0 way of doing it, I'd like to take the submitted list of names, convert them to a simple .txt list, and then display that list on the webpage.
So far, the easist way to do this is to use an iframe element... only thing is, I cannot (or don't know how to) apply any text styling to the contents of the iframe. I've published a sample of what I've been able to accomplish here: http://dongarber.com/test//helpus-iframetest.html
The default font is courier, and the client probably ain't gonna be too keen on it.
Is there a better way to do this, that's doesn't require ASP.NET or a database?
#list  p {
    font: arial;
    font-size: 14px;
}

...

Help us locate all of our classmates from the High School class of 1961. If  you know where they live or their e-mail addresses contact the Reunion Committee.

A: How are you converting the submitted names to "a simple .txt list"?  During that step, can you instead convert them into a simple HTML list or table?  Then you could wrap that in a standard header which includes any styling you want.

A: That's the code I use:
<?php
    $path="C:/foopath/";
    $file="foofile.txt";

    //read file contents
    $content="

$file

".htmlspecialchars(file_get_contents("$path/$file"))."

            ";

    //display
    echo $content;
?>

Keep in mind that if the user can modify $path or $file (for example via $_GET or $_POST), he/she will be able to see all your source files (danger!)

A: Easy way:

*

*Rename missingmen.txt to missingmen.html.

*Add a single line to the top of missingmen.html:
<link href="txtstyle.css" rel="stylesheet" type="text/css" />

*Create a file called txtstyle.css, and add to it a line like this:
html, body {font-family:Helvetica, Arial, sans-serif}

A: You cannot style a text file, it must be HTML

A: In more recent browsers code like below may be enough.

<object data="https://www.w3.org/TR/PNG/iso_8859-1.txt" width="300" height="200">
Not supported
</object>

A: I find that if I try things that others say do not work, it's how I learn the most.

README.txt

This worked for me. I used the yellow background-color that I set in the stylesheet.
#list  p {
    font: arial;
    font-size: 14px;
    background-color: yellow ;
}

A: If you just want to throw the contents of the file onto the screen you can try using PHP.
<?php
    $myfilename = "mytextfile.txt";
    if(file_exists($myfilename)){
      echo file_get_contents($myfilename);
    }
?>

A: Most easy and simple way to show file on your web page

Here is a screenshot. You can see here a pdf and txt file.

Sample Screenshot of TXT file rendered on HTML using iframe.

A: You can add it as script file.
save the txt file with js suffix
in the head section add


text:
Q: Homework measure Let $f \in L^{1}(0,1)$, $\alpha \in (0,1)$. Suppose that integral of $f$ over any set of measure $\alpha$ is zero. Then $f=0$ almost everywhere.
I had the following idea:
Let $E = \{ x: f(x)>0\}$ it is measurable. $E_n = \{x:f(x) > \frac{1}{n}\}$ is also measurable.
Then $E = {\bigcup}^\infty_{n=1} E_n$
Next suppose by contradiction that $f=0$ almost everywhere.
With this exist $n \in \mathbb N$ that
$\mu (E_n \cap X) > 0$
Lastly
$\int_E |f(x)|d\mu > \frac{1}{n}\int_E X_{E_{n}}d\mu$.
Which is a contradiction.


text:
Q: LINQ query to return duplicated in list not working I am not sure why but the below code and LINQ statements are returning 0 items and I cannot figure out why. There should be 3 duplicate entries....
List<SelectListItem> allClientUserAndCandidateViews = new List<SelectListItem>();
foreach (var clientUserView in clientUserViews)
            {
                SelectListItem item =
                    new SelectListItem
                    {
                        Value = clientUserView.ClientViewId.ToString(),
                        Text = clientUserView.Name
                    };
                allClientUserAndCandidateViews.Add(item);
            }

    List<SelectListItem> matchingClientUserAndCandidateViews = allClientUserAndCandidateViews
          .GroupBy(x => x)
          .Where(g => g.Count() > 1)
          .Select(y => y.Key)
          .ToList();

     List<SelectListItem> matchClientUserAndCandidateViews = allClientUserAndCandidateViews
          .GroupBy(x => x)
          .Where(g => g.Skip(1).Any())
          .SelectMany(g => g)
          .ToList();

A: The reason for this behavior is that SelectListItem is using default implementation for GetHashCode and Equals (source), meaning that all groups on (x => x) will have exactly one item.
Since SelectListItem is outside your code, work around the problem by grouping by value and text instead:
List<SelectListItem> matchingClientUserAndCandidateViews = allClientUserAndCandidateViews
      .GroupBy(x => new {x.Value, x.Text})
      .Where(g => g.Count() > 1)
      .Select(y => y.First())
      .ToList();

 List<SelectListItem> matchClientUserAndCandidateViews = allClientUserAndCandidateViews
      .GroupBy(x => new {x.Value, x.Text})
      .Where(g => g.Skip(1).Any())
      .SelectMany(g => g)
      .ToList();

A: If the SelectListItem in your code is this one, then the problem is related to treating all elements as distinct ones, as Distinct uses a default comparer which does not properly compare all the properties.
Check this answer for a full solution:
public class SelectListItemComparer : IEqualityComparer<SelectListItem>
{
    public bool Equals(SelectListItem x, SelectListItem y)
    {
        return x.Text == y.Text && x.Value == y.Value;
    }

    public int GetHashCode(SelectListItem  item)
    {
        int hashText = item.Text == null ? 0 : item.Text.GetHashCode();
        int hashValue = item.Value == null ? 0 : item.Value.GetHashCode();
        return hashText ^ hashValue;
    }
}

As a side note, I would make a clear separation between application logic (computing distinct items) and view logic (view models such as SelectListItem). Particularly, you could define some ItemServiceModel to hold relevant data, compute the distinct items and them map to SelectListItems.

A: In your GroupBy you need to GroupBy(x=> x.Value) or GroupBy(x=>x.Text)

A: If you are looking for getting the grouping and counting, this should work for you.
var countByGroups = allClientUserAndCandidateViews.GroupBy(x => x.Text, (key, values) => new { key, Count = values.Count() });

Also you can use LinqPad to see what the results of your groupings are by calling Dump method.  Copy Paste this in LinqPad.
void Main()
{
    var clientUserViews = new List<Test>();
    var t1 = new Test()
    {
        Text = "A",
        Value = "A"
    };
    var t2 = new Test()
    {
        Text = "A",
        Value = "A"
    };
    var t3 = new Test()
    {
        Text = "A",
        Value = "A"
    };

    clientUserViews.Add(t1);
    clientUserViews.Add(t2);
    clientUserViews.Add(t3);
    List<Test> allClientUserAndCandidateViews = new List<Test>();
    foreach (var clientUserView in clientUserViews)
    {
        Test item =
            new Test
            {
                Value = clientUserView.Value.ToString(),
                Text = clientUserView.Text
            };
        allClientUserAndCandidateViews.Add(item);
    }

    allClientUserAndCandidateViews.Dump("allClientUserAndCandidateViews");

    allClientUserAndCandidateViews.GroupBy(x => x.Text, (key, values) => new { key, Count = values.Count() }).Dump();

}

// Define other methods and classes here
public class Test
{
   public string Value { get; set; }
   public string Text { get; set; }
}


text:
Q: datatables row toggle and fixedColumns I use datatable-row-toggle-option feature (grouping and collapsing rows)
DataTable Row Toggle Option
and need datatables.fixedColumns (first column is always show)
but new created row with category make bug in fixedColumns plugin
this throw error
Uncaught TypeError: Cannot read property 'anCells' of undefined
at HTMLTableRowElement.<anonymous> (dataTables.fixedColumns.min.js:27)
at Function.each (jquery.min.js:130)
at init.each (jquery.min.js:49)
at m._fnClone (dataTables.fixedColumns.min.js:27)
at m._fnCloneLeft (dataTables.fixedColumns.min.js:23)
at m._fnDraw (dataTables.fixedColumns.min.js:22)
at HTMLTableElement.<anonymous> (dataTables.fixedColumns.min.js:13)
at HTMLTableElement.dispatch (jquery.min.js:1199)
at HTMLTableElement.y.handle (jquery.min.js:1153)
at Object.trigger (jquery.min.js:1188)

this is my configuration :
var table = $('#example').DataTable( {
                        ajax: {
                        "drawCallback": function ( settings ) {
                            var api = this.api();
                            var rows = api.rows( {page:'current'} ).nodes();
                            var last=null;

                            api.column(1, {page:'current'} ).data().each( function ( group, i ) {
                                if ( last !== group ) {
                                    $(rows).eq( i ).before(
                                        '
'+group+'
'
                                    );

                                    last = group;
                                }
                            } );
                        },
                        "columnDefs": [

                            { "visible": false, "targets": 2 },

                            {
                                "render": function ( data, type, row ) {

                                    return data+' N/A';
                                },
                                targets: '_all',
                            }

                        ],
                        fixedColumns:   true,

                    } );


text:
Q: What does the little squiggly ~ do in Linux? I have two instances of it being used and I am wondering what each does:

*

*service=~

*mv ~/Desktop/Service$version.tgz $service
What does the little squiggly ~ do?
Then, after that that, what would cd $service do?

A: It looks like the commands are doing the following.

*

*Assign a variable called service to your home folder location, for example:
/home/user

*It moves the file from your desktop to the top level of your home directory, for example:
/home/user/Desktop/Service$version.tgz $service

*The script then changes the directory to the top level of the home directory.
So, all the script is doing is just cleaning up your desktop by moving the file to your /home/user folder instead.

A: The squiggly thing is called a "tilde".
It expands to your home directory.
Try
echo ~
echo $HOME

Both statements put your home directory by itself on a line..
See bash Tilde Expansion for details.

A: The "squiggly" is called a tilde. It is used to refer to your home directory which on Linux, is normally /home/username. It is also stored in the $HOME environment variable. Expanding the ~ to the location of the home directory is the job of the shell (like zsh or bash) or file manager (like Nautilus) and not the filesystem or OS its self.
You can also use this to refer to another user's home directory. For instance, if the other user's username is bob, you could refer to their home directory with ~bob, which will be expanded to /home/bob/.
The first example you've given sets the variable service to ~, so it corresponds to your home directory. This is equivalent to service=/home/username or service=$HOME.
The second example copies the file ~/Desktop/Service$version.tgz (or /home/username/Desktop/Service$version.tgz) to /home/username. This command is equivalent to:
mv ~/Desktop/Service$version.tgz ~

or
mv ~/Desktop/Service$version.tgz $HOME

or
mv ~/Desktop/Service$version.tgz /home/username/

The third will change the current working directory ($PWD) to /home/username/. This is equivalent to:
cd /home/username/

or
cd $HOME

A: In both #1 & #2: ~ is your home directory, so if you are qwerty it will likely be the directory /home/qwerty.  So try ls ~ to see that.
For #1: it looks to me like the variable service is being defined as your home directory.
That means after #2 has moved the tgz file from the Desktop subdirectory to your home directory, #3 then changes to the home directory.

A: I'll add here that ~user also expands to [user]'s home directory, so it's not just a shortcut for your own home directory.
E.g.:
[guy@abox anotherdir]$ cd ~
[guy@abox ~]$ pwd
/home/guy
[guy@abox ~]$ cd ~john
[guy@abox john]$ pwd
/home/john


text:
Q: A group $G$ is said to satisfy the permutizer condition in $G$ if $P_{G}(H)$ strictly contains $H$ for any subgroup $H$ of $G$. The permutizer of a subgroup $H$ of $G$ is defined to be the subgroup generated by all cyclic subgroups of $G$ that permute with$H$, i.e. $P_{G}(H)= \langle x \in G | \langle x\rangle H = H \langle x \rangle \rangle$.
A group $G$ is said to satisfy the permutizer condition in $G$ if $P_{G}(H)$ strictly contains $H$ for any subgroup $H$ of $G$.
A group $G$ is said to $satisfy$ the maximal permutizer condition if $P_{G}(M)=G$ for any maximal subgroup $M$ of $G$.
Let $M$ be a maximal subgroup of $G$ and $P_{G}(M)=G$ .Then there exists an element $x \in G/M $  such that $G= \langle x \rangle M= M \langle x \rangle$, which implies that $M$ has a cyclic supplement in $G$.Hence $G$ is soluble.
  $Z_{n}$ is a example for this groups. What other examples are there for this?


text:
Q: How to retain the instance variables passed to Quartz job ever after webserver restart? I am using Quartz scheduler in java web application.
My question is an extension to How to pass instance variables into Quartz job
I followed the Accepted answer in the above post & could pass instance variable to my quartz job. But after restarting the web server, the passed instance variable is not retained (i.e., it is null)
public class SimpleJob implements Job {
    @Override
    public void execute(JobExecutionContext context)
            throws JobExecutionException {
        SchedulerContext schedulerContext = null;
        try {
            schedulerContext = context.getScheduler().getContext();
        } catch (SchedulerException e1) {
            e1.printStackTrace();
        }
        ExternalInstance externalInstance =
            (ExternalInstance) schedulerContext.get("ExternalInstance");

        System.out.println(externalInstance); //Will print "null" after web server restart

        float avg = externalInstance.calculateAvg();
    }
}

How can I retain the "ExternalInstance" even after web server restart?
Thank you very much in advance.

A: You can add a ServletContextListener to your web project, and on contextInitialized(), you can put the externalInstance in the SchedulerContext. That way, it will be loaded every time the server restarts.


text:
Q: Bash Menu issue / question? There is another thread for this topic but it is closed. I would like to revisit this. I m trying to write a utility script for myself. However i am not a programmer so I wanted to get some feed back. although I do appreciate others attempt to help, I do not want to go off on a tangent and have to read a bunch of stuff. My need is very specific.
PS3='Please enter your choice: '
options=("Option 1" "Option 2" "Option3" "Quit")
select opt in "${options[@]}"
do
    case $opt in

 if [ "$RESP" = "y" ]; then
                action here
        else
                echo "Thank you."
        sleep 2
    exit;
fi

;;
        "Option 2")
            echo "you chose choice 2"
            ;;
        "Option 3")
            echo "you chose choice 3"
            ;;
        "Quit")
            break
            ;;
        *) echo invalid option;;
    esac
done

How do I get from the exit; or fi back to the menu ?
Thanks very much,

A: First, you're missing an "Option 1") case before your if. And "Option3" in your options list is missing a space: it should be "Option 3".
Other than that, I can't really understand your question. What's the problem? Once those are fixed, it seems to work for me. Below is a test run. To clarify, exit exits the script and returns the user to their shell prompt. If you want to stay in the script, don't use exit.
ace@ace2:~$ ./test.sh
1) Option 1
2) Option 2
3) Option 3
4) Quit
Please enter your choice: 1
Thank you.
ace@ace2:~$ RESP="y" ./test.sh
1) Option 1
2) Option 2
3) Option3
4) Quit
Please enter your choice: 1
you chose choice 1
Please enter your choice: 2
you chose choice 2
Please enter your choice: 3
you chose choice 3
Please enter your choice: 4
ace@ace2:~$

Here is the code:
#!/bin/bash
PS3='Please enter your choice: '
options=("Option 1" "Option 2" "Option 3" "Quit")
select opt in "${options[@]}"
do
    case $opt in

    "Option 1")
        if [ "$RESP" = "y" ]; then
            echo "you chose choice 1"
        else
            echo "Thank you."
            sleep 2
            exit
        fi
        ;;
    "Option 2")
        echo "you chose choice 2"
        ;;
    "Option 3")
        echo "you chose choice 3"
        ;;
    "Quit")
        break
        ;;
    *)
        echo invalid option
        ;;
    esac
done


text:
Q: Error reading SSH protocol banner[WinError 10054] An existing connection was forcibly closed by the remote host I made this code to log on to several servers but it doesn't work optimally. It works until a certain moment, when I start to receive the same error countless times. Why is this happening and how can I fix it?
Error:
Traceback (most recent call last):
  File "C:\Users\Silver\AppData\Local\Programs\Python\Python39\lib\site-packages\paramiko\transport.py", line 2039, in run
    self._check_banner()
  File "C:\Users\Silver\AppData\Local\Programs\Python\Python39\lib\site-packages\paramiko\transport.py", line 2215, in _check_banner
    raise SSHException(
paramiko.ssh_exception.SSHException: Error reading SSH protocol banner[WinError 10054] An existing connection was forcibly closed by the remote host

Code:
import paramiko
from concurrent.futures import ThreadPoolExecutor
from threading import Thread
scanned = 0

def replace_cmd_line(output):
    print(output,end='\r')

def check_connection(ip,username,password):
    global scanned
    scanned += 1
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(ip,22,user_pass[0],user_pass[1])
        print("Found " + ip + " ---> " + username + ':' + password)
        out = open("found_ssh_ips.txt",'a')
        out.write(f"{ip} {username}:{password}")
        out.close()
    except:
        ssh.close()
        return

executor = ThreadPoolExecutor(max_workers=5)
file = open('ips_ssh.txt','r')

def output():
    global scanned
    global file
    while True:
        replace_cmd_line('Scanned ' + str(scanned))

Thread(target=output).start()

for ip in file.readlines():
    ip = ip[:-1]
    with open('passfile.txt','r') as passfile:
        for user_pass in passfile.readlines():
            user_pass = user_pass.split(':')
            user_pass[1] = user_pass[1][:-1]
            executor.submit(check_connection,ip,user_pass[0],user_pass[1])

A: I guess the reason for the Error reading SSH protocol banner exception is that you close the connection only in case when an exception is generated. So better use a finally statement to close the connection in any case.
from concurrent.futures import ThreadPoolExecutor
from threading import Thread
scanned = 0

def replace_cmd_line(output):
    print(output,end='\r')

def check_connection(ip,username,password):
    global scanned
    scanned += 1
    ssh = None
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(ip,22,user_pass[0],user_pass[1])
        print("Found " + ip + " ---> " + username + ':' + password)
        out = open("found_ssh_ips.txt",'a')
        out.write(f"{ip} {username}:{password}")
        out.close()
    except:
        pass

    finally:
        if ssh:
            ssh.close()

executor = ThreadPoolExecutor(max_workers=5)
file = open("/home/thales/Desktop/WORKSPACE/CTAST/Updater/example_ips",'r')

def output():
    global scanned
    global file
    while True:
        replace_cmd_line('Scanned ' + str(scanned))

Thread(target=output).start()

for ip in file.readlines():
    ip = ip[:-1]
    with open("/home/thales/Desktop/WORKSPACE/CTAST/Updater/example_ips",'r') as passfile:
        for user_pass in passfile.readlines():
            user_pass = user_pass.split(':')
            user_pass[1] = user_pass[1][:-1]
            executor.submit(check_connection,ip,user_pass[0],user_pass[1])


text:
Q: Sending different Events via ZeroMQ using Flatbuffer Union I want to use flatbuffer to send events, which contain different data, over TCP (Using ZeroMQ). Therefore, I am using a Union.
// event.fbs
namespace event;

table ByteArray {
    bytes:[byte];
}

table OtherData {
    id:uint;
    value:uint;
}

union EventData {
    ByteArray,
    OtherData,
    String:string
}

table Event {
  name:string (key);
  timestamp:ulong = -1;
  data:EventData;
}

root_type Event;

In my C++-class I want to create new events and transfer them to my Publisher-class that sends out the events via ZeroMQ. Is there a nice or common way of doing this? I was thinking about something like this:
mPublisher.publishEvent(event::Event("event1", 0, "dataString"));
mPublisher.publishEvent(event::Event("event2", 1, byteArray));

The example above is not working because there is no such constructor. Is there a nice way of creating multiple events with different data? How am I supposed to pass these flatbuffer-events to another class like my publisher? Should I pass the flatbuffer or the event-offset?

A: You just need to use the actual constructors provided, so it will look something like:
event::CreateEvent(fbb, "event1", 0, fbb.CreateString("dataString"));

There is also an event::CreateByteArray etc. See the generated code, or the tutorial.
event::CreateEvent returns an offset into an unfinished FlatBuffer, so is generally not suitable for passing to non-FlatBuffer functions. You'll want to call fbb.Finish() on that offset, then pass the resulting buffer to other functions (again, see the tutorial).


text: Q: Compare and contrast ACTIVITY_INTENT_ACTION and BROADCAST_INTENT_ACTION At first I thought that ACTIVITY_INTENT_ACTION were meant for intents that are dispatched with startActivity and that BROADCAST_INTENT_ACTION for those dispatched with sendBroadcast, but then I saw that for example the intent whose action is ACTION_CREATE_SHORTCUT is dispatched with sendBroadcast even though the action is an ACTIVITY_INTENT_ACTION. So will someone please explain? I know this may be an advance question to ask, but there are a lot of android experts here. So thanks for any help.


text:
Q: Best way to do conditional access to a controller action method based on provided parameters? I have an application where each resource has multiple "sites". A user can have permission to access this resource for a number of these sites or none at all.
I have middleware set up that reads a user from a jwt and adds that user to the context. I then have an authorize attribute that simply checks for the existence of a user.
This is where I could use some help. I am not sure of the best way to conditionally restrict access to the resource (the condition being which site the end-user is specifically requesting the resource from).
I could break the resource into separate action methods and use an attribute that requires a specific role, but that feels a bit too much like duplication, I'd rather not deal with 7 endpoints that basically do the same thing, and adding new sites in the future will require adding a ton of new action methods.
Another solution I had in mind is to create an attribute/filter that compares the end-users permissions to the specific site that they are requesting. This sounds better but I'm not sure how to access specific arguments on the action method from the attribute. Also not sure of the best way to store all of a users "Roles" on an entity class...
Any insight is appreciated.


text:
Q: Can we generalise the statement, "any well-defined function with domain the integers is continuous" beyond just the integers? Let us use the following definition for continuity:
For a subset $A \subset \mathbb{R}$, $f : A \to \mathbb{R}$ is continuous if $\forall_{\epsilon > 0} \exists_{\delta >0} \forall_{x,y \in \mathbb{Z}}$,  $|x-y|< \delta \implies  |f(x) - f(y)| < \epsilon$.
The statement holds for $\mathbb{Z}$, the proof goes as follows:
we consider the function $g: \mathbb{Z} \to \mathbb{R}$: given any $\epsilon$, we can just let $\delta = \frac{1}{2}$ (any value in $(0,1)$ works). Then $|x-y|< \frac{1}{2} \implies x = y \implies |g(x) - g(y)| = |g(x) - g(x)| = 0 < \epsilon$, as required.
It is easy to see that this argument holds for any codomain set $B$ such that $h: \mathbb{Z} \to B$ is well-defined, since $h(x) - h(x) = 0$ for all $h(x) \in B$.
Hence $h$ is continuous.
I believe a similar argument also works for, say, the set $C(a) = \{a^n : n \in \mathbb{N}\}$ $\forall_{a \in \mathbb{R}\setminus\{0\}}$ (in this case, however, $\delta$ is not constant; it depends on $\epsilon$).
The common property of $\mathbb{Z}$ and $C(a)$ is that they are countable, so one may think that the argument holds for all countable sets, however this isn't the case. We cannot apply this argument to the rationals, $\mathbb{Q}$, since we cannot find a $\delta$ such that $|x-y|<\delta \implies x = y$ $\forall_{x,y \in \mathbb{Q}}$, as we could in the previous examples since given any $\delta$, there exists some $n \in \mathbb{N}$ such that $\frac{1}{10^n} < \delta$. Clearly, $\frac{1}{10^n} \in \mathbb{Q}$, so we can define $y = x + \frac{1}{10^n}$ and then $|x-y| = |x - (x + \frac{1}{10^n})| = \frac{1}{10^n} < \delta$ but $x \neq x + \frac{1}{10^n} = y$, at which points the previous argument falls apart.
So then what would be the generalisation of the statement? My intuition would be to think about functions containing only isolated points, but I am not sure. Thanks!

A: The correct generalization is to domains which are discrete, i.e. topological spaces $(X,T)$ with $T$ being the power set of $X$. This means they do indeed consist of isolated points.


text:
Q: Hello, I'm receiving an HTML code error regarding img -- Attribute img not allowed on element input at this point i'm getting this error when validating my HTML code in validatorw3.org. Can someone assist if they recognize this error. Much thanks.
<input type=image img id="magnifying-glass" src="images/magnifying-glass.png" alt="magnifying glass in search bar">↩

A: You need to delete the img attribute from your input.
It should be this:
<input type=image id="magnifying-glass" src="images/magnifying-glass.png" alt="magnifying glass in search bar">
Not this: <input type=image img id="magnifying-glass" src="images/magnifying-glass.png" alt="magnifying glass in search bar">


text:
Q: How to handle modal-dialog box in Protractor? I am trying to use sendKeys() on a modal-dialog box on this website. This dialog box appears after clicking Sign In button. I cannot seem to find any way to switch focus on the box. See the gist
I tried using browser.driver.switchTo().activeElement(); in
InvalidLogInUnSuccess: {
        get: function () {
            this.loginButton.click();
            browser.driver.switchTo().activeElement();
            this.email.sendKeys("Test");
        }
    }

with no luck and throws ElementNotVisibleError

Message:
       ElementNotVisibleError: element not visible
    (Session info: chrome=41.0.2272.101)
    (Driver info: chromedriver=2.14.313457 (3d645c400edf2e2c500566c9aa096063e707c9cf),platform=Windows NT 6.3 x86_64)
     Stacktrace:
       ElementNotVisibleError: element not visible

A: I've experienced a similar issue while testing an internal application when a popup was being opened with an animation effect (I think it is a culprit here) which had me think about waiting for an element inside the popup to become visible.
visibilityOf expected condition works for me in this case:
var email = element(by.css('.container.login.ng-scope #email'));
browser.wait(EC.visibilityOf(email), 5000);

email.sendKeys('test');

where EC is something I usually define globally in the onPrepare():
onPrepare: function () {
    ...

    global.EC = protractor.ExpectedConditions;
},

Just a side note, I think the locator could be improved here:

*

*ng-scope is not something I would rely on

*there is a model defined on the email field, how about:
element(by.model('email'));

FYI, the complete spec I've executed:
"use strict";

describe("gifteng test", function () {
    var scope = {};

    beforeEach(function () {
        browser.get("http://www.gifteng.com/?login");
        browser.waitForAngular();
    });

    describe("Logging in", function () {
        it("should send keys to email", function () {
            var email = element(by.css('.container.login.ng-scope #email'));
            browser.wait(EC.visibilityOf(email), 5000);

            email.sendKeys('test');
        });

    });
});

A: Protractor works with promises you should write :
  InvalidLogInUnSuccess: {
            get:  async() => {
                await this.loginButton.click();
                await browser.driver.switchTo().activeElement();
                await this.email.sendKeys("Test");

just apply Promises before protractor code. I removed function and write async. so i applied async/await.
reference: Link


text:
Q: Testing Smart contract requires in Truffle: transaction reverted if function isnt void im trying to test the requires of a Smart Contract using just solidity according to this article:
http://truffleframework.com/tutorials/testing-for-throws-in-solidity-tests
This is the contract, the throw proxy contract and the test:
/* Testing with solidity tests. */

import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/MyContract.sol";

contract TestMyContract {

function testInitialStoredValue() {
    MyContract mycontract = new MyContract();

    uint expected = 24;

    Assert.equal(mycontract.mynumber(), expected, "First number set should be 24.");
}

function testTheThrow() {
    MyContract mycontract = new MyContract();

    ThrowProxy throwproxy = new ThrowProxy(address(mycontract));
    uint num = 7;
    MyContract(address(throwproxy)).storeNum(num);

    bool r = throwproxy.execute.gas(200000)();

    Assert.isFalse(r, "Should be false because is should throw!");

}

function testNoThrow() {
    MyContract mycontract = new MyContract();

    ThrowProxy throwproxy = new ThrowProxy(address(mycontract));

    MyContract(address(throwproxy)).storeNum(22);

    bool r = throwproxy.execute.gas(200000)();

    Assert.isTrue(r, "Should be true because is should throw!");

}

}

// Proxy contract for testing throws
contract ThrowProxy {
  address public target;
  bytes data;

  function ThrowProxy(address _target) {
    target = _target;
  }

  //prime the data using the fallback function.
  function() {
    data = msg.data;
  }

  function execute() returns (bool) {
    return target.call(data);
  }
}

If i run the tests i get this error:

If i change the storeNum function to void from
 function storeNum(uint mynum)
        public
        returns (bool)
    {
     require(mynum > 10);
     mynumber = mynum;
     return true;
    }

to
 function storeNum(uint mynum)
        public
    {
     require(mynum > 10);
     mynumber = mynum;
     return true;
    }

the tests works..
Any ideas?
Im using Truffle v4.1.11

A: Let's look at your code:
function storeNum(uint mynum)
        public
        returns (bool success)
    {
     require(mynum > 10);
     mynumber = mynum;
     return true;
    }

By defining returns (bool success) you're saying to the solidity compiler two things:

*

*There is a variable named success of the type bool (variable definition)

*That variable success will be returned by the function (return definition)

But your variable isn't returned after all (your function ends with return true, and that's why you get an InvalidResponse error on your tests.
For your code, the most efficient code would be:
function storeNum(uint mynum)
        public
        returns (bool)    // you should define at least the type
    {
     require(mynum > 10);
     mynumber = mynum;
     return true;
    }

As an exercise, a version using the variable success:
function storeNum(uint mynum)
        public
        returns (bool success)
    {
     require(mynum > 10);
     mynumber = mynum;
     success = true;    // don't need to use return
    }

Hope it helps.

A: Well, i have submited an issue into Truffle github and it is still opened, maybe this is related to recent solidity changes:
https://github.com/trufflesuite/truffle/issues/1001
A workarround for now is to wrap the functions into void functions and test if the execution succeeds or not:
/*
    Contract wrapper that inherits from MyContract. This contract wraps the calls of non void functions when
    testing for exceptions.

    Why not invoke directly the function?: https://github.com/trufflesuite/truffle/issues/1001
*/

contract MyExposedContract is MyContract() {

    function callStoreNum(uint256 num)  public {
        storeNum(num);
    }

}

Then use that wrapper in your tests:
function testTheThrow() {
    MyExposedContract mycontract = new MyExposedContract ();

    ThrowProxy throwproxy = new ThrowProxy(address(mycontract));
    uint num = 7;
    MyExposedContract (address(throwproxy)).callStoreNum(num);

    bool r = throwproxy.execute.gas(200000)();

    Assert.isFalse(r, "Should be false because it should throw!");

}


text:
Q: Pandas, remove duplicates by column which duplicate N times Here an example:
df = pd.DataFrame({
    'file': ['file1','file1','file1','file1','file2','file3','file4','file4','file4','file4'],
    'text': ['Text1','Text2','Text3','Text4','Text5','Text6','Text7','Text8','Text9','Text10'],
})

I need to remove rows which 'file' repeat 4 time, so in this example i need to remove rows where file = file1 and file4

A: Use GroupBy.transform for get count of values per groups, so possible filter by boolean indexing:
df1 = df[df.groupby('file')['file'].transform('size') != 4]

Explanation: For using transform is necessary specify some column after groupby for counts - if use size it working same if use any column of DataFrame and it return new column (Series) with same size like original DataFrame filled by counts:
print (df.groupby('file')['file'].transform('size'))
0    4
1    4
2    4
3    4
4    1
5    1
6    4
7    4
8    4
9    4
Name: file, dtype: int64

Or use DataFrameGroupBy.filter - performance should be slowier if large data:
df1 = df.groupby('file').filter(lambda x: len(x) != 4)

Or Series.map with Series.value_counts:
df1 = df[df['file'].map(df['file'].value_counts()) != 4]

print (df)
    file   text
4  file2  Text5
5  file3  Text6

A: Using GroupBy with transform:
df[df.groupby('file').text.transform('size').ne(4)]

   file   text
4  file2  Text5
5  file3  Text6


text:
Q: Font issue in reactjs Inside react public folder, I have style.css and index.html. Inside style.css I have written
*{
   font-family: 'Roboto', sans-serif
}

This means Roboto font is applied to all the components. I have imported Roboto font link from google in index.html.
Now in App.js, I have the following routes
<Router>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/login" component={Login} />
        <Route path="/register" component={Register} />
        <Route path="/profile" component={Profile} />
      </Switch>
    </Router>

Now, for any component, when I give pathname as forward-slash / and pathname, such as /profile, then it works perfectly, the component gets rendered and Roboto font also work but, if I give pathname as forward-slash / and pathname, such as /profile and again after that, if I add user id or username param like /profile/:username, then Roboto font does not get affected rather, it displays default font but, if I again remove :username param from /profile/:username and make it /profile then Roboto font works again. So what's the issue here. Why font is not working in that component after adding / and any pathname or params in that route.

A: First of all, move the css file to your /src directory(e.g. /src/css/styles.css), and in the file where everything gets wrapped inside of the router import the css file by:
import "./css/styles.css"
(assuming the js file is directory located in the /src directory without any nesting)


text:
Q: IP2Location + Netmiko to SSH to VM's to MTR and print results (If, elif, else statements issues) PYTHON3 Im new on asking a question, always reading answers to improve my codes but never asked, so this is my first time here.
Im trying to make a simple scenario implementing some network automation.
Scenario:
I Have 3 VM's (1st is in Argentina, 2nd is in Brazil, 3rd is in Miami)
Need to connect to this machines through SSH to perform an MTR test over the recently filled IP address in the IP2Location module.
The thing is that i need to perform this test through the most near point of the IP.
Example: If i have a Chile IP Address i need to make this test over the VM in Argentina, if the IP is from Mexico i need to tests it through my VM in Miami, etc.
For this to work i use IP2Location (I simply modified the base code to fill the IP manually)
After the IP is placed, IP2Location prints the Country full name.
Once i have the country full name i use the (if, elif, else) statements to connect to the different VM's i have with Netmiko, perform the tests and print the results.
But, this is not working as i expected, it always goes to the "else" statement overlooking the IF and ELIF.
Here's the Code:
import IP2Location
from netmiko import ConnectHandler
from datetime import datetime
import subprocess

IP2LocObj = IP2Location.IP2Location();
IP2LocObj.open("/Volumes/DATA/nico/Desktop/ServDeg/IP2LOCATION-LITE-DB1.BIN"); #Path to the Database BIN
rec = IP2LocObj.get_all((str(input("IP: "))));
print(rec.country_long)

if rec.country_long is 'Brazil':
    net_connect = ConnectHandler(device_type='linux', ip='xxx.xxx.xxx.xxx', username='xxx', password='xxx')
    output = net_connect.send_command('mtr ' + IP2LocObj + ' -c 10')
    print(output)
elif rec.country_long is 'Argentina':
    net_connect = ConnectHandler(device_type='linux', ip='xxx.xxx.xxx.xxx', username='xxx', password='xxx')
    output = net_connect.send_command('mtr ' + IP2LocObj + ' -c 10')
    print(output)
elif rec.country_long is 'Chile':
    net_connect = ConnectHandler(device_type='linux', ip='xxx.xxx.xxx.xxx', username='xxx', password='xxx')
    output = net_connect.send_command('mtr ' + IP2LocObj + ' -c 10')
    print(output)
elif rec.country_long is 'Uruguay':
    net_connect = ConnectHandler(device_type='linux', ip='xxx.xxx.xxx.xxx', username='xxx', password='xxx')
    output = net_connect.send_command('mtr ' + IP2LocObj + ' -c 10')
    print(output)
else:
    net_connect = ConnectHandler(device_type='linux', ip='xxx.xxx.xxx.xxx', username='xxx', password='xxx')
    output = net_connect.send_command('mtr ' + IP2LocObj + ' -c 10')
    print(output)

You can download the bin file for IP2location DB from here https://www.ip2location.com/developers/python
(i don't show the IP's because these are Public and everyone can enter) but this can be simply emulated on GNS3.
Thanks and Regards!!!

A: So here's the solution:
#Serv_deg_without_Demark_device by NMorra
from netmiko import ConnectHandler
from datetime import datetime
import IP2Location

start_time = datetime.now()
IP2LocObj = IP2Location.IP2Location() #Modulo IP-GEOLOCATION
IP2LocObj.open("/Volumes/DATA/nico/Desktop/ServDeg/IP2LOCATION-LITE-DB1.BIN");
#Bin Location
country = IP2LocObj.get_all(ipaddr) # ('mtr ' + str(var) + ' -c 10')
print("", ipaddr) #
country.country_long = str(country.country_long)[2:-1]

print(country.country_long)
print('Test in progress...')

if country.country_long == ('Argentina'):
    net_connect = ConnectHandler(device_type='linux', ip='xxx.xxx.xxx.xxx',
    username='xxx', password='xxx')
mtr = net_connect.send_command('mtr ' + str(ipaddr) + ' -c 10 -r')
net_connect.disconnect()
elif country.country_long == ('Chile'):
    net_connect = ConnectHandler(device_type='linux', ip='xxx.xxx.xxx.xxx',
    username='xxx', password='xxx')
    mtr = net_connect.send_command('mtr ' + str(ipaddr) + ' -c 10 -r')
    net_connect.disconnect()
elif country.country_long == ('Uruguay'):
    net_connect = ConnectHandler(device_type='linux', ip='xxx.xxx.xxx.xxx',
    username='xxx', password='xxx')
mtr = net_connect.send_command('mtr ' + str(ipaddr) + ' -c 10 -r')
net_connect.disconnect()
elif country.country_long == ('Brazil'):
    net_connect = ConnectHandler(device_type='linux', ip='xxx.xxx.xxx.xxx',
    username='xxx', password='xxx')
mtr = net_connect.send_command('mtr ' + str(ipaddr) + ' -c 10 -r')
net_connect.disconnect()
else:
    net_connect = ConnectHandler(device_type='linux', ip='xxx.xxx.xxx.xxx',
    username='xxx', password='xxx')
    mtr = net_connect.send_command('mtr ' + str(ipaddr) + ' -c 10 -r')
    net_connect.disconnect()

print('')
print('>'*10, 'MTR', '<'*10)
print(mtr)
end_time = datetime.now()
time = end_time-start_time
print('_'*5)
print('Time: ', time)


text:
Q: How to do Aadhar Authentication and fetch KYC details using API We are developing a mobile app for our health care client. To keep the patient signup/registration process quick we will use Aadhar APIs. So that patient will enter his/her Aadhar number after that will receive OTP and submit it to Aadhar authentication API and once authentication is successful we will fetch demographic details of a patient like a Name, Address, DOB, etc. using KYC API.
I have already gone through the
AADHAR OTP Request API - https://uidai.gov.in/images/resource/aadhaar_otp_request_api_2_5.pdf
AADHAR Auth API -
https://uidai.gov.in/images/resource/aadhaar_authentication_api_2_5.pdf
Aadhaar e-KYC API -
http://uidai.gov.in/images/resource/aadhaar_ekyc_api_2_5.pdf
But these official documents only explain the endpoints, communication protocol, and request/response formats. It does not offers clear help for the software developers in order to use and integrate it into the website/mobile app.
Is there any other way via which we can do the customer onboarding process quickly and smoothly?
Any hints or help will be appreciated.
Thanks,
Mahendra


text:
Q: Use Fourier Transform result to solve an integral I have a problem that says: find the Fourier Transform by definition of the function $f(t)$, being
$$ f(t)= e^{-2 \vert t\vert } $$
Then, use this result to solve
$$  \int_{-\infty} ^{-\infty} \frac{1}{(x^2+2^2)^2}dx $$
I found that
$$\mathscr{F}\{f(t)\}= \frac{2^2}{2^2+w^2}$$
But now I don't know how to relate this result with the integral

A: $$\mathscr{F}\{e^{-2|t|}\}= \frac{4}{w^2+4}$$
$$\mathscr{F}\left\{\dfrac {e^{-2|t|}}4 \right\}= \frac{1}{w^2+4}$$
Now by Plancherel's theorem you have
$$\int_{-\infty}^\infty\hat f^2 (\xi)d\xi=2\pi\int_{-\infty}^\infty\ f^2 (t)dt $$
$$\int_{-\infty}^\infty\frac{1}{(\xi^2+4)^2}d\xi=\frac {\pi}8\int_{-\infty}^\infty\ e^{-4|t|}dt $$
You need to evaluate this integral:
$$
I=\frac {\pi}8\int_{-\infty}^\infty e^{-4|t|}dt $$
$$I=\frac {\pi}8\left (\int_{0}^\infty e^{-4t}dt +\int_{-\infty}^0\ e^{4t}dt \right )   $$
$$I=\frac {\pi}8\left (\left | \dfrac {e^{-4t}}{-4} \right |_{0}^\infty+ \left |\dfrac {e^{4t}}{4} \right |_{-\infty}^0 \right ) $$
$$
I=\frac {\pi}8\left ( \dfrac 14+\dfrac 14 \right ) =\frac {\pi} {16}$$
Therefore:
$$\int_{-\infty} ^{\infty} \frac{dx}{(x^2+4)^2}=\frac {\pi} {16}$$
As you see the integral dosen't diverge.


text:
Q: Send Outlook MailItem even when Outlook is Closed I have a .NET application which allows users to click a button that will launch a new pre-populated message in Outlook.  This works great for the most part, with one minor exception.  If the user does not have Outlook open when they send the message, then the message will go into their Outbox until they actually launch the main Outlook application.  Only then does a Send/Receive ever seem to actually happen.
Here is the snippet of code I am using to create the MailItem:
Dim mailItem As Outlook.MailItem = Me.OutlookApplication.CreateItem(Outlook.OlItemType.olMailItem)
mailItem.To = "test@test.com"
mailItem.Subject = "Some Subject"
mailItem.HTMLBody = "Some Text"
mailItem.Display(False)

I hook into the ItemSend event for the Outlook.Application as well, so I am able to see that when the user clicks Send from the MailItem, Outlook successfully raises the event.
If Outlook is not running when the user launches the message, then a new OUTLOOK.EXE process is spawned.  In either case, an icon will appear in the system tray signifying that Outlook is connected to an external application.
Is it possible for me to somehow trigger a Send/Receive using Interop, so I can ensure that the message will be sent without requiring the user to open Outlook separately?

A: Try to use Namespace.SendAndReceive
Keep in mind that message submission is asynchronous, so you need to keep Outlook.Application alive until Send/Receive finishes.


text:
Q: GET 404 error for css and js files I am trying to use an HTML5 template with my code using node.js for my home page, but I keep getting a GET 404 Not Found error for: main.css, jquery.min.js, skel.min.js, and main.js. I checked my directory, and everything seems to be in the right place. Below is a snapshot of it:

And here is the HTML where I linked my css and js files in the index.html:
<head>
  <link rel="stylesheet" href="assets/css/main.css" />
</head>

<body>
   <script src="assets/js/jquery.min.js"></script>
    <script src="assets/js/skel.min.js"></script>
    <!--[if lte IE 8]><script src="assets/js/ie/respond.min.js"></script><![endif]-->
    <script src="assets/js/main.js"></script>
</body>

Does anyone know why I keep getting this error and what I can do to fix it? Thanks in advance.

A: Try adding a beginning slash to your src and href attributes.

A: Make sure you've specified your static asset directory. (http://www.tutorialsteacher.com/nodejs/serving-static-files-in-nodejs)
Aside from that:
Try setting your script paths to include the precursory slash:
<script src="/assets/js/jquery.min.js"></script>
<script src="/assets/js/skel.min.js"></script>
<!--[if lte IE 8]><script src="/assets/js/ie/respond.min.js"></script><![endif]-->
<script src="/assets/js/main.js"></script>

If that isn't working, and you're running Adblock in your browser, try disabling it.
Check to see if you're able to see the files if you paste the address into the browser?


text:
Q: Truncation error of an integration method I read that the local truncation error of a method of order $p$ is $O(h^{p+1})$ (thus, one order higher). Yet, the global truncation error is in general $O(h^p)$ for a stable method (thus, one order lower than the local error). But why?
If the global truncation error is the accumulation of local truncation error at all steps $h$, shouldn't it be still order $p+1$?

A: For a fixed interval of integration, the number of steps is $O(h^{-1})$. The global error is the local error times the number of steps. So if $e_i$ is the error at step $i$, and $E$ is the global error, and we're integrating over an interval of length $L$, informally we have:
$$
e_i = O(h^{p+1}) \Leftrightarrow |e_i| \le Ch^{p+1}
$$
$$
|E| = \left| \sum_{i=1}^{\lfloor L/h \rfloor}e_i \right| \le \sum_{i=1}^{\lfloor L/h \rfloor}Ch^{p+1} \le CLh^p \Leftrightarrow E = O(h^p)
$$


text:
Q: How to build for all platform using vue-cli-plugin-electron-builder Is possible to make multiple platform build using vue-cli-plugin-electron-builder? Anyone have experience with it? What will be the correct plugin configuration if this is possible?
Thanks