text:
Q: Operand should contain 1 column in express mysql query Am curretly facing the following error when i try to query using express
  code: 'ER_OPERAND_COLUMNS',
  errno: 1241,
  sqlMessage: 'Operand should contain 1 column(s)',
  sqlState: '21000',
  index: 0,
  sql: "insert into quiz(user_pk,question,answer,choices,discussion) values (1, 'what is math', 'study of calculations', ('study of calculations', 'study of computing', 'study of books'), 'its amaizing')"
}

routes
.post((req, res) => {
        query =
            "insert into quiz(user_pk,question,answer,choices,discussion) values ?";
        values = [Object.values(req.body)];
        console.log(values)
        connection.query(
            query,
            [values],
            (err, result) => {
                if (err) throw err;
                res.json({ message: "question sussefully created" });
            }
        );
    });

data i want to insert
{
    "user_pk":1,
    "question":"what is math",
    "answer":"study of calculations",
    "choices":["study of calculations","study of computing","study of books"],
    "discussion":"its amaizing"
}

example of query i want to perform
insert into quiz(user_pk,question,answer,choices,discussion)
values(1,'what is physics?','study of matter','["study of matter","study of dances","study of matter"]','lorem ipsum dolor lorem');

here is the quiz table
CREATE TABLE if NOT EXISTS quiz(
    quiz_pk INT NOT NULL AUTO_INCREMENT,
    user_pk INT NOT NULL,
    question VARCHAR(255) NOT NULL,
    answer VARCHAR(255) NOT NULL,
    choices JSON NOT NULL,
    discussion VARCHAR(255) NOT NULL,
    PRIMARY KEY (quiz_pk),
    FOREIGN KEY (user_pk) REFERENCES user(user_pk)
);

please help me out.Thanks alot


text:
Q: Selenium/TestNG: How to run a part of code only once with DataProvider Is there a way I can use Data Provider for only part of the code but not for the entire class?
For example, if I want to do
1. Function A - Login
2. Function B - X (with 5 rows in the data sheet excel and I'd like this function to repeat for 5 times)
How do I run login only once? I tried the following but funcA (login) still runs for multiple times.
class X{
  funcA (@Test)
  funcB (@Test(dataProvider))
}

A: If there is only one test method in your class X use @BeforeClass annotation on funcA since it executes before the first test method in the current class (in this case that would be funcB test method).
For more info about @BeforeClass and other before annotations you can check out this site.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Without error: Black fragment in asymptote graphic I've just copied some asymptote example code to test the compiling. This is my result:
Screenshot

MWE
\documentclass{standalone}

\usepackage[inline]{asymptote}

\begin{document}
\begin{asy}
import three;

currentprojection=orthographic(5,4,2,center=true);

size(5cm);
size3(3cm,5cm,8cm);

draw(unitbox);

dot(unitbox,red);

label("$O$",(0,0,0),NW);
label("(1,0,0)",(1,0,0),S);
label("(0,1,0)",(0,1,0),E);
label("(0,0,1)",(0,0,1),Z);
\end{asy}
\end{document}

What I did

*

*pdflatex cube.tex

*asy cube-1.asy

*pdflatex cube.tex
and I also tested it without LaTeX, but with the same result

*

*asy cube.asy
There was no error or anything else. Does someone has an idea how to get things to work?

A: Schrödinger's cat mentioned this post where O.G. uses the maxtile trick to solve the graphic card issue. I tested it and it works:
settings.outformat="pdf";
settings.prc = false;
settings.render = 0;

import three;

currentprojection=orthographic(5,4,2,center=true);

size(5cm);
size3(3cm,5cm,8cm);

draw(unitbox);

dot(unitbox,red);

label("$O$",(0,0,0),NW);
label("(1,0,0)",(1,0,0),S);
label("(0,1,0)",(0,1,0),E);
label("(0,0,1)",(0,0,1),Z);

...compiling this with asy -maxtile "(256,256)" cube.asy results in:


text:
Q: Ionic Cordova CLI failures on build ios command - "Module not found, can't resolve..." I am trying to run ionic cordova build ios and am consistently met with the following:
Error: ./src/app/app.module.ts
Module not found: Error: Can't resolve '@ionic-native/file' in '/Users/justinfrevert/Desktop/AceAdz-App/app-copy/src/app'
resolve '@ionic-native/file' in '/Users/justinfrevert/Desktop/AceAdz-App/app-copy/src/app'
  Parsed request is a module
  using description file: /Users/justinfrevert/Desktop/AceAdz-App/app-copy/package.json (relative path: ./src/app)
    Field 'browser' doesn't contain a valid alias configuration
  after using description file: /Users/justinfrevert/Desktop/AceAdz-App/app-copy/package.json (relative path: ./src/app)
    resolve as module
      looking for modules in /Users/justinfrevert/Desktop/AceAdz-App/app-copy/node_modules
        using description file: /Users/justinfrevert/Desktop/AceAdz-App/app-copy/package.json (relative path: ./node_modules)
          Field 'browser' doesn't contain a valid alias configuration
        after using description file: /Users/justinfrevert/Desktop/AceAdz-App/app-copy/package.json (relative path: ./node_modules)
          using description file: /Users/justinfrevert/Desktop/AceAdz-App/app-copy/package.json (relative path: ./node_modules/@ionic-native/file)
            no extension
              Field 'browser' doesn't contain a valid alias configuration
              /Users/justinfrevert/Desktop/AceAdz-App/app-copy/node_modules/@ionic-native/file doesn't exist
            .ts
              Field 'browser' doesn't contain a valid alias configuration
              /Users/justinfrevert/Desktop/AceAdz-App/app-copy/node_modules/@ionic-native/file.ts doesn't exist
            .js
              Field 'browser' doesn't contain a valid alias configuration
              /Users/justinfrevert/Desktop/AceAdz-App/app-copy/node_modules/@ionic-native/file.js doesn't exist
            .json
              Field 'browser' doesn't contain a valid alias configuration
              /Users/justinfrevert/Desktop/AceAdz-App/app-copy/node_modules/@ionic-native/file.json doesn't exist
            as directory
              /Users/justinfrevert/Desktop/AceAdz-App/app-copy/node_modules/@ionic-native/file doesn't exist
[/Users/justinfrevert/Desktop/AceAdz-App/app-copy/node_modules/@ionic-native/file]
[/Users/justinfrevert/Desktop/AceAdz-App/app-copy/node_modules/@ionic-native/file.ts]
[/Users/justinfrevert/Desktop/AceAdz-App/app-copy/node_modules/@ionic-native/file.js]
[/Users/justinfrevert/Desktop/AceAdz-App/app-copy/node_modules/@ionic-native/file.json]
[/Users/justinfrevert/Desktop/AceAdz-App/app-copy/node_modules/@ionic-native/file]
 @ ./src/app/app.module.ts 23:0-42
 @ ./src/app/main.ts,./src/app/app.module.ts
Module not found: Error: Can't resolve '@ionic-native/photo-library' in '/Users/justinfrevert/Desktop/AceAdz-App/app-copy/src/app'
resolve '@ionic-native/photo-library' in '/Users/justinfrevert/Desktop/AceAdz-App/app-copy/src/app'
  Parsed request is a module
  using description file: /Users/justinfrevert/Desktop/AceAdz-App/app-copy/package.json (relative path: ./src/app)
    Field 'browser' doesn't contain a valid alias configuration
  after using description file: /Users/justinfrevert/Desktop/AceAdz-App/app-copy/package.json (relative path: ./src/app)
    resolve as module
      looking for modules in /Users/justinfrevert/Desktop/AceAdz-App/app-copy/node_modules
        using description file: /Users/justinfrevert/Desktop/AceAdz-App/app-copy/package.json (relative path: ./node_modules)
          Field 'browser' doesn't contain a valid alias configuration
        after using description file: /Users/justinfrevert/Desktop/AceAdz-App/app-copy/package.json (relative path: ./node_modules)
          using description file: /Users/justinfrevert/Desktop/AceAdz-App/app-copy/package.json (relative path: ./node_modules/@ionic-native/photo-library)
            no extension
              Field 'browser' doesn't contain a valid alias configuration
              /Users/justinfrevert/Desktop/AceAdz-App/app-copy/node_modules/@ionic-native/photo-library doesn't exist
            .ts
              Field 'browser' doesn't contain a valid alias configuration
              /Users/justinfrevert/Desktop/AceAdz-App/app-copy/node_modules/@ionic-native/photo-library.ts doesn't exist
            .js
              Field 'browser' doesn't contain a valid alias configuration
              /Users/justinfrevert/Desktop/AceAdz-App/app-copy/node_modules/@ionic-native/photo-library.js doesn't exist
            .json
              Field 'browser' doesn't contain a valid alias configuration
              /Users/justinfrevert/Desktop/AceAdz-App/app-copy/node_modules/@ionic-native/photo-library.json doesn't exist
            as directory
              /Users/justinfrevert/Desktop/AceAdz-App/app-copy/node_modules/@ionic-native/photo-library doesn't exist
[/Users/justinfrevert/Desktop/AceAdz-App/app-copy/node_modules/@ionic-native/photo-library]
[/Users/justinfrevert/Desktop/AceAdz-App/app-copy/node_modules/@ionic-native/photo-library.ts]
[/Users/justinfrevert/Desktop/AceAdz-App/app-copy/node_modules/@ionic-native/photo-library.js]
[/Users/justinfrevert/Desktop/AceAdz-App/app-copy/node_modules/@ionic-native/photo-library.json]
[/Users/justinfrevert/Desktop/AceAdz-App/app-copy/node_modules/@ionic-native/photo-library]
 @ ./src/app/app.module.ts 28:0-59
 @ ./src/app/main.ts
    at new BuildError (/Users/justinfrevert/Desktop/AceAdz-App/app-copy/node_modules/@ionic/app-scripts/dist/util/errors.js:16:28)
    at callback (/Users/justinfrevert/Desktop/AceAdz-App/app-copy/node_modules/@ionic/app-scripts/dist/webpack.js:121:28)
    at emitRecords.err (/Users/justinfrevert/Desktop/AceAdz-App/app-copy/node_modules/webpack/lib/Compiler.js:269:13)
    at Compiler.emitRecords (/Users/justinfrevert/Desktop/AceAdz-App/app-copy/node_modules/webpack/lib/Compiler.js:375:38)
    at emitAssets.err (/Users/justinfrevert/Desktop/AceAdz-App/app-copy/node_modules/webpack/lib/Compiler.js:262:10)
    at applyPluginsAsyncSeries1.err (/Users/justinfrevert/Desktop/AceAdz-App/app-copy/node_modules/webpack/lib/Compiler.js:368:12)
    at next (/Users/justinfrevert/Desktop/AceAdz-App/app-copy/node_modules/tapable/lib/Tapable.js:218:11)
    at Compiler.compiler.plugin (/Users/justinfrevert/Desktop/AceAdz-App/app-copy/node_modules/webpack/lib/performance/SizeLimitsPlugin.js:99:4)
    at Compiler.applyPluginsAsyncSeries1 (/Users/justinfrevert/Desktop/AceAdz-App/app-copy/node_modules/tapable/lib/Tapable.js:222:13)
    at Compiler.afterEmit (/Users/justinfrevert/Desktop/AceAdz-App/app-copy/node_modules/webpack/lib/Compiler.js:365:9)

This did not occur after a code change. This started occurring after a separate error that I was trying to correct: the compiler complaining about improper types being passed into the watchPosition() method from ionic native geolocation. That was a separate issue also caused by version changes - so I tried to revert the version back from the latest to 3.14.0. that was what gave the above mentioned error. I then reverted to 3.11.0, because that was the original version I had it on when it was working. I tried to build, and it still did not work. I then switched back to the latest version, but still got the above error. I tried uninstalling and reinstalling the cordova and npm packages for geolocation, still no dice. Please let me know what I might be able to do to fix this.

A: Now you have latest version so make sure you have all the latest cordova and npm packages installed. After this please remove the ios platform and than again add this.Also, make sure that there are engine entries in your config.xml for all your platforms of interest. This guarantees that your are using the exact platform tool versions that you're using locally. I think instances where the platform tool versions specified in the config.xml are incompatible with the project and needed to be either upgraded or downgraded.


text:
Q: Solve $2p+6=n^3$ How can I prove that if $p$ is a prime, there is an unique solution for the equation
$$2p+6=n^3$$
where $n$ is an integer?
I know that $p=29$ is the solution, but I don't know how to demonstrate that is the only one. Anyone can help me?

A: Motivated by Arentino's observation, here are some other solutions as provided by Mathematica 10 (all solutions for $n\le 1000$). They are listed in the form $\{n,p\}$.
Here's the code:
Do[If[PrimeQ[(n^3 - 6)/2], Print[{n, (n^3 - 6)/2}]], {n, 2 Range[500]}]

{4,29}
{28,10973}
{32,16381}
{44,42589}
{50,62497}
{58,97553}
{98,470593}
{128,1048573}
{148,1620893}
{154,1826129}
{172,2544221}
{182,3014281}
{224,5619709}
{242,7086241}
{254,8193529}
{268,9624413}
{274,10285409}
{280,10975997}
{302,13771801}
{322,16693121}
{358,22941353}
{394,30581489}
{428,39201373}
{442,43175441}
{452,46172701}
{508,65548253}
{518,69495913}
{568,91625213}
{574,94559609}
{592,103737341}
{604,110174429}
{610,113490497}
{620,119163997}
{694,167127689}
{722,188183521}
{728,192914173}
{730,194508497}
{760,219487997}
{764,222971869}
{784,240945149}
{788,244651933}
{802,257924801}
{812,267693661}
{814,269676569}
{830,285893497}
{938,412646833}
{994,491053889}

A: It is not the only solution: $10973$ is prime and $2\cdot10973+6=28^3$.


text:
Q: Setting debug_mode with Measurement Protocol (GA4) Can't find a way to set the debug_mode parameter using Measurement Protocol 4.
Tried to put it everywhere (and naming it all i can think of) but without luck :)
Documentation is still very light and doesn't mention the debug_mode.
With web/js and GA4 it works fine!

A: Weird. Suddenly the debug mode started to work with code I'm 100% sure didn't work before.
Adding the parameter "debug_mode": true to the measurement protocol request will make it show up in Analytics' DebugView.
Sample json payload that works:
{
  "client_id": "XXXXXXXXXX.YYYYYYYYYY",
  "events": [
    {
      "name": "page_view",
      "params": {
        "page_location": "...",
        "page_path": "...",
        "page_title": "...",
        "debug_mode": true
      }
    }
  ]
}

A: To add to the answers of @DalmTo and @bang - I wasn't seeing events I was sending over the Measurement Protocol show up in our GA4 Debug View. The root cause in my case was that the Measurement Protocol expects a funky format for the user_properties, but the following steps should help others debug other problems as well.
Steps I took to resolve:

*

*Add the debug_mode: true field to individual event params as described in @bang's answer

*Use the /debug/mp endpoint as described in @DalmTo's answer - this pointed me towards the errors in my user_properties format

Regarding the user_properties field, I was sending something along these lines:
{
  "client_id": "XXX.XXX",
  "user_id": "YYY",
  "user_properties": {
    "property_a": "value_a",
    "property_b": "value_b"
  },
  "events": ...
}

Turns out GA4 / Measurement Protocol expect something like this:
{
  "client_id": "XXX.XXX",
  "user_id": "YYY",
  "user_properties": {
    "property_a": { "value": "value_a" },
    "property_b": { "value": "value_b" }
  },
  "events": ...
}

At the time of writing, the only way to figure this out is to carefully check out the example here.

A: The measurment protocol for ga4 has two endpoints just like the measurment protocol for the old Google anlaytics

*

*Measurement Protocol  /mp/collect

*Measurement Protocol Validation Server    /debug/mp/collect

So if you send a event to it will be sent to Google anlaytics ga4
POST /mp/collect HTTP/1.1
HOST: www.google-analytics.com

<payload_data>

So if you send a event to it will be sent to debug endpoint for Google anlaytics ga4
POST /debug/mp/collect HTTP/1.1
HOST: www.google-analytics.com

<payload_data>


text:
Q: How can I easily switch between environment specific runtime configuration with IntelliJ? In most Java projects (Maven, Spring) I work on, I have the following requirements:

*

*The packaged jar needs to run in multiple environments e.g. dev, beta, prod

*The jar must not be rebuilt for each environment

*Each environment requires different configuration properties

*In development, I need to be able to easily switch between different environments in order to ensure that each environment is configured correctly, before deployment

So far, I have accomplished this by putting all configuration properties into separate properties files, one per environment. I then have Spring load in these files from the classpath. Then I simply alter the classpath at runtime to load in the needed properties.
This approach has worked well when I was using Eclipse since it is easy to setup multiple run configurations and alter the classpath for each one. Once this is done, switching environments is a matter of choosing the relevant run configuration.
Unfortunately, this is much harder to accomplish in IntelliJ because runtime dependencies can only be added to a module's configuration (as documented in this answer). If I try to set the classpath in the run configuration itself then this overrides all of modules dependencies, preventing the application from running at all (as documented here). Therefore, to switch environment, I must re-edit the modules dependencies every time.
Is there an easier way of achieving this with IntelliJ?
If not, is that because my configuration requirements, or my solutions to them, are unusual? In which case, is there a better way?
Previous Approaches
I have already tried and rejected a number of approaches:

*

*Maven Profiles - These require rebuilding my jar whenever I want to switch environment. Apart from being annoying and dangerous, this seems entirely inappropriate for runtime configuration (but ideal for buildtime configuration). This seems like a great way to risk getting a broken build into production as you aren't testing against the same jar that actually gets deployed. Yuck!

*Spring Profiles - These look much more appropriate but appear to require all configuration to be deployed with the jar and distinguished by filename e.g. dev.properties, prod.properties. You can then select which one you want by passing a variable at runtime. This is much better but I don't want my prod.properties to find their way into version control, nor get deployed with the jar itself. Therefore, it still seems necessary to modify the classpath in order to include them which I can't easily do in IntelliJ

A: When I ran in similar problems, I started loading my properties with a helper class. The helper class will look for a System property that contains either the environment or the absolute/classpath-relative path to load the properties from.
That way, the code is always the same and I don't have to change the project's configuration. I just use different launch configs that set different properties.
The main drawback here of course that test / dev configs leak into prod. With Maven, the simple solution is to move those into a new module and set the scope for it to provided. That way, the module will be visible inside of Maven but it won't be included during WAR packaging, etc.

A: I do something similar to what @AaronDigulla does but I overlay the properties. That is I first load all the properties from property files in the classpath (using Spring). Then I search for specific variable name and value (in the following order):

*

*in servlet init parameters

*then in system properties

*finally then environment variables

This variable name and value contains the path of property files that will override/overlay the properties loaded from the classpath. Also each property loaded will perform the same type of resolution (that is system properties, environment variables and servlet init parameters override the properties from the property file).
Now all developers are pushed to use the default configuration that is in the classpath (ie use the same username/password for their database). Those that have different settings can use the above 3 different ways to override.
You can use the same bootstrapping configuration code that I use which will load all property files in classpath*:META-INF/spring/*.properties first then it will load all property files with the file/classpath URL set in the property/environment/init parameter variable called MyConfigParameter (if set).
Then finally after the property files are loaded it will set the Spring profiles by pulling the property/environment/init parameter called MyConfig.profiles (comma separated).
So in production you might set the environment variable MyConfigParameter=file://etc/myapp/*.properties.
Then in one of those property files you might set MyConfig.profiles=production,postgres which will set the Spring profile production and postgres.
Your Maven profiles for releasing/building on your build machine can obviously adjust the  MyConfigParameter in the environment using System Properties. However you will have to tell surefire unit testing specifically about this property (especially if forking):
        <!-- Surefire setup -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.9</version>
            <configuration>
                <printSummary>false</printSummary>
                <redirectTestOutputToFile>true</redirectTestOutputToFile>
                <systemPropertyVariables>
                    <MyConfigParameter>${MyConfigParameter}</MyConfigParameter>
                </systemPropertyVariables>
            </configuration>
        </plugin>

<!-- Profile to change MyConfigParameter -->

<profiles>
    <profile>
        <id>release</id>
        <activation>
            <property>
                <name>env</name>
                <value>release</value>
            </property>
        </activation>
        <properties>
            <MyConfigParameter>file://etc/MyApp/*.properties</MyConfigParameter>
        </properties>
    </profile>
</profiles>


text:
Q: I am having "Request Entity Too Large error" with react-app on heroku? I have deployed my react-app on heroku, and I know create-react-app-buildpack just allow 1mb file transfer. I have created a static.json in root directory:
{
  "max_body_size": "50m",
  "root": "build/",
  "https_only": true,
  "routes": {
    "/**": "index.html"
  }
}

Still, I have problem posting images larger than 1 MB! Please help if anyone has a solution?


text:
Q: Iterating through comparison of dates in Python Pandas Right now I am iterating over a pandas dataframe to patch data inconsistencies with datetime columns, but the runtime is brutal.
def fix(row):
        return row.datetime_column2 if row.datetime_column1 > row.datetime_column2 else row.datetime_column1

df['datetime_column1'] = df.apply(fix, axis = 1)

Is there a smarter way to do this?

A: IIUC you can use this vectorized approach:
df['datetime_column1'] =  \
    np.where(df['datetime_column1'] > df['datetime_column2'],
             df['datetime_column2'],
             df['datetime_column1'])

or:
df['datetime_column1'] = df[['datetime_column1','datetime_column2']].min(1)

A: If possible with pandas/numpy, don't use for loops as you do with (axis=1).  Try the following. Should work for dates too.
df=pd.DataFrame(data={'column_1':[1,3,5,5],'column_2':[0,4,1,6] })
df.loc[df.column_1>df.column_2, 'column_1'] = df.column_2


text:
Q: Privacy Statement Windows 8 Charm Settings My Windows Store App certification failed and the note given to me by the tester is that:

"The app has declared access to network capabilities and no privacy
  statement was provided in the Windows Settings Charm".

Can Somebody give me the exact code to solve this problem.

A: it looks like you have not included a privacy policy with your application. This is a requirement in the windows store Check this link out for more information.

A: In your base page, (or individual page if you want it only on one), you can define the settings like this:
SettingsPane.GetForCurrentView().CommandsRequested += SettingsCommandsRequested;

private void SettingsCommandsRequested(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args)
{
    //use "new Guid()" instead of string "privacy" if you're experiencing an exception
    var privacyStatement = new SettingsCommand("privacy", "Privacy Statement",
            async x => await Launcher.LaunchUriAsync(new Uri("http://some-url.com")));

    args.Request.ApplicationCommands.Clear();
    args.Request.ApplicationCommands.Add(privacyStatement);
}

Obviously in this example, we had the privacy policy link to an external page, however you can modify the code to open up a separate page within the app if you want.


text:
Q: Proving: $\lim _{x \rightarrow \infty} \ f(x)=\lim_{t \rightarrow 0^+} \ f(1/t)$ Please advise: is my proof sufficient? or do I need to use $\epsilon$?
Prove that $$
\lim_{x \to \infty} \ f(x)=
\lim_{t \to 0^+} \ f(1/t)$$ if these limits exist
Proof: putting $t=\dfrac{1}{x}$ then as $x\to\infty, \ t\to0^+$ and $x=\dfrac{1}{t}$
Then $\lim_{x \to \infty} \ f(x)=\lim_{t \to 0^+} \ f(1/t)$

A: This is just exercise 75 in Section 2.7, James Stewart, Calculus Early Transcendentals 7th ed. 2011. Page 143.
Note that this result is true for $x \rightarrow -\infty$ and $t \rightarrow 0^-$ also.


text:
Q: "catching" errors in embedded youtube videos I'm embedding a YouTube video in my website as follows:

It works great but on my work computer, when I'm logged into Google Chrome with my work email, I get the following error:

An error occurred. Please try again later. (Playback ID: TMjivVwHlyxtQxnL) Learn More

This is expected. It's because my work email doesn't have permission to access YouTube. Here's the error I'm getting when I try to access it with my work email:
According to the DOM Inspector / Network tab requests to https://www.youtube.com/youtubei/v1/player?key=C_JiP-j2FwM are giving this error back:
{
  "error": {
    "code": 403,
    "message": "The caller does not have permission",
    "errors": [
      {
        "message": "The caller does not have permission",
        "domain": "global",
        "reason": "forbidden"
      }
    ],
    "status": "PERMISSION_DENIED"
  }
}

The code works because I can play the embedded video back in Incognito back just fine (because I'm not logged into my work email when I'm in Incognito).
Here's the code in it's full glory so people can reproduce the "problem" and see that it, in all likelihood, works great for them: https://jsfiddle.net/p3jz62uL/
What I'd like to be able to do is "catch" the error and change the behavior if it would occur. Maybe I'd remove the video all together or maybe I'd replace it with an image idk.

A: You can try making use of the youtube iframe api to detect this issue and respond accordingly. See the error codes available https://developers.google.com/youtube/iframe_api_reference#onError
To get you started,

I cant include it as snippet here since its sandboxed, but you can check the jsfiddle https://jsfiddle.net/puejzy6o/1/ example
Take note that your iframe url needs the query parameter &enablejsapi=1 and that onYouTubeIframeAPIReady is called automatically
Note: I didn't actually try to test if your particular error is handled by the api, but it should be.


text:
Q: What is the alternate to app.config in c# console application? I have been successfully using an exe (output of console app that i wrote) along with its application config file for a while. When i zipped them and sent it to my manager, he asked if i could get rid of the app.config file so the only thing that he copies in future is the exe.
Here is a gist of what my console app does.  For example, my app.config has the following.
 <userSettings>
        <myapp.Properties.Settings>
            <setting name="productline" serializeAs="String">
                <value>Electronics</value>
            </setting>
</userSettings>

When i run the app like
c:\>myapp.exe -productline Mechanical -save

it will update the productline settings to Mechanical. When i run my app again, the productline is retained as Mechanical until i change it again.
Back to the problem, I thought i will get rid of the app.config file and have a static variable 'productline' and update it. However, when i tested, the static variable is overridden only till i run the exe one time. Next time i run the exe, it goes back to default 'Electronics'. I assume the second time i run the exe is like running the web application with iisreset so the static variables are fresh again.
What is the best approach here? Can an app.config be embedded into the exe, so i  can still use it but the output will be just one exe file? Or what is the alternate way to save and retain the variables in this scenario ?

A: If you have a constraint that prevents you from saving to a file then you could put your setting in the registry. The RegistryProxy class gives you easy access to the CurrentUser registry settings. This documentation provides methods for creating and manipulating those settings.


text:
Q: How to support MOV(quick time) in android? I want to play in .mov file in android. But videoview or mediaplayer doesn't support this meida format. How can i add the support to it?

A: In general Android doesn't support any other media formats than the one listed here. That being said, there are quite a few 3rd party players that enable playback of more exotic formats, most of which are probably based around ffmpeg. You might want to take a look at the open source Dolpin Player (actual player also available in the Play store) for Android for some more pointers - not sure if mov playback is supported by default though.
However, since most mov files are actually H.264 encoded these days, why not remultiplex (or re-encode, depending on the source) into an something that Android plays nice with, e.g. an mp4 container? In terms of video support on Android, H.264 is definitely the way, as also pointed out by the 'Video Encoding Recommendations' section in the earlier link.

A: I know this is an old question, but times changin'
Now we can use the ExoPlayer as a custom Video Player (like VideoView), it supports more formats than the VideoView on android.
It's really simple to use, just to play videos, but has the powerfull of customization if you needed.
https://google.github.io/ExoPlayer/
Give it a try and please respond if this helped you.

A: Just try to play it anyway. The Quicktime .mov specification is the predecessor of the MP4 spec. There are only differences in a few atoms/boxes. You will be able to play an MP4 as .mov and a .mov as MP4 in most cases.

A: I found that even the big named players such as MX Player, BS Player and VLC for Android would not play .mov files correctly, especially those that had been recoreded on my wifes iphone 4s.
The playback was very choppy on my Nexus 7 and Nexus 10 and totally unwatchable on my HTC One (M7).
The player I found and installed that will play old and new iphone movie clips (.mov) flawlessly was found freely available from the Google Play Store.
Here is the best player I have found and believe me I have tried lots:
Playing .MOV files on an Android Device
Hope this helps some of those people with an Android device wishing to view iphone .mov files.


text:
Q: Stack gives 'dyld: malformed mach-o' When I attempt to run stack, for example even just stack --version, I get
dyld: malformed mach-o: load commands size (38712) > 32768

What can I do to fix this. This started appearing after some recent updates to Homebrew.

A: I'm guessing you've upgraded to macOS Sierra, because that message looks like you're hitting a new limit in its dynamic linker.  Might be that your stack executable is dynamically linked with all the Haskell libraries it uses, which is known to exceed the new limit.  You might try downloading the osx binary from the Stack releases page, which I've heard reports of working on Sierra (it's only dynamically linked to system libraries, but statically linked with Haskell libraries, so shouldn't hit the limit just to run).  Note that you may still have trouble building projects with a large number of dependencies, and so far we do not have a workaround for that yet.
Related: Stack issue #2577, and GHC issue #12479.

A: I also experienced the same issue when I upgraded to macOS Sierra, I was able to run Stack commands again by installing the Haskell Platform. The Stack tools included in the package seem to work.


text:
Q: How to copy consecutive sheets in excel using VBA I searched multiple posts about how to copy a sheet to another workbook.  In all instances, the sheets names are known.
If I am on the current sheet, how can I create a vba that copy the current sheet and the next 2 consecutive sheets into a new workbook.  The sheets' names change every week, so the program needs to pick the current active sheet and the next 2 sheets only.  Thank you for your help.

A: Below code would suffice your requirement. Just make sure you are at the 3rd last sheet of workbook when running it.
Option Explicit
Sub copyConsecutiveSheets()
Dim x As Integer
Dim k As Integer
Dim j As Integer
Dim b As String

x = 1
k = ActiveSheet.Index

ThisWorkbook.Sheets(k).COPY
For j = 1 To 2
b = ActiveWorkbook.Name
ThisWorkbook.Sheets(k + j).COPY After:=Workbooks(b).Worksheets(x)
x = x + 1
Workbooks(b).Activate

Next

End Sub


text:
Q: Convert 5 digit zip code to 3 digit zip code in R I have a large data set and all the zip codes are in 5 digit numeric form.  I need to take these and make them in to 3 digit zip codes (so that it keeps the first 3 digits of the zip code, including any 0s).  So
State Zip
A     12345

becomes
State Zip
A     123

How is this done?

A: Convert to string, then trim it:
> zip=12345
> strtrim(as.character(zip), 3)
[1] "123"

Then you can convert back to a number.


text:
Q: Can aperiodic tilings be non-hierarchical? and confusion over domino problem Anyone experienced with the undecidability of aperiodic tiling?
It's related to the halting problem which Turing proved was undecidable in the 30's and basically superimposes tiles onto other tiles which can be used to construct a Turing machine which would tile the plane aperiodically.
The proof given in Robinson (see below) shows that because you can construct such a machine the tiling problem is equal to the halting problem and therefore undecidable. I follow this through the paper and feel I understand the conclusion.
The problem is my girlfriend says this is all fine but only works for hierarchical tilings. I say well all aperiodic tiles are hierarchical and she says prove it.
Problem is I can't so I think I'm reading the proof wrong.
The paper is here
http://lipn.univ-paris13.fr/~fernique/qc/robinson.pdf

A: It sounds like you're misunderstanding the proof: the main theorem is

There is a computable function $f$ (such things are in general called many-one reductions) from $\mathbb{N}$ to $\{$finite sets of tiles$\}$ (construed appropriately) such that $\Phi_e(e)\uparrow$ if and only if the set of tiles $f(e)$ can tile the plane.

From this we conclude that the set of finite sets of shapes which tile the plane is not computable, since otherwise - pulling back along $f$ - we could compute the halting problem.
At this point, maybe (I haven't read the proof in detail in a long time) it turns out that every set of tiles of the form $f(e)$ which does tile the plane, does so in a "hierarchical" fashion (whatever that means). This might be the case; however, it would be wrong to say that the proof "only works for hierarchical tilings," since the tilings aren't the 'inputs' to the theorem. Additionally, I'd be very surprised if this were true: I have a vague picture in my head of what "hierarchical" ought to mean to me, and my recollection is that the tilings constructed in the proof of undecidability of the tiling problem appear to be not hierarchical.
It might be the case that all the images of all such reductions $f$ all have to mostly consist of hierarchically tilable sets of tiles; for example, it is conceivable that

There is no computable function $f$ from $\mathbb{N}$ to $\{$finite sets of tiles$\}$, such that (i) $f(e)$ can tile the plane if and only if $\Phi_e(e)\uparrow$, and (ii) each set of tiles $f(e)$ (for $\Phi_e(e)\uparrow$) can not tile the plane hierarchically.

Depending on the definition of "hierarchical," I'd be surprised by that result, but in principle it could be true. However, if true it would require considerable work to prove, probably more than proving the original result.
None of the above, by the way, relies on aperiodicity. Where aperiodicity arises is in the fact that, if every set of tiles which could tile the plane could do so periodically, then the tiling problem would be computable (see the bottom of the first page of the article), so we must be using mostly sets of tiles which do not tile the plane periodically. That is, a lemma standing 'morally' (at least I think so) at odds to the undecidability of the tiling problem is:

There is no computable function $f$ from $\mathbb{N}$ to $\{$finite sets of tiles$\}$ such that $(i)$ $f(e)$ can tile the plane if and only if $\Phi_e(e)\uparrow$, and $(ii)$ if $\Phi_e(e)\uparrow$ then $f(e)$ can tile the plane periodically.

So aperiodicity is really an after-the-fact thing: because the tiling problem is unsolvable, it therefore follows that there are finite sets of tiles which can tile the plane, but can not do so periodically. (This is the first full sentence on page 178 of Robinson's article.)

I'm a little unclear, though, exactly what your question is, so I might not have addressed it well; is this what you were looking for?


text:
Q: Why can't date and regexes in Python be as succinct as they are in JS?
*

*Why is datetime a "child" of itself? Why is it datetime.datetime.now instead of datetime.now?

*Why can't I use regex literals like in Javascript? EG /foo/.test('foo')

A: datetime is  a python module that contains datetime class that has a method now.
I agree with you datetime.datetime only looks ugly because the module and class have the same name . I have myself been stumped at times due to this specific issue.
I have mostly incorporated the class directly in my module by doing.
from datetime import datetime  <-- the first datetime is module and second a class
....
datetime.now()   <------ this datetime is a class

A: *

*datetime.now() (where datetime is a class and .now() is a static method of this class) is perfectly possible. You just have to from datetime import datetime (where the first datetime is a module of the standard library -- python likes namespaces very much -- and the second the said class in that module). It's just not common.

*Design decision. I suppose it complicates the grammar quite a bit (it sure looks like it does) and it's also not clearly superior - forward slashes must be escaped, the alternatuve (raw string literals) don't need backslashe escaping, so they're about even. Also, Python (unlike e.g. Perl, where regex literals come from as far as I know) is not solely a scripting language for e.g. text processing. I've written several Python modules a hundred lines long that didn't use a single regex.

A: For 1. you could do this:
from datetime import datetime
datetime.now() #thus saving "datetime"

A: Because it's a namespace. You can change that
[~]
|4>from datetime import datetime

[~]
|5>givemethetime = datetime.now

[~]
|6>givemethetime()
[6] datetime.datetime(2010, 12, 10, 12, 27, 20, 872721)

A: Javascript has some great strengths, but namespaces aren't really seen as one of its strengths (there are workarounds as mentioned in the book:  Javascript: the good parts).
As mentioned by others, isn't date succinct if you do: from datetime import datetime?


text:
Q: libuv and intel-iot-devkit/mraa for Beaglebone Black IO control Does someone use libuv and the the intel-iot-devkit/mraa together doing some not so fast IO work. I do need any framework in C for doing some measurement and control stuff on a BBB. Or is there any better library or framework someone can recommend.
many thanks

A: GitHub . com/intel-iot-devkit/upm
Try this page on GitHub...
Seth
P.S. They have plenty of examples and software to try out for different modules.

A: the library I found from a person on github.com shows to be promising for C but not with upm as the basis for modules.
Try here with the C language in mind: https://github.com/shabaz123/iobb
I think it only works with the BBB and related boards.


text:
Q: rake db:reset fails halfway through dropping databases In an attempt to solve a NoMethodError I was having, I read somewhere that running rake db:reset may help fix the problem. I am new to Rails and made the mistake of doing this without knowing exactly what this would do. When I ran it, it successfully dropped my development database (PosgreSQL), but then it hit a fatal error with the following message:
Dropped database 'development'
FATAL:  Peer authentication failed for user "postgres"
Couldn't drop database 'test'
rake aborted!
PG::ConnectionBad: FATAL:  Peer authentication failed for user "postgres"

Tasks: TOP => db:drop:_unsafe

I tried manually dropping the test database and rerunning rake db:reset, however the same error occurred. So I lost the data I had in my development database and am stuck with nothing but an empty production database.
I realize that this can probably be fixed by editing the pg_hba.conf file, but my app is running on my school's high performance cluster (Linux VM) and I don't have write access for that file. What I don't understand is why it was able to drop my development database, but not the rest.
I still have my seeds.rb and schema.rb files, so would it be possible to rebuild my databases without messing things up further? Or is there some way for me to fix the problem directly affecting the reset command?

A: rake db:reset runs db:drop and db:setup.  db:drop drops the database for the current RAILS_ENV.  If RAILS_ENV is not set, it will attempt to drop both the development and test databases.
Try setting the your RAILS_ENV before running:
RAILS_ENV=development rake db:reset

A: I figured out my problem regarding the authentication failure. When I first set up my database over a week ago I had added host:localhost to my database.yml file to circumvent the same issue. However, I only added it for my development database because that was all I needed to access up until now. Adding host:localhost to the other two databases in the file has fixed my issue.


text:
Q: How can I exit a multi-line shell script, on fail, and still log the error stream to a file? I'm trying to create a shell script (e.g., test.sh) that executes multiple commands, and redirect each command's stdout and stderr to a specific log file.
But, if a command fails, after writing stderr to the log file, I want to abort, rather than continuing with the remaining commands.
Will the following work, or do I need to do something different?
    command1 > log1.txt 2>&1
    command2 > log2.txt 2>&1
    command3 > log3.txt 2>&1

A: Make sure that each command returns an error code (ie non-zero) on failure, then you can use that to bail the containing script eg:
if command1 > log1.txt 2>&1; then
  if command2 > log2.txt 2>&1; then
    command3 > log3.txt 2>&1
  fi
fi

Or, more tersely:
command1 > log1.txt 2>&1 &&
command2 > log2.txt 2>&1 &&
command3 > log3.txt 2>&1


text:
Q: Running time of HashTable Operations vs HashMap operations? What are running times (Big O notaton) for the common operations (get, put, size) on HashTable and HashMap, is there a difference?

A: There is not a difference between the asymptotics of Hashtable and HashMap, and they are the predictable expected amortized O(1) for put and expected O(1) for get, assuming that you have a good hash function.
The biggest difference is that Hashtable incurs gratuitous overhead synchronizing accesses from concurrent threads, which a) you usually don't need, and b) is done more efficiently by ConcurrentHashMap.  You should basically never use Hashtable in new code.


text:
Q: What neural network architecture can I use to take advantage of clusters in the data? What neural network architectures can I use to take advantage of clusters in the data? In particular, I'm interested in doing a classification problem in which I believe that each cluster behaves slightly differently but that there are still trends across the data points across all clusters.
My current thoughts are to augment the data points to use a one-hot encoding based on which cluster each data point is in, but I'm not sure that this is effective.

A: A neural net with one hidden layer is
$$
y = g(a(X\Gamma_1)\Gamma_2)
$$
where $g()$ is your output activation and $a()$ is your relu or whatever.
So you have a cluster variable $c$ that you can turn into a matrix of dummies $C$.  Is cluster membership predictive of $y$?  (Go run a logistic regression right now if you don't know the answer.  You should have done this first.)
Just modify your neural net:
$$
y = g(C\beta + a(X\Gamma_1)\Gamma_2)
$$
If you think that there are nonlinear interactions between the clusters and $X$ you can do
$$
y = g(C\beta + a([C,X]\Gamma_1)\Gamma_2)
$$
Heck, if you think there are linear interactions between the network output and C you could do
$$
y = g(C\beta + a(X\Gamma_1)\Gamma_2 + (C\times a(X\Gamma_1))\Gamma_3)
$$
All of this is easy-enough to implement in Keras using the functional API.  You need multiple inputs if you want parametric structure.


text:
Q: Norm computation in number fields Let $\alpha:=\sqrt[3]{7}$ and let $K:=\mathbb{Q}[\sqrt[3]{7}]$. Consider a generic algebraic integer $a+b\alpha+c\alpha^2$, with $a,b,c\in\mathbb{Z}$. I want to find $N(a+b\alpha+c\alpha^2)$, where $N$ denotes the norm of $K$ over $\mathbb{Q}$. I wrote $N(a+b\alpha+c\alpha^2)=(a+b\alpha+c\alpha^2)(a+b\alpha\zeta+c\alpha^2\zeta^2)(a+b\alpha\zeta^2+c\alpha^2\zeta)$, where $\zeta$ is a 3rd primitive root of $1$, and after a very very long computation I found $a^3+7b^3+49c^3-21abc$.
Is there some way to shorten this?

A: I personally don't think that's much of calculation :), but there are other ways to find the norm.
Namely, let $\beta=a+b\alpha+c\alpha^2$. We want to find the matrix of the multiplication map $M_\beta$. Well,
$$\beta\cdot 1=\beta=a+b\alpha+c\alpha^2$$
$$\beta\alpha=a\alpha+b\alpha^2+c\alpha^3=7c+a\alpha+b\alpha^2$$
$$\beta \alpha^2=a\alpha^2+b\alpha^3+c\alpha^4=7b+7c\alpha+a$$
So,
$$M_\beta=\begin{pmatrix} a & b & c\\ 7c & a & b\\ 7 b & 7c & a\end{pmatrix}$$
and thus
$$N_{K/\mathbb{Q}}(\beta)=\det M_\beta=a^3-21abc+7b^3+49b^3$$

In practice, if you wanted to find $N_{L/K}(x)$ for some element $x\in L$, you can use particular properties about $x$. For example, $N_{L/K}(x)=(-1)^n a_0^{\frac{n}{d}}$ where $a_0$ is the constant coefficient of the minimal polynomial of $x$ over $K$, and $d=[K(x):K]$. Or, more generally to try and reduce your calculation to a smaller subextension (the last formula is a teased out version of this, where you restrict to the subextension $K(x)/K$).


text:
Q: NavigationLink is getting randomly popped and "Unable to present. Please file a bug." I have 6 navigation links within a navigation view but on some of them it randomly pops back to the root and says "Unable to present. Please file a bug." in the console. Here is my code for my NavigationView:
NavigationView {
    VStack {
        NavigationLink(
            destination: EventSetupQueueSelectionView()
                .background(Color.neutral(.oneHundred))
                .navigationBarTitle("")
                .navigationBarHidden(true)
                .navigationBarBackButtonHidden(true)
            ,
            tag: 1,
            selection: $modelController.currentPage,
            label: { EmptyView() }
        )

        NavigationLink(
            destination: EventSetupQueueDetailsView()
                .background(Color.neutral(.oneHundred))
                .navigationBarTitle("")
                .navigationBarHidden(true)
                .navigationBarBackButtonHidden(true)
            ,
            tag: 2,
            selection: $modelController.currentPage,
            label: { EmptyView() }
        )

        NavigationLink(
            destination: EventSetupSigningView()
                .background(Color.neutral(.oneHundred))
                .navigationBarTitle("")
                .navigationBarHidden(true)
                .navigationBarBackButtonHidden(true)
            ,
            tag: 3,
            selection: $modelController.currentPage,
            label: { EmptyView() }
        )

        NavigationLink(
            destination: EventSetupRetailView()
                .background(Color.neutral(.oneHundred))
                .navigationBarTitle("")
                .navigationBarHidden(true)
                .navigationBarBackButtonHidden(true)
            ,
            tag: 4,
            selection: $modelController.currentPage,
            label: { EmptyView() }
        )

        NavigationLink(
            destination: EventSetupPrivacyView()
                .background(Color.neutral(.oneHundred))
                .navigationBarTitle("")
                .navigationBarHidden(true)
                .navigationBarBackButtonHidden(true)
            ,
            tag: 5,
            selection: $modelController.currentPage,
            label: { EmptyView() }
        )

        NavigationLink(
            destination: EventSetupSummaryView()
                .background(Color.neutral(.oneHundred))
                .navigationBarTitle("")
                .navigationBarHidden(true)
                .navigationBarBackButtonHidden(true)
            ,
            tag: 6,
            selection: $modelController.currentPage,
            label: { EmptyView() }
        )
        EventSetupDetailView()
            .background(Color.neutral(.oneHundred))
            .navigationBarTitle("")
            .navigationBarHidden(true)
            .navigationBarBackButtonHidden(true)

    }
}

I've seen other stackoverflow/apple dev forum answers that talk about adding this to the NavigationView but it doesn't work for me:
NavigationLink(destination: EmptyView()) {
   EmptyView()
}

How can I fix this?

A: That's not how you're meant to work with NavigationLink + selection. It should be used when you're selecting one of destinations from current screen, it's not meant to be changed while an other screen presenting. And in your case you're pushing new destination before previous disappeared, that's why it's not working.
I suggest you Chaining your views into a navigation stack:
struct ContentView: View {

    var body: some View {
        NavigationView {
            EventSetupDetailView()
                .navigationBarHidden(true)
                .navigationBarBackButtonHidden(true)
                .background(Color.yellow)
                .onAppear {
                    print("hello")
                }
        }
    }
}

struct EventSetupDetailView: View {
    var body: some View {
        NavigationLink(
            destination: EventSetupQueueSelectionView()
                .navigationBarHidden(true)
                .navigationBarBackButtonHidden(true)
                .background(Color.yellow)
        ) {
            Text("next")
        }
    }
}

struct EventSetupQueueSelectionView: View {
    @Environment(\.presentationMode) var presentationMode

    var body: some View {
        Button("Back") {
            presentationMode.wrappedValue.dismiss()
        }
        NavigationLink(
            destination: EventSetupQueueDetailsView()
                .navigationBarHidden(true)
                .navigationBarBackButtonHidden(true)
                .background(Color.yellow)
        ) {
            Text("next")
        }
    }
}
struct EventSetupQueueDetailsView: View {
    @Environment(\.presentationMode) var presentationMode

    var body: some View {
        Button("Back") {
            presentationMode.wrappedValue.dismiss()
        }
        NavigationLink(
            destination: EventSetupSigningView()
                .navigationBarHidden(true)
                .navigationBarBackButtonHidden(true)
                .background(Color.yellow)
        ) {
            Text("next")
        }
    }
}
struct EventSetupSigningView: View {
    @Environment(\.presentationMode) var presentationMode

    var body: some View {
        Button("Back") {
            presentationMode.wrappedValue.dismiss()
        }
        NavigationLink(
            destination: EventSetupRetailView()
                .navigationBarHidden(true)
                .navigationBarBackButtonHidden(true)
                .background(Color.yellow)
        ) {
            Text("next")
        }
    }
}
struct EventSetupRetailView: View {
    @Environment(\.presentationMode) var presentationMode

    var body: some View {
        Button("Back") {
            presentationMode.wrappedValue.dismiss()
        }
        NavigationLink(
            destination: EventSetupPrivacyView()
                .navigationBarHidden(true)
                .navigationBarBackButtonHidden(true)
                .background(Color.yellow)
        ) {
            Text("next")
        }
    }
}
struct EventSetupPrivacyView: View {
    @Environment(\.presentationMode) var presentationMode

    var body: some View {
        Button("Back") {
            presentationMode.wrappedValue.dismiss()
        }
        NavigationLink(
            destination: EventSetupSummaryView()
                .navigationBarHidden(true)
                .navigationBarBackButtonHidden(true)
                .background(Color.yellow)
        ) {
            Text("next")
        }
    }
}
struct EventSetupSummaryView: View {
    @Environment(\.presentationMode) var presentationMode

    var body: some View {
        Button("Back") {
            presentationMode.wrappedValue.dismiss()
        }
        Text("next")
    }
}


text:
Q: Fortran fibonacci woes I am working my way through "Modern Fortran explained" by Metcalf, Reid, and Cohen and in chapter four it assigns a Fibonacci program as a homework problem.  My code below doesn't compile.  How can I correct it?
    !  Fibonacci here we go
    integer :: lim, i
    lim=0
    read *, lim

    integer, dimension(lim) :: fib

    if( lim >= 1 )
        fib(1) = 0
    end if

    if( lim >= 2 )
        fib(2) = 1
    end if

    if( lim >= 3 )
        fib(3) = 1
    end if

    do i=4, lim
        fib(i) = fib(i-2) + fib(i-1)
    end do

    do i=1, size(fib)
        print *, fib(i)
    end do

    end

Also, here are the errors I am getting.  I would attempt to shorten this to what is needed but I am not sure what one needs when looking at Fortran error logs.
Compiling the source code....
$/usr/bin/gfortran /tmp/135997827718658.f95 -o /tmp/135997827718658 2>&1
In file /tmp/135997827718658.f95:7

integer, dimension(lim) :: fib
1
Error: Unexpected data declaration statement at (1)
In file /tmp/135997827718658.f95:9

if( lim >= 1 )
1
Error: Unclassifiable statement in IF-clause at (1)
In file /tmp/135997827718658.f95:10

fib(1) = 0
1
Error: Unclassifiable statement at (1)
In file /tmp/135997827718658.f95:11

end if
1
Error: Expecting END PROGRAM statement at (1)
In file /tmp/135997827718658.f95:13

if( lim >= 2 )
1
Error: Unclassifiable statement in IF-clause at (1)
In file /tmp/135997827718658.f95:14

fib(2) = 1
1
Error: Unclassifiable statement at (1)
In file /tmp/135997827718658.f95:15

end if
1
Error: Expecting END PROGRAM statement at (1)
In file /tmp/135997827718658.f95:17

if( lim >= 3 )
1
Error: Unclassifiable statement in IF-clause at (1)
In file /tmp/135997827718658.f95:18

fib(3) = 1
1
Error: Unclassifiable statement at (1)
In file /tmp/135997827718658.f95:19

end if
1
Error: Expecting END PROGRAM statement at (1)
In file /tmp/135997827718658.f95:22

fib(i) = fib(i-2) + fib(i-1)
1
Error: Statement function at (1) is recursive
Error: Unexpected end of file in '/tmp/135997827718658.f95'

A: random fixes....
if block should be
if (condition) then
  do something
endif

cannot ommit "then".
you cannot go
read *, lim
integer, dimension(lim) :: fib

all the declaration has to come before executable codes.   so instead, use allocatable array
integer, dimension(:), allocatable :: fib
read *, lim
allocate(fib(lim))


text:
Q: SQL Sorting within Groupings I need help with SQL (MSSQL), where I am sorting by multiple boolean types in order to group the results, but also need to sort by a date field within each of the type groupings.
The following SQL seemingly works ok:
Select * from staff ORDER BY admin DESC, hr DESC, sales DESC, it DESC, updated DESC

The trick is that some records have more than 1 type selected and then the output gets messed up. I only need to show staff in one grouping, but they should appear sorted by updated DESC within each grouping.
This is the output I get:
Name  updated    admin  hr     sales  it
-------------------------------------------
fred  2012/04/01 true   true
bill  2011/10/01 true   true
joe   2012/04/01 true
sam   2012/03/01 true
jo    2012/02/01 true
beth  2012/03/01        true
mary  2012/02/01        true
harry 2011/02/01               true  true
gary  2012/04/01               true
bruce 2012/04/01                     true

This is the output I need
Name  updated    admin  hr     sales  it
-------------------------------------------
fred  2012/04/01 true   true
joe   2012/04/01 true
sam   2012/03/01 true
jo    2012/02/01 true
bill  2011/10/01 true   true
beth  2012/03/01        true
mary  2012/02/01        true
gary  2012/04/01               true
harry 2011/02/01               true  true
bruce 2012/04/01                     true

Hope that makes sense.

A: You can use case expressions in the order by clause for conditional sorting.
SELECT *
FROM staff
ORDER BY
    admin DESC,
    CASE admin WHEN 'true' THEN updated END DESC,
    hr DESC,
    CASE hr WHEN 'true' THEN updated END DESC,
    sales DESC,
    CASE sales WHEN 'true' THEN updated END DESC,
    it DESC,
    updated DESC


text:
Q: Java 7 Zip-JBinding Truncated zip file extracted from ISO I am using below code (link to full code) to extract zip file which is inside iso file using 7-zip-JBinding.
    for (ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) {
                    final int[] hash = new int[] { 0 };
                    if (!item.isFolder()) {
                        ExtractOperationResult result;

                        final long[] sizeArray = new long[1];
                        result = item.extractSlow(new ISequentialOutStream() {
                            public int write(byte[] data) throws SevenZipException {
                                hash[0] ^= Arrays.hashCode(data); // Consume data
                                sizeArray[0] += data.length;
                                return data.length; // Return amount of consumed data
                            }
                        });

                        if (result == ExtractOperationResult.OK) {
                            System.out.println(String.format("%9X | %10s | %s",
                                    hash[0], sizeArray[0], item.getPath()));
                        } else {
                            System.err.println("Error extracting item: " + result);
                        }
                    }
                }

It works fine for some of the file (e.g. this file which is 1.74 GB), but when I try to use it with this file which is 4.01 GB, it is getting truncated and extracted file is only of 8.26 MB zip file from ISO whereas actual ZIP file size is 4.00 GB.
How do I resolve this issue? Is there any configuration that is restricting this file to extract appropriately which I need to change?


text:
Q: Strange carousel with jquery bx slider I´ve got two carousels and the first one should work like the second one but it dowsnt, ca you help me with that problem?
 $('.slider1').bxSlider({
      slideWidth: 960,
    minSlides: 1,
    maxSlides: 8,
    slideMargin: 0

  });

    http://jsfiddle.net/qF39p/

Thanks

A: Try this the solution on github https://github.com/stevenwanderski/bxslider-4/pull/481#issuecomment-38479768
Problem is probably in jquery 1.11

A: Note: Use bxslider without specifying slide width and also margin apply only in css it take effect from there.

*

*to solve this problem remove float:left;and add display:inline-block in your list element.
$('.slider1').bxSlider({
      minSlides: 1,
      maxSlides: 8,
 });

*Also try to remove max slides because its make your slider static.

*if your carousel contain different height in every item then use adaptiveHeight:true in function.


text:
Q: Electrical circuit with capacitors and transistor I don't know how this circuit works. So I would like someone to explain me. I know that the qustion is too general, but I am new in electricity and I don't know someone who can answer me how this works.
The result is that when The circuit is connected to 9V battery one of the diodes start lighting and after some time (for example 5 seconds) the other diode start lighting while the light of the first diode start to decrease (start to dim) and a after second for example it stops lighting. So only the second diode now lighting and after for example 5 second it starts dimming and the first diode start lighting and after one second the second diod stop lighting at all an so on and so on.
I do the following measurements when D2 lights. C2 start to discharge when D2 start to ligthing.I measure that VCE (voltage drop between C and E) is positive. I measure that VDE is the sum of 9V + current voltage of C2.
So let assume that D2 starts lighting. I have the following questions:

*

*The capacitor is charged at 6.8 Volts, but why?

*Why when the D2 starts lighting the D1 dim for one for one second. Where the current goes through that lights the diode?

*Why the voltage drop of R2 is the sum of 9V + voltage of C2. And when we have voltage drop through it this means that some current pass through it, but what is its path (maybe through C2?)

*Why D2 stops lighting when the voltage drop across C2 is 0V. Why it don't stops when it is 0.7 for example?

Thanks in advance for your attention!

A: This is called an astable multivibrator. It's a beautifully simple circuit that is very challenging to explain! If you're new to electricity then don't get too discouraged - this is tricky for even experienced people to understand. There are many explanations on the web. This one is pretty good.
I highly recommend simulating the circuit, and attempting to answer all your questions by probing the circuit in simulation. If you don't already have a simulation tool, try CircuitLab (which happens to be the built-in circuit tool on this site) or LTSpice. They're both relatively easy to get started and will easily handle this sort of circuit.
Now to your questions:

*

*Consider D1 on, D2 off. T1 is on so its collector is at ground allowing C1 to charge via R3. Once it gets to about 0.6V, T2 switches on clamping the voltage on that side of the capacitor. T1 switches off at the same time so now C1 is charging in the opposite direction via D1. The 9V source, minus the two diode drops in D1 and T2, means the voltage across C1 tends towards about 7V. Before it gets there the circuit switches again, giving you about 6.8V on the cap.

*Through C1, as per answer above.

*When T1 is off, there is a path from 9V through R2, C2 and T2, until C2 charges. There is very little drop across T2, so during that period V(R2) + V(C2) = 9V.

*D2's turn off is caused by C1 - when C2 charges enough to turn on T1, C1 is suddenly pulled to ground which pulls the gate of T2 low, turning off D2.


text:
Q: Strategy to incorporate Likes, while preventing users from "multi-liking" utilizing MySQL I have a website that needs to incorporate likes, while preventing any user from liking a post multiple times. I am using React, Express, and MySql.
On this website, there is a page where a user can view all posts, where each entry includes: (1) the post message, (2) the user who created the post, and (3) how many likes that post might have. This was a trivial SQL Command where I performed the following query:
SELECT users.username, posts.message, posts.likes
FROM users
INNER JOIN posts
WHERE users.user_id = posts.post_id

With my current implementation, I have a button located on each post, that when clicked will communicate with my backend to insert the associated user_id and post_id within my 'likes' table. My vision is that if a user has already liked a certain post, then to show a dislike button, and if the user has not liked a post, to show the like button.
I know I am on the right track with creating a 'likes' table, since I can't have duplicate entries.
The query I desire is one where I can have a list of all the posts a user has liked as well as the ones they have not liked. I know this can be obtained with either a LEFT or RIGHT JOIN between the 'posts' table and the 'likes' table. However, with this list of results, how can I distinguish which posts a user has liked and the ones they have not liked, so that when I map() through this list I can easily place a like button if the user has not liked a post or a unlike if the user has not liked the post?
Here is my SQL schema:
Users Table (user_id, username, password) //Primary Key: user_id
Posts Table (post_id, message, likes) //Primary Key: post_id
Likes Table (user_id, post_id) //Primary Keys: user_id, post_id and Foreign Keys: user_id, post_id

A: Left join the likes to the posts on common post_id and the ID of the user in question. Then check if l.user_id IS NOT NULL. If and only fi it is, then the user liked that post.
SELECT p.*,
       l.user_id IS NOT NULL liked
       FROM posts p
            LEFT JOIN likes l
                      ON l.post_id = p.post_id
                         AND l.user_id = ?;


text:
Q: Recover expired session with Retrofit I am using retrofit for my http calls in an android app. Any of the calls to server can return a 401 code in any moment if the session is expired. So I need a generic mechanism to detect that code in any call, do a new login request to server and when I have the response, retry the original petition. I want to centralize that login in one method to avoid repiting the retry login in all my calls.
I think I should do that with an Interceptor. My idea is:
Create an Interceptor used by all my calls to server. In that interceptor, look for the response code. If response code is 401, do a login request and after that the original request again. And when the process finishes, interceptor has to return the response from the last request, the original one.
The problem is that I dont know how can I make new requests in the interceptor method intercept(Interceptor.Chain chain). I cant find any example to do that.


text:
Q: Height li element to change variable I want to change the value based on the height of a li - element.
The element is shown based on a value from our database which can't use here.
Here is my HTML code:

  Achtergronddata

And my Javascript code:
if($("ul_customer1").actual("height") > 5) {
  var customer= 1;
} else {
  var customer= 0;
}

When active the height of the li = 129. When hidden it is 4.
I also tried "visible" and "css display block", but those don't work.
How can I change var customer based on the height of the li element?
Thanks,
Isabelle

A: You can use the outerHeight() or height() functions:
if ($("#ul_customer1").height() > 5) {
  var customer = 1;
} else {
  var customer = 0;
}

And make sure you give # for id.
Here's a demo for you:
When there's nothing inside #ul_customer1...

$(function () {
  if ($("#ul_customer1").height() > 5) {
    var customer = 1;
  } else {
    var customer = 0;
  }
  alert(customer);
});

When there's something inside #ul_customer1...

$(function () {
  if ($("#ul_customer1").height() > 5) {
    var customer = 1;
  } else {
    var customer = 0;
  }
  alert(customer);
});

Hello
Hi

Note: This looks like a X-Y Problem to me. I believe you are checking if the particular element is empty or not. If that was the case, use :is(empty) instead.


text:
Q: SQL Filter rows based on multiple distinct values of a column Given the following table
DECLARE @YourTable TABLE (id int, PLU int, Siteid int, description varchar(50))

INSERT @YourTable VALUES (1, 8972, 2, 'Beer')
INSERT @YourTable VALUES (2, 8972, 3, 'cider')
INSERT @YourTable VALUES (3, 8972, 4, 'Beer')
INSERT @YourTable VALUES (4, 8973, 2, 'Vodka')
INSERT @YourTable VALUES (5, 8973, 3, 'Vodka')
INSERT @YourTable VALUES (6, 8973, 4, 'Vodka')

I trying to write a query that would give me all rows that have multiple distinct values for a given description value against a plu.
So in the example above I would want to return rows 1,2,3 as they have both a 'cider' value and a 'beer' value for a plu of '8972'.
I thought 'GROUP BY' and 'HAVING' was the way to go but I can't seem to get it to work correctly.
SELECT P.PLU, P.Description
FROM @YourTable P
GROUP BY P.PLU, P.Description
HAVING COUNT(DISTINCT(P.DESCRIPTION)) > 1

Any help appreciated.

A: You shouldn't GROUP BY the description if you are doing a DISTINCT COUNT on it (then it will always be just 1).  Try something like this:
SELECT P2.PLU, P2.Description
FROM @YourTable P2
WHERE P2.PLU in (
      SELECT P.PLU
      FROM @YourTable P
      GROUP BY P.PLU
      HAVING COUNT(DISTINCT(P.DESCRIPTION)) > 1
)


text:
Q: Trying to parse 2-d JSON array for the aggregations I want Basically I want to parse this JSON 2-day array(example of snapshot data below) to sum up all the values for cases and deaths for each date, including the states.  It will ignore the state column and just add up cases and deaths from all state for each date. I can do it in SQL, difficult in javascript.
So in the end it will look like:
the JSON 2-d array that looks like this :
{date: "2020-02-17", totalCases: "7", totalDeaths: "1"}
{date: "2020-02-18", totalCases: "150", totalDeaths: "2"}
{date: "2020-02-19",  totalCases: "210", totalDeaths: "3"}
{date: "2020-02-20",  totalCases: "350", totalDeaths: "7"}

THE original JSON OBJECT to be aggregated IS BELOW
138: {date: "2020-02-18", state: "California", fips: "06", cases: "7", deaths: "0"}
139: {date: "2020-02-18", state: "Illinois", fips: "17", cases: "2", deaths: "0"}
140: {date: "2020-02-18", state: "Massachusetts", fips: "25", cases: "1", deaths: "0"}
141: {date: "2020-02-18", state: "Nebraska", fips: "31", cases: "10", deaths: "0"}
142: {date: "2020-02-18", state: "Texas", fips: "48", cases: "2", deaths: "0"}
143: {date: "2020-02-18", state: "Washington", fips: "53", cases: "1", deaths: "0"}
144: {date: "2020-02-18", state: "Wisconsin", fips: "55", cases: "1", deaths: "0"}
145: {date: "2020-02-19", state: "Arizona", fips: "04", cases: "1", deaths: "0"}
146: {date: "2020-02-19", state: "California", fips: "06", cases: "7", deaths: "0"}
147: {date: "2020-02-19", state: "Illinois", fips: "17", cases: "2", deaths: "0"}
148: {date: "2020-02-19", state: "Massachusetts", fips: "25", cases: "1", deaths: "0"}
149: {date: "2020-02-19", state: "Nebraska", fips: "31", cases: "10", deaths: "0"}
150: {date: "2020-02-19", state: "Texas", fips: "48", cases: "2", deaths: "0"}
151: {date: "2020-02-19", state: "Washington", fips: "53", cases: "1", deaths: "0"}
152: {date: "2020-02-19", state: "Wisconsin", fips: "55", cases: "1", deaths: "0"}
153: {date: "2020-02-20", state: "Arizona", fips: "04", cases: "1", deaths: "0"}
154: {date: "2020-02-20", state: "California", fips: "06", cases: "8", deaths: "0"}
155: {date: "2020-02-20", state: "Illinois", fips: "17", cases: "2", deaths: "0"}
156: {date: "2020-02-20", state: "Massachusetts", fips: "25", cases: "1", deaths: "0"}
157: {date: "2020-02-20", state: "Nebraska", fips: "31", cases: "11", deaths: "0"}

A: You can do it by using reduce.

const records = {
 138: {date: "2020-02-18", state: "California", fips: "06", cases: "7", deaths: "2"},
 139: {date: "2020-02-18", state: "Illinois", fips: "17", cases: "2", deaths: "0"},
 140: {date: "2020-02-18", state: "Massachusetts", fips: "25", cases: "1", deaths: "0"},
 141: {date: "2020-02-18", state: "Nebraska", fips: "31", cases: "10", deaths: "0"},
 142: {date: "2020-02-18", state: "Texas", fips: "48", cases: "2", deaths: "0"},
 143: {date: "2020-02-18", state: "Washington", fips: "53", cases: "1", deaths: "2"},
 144: {date: "2020-02-18", state: "Wisconsin", fips: "55", cases: "1", deaths: "0"},
 145: {date: "2020-02-19", state: "Arizona", fips: "04", cases: "1", deaths: "0"},
 146: {date: "2020-02-19", state: "California", fips: "06", cases: "7", deaths: "0"},
 147: {date: "2020-02-19", state: "Illinois", fips: "17", cases: "2", deaths: "0"},
 148: {date: "2020-02-19", state: "Massachusetts", fips: "25", cases: "1", deaths: "0"},
 149: {date: "2020-02-19", state: "Nebraska", fips: "31", cases: "10", deaths: "0"},
 150: {date: "2020-02-19", state: "Texas", fips: "48", cases: "2", deaths: "0"},
 151: {date: "2020-02-19", state: "Washington", fips: "53", cases: "1", deaths: "0"},
 152: {date: "2020-02-19", state: "Wisconsin", fips: "55", cases: "1", deaths: "0"},
 153: {date: "2020-02-20", state: "Arizona", fips: "04", cases: "1", deaths: "0"},
 154: {date: "2020-02-20", state: "California", fips: "06", cases: "8", deaths: "0"},
 155: {date: "2020-02-20", state: "Illinois", fips: "17", cases: "2", deaths: "0"},
 156: {date: "2020-02-20", state: "Massachusetts", fips: "25", cases: "1", deaths: "0"},
 157: {date: "2020-02-20", state: "Nebraska", fips: "31", cases: "11", deaths: "0"}
};

const res = Object.values(records).reduce((acc, {date, cases, deaths}) => {
 if (acc[date] !== undefined) {
  acc[date].totalCases += (+cases);
  acc[date].totalDeaths += (+deaths);
 } else {
  acc[date] = {date, totalCases: (+cases), totalDeaths: (+deaths)};
 }

 return acc;
}, {});

console.log(res);
.as-console-wrapper {min-height: 100% !important; top: 0;}


text:
Q: Highlighting arbitrary points in a matplotlib plot I am new to python and matplotlib.
I am trying to highlight a few points that match a certain criteria in an already existing plot in matplotlib.
The code for the initial plot is as below:
pl.plot(t,y)
pl.title('Damped Sine Wave with %.1f Hz frequency' % f)
pl.xlabel('t (s)')
pl.ylabel('y')
pl.grid()
pl.show()

In the above plot I wanted to highlight some specific points which match the criteria abs(y)>0.5. The code coming up with the points is as below:
markers_on = [x for x in y if abs(x)>0.5]

I tried using the argument 'markevery', but it throws an error saying
'markevery' is iterable but not a valid form of numpy fancy indexing;

The code that was giving the error is as below:
pl.plot(t,y,'-gD',markevery = markers_on)
pl.title('Damped Sine Wave with %.1f Hz frequency' % f)
pl.xlabel('t (s)')
pl.ylabel('y')
pl.grid()
pl.show()

A: The markevery argument to the plotting function accepts different types of inputs. Depending on the input type, they are interpreted differently. Find a nice list of possibilities in this matplotlib example.
In the case where you have a condition for the markers to show, there are two options. Assuming t and y are numpy arrays and one has imported numpy as np,

*

*Either specify a boolean array,
plt.plot(t,y,'-gD',markevery = np.where(y > 0.5, True, False))

or

*an array of indices.
plt.plot(t,y,'-gD',markevery = np.arange(len(t))[y > 0.5])

Complete example
import matplotlib.pyplot as plt
import numpy as np; np.random.seed(42)

t = np.linspace(0,3,14)
y = np.random.rand(len(t))

plt.plot(t,y,'-gD',markevery = np.where(y > 0.5, True, False))
# or
#plt.plot(t,y,'-gD',markevery = np.arange(len(t))[y > 0.5])

plt.xlabel('t (s)')
plt.ylabel('y')

plt.show()

resulting in

A: markevery uses boolean values to mark every point where a boolean is True
so instead of markers_on = [x for x in y if abs(x)>0.5]
you'd do markers_on = [abs(x)>0.5 for x in y] which will return a list of boolean values the same size of y, and every point where |x| > 0.5 you'd get True
Then you'd use your code as is:
pl.plot(t,y,'-gD',markevery = markers_on)
pl.title('Damped Sine Wave with %.1f Hz frequency' % f)
pl.xlabel('t (s)')
pl.ylabel('y')
pl.grid()
pl.show()

I know this question is old, but I found this solution while trying to do the top answer as I'm not familiar with numpy and it seemed to overcomplicate things

A: The markevery argument only takes indices of type None, integer or boolean arrays as input. Since I was passing the values directly it was throwing the error.
I know it is not very pythonic but I used the below code to come up with the indices.
marker_indices = []
for x in range(len(y)):
    if abs(y[x]) > 0.5:
        marker_indices.append(x)

A: I was having this issue because I was trying to mark some points that were out of the bounds of the data frame.
For example:
some_df.shape
-> (276, 9)

markers = [1000, 1080, 1120]

some_df.plot(
    x='date',
    y=['speed'],
    figsize=(17, 7), title="Performance",
    legend=True,
    marker='o',
    markersize=10,
    markevery=markers,
)

-> ValueError: markevery=[1000, 1080, 1120] is iterable but not a valid numpy fancy index

Just make sure that the values you are giving as markers are within the bounds of the data frame you want to plot.


text:
Q: Как вывести видео в галерее Carbon Fields? Подскажите пожалуйста как вставить видео в галерее Carbon Fields. С картинками всё получается, а видео не выводится. Код прилагается:
<?php
use Carbon_Fields\Container;
use Carbon_Fields\Field;

Container::make( 'post_meta', 'Дополнительные поля' )
->show_on_page(7)
->add_tab( 'Отзывы', [
Field::make( 'text', 'responce-title', 'Заголовок' ),
Field::make( 'media_gallery', 'crb_media_gallery', 'Видео отзывы' )
->set_type( array( 'video' ) ),
]);

<?php $slides=carbon_get_post_meta($page_id, 'crb_media_gallery');
 foreach ($slides as $slide):
 $video_src= wp_get_attachment_image_url($slide, 'full');
?>
<div>
 <video controls class="video__item">
  <source type="video/mp4" src="<?php echo  $video_src; ?>">
 </video>
</div>
<?php endforeach; ?>


text:
Q: Factory Pattern implementation in C# I'm implementing a factory pattern that looks as follows.
public class FeedFactory
{
    #region Singleton Pattern
    //..
    #endregion

    private static Feed[] _factory = new Feed[(int)FeedType.Total];

    public void RegisterFeed(FeedType feedType,Feed feed)
    {
        if (_factory[(int)feedType] == null)
        {
            _factory[(int)feedType] = feed;
        }
        else
        {
            // already registered
        }
    }

    public Feed GetFeed(FeedType feedType)
    {
        return _factory[(int)feedType];
    }
}

Here, Feed is an abstract class from which the different classes inherit. How can I register the different classes? Is it possible to do it from their constructor?

A: This is not a factory pattern. A factory will always have some constructor logic in it, at least one new. That's the idea of a factory: the caller doesn't have to worry about how objects are created. This is a singleton repository.
So first of all, instead of using an array, you should be having a type indexed dictionary.
private static Dictionary<Type, Feed> _singletons = new Dictionary<Type, Feed>();

After that, you don't need a register method. The dictionary should be filled automatically when you retrieve singletons.
Now I suppose your Feed class has a default constructor without arguments. In that case, you can implement a factory method directly from the abstract class Feed. We're going to use some generics here, because it allows you to control inheritance:
public abstract class Feed
{
    public static T GetInstance<T>() where T:Feed, new()
    {
        T instance = new T();
        // TODO: Implement here other initializing behaviour
        return instance;
    }
}

Now back to your singleton repository.
public class FeedSingletonRepository
{
    private static readonly object _padlock = new object();
    private static Dictionary<Type, Feed> _singletons = new Dictionary<Type, Feed>();

    public static T GetFeed<T>() where T:Feed
    {
        lock(_padlock)
        {
             if (!_singletons.ContainsKey(typeof(T))
             {
                 _singletons[typeof(T)] = Feed.GetInstance<T>();
             }
             return (T)_singletons[typeof(T)];
        }
    }
}

Note that I included a threadsafe behaviour which is a good thing to do when you work with singletons.
Now if you want to get the singleton for a given type inheriting from Feed (let's call it SpecializedFeedType), all you have to do is:
var singleton = FeedSingletonRepository.GetFeed<SpecializedFeedType>();

or
SpecializedFeedType singleton = FeedSingletonRepository.GetFeed();

which is the same line with a slightly different syntax.
Edit2: changed some syntax errors.

A: Just as a side note -- as a factory is intended to wrap creation, it's a curious choice that you're creating objects and registering them with the factory. Is this more an object repository than a factory, or is there more to the class than I'm seeing?
If it is an object repository, then you might also find some extra inspiration in other questions, like this one.

A: When you call the RegisterFeed method you need to pass a concrete instance of a Feed class. So it is the responsibility of the caller to provide the concrete implementation.

A: Just register the type of the classes you want to create, then use Activator.CreateInstance to create instances of that type.
It should work this way:
private static Type[] _factory = new Type[(int)FeedType.Total];

public void RegisterFeed(FeedType feedType, Type type)
{
  ...
  _factory[(int)feedType] = type;
  ...
}

public Feed GetFeed(FeedType feedType)
{
    return Activator.CreateInstance(_factory[(int)feedType]) as Feed;
}

You can call RegisterFeed like the following:
RegisterFeed(FeedType.SomethingSpecial, typeof(MyDerivedSpecialFeed));

A: class FeedFactory {

    public IFeedFactory GetFeedFactory(string type) {
       switch(type) {
          case "1": return new Feed1(); break;
          case "2": return new Feed2(); break;
       }

    }

}

Note all Feeds Must implement an IFeedFactory interface and implement the method necessary.
//From the client
FeedFactory ff1 = new FeedFactory();
IFeedFactory obj = ff1.GetFeedFactory("1");
obj.ExecuteMethod();


text:
Q: Powershell pass Json String to external function I am trying to pass an JSON String to External Function. However, seems like it's not able to consider this as valid argument.
Following works perfectly find is Shell Script
old_config=`databricks clusters get --cluster-id $cluster_id`
databricks clusters edit --json "${old_config}"

However, Following throws and Error in PowerShell
$OldConfig=databricks clusters get --cluster-id $ClusterID
databricks clusters edit --json "${OldConfig}"

Error
PS Azure:\>   databricks clusters edit --json "$OldConfig" --debug
HTTP debugging enabled
Usage: databricks clusters edit [OPTIONS]
Try "databricks clusters edit -h" for help.

Error: Got unexpected extra arguments (cluster terminated (inactive for 15 minutes).,    autotermination_minutes: 15,    terminated_time: 1575562085278,    spark_conf: {spark.databricks.cluster.profile: serverless,      spark.databricks.io.cache.enabled: false,      spark.databricks.repl.allowedLanguages: sql,python,r,      spark.databricks.io.cache.maxMetaDataCache: 0,      spark.databricks.delta.preview.enabled: true,      spark.driver.maxResultSize: 7GB   },    driver_node_type_id: Standard_DS4_v2,    last_state_loss_time: 1575561173235,    start_time: 1566998040228,    termination_reason: {     code: INACTIVITY,      parameters: {       inactivity_duration_min: 15     }   },custom_tags: {     cluster_name: GatewayCluster,      ResourceClass: Serverless,      cluster_id: 0828-11122-ddi3i3   },    cluster_name: GatewayCluster,    init_scripts_safe_mode: false,    state: TERMINATED,    spark_version: 5.5.x-scala2.11,    cluster_id: 0828-131400-dents910,    creator_user_name: abc@xyz.com,    default_tags: {     ClusterName: GatewayCluster,      ClusterId: 0828-11122-ddi3i3,      Vendor: Databricks,      Creator: abc@xyx.com   },    cluster_source: UI,  autoscale: {     max_workers: 20,      min_workers: 7   },    spark_context_id: 11299222 })
(.venv) Azure:/


text:
Q: Proving existence of intermediate field of degree 2 If $K$ is the splitting field of an irreducible polynomial, which is not solvable by radicals, of degree 5 over Q, show that there is at most one intermediate field, $E$, of degree 2. Prove that if $a, b$ are irrational in $K$ such that $a^2, b^2$ are rational, then $a = rb$ where $r \in \mathbb{Q}$.
I began to think that the galois group is $S_5$ because the polynomial is not solvable by radicals and is irreducible. The only subgroup of index 2 is $A_5$ so I figured this has something to do with it.
For the second part, if I assume the first part, I think the first part of the proof: Consider $\mathbb{Q}(a) = \mathbb{Q}(b)$ because of the first part. So, there exists some automorphism on $\mathbb{Q}$ where $a \to b$.

A: The Galois group $G$ can be $S_5$ or $A_5$. Both these cases occur.
It cannot be any other group as all other subgroups of $S_5$ are soluble.
As you say $S_5$ has only one index two subgroup. But $A_5$ has none.
A quadratic subextension corresponds to an index $2$ subgroup of $G$.
There is one when $G=S_5$ and none for $G=A_5$. (The quadratic subextension
is $\Bbb Q(\sqrt D)$ where $D$ is the discriminant of the quintic).
If $a^2=A$, $b^2=B$ with $a$, $b\in K-\Bbb Q$ and $A$, $B\in \Bbb Q$ then
$\Bbb Q(\sqrt A)$ and $\Bbb Q(\sqrt B)$ are quadratic extensions of $\Bbb Q$. We must be in the $G=S_5$ situation, and $\Bbb Q(\sqrt A)=\Bbb Q(\sqrt B)=\Bbb Q(\sqrt D)$. The only rationals with square roots in
$\Bbb Q(\sqrt A)$ are squares of rationals and squares of rationals
multiplied by $A$. So $B=r^2 A$, equivalently $b=\pm r a$, for some $r\in \Bbb Q$.


text:
Q: Include functions written in different folders How can I use a function written within a .cpp saved in a folder different from the one that needs that function? For all the .cpp of the first folder I've simply added an #include to the .h of the cpp (and it works fine), but trying to add an #include "..\Folder1\....h" to all the .cpp of the second folder is not enough and the Borland C++ Builder gives me the Unresolved external error.
What can I do?
Thanks

A: You need to compile the cpp file into an object file (.o) inside its own directory and link that object file with your program.

A: Add the location of the object files to your linker search path.


text:
Q: How do I create a regex to exclude 2, 102 and 103 the regex should allow all other digits.
Thanks

A: The same way you use a toothpick to cut down a tree, or parse XML with regular expressions, or write an operating system in COBOL, or do anything with Pascal :-)
You don't. You use the right tool for the job, which would be something like (pseudo-code):
if val = 2 or val = 102 or val = 103:
    return
# Process other values.

A: It's far simpler to allow any numbers, then exclude the ones you don't want outside the regex.
while (/([0-9]+)/g) {
   next if $1 == 2 || $1 == 102 || $1 == 103;
   say $1;
}

But it can be done.
 1. Complex pattern,
/
   ...
   (?<![0-9])  # Possible to omit in some circumstances.
   (
      (?: 0
      |   [3-9][0-9]*
      |   2[0-9]+
      |   1(?:[1-8][0-9]*)?
      |   10([014-9][0-9]*)?
      |   10[23][0-9]+
      )
   )
   (?![0-9])   # Possible to omit in some circumstances.
   ...
/xg

 2. Embed Perl code into the pattern
/
   ...
   (?<![0-9])  # Possible to omit in some circumstances.
   ([0-9]+)
   (?![0-9])   # Possible to omit in some circumstances.
   (?(?{ $^N == 2 || $^N == 102 || $^N == 103 })(?!))
   ...
/xg

 3. Negative lookahead
/
   ...
   (?<![0-9])  # Possible to omit in some circumstances.
   (?!(?:2|102|103)(?![0-9]))
   ([0-9]+)
   ...
/xg

The tricky part is making sure that

*

*20 matches

*102 doesn't get matched as 10

A: True regex compilable to an NFA/DFA:
length 1:
  [0-13-9]

length 2:
  [0-9][0-9]

length 3:
  [02-9][0-9][0-9]

  10[0-14-9]

  1[1-9][0-9]

length 4 or more:
  [0-9][0-9][0-9][0-9]+

combine:
  [0-13-9]|[0-9][0-9]|[02-9][0-9][0-9]|10[0-14-9]|1[1-9][0-9]|[0-9][0-9][0-9][0-9]+

grep line for validation:
  grep -E '^([0-13-9]|[0-9][0-9]|[02-9][0-9][0-9]|10[0-14-9]|1[1-9][0-9]|[0-9][0-9][0-9][0-9]+)$'

A: Ummm, do you mean get one number per line and throw out ones that are "2", etc.?
if ($a =~ /^(\s)*(10)?([23])(\s*)$/ || $a =~ /^(\s)*(2)(\s)*$/)
     {
                #bad string!  do whatever
     }
 else
    {
                #good string!
    }

This matches
2
102
103

that is, a line with JUST your "bad" number and maybe some spaces. "111103444", is considered a "good number", so if you mean to filter out your bad numbers try something like
$a =~ s/^(?:102|103|2)$//g;

which may not technically be a pure regex...
Why did someone say not to use perl for regular expressions???


text:
Q: How to use Twitter Insights and retrieve data out there? In Twitter Analytics Under Audience Insights I can see my followers Interests,Gender and etc. See the attached image
I have skimmed through some APIs of Twitter but I am still unsure about how to retrieve those data programmatically..
Which API documentation should I take into account as a reference? Also is it a necessity to be an official partner to reach those data or not?

A: Not all of this data is available via API today, but some of it is. There are two possible sources of this data via API:

*

*The Ads API has Audience Insights endpoints for whitelisted partners that provide insights into the audiences of advertisers. These include two endpoints: GET insights/accounts/:account_id and GET insights/accounts/:account_id/available_audiences

*The GNIP APIs also have an Audience Insights API in beta that exposes more data that the Ads API. The reference for this API is available now.


text:
Q: How can I open a certain file with a specific program which directories have special characters? Let's see if somebody can lend me a hand ;)
First of all, I would like to open specific files with specific programs that are not set as default. That's why I need a batch file.
I don't exactly know how to do it, but it would be something like:
start "C:\hello world\awesome program.exe" "C:\bye world\awesome file.bmp"

(I don't know if this code would work. Please, correct it if I'm wrong.)
Nevertheless, I have many folders with special characters since my native language is Spanish. Hence, I use characters such as 'á', 'é', 'ñ', etc.
As a result, if I do this:
start "C:\hola mundo\programa increíble.exe" "C:\adiós mundo\archivo increíble.bmp"

It kind of breaks because Command Promt doesn't seem to recognise these characters, namely 'í' and 'ó'.
I know this is a very specific question, but since I'm an absolute ignorant on this issues, I need some help.
Thank you very much!
P.S: I use Windows 10, if that helps.

A: Ok, I solved it. So for any Spanish speakers and other European people (French, Italian, German, Dutch, etc.), this could be important:
There is a problem assigning characters, so you have to change Code Page from 850 (default) to 1252 (Western European characters for Windows).
So the code is:
chcp 1252

start "" "C:\hola mundo\programa increíble.exe" "C:\adiós mundo\archivo increíble.bmp"

It is important to say that chcp changes your Code Page and that start command works like this:
start "TITLE" "PROGRAM DIRECTORY" "FILE DIRECTORY"

However, you can skip the title if you leave quotes alone:
start "" "PROGRAM DIRECTORY" "FILE DIRECTORY"

A: I'm thinking you need to save it as a utf-8 file instead of an ansi codepage file.  Lots of good editors allow you to set the encoding type on a file.


text:
Q: Why request.form from input fields not work? I have an HTML page with a form compiled yet with default values as a modify form, in python program i want to get the modified information, if there are. i have a ID to use for update the data in my DB with pymssql. When i get data from the form in HTML page, the ID it's get, but the CF block the program and give me the error: POST/[name_page] HTTP/1.1" 400
PYTHON
@app.route('/salva_modifiche_paziente',methods=['POST'])
def dati_paziente_modificato():
    id = dett_id_paz()
    cf = request.form.get['cf']
    nome = request.form['nome']
    cognome = request.form['cognome']
    data_nascita = request.form['data_nascita']
    residenza = request.form['residenza']
    grado_dolore = request.form['grado_dolore']
    sintomi = request.form['sintomi']
    data_ricovero = request.form['data_ricovero']
    data_dimissione = request.form['data_dimissione']
    reparto = request.form['reparto']
    n_stanza = request.form['n_stanza']
    n_letto = request.form['n_letto']

    modifica_paziente(id, cf, nome, cognome, data_nascita, residenza, grado_dolore, sintomi, data_ricovero,
                      data_dimissione, reparto, n_stanza, n_letto)

    dett = dettagli_paziente_ricoverato()

    return render_template('dettagli_paziente_ricoverato.html', det_paz=dett)

def modifica_paziente(id,cf,nome,cognome,data_nascita,residenza,grado_dolore,sintomi,data_ricovero,data_dimissione,reparto,n_stanza,n_letto):

    connection1 = pymssql.connect(database="UNICLINIC")
    connection2 = pymssql.connect(database="UNICLINIC")
    cursor1 = connection1.cursor()
    cursor2 = connection2.cursor()

    cursor1.execute("UPDATE paziente SET CF = (%s), nome = (%s), cognome = (&s), \
    data_di_nascita = (%s), residenza = (%s), grado_dolore = (%d), sintomi = (%s) WHERE ID_paziente = %d",(cf,nome,cognome,data_nascita,residenza,grado_dolore,sintomi, int(id) ))

    cursor2.execute("UPDATE ricoverato SET data_ricovero = (6s), \
    data_dimissione = (%s), COD_reparto = (%s), n_stanza = (%s), n_letto = (%s) \
    WHERE ID_paziente = (%d)"
                    ,(data_ricovero, data_dimissione, reparto, n_stanza, n_letto,int(id)))

    connection1.commit()
    connection2.commit()
    cursor1.close()
    cursor2.close()
    connection1.close()
    connection2.close()

def dett_id_paz():
    id = request.form['id_paziente']
    print(id)
    return id

HTML
<!DOCTYPE html>

        <meta charset="utf-8">
        <title>Modifica paziente | UNICLINIC</title>
        <link rel="stylesheet" href={{ url_for('static', filename='style.css') }} type="text/css" media="all"/>

                    <button class="menu_btn">HOME</button>
                    <button class="menu_btn">LOGIN</button>
                    <button class="menu_btn">CONTACTS</button>

                        Dati profilo di {{det_paz.nome}} {{det_paz.cognome}}

                <form id="modifica" method="post" action="salva_modifiche_paziente" class="form">

                        ID paziente:

                            {{det_paz.id}}
                                <input style="display:none" id="id_paziente" name="id_paziente" type="text" value="{{det_paz.id}}" />

                        Codice Fiscale:

                                <input type="text" id="cf" name="cf " value="{{det_paz.cf}}"/>

                        Nome:

                            <input type="text" id="nome" name="nome" value="{{det_paz.nome}}"/>

                        Cognome:

                            <input type="text" id="cognome" name="cognome" value="{{det_paz.cognome}}"/>

                        Data di nascita:

                            <input type="date" id="data_nascita" name="data_nascita" value="{{det_paz.data_nascita}}"/>

                        Residenza:

                            <input type="text" id="residenza" name="residenza" value="{{det_paz.residenza}}"/>

                        Grado dolore:

                            <select name="grado_dolore" id="grd_d">
                                {% for g in range(10) %}
                                    <option type="text" id="grado_dolore" name="grado_dolore" value="{{g+1}}">Grado {{g+1}}</option>
                                {% endfor %}
                            </select>

                        Sintomi:

                            <input type="text" id="sintmi" name="sintomi" value="{{det_paz.sintomi}}"/>

                        Data ricovero:

                            <input type="date" id="data_ricovero" name="data_ricovero" value="{{det_paz.data_ricovero}}"/>

                        Data dimissione:

                            <input type="date" id="data_dimissione" name="data_dimissione" value="{{det_paz.data_dimissione}}"/>

                        Reparto ricovero:

                            <select name="reparto" id="rep" class="p_dv">
                                {% for reparto in rep %}
                                    <option type="text" id="reparto" name="reparto" value="{{reparto.COD_reparto}}">{{reparto.COD_reparto}} - {{reparto.nome_reparto}}</option>
                                {% endfor %}
                            </select>

                        Stanza nr.:

                            <input type="text" id="n_stanza" name="n_stanza" value="{{det_paz.n_stanza}}"/>

                        Letto nr.:

                            <input type="text" id="n_letto" name="n_letto" value="{{det_paz.n_letto}}"/>

                        <button type="submit" form="modifica" class="menu_btn_d">CONFERMA</button>
                        <button type="reset" class="menu_btn_d">ANNULLA</button>

                </form>