text:
Q: PHP looping recursive function I had this looping function and what it does to fetch data then display the result in json format. In $subArray[] i try to call the looping function again so it can read if got any sub-nodes underneath. But seem the result not display as I expected to be.
function recursiveNode($ledgerID,$accountID){
  global $ehorsObj;
  $subArray = array();

  $query_get_subchild = " SELECT accountLedgerID, accountID, accountMainID, accountName, active
                          FROM tblAccAccounts
                          WHERE accountMain = 'y'
                          AND accountSub = 'y'
                          AND accountMainID = '".$accountID."'
                          AND accountLedgerID = '".$ledgerID."'
                          ORDER BY accountName
";
  $GetResult = $ehorsObj->FetchData($query_get_subchild, $ehorsObj->DEFAULT_PDO_CONNECTIONS);
  while ($row3 = $GetResult->fetch()) {

    $subArray[] = array('accountLedgerID' => $row3['accountLedgerID'], 'accountID' => $row3['accountID'], 'accountMainID' => $row3['accountMainID'], 'accountName' => $row3['accountName'], 'active' => $row3['active'], 'items' => recursiveNode($ledgerID, $row3['accountID']));

  }
  header("Content-type: application/json");
  $result = json_encode($subArray);
  echo $result;
}

it show the result (as image below)

and the result I expected to be like this

[
  {
    accountLedgerID: "LA1",
    accountID: "LA95",
    accountMainID: "LA5",
    accountName: "SubGroup RunDeposit 1",
    active: "y"
  },
  {
    accountLedgerID: "LA1",
    accountID: "LA2",
    accountMainID: "LA5",
    accountName: "SubGroup RunDeposit 2",
    active: "y",
    item: [
      {
        accountLedgerID: "LA1",
        accountID: "LA125",
        accountMainID: "LA2",
        accountName: "Sub x2 Group RunDeposit 2",
        active: "y",
        items: [
          {
            accountLedgerID: "LA1",
            accountID: "LA6",
            accountMainID: "LA125",
            accountName: "Sub x3 Group RunDeposit 2",
            active: "y",
            items: [ ]
          }
        ]
      }
    ]
  }
]

A:
function fetch_account ($dbresult, $ledgerID, $accountID) {
  $result = array_filter($dbresult, function ($something) use ($ledgerID, $accountID) {
    if ( $something['accountMainID'] == $accountID && $something['accountLedgerID'] == $ledgerID ) {
      return true;
    }
    return false;
  });
  return array_values($result);
}

function recursiveNode($ledgerID,$accountID){
  $testArray = [
    [
      'accountLedgerID' => 'LA1',
      'accountID' => 'LA95',
      'accountMainID' => 'LA5',
      'accountName' => 'SubGroup RunDeposit 1',
      'active' => 'y'
    ],
    [
      'accountLedgerID' => 'LA1',
      'accountID' => 'LA2',
      'accountMainID' => 'LA5',
      'accountName' => 'SubGroup RunDeposit 2',
      'active' => 'y'
    ],
    [
      'accountLedgerID' => 'LA1',
      'accountID' => 'LA125',
      'accountMainID' => 'LA2',
      'accountName' => 'Sub x2 Group RunDeposit 2',
      'active' => 'y'
    ],
    [
      'accountLedgerID' => 'LA1',
      'accountID' => 'LA6',
      'accountMainID' => 'LA125',
      'accountName' => 'Sub x3 Group RunDeposit 2',
      'active' => 'y'
    ]
  ];

  $someArray = fetch_account($testArray, $ledgerID, $accountID);
  $subArray = array();
  $i = 0;
  while (!empty($someArray[$i]) && $row3 = $someArray[$i]) {
    $subArray[] = array(
      'accountLedgerID' => $row3['accountLedgerID'],
      'accountID' => $row3['accountID'],
      'accountMainID' => $row3['accountMainID'],
      'accountName' => $row3['accountName'],
      'active' => $row3['active'],
      'items' => recursiveNode($ledgerID, $row3['accountID'])
    );
    $i++;
  }
  return $subArray;
}

$myArray = recursiveNode('LA1', 'LA5');
$result = json_encode($myArray);
echo $result;

A: Breaking down the problem first, I think the recursive function isn't returning anything. I think this is indicative when your result has 'items' as null.


text:
Q: Ajax readyState returning always 0 I've got a problem with this Ajax code, is returning 0 everytime I access 'readyState'. Don't know what the source of the problem is yet, any help would be appreciated:
var xhr = null;
function performAjax(inputUrl){

    // instantiate XMLHttpRequest object
    try{
        xhr = new XMLHttpRequest();
        alert("XMLHttpRequest");
    }
    catch(e){
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }

    // handle old browsers
    if( xhr == null ) {
        alert("Ajax not supported by your browser");
        return;
    }

    // get the URL
    var url = inputUrl;
    alert(inputUrl);
    // get Ajax answer
    xhr.onreadystatechange = handler();
    //alert(xhr.readyState);
    xhr.open("POST", url, true);
    xhr.send(null);
}

function handler() {

    alert("Handler: " + xhr.readyState + " Status: " + xhr.status);
    // handle only loaded requests
    if(xhr.readyState == 4) {   // state 4: that data has been received
        alert("here");
        if(xhr.status == 200) {
            alert(xhr.reponseText);
        }
        else alert("Error with Ajax");
    }
}

A: You're assigning the handler function incorrectly:
xhr.onreadystatechange = handler; // <--- THERE SHOULD BE NO PARENTHESES

When you include the parentheses, you're asking that the function be called. Without them, you're merely referring to the function, which is what you want.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Как правильно организовать запросы к API Получаю все данные по пользователю из разных методов в один объект:
let client = {};
apiGetClient()
  .then((response) => {
    client = { ...client, ...response.data };
    apiGetClientInfo().then(response => {
      client = { ...client, ...response.data };
      apiClientIdentities().then(response => {
        client = { ...client, ...response.data };
        apiClientAddresses().then(response => {
          client = { ...client, ...response.data };
          apiClientGuarantors().then(response => {
            client = { ...client, ...response.data };
            apiClientWork().then(response => {
              client = { ...client, ...response.data }
              apiClientContacts().then(response => {
                client = { ...client, ...response.data }
                console.log(client, "Client")
              })
            })
          })
        })
      })
    })
  })

Я не понимаю как это переделать правильно на цепочку промисов,
apiGetClient()
  .then((response) => {
    return client = { ...client, ...response.data };

  })
  .then((client) => {
    apiGetClientInfo().then(response => {
      client = { ...client, ...response.data };
    })
  })
  .then((client) => {
    apiClientIdentities().then(response => {
      client = { ...client, ...response.data };
    })
  })
  .then((client) => {
    apiClientAddresses().then(response => {
      client = { ...client, ...response.data };
    })
  })
  .then((client) => {
    apiClientGuarantors().then(response => {
      client = { ...client, ...response.data };
    })
  })
  .then((client) => {
    apiClientWork().then(response => {
      client = { ...client, ...response.data }
    })
  })
  .then((client) => {

    apiClientContacts().then(response => {
      client = { ...client, ...response.data }
    })

  })
  .then((client) => {
    console.log(client, "Client")
  })

Как я понял должно быть что то вроде этого но как вернуть все в один обьект?

A: Цепочка нужна там, где следующий запрос зависит от того, что вернет предыдущий.
В данном случае, так как результаты не зависят друг от друга, стоит вообще убрать цепочку и воспользоваться методом Promise.all
let client = {};
Promise.all([
    apiGetClient(),
    apiGetClientInfo(),
    apiClientIdentities(),
    apiClientAddresses(),
    apiClientGuarantors(),
    apiClientWork(),
    apiClientContacts()
])
  .then(responses => responses.map(r => r.data))
  .then(data => Object.assign(client, ...data))
  .then(client => console.log(client, "Client"));

A: (async () => {
  let resClient = await apiGetClient();
  let resClientInfo = await apiGetClientInfo();
  let resClientIdenties = await apiClientIdentities();
  let respClientAddress = await apiClientAddresses();
  let resClientGuarantos = await apiClientGuarantors();
  let resClientWork = await apiClientWork();
  let resClientContact = await apiClientContacts();

  let client = {
    ...resClient.data,
    ...resClientInfo.data,
    ...resClientIdenties.data,
    ...respClientAddress.data,
    ...resClientGuarantos.data,
    ...resClientWork.data,
    ...resClientContact.data
  };
 console.log(client, "Client");
})()


text:
Q: SQLite open database from string Assume I have a string containing an sqlite database.
(I read the entire content of the file containing the Sqlite database into a string)
Now, I want to get a connection to the database  without saving the string to a file first.
Basically, this is an in-memory data base, which is totally possible in sqlite. But according to the sqlite documentation  "[when you open an in memory data base] no disk file is opened. Instead, a new database is created purely in memory".
But I have string representing a data base. i want to use it and not create a new one.
Can this be done?

A: In-memory databases do not give you access to the underlying memory.
It is possible to copy databases with the backup API, but that would require another, file-based database.
Just create a temporary file, and open it directly.


text:
Q: Quotes appearing as "?" in bibliography I'm using Overleaf's XeLaTeX compiler, along with \usepackage{polyglossia} to write greek and latin text. There seems to be some conflict between polyglossia and my bibliography:
I've tried different lines of \usepackage[xx]{csquotes} trying to fix this, but nothing seems to be working.
Any help would be appreciated. Thanks.


text:
Q: React Native Android - how to disable android back button in StackNavigator I am trying to implement a lock screen.
Only when the password is correct does the screen go back, otherwise the screen must not be exited.
But if you press the Back button on Android, it will always go back.
I tried using BackHandler but it failed.
It seems to be related to StackNavigator.
How can I do nothing when the backButton is pressed?
import React, { PureComponent } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import PINCode from '@haskkor/react-native-pincode';
import { BackHandler } from 'react-native';
import {
  View, Text, Button,
} from 'native-base';
import { NavigationEvents } from 'react-navigation';
import Colors from '../common/Colors';

class LockScreenContainer extends PureComponent {
  static navigationOptions = () => ({
    header: false,
    gesturesEnabled: false,
  });

  finishProcess = async () => {
    const { navigation } = this.props;
    navigation.goBack();
  }

  render() {
    const { navigation,isLock } = this.props;

    return (
      <View style={{ backgroundColor: Colors.GRAY_LV0, justifyContent: 'center', flex: 1 }}>
        <NavigationEvents
          onWillBlur={() => BackHandler.removeEventListener('hardwareBackPress')}
          onWillFocus={() => BackHandler.addEventListener('hardwareBackPress', () => false)}
        />
        <PINCode
          status={isLock ? 'enter' : 'choose'}
          finishProcess={this.finishProcess}
        />
      </View>
    );
  }
}

export default connect(
  state => ({
    isLock: state.lock.isLock,
  }),
  undefined,
)(LockScreenContainer);

insert BackHandler.addEventListener ('hardwareBackPress', () => false) into componentDidMount also has the same result.

A: You may do something like the following
componentWillMount() {
BackHandler.addEventListener('hardwareBackPress', this.backButtonActionCheck);
}

componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress',this.backButtonActionCheck);
}

backButtonActionCheck = () => {
// Your logic to check if user should go back or stay
}


text:
Q: android app deployment and publishing I am about to finish my first android app.
Could you give me some knowledge/links/references about stuff like
deployment, app signing, android market, app publishing etc
Thanks

A: Everything is in the dev guide:
http://d.android.com/guide/publishing/app-signing.html
http://d.android.com/guide/publishing/versioning.html
http://d.android.com/guide/publishing/licensing.html
http://d.android.com/guide/publishing/preparing.html
http://d.android.com/guide/publishing/publishing.html

A: android developer guide contains everything you need to know.
And this video tutorial is also a good source to get some knowledge on app publishing.


text:
Q: How to create PDF reports using XML and XSLT using C#? I am curious to how can somebody generate a PDF file using C# and use XML and XLST as mark up language.
Do I need specific Libraries? - Also, I can't find anything on Google or Youtube on a tutorial to create a PDF file using XML as mark up and XLST as style using C#.
This is the idea:

*

*Create XML Mark up

*Use XLST to style XML

*C# to insert data into XML template e.g. Contact name, telephone number... (But not saving/overwrite the XML file - only to use as template)

*Save it as PDF as output

Where can I start learning this? - Has anybody had experience in this field? If so, can do you direct me to achieve this goal?


text:
Q: How to convert string into control characters? We have a program where a user can input a line-break for another system.
the problem is when substituting a string with this line-break, it simply adds "\n".
for instance :
works :
var test = 'message';
test+='\n';
console.log("message " + test); // (doesnt show \n)

doesn't work :
var test="message";
var myLineBreakFromDatabase = getMyLineBreak();//simply returns a string containing "\n"
test+=myLineBreakFromDatabase;

test is now = "message\n" which is useless.
However, we using Javascript in the entire system so I guess just to figure out how to convert a line-break from string into control-characters?

A: The issue is that the string you are getting back from your database is actually something like "\\n", not "\n".  Most likely you have some autoescaping going on somewhere, either before things get saved in the DB or before it gets to where you are using it in your app.
Hacky workaround that isn't a great idea but will probably "work":
var myLineBreakFromDatabase = getMyLineBreak().split('\\n').join('\n');

A: If your linebreaks for different systems are stored in a database where the linebreak for unix is \u000A and the one for windows is \u000D\u000A, then you could read the text into myLineBreak and then do something like:
var actualLineBreakString=JSON.parse('"' + myLineBreak + '"');

You'll have to make sure your javascript has the JSON object. If needed, it can be grabbed at json.org.
This approach works for any of the special characters. See here: http://msdn.microsoft.com/en-us/library/ie/2yfce773(v=vs.94).aspx


text:
Q: Positioning multiple spans on top of separate divs correctly between browsers I am having a problem with getting multiple spans to lay on top of a few divs within a WordPress post of mine correctly.
I created my own dummy webpage within Notepad++ with all the styling and things to make sure it looked how I wanted, and it looks fine. However, when I then go and put all of the HTML structure and the CSS into my WordPress site, then it doesn't look quite right.
The HTML content is the following:

MEMBER
    •

    ✔SILVER••

GOLD
    •••

And the CSS to back it is this:
.member-status {
position:relative;
width:200px;
color:#fff;
display:block;
margin:0 auto;
border-radius:5px;
border:1px solid #5cadff;
text-align:center;
font-family: sans-serif;
font-weight: bold;
text-shadow: 0px 1px 1px #5cadff;
padding:20px 30px;

background:#1874cd;
background-image: -webkit-linear-gradient(#4f9eea, #1874cd);
background-image: -moz-linear-gradient(#4f9eea, #1874cd);
background-image: linear-gradient(#4f9eea, #1874cd);

-webkit-box-shadow: 10px 10px 5px #777;
-moz-box-shadow: 10px 10px 5px #777;
box-shadow: 10px 10px 5px #777;
}

.silver-status {
position:relative;
width:200px;
color:#555;
display:block;
margin:0 auto;
border-radius:5px;
border:1px solid #bbb;
text-align:center;
font-family: sans-serif;
font-weight: bold;
text-shadow: 0px 1px 1px #bbb;
padding:20px 30px;

background:#c0c0c0;
background-image: -webkit-linear-gradient(#eaeaea, #c0c0c0);
background-image: -moz-linear-gradient(#eaeaea, #c0c0c0);
background-image: linear-gradient(#eaeaea, #c0c0c0);

-webkit-box-shadow: 10px 10px 5px #777;
-moz-box-shadow: 10px 10px 5px #777;
box-shadow: 10px 10px 5px #777;
}

.gold-status {
position:relative;
width:200px;
color:#e68a00;
display:block;
margin:0 auto;
border-radius:5px;
border:1px solid #ffff80;
text-align:center;
font-family: sans-serif;
font-weight: bold;
text-shadow: 0px 1px 1px #ffff80;
padding:20px 30px;

background:#ffd700;
background-image: -webkit-linear-gradient(#fff2aa, #ffd700);
background-image: -moz-linear-gradient(#fff2aa, #ffd700);
background-image: linear-gradient(#fff2aa, #ffd700);

-webkit-box-shadow: 10px 10px 5px #777;
-moz-box-shadow: 10px 10px 5px #777;
box-shadow: 10px 10px 5px #777;
}

.big-checkmark {
position:absolute;
top:7px;
left:12px;
color:#3c3;
font-size:2.5em;
}

.level-dot {
position:absolute;
top:7px;
right:15px;
font-size:2.5em;
}

You can see the end result on JSFiddle here: http://jsfiddle.net/WcQbL/1/
Here's the thing... on Chrome this looks perfect to me. The big-checkmark and level-dot spans look perfectly placed where I want them.
In Firefox and IE11, the level-dots look like they are positioned well, but the big-checkmark is positioned way down from the center on Firefox, and slightly down from center on IE11. I am pushing both the spans down the exact same way using top:7px;
Now... I went and plugged in this same HTML structure into a test post of mine on WordPress, and I added all the appropriate CSS to my child theme's style.css file.
However, when I go to the post, both the level-dots and the big-checkmark are positioned way up high on all 3 of the divs and it looks really bad.
So, my question is... is there a better way I can go about positioning these spans on top of these divs so that it is consistent among all browsers? And is there maybe some CSS in my parent style.css that would be affecting the spans being way up high once I plug the SAME exact code into my WordPress post?
Any help would be greatly appreciated. This is my first time working with spans on top of divs, so I apologize if the CSS code is not-so-great.
One more note, I originally had posted this on the "WordPress Development" Stack Exchange, but they told me to come here. I feel like it may just be purely a markup issue that will get it to work on all browsers including my Wordpress site, but maybe it is WordPress specific.
Thanks!

A: I figured out the solution to my problem. In the old code, I was letting the padding on my divs more or less do the "sizing" of the div for me and give it the look that I wanted. In the old code, I had only specified a width on my divs, no height.
In the fix, I specified my own height and width (width:275px and height:70px). Then, in order to get text or other things to center correctly within a div you should specify the "line-height" property as well so I set line-height:70px to match my regular height. Then, took all of the padding out (padding:0).
As a specific example, the "member-status" class now looks like this:
.member-status {
    position:relative;
    height:70px;
    line-height:70px;
    width:275px;
    color:#fff;
    display:block;
    margin:0 auto;
    border-radius:5px;
    border:1px solid #5cadff;
    text-align:center;
    font-family: sans-serif;
    font-weight: bold;
    text-shadow: 0px 1px 1px #5cadff;
    padding: 0;

    background:#1874cd;
    background-image: -webkit-linear-gradient(#4f9eea, #1874cd);
    background-image: -moz-linear-gradient(#4f9eea, #1874cd);
    background-image: linear-gradient(#4f9eea, #1874cd);

    -webkit-box-shadow: 10px 10px 5px #777;
    -moz-box-shadow: 10px 10px 5px #777;
    box-shadow: 10px 10px 5px #777;
}

Lastly, I was forcing the "big checkmark" and "level-dot" to be in a specific position. I took the "top:7px" property out because that was pushing it down too far now with my changes, but left the "left" and "right" properties on there to get them spaced away from the left and right borders where I wanted them.
You can see the new code at: New fixed way
And the old code at: Old wrong way
If you look at the new code in all the different browsers, it looks the exact same now and exactly how I want it -- no differences between each browser.
Hope this helps someone!


text:
Q: Retrieving nest thermostat schedules I am trying to retrieve nest thermostat schedules. However i get back the object which doesn't contain the thermostat schedules in it.
Is there an api that nest has which i can use to retrieve the thermostat schedules

A: As far as I know it is not possible to get the schedules. I think it is for security reasons.
But maybe it is possible.
For other persons it is better if you show some of the code and data. So we understand what you are doing. So like Holger Just said: "What kind of calls do you make, and what kind of data do you get back?"


text:
Q: Database error: no such table: auth_user. Extending AbstractUser and using model to register on admin I'm trying to use AbstractUser to add a field to Django's standard User model. This is my code:
class GUser(AbstractUser):
    uuid = UUIDField(auto=True)

This has been successful because from the shell I can say,
>>> a = GUser.objects.all()

>>> a
[<GUser: User1>]

>>> a[0].uuid
UUID('7d1f0b7b52144a2ea20db81ce74741e3')

The problem I am having is registering a new user from the /admin. When I create a new user I get a Database error:
no such table: auth_user

Before I get more into it, here is my forms.py:
class GUserChangeForm(UserChangeForm):
    class Meta:
        model = get_user_model()

class GUserCreationForm(UserCreationForm):

    class Meta:
        model = get_user_model()

    def clean_username(self):
            username = self.cleaned_data["username"]
            try:
                get_user_model().objects.get(username=username)
            except get_user_model().DoesNotExist:
                return username
            raise forms.ValidationError(self.error_messages['duplicate'])

And my admin.py:
class GUserAdmin(UserAdmin):
    form = GUserChangeForm
    add_form = GUserCreationForm
    fieldsets = (
        (None, {'fields': [('username', 'password')]}),
        ('Personal info', {'fields': ('is_active','is_staff','is_superuser','groups',    'user_permissions')}),
        ('Important dates', {'fields': ('last_login', 'date_joined')}),
        #('Universal ID', {'fields': ('uuid')})
        )

admin.site.register(GUser,GUserAdmin)

I read that when this has happened to other people they implemented their own Forms (as I did) to overwrite clean_username(self):
However I don't think this is getting called when I try to add a user from the admin. The auth.forms.py file is getting called even though I register my GUserAdmin.
Also, when I delete my database (sqlite3) and then call python manage.py syncdb, I see that a auth_user table is actually not getting created.
Yes, I have included AUTH_USER_MODEL in settings.py.
Any help would be greatly appreciated.
I have read:
https://docs.djangoproject.com/en/1.5/topics/auth/customizing/#custom-users-and-the-built-in-auth-forms
Along with tons of SO posts but none of them seem to fix the issue I'm having.

A: Perhaps the error lies in incorrect zeroing of the database.
'Database error: no such table: str'
To delete the database, delete only database & all migrations in the migration packages(like 0001_initial.py and etc.).
Do not delete all migration packages and file "init.py". If you did this, create them. Django will not create them again.
And after, do not remember run makemigrations & migrate.

A: So deleted all the work I had done with this and moved on with the standard user so that I could make progress. Then one day I went back to it and managed to get it working in an hour.
I'll post the code for reference but I can't really pin point what made the difference. I do know that the creation forms and stuff were not necessary.
models.py
class PropaUser(AbstractUser):
    uuid = UUIDField(auto=True)

admin.py
from django.contrib import admin
from login.models import PropaUser

admin.site.register(PropaUser)

settings.py
AUTH_USER_MODEL = "login.PropaUser"

other models.py
class Word(models.Model):
    user = models.ManyToManyField(settings.AUTH_USER_MODEL)
    deck = models.ManyToManyField(Deck)
    word = models.CharField(max_length=100)

    def __unicode__(self):  # Python 3: def __str__(self):
    return self.word

This is what is working. I do not know what was causing all the issues before because I think I tried this method before posting this question. This may not be a satisfactory answer but this is what is working. Earlier I was also confused about what it takes simply to add a field to the existing User. This is it.


text:
Q: mysql join: what is faster? My tables: big_table
+-----------------+--------------+------+-----+---------+----------------+
| Field           | Type         | Null | Key | Default | Extra          |
+-----------------+--------------+------+-----+---------+----------------+
| id              | mediumint(7) | NO   | PRI | NULL    | auto_increment |
| title           | varchar(255) | NO   |     | NULL    |                |
| category_id     | tinyint(2)   | NO   |     | NULL    |                |
| sub_category_id | tinyint(2)   | NO   |     | NULL    |                |
| width           | smallint(5)  | NO   |     | NULL    |                |
| height          | smallint(5)  | NO   |     | NULL    |                |
| ratio_width     | smallint(5)  | NO   |     | NULL    |                |
| ratio_height    | smallint(5)  | NO   |     | NULL    |                |
| size            | int(8)       | NO   |     | NULL    |                |
| mime            | tinyint(2)   | NO   |     | NULL    |                |
| views           | mediumint(7) | NO   | MUL | NULL    |                |
| time            | int(10)      | NO   |     | NULL    |                |
| file            | varchar(255) | NO   |     | NULL    |                |
+-----------------+--------------+------+-----+---------+----------------+

small_table

+--------+--------------+------+-----+---------+-------+
| Field  | Type         | Null | Key | Default | Extra |
+--------+--------------+------+-----+---------+-------+
| id     | mediumint(7) | NO   | PRI | NULL    |       |
| width  | smallint(5)  | NO   | MUL | NULL    |       |
| height | smallint(5)  | NO   | MUL | NULL    |       |
+--------+--------------+------+-----+---------+-------+

so what's faster (example):
   SELECT * FROM `big_table` WHERE `width` =1920 AND `height`=1080;

or use join
 select big_table.*
 from small_table
 left join small_table small_table2
 ON (small_table.id=small_table2.id
     and `small_table`.`height` = '1080')
 left join big_table
 ON (big_table.id=small_table.id)
 where small_table.width = '1920';

or join's from the same table?
select big_table.*
from big_table as big_table1
left join big_table big_table2
ON (big_table1.id=big_table2.id and  `big_table1`.`height` = '1080')
left join big_table
ON (big_table.id=big_table1.id)
where big_table1.width = '1920';

or there is some better solution, better select's?
 (on both tables I can use indexes (width and height), but only ID is unique)

A: No join is faster that join. If you have a proper index (that is, a single index on the combination of width and height) then the simple select on big_table will be way faster.

A: Query execution time, is not the only parameter to take into consideration.
If any other table would have to join big_table, it would kill performance on those joins.
For scalability, I would defiantly split the tables, having the data separated will ensure you, that a bottleneck won't arise here.
Make sure you put least used data in a table for itself, and most commonly used data in the other. If you have a huge text, putting this in the least used table, would be good as well.


text:
Q: How to pass an expression to a geom_text label in ggplot? I am attempting to pass an expression with subscript to a single geom_text() label in ggplot. Here is my code right now:
my_exp <- expression('my_exp'[s][u][b])

my_data <-
  data.frame(
    var_1 = c("a", "b", "c"),
    var_2 = c(1, 2, 3)
  )

my_data %>%
  ggplot(aes(x = var_1, y = var_2))+
  geom_text(aes(label = var_1))

Here is the resulting plot:

What I would like to do is replace the var_1 value of "a" with the expression specified by my_exp and then have geom_text() evaluate that value as an expression, resulting in the subscript appearing on the ggplot.

A: I would suggest this approach. You can build another variable for your labels and then enable the option parse=T from geom_text() in order to have the desired plot. Here the code:
library(ggplot2)
library(tidyverse)
#Data
my_exp <- as.character(expression('my_exp'[s][u][b]))

my_data <-
  data.frame(
    var_1 = c("a", "b", "c"),
    var_2 = c(1, 2, 3),stringsAsFactors = F
  )
#Mutate
my_data$label <- ifelse(my_data$var_1=='a',my_exp,my_data$var_1)
#Plot
my_data %>%
  ggplot(aes(x = var_1, y = var_2))+
  geom_text(aes(label = label),parse = T)

Output:

Update: If there are issues with labels here a code for that:
#Label
my_exp <- "14~M~my_exp[s][u][b]"
#Code
my_data <-
  data.frame(
    var_1 = c("a", "b", "c"),
    var_2 = c(1, 2, 3),stringsAsFactors = F
  )
#Mutate
my_data$label <- ifelse(my_data$var_1=='a',my_exp,my_data$var_1)
#Plot
my_data %>%
  ggplot(aes(x = var_1, y = var_2))+
  geom_text(aes(label = label),parse = T)

Output:


text:
Q: Salesforce APEX Unit Test Error with REST Services / Error at SELECT of Case Object I've succeeded to successfully construct a REST API using APEX language defined with an annotation: @RestResource.
I also wrote a matching Unit test procedure with @isTest annotation. The execution of the REST API triggered by a HTTP GET with two input parameters works well, while the Unit Test execution, returns a "null" value list resulting from the SOQL query shown below:
String mycase = inputs_case_number; // for ex. '00001026'
sObject[] sl2 = [SELECT Id, CaseNumber FROM Case WHERE CaseNumber = :mycase LIMIT 1];

The query returns:
VARIABLE_ASSIGNMENT [22]|sl2|[]|0x1ffefea6

I've also tried to execute it with a RunAs() method (see code below), using a dynamically created Salesforce test user, not anonymous, connected to a more powerful profile, but still receiving a "null" answer at the SOQL query. The new profile defines "View All" permission for Cases. Other SOQL queries to objects like: "User" and "UserRecordAccess" with very similar construction are working fine, both for REST APEX and Test APEX.
Is there a way to configure an access permission for Unit test (@isTest) to read the Case object and a few fields like: Id and CaseNumber. Is this error related to the "Tooling API" function and how can we fix this issue in the test procedure?
Code attachment: Unit Test Code
@isTest
private class MyRestResource1Test {
     static testMethod void MyRestRequest() {
     // generate temporary test user object and assign to running process
     String uniqueUserName = 'standarduser' + DateTime.now().getTime() + '@testorg.com';
     Profile p = [SELECT Id FROM Profile WHERE Name='StandardTestUser'];
     User pu = new User(Alias='standt',Email='standarduser@testorg.com',LastName='testing',EmailEncodingKey='UTF-8',LanguageLocaleKey='en_US',LocaleSidKey='en_US',ProfileId=p.Id,TimeZoneSidKey='America/New_York',UserName=uniqueUserName);
     System.RunAs(pu) {
          RestRequest req = new RestRequest();
          RestResponse res = new RestResponse();
          req.requestURI = '/services/apexrest/sfcheckap/';
          req.addParameter('useremail','testuserid@red.com');
          req.addParameter('casenumber','00001026');
          req.httpMethod = 'GET';
          RestContext.request = req;
          RestContext.response = res;
          System.debug('Current User assigned is: ' + UserInfo.getUserName());
          System.debug('Current Profile assigned is: ' + UserInfo.getProfileId());
          Test.startTest();
          Map<String, Boolean> resultMap = MyRestResource1.doGet();
          Test.stopTest();
          Boolean debugflag = resultMap.get('accessPermission');
          String debugflagstr = String.valueOf(debugflag);
          System.assert(debugflagstr.contains('true'));
        }
    }
}

A: Found a solution path by using: @isTest(SeeAllData=true)
See article:  "Using the isTest(SeeAllData=true) Annotation"
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_seealldata_using.htm


text:
Q: dropzone using a form in laravel I added dropzone in a form in laravel and every single time I add the images the form immediately submits without me clicking on the submit button. Please refer to following codes:
Here are the codes from the dropzone vue component
<template>

            DROP IMAGE(S) HERE

</template>

Here are the codes from the BlogsController.php:
    public function store(Request $request)
{
    if(! is_dir(public_path('blog_images'))){
        mkdir(public_path('/blog_images'), 0777);
    }
    $blogimages = Collection::wrap( request()->file('file'));

    $blogimages->each(function($blogimage){
        $basename = Str::random();
        $original = $basename . '.'. $blogimage->getClientOriginalExtension();

        $blogimage->move(public_path('/blog_images'), $original);

        Blog::create([
            'original' => '/blog_images/' . $original,
        ]);

    });
    $blog = Blog::create($this->validateRequest());

    return view('blog.index');
}

public function validateRequest()
{
    return request()->validate([
        'title' => 'required',
        'caption' => 'required',
    ]);
}

Here are the codes from the create.blade.php which contains the form:

<form action="/blog" method="POST" enctype="multipart/form-data">

        Blog Title

            <input id="title" type="text" class="form-control @error('title') is-invalid @enderror" name="title"
                value="{{old('title') }}" autocomplete="title" placeholder="Title">

{{ $errors->first('title') }}

        Blog Caption

            <input id="caption" type="text" class="form-control @error('caption') is-invalid @enderror" name="caption"
                value="{{old('caption') }}" autocomplete="caption" placeholder="caption">

{{ $errors->first('caption') }}

        Blog Images

            <dropzone-component></dropzone-component>

        <button type="submit" class="btn btn-primary"> Post Blog</button>
@csrf
</form>

Here are the codes from the web.php file:
Route::resource('blog', 'BlogsController');

Here are the codes from the create_blogs_table.php
Schema::create('blogs', function (Blueprint $table) {
        $table->id();
        $table->timestamps();
        $table->string('original');
        $table->string('title');
        $table->string('caption');
    });

A: You can set the options:
autoProcessQueue: false
parallelUploads: 10

So the dropzone does not upload immediately.


text:
Q: Modifying Exchange ACL for folders with python while try to read the ACL Table of a folder, I ran into this problem:
In a C++ tool (MFCMAPI) this method is used to get the Property PR_ACL_TABLE in a usable data type:
// Open the table in an IExchangeModifyTable interface
 EC_H(lpMAPIProp->OpenProperty(
  ulPropTag,
  (LPGUID)&IID_IExchangeModifyTable,
  0,
  MAPI_DEFERRED_ERRORS,
  (LPUNKNOWN FAR *)&lpExchTbl));

I figured out to do this in python win32:
table = mystore.OpenProperty(mapitags.PR_ACL_TABLE, IID_IExchangeModifyTable, 0 , mapi.MAPI_DEFERRED_ERRORS)

But it seems that the MAPI Extension does not know the IID_IExchangeModifyTable type. I just got just this error:
AttributeError: 'module' object has no attribute 'IID_IExchangeModifyTable'
Does anybody know another way to get and modify the ACL data from exchange via the MAPI (and python)?
Thanks
- Marquies

A: According to the docs, you need a PyIID object.

However, in almost all cases,
  functions that expect a CLSID/IID as a
  param will accept either a string
  object, or a native PyIID object.

That said, I've seen mapi.IID_IMessage used with the OpenProperty method.

A: IExchangeModifyTable is declared in edkmdb.h
Are you using mapi33 in python? Is that interface even declared in mapi33?
You can use RDOFolder.ACL in Redemption (I am its author): http://www.dimastr.com/redemption/rdo/RDOACL.htm

A: It looks like you are trying to access the ACL table on a message store object.  As far as I know, ACL tables are specific to folder objects and don't exist on message stores.  Try using your "mystore" object to open a particular folder within the store, and then call OpenProperty on the folder object to retrieve the ACL table. Make sure you open the folder object with the MAPI_NO_CACHE and MAPI_MODIFY flags specified as well.


text:
Q: Configuring database access for local version of Heroku app I'm modifying the "Getting Started on Heroku with Java" sample app (documentation from Heroku / source on Github) and having trouble with my local database connection.
The relevant code is from the main class:
public class Main {
    @Value("${spring.datasource.url}")
    private String dbUrl;

[...]

    @Bean
    public DataSource dataSource() throws SQLException {
        if (dbUrl == null || dbUrl.isEmpty()) {
            return new HikariDataSource();
        } else {
            HikariConfig config = new HikariConfig();
            config.setJdbcUrl(dbUrl);
            return new HikariDataSource(config);
        }
    }

The value of dbUrl is pulled by Spring from the application.properties file, which has the contents
spring.datasource.url: ${JDBC_DATABASE_URL:}
spring.datasource.hikari.connection-timeout=30000
spring.datasource.hikari.maximum-pool-size=10

[...]

So, the properties file just refers to another variable, ${JDBC_DATABASE_URL:}. According to Heroku's documentation on database connections, ${JDBC_DATABASE_URL:} is generated at runtime. On the deployed version, the app figures out the "real" DB URL just fine, but when I run locally, I get the Hikari error

dataSource or dataSourceClassName or jdbcUrl is required.

when attempting to access the DB or even just get a connection from the connection pool.
I've already

*

*downloaded the latest version of Postgres to my local machine

*verified that it's using port 5432 as expected

*set the DATABASE_URL environment variable on the command line using set DATABASE_URL=postgres://my_db_user:somePassword@localhost:5432/my_local_db_name
What more configuration do I have to do to get the app to run locally? Or more specifically, how do I get the local version of the app to have the correct DATABASE_URL/JDBC_DATABASE_URL value?

A: Instead of setting DATABASE_URL locally, set JDBC_DATABASE_URL like this:
JDBC_DATABASE_URL=jdbc:postgresql://localhost:5432/my_local_db_name?user=my_db_user&password=somePassword

You can also put this in your .env file if you're using heroku local.


text:
Q: reactjs: how to convert twitters key + secret string to base64 I am trying to use rest api of twitter. Presently i want to use the search api. For that I only need the application only authentication. I am using reactjs frontend. I am using the react library inside the html. The following is the code to create a combined key + secret. I dont know how to convert to base64.
            var key = "*****************";
            var secret = "******************";
            var cat = key +":"+secret;
            var credentials = ?? How to convert cat to base64 ??

This is the full code. Let me know which libraries i have to include.
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <title>Twitter API</title>

A: This should do it.
var credentials = new Buffer(cat).toString('base64');

If 'Buffer' is not available, try:
var credentials = window.btoa(cat);


text:
Q: Getting response from AJAX call - accepting callbacks I read about AJAX and getting calls from it and Im trying to restructure code, to get work.
Working on functions that accept callbacks.
I created code, but still variable error is not working outside the AJAX.
    $('.login').submit(function(e) {

        e.preventDefault();
        var error = 0;

    var email = $email.val();

    // function that makes a request and returns a promise:
    function testAjax() {
        return $.ajax({
            url: 'MY URL',
            data: {
            'email': email
            },
            type: 'POST',
        });
    }

    // function that expects a promise as an argument:
    function displayData(x) {
        x.success(function(realData) {
            if (realData == 1) {
                createErrTult("Błąd! taki email już istnieje w bazie!", $email)

    //THAT VARIABLE IS STILL NOT WORKING OUTSIDE AJAX
                error++;
            }
        });
    }

    // get a promise from testAjax:
    var promise = testAjax();

    // give a promise to other function:
    displayData(promise);

            if (error!=0)return;
        self.find('[type=submit]').attr('disabled', 'disabled');

        self.children().fadeOut(300,function(){ $(this).remove() })
        $('
sign in
welcome to A.Movie

You have successfully
 signed in!
').appendTo(self)
        .hide().delay(300).fadeIn();

});

How I can fix that problem? Thought that did that code correct.

A: Try
$('.login').submit(function(e) {

e.preventDefault();
var error = 0;

var email = $email.val();

// function that makes a request and returns a promise:
function testAjax() {
    return $.ajax({
        url: 'MY URL',
        data: {
        'email': email
        },
        type: 'POST',
    });
}
var error = 0;
var promise = testAjax();
function displayData(x) {
   return x.then(function(realData) {
        if (realData == 1) {
            createErrTult("Błąd! taki email już istnieje w bazie!", $email)

//THAT VARIABLE IS STILL NOT WORKING OUTSIDE AJAX
            error++;
        }
    }, function(jqxhr, textStatus, errorThrown) {
       console.log(errorThrown)
    });
};
displayData(promise).then(function(data) {
     // if (error !=0 ) return;
     // evaluate `error` status here ,
     // do stuff
});

function test() {
  return $.ajax("https://gist.githubusercontent.com/guest271314/6a76aa9d2921350c9d53/raw/49fbc054731540fa68b565e398d3574fde7366e9/abc.txt")
};
var error = 0;
var promise = test();
function displayData(x) {
   return x.then(function(realData) {
       if (realData) {
            console.log("Błąd! taki email już istnieje w bazie!")

//THAT VARIABLE IS STILL NOT WORKING OUTSIDE AJAX
            error++;
        }
    }, function(jqxhr, textStatus, errorThrown) {
       console.log(errorThrown)
    });
};
displayData(promise).then(function(data) {
  if (error !== 0)
  console.log(error)
})


text:
Q: Understanding ls */ -d * means all files and directories including files in sub directories.
/ means in root directory
ls */ brings files in sub directories in current directory (not includes files in current directory)
ls -d list directory entries instead of contents.
My directory full of files and sub directories. Why in my case this brings only ./ ?
By adding all together I have ls */ -d. It brings all directories in current directory. What is logic of this combination? If I take separate parts of this command listed it not brings such result.

A: / doesn't mean root directory. It's a path separator. If the path begins with /, then of course, you have an absolute path, which starts at the root level. Here, the slash comes after *. The asterisk globs all the entries of the current directory, but here, the pattern is */: everything in the current directory that ends on a /; files don't end on /, but ending a path with a slash means you specified a directory, so this only means directories. Compare with *.txt which would mean all entries ending with .txt.


text:
Q: Remove chapter from ToC without losing the numbering in the document I'm trying to remove a chapter in the ToC to instead replace it with a custom text.
A easy way is do like this:
\chapter*{Chapter}
\addcontentsline{toc}{chapter}{Custom chapter name}

But this unfortunately removes all chapter numbers in the
underlying sections and subsections.

How can I go around this?

A: Here's a somewhat cleaner way (in my point of view) to provide a different chapter number title:
Either manipulate the tocdepth counter temporarily or use \chapter[Other ToC Title]{Different in - body - title}.

\documentclass{book}

\usepackage{blindtext}

\begin{document}

\tableofcontents
\chapter{A regular chapter}
\blindtext[10]
\addtocontents{toc}{\protect\setcounter{tocdepth}{-5}} % Switch off toc appeareance for a moment
\chapter{In - document chapter name}
\addtocontents{toc}{\protect\setcounter{tocdepth}{3}}
\addcontentsline{toc}{chapter}{Custom chapter name}
\section{Foo}
\blindtext

\chapter[And yet another chapter title in ToC]{And this is the long chapter title that shouldn't appear in ToC!}
\section{Foo bar}
\blindtext[10]

\chapter{Another regular Chapter}
\section{Foo bar bar}
\blindtext

\end{document}

A: Perhaps \refstepcounter{chapter} as in
\refstepcounter{chapter}%
\chapter*{Chapter}
\addcontentsline{toc}{chapter}{Custom chapter name}%

does the trick.


text:
Q: Semantic-ui - how to prevent semantic-ui css file from globally taking over other divs / parts of the page / app I am loading basic semantic-ui.min.css through CDN, ie:
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.2/semantic.min.css"></link>

However, my page has other divs like this:

I would like semantic-ui css to be applied selectively to only:

div #menu-in-react

and not to

div #container-for-non-react-stuff

However, right now, by including the semantic-ui-css file, it is applying its style to div #container-for-non-react-stuff too.
How do I limit the application of semantic-ui.css to only specific divs (or exclude from certain divs)?
Note: I also tried using require('./myDist/semantic.css') using webpack to load the css, but this also ended up in semantic-ui taking over all my divs.
Thanks!

A: If you use sass, you can nest the entire semantic ui framework inside a parent selector so that it only applies to elements within:
#menu-in-react {
  @import 'semantic-ui';
}

See here for more info:
https://codepen.io/trey/post/nesting-sass-includes
Do note that you'll have to save the framework css as a local sass partial like _semantic-ui.scss in order for this to work, as sass imports will not parse externally hosted resources.
I wouldn't recommend importing the entire framework without cleaning up some of it at least; the framework css includes some dom element styles (ie. html, body, etc) which would be quite useless when nested in a parent selector.


text:
Q: Why are C++ classes allowed to have zero data members? question about c++
why minimal number of data members in class definition is zero
i think it should be one , i.e pointer to virtual table defined by compiler
thanks a lot

A: I'm working on a library that sometimes even uses types that – gasp! – aren't even defined, much less have data members!
That is, the type is incomplete, such as
struct foobar;

This is used to create an unambiguous name, nothing more.
So what is this useful for? Well, we use it to create distinct tags, using an additional (empty, but fully defined) type:
template <typename TSpec>
struct Tag {};

Now you can create distinct tags like so (yes, we can declare the type inside the template argument list, we do not need to declare it separately):
using ForwardTag = Tag<struct Forward_>;
using RandomAccessibleTag = Tag<struct RandomAccessible_>;

These in turn can be used to disambiguate specialized overloads. Many STL implementations do something similar:
template <typename Iter>
void sort(Iter begin, Iter end, RandomAccessibleTag const&) …

Strictly speaking, the indirect route via a common Tag class template is redundant, but it was a useful trick for the sake of documentation.
All this just to show that a (strict, static) type system can be used in many different ways than just to bundle and encapsulate data.

A: Well, actually C++ mandates that all classes must occupy some space (You need to be able to generate a pointer to that class). They only need a pointer to a vtable though, if the class is polymorphic. There's no reason for a vtable at all in a monomorphic class.

A: It is often useful to have a class with no data members for use in inheritance hierarchies.
A base class may only have several typedefs that are used in multiple classes.  For example, the std::iterator class template just has the standard types defined so that you don't need to define them in each iterator class.
An interface class typically has no data members, only virtual member functions.
A virtual table has nothing to do with the data members of a class.

A: Another use of a class with no data-members is for processing data from other sources. Everything gets passed into the class at runtime through pointers or references and the class operates on the data but stores none of it.
I hadn't really thought about this until I saw it done in a UML class I took. It has it's uses, but it does usually create coupled classes.

A: Because classes are not structures.  Their purpose, contrary to popular belief, is not to hold data.
For instance, consider a validator base class that defines a virtual method which passes a string to validate, and returns a bool.
An instance of a validator may refuse strings which have capital letters in them.  This is a perfect example on when you should use a class, and by the definition of what it does, there's clearly no reason to have any member variables.

A:
question about c++ why minimal number of data members in class definition is zero

It is zero because you have various cases of classes that should have no members:
You can implement traits classes containing only static functions for example. These classes are the equivalent of a namespace that is also recognizable as a type. That means you can instantiate a template on the class and make sure the implementation of that template uses the functions within the class. The size of such a traits class should be zero.
Example:
class SingleThreadedArithmetic
{
    static int Increment(int i) { return ++i; }
    // other arithmetic operations implemented with no thread safety
}; // no state and no virtual members -> sizeof(SingleThreadedArithmetic) == 0

class MultiThreadedArithmetic
{
    static int Increment(int i) { return InterlockedIncrement(i); }
    // other arithmetic operations implemented with thread safety in mind
}; // no state and no virtual members -> sizeof(MultiThreadedArithmetic) == 0

template<class ThreadingModel> class SomeClass
{
public:
    void SomeFunction()
    {
        // some operations
        ThreadingModel::Increment(i);
        // some other operations
    }
};

typedef SomeClass<SingleThreadedArithmetic> SomeClassST;
typedef SomeClass<MultithreadedArithmetic>  SomeClassMT;

You can define distinct class categories by implementing "tag" classes: classes that hold no interface or data, but are just used to differentiate between separate "logical" types of derived classes. The differentiation can be used in normal OOP code or in templated code.
These "tag" classes have 0 size also. See the iterators tags implementation in your current STL library for an example.
I am sure there are other cases where you can use "zero-sized" classes.


text:
Q: Can you inject code/an exe into a process with python? I've seen a few sites talking about injecting DLL's (such as http://www.codeproject.com/KB/DLL/DLL_Injection_tutorial.aspx), but I'm struggling with how to get an EXE to work. any help/tips would be appreciated.
The best way I know how to explain it is "RunPE" where you execute an exe in the memory. Does that help at all?

A: If you're asking how to inject code into a running Python process, what you want is https://github.com/lmacken/pyrasite .

A: You can use the Reflective DLL Injector as described here. Metasploit project uses it to load its meterpreter plug-ins. AFAIK this is the only way to inject a DLL, as MS officially does not support "injecting" from memory, only loading from file system.
On a low level, nothing forbids you from allocating a memory region, loading code there, marking it executable.
Note, that none of these techniques are Python specific or even Python related - it is a win32 problem.

A: What you're talking about is re-implementing UPX in python with more stuff.
Things you would need to do in order to do this:
Change all VirtualAlloc calls to be VirtualAllocEx calls.
Change all Loadlibrary calls to be loadlibraryEX calls.
Implement the relocation fix-ups.
A better approach would probably be tweaking UPX to output a DLL instead of an executable.  Then using some python DLL injection code to throw that into another process.  You're going to be working with CTypes a lot if you want to do this.  Fair warning...

A: I would recommend this book http://www.amazon.com/Gray-Hat-Python-Programming-Engineers/dp/1593271921  - especially the chapters on writing your own debugger, but it covers the metasploit and other tools as described above.

A: To inject a shared object (.so, .dll) into any process you can use injector with C, or pyinjector with python/shell.
To inject python code into a running python process, you can use hypno.


text:
Q: Examine the uniform continuity $f(x)=(e^{x}-1)\sin\frac{1}{3^x-1}$ for $x \in (0,+\infty)$ My try:
I know that if for all $x_{n},y_{n}$ condidion $\lim_{n \rightarrow +\infty}(x_{n}-y_{n})=0$ implies $\lim_{n \rightarrow +\infty}(f(x_{n})-f(y_{n})=0$ then $f$ is uniform continuity.
Let: $$x_{n}=\frac{1}{n}$$ $$y_{n}=\frac{1}{2n}$$Then:$$x_{n}-y_{n}=\frac{1}{2n} \rightarrow 0$$
$$f(x_{n})-f(y_{n})=(e^{\frac{1}{n}}-1)\sin\frac{1}{3^{\frac{1}{n}}-1}-(e^{\frac{1}{2n}}-1)\sin\frac{1}{3^{\frac{1}{2n}}-1}$$
I know that $f(x_{n})-f(y_{n})$ is periodic so $\lim \neq 0$ so I find counterexample that $f$ is uniform continuity.However I don't know how I can show it in a professional way.Have you some idea?

A: This limit is equal to zero because
$$\lim_{n\to\infty} (e^{\frac1{kn}}-1)=0$$
given that $k\in\mathbb{R}$, $k\ne0$. As $\sin{(x)}$ is bounded for any $x\in\mathbb{R}$ the value of the two multiplied together is still zero. Also $f(x_n)-f(y_n)$ is not periodic.

A: Show that $\lim_{x \downarrow 0} f(x) = 0$, $\lim_{x \to \infty} f(x) = 0$ and combine
this with uniform continuity of continuous functions on compact intervals to show that
$f$ is uniformly continuous.


text:
Q: ValueError: Input 0 of layer "model_1" is incompatible with the layer: expected shape=(None, 5312), found shape=(None, 168) I am unable to train the model. Someone, please help!!!!!
Here is the code I am trying. While running model_history = model_final.fit([X_weather, X_soil], y,batch_size=16, epochs=100) I am getting this error.
X_weather.shape
(25345, 168)
X_soil.shape
(25345, 66)

input1 = Input(shape=(168,1))
input2 = Input(shape=(66,1))
model_1D = Conv1D(16, kernel_size= 9 , strides=1, activation='relu')(input1)
model_1D = tf.keras.layers.AveragePooling1D(pool_size= 2, strides=2)(model_1D)
model_1D = Conv1D(32, kernel_size= 3 , strides=1, activation='relu')(model_1D)
model_1D = tf.keras.layers.AveragePooling1D(pool_size= 2, strides=2)(model_1D)
model_1D = Conv1D(48, kernel_size= 3 , strides=1, activation='relu')(model_1D)
model_1D = tf.keras.layers.AveragePooling1D(pool_size= 2, strides=2)(model_1D)
model_1D = Conv1D(64, kernel_size= 3 , strides=1, activation='relu')(model_1D)
model_1D = tf.keras.layers.AveragePooling1D(pool_size= 2, strides=2)(model_1D)
model_1D = Flatten()(model_1D)
model_s = Dense(10 , activation='relu')(input2)
model_s = Dense(10 , activation='relu')(model_s)
model_s = Flatten()(model_s)
merged = Concatenate()([model_1D, model_s])
output = Dense(128, activation='relu')(merged)
output = Dense(32 , activation='relu')(output)
output = Dense(1 , activation='relu')(output)
model_final = Model(inputs=[model_1D, model_s], outputs=[output])

model_final.compile(
    optimizer = RMSprop(learning_rate=0.02,rho=0.9,epsilon=None,decay=0),
    loss = 'mean_squared_error',
    metrics=['accuracy']

)

model_history = model_final.fit([X_weather, X_soil], y,batch_size=16, epochs=100)```


text:
Q: unordered list not visible when I test code in browser The following html code is leaving the whole unordered list invisible when I try to view it in browser from within eclipse.  I would like it to be simple html that works on any browser.  How do I change the below so that the unordered list becomes visible?  (Note: I edited the posting to include the full code.)

    <title>page title</title>
    <meta name="description" content="meta text.">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" type="text/css" href="css/mystyle.css">

                one

                  two

                  three

                  four

                  five

                six

the title

three items follow:

topic1: description1.

topic2: description2.

topic3: description3.

some text

some text.

some text.

Also, just for kicks, the css file contains the following:
h1 {color:#003366; font-size:150%; text-align:center}
h3 {color:#003366}
html {color:white}
p {margin-left:20px; color:#003366; font-size: large}
body {margin: 0; padding: 0; background-color:white;}
a.toc:link {color:#FFCC66;}      /* unvisited link */
a.toc:visited {color:#00FF00;}  /* visited link */
a.toc:hover {color:#FFFFFF;}  /* mouse over link */
a.toc:active {color:#336699;}  /* selected link */
a.body:link {color:#993300;}      /* unvisited link */
a.body:visited {color:#00FF00;}  /* visited link */
a.body:hover {color:#097054;}  /* mouse over link */
a.body:active {color:#336699;}  /* selected link */

A: You problem is a combination of these rules:
html {color:white}

and
body {margin: 0; padding: 0; background-color:white;}

the color rule is setting all the font to be white. White on white tends to be hard to see.
And for the font, based on what you have above.
p { margin-left:20px }
p, ul { color:#003366; font-size: large }


text:
Q: Error to open design Theme: Content-->Design-->Configuration? When I try to open Content-->Design-->Configuration and click on edit, it came up with below error.

1 exception(s): Exception #0 (RuntimeException): Can't create
  directory
  /home/tassosco/public_html/var/generation/Magento/Theme/Model/Design/Backend/Favicon/.

How can we resolve this?

A: As you can see in the comments you need to set proper permission for your var/generation folder. This is also given in the official documentation too.
As you can see in the error, Magento is trying to generate some files on the fly and it cannot create the file some how (this is most probably due to permission issue).
Either the apache user/command line user do not have the privilege to create files or folders or the permission to the var/generation folder is not 755. You need to make sure these two conditions are configured correctly in your M2 instance.
Please see below docs for your reference.

*

*Set ownership and permission in M2

*Cannot write to the var/generation directory


text:
Q: How to set encoding of a variable when passing between ASP pages Let's say I have page A, which uses ks_c_5601-1987(Korean) as encoding and page B, using UTF-8 (Korean) as encoding. I need to pass a string variable from A to B that is in Korean. Because two pages use a different encoding, the variable gets jumbled up when B receives it using Request().
How can I encode the string variable in A to UTF-8 when passing it to B? I'm aware that setting both pages as UTF-8 encoding scheme is the most sensible solution here but it unfortunately is not an option here since page A uses several dlls that relies entirely on ks_c_5601-1987 encoding.
Edit: After reviewing the answer, I have went ahead and tried the method. This is the code to send the variable mailbox into get_list_center.asp:

<%
dim mailbox = "테스트"
Response.CodePage = 65001 'Response.write should now encode the string into UTF-8
%>

...
<frame name="get_list_center" scrolling="auto" marginwidth="0" framespacing="0" marginheight="0" frameborder="0" src="get_list_center.asp?mailbox=<%=mailbox%>">

and this is how I'm receiving the variable in get_list_center.asp:
<%
Session.Codepage=65001

Response.CharSet="UTF-8"

response.Write CStr(response.codepage) & "
"
response.Write CStr(session.CodePage) & "
"
response.Write CStr(response.CharSet) & "
"
response.codepage = 949
response.Write mailbox & "
"
response.codepage = 65001
response.Write mailbox & "
"
%>

Here is the result:

Both 949 (ks_c_5601-1987) and 65001 (UTF-8) versions of response.write comes out broken. Is there anything else I'm missing?

A: I would think that you could get an answer by reading the solution to this question: internal string encoding
.
By utilizing Reponse.Codepage you can affect how posted variables are interpreted. And as I understand you can then switch back to wichever encoding you like.

[Update]
Because you are using an iframe it is the browser that handles the encoding when sending the request back to the server. And the browser (as I understand) sends the data in the same encoding as the originating page. So if page A that contains the iframe has the charset=Korean I believe that data is sent using Korean encoding.
Is the charset defined in the html  tag on page A? If not, add it and then try to use the same in page B.
<meta charset="utf-8">

Also, as "테스트" is a string literal that is affected of the FILE-encoding, make sure to save the asp-file in the appropiate encoding.


text:
Q: Capturing and saving objects coordinates with fabric js I am working on an app where a user can create multiple boxes on a canvas, save the coordinates of each box(Top, Left, Width, Height) individually in database, and later retrieve them back on a canvas, whenever needed to update its position.
I am able to do all this, except updating the position of the box.
For eg. Lets say user selects "box1":
1) canvas.on('mouse:down', function (evt) { }); - gives the current coordinates for box1, that matches with the database entry.
2) canvas.on('object:modified', function (evt) { }); - gives the new coordinates for box1, that I can use to update the database fields.
The only problem is, if the user selects box1, drag it some where, drops it, and again drags it to a new position. I loose the original value (since he clicked mouse:down twice for box1), and thus not able to finally identify, which box was updated wrt database.
Below is the code snippet:
window.addRect = function() {
  var box = new fabric.Rect({
    left: 0,
    top: 0,
    stroke: 'red',
    fill: 'rgba(255,0,0,.4)',
    width: 50,
    height: 50,
  });
  box.hasRotatingPoint = false;
  canvas.add(box);
}

canvas.on('object:modified', function (evt) {   // for updated values
var modifiedObject = evt.target;
console.log('modifiedObject: ' + modifiedObject.get('left'), modifiedObject.get('top'), modifiedObject.getScaledWidth(), modifiedObject.getScaledHeight());
});

canvas.on('mouse:down', function (evt) {  // for original values
var downObject = evt.target;
console.log('downObject: ' + downObject.get('left'), downObject.get('top'), downObject.getScaledWidth(), downObject.getScaledHeight());  });

Is there anything other than mouse:down and object:modified, that I can use? I am looking for a solution in Extjs.


text:
Q: how to create db back up jobs in sql server 2008? Microsoft SQL Server 2008 (X64) Microsoft Corporation  Developer Edition (64-bit)
i need to create a job for the SQL database to backup everyday
with a different set of new files
i tried doing it and it over rites everyday
i wanted it to create new files everyday...
Plz help me as soon as...
Note:
     If i want to create separate folder for each day and stored the back up...

How can i do that plz help me....

A: If that version include the SQL Agent you can schedule a backup with a SQL script like that:
Edit: corrected code to use dynamic SQL:
declare @sql as nvarchar(1000)
set @sql='BACKUP DATABASE YourDB TO DISK = ''D:\Backups\YourDB-'+convert(char(8),getdate(),112)+'.bak'''
exec sp_executesql @sql

A: You should be able to do this with a Maintenance Plan and make use of the Back Up Database Task. Taking a look at our backup schedule this generates a new file for the backup each day, with a date and time stamped filename. I believe this is in fact the default and as a consequence for our scenario we also have a cleanup task to delete older backups.

A: If there is no solution using SSMS, you might try my Powershell script automssqlbackup.


text:
Q: Python / Tensorflow 'list' object has no attribute 'shape' on yolov3 model I have the following code which uses TensorFlow. After I reshape a list, it says
'list' object has no attribute 'shape'

when I try to print its shape.
image_batch, label_batch = next(iter(train_ds))
feature_batch = train_model(image_batch)
print(feature_batch.shape)

my code for yolov3 model
# define the model
model = make_yolov3_model()

# load the model weights
# I have loaded the pretrained weights in a separate dataset
weight_reader = WeightReader('yolov3.weights')

# set the model weights into the model
weight_reader.load_weights(model)

# save the model to file
model.save('model.h5')

# load yolov3 model
from keras.models import load_model
train_model = load_model('model.h5', compile=False)

Output

AttributeError                            Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_4412\2773113981.py in <module>
1 image_batch, label_batch = next(iter(train_ds))
2 feature_batch = train_model(image_batch)
----> 3 print(feature_batch.shape)
AttributeError: 'list' object has no attribute 'shape'

Could anyone please tell me what I am missing?

A: The Python "AttributeError: 'list' object has no attribute 'shape'" occurs when we try to access the shape attribute on a list.
Lists do not have any attribute name shape.
To solve this error, pass the list to the numpy.array() method to create a numpy array before accessing the shape attribute.
So, you can do:
import numpy as np
feature_batch=np.array(feature_batch)
print(feature_batch.shape)


text:
Q: Selecting specific columns based in column name from several sheets of an excel workbook I've got an excel workbook with several sheets. Each sheet represents a year and contains several columns. Not all the sheets have the same columns names but I want to pull out specific columns with names that are shared in all sheets.
I've imported the sheet using the following function to make it into a list
    sheets <- readxl::excel_sheets(filename)
    x <- lapply(sheets, function(X) readxl::read_excel(filename, skip = 2, sheet = X))
    if(!tibble) x <- lapply(x, as.data.frame)
    names(x) <- sheets
    x }

I now have a large list containing about 7 elements. I created another list containing the column names I want to pull out from each sheet
select <-list(c("average","total","percentage","year on year"))
How do I use this list to pull out the respective columns from each sheet into a new df?
Sorry if fairly obvious and thanks in advance for any advice!

A: We may select the columns afterwards.  Also, instead of list of element 1, just pass a vector of column names
library(purrr)
library(readxl)
nm1 <- c("average","total","percentage","year on year")
map(sheets, ~ readxl::read_excel(filename, skip = 2, sheet = .x) %>%
                dplyr::select(all_of(nm1)) %>%
                 as_tibble))


text:
Q: Why doesn't highcharts refresh this chart correctly? Highcharts is failing to refresh my chart in any kind of intelligent way.This seems like a fairly common use case:
I am rendering an area percentage chart, which renders perfectly the first time. At some point the data changes and I want to refresh the chart.
The word on the streets is that I should manually iterate my data and call setData on each series. The problem with this approach is that the series are not guaranteed to be the same when I am trying to refresh. So there are edge cases where using this technique would mismatch data.
I tried this :
data = this.getAreaChartData();

if (data !== null && data !== undefined) {

var dataLength = data.length;
for (var dataIndex = 0; dataIndex < dataLength; dataIndex++) {

    var currentSeries = data[dataIndex];

    this.chart.series[dataIndex] = currentSeries;

}

For the sake of simplicity let's assume that getAreaChartData() produces perfectly valid data. When I set the series like this nothing happens and the chart gets buggy.
I try to call chart.redraw() just to see if I can force it and still nothing happens.
What am I doing wrong ?

A: You should use update to update a serie with a new set of options.
Like the following:
data = this.getAreaChartData();

var dataLength = data.length,
    chart = this.chart;
for( var dataIndex = 0; dataIndex < dataLength; dataIndex++ ) {

    // add series without redraw, we'll redraw later
    chart.series[ dataIndex ].update( data[dataIndex], false );
}

chart.redraw();

Reference:

*

*http://api.highcharts.com/highstock#Series.update()

A: You should use setData function after updating the data in your series. Only then highcharts would come to know that you have made changes in your data. It makes more sense to use setData as compared to update function as it is mentioned in the docs that update function is more expensive (performance wise).
http://api.highcharts.com/highstock#Series.update


text:
Q: hdd goes to sleep only when in hotplug i have absolutely quiet computer while in idle mode. Only 1 thing is making noise - that is hdd that I use very rarely, so it always keeps spinning though I'm not using it.
In fact I have a case with hot-plug for hdd and when I plug it in there it stops spinning after about 1 minute (sleep mode for hdd after 1 min in windows enabled).  How can I make it do the same thing while hdd is internal? (hotplug mode is enabled for all satas in bios). I'm running under Windows 7  64-bit. Thank you.

A: Problem solved after I plugged in my hdd to a sata port on motherboard where hot-plug module was plugged in, seems strange to me.


text:
Q: symmetric matrix half vectorization I am facing an issue concerning how to store the lower triangular factor of a given symmetric matrix (it's a distance matrix) into a vector.
Generally, I would like directly generating the lower triangular entries by only giving the coordinates (Y,Z) of a set of points on a rectangular grid: and actually it's where I got terribly stuck.
So that, I started thinking to attack the problem from a slightly different point of view: generating the full distance matrix (again given the (Y,Z) couples) and then half vectorize the distance matrix.
Nevertheless, I don't really have a sound idea on how to achieve the goal by means of for loops.
Besides I also know that there may be any external Java library which implements the vech function: vech returns the vector obtained by eliminating all supradiagonal elements of the square matrix X and stacking the result one column above the other. This has uses in matrix calculus where the underlying matrix is symmetric and it would be pointless to keep values above the main diagonal.
Substantially, given a matrix A = {{a,c},{b,d}}, by applying vech(A), the result will be
vech(A) = {a,b,d}.
EDIT
I mean something like the following:
    a11 a12 a13 a14
        a22 a23 a24
 A=         a33 a34  (aij = aji)
                a44

Packed storage of the upper triangle of A:
  AP = { a11, a12, a22, a13, a23, a33, a14, a24, a34, a44 }

A: public static double[] vech(double[][] a) {
    int na = Math.min(a.length, a[0].length); // Dimension of the matrix
    int nv = na * (na + 1) / 2; // 1 + 2 + 3 + .. + na
    double[] v = new double[nv];
    int k = 0; // index in v.
    for (int i = 0; i < na; ++i) {
        for (int j = 0; j <= i; ++j) {
            v[k] = a[i][j];
            ++k;
        }
    }
    return v;
}

Case 2x2 Matrix:
Picks [0][0], [1][0], [1][1] (skipping [0][1])
Row-major order: (C, C#, Java) a[i][j] is element at row i, column j.
The code flattens the bottom left triangle.
Column-major order: (MATLAB, SciLab) a[i][j] is element at column i, row j.
The code flattens the upper right triangle.
Other sequence
The other triangle would be given as:
        for (int j = i; j < na; ++j) {

Combined with mirroring in the main diagonal, one receives the orignal triangle again:
            a[j][i]

A: There is another interesting thing about all this packing. You can also define a mapping algorithm to convert (i, j) positon in symmetric matrix into equivalent offset in flatten array (just like you described). You can use ideas of Arithmetic progression to define such mapping. I did this while working on RandomSymmetricMatrixSource.java class in la4j. So, you can use these formulas (it doesn't handle the case when i == j):
int flatten(int i, int j) {
  int offset = -1;

  if (i < j) {
    offset = j - (i + 1) + (int)((((size - 1) + (size - i)) / 2.0) * i);
  } else {
    offset = i - (j + 1) + (int)((((size - 1) + (size - j)) / 2.0) * j);
  }

  return offset;
}

, where size is the size of symmetric matrix.

A: I can't think of a library that would let you do this, although i'm sure there is one somewhere, but you could use a for loop as follows:
ArrayList<ArrayList<int>> matrix = new ArrayList<ArrayList<int>>();
// add other arraylists to your matrix here i.e.:

ArrayList<Integer> first = new ArrayList<Integer>();
first.add(1);
first.add(2);
first.add(3);

ArrayList<Integer> second = new ArrayList<Integer>();
second.add(4);
second.add(5);
second.add(6);

ArrayList<Integer> third = new ArrayList<Integer>();
third.add(7);
third.add(8);
third.add(9);

matrix.add(first);
matrix.add(second);
matrix.add(third);

ArrayList<int> finalArray = new ArrayList<int>();

for(int i=0; i<matrix.size(); i++)
{
    ArrayList<Integer> inner = matrix.get(i);
    for(int j=0; j<i+1; j++)
    {
        finalArray.add(inner.get(j));
    }
}

This gives: matrix=[[1, 2, 3], [4, 5, 6], [7, 8, 9]] and finalArray=[1, 4, 5, 7, 8, 9]
Of course, this is assuming your matrix is structured using arraylists.


text:
Q: Group Pandas data frame by number of rows and create a new column with group number I want to identify every x number of rows with a unique id. The last group can take less than x rows if the reminder is smaller than x.
From the example below, I want to create the column group_id that attributes an id for every 3 observations.
   foo  group_id
0    1  1
1    2  1
2    3  1
3    4  2
4    5  2
5    6  2
6    7  3
7    8  3
8    9  3
9   10  4

A: Another variant which may offer some flexibility :)
1. First for what you initially requested:
mylist = [[i+1]*3 for i in range(len(df))]
df['group_id'] = np.resize(mylist,len(df))
df

index
foo
group_id

0
1
1

1
2
1

2
3
1

3
4
2

4
5
2

5
6
2

6
7
3

7
8
3

8
9
3

9
10
4

2. What if you would like to attribute strings?
mylist = [[i]*3 for i in ['aaa','bbb','ccc','ddd']]
df['group_id'] = np.resize(mylist,len(df))
df

index
foo
group_id

0
1
aaa

1
2
aaa

2
3
aaa

3
4
bbb

4
5
bbb

5
6
bbb

6
7
ccc

7
8
ccc

8
9
ccc

9
10
ddd


text:
Q: Reading file's columns into array i'm reading file which has some number of columns each line has different number of columns and they are numerical values of different length, and i have fix number of rows (20) how to put each column in to array?
suppose i have data file like following (there is tab between each column)
20   30      10
22   10       9       3     40
60    4
30    200   90
33    320    1        22    4

how to put these columns into different array,, that column 1 goes to one arrary and column 2 goes to another. Only column 2 has more than 2 digit values and the rest of columns has 1 or two digit values, and some columns are null too except 1, 2, and 3
int main()
{
    ifstream infile;
    infile.open("Ewa.dat");

    int c1[20], c2[20], ... c6[20];

    while(!infile.eof()) {
        //what will be the code here?
        infile >>lines;
        for(int i = 1; i<=lines; i++) {
            infile >> c1[i];
            infile >> c2[i];
             .
             .
            infile >> c6 [20];
        }
    }
}

A: Here's the main idea:
Use a 2D array instead of many 1D arrays.
Read each line using std::string.
Then use:     istringstream is(str); which will help parse the string and put into the arrays like this:
while(...) {
    ....
    getline(infile, str);
    istringstream is(str);
    j=0;
    while(is)
        {
            is >> c[i][j];
        }
    i++;
    ....
    }

I'll leave the rest to you.

A: It might be easier to take advantage of some of some C++ library classes, like std::vector, std::istringstream, and std::string:
#include <vector>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

int main() {
  std::vector<std::vector<int> > allData;

  std::ifstream fin("data.dat");
  std::string line;
  while (std::getline(fin, line)) {      // for each line
    std::vector<int> lineData;           // create a new row
    int val;
    std::istringstream lineStream(line);
    while (lineStream >> val) {          // for each value in line
      lineData.push_back(val);           // add to the current row
    }
    allData.push_back(lineData);         // add row to allData
  }

  std::cout << "row 0 contains " << allData[0].size() << " columns\n";
  std::cout << "row 0, column 1 is " << allData[0][1] << '\n';
}


text:
Q: Issues with make jQuery ajax call to a rest api I am trying to use jquery ajax to make a post request that returns some response but it does not seem to work properly. Sometimes it works after a long wait, other times it does not work at all.This is my code.

<script type="text/javascript">

const id =  $('#auth').val();
  $("#set").click(function(){
    $('.spinner-grow').show();

  $.post("https://ravesandboxapi.flutterwave.com/v2/gpx/transactions/escrow/settle",
  {
    id: id,
    secret_key: "FLWSECK-25*******************0628-X"
  },

  function(data, status){
    alert("Data: " + data + "\nStatus: " + status);
    $('.spinner-grow').hide();
  });
});

</script>

what might be the issue here?

A: The following is a complete example of a AJAX post is handled via jQuery. Just sharing it for reference.
    var url = "api/path/to/your/controller";
    var data = {};
    data.id = id;
    data.secret = 'your-secret';
    $.ajax({
        type: 'POST',
        url: url,
        data: data,
        success: function (resultObject) {
            console.log(resultObject);
        },
        error: function (err) {
            console.log('An error occured');
        }
    });

If you are getting a 404 error, better check the path to the API. You can use a tool like Postman to validate your requests and then try implementing the same in code.
Also make sure that there is no CORS issue as from your code we cannot understand if your post is triggered from the same domain.


text:
Q: flexbox fixed width and fixed row count I made a site and using CSS flexbox for layout.
First, look at the below code that I worked.

html, body {
  margin: 0;
  padding: 0;
}
.wrap {
  height: 100%;
  background-color: antiquewhite;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
}
.box {
  flex: 0 0 350px;
  height: 350px;
  background-color: aquamarine;
  border: 1px solid black;
}

My goal is here.

*

*Make every box's width fixed to 350px.

*Regardless of browser's size, one row must have only 3 boxes. (If browser size getting bigger)

*Do not consider case of smaller size browser.
So I defined flex: 0 0 350px to .box and flex-wrap: wrap to .wrap
But it works differently with my expectation.
Is there any way to implement fixed width flexbox?
Or solution here?
Thanks.

A:

html, body {
  margin: 0;
  padding: 0;
/* add height so that .wrap height: 100% knows what it's a percentage of */
height:100%;
}
.wrap {
  height: 100%;
  background-color: antiquewhite;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
/* add widths so that you will always have three in a row */
min-width:1056px; /* extra 6px to cater for border */
max-width:1056px;
width:1056px;
}
.box {
  flex: 0 0 350px;
  height: 350px;
  background-color: aquamarine;
  border: 1px solid black;
}


text:
Q: How do you make a bow that shoots fireworks instead of arrows? I would like to know how to make a bow that shoots fireworks in place of arrows. I already have a feature where when the arrow hits the ground, it explodes and releases a firework. If you think you got it, or need more information, tell me below.

A: I think I have it. The operation requires four commands, not counting the fill clock. The arrow will still exist but will spawn fireworks that explode immediately.
Type this in chat:
/scoreboard objectives add ground dummy ground

1st Command Block on fill clock:
/scoreboard players set @e[type=Arrow] ground 0 {inGround:0b}

2nd Command Block on fill clock:
/scoreboard players set @e[type=Arrow] ground 1 {inGround:1b}

3rd Command Block on fill clock:
/execute @e[type=Arrow,score_ground=0] ~ ~ ~ summon FireworksRocketEntity ~ ~ ~ {LifeTime:-1,FireworksItem:{id:401,Count:1,tag:{Fireworks:{Explosions:[{Type:0,Flicker:0,Trail:0,Colors:[0],FadeColors:[0]}]}}}}

You can make your own firework to put in the execute command at http://www.minecraftupdates.com/fireworks but make sure the lifetime is set to -1.
I hope this helped and that this was what you were looking for.


text:
Q: Decode in insert statement I have many columns in table of which 2 columns are
A : number
B : varchar
I am trying to insert value in B based on value of A from java.
insert into table(A,B) values (? , decode('A',110,'ABC',NA));

this gives me an error : illegal number
So i tried the below :
insert into table(A,B) values (? , decode('A','110','ABC','NA'));

This always inserts NA in the column.
Can someone please help me with this ?

A: Instead of using 'A' you should provide the content of variable A


text:
Q: Incremental solving of GEKKO dynamic models I would like to use GEKKO to incrementally solve a dynamic model. I need to insert some parameters at different points in the simulation that are determined stochastically using an external model.
As a simple proof of concept, I tried adjusting the PID control example from the tutorial website to solve in 10 minute increments.
m = GEKKO()

tf = 40
timesteps = np.linspace(0,tf,2*tf+1)
step = np.zeros(2*tf+1)
step[3:40] = 2.0
step[40:]  = 5.0

# Controller model
Kc = 15.0                    # controller gain
tauI = 2.0                  # controller reset time
tauD = 1.0                  # derivative constant
OP_0 = m.Const(value=0.0)   # OP bias
OP = m.Var(value=0.0)       # controller output
PV = m.Var(value=0.0)       # process variable
SP = m.Param(value=step)    # set point
Intgl = m.Var(value=0.0)    # integral of the error
err = m.Intermediate(SP-PV) # set point error
m.Equation(Intgl.dt()==err) # integral of the error
m.Equation(OP == OP_0 + Kc*err + (Kc/tauI)*Intgl - PV.dt())

# Process model
Kp = 0.5                    # process gain
tauP = 10.0                 # process time constant
m.Equation(tauP*PV.dt() + PV == Kp*OP)

setpoint_final = []
pv_final = []
output_final = []
for i in range(8):
    SP.value = step[10*i:10*(i+1)]
    m.time = timesteps[10*i:10*(i+1)]
    m.options.IMODE=7
    m.solve(disp=False)
    setpoint_final.append(SP.value)
    pv_final.append(PV.value)
    output_final.append(OP.value)

plt.figure()
plt.subplot(2,1,1)
plt.plot(timesteps[:-1],np.concatenate(output_final),'b:',label='OP')
plt.ylabel('Output')
plt.legend()
plt.subplot(2,1,2)
plt.plot(timesteps[:-1],np.concatenate(setpoint_final),'k-',label='SP')
plt.plot(timesteps[:-1],np.concatenate(pv_final),'r--',label='PV')
plt.xlabel('Time (sec)')
plt.ylabel('Process')
plt.legend()
plt.show()

I should get something like this:

Instead it seems to reset at each interval:

Is there something I am missing or is this type of simulation not possible in GEKKO?

A: Try using m.options.TIME_SHIFT=10, m.options.IMODE=4, and change the way the values are stored.

from gekko import GEKKO
import numpy as np
import matplotlib.pyplot as plt

m = GEKKO(remote=False)

tf = 40
timesteps = np.linspace(0,tf,2*tf+1)
step = np.zeros(2*tf+1)
step[3:40] = 2.0
step[40:]  = 5.0

# Controller model
Kc = 15.0                    # controller gain
tauI = 2.0                  # controller reset time
tauD = 1.0                  # derivative constant
OP_0 = m.Const(value=0.0)   # OP bias
OP = m.Var(value=0.0)       # controller output
PV = m.Var(value=0.0)       # process variable
SP = m.Param(value=step)    # set point
Intgl = m.Var(value=0.0)    # integral of the error
err = m.Intermediate(SP-PV) # set point error
m.Equation(Intgl.dt()==err) # integral of the error
m.Equation(OP == OP_0 + Kc*err + (Kc/tauI)*Intgl - PV.dt())

# Process model
Kp = 0.5                    # process gain
tauP = 10.0                 # process time constant
m.Equation(tauP*PV.dt() + PV == Kp*OP)

setpoint_final = []
pv_final = []
output_final = []
m.options.TIME_SHIFT=10
m.time = timesteps[0:10]
for i in range(8):
    SP.value = step[10*i:10*(i+1)]
    m.options.IMODE=4
    m.solve(disp=False)
    setpoint_final = np.concatenate((setpoint_final,SP.value))
    pv_final = np.concatenate((pv_final,PV.value))
    output_final = np.concatenate((output_final,OP.value))

plt.figure()
plt.subplot(2,1,1)
plt.plot(timesteps[:-1],output_final,'b:',label='OP')
plt.ylabel('Output')
plt.legend()
plt.subplot(2,1,2)
plt.plot(timesteps[:-1],setpoint_final,'k-',label='SP')
plt.plot(timesteps[:-1],pv_final,'r--',label='PV')
plt.xlabel('Time (sec)')
plt.ylabel('Process')
plt.legend()
plt.show()


text:
Q: Making the arraylist get method work and other problems I am coding in blueJ. My objectives are this: 1)Write a User class
A User:
has a username e.g 'fj3'
has a userType which can be: 'user', 'editor' or 'admin'
has a name e.g 'Francis'
has a constructor which takes the username, userType and name as parameters
has a getUsername() method
has a getUserType() method
has a getName() method
has a setUserType() method which takes one of the user types as a parameter

2)Write a UserGroup class
The UserGroup class must have an ArrayList of Users.
Write a constructor for the UserGroup class. It should instantiate the ArrayList.
In UserGroup write a method called .addSampleData() which creates 10 Users and using the ArrayList's add() method put the 10 new User objects into the ArrayList.
In UserGroup write a getUser method which takes an int as a parameter and returns the User in that slot of the ArrayList.
In UserGroup write a printUsernames() method in UserGroup:
Using an enhanced for loop (see above), loop through the ArrayList and print the username and userType of each user in the ArrayList.
What I have so far is:
package user;
public class User{
    public enum UserType{
        ADMIN, EDITOR, USER;
    }

    private String id;
    private UserType userPermissions;
    private String actualName;

    public User(String username, UserType userType, String name){
        id = username;
        userPermissions = userType;
        actualName= name;
    }

    public String getUsername(){
        return id;
    }

    public UserType getUserType(){
        return userPermissions;
    }

    public String getName(){
        return actualName;
    }

    public void setUserType(UserType input){
        userPermissions = input;
    }
}

And my UserGroup class:
package user;
import java.util.*;
import user.User.UserType;

public class UserGroup{

    private ArrayList<User> people;

    public UserGroup(){
        people = new Arraylist<User>();
    }

    public static void addSampleData(String username, UserType userType, String name){
        people.add(new User(username, userType,name));
    }

    public User get(int){
        return User;
    }

    public void printUsernames(){
        for (User user: groupArray){
            System.out.printf("%s %s\n", user.getUsername(), user.getuserType);
        }
    }
}

This is obviously far from being complete but I am completely stuck. My first problem is that I am unsure how to write the get method for this. Please help me with this!! I think my User class is fine but my UserGroup class is nowhere near completing all the objectives and I don't know how to do them!!

A: Looks good so far, some corrections:
The addSampleData()method should not be static, as it uses a non-static member of the class. The request also states it to add the sample data itself.
The getUser() is pretty straight forward then.
The printUsernames()method uses an unknown member.
public void addSampleData() {
    people.add(new User("pe3", UserType.ADMIN,"Peter"));
    people.add(new User("u987", UserType.EDITOR,"Udo"));
    people.add(new User("frank123", UserType.USER,"Frank"));
    // repeat ...
}

public User getUser(int idx) {
    return people.get(idx);
}

public void printUsernames(){
    for (User user: people){
        System.out.printf("%s %s\n", user.getUsername(), user.getuserType);
    }
}

In a main method then:
UserGroup grp = new UserGroup();
grp.addSampleData();
grp.printUsernames();
User u1 = grp.getUser(0);


text:
Q: Why only one clustered index per table should be created in sql server? I have read tips about sql server database on http://www.sql-server-performance.com/2007/clustered-indexes
In conclusion section author mentioned:
"Since you can only create one clustered index per table, take extra time to carefully consider how it will be used."
My question is:
*Why only one clustered index per table should be created in sql server? *

A: This is simply SQL Server's implementation decision. Theoretically, there are can be any number of clustering indexes. MongoDB and MyISAM have no clustering indexes and store data in a flat file. InnoDB for MySQL has one clustering index, the primary key, which may be hidden if a primary key is not declared. TokuDB for MySQL and TokuMX (both of which I work on) allow users to have multiple clustering indexes, with the implicit tradeoff being more disk space used for faster queries.

A: Because the clustered index is the way that the data in the table is ordered when it is written to disk.  In other words, the clustered index is the table.
This is also why you cannot specify included columns on a clustered index - because by its nature all of the columns are already included.

A: A clustered index sorts and stores the data rows in the table based on the index key values. Therefore only one clustered index can be created on each table because the data rows themselves can only be sorted in one order.
To create a different clustered index on the same table, change the Create as Clustered property setting on the existing clustered index before creating the second index.

A: Clustered Index:
Clustered index defines the way in which data is ordered physically on the disk.
And there can only be one way in which you can order the data physically.
Hence there can only be one clustered index per table.
Why care about clustered index?
If we put clustered index on the table then the data is retrieved much faster because sql server doesn't have to read the whole data -- Depends on query.
But data retrieval is much faster.
NOTE: Although you can create more than one Non-Clustered index on a single table.

A: YOU CAN! (indirectly)
If you need multiple clustered index on a table, you could create indexed view on that table. But at the same time, you should be aware that clustered index always has its cost.

A: A clustered index determine the physical order of the data in the table , is like a home address that is why we should have only one home address ,  if not the postman get confused.
http://msdn.microsoft.com/en-us/library/aa933131.aspx


text:
Q: preg_replace_callback() para remover caracteres que não são dígitos Eu utilizo o Laravel e estou tentando utilizar a função preg_replace_callback() para remover ponto, vírgula, hífen, traço e barra dos números de CNPJ inseridos no sistema.
Eu utilizei a função preg_replace_callback() dessa forma:
    function parseTagsRecursive($input)
    {

        $regex = '#[^0-9]#';

        return preg_replace_callback($regex, 'parseTagsRecursive', $input);
    }

    $cnpj = parseTagsRecursive($cnpj);

Estou tendo como retorno o seguinte erro:

preg_replace_callback(): Requires argument 2, 'parseTagsRecursive&#039

Utilizei o exemplo 3 da documentação.
De acordo com esse exemplo, estou implementando da maneira correta. Alguém tem alguma dica de como devo proceder?
Tentei também o método preg_replace da seguinte forma:
function deixarSomenteDigitos($input) {
        return preg_replace('/[^0-9]/', '', $input);
    }

    $input['cgc_cl1'] = deixarSomenteDigitos($input['cgc_cl1']);

Utilizei um site para gerar um cnpj aleatório para testes. Ele retornou: 70.700.516/0001-24
Ao tratar o campo para salvar no banco, o cnpj foi salvo da mesma forma que entrou.
Alguns pontos a considerar: estou fazendo essas validações dentro de um arquivo FormRequest do Laravel, responsável pelas validações dos dados da minha classe.

A: Se você só quer remover tudo que não for números, pode simplesmente usar preg_replace:
echo preg_replace('/[^0-9]/', '', '74.208.285/0001-97'); // 74208285000197

No caso, tudo que não for número ([^0-9]) é substituído pela string vazia (''), ou seja, esses caracteres são removidos, e no final sobram somente os números.
Se quiser, pode criar uma função para isso:
function deixarSomenteDigitos($input) {
    return preg_replace('/[^0-9]/', '', $input);
}

echo deixarSomenteDigitos('74.208.285/0001-97'); // 74208285000197

preg_replace_callback é útil quando você precisa manipular os matches de alguma maneira não trivial (algo que exija uma função para tal, como nos exemplos citados na documentação).
E o exemplo 3 da documentação é mais complexo ainda, porque usa regex recursiva (já que ele está manipulando uma estrutura que pode ser recursiva), e faz as substituições recursivamente também.
Mas esse não é o seu caso, pois você só precisa detectar tudo que não for dígito e remover, então não é necessário um callback (e muito menos recursivo).


text:
Q: Load JS (CSS) file from another JS (CSS) file on Objective C I'm trying to load an entire source library of JS/CSS from Objective C (Xcode) from a UIWebView with an HTML loaded. The problem is that in the library documentation, they say you just need to load one JS file, but inside it's requiring others JS. The question is how i have to arrange the files... Just one folder with all the sources? Nested folders containing the JS/CSS just as they come on the library? or Do I need to fix the path of the requires in order to load them (say absolute or relative)?
Thanks in advance

A: I suggest minifying all of your JS (CSS) into 1 file.  You can download tools to do this, but one easy free one online is: http://jscompress.com/
Using some command or a downloaded app would probably make the code-minify-debug process much quicker, but you can test out the idea using that online tool.


text:
Q: Difference in articulation (or voiceness?) of /z/ between Ame and RP? I have observed some differences between Americans and British people when pronouncing /z/ in almost any word. But I don't know exactly what is the difference, I would describe it as Ame /z/ being more exaggerated, more sonorous, while for British I think I have heard them to make quite often the voiced sound but not fully voiced, in the sense that the voiceness stops before the sibilant sound does. I haven't been able to find anything on the internet so maybe you can help me.

A: I think it is the difference between the US "Zeeeeeeee" and the UK "Zed".
Some of the US accents emphasise the "eeeeee", as in "Zeeeeeebra" (ziː.brə), while, as a Brit, I would pronounce it "Zeb.ra" with the 'e' pronounced as 'eh'
You can compare pronunciations here, just under the word.