text:
Q: PHP Mysqli Select values from multi table I create 2 database table , 1 is with customer order and 1 is with stock shop and website.
I want to show in order the stock. but i don't success to make the select DB with stock.
  <?php
                            $rowCount = count($_GET['bid_id']);
                            for($i=0;$i<$rowCount;$i++) {
                                $result = $DBcon->query("SELECT c.*, SUM(s.stoc) as stoc, SUM(s.stoc_rezervat) as stoc_rezervat, s.sku FROM comenzi_okazii AS c LEFT JOIN stocuri_mentor AS s ON c.nume_produs LIKE s.sku WHERE bid_id='$bid_id'");
                                while($row[$i] = $result->fetch_array()) {?>

                                        <td id="<?php echo $bid_id; ?>"><button type="button" class='btn btn-danger delete' id="<?php echo $row[$i]['id']; ?>"></button>
                                        <input class="form-control" required oninvalid="this.setCustomValidity('Cod Produs este Gol')" placeholder="Cod Produs" style="width:100%" type='text' id='cod_produs_1' name='nume_produs[]' value="<?php echo $row[$i]['nume_produs']; ?>"/>
                                        <input class="form-control qty_1" placeholder="Cantitate" style="width:100%" type="text" id="qty_1" name='qty[]' value="<?php echo $row[$i]['qty']; ?>"/>
                                        <input class="form-control" placeholder="Nume" style="width:100%" type='text' id='nume_1' name='nume_ales[]' value="<?php echo $row[$i]['nume_ales']; ?>"/>
                                        <input class="form-control" readonly placeholder="Stoc" style="width:100%" type='text' id='stoc_1' name='stoc_magazin[]' value="<?php echo $row[$i]['stoc']; ?>"/>
                                        <input class="form-control" readonly placeholder="Rezervat" style="width:100%" type='text' id='stoc_rez_1' name='stoc_rezervat[]' value="<?php echo $row[$i]['stoc_rezervat'];?>"/>

But don't work the stock or show the information only 1 product or hide all product and show only one.
Structure from DB comenzi_okazii saves the products that are in the order.
id - AI
bid_id - Number of Order
nume_produs - Product Code (SKU)
qty - Quantity of product in order
price - Price of Product

Structure from DB stocuri_mentor this my management program save the stock of
shop.
id - AI
sku - Product Code(SKU)
stoc - Product Stock
stoc_rezervat - Reserved stock

Thanks

A: The aggregate functions in the SELECT list (SUM(), without a GROUP BY clause means the query will return one row.
(Other relational databases would throw an error, with the non-aggregate expressions in the SELECT list not appearing in the GROUP BY clause. A non-standard extension specific to MySQL allows the query to execute, without throwing an error.)
Add a GROUP BY clause to get a row for each distinct value of an expression (or set of expressions)
For example:
  SELECT c.*
       , SUM(s.stoc) AS stoc
       , SUM(s.stoc_rezervat) AS stoc_rezervat
       , s.sku
    FROM comenzi_okazii c
    LEFT
    JOIN stocuri_mentor s
      ON c.nume_produs LIKE s.sku
   WHERE c.bid_id = 'somevalue'
   GROUP BY c.nume_produs
-- ^^^^^^^^^^^^^^^^^^^^^^                    -- *** add GROUP BY clause ***

Non-standard behavior of GROUP BY is documented in the MySQL Reference Manual
https://dev.mysql.com/doc/refman/5.6/en/group-by-handling.html

SQL Injection vulnerability
It's not at all clear what value $bid_id contains, and whether that value is guaranteed to be "safe" to include in the text of SQL statement. The code pattern appears to be vulnerable to SQL Injection. We don't see $bid_id is returned from mysqli_real_escape_string.
http://php.net/manual/en/mysqli.real-escape-string.php
The preferred pattern is to avoid including values in SQL text, and to instead use prepared statements with bind placeholders
See also:
https://xkcd.com/327/
https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet


text:
Q: Convergence of series $\sum\limits_{n=2}^\infty\frac{n^3+1}{n^4-1}$
Investigate the series for convergence and if possible, determine its
  limit: $\sum\limits_{n=2}^\infty\frac{n^3+1}{n^4-1}$

My thoughts
Let there be the sequence $s_n = \frac{n^3+1}{n^4-1}, n \ge 2$.
I have tried different things with no avail. I suspect I must find a lower series which diverges, in order to prove that it diverges, and use the comparison test.
Could you give me some hints as a comment? Then I'll try to update my question, so you can double-check it afterwards.
Update
$$s_n \gt \frac{n^3}{n^4} = \frac1n$$
which means that
$$\lim\limits_{n\to\infty} s_n > \lim\limits_{n\to\infty}\frac1n$$
but $$\sum\limits_{n=2}^\infty\frac1n = \infty$$
so $$\sum\limits_{n=2}^\infty s_n = \infty$$
thus the series $\sum\limits_{n=2}^\infty s_n$ also diverges.
The question is: is this formally sufficient?

A: $$\frac{n^3+1}{n^4-1}\gt\frac{n^3}{n^4}=\frac1n\;.$$

A: Use the limit comparison test with the series $1/1+1/2+1/3+...$

A: Try the limit comparison test with $\sum_{n=1}^\infty \frac1n$, i.e. calculatte the limit
$$\lim_{n\to\infty}\frac{\frac{n^3+1}{n^4-1}}{\frac1n}$$

A: Do you know the ratio test?
In this case, try to compare with $\sum_{n=0}^\infty \frac{1}{n}$.
EDIT. Ok, the reference was wrong. What I meant is the criterion which says: let $\sum a_n$ and $\sum b_n$ be two (positive) series, and assume
$$
\mathrm{lim}\ \frac{a_n}{b_n} = L, \qquad \text{with $L \neq 0,\infty$}
$$
then
$$
\sum a_n \quad \text{converges} \qquad \Longleftrightarrow \qquad \sum b_n \quad \text{converges} \ .
$$
Which in our case, says:
$$
\mathrm{lim}\ \frac{\frac{n^3+1}{n^4 -1}}{\frac{1}{n}} = \mathrm{lim}\ \frac{n^4 + n}{n^4 - 1} = 1 \ .
$$
Hence, as $\sum \frac{1}{n}$ diverges, so does $\sum \frac{n^3+1}{n^4 -1}$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Click function jquery not working I use tab bootstrap component like this

                        show == null || request()->show == 'published' ? 'active' : '' }}">Semua

                        show == 'draft' ? 'active' : '' }}">Draft

                        show == 'pending' ? 'active' : '' }}">Pending

And i handle when  click then redirect to different link
$("#show").click(function(e) {
      e.preventDefault();
      window.location =  updateURLParameter(window.location.href, "show", $(this).attr("data-show"));
   });

But the browser not redirect

A: Just use this:
$("#show").click(function(e) {
      e.preventDefault();
      window.location = '/data-show';
   });

A: The jquery selector has to be $("[id='idOfElement']") format.
So use:
$("[id='show']").click(function(e) {
    e.preventDefault();
    window.location =  updateURLParameter(window.location.href, "show",
$(this).attr("data-show"));
  });

A: I suggest this way
$("body #show").click(function(e) {
    console.log("It so ok");
    #your code
});

A: Because you use id, An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.I recommend switching to class,
$(".nav-item a").click(function(e) {
      e.preventDefault();
      window.location =  updateURLParameter(window.location.href, "show", $(this).attr("data-show"));
   });


text:
Q: Use different Android SDK (stock and custom) for each product flavor I need to build my app against both a stock Android SDK and a custom Android SDK for a specific device with AOSP modifications.
My thought was to use product flavors in my build.gradle to conditionally point to the correct SDK directory. Basically, I'm looking for something to the effect of:
productFlavors {
    stock {
        sdk.dir "/path/to/stocksdk"
    }
    mydevice {
        sdk.dir "/path/to/customsdk"
    }
}

Looking at the ProductFlavor DSL documentation, there isn't a property to set SDK directory.
What other ways could I achieve a similar result?

A: Interesting question but, unfortunately you cannot have different SDKs for productFlavors or buildTypes. You can have it only at the project level.

Product flavors can customize the following properties:
minSdkVersion
targetSdkVersion
versionCode
versionName
package name (overrides value from manifest)
release signing info (keystore, key alias, passwords,...).
BuildConfig: Ability to provide custom Java code.
NDK ABI filter (Not implemented yet)
test info
package name for test app (optional, default is <base>.test)
InstrumentationTestRunner class (optional)
Additionally, Product Flavor can provide their own source code, resources and manifest.

And

A Build Type provides configuration for the following build
  properties:
manifest debuggable flag
native compilation debug flag
proguard enabled + specific rules (Not implemented yet)
debug signing flag (ie whether to use debug key or release key)
package name suffix (2)
version name suffix (new in milestone 0.3)
Buildconfig
DEBUG flag. Set automatically based on the manifest debuggable flag.
Ability to provide custom Java code.

Source (Build System Concepts on http://tools.android.com/tech-docs/)

What other ways could I achieve a similar result?

You could make this project a library project and then create wrapper projects with different SDKs, just using the functionality in the library. So now you have a separate wrapper project instead of the productFlavors and you can change the sdk.dir for each wrapper project in the local.properties file.


text:
Q: distcp between nameservice1 and nameservice2 we have CDH 5.2 with Cloudera Manager 5.
We want to copy data from nameservice2 to nameservice1
Both clusters are on same CDH version
When I tried hadoop distcp hdfs://nameservice2/foo/bar hdfs://nameservice1/bar/foo
I got error
java.lang.IllegalArgumentException: java.net.UnknownHostException: nameservice2
So I added following config from Nameservice2 to Nameservice1
HDFS Client Advanced Configuration Snippet (Safety Valve) for hdfs-site.xml in Cloudera manager (Gateway Default Group)
<property>
<name>dfs.nameservices</name>
<value>nameservices2</value>
</property>
<property>
<name>dfs.client.failover.proxy.provider.nameservices2</name>
<value>org.apache.hadoop.hdfs.server.namenode.ha.ConfiguredFailoverProxyProvider</value>
</property>
<property>
<name>dfs.ha.namenodes.nameservices2</name>
<value>namenode36,namenode405</value>
</property>
<property>
<name>dfs.namenode.rpc-address.nameservices2.namenode36</name>
<value>hnn001.prod.cc:8020</value>
</property>
<property>
<name>dfs.namenode.servicerpc-address.nameservices2.namenode36</name>
<value>hnn001.prod.com:54321</value>
</property>
<property>
<name>dfs.namenode.http-address.nameservices2.namenode36</name>
<value>hnn001.prod.com:50070</value>
</property>
<property>
<name>dfs.namenode.https-address.nameservices2.namenode36</name>
<value>hnn001.prod.com:50470</value>
</property>
<property>
<name>dfs.namenode.rpc-address.nameservices2.namenode405</name>
<value>hnn002.prod.com:8020</value>
</property>
<property>
<name>dfs.namenode.servicerpc-address.nameservices2.namenode405</name>
<value>hnn002.prod.com:54321</value>
</property>
<property>
<name>dfs.namenode.http-address.nameservices2.namenode405</name>
<value>hnn002.prod.com:50070</value>
</property>
<property>
<name>dfs.namenode.https-address.nameservices2.namenode405</name>
<value>hnn002.prod.com:50470</value>
</property>

But I am still getting same error.
Any workaround this  ?
thanks

A: In HA enabled HDFS namenode nameservice1,nameservice2 are logical names, you cannot use ports along with that logical name.
you have two methods.
Easy method is to find the active namenodes and use the active namenode:port in  the distcp command as follows. Namenode web UI can be used for finding active namenodes of two clusters.
hadoop distcp hdfs://hnn001.prod.cc:8020:8020/foo/bar hdfs://<dest-cluster-active-nn-hostname>:8020/bar/foo

Another method is to use logical names of two clusters as follow, But before trying the below command make sure you have properly configured nameservice1 and nameservice2 in your client hdfs-site.xml.
hadoop distcp hdfs://nameservice2/foo/bar hdfs://nameservice1/bar/foo

Confiruting remote cluster's nameservice in local cluster.
Looks like nameservice2 is your local and nameservice1 is your remote. You need to keep the all associated properties of  nameservice1 and nameservice2 in the local cluster ie. Your local cluster's client hdfs-site.xml files should be as follows.
<configuration>
<!-- Available nameservices -->
<property>
<name>dfs.nameservices</name>
<value>nameservices1,nameservices2</value>
</property>

<!-- Local nameservice2 properties -->
<property>
<name>dfs.client.failover.proxy.provider.nameservices2</name>
<value>org.apache.hadoop.hdfs.server.namenode.ha.ConfiguredFailoverProxyProvider</value>
</property>
<property>
<name>dfs.ha.namenodes.nameservices2</name>
<value>namenode36,namenode405</value>
</property>
<property>
<name>dfs.namenode.rpc-address.nameservices2.namenode36</name>
<value>hnn001.prod.cc:8020</value>
</property>
<property>
<name>dfs.namenode.servicerpc-address.nameservices2.namenode36</name>
<value>hnn001.prod.com:54321</value>
</property>
<property>
<name>dfs.namenode.http-address.nameservices2.namenode36</name>
<value>hnn001.prod.com:50070</value>
</property>
<property>
<name>dfs.namenode.https-address.nameservices2.namenode36</name>
<value>hnn001.prod.com:50470</value>
</property>
<property>
<name>dfs.namenode.rpc-address.nameservices2.namenode405</name>
<value>hnn002.prod.com:8020</value>
</property>
<property>
<name>dfs.namenode.servicerpc-address.nameservices2.namenode405</name>
<value>hnn002.prod.com:54321</value>
</property>
<property>
<name>dfs.namenode.http-address.nameservices2.namenode405</name>
<value>hnn002.prod.com:50070</value>
</property>
<property>
<name>dfs.namenode.https-address.nameservices2.namenode405</name>
<value>hnn002.prod.com:50470</value>
</property>

<!-- Remote nameservice1 properties -->
<!-- You can find these properties in the remote machine's hdfs-site.xml file -->

<property>
<name>dfs.client.failover.proxy.provider.nameservices1</name>
<value>org.apache.hadoop.hdfs.server.namenode.ha.ConfiguredFailoverProxyProvider</value>
</property>
<property>
<name>dfs.ha.namenodes.nameservices1</name>
<value>namenodeXX,namenodeYY</value>
</property>
<property>
<name>dfs.namenode.rpc-address.nameservices1.namenodeXX</name>
<value><Remote-nn1>:8020</value>
</property>
<property>
<name>dfs.namenode.servicerpc-address.nameservices1.namenodeXX</name>
<value><Remote-nn1>:54321</value>
</property>
<property>
<name>dfs.namenode.http-address.nameservices1.namenode**XX**</name>
<value><Remote-nn1>:50070</value>
</property>
<property>
<name>dfs.namenode.https-address.nameservices1.namenodeXX</name>
<value><Remote-nn1>:50470</value>
</property>
<property>
<name>dfs.namenode.rpc-address.nameservices1.namenodeYY</name>
<value><Remote-nn2>:8020</value>
</property>
<property>
<name>dfs.namenode.servicerpc-address.nameservices1.namenodeYY</name>
<value><Remote-nn2>:54321</value>
</property>
<property>
<name>dfs.namenode.http-address.nameservices1.namenodeYY</name>
<value><Remote-nn2>:50070</value>
</property>
<property>
<name>dfs.namenode.https-address.nameservices1.namenodeYY</name>
<value><Remote-nn2>:50470</value>
</property>

<!-- Other properties -->

</configuration>

In the above configuration files replace all place holders like     YY  XX with corresponding values in the remote machine's hdfs site.xml.


text:
Q: Add a character for every 3 characters for UITextField I am trying to add a character while user is typing for every three characters, for example user types : 123456789 it should automatically change to 123,456,789. How can I add character in
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool

A: Here is a way how to do that:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    var proposedString = (textField.text as NSString?)!.replacingCharacters(in: range, with: string)

    // do whatever modifications you need to do, e.g. remove commas:
    proposedString = proposedString.replacingOccurrences(of: ",", with: "")
    let modulo = proposedString.count % 3
    for index in stride(from: modulo, to: proposedString.count, by: 3).reversed() {
        print(index)
        if index != 0 {
            proposedString.insert(",", at: proposedString.index(proposedString.startIndex, offsetBy: index))
        }
    }

    // manually set the new value
    textField.text = proposedString

    // don't let it update itself
    return false
}

Note: This little algorithm of mine works with commas only - you should therefore do adding the commas using Locale (docs), or NumberFormatter (docs) if the commas are part of how you present number in your country.

A: You should take into consideration that different regions across the world use different ways of formatting a number. To get around that fact, let iOS do the formatting for you.
This turns out to be exceptionally simple. The one line of code you require is:
NumberFormatter.localizedString(from: 123456 as NSNumber, number: NumberFormatter.Style.decimal)


text:
Q: Visual Studio Code Behind Missing After Windows 10 Error Now I'm speechless, when i was working on my visual studio project, I got windows 10 error (blue screen said, my PC ran into problem.....).
After i restart, one of my code behind files is missing, no one single line in it!!
Now I don't know what to do, is there any way to retrieve it back?
If i open it with Notepad++,
it shows like this

Thanks

A: Okay, it's all under control now.
I go to my visual studio project location, and found "Backup Files" folder there.
And I found a file there.
And it saved my time!!
Thanks


text:
Q: Secret agent that also sings opera and travels through windows I read this story about 5 years ago, but it was not new at the time. It was probably written in the 90s to early 2000s.
It was part of a series, I think referred to as the author's "Hundred World" saga. It was not the first book of the series.
I do not remember the cover.
The only details to the story I remember are these:
The main character is some sort of secret agent. He works for an organization that polices travel by these devices that allow you to step from one place to another.
At the beginning of the story, he's preparing to sing operatically for a sold-out audience, because his public identity is a world(s)-renowned singer. He prepares by drinking a special blend of tea and honey to soothe his throat.
The appearance was actually a bait tactic to lure out assassins. They appear (using the instant-travel devices, I think?). I can't remember how this scene ends.
I remember that this character's "boss" is someone they call a nickname like Chief, and Chief's history is classified. But, eventually you find out that the window devices that let you travel from place-to-place originally came from another world (maybe dimension?), and that the Chief came from this world (but was a child at the time). I remember this was supposed to be a big reveal, but since I didn't read the previous novel about Chief's character it didn't mean much to me.
I don't remember much else, aside from this book or another in the series taking place on a different planet where the government was either very religious or very picky about the language you spoke.
I may still own this book, but it's likely inaccessible in storage if it wasn't already donated.

A: John Barnes's ''The Armies of Memory''. Excerpt from Wikipedia:

Several attempts are made on Giraut's life as he works on his new Ix cycle of music. He is sent back to Wilson, his home planet and culture of Occitan, to complete the new music along with his Office of Special Projects team as protection. Paxa retires from the OSP and leaves Giraut after finding out she cannot be successfully backed up on a psypyx, which would make her death permanent. Giraut begins to fall in love with a fellow musician Azalais who introduces him to Ebles, a contact for rogue colonies outside of Council space which call themselves the Union. Soon after, Azalais is killed and Giraut is severely injured in another assassination attempt.

It's part of the "Thousand Cultures" series and involves "the springer", a "method of instantaneous transportation which is quickly reuniting humanity across known space." It's the fourth and final (so far) book of the series.


text:
Q: how to acess Struct property by name as a string in runtime in swiftui i have an JSON RESPONSE
 result:
        [
            Result(date: "2022-04-24", abc: 1463, def: 0, ghi: 0.0),
            Result(date: "2022-04-25", abc: 1451, def: 0, ghi: 0.0),
            Result(date: "2022-04-26", abc: 24838, def: 100, ghi: 25.0),
            Result(date: "2022-04-27", abc: 72833, def: 461, ghi: 115.25),
            Result(date: "2022-04-28", abc: 31881, def: 0, ghi: 0.0),
            Result(date: "2022-04-29", abc: 18706, def: 0, ghi: 0.0)
        ],

, now in my code i am using picker and have to dynamically change the key
**example--->**
result.abc,
result.def,
result.ghi

Code where i have to dynamically change
HStack{

ForEach(downloads.indices, id: \.self){ index in

                if index == downloads.count-1 {

                    Text("\(downloads[index].abc)")
                        .font(.largeTitle.bold())
                        .foregroundColor(.white)

                }

            }
        }
        .frame(maxWidth: .infinity, alignment: .leading)

You can see in above code
downloads[index].**abc**

in place of this i need to change def and ghi but dhynamically
In my Home View where i call above file
@State var selectedScreen: [String] = ["abc","def", "ghi"]
BarGraph(downloads: dataservice.statsdetails, value: selectedScreen[pickerSelectedItem])

but if i pass it dynamically as a string it gives me error
  [1]: https://i.stack.imgur.com/l6kna.png

Can you help me how to solve this

A: A straightforward way is to add a function to your struct that returns the right value for a given key.
func stringProperty(for path: String) -> String {
    switch path {
    case "abc":
        return "\(abc)"
    case "def":
        return "\(def)"
    case "ghi":
        return "\(ghi)"
    default:
        fatalError("Unknown property name")
    }
}


text:
Q: How would I implement this table configuration in SQLalchemy and flask I need to add a column to the File class that would store all the allowed viewers but I'm confused on how I would do that. Do I need a whole new table or do I need to make it a Many-to-many relationship. TY
from flask_login import UserMixin
from . import db

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key = True)
    email = db.Column(db.String(1000), unique = True)
    name = db.Column(db.String(1000))
    password = db.Column(db.String(1000))
    isAdmin = db.Column(db.Boolean(), deafault = False)
    files = db.relationship("File")

class File(db.Model):

    id = db.Column(db.Integer, primary_key = True)
    filePath = db.Column(db.String(1000), unique = True)
    fileName = db.Column(db.String(1000))
    authorizedViewers = ???
    fileOwnerId = db.Column(db.Integer, db.ForeignKey("user.id"))


text:
Q: Typescript dynamic module loading at runtime I have defined an abstract BaseClass in a NodeJS Typescript project and I have a list of derived classes that implement and extend this BaseClass.
// baseModule.ts
export abstract class BaseClass {
  constructor() {}
  abstract method(): void;
}

export interface ModuleConstructor<T extends BaseClass> {
  new (): T
}

export function createModule<T extends BaseClass>(type: ModuleConstructor<T>): T {
  return new type();
}

I am trying to find a way to programmatically at runtime create an instance of one of these classes.
The constraint here is that I would like to be able to drop a new myDerivedClass.ts file into my project folder and have it be automatically included in a list of available modules at runtime.
The developer workflow would be 1) create new file myNewModule.ts 2) create and export a class that extends BaseClass 3) save myNewModule.ts to ./myModules
// ./myModules/myNewModule.ts
export class MyModule extends BaseClass {
  constructor() {
    super()
  }

  method() {
    //Do something custom
  }
}

The runtime flow (ideally without having to rebuild) would be 1) User selects from a list of available modules 2) createModule Factory function creates a new instance of chosen module and passes as an instance of
// someOtherClass.ts

const modules = require('./myModules/*') //<- Something to this effect
import { BaseClass, createModule, ModuleConstructor } from './BaseClass'

export class SomeOtherClass {
  public mod: BaseClass
  constructor(mod: ModuleConstructor) {
    this.mod = createModule(mod)
  }
}

for (let m in modules) {
  console.log(modules[m].name);
}

let someObj = SomeOtherClass(modules[m]);
someObj.mod // <- instance of derived class.

A: Here is the solution that I ended up using, perhaps there is an easier way though.
1) Create a dynamic module loader function
2) Use NodeJS fs module to scan the directory containing the modules
3) Iterate through each file and dynamic import the file into an array
// BaseModule.ts
import * as path from 'path'
import { promisify } from 'utils'

const readdirAsync = promisify(fs.readdir);

export async function loadModules() {
  let files = await readdirAsync(path.resolve(__dirname, 'rel/path/to/modules'));
  let imports = await Promise.all(files.map(file => (
    import(path.resolve(__dirname, '..', './exchanges/brokers', file))))
  )

  // this next part will depend on how you're exporting within
  // the module. In my case, each module has an "export class"
  // statement. Typically you would "import { className } from 'moduleName'"

  let moduleNames: { [name: string]: number } = {};
  let modules: ModuleConstructor<BaseClass>[] = [];
  for (let i in imports) {
    Object.keys(imports[i]).forEach((key: string) => {
      moduleNames[key] = modules.length;
      modules.push(imports[i][key])
    })
  }
  return [moduleNames, modules];
}

// someOtherClass.ts
import { BaseClass, loadModules, ModuleConstructor } from './BaseClass'

export class SomeOtherClass<T extends BaseClass> {
  public mod: T
  constructor(mod: T ) {
    this.mod = mod;
  }
}

loadModules()
  .then(([moduleNames, modules]: [string[], ModuleConstructor<BaseClass>[]] => {

    // not necessary, but just for purpose of demonstration
    let names: string[] = Object.keys(moduleNames);
    let name = names[0]; // pick one of the module names

    // use the name dictionary as a lookup into the constructor array
    let someObj = SomeOtherClass(new modules[moduleNames[name]]);
    someObj.mod // <- instance of derived class.
  })
  .catch((err) => {
    console.log(err.message);
  });

After doing this I realized that NPM package systemJS handles dynamic loader.


text:
Q: How to create a many to many relationship in a view Let me be more specific in my question.
I have a many to many relationship. I have an Opportunity and I have items.
In my Opportunity/Create view I want to be able to "add" as many items from the items list as I want. So when I click the save button on the create form, I would be potentially saving many items that would be associated with this record.
So the only way to do this is to include a click box for every item in my items table? How would I do something like Click this button to insert a new item from a drop down list?
Models:
public class Opportunity
{
    public int Id { get; set; }
    public string MyOpportunity { get; set; }
}

public class Items
{
    public int Id { get; set; }
    public string ItemName { get; set; }

}

public class ItemsToOpportunity
{
    public int Id { get; set; }
    public int OpportunityId { get; set; }
    public int ItemId { get; set; }

}

A: Based on your question and comment, it sounds like you just need to provide a form with multiple checkboxes or so.
Then, when you post to the server, the shared name of the checkboxes becomes a comma delimited set of Ids to use.
 <input type="checkbox" name="myNewOpportunityItems" value="1">Item 1
 <input type="checkbox" name="myNewOpportunityItems" value="2">Item 1
 <input type="checkbox" name="myNewOpportunityItems" value="3">Item 1
 <input type="checkbox" name="myNewOpportunityItems" value="4">Item 1

Then, when the user selects the checkboxes of the items they want to associate, that gets posted as a comma delimited string:
 public ActionResult MyPostActionResult(string myNewOpportunityItems)
 {
       // myNewOpportunityItems == "1,3,4";
 }


text:
Q: Chid items not displaying in mat navigation I wanted to render multiple level naviation using angular matrial design.
Below is the sample nav data,
navData=[{url:"/index",description:"Main Nav 1",children:[{url:"/index",description:"Sub Child 1"},{url:"/index",description:"Sub Child 2"},{url:"/index",description:"Sub Child 3"},{url:"/index",description:"Sub child 4",children:[{url:"/index",description:"Child 1 of Sub Child 4"}]},{url:"/index",description:"Sub Child 5",children:[{url:"/index",description:"Child 1 of Sub Child 5"}]},{url:"/index",description:"Sub Child 6"}]}];

In the sample data, It as 3 level.
Currently I'm displaying first level of navigation.
How to display it's child nav. Please help.
My StackBlitz link https://stackblitz.com/edit/angular-xszcga?file=app/sidenav-overview-example.html
My HTML code,
<mat-sidenav-container class="example-container">
    <mat-sidenav mode="side" opened>
        <mat-nav-list>
            <mat-list-item *ngFor="let nav of navData">
                {{nav.description}}
            </mat-list-item>
        </mat-nav-list>
    </mat-sidenav>
    <mat-sidenav-content>Main content</mat-sidenav-content>
</mat-sidenav-container>

A: You can use ng-template to nest mat-nav-list using [ngForOf] by accessing the children property of the upper levels of your navigation.
<mat-sidenav-container class="example-container">
    <mat-sidenav mode="side" opened>
        <mat-nav-list>
          <ng-template ngFor let-nav [ngForOf]="navData">
            <mat-list-item (click)="toggle(nav)">
              {{nav.description}}
            </mat-list-item>
            <ng-template [ngIf]="nav.open">
              <mat-nav-list>
                <ng-template ngFor let-child [ngForOf]="nav.children">
                  <mat-list-item (click)="toggle(child)">
                    {{child.description}}
                  </mat-list-item>
                  <ng-template [ngIf]="child.open">
                    <mat-nav-list>
                      <mat-list-item *ngFor="let child2 of child.children">
                        {{child2.description}}
                      </mat-list-item>
                    </mat-nav-list>
                  </ng-template>
                </ng-template>
              </mat-nav-list>
            </ng-template>
          </ng-template>
        </mat-nav-list>
    </mat-sidenav>
    <mat-sidenav-content>Main content</mat-sidenav-content>
</mat-sidenav-container>

and add toggle = nav => nav.open = !nav.open; inside the component in your TS file


text:
Q: mysqldump fails with "Skipping dump data for table 'table1', it has no fields" I'm running mysqldump from an older mysql database. The mysqldump is part of a mariadb distribution if it matters.
When I run mysqldump locally, it's fine. When I run it on a remote system, I get no data dumped. If I run it with mysqldump -v the last line is
Skipping dump data for table 'table1', it has no fields

A: From some googling and this reddit thread, I determined that you need to set the default locale.
So the command that worked for me was:
mysqldump --default-character-set=latin1 --lock-tables=false --single-transaction=TRUE --host=$HOST --user=$USER --password=$PASSWORD $DB

I used both lock-tables and single transaction because I have a mix of myisam and innodb tables.


text:
Q: MonoDroid lacks support for System.IO.Ports I have an application written in C# .NET 4.0. I consider using MonoDroid for making it run also on Android systems. Thing is, the application relies heavily on .NET Framework namespace System.IO.Ports which doesn't seem to exist in MonoDroid. What solution is there for me, so I could still use MonoDroid?

A: I've added an enhancement request for serial port support to Mono for Android:
https://bugzilla.novell.com/show_bug.cgi?id=687407
However, I'm not sure how useful it would be, as cursory searching suggests that a custom Linux kernel is needed in order to get RS232 serial port support on Android, so that may be a bit of a non-starter.
There's also android-serialport-api...but the wiki also suggests recompiling the kernel.
Assuming you want this for "normal" use (deployment on the Android Market, etc.), I'm not sure serial ports are supportable in any form.

A: If you just need some simple code constructs, you could grab some code from the mono github repo. Of course not everything in the main mono repo may work in MonoDroid, but some stuff like enums should copy/paste without issue. Ultimately though, as far as I've seen, you don't get an actual serial port in Android.
As stated by others, there may be a way to hack serial onto your device. However you might be better off exploring a bluetooth or wifi serial adapter. (Bluetooth SPP is available for Android, but might not be for iOS, so if you want to cover both you may want to go wifi.) You could then perhaps create your own System.IO.Ports.SerialPort implementation to wrap it inside your MonoDroid project.
I have not done this myself, but it is something I've explored.


text:
Q: Wordpress function.php file --- unexpected end of file I'm trying to modify a Wordpress child theme's function.php file by introducing a new function. However, system keeps showing an error after I add the function. This is the original code without the added function yet (which works perfectly fine):
<?php
/*
* Custom functions that overwrites original Travelify functionality
*/
add_action( 'wp_enqueue_scripts', 'travelify_enqueue_styles' );
function travelify_enqueue_styles() {
    wp_enqueue_style( 'travelify-parent-style', get_template_directory_uri() . '/style.css' );
}
?>

And this is after adding the new function --- which results in an error:
<?php
/*
* Custom functions that overwrites original Travelify functionality
*/
add_action( 'wp_enqueue_scripts', 'travelify_enqueue_styles' );
function travelify_enqueue_styles() {
    wp_enqueue_style( 'travelify-parent-style', get_template_directory_uri() . '/style.css' );
}

if ( ! function_exists( 'travelify_setup' ) ):

function travelify_setup() {
    /** Load Structure */
    require( get_template_directory() . '/library/structure/header-extensions.php' );
    require( get_template_directory() . '/library/structure/sidebar-extensions.php' );
    require( get_template_directory() . '/library/structure/footer-extensions.php' );
    require( get_template_directory() . '/library/structure/content-extensions.php' );
    /**
}

endif; // travelify_setup

?>

System keeps pointing to ?> as an unexpected end of file. I'm not an expert in coding so I'm not sure why such an error keeps showing up.
Thanks in advance for any feedback.


text:
Q: How to create a File Upload with progress data? I'm developing a web (using asp.net and c#) which has a FileUpload control from asp.net. The upload thing works perfect and as far as I know I can't show progress data (%, bytes transfered, upload speed, time elapsed, time left, progress bar) using the FileUpload control from asp.net because its not asyncrhonous.
I've searched a lot (really) on the internet and I didn't find what i'm looking for and too much info has become a big confusion since I'm not sure about what I have to use.
On my web page I have a file named "UploadFile.aspx" which has a FileUpload control and a button that handles the uploading. On code-behind (UploadFile.aspx.cs) I have all the server-side logic (Upload the file into specific folder, store info about that file into a database, etc. etc) and I don't want to change this.
What I need to know is how to show the progress data to the user while is uploading the file? I can't use 3rd party applications because this is for an important commercial site. It's not a problem for me if I have to learn javascript / jQuery / Whatever but really i'm a bit lost and I don't know how to start.
Thanks for your time and your help guys.

A: There's some pretty cool solutions out there.  Granted, you can code your own, but I'd suggest using a jQuery plugin like Plupload.  If you need help setting it up, you can read their documentation.

A: There are lots of lots of demo code are available on the net to show the progress bar with file upload control in c#, most of them work fine on Local system but never work on the live server, Because You CAN'T USE A FileUpload control for what you want to do. When a user POSTs a file, you have to think of it like a querystring parameter. It goes as one Http Request. If you want to do a progress bar you'll want to look into something that can interact with the server asynchronously.

A: If you don't want to use any 3rd party that relies on Flash / Html 5, please take a look at this article:
http://vanacosmin.ro/Articles/Read/AjaxFileUpload
This is possible (and if you're using .NET 4.5 GetBufferedInputStream will make your life easier), but it is not very easy, as you'll see.
Basically, if you want a file upload with progress bar that is fully compatible with every browser, you need to handle this server side and give an url where the client (the browser) can check periodically for the progress with ajax.


text:
Q: Endless terrain in jMonkey using TerrainGrid I have started to learn game development using jMonkey engine. I am able to create single tile of terrain using TerrainQuad but as the next step i m stuck at making it infinite. I have gone through the wiki and want to use the TerrainGrid class but my code doesnot seem to work. I have looked around on the web and searched other forums but cannot find any other code example to help.
I believe in the below code, ImageTileLoader returns an image which is the heightmap for that tile. i have modified it to return the same image every time. But all i see is a black window.
The Namer method is not even called. Appreciate if someone can help with some example or tutorial on net.
terrain = new TerrainGrid("terrain", patchSize, 513, new ImageTileLoader(assetManager, new Namer() {
        public String getName(int x, int y) {
            //return "Scenes/TerrainMountains/terrain_" + x + "_" + y + ".png";
            System.out.println("X = " + x + ", Y = " + y);
            return "Textures/heightmap.png";
        }
    }));

These are my sources:
jMonkeyEngine 3 Tutorial (10) - Hello Terrain, TerrainGridTest.java, ImageTileLoader
This is the result when i use TerrainQuad
My full code,
// Sample 10 - How to create fast-rendering terrains from heightmaps, and how to
// use texture splatting to make the terrain look good.
public class HelloTerrain extends SimpleApplication {

    private TerrainQuad terrain;
    Material mat_terrain;
    private float grassScale = 64;
    private float dirtScale = 32;
    private float rockScale = 64;

    public static void main(String[] args) {
        HelloTerrain app = new HelloTerrain();
        app.start();
    }
    private FractalSum base;
    private PerturbFilter perturb;
    private OptimizedErode therm;
    private SmoothFilter smooth;
    private IterativeFilter iterate;

    @Override
    public void simpleInitApp() {
        flyCam.setMoveSpeed(200);

        initMaterial();

        AbstractHeightMap heightmap = null;
        Texture heightMapImage = assetManager.loadTexture("Textures/heightmap.png");
        heightmap = new ImageBasedHeightMap(heightMapImage.getImage());
        heightmap.load();

        int patchSize = 65;
        //terrain = new TerrainQuad("my terrain", patchSize, 513, heightmap.getHeightMap()); // * This Works but below doesnt work*

        terrain = new TerrainGrid("terrain", patchSize, 513, new ImageTileLoader(assetManager, new Namer() {
            public String getName(int x, int y) {
                //return "Scenes/TerrainMountains/terrain_" + x + "_" + y + ".png";
                System.out.println("X = " + x + ", Y = " + y);
                return "Textures/heightmap.png";
                // set to return the sme hieghtmap image.
            }
        }));

        terrain.setMaterial(mat_terrain);
        terrain.setLocalTranslation(0,-100, 0);
        terrain.setLocalScale(2f, 1f, 2f);
        rootNode.attachChild(terrain);

        TerrainLodControl control = new TerrainLodControl(terrain, getCamera());
        terrain.addControl(control);
    }

    public void initMaterial() {
        // TERRAIN TEXTURE material
        this.mat_terrain = new Material(this.assetManager, "Common/MatDefs/Terrain/HeightBasedTerrain.j3md");

        // GRASS texture
        Texture grass = this.assetManager.loadTexture("Textures/white.png");
        grass.setWrap(WrapMode.Repeat);
        this.mat_terrain.setTexture("region1ColorMap", grass);
        this.mat_terrain.setVector3("region1", new Vector3f(-10, 0, this.grassScale));

        // DIRT texture
        Texture dirt = this.assetManager.loadTexture("Textures/white.png");
        dirt.setWrap(WrapMode.Repeat);
        this.mat_terrain.setTexture("region2ColorMap", dirt);
        this.mat_terrain.setVector3("region2", new Vector3f(0, 900, this.dirtScale));

        Texture building = this.assetManager.loadTexture("Textures/building.png");
        building.setWrap(WrapMode.Repeat);

        this.mat_terrain.setTexture("slopeColorMap", building);
        this.mat_terrain.setFloat("slopeTileFactor", 32);

        this.mat_terrain.setFloat("terrainSize", 513);
    }
}

A: So, I worked further on my problem and was able to achieve what I wanted to. But I still cannot understand what was the error on my first code. Below is the final code that I got by modifying the TerrainGrid example from here. Below is the final code for anyone who falls into the same situation. It is not the final thing but does answer my question above.
public class TerrainGridTest extends SimpleApplication {

    private Material mat_terrain;
    private TerrainGrid terrain;
    private float grassScale = 64;
    private float dirtScale = 16;

    public static void main(final String[] args) {
        TerrainGridTest app = new TerrainGridTest();
        app.start();
    }

    @Override
    public void simpleInitApp() {
        this.flyCam.setMoveSpeed(100f);
        initMaterial();
        initTerrain();
        this.getCamera().setLocation(new Vector3f(0, 200, 0));
        this.getCamera().lookAt(new Vector3f(0,0,0), Vector3f.UNIT_Y);
        this.viewPort.setBackgroundColor(new ColorRGBA(0.7f, 0.8f, 1f, 1f));
        initLight();
    }

    @Override
    public void simpleUpdate(final float tpf) {

    }

    public void initMaterial() {
        // TERRAIN TEXTURE material
        this.mat_terrain = new Material(this.assetManager, "Common/MatDefs/Terrain/HeightBasedTerrain.j3md");

        // GRASS texture
        Texture grass = this.assetManager.loadTexture("Textures/white.png");
        grass.setWrap(WrapMode.Repeat);
        this.mat_terrain.setTexture("region1ColorMap", grass);
        this.mat_terrain.setVector3("region1", new Vector3f(-10, 0, this.grassScale));

        // DIRT texture
        Texture dirt = this.assetManager.loadTexture("Textures/white.png");
        dirt.setWrap(WrapMode.Repeat);
        this.mat_terrain.setTexture("region2ColorMap", dirt);
        this.mat_terrain.setVector3("region2", new Vector3f(0, 900, this.dirtScale));

        // ROCK texture
        //Texture rock = this.assetManager.loadTexture("Textures/Terrain/Rock2/rock.jpg");
        Texture building = this.assetManager.loadTexture("Textures/building.png");
        building.setWrap(WrapMode.Repeat);

        this.mat_terrain.setTexture("slopeColorMap", building);
        this.mat_terrain.setFloat("slopeTileFactor", 32);

        this.mat_terrain.setFloat("terrainSize", 513);
    }

    private void initLight() {
        DirectionalLight light = new DirectionalLight();
        light.setDirection((new Vector3f(-0.5f, -1f, -0.5f)).normalize());
        rootNode.addLight(light);
    }

    private void initTerrain() {
        this.terrain = new TerrainGrid("terrain", 65, 257, new ImageTileLoader(assetManager, new Namer() {

            public String getName(int x, int y) {
               //return "Interface/Scenes/TerrainMountains/terrain_" + x + "_" + y + ".png";
                return "Textures/heightmap.png";
            }
        }));

        this.terrain.setMaterial(mat_terrain);
        this.terrain.setLocalTranslation(0, 0, 0);
        this.terrain.setLocalScale(3f, 1.5f, 3f);
        this.rootNode.attachChild(this.terrain);

        TerrainLodControl control = new TerrainGridLodControl(this.terrain, getCamera());
        control.setLodCalculator( new DistanceLodCalculator(65, 2.7f) ); // patch size, and a multiplier
        this.terrain.addControl(control);
    }
}


text:
Q: Google Analytics API V3 with PHP returns blank page I'm trying to display some basic Google Analytics information about my website using the Google Analytics Reporting API and Oauth 2.0. I've been trying to make it work for hours, but in vain.
I've copied and edited the code from this topic. Everything should work correctly, but somehow when I view the page in my browser, I only see a blank page.
I have:

*

*Created a Service Account in the Google API Console.

*Enabled the Google Analytics API in the Google API Console.

*Added the e-mail address of the service account to Google Analytics.

The code ('XXXX' means I've filtered out personal information):
<?php

require_once 'google-api/src/Google/Client.php';
require_once 'google-api/src/Google/Service/Analytics.php';

$keyfile = 'XXXX.p12';

// Initialise the Google Client object
$client = new Google_Client();
$client->setApplicationName('Application Name');

$client->setAssertionCredentials(
    new Google_AssertionCredentials(
        'XXXX@developer.gserviceaccount.com',
        array('https://www.googleapis.com/auth/analytics.readonly'),
        file_get_contents($keyfile)
    )
);

// Get this from the Google Console, API Access page
$client->setClientId('XXXX.apps.googleusercontent.com');
$client->setAccessType('offline_access');
$analytics = new Google_AnalyticsService($client);

// We have finished setting up the connection,
// now get some data and output the number of visits this week.

// Your analytics profile id. (Admin -> Profile Settings -> Profile ID)
$analytics_id   = 'XXXX';
$lastWeek       = date('Y-m-d', strtotime('-1 week'));
$today          = date('Y-m-d');

try {
    $results = $analytics->data_ga->get($analytics_id,
                        $lastWeek,
                        $today,'ga:visits');
    echo '<b>Number of visits this week:</b> ';
    echo $results['totalsForAllResults']['ga:visits'];
} catch(Exception $e) {
    echo 'There was an error : - ' . $e->getMessage();
}

?>

I've struggled with this for a very long time, any help would be greatly appreciated!


text:
Q: dbms_lob.append cannot append a string to a bind variable Would someone please point out what I am missing here?
Below is a minimal example:
var c clob
exec dbms_lob.append(:c, 'test')
print c

It produces this error:
BEGIN dbms_lob.append(:c, 'test'); END;
Error report -
ORA-06502: PL/SQL: numeric or value error: invalid LOB locator specified: ORA-22275
ORA-06512: at "SYS.DBMS_LOB", line 656
ORA-06512: at line 1
06502. 00000 -  "PL/SQL: numeric or value error%s"
*Cause:    An arithmetic, numeric, string, conversion, or constraint error
           occurred. For example, this error occurs if an attempt is made to
           assign the value NULL to a variable declared NOT NULL, or if an
           attempt is made to assign an integer larger than 99 to a variable
           declared NUMBER(2).
*Action:   Change the data, how it is manipulated, or how it is declared so
           that values do not violate constraints.

I checked the Oracle docs about bind variables, which says

When you execute a VARIABLE ... CLOB or NCLOB command, SQL*Plus associates a LOB locator with the bind variable.

So I don't think it is because there is no locator allocated to c.

A: You need to 'create' the lob before using it like this.
SQL> var c clob
SQL> exec dbms_lob.createtemporary(:c,false);

PL/SQL procedure successfully completed.

SQL> exec dbms_lob.append(:c,'acb');

PL/SQL procedure successfully completed.

SQL> print :c

C
--------------------------------------------------------------------------------
acb


text:
Q: Log4net not inserting into the database? I have log4net setup and configured to insert into a sql server 2005 table. My table is called Log. When I call the log4net method it does not enter any data into the log database in sql server. I am not getting any errors from my client c# code. Do I need to add a user to the log table in sql? Right now I am using windows authentication.
<configSections>
  <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
 <appender name="ADONetAppender" type="log4net.Appender.ADONetAppender">
   <bufferSize value="100" />
   <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
connectionString value="Data Source=V-FIN-SQL-D\SQL2005;Initial Catalog=DevMHAIC;Integrated Security=True;Connection Timeout=360" />
  <commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES
       (@log_date, @thread, @log_level, @logger, @message, @exception)" />
 <parameter>
   <parameterName value="@log_date" />
        <dbType value="DateTime" />
<layout type="log4net.Layout.RawTimeStampLayout" />
  </parameter>
   <parameter>
 <parameterName value="@thread" />
     <dbType value="String" />
   <size value="32" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%t" />
 </layout>
 </parameter>
   <parameter>
    <parameterName value="@log_level" />
    <dbType value="String" />
    <size value="512" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%p" />
    </layout>
  </parameter>
   <parameter>
    <parameterName value="@logger" />
    <dbType value="String" />
    <size value="512" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%c" />
    </layout>
  </parameter>
  <parameter>
    <parameterName value="@message" />
    <dbType value="String" />
    <size value="4000" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%m" />
    </layout>
  </parameter>
   <parameter>
    <parameterName value="@exception" />
    <dbType value="String" />
    <size value="2000" />
    <layout type="log4net.Layout.ExceptionLayout" />
  </parameter>
</appender>
<root>
  <level value="DEBUG" />
  <appender-ref ref="ADONetAppender" />
</root>
</log4net>

Here is my sql code for the log database:
CREATE TABLE [dbo].[Log](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Date] [datetime] NULL,
[Thread] [varchar](255) NULL,
[Level] [varchar](50) NULL,
[Logger] [varchar](255) NULL,
[Message] [varchar](4000) NULL,
[Exception] [varchar](2000) NULL
) ON [PRIMARY]

Here is my class that I am using to call the log4net.
public class ErrorLog : ILog
{
    log4net.ILog _Log;

    /// <summary>
    /// Initializes a new instance of the <see cref="ErrorLog"/> class.
    /// </summary>
    /// <param name="log">The log.</param>
    public ErrorLog(log4net.ILog log) : this()
    {
        _Log = log;
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="ErrorLog"/> class.
    /// </summary>
    public ErrorLog()
    {
        _Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        log4net.Config.XmlConfigurator.Configure();
    }

    /// <summary>
    /// Informationals the specified message.
    /// </summary>
    /// <param name="message">The message.</param>
    public void informational(string message)
    {
        _Log.Info(message);
    }

    /// <summary>
    /// Informationals the specified message.
    /// </summary>
    /// <param name="message">The message.</param>
    /// <param name="innerException">The innerException.</param>
    public void informational(string message, Exception innerException)
    {
        _Log.Info(message, innerException);
    }

    /// <summary>
    /// Debugs the specified message.
    /// </summary>
    /// <param name="message">The message.</param>
    public void debug(string message)
    {
        _Log.Debug(message);
    }

    /// <summary>
    /// Debugs the specified message.
    /// </summary>
    /// <param name="message">The message.</param>
    /// <param name="innerException">The innerException.</param>
    public void debug(string message, Exception innerException)
    {
        _Log.Debug(message, innerException);
    }

    /// <summary>
    /// Errors the specified message.
    /// </summary>
    /// <param name="message">The message.</param>
    public void error(string message)
    {
        _Log.Error(message);
    }

    /// <summary>
    /// Errors the specified message.
    /// </summary>
    /// <param name="message">The message.</param>
    /// <param name="innerException">The innerException.</param>
    public void error(string message, Exception innerException)
    {
        _Log.Error(message, innerException);
    }

    /// <summary>
    /// Warnings the specified message.
    /// </summary>
    /// <param name="message">The message.</param>
    public void warning(string message)
    {
        _Log.Warn(message);
    }

    /// <summary>
    /// Warnings the specified message.
    /// </summary>
    /// <param name="message">The message.</param>
    /// <param name="innerException">The innerException.</param>
    public void warning(string message, Exception innerException)
    {
        _Log.Warn(message, innerException);
    }
}

Here is my interface:
public interface ILog
{
    /// <summary>
    /// Informationals the specified message.
    /// </summary>
    /// <param name="message">The message.</param>
    void informational(string message);

    /// <summary>
    /// Informationals the specified message.
    /// </summary>
    /// <param name="message">The message.</param>
    /// <param name="innerException">The innerException.</param>
    void informational(string message, Exception innerException);

    /// <summary>
    /// Debugs the specified message.
    /// </summary>
    /// <param name="message">The message.</param>
    void debug(string message);

    /// <summary>
    /// Debugs the specified message.
    /// </summary>
    /// <param name="message">The message.</param>
    /// <param name="innerException">The innerException.</param>
    void debug(string message, Exception innerException);

    /// <summary>
    /// Errors the specified message.
    /// </summary>
    /// <param name="message">The message.</param>
    void error(string message);

    /// <summary>
    /// Errors the specified message.
    /// </summary>
    /// <param name="message">The message.</param>
    /// <param name="innerException">The innerException.</param>
    void error(string message, Exception innerException);

    /// <summary>
    /// Warnings the specified message.
    /// </summary>
    /// <param name="message">The message.</param>
    void warning(string message);

    /// <summary>
    /// Warnings the specified message.
    /// </summary>
    /// <param name="message">The message.</param>
    /// <param name="innerException">The innerException.</param>
    void warning(string message, Exception innerException);
}

A: <bufferSize value="100" />

It is saying that it will keep 100 logs in memory until written into DB. Maybe that's why you don't see anything in DB?

A: I don't really have any insight to your problem just by looking at your configuration, but you might try adding this to your app settings to see if log4net can tell you what is going wrong:
<appSettings>
  <add key="log4net.Internal.Debug" value="true"/>
</appSettings>

See the section titled "How do I enable log4net internal debugging?" for a description of how to capture log4net's internal logging.

A: I had the same problem.  In my case, I had to remove the use of [Exception] and @exception from the insert.
So, I had to change my logging too.  I basically had to create a nice dump of my exception and pass that into the message parameter.
I hope this helps

A: Unless you specifically set a user in your connection string Log4Net will attempt to log with whatever user account is assigned to the process (ASP.NET worker process if that is the case). Log4Net also will not throw exceptions if you it is unable to log. You can turn on debugging to see what the issue is.


text:
Q: How can I apply a hook to multiple Emacs modes at once? I was reading an article about well-formatted Git commits, and I was wondering how I could apply some of the rules to the Magit log mode.
It seems to use 3 major modes simultaneously: Magit, Log, Edit.
So how would I get just those modes, when used together, to hard-wrap at 72 characters automatically?

A: Emacs modes have "base modes" which is to say bade modes.  For example python-mode extends prog-mode which itself extends fundamental-mode.  All modes extend fundamental-mode.  So to hook python-mode plus c-mode but not text-mode, you could hook prog-mode.

A: There can be only one major mode in Emacs buffer (unless you are using something like MMM or MuMaMo). In your case that one major mode is magit-log-edit-mode, whose name consists of three words ("Magit Log Edit"). You can just add to it whatever hook you like:
(defun my-turn-on-auto-fill ()
  (setq fill-column 72)
  (turn-on-auto-fill))

(add-hook 'magit-log-edit-mode-hook 'my-turn-on-auto-fill)

A: In general, you could define your own function, say my-common-hook and add it to all the major modes, for example:
(defun my-common-hook ()
   ... do stuff ...
   )
(add-hook 'one-mode-hook 'my-common-hook)
(add-hook 'another-mode-hook 'my-common-hook)
(add-hook 'a-third-mode-hook 'my-common-hook)

A: In answer to the original stated question, if you have a single function to add to numerous hook variables, you could do it like this:
(defun my-add-to-multiple-hooks (function hooks)
  (mapc (lambda (hook)
          (add-hook hook function))
        hooks))

(defun my-turn-on-auto-fill ()
  (setq fill-column 72)
  (turn-on-auto-fill))

(my-add-to-multiple-hooks
 'my-turn-on-auto-fill
 '(text-mode-hook
   magit-log-edit-mode-hook
   change-log-mode-hook))

Not the best example, perhaps, but I have something similar for some common behaviours I want enabled in programming modes, of which there are a great many more to list.

A: Just seeing this now, but here's what I've done. The end result is that i want to do the following:
(hook-up-modes my-lisps 'standard-lisp-environment).
To do this, i define the following defvars.
(defvar my-lisps  "clojure lisp emacs-lisp cider-repl")
(defun standard-lisp-environment ()
  (paredit-mode 1)
  (rainbow-delimiters-mode 1)
  (eldoc-mode 1))

I want to have lisp append -mode-hook to the lisps i use so i have the following:
(defun append-suffix (suffix phrases)
  "take SUFFIX and append it to each of the PHRASES."
  (mapcar #'(lambda (phrase) (concat phrase suffix)) phrases))

so that ("clojure" "lisp") => ("clojure-mode-hook" "lisp-mode-hook").
Now that we could easily have these, we need their reader symbols, which we easily get from
(defun symbols-from-strings (strings)
  "Given a list of strings, get their symbol values"
  (mapcar #'intern strings))

And then finally we have the similar form posted above:
(defun multiple-mode-add-hook (modes hook)
  "Given a list of x-mode-hook symbols in MODE, add the HOOK to them."
  (mapc (lambda (mode) (add-hook mode hook)) modes))

These all operate on the type that makes sense for them, list of strings, list of symbols 'blah-mode-hook, etc. So now we need a nice user facing function that we can work with.
(defun hook-up-modes (strings hook)
  (let ((modes (symbols-from-strings
                (append-suffix "-mode-hook" (split-string strings)))))
    (multiple-mode-add-hook modes hook)))

Now this should be pretty legible: We create our modes from a space delimited list of strings and apply the hook to it. Also, since I've defined a standard-lisp-environment, all my lisps behave similarly, and I can easily remove the hook later if I like. Then the code that actually does work is the super simple phrase
(hook-up-modes my-lisps 'standard-lisp-environment).

A: (dolist (mode-hook '(org-mode-hook
               term-mode-hook))
  (add-hook mode-hook (lambda () (display-line-numbers-mode 0))))


text:
Q: Simple AJAX Retrieval of data in XML file, going wrong around ".responseXML" I've searched and searched and quadruple checked spelling and syntax and I'm stumped.  I even checked the syntax on "jslint".  I've placed all the code on "jsfiddle":
http://jsfiddle.net/sxtuX/
var xmlHttp= createXmlHttpRequestObject();

function createXmlHttpRequestObject(){
   var xmlHttp;
   if(window.XMLHttpRequest){
      xmlHttp = new XMLHttpRequest();
   }
   else{
      xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
   }
   return xmlHttp;
}

function process() {
   if (xmlHttp) {
      try{
         xmlHttp.open("GET", "data_people.xml", true);
         xmlHttp.onreadystatechange = handleStateChange;
         xmlHttp.send(null);
      }
      catch (e) {
        alert ("In process function.
Error in creating xmlHttp object: "+ e.toString());
      }
   }
}

function handleStateChange() {
    if(xmlHttp.readyState==4) {
       if (xmlHttp.status==200) {
          try {
             handleResponse();
          }
          catch(e) {
             alert ("Trouble getting text." + e.toString());
          }
        }
        else {
           alert ("State = "+xmlHttp.readyState+" Status= " + xmlHttp.status);
        }
    }
}

function handleResponse() {
    var xmlResponse = xmlHttp.responseXML,
        root = xmlResponse.documentElement,
        names = root.getElementsByTagName("name"),
        ssns = root.getElementsByTagName("ssn");

    alert (xmlHttp.responseText);

    var stuff = "";
    for(var i=0;i<names.length;i++) {
        stuff = names.item(i).firstChild.data + "-" + ssns.item(i).firstChild.data + "
";
    }
    theD = document.getElementById("theD");
    theD.innerHTML = stuff;
}

The javascript works fine up until the last function "handleResponse()" which is the last function.  I've placed an "alert" after all the variable declarations using "xmlHttp.responseText" just to prove to myself the file is being accessed and it does print the entire XML file in the alert window.
I tried to create the XML datafile on "jsfiddle" by following the instructions, assuming it was like the HTML file example, but I couldn't get it to work.
So my questions: Why isn't "xmlHttp.responseXML" returning anything?  It's either that or something is going wrong with .documentElement. When I examine "names.length" or "ssns.length" they are both zero.  Also, can I get some assistance in figuring out the proper way to code an XML file on "jdfiddle" by correcting my fibble attempt?

A: The way you have your javascript options in the fiddle are set up it only gets executed onLoad (which means all your functions will be defined inside an onload function - and will both not be available in the global scope nor before said function has been executed). It's a catch 22 with sprinkles on top. You'll need to set the second dropdown on the left to either No wrap - in  or No wrap - in .
Next up - the jsfiddle example code. There's a whole bunch wrong here:

*

*You should have been referencing Request - not Request.XML (which you just made up ;P). And you should have included the MooTools library (first dropdown on the left) - because that's where Request is from ;)

*The url is case sensitive! "/echo/xml/" instead of "/echo/XML/".

*The xml string needs to be have properly escaped quotes and javascript strings don't support raw line-breaks (they can be escaped too... but that's another story) - just collapse them for now.

... But you don't need that example. Just use your own code!
Just remember to use the proper test url (with POST not GET) and escape/collapse your test xml.
This is a working fiddle: http://jsfiddle.net/sxtuX/3/


text:
Q: Broken assembler on Snow Leopard This is XCode 3.2.6 on snow leopard (gcc 4.2.1). Trying to compile a Hello World program and get a segfault, with a crash report like the one below (this was trying the first example in Learn C the Hard Way). Any hints towards a possible solution would be great.
Additionally, XCode crashes with "+entityForName: could not locate an NSManagedObjectModel for entity name 'DTExtensionPointDescription'" when you try to open or create a project.
Process:         as [44911]
Path:            /usr/bin/as
Identifier:      as
Version:         ??? (???)
Code Type:       X86-64 (Native)
Parent Process:  i686-apple-darwin10-gcc-4.2.1 [44909]

Date/Time:       2012-06-11 08:47:14.521 -0400
OS Version:      Mac OS X 10.6.8 (10K549)
Report Version:  6

Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: KERN_INVALID_ADDRESS at 0x0000000000000000
Crashed Thread:  0  Dispatch queue: com.apple.main-thread

Thread 0 Crashed:  Dispatch queue: com.apple.main-thread
0   libSystem.B.dylib               0x00007fff851cdad2 rindex + 8
1   as                              0x0000000100000775 0x100000000 + 1909
2   as                              0x00000001000006d4 0x100000000 + 1748

Thread 0 crashed with X86 Thread State (64-bit):
  rax: 0x0000000000000000  rbx: 0x00007fff5fbff2a0  rcx: 0x000000000000002f  rdx: 0x0000000000000000
  rdi: 0x0000000000000000  rsi: 0x000000000000002f  rbp: 0x00007fff5fbfee40  rsp: 0x00007fff5fbfee40
   r8: 0x0000000000000001   r9: 0x8080808080808080  r10: 0x00007fff8a96c169  r11: 0x00007fff851cdaca
  r12: 0x00007fff5fbfee98  r13: 0x0000000000000000  r14: 0x00007fff5fbff708  r15: 0x0000000000000007
  rip: 0x00007fff851cdad2  rfl: 0x0000000000010246  cr2: 0x0000000000000000

Binary Images:
       0x100000000 -        0x100002fff  as ??? (???) <44A4A2BA-257C-914C-FA97-714D15FFDBE1> /usr/libexec/gcc/i686-apple-darwin10/4.2.1/as
    0x7fff5fc00000 -     0x7fff5fc3be0f  dyld 132.1 (???) <DD3F7F3E-8612-A7BD-F508-9EF29132C419> /usr/lib/dyld
    0x7fff82f8a000 -     0x7fff82f8eff7  libmathCommon.A.dylib 315.0.0 (compatibility 1.0.0) <95718673-FEEE-B6ED-B127-BCDBDB60D4E5> /usr/lib/system/libmathCommon.A.dylib
    0x7fff85191000 -     0x7fff85352fef  libSystem.B.dylib 125.2.11 (compatibility 1.0.0) <9AB4F1D1-89DC-0E8A-DC8E-A4FE4D69DB69> /usr/lib/libSystem.B.dylib
    0x7fffffe00000 -     0x7fffffe01fff  libSystem.B.dylib ??? (???) <9AB4F1D1-89DC-0E8A-DC8E-A4FE4D69DB69> /usr/lib/libSystem.B.dylib

Here's something interesting-- here are all the 'as' binaries (and/or links) on my system:
/Developer/usr/bin/as
/Developer/usr/libexec/gcc/darwin/i386/as
/Developer/usr/libexec/gcc/darwin/ppc/as
/Developer/usr/libexec/gcc/darwin/ppc64/as
/Developer/usr/libexec/gcc/darwin/x86_64/as
/Developer/usr/libexec/gcc/i686-apple-darwin10/4.0.1/as
/Developer/usr/libexec/gcc/i686-apple-darwin10/4.2.1/as
/Developer/usr/libexec/gcc/powerpc-apple-darwin10/4.0.1/as
/Developer/usr/libexec/gcc/powerpc-apple-darwin10/4.2.1/as
/Developer/usr/llvm-gcc-4.2/libexec/gcc/i686-apple-darwin10/4.2.1/as
/Developer/usr/llvm-gcc-4.2/libexec/gcc/powerpc-apple-darwin10/4.2.1/as

It's the i686 ones that segfault (even when called with no input). Is there a way (an environment variable) I can use to tell GCC to use the x86_64 architecture (I'm on an i7, so it should be the appropriate one anyways)

A: The point of a Hello World program is to confirm that your compilation system is working and you know how to use it.
Blowing up the assembler with a Hello World is pretty clear indication that your compilation system is not working.


text:
Q: can't rdp to work desktop over vpn by name I have a couple of users that are having the same issue. They can VPN in to our local site but once the VPN is established they can only RDP to there desktop using the IP address. I have had a user test this and when they ping their work desktop from home, after the VPN connection is established, by IP address she gets a good return, but by desktop name she gets a "Request timed out." return and I noticed the address it has in brackets next to the name is nowhere near correct [198.105.254.63]. We have our local network set up as 10.101.x.x. Any idea why this could be and how I can fix this? The DNS IP's she is getting, after the VPN is connected, are correct.

A: I guess your VPN clients are not using your Internal Office DNS servers when connected, and that's why can not resolve the internal hostnames correctly.
You need to make sure that you configure your VPN server so that the clients, when connected also recieve the internal namservers (those you use in Office lan). Then they will be able to resolve the names properly.
The hostnames that are used in LAN environment are not globally resolvable as they used some private ip addresses which are also not globally routable. The host/ipaddress information are configured and stored in local nameservers and that's why when using some other DNS server outside the LAN they are not resolvable.


text:
Q: SQL - table alias scope I've just learned ( yesterday ) to use "exists" instead of "in".
 BAD
 select * from table where nameid in (
          select nameid from othertable where otherdesc =  'SomeDesc' )
 GOOD
 select * from table t where exists (
          select nameid from othertable o where t.nameid = o.nameid and otherdesc =  'SomeDesc' )

And I have some questions about this:
1) The explanation as I understood was: "The reason why this is better is because only the matching values  will be returned instead of building a massive list of possible results".  Does that mean that while the first subquery might return 900 results the second will return only 1 ( yes or no )?
2) In the past I have had the RDBMS complainin: "only the first 1000 rows might be retrieved", this second approach would solve that problem?
3) What is the scope of the alias in the second subquery?... does the alias only lives in the parenthesis?
for example
 select * from table t where exists (
          select nameid from othertable o where t.nameid = o.nameid and otherdesc =  'SomeDesc' )
 AND
          select nameid from othertable o where t.nameid = o.nameid and otherdesc =  'SomeOtherDesc' )

That is, if I use the same alias ( o for table othertable ) In the second "exist" will it present any problem with the first exists? or are they totally independent?
Is this something Oracle only related or it is valid for most RDBMS?
Thanks a lot

A: It's specific to each DBMS and depends on the query optimizer. Some optimizers detect IN clause and translate it.
In all DBMSes I tested, alias is only valid inside the ( )
BTW, you can rewrite the query as:
select t.*
from table t
join othertable o on t.nameid = o.nameid
    and o.otherdesc in ('SomeDesc','SomeOtherDesc');

And, to answer your questions:

*

*Yes

*Yes

*Yes

A: You are treading into complicated territory, known as 'correlated sub-queries'.  Since we don't have detailed information about your tables and the key structures, some of the answers can only be 'maybe'.
In your initial IN query, the notation would be valid whether or not OtherTable contains a column NameID (and, indeed, whether OtherDesc exists as a column in Table or OtherTable - which is not clear in any of your examples, but presumably is a column of OtherTable).  This behaviour is what makes a correlated sub-query into a correlated sub-query. It is also a routine source of angst for people when they first run into it - invariably by accident.  Since the SQL standard mandates the behaviour of interpreting a name in the sub-query as referring to a column in the outer query if there is no column with the relevant name in the tables mentioned in the sub-query but there is a column with the relevant name in the tables mentioned in the outer (main) query, no product that wants to claim conformance to (this bit of) the SQL standard will do anything different.
The answer to your Q1 is "it depends", but given plausible assumptions (NameID exists as a column in both tables; OtherDesc only exists in OtherTable), the results should be the same in terms of the data set returned, but may not be equivalent in terms of performance.
The answer to your Q2 is that in the past, you were using an inferior if not defective DBMS.  If it supported EXISTS, then the DBMS might still complain about the cardinality of the result.
The answer to your Q3 as applied to the first EXISTS query is "t is available as an alias throughout the statement, but o is only available as an alias inside the parentheses".  As applied to your second example box - with AND connecting two sub-selects (the second of which is missing the open parenthesis when I'm looking at it), then "t is available as an alias throughout the statement and refers to the same table, but there are two different aliases both labelled 'o', one for each sub-query".  Note that the query might return no data if OtherDesc is unique for a given NameID value in OtherTable; otherwise, it requires two rows in OtherTable with the same NameID and the two OtherDesc values for each row in Table with that NameID value.

A: *

*Oracle-specific: When you write a query using the IN clause, you're telling the rule-based optimizer that you want the inner query to drive the outer query. When you write EXISTS in a where clause, you're telling the optimizer that you want the outer query to be run first, using each value to fetch a value from the inner query. See  "Difference between IN and EXISTS in subqueries".

*Probably.

*Alias declared inside subquery lives inside subquery. By the way, I don't think your example with 2 ANDed subqueries is valid SQL. Did you mean UNION instead of AND?

A: Personally I would use a join, rather than a subquery for this.
SELECT t.*
FROM yourTable t
    INNER JOIN otherTable ot
        ON (t.nameid = ot.nameid AND ot.otherdesc = 'SomeDesc')

A: It is difficult to generalize that EXISTS is always better than IN. Logically if that is the case, then SQL community would have replaced IN with EXISTS...
Also, please note that IN and EXISTS are not same, the results may be different when you use the two...
With IN, usually its a Full Table Scan of the inner table once without removing NULLs (so if you have NULLs in your inner table, IN will not remove NULLS by default)... While EXISTS removes NULL and in case of correlated subquery, it runs inner query for every row from outer query.
Assuming there are no NULLS and its a simple query (with no correlation), EXIST might perform better if the row you are finding is not the last row. If it happens to be the last row, EXISTS may need to scan till the end like IN.. so similar performance...
But IN and EXISTS are not interchangeable...


text:
Q: how to make distributable C++ programs in Visual Studio The programs made in visual studio do not run on machines that don't have visual studio
I have searched over the internet for this but found nothing helpful
I'm new to programming and I can't make pure win32 apps rather I can only make console win 32 apps
Can anybody tell me how can I make my programs distributable?
Thanks in advance

A: The issue is that the machines where the program fails to run are missing the appropriate C/C++ runtime runtime.
You have two main options.

*

*Deploy the appropriate redistributable package for your version of Visual Studio. This is needed when you link to the runtime dynamically.

*Link to the runtime statically. That way the runtime is built into your executable.


text:
Q: Unable to update variable in bash script I am trying to print names of all .txt files from current folder in one line. I am using following script. However, it is not printing file names.
REF_SEQ=""
find . -name "*.txt" -maxdepth 1 -type f |
while read f;
do
    name=$(echo ${f}| xargs -I {} basename {} )
    REF_SEQ+="${name} "
done

echo "Full Sequence:  ${REF_SEQ}"

I have 3-4 .txt files in my current folder (A.txt, B.txt ...). I am expecting output as

Full Sequence: A.txt B.txt ...

If I just use find command without assigning output to variable RED_SEQ, I do get desired output. This suggests that find command is working fine but somehow I am unable to assign it to variable. I tried various different assignment operators but still no luck.

A: To update a variable in bash, you must use this syntax:
VAR="some stuff$VAR"

But, since you are using a pipe, the while loop is executed in a sub-shell, you variable is lost.
To correct this, you must have the syntax:
while read f
do
done <<< $(input)

So in your case:
REF_SEQ=""

while read f;
do
    name=$(echo ${f}| xargs -I {} basename {} )
    REF_SEQ="${REF_SEQ}${name} "
done <<< $(find . -name "*.txt" -maxdepth 1 -type f)

echo "Full Sequence:  ${REF_SEQ}"

A: The problem is, that you use {} behind the pipe symbol. This is just valid in the -exec option of find, but not behind the pipe symbol.
You could try the following:
REF_SEQ=$(find . -maxdepth 1 -name "*.txt" -type f -printf "%f " | xargs)
This should produce the result you desire. The printf-directive %f outputs the basename of the file found and the xargs "transposes" the result.
Kind regards
Jürgen


text:
Q: Google map not loading fully I have an Android app where I use a map and a test app. The map is loading fine on the test app, and is zooming in smoothly without any flicker, shows all details at that level of zoom. However, on my actual app, the map does not load fully and when I try to zoom in, it is just like stretching an image - the details are not showing as relevant for that level of zoom. Please let me know what might be wrong. Appreciate your help.

A: It seems like height problem in the map. Check if you have static value, match_parent etc. Without logs cannot say more.


text:
Q: Select list items and replace all their occurances with html formatting syntax I have a big text file that contains a list of items, such as:
a. item number one
b. item number two
c. item number three
d. ..
e. ..
Under that list there is an elaborating text that gives an idea about each item, such as:
At home we need item number one as it helps in cleaning. As for item number two, if you are a handy person you will certainly need it as it protects your hands. In regards to item number three, it is a must to have to protect your children from crawling insects. Etc.
What I am after is a find & replace expression for Notepad++ to select eg "item number one" only without "a. " (a dot space) from the list and replace it with html colour formatting syntax item number one, so the listed item will be distinguishable in red when the elaborating text is displayed in the browser. Thus, the previous paragraph will be like the following before it is pasted on the website:
At home we need item number one as it helps in cleaning. As for item number two, if you are a handy person you will certainly need it as it protects your hands. In regards to item number three, it is a must to have to protect your children from crawling insects. Etc.
Can anyone help with this please?
Thanks in advance..

A: How about:
Find what: (item number \w+)
Replace with: $1
According to your comment, here is a way to select what you want in your list of items:
Find what: (?<=^\w\. ).+$


text:
Q: htaccess redirect http://domain and http://www.domain to https://www.domain, excluding specified subdomain Goal:

*

*Redirect any HTTP request with or without WWW, to the matching page at https_www.domain.com EXCEPT for requests containing subdomain.domain.com which should be unaffected.

(I'm using underscores in place of :// because my post was being detected as spam, otherwise)
Examples:

*

*http_domain.com > https_www.domain.com

*http_domain.com* > https_www.domain.com*

*http_www.domain.com > https_www.domain.com

*http_www.domain.com* > https_www.domain.com\anything

*http_subdomain.domain.com > http_subdomain.domain.com

*http_subdomain.domain.com* > http_subdomain.domain.com*

*https_subdomain.domain.com > http_subdomain.domain.com

*https_subdomain.domain.com* > http_subdomain.domain.com*

I thought the following would do it, but it didn't work:
// redirect any request for http_domain.com or http_www.domain.com to https_www.domain.com
// condition 3 should exclude subdomain.domain.com from being affected by the rewrite rule
rewriteengine on
rewritecond %{HTTPS} off
rewritecond %{HTTP_HOST} ^domain.com$
rewritecond %{HTTP_HOST} !^subdomain\.domain\.com$  [NC]
rewriterule ^(.*)$ https://www.domain.com/$1 [R=301,L]

Any idea why that doesn't accomplish my goal?

A: You can use the following rule :
RewriteEngine on

RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} !^admin\.domain\.com$
RewriteCond www.%{HTTP_HOST} ^(?:www\.)?(www\..+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [NE,L,R]

*

*The first line checks if the scheme is http (https==off)

*The second line excludes the subdomain from https redirectiom (host=!"admin.domain.com")

*The third line matches the host value  www.domain.com or domain.com .and automatically adds www to non-www so our %1 always contains www.domain.com .


text:
Q: Specific template for category and product page in OpenCart 2.2.0.0 I am using OpenCart version 2.2.0.0 and trying to set different template for each category and product page. Searching online I found following code:
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/product/category_' . $category_id . '.tpl')) {
    $this->template = $this->config->get('config_template') . '/template/product/category_' . $category_id . '.tpl';
} elseif (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/product/category.tpl')) {
    $this->template = $this->config->get('config_template') . '/template/product/category.tpl';
} else {
    $this->template = 'default/template/product/category.tpl';
}

This code works fine for older version of OpenCart but in new version I am not finding similar code structure in catalog/controller/product/category.php file
How can I achieve similar result in OpenCart 2.2.0.0?

A: Since Opencart changed its method from 2.2 that code doesn't work anymore, you can modify it like this:
First we must know which theme is active, store its name in a variable
$config_theme = $this->config->get('config_theme') == 'theme_default' ? 'default' : $this->config->get('config_theme');

Then we must check if there is a file specially for current category, for example if we are on category 20, we check for category_20.tpl existance.
if (file_exists(DIR_TEMPLATE . $config_theme . '/template/product/category_' . $category_id . '.tpl')) {

If found that file:
$view = 'product/category_' . $category_id;

if there is no such file, use original file: category.tpl
} else {
    $view = 'product/category';
}

load selected view file based on above statement.
$this->response->setOutput($this->load->view($view, $data));

conclusion:
find $this->response->setOutput($this->load->view('product/category', $data)); in catalog/controller/product/category.php and replace it with above codes, here is full code:
$config_theme = $this->config->get('config_theme') == 'theme_default' ? 'default' : $this->config->get('config_theme');
if (file_exists(DIR_TEMPLATE . $config_theme . '/template/product/category_' . $category_id . '.tpl')) {
    $view = 'product/category_' . $category_id;
} else {
    $view = 'product/category';
}
$this->response->setOutput($this->load->view($view, $data));

A: I had OpenCart 2.2 designedlike only catalog of goods, index.php had this line:
$application_config = 'catalog';
I found here the lines responsible for choosing file of View (MVC technology):
catalog/controller/event/theme.php
My theme dir is 'default2'
Here I change template file for path: /index.php?route=product/category&path=69_65
to file catalog/view/theme/default2/template/product/category_69_65.tpl
The whole code with my snippet is this.
<?php
class ControllerEventTheme extends Controller {
    public function index(&$view, &$data) {
        if (!$this->config->get($this->config->get('config_theme') . '_status')) {
            exit('Error: A theme has not been assigned to this store!');
        }

        // This is only here for compatibility with old themes.
        if (substr($view, -4) == '.tpl') {
            $view = substr($view, 0, -4);
        }

        if ($this->config->get('config_theme') == 'theme_default') {
            $directory = $this->config->get('theme_default_directory');
        } else {
            $directory = $this->config->get('config_theme');
        }

        if (is_file(DIR_TEMPLATE . $directory . '/template/' . $view . '.tpl')) {
            $view = $directory . '/template/' . $view;
            //my snippet starts
            if ($view=='default2/template/product/category') {
                $url=$data['breadcrumbs'][count($data['breadcrumbs'])-1]['href'];
                if (substr($url, -5)=='69_65') {
                    if (is_file(DIR_TEMPLATE . $directory . '/template/product/category_69_65.tpl')) {
                        $view = $directory . '/template/product/category_69_65';
                    }
                }
            }
        //end of my snippet
        } else {
            $view = 'default/template/' . $view;
        }
    }
}

And this file is that reacts for uri product/catalog  & path=69_65:
catalog/view/theme/default2/template/product/category_69_65.tpl


text:
Q: ng-options with pre-selected value using ng-model not working I know there are lots of similar questions all around, but i have no clues why this is not working for me? I want size '4x4' as preselected in the dropdown. '4x4' is now static but finally i will replace '4x4' with a variable that will provide dynamic sizes.
Here is my Controller code:
    $scope.sizes = [{
                        size: '4 x 4',
                        price: 1.00
                    },
                    {
                        size: '4 x 6',
                        price: 5.00
                    },
                    {
                        size: '4 x 8',
                        price: 7.00
                    },
                    {
                        size: '5 x 6',
                        price: 9.00
                    },
                    {
                        size: '5 x 8',
                        price: 10.00
                    },
                    {
                        size: '6 x 8',
                        price: 15.00
                    }]

   $scope.selected = {
      "size": '4 x 4'
   }

And here is view code:
<select class="form-control" ng-model="selected.size" ng-options="item.size for item in sizes">
</select>

A: try this
 $scope.selected = $scope.sizes[0];
  <select class="form-control" ng-model="selected" ng-options="item.size for item in sizes">

Demo

angular.module("App", [])
 .controller("mainCtrl", function($scope){
   $scope.sizes = [{
                        size: '4 x 4',
                        price: 1.00
                    },
                    {
                        size: '4 x 6',
                        price: 5.00
                    },
                    {
                        size: '4 x 8',
                        price: 7.00
                    },
                    {
                        size: '5 x 6',
                        price: 9.00
                    },
                    {
                        size: '5 x 8',
                        price: 10.00
                    },
                    {
                        size: '6 x 8',
                        price: 15.00
                    }]
$scope.selected =    $scope.sizes[0];

});

<select class="form-control" ng-model="selected" ng-options="item.size for item in sizes">
</select>

A: I would change the template to
<select class="form-control" ng-model="selected" ng-options="item.size for item in sizes">
</select>

and the controller to
$scope.selected = $scope.sizes[0];

A:
Call first object in ng-init ng-init="selected.size = sizes[0];" and should initialize selected object like $scope.selected={}

Working Demo

angular.module("App", [])
 .controller("mainCtrl", function($scope){
   $scope.sizes = [{
                        size: '4 x 4',
                        price: 1.00
                    },
                    {
                        size: '4 x 6',
                        price: 5.00
                    },
                    {
                        size: '4 x 8',
                        price: 7.00
                    },
                    {
                        size: '5 x 6',
                        price: 9.00
                    },
                    {
                        size: '5 x 8',
                        price: 10.00
                    },
                    {
                        size: '6 x 8',
                        price: 15.00
                    }]
  $scope.selected={};

});

<select class="form-control" ng-model="selected.size" ng-init="selected.size = sizes[0];"  ng-options="item.size for item in sizes">
</select>

Update

'4x4' is now static but finally i will replace '4x4' with a variable that will provide dynamic sizes.

You can create a new scope object (as YourDynamicObject) and assign the dynamic value. it will be affect in ng-init
Code like
ng-init="selected.size = YourDynamicObject"  // html

$scope.YourDynamicObject=$scope.size[dynamicindex];//controller

A: try some thing like this:
  <select ng-init="selected= sizes[0]"
            ng-model="selected"
            ng-options="item.size for item in sizes">
    </select>

A:

angular.module("App", [])
 .controller("mainCtrl", function($scope){
   $scope.sizes = [{
                        size: '4 x 4',
                        price: 1.00
                    },
                    {
                        size: '4 x 6',
                        price: 5.00
                    },
                    {
                        size: '4 x 8',
                        price: 7.00
                    },
                    {
                        size: '5 x 6',
                        price: 9.00
                    },
                    {
                        size: '5 x 8',
                        price: 10.00
                    },
                    {
                        size: '6 x 8',
                        price: 15.00
                    }]
$scope.selected =    $scope.sizes[0];

});

<select class="form-control" ng-model="selected" ng-options="item.size for item in sizes">
</select>

{{selected}}


text:
Q: PDF/Tex-file produced by knitr contains different random numbers from those generated with same code in console Knitr is great at integrating text and output from code. The goal of using this is often called 'reproducible research'. Now when this research contains random numbers (e.g. for multiple imputations) then the key to reproducibility is the set.seed function in R.
But somehow the two types of reproducible are not compatible.
Look at the short Rnw-file below.
\documentclass{article}

\begin{document}

When I run the below chunck in the console I get (every time) the following numbers:

$$8, 94, 96, 92, 99, 57, 44, 45, 35, 43, 44, 71$$

However, when I run the enitre Rnw-program using the 'Compile pdf' button in Rstudio I get (every time) the following numbers:

$$34, 97, 52, 68, 2, 57, 76, 20, 96, 68, 27, 29$$

What number do \emph{you} get?

<<minimalexample, results = 'markup'>>=
set.seed(20200705)
sample(seq(1, 100), 12, replace = T)
@

\end{document}

My questions are:

*

*How is this possible?

*Can we do something to get the same numbers in both ways of running the code?

*What numbers do you (the reader) get when running this program and/or only the chunck?

A: I managed to reproduce your results on R 4.0.2. Try running the following line in both your console and your knitr file:
RNGkind()

If I'm not mistaken, you'll see the following (different) outputs depending on where you're running it:
# In the console:
RNGkind()
# [1] "Mersenne-Twister" "Inversion"        "Rounding"

# In the knitr file:
RNGkind()
# [1] "Mersenne-Twister" "Inversion"        "Rejection"

Reading through the documentation, you find that it's the sample.kind that's different. From the above link:

sample.kind can be "Rounding" or "Rejection", or partial matches to these. The former was the default in versions prior to 3.6.0: it made sample noticeably non-uniform on large populations, and should only be used for reproduction of old results.

Seems like your console is for some reason stuck with an old version of sample generation. To make it run with the modern, "Rejection" version, execute the following in your console:
RNGkind(sample.kind = "Rejection")

You should then get the same random sequence as in your knitr file.


text:
Q: how generate only darken random colors in javascript? I've been reading the questions here about how to generate random colors in JS/JQuery. But I want to generate only darken colors avoiding the black, yellow and gray range colors, in order to be able to draw areas in google maps with different colors.
Thanks

A: var hue = Math.floor(Math.random() * 360),
    saturation =  Math.floor(Math.random() * 100),
    lightness =  Math.floor(Math.random() * 50),
    color = "hsl(" + hue + ", " + saturation + "%, " + lightness + "%)";

That was to generate a random hsl color. But if you want to darken an existing rgb color the best thing to do is to convert it to hsl and then setting its lightness value according to your needs. Have fun with these functions:
function rgbToHsl(r, g, b) {
    var maxRGB = Math.max(r, g, b),
        minRGB = Math.min(r, g, b),
        tmp, h, s, l;
    tmp = maxRGB - minRGB;
    l = (maxRGB + minRGB)/255;
    if (tmp) {
        s = Math.round(tmp/(l < 1 ? l : 2 - l))/255;
        if (r === maxRGB) h = (g - b)/tmp;
        else if (g === maxRGB) h = 2 + (b - r)/tmp;
        else h = 4 + (r - g)/tmp;
        h = (h < 0 ? h + 6 : h)*60 % 360;
    } else h = s = 0;
    l /= 2;
    return [h, s, l];
}
function hslToRgb(h, s, l) {
    if (!s) return r = g = b = l*255;
    var q = l < .5 ? l*(1 + s) : l + s - l*s,
        p = 2*l - q;

    for (var i = 120, t, c = []; i >= -120; i -= 120) {
        t = h + i;
        if (t < 0) t += 360;
        else if (t >= 360) t -= 360;
        if (t < 60) c.push(p + (q - p)*t/60);
        else if (t < 180) c.push(q);
        else if (t < 240) c.push(p + (q - p)*(240 - t)/60);
        else c.push(p);
    }
    return [c[0]*255, c[1]*255, c[2]*255];
}

Here, s and l ranges from 0 to 1, r, g and b from 0 to 255 and h from 0 to 359.

A: According to duplicate taken from comment of jj__?
function getGMapRandomColor() {
    return 'hsla(' + Math.floor(Math.random()*360) + ', 100%, 70%, 1)';
}

A: First define the RGB ranges you do want, and once you have those defines just generate random values within those ranges. Or define the ranges you don't want and keep looping till you find a colour that fits those criteria, a lot less efficient, but quite a bit easier to program if efficiency is not an issue.

A: Where's the problem? Just generate 3 random numbers, maybe in the range from, let's say 30 to 150, so you will only get relatively low values for R, G and B, and block "black-like" colors. Then you would just have to check if these three values fall into the range of your defined blacklisted color ranges like yellow or gray.

A: For simplicity of implementation and thoroughness, I can't recommend this script highly enough:
David Merfeld's randomColor
Choose between hex or rgb, add in some alpha, specify light or dark palettes, avoid repeats, etc.