text:
Q: changing value in nested dictionary python using class class warehouse:

    def __init__(self):
        self.A={}
        self.B={}
        self.racks={'A':self.initialize(self.A),'B':self.initialize(self.B)}

    def initialize(self,rack):
        shelf = dict([  (items,0) for items in range(1,6)  ])
        for x in range(3):
            rack[x+1]=shelf
        return rack

    def store(self,_id,owner_id,colour,weigth):
        import pdb;pdb.set_trace()
        empty_position=self.empty_positions(self.store.__name__)[0]
        self.racks[empty_position[0]][empty_position[1]][empty_position[2]]=   {'id':_id,'owner':owner_id,'colour':colour,'weigth':weigth}
        print self.racks
    def empty_positions(self,name):

        store_list=[]
        for rack,shelfs in self.racks.iteritems():
            for shelf_number,shelf_objects in shelfs.iteritems():
                    store_list.append([rack,shelf_number])
                    for position,value in shelf_objects.iteritems():
                        if 0==value:
                            store_list.append([rack,shelf_number,position])

        return store_list

obj=warehouse()
val=obj.store(2,34,4,44)

It is a class warehouse I want to create a dictionary which I did by the calling the init methods of the class.Now I want to store some values into the nested dictionary using same instance of class warehouse.When I call the obj.store(2,34,4,44).It updates the dictionary and gimme the result.
{'A': {1: {1: {'colour': 4, 'id': 2, 'owner': 34, 'weigth': 44},
           2: 0,
           3: 0,
           4: 0,
           5: 0},
       2: {1: {'colour': 4, 'id': 2, 'owner': 34, 'weigth': 44},
           2: 0,
           3: 0,
           4: 0,
           5: 0},
       3: {1: {'colour': 4, 'id': 2, 'owner': 34, 'weigth': 44},
           2: 0,
           3: 0,
           4: 0,
           5: 0}},
'B': {1: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
      2: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
      3: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0}
     }
 }

But I was expecting :
{'A': {1: {1: {'colour': 4, 'id': 2, 'owner': 34, 'weigth': 44},
           2: 0,
           3: 0,
           4: 0,
           5: 0},
       2: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
       3: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0}},
 'B': {1: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
       2: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
       3: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0}
      }
 }

It sets the value in all the other nested dictionary of key 'A' and 1
I try to put PDB and debuge it, but it is showing the same result.
But If I do this operation in teminal then I get the result what I was expecting.
Python 2.6.6 (r266:84292, Sep 15 2010, 15:52:39)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> d={'A': {1: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0}, 2: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0}, 3: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0}}, 'B': {1: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0}, 2: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0}, 3: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0}}}
>>> d['A'][1][1]={"some_key":"some_value",}
>>> d
{'A': {1: {1: {'some_key': 'some_value'}, 2: 0, 3: 0, 4: 0, 5: 0}, 2: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0}, 3: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0}}, 'B': {1: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0}, 2: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0}, 3: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0}}}

I dont know maybe I am missing something, or there is something wrong that I am not able to catch up.I am using python 2.6.6 and tried this is 2.7.1 as well .

A: When you do:
shelf = dict([  (items,0) for items in range(1,6)  ])
for x in range(3):
    rack[x+1]=shelf

You are creating one shelf, then putting the same shelf in the rack 3 times. The shelves aren't copies, they're one and the same.
You need to create a new shelf each time:
def initialize(self, rack):
    for x in range(3):
        rack[x+1] = dict((items,0) for items in range(1,6))
    return rack

In python 2.7, using dictionary comprehensions, this can become:
def initialize(self, rack):
    rack.update({
        x + 1 : { item : 0 for item in range(1, 6) } for x in range(3)
    })
    return rack

A: Your problem is in the initialize() method, specifically rack[x+1]=shelf:
def initialize(self,rack):
    shelf = dict([  (items,0) for items in range(1,6)  ])
    for x in range(3):
        rack[x+1]=shelf
    return rack

rack[x+1]=shelf may seem harmless, but it isn't. rack will contain multiple references to the same shelf object, which yields strange results:
>>> a = {1: 2}
>>> b = [a for i in range(3)]
>>> b
[{1: 2}, {1: 2}, {1: 2}]
>>> b[0][1] = 3
>>> b
[{1: 3}, {1: 3}, {1: 3}]

Notice how all of the references to that single instance of a were affected when I changed one. They all point to the same object.
To fix this, change rack[x+1]=shelf to rack[x+1]=dict(shelf). Now, you're forcing Python to create a separate instance of shelf.


text:
Q: Why is brain.getObject() raising Unauthorized? I thought it was supposed to return None.
But it seems to be raising Unauthorized breaking the following idiomatic usage:
results = [x.getObject() for x in catalog(...) if x.getObject() ]

Is this a recent change?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Connecting to postgresql from lapis I decided to play with lapis - https://github.com/leafo/lapis, but the application drops when I try to query the database (PostgreSQL) with the output:

2017/07/01 16:04:26 [error] 31284#0: *8 lua entry thread aborted: runtime error: attempt to yield across C-call boundary
  stack traceback:
  coroutine 0:
          [C]: in function 'require'
          /usr/local/share/lua/5.1/lapis/init.lua:15: in function 'serve'
          content_by_lua(nginx.conf.compiled:22):2: in function , client: 127.0.0.1, server: , request: "GET / HTTP/1.1", host: "localhost:8080"

The code that causes the error:
local db = require("lapis.db")
local res = db.query("SELECT * FROM users");

config.lua:
config({ "development", "production" }, {
    postgres = {
        host = "0.0.0.0",
        port = "5432",
        user = "wars_base",
        password = "12345",
        database = "wars_base"
    }
})

The database is running, the table is created, in table 1 there is a record.
What could be the problem?
Decision: https://github.com/leafo/lapis/issues/556

A: You need to specify the right server IP in the host parameter.
The IP you have specified 0.0.0.0 is not a valid one, and normally it is used when you specify a listen address, with the meaning of "every address".
Usually you can use the '127.0.0.1' address during development.


text:
Q: Pandas Groupby: How to get distinct Column Values Trying to get distinct values for columns after grouping; but am getting a total sum
groupby is dropping object distinction and losing leading zeros for column
df = pd.read_csv("trial.txt",sep='|',converters={'zip':str},keep_default_na=True,low_memory=False)
Data:
Emp State   Zip      Jan feb mar

Int  NY    11111      1   0   1

int  NY    11111      1   1   0

int  NC    09999      2   2   0

int  ON    NH443     2   2   2

after
df2 = df.groupby("Zip").count()

df2 for zip my output for zip = 11111
i'll have the output for all 12 months show 2 2 2.
    Were I would expect 2 1 1
and zip 09999 shows as 9999.
How what is wrong about the grouping to not get distinct column values.
     Have account for non-null values (there are no nulls). Column value is only (0 , 1 ,2)

A: Let's start from why Zip column is read as int.
Note the subtle difference:

*

*Third column name in the source file is Zip, with capital Z.

*In your code you put converters={'zip': str}, with column name
starting with lower case z.

Change it to converters={'Zip': str} and the column in question will
be read as string.
Another, maybe better solution is to pass dtype={'Zip': object} instead.
I wrote better because no conversion is actually needed.
It is enough just to specify the column type.
I performed also additional check, i.e. I changed Zip in the last row
from NH443 to 88443.
So even if this column in the source file contains only digits (in all rows),
its type will be object, meaning actually string.
And now let's look at what is actual result of your code:
When you run df2 = df.groupby('Zip').count(), the result is:
       Emp  State  Jan  Feb  Mar
Zip
09999    1      1    1    1     1
11111    2      2    2    2     2
88443    1      1    1    1     1

Note the description of count function (GroupBy variant),
which reads: Compute count of group, excluding missing values.
As you didn't pass any column list, this count is computed for
all columns.
So your code does'n generate distinct values, but instead it counts
non-null values along each column in each group.
If you want what you wrote in the title, i.e. a list of
distinct values, for each column (not their counts), run:
df.groupby('Zip').agg(lambda col: np.sort(col.unique()).tolist())

This time the result is:
         Emp State  Jan     Feb    Mar
Zip
09999  [Int]  [NC]  [2]     [2]     [0]
11111  [Int]  [NY]  [1]  [0, 1]  [0, 1]
88443  [Int]  [ON]  [2]     [2]     [2]

E.g. group 11111 contains in Feb and Mar columns
two distinct values: 0 and 1.
In all other cases (for your sample data) each column
in each group contains a single distinct value,
so corresponding lists contain only a single element.

A: count returns the count of each group, excluding missing values.  That means that a value of zero would also be included in the count.  To only count positive values, you can apply a lambda function that sums the count of values greater than zero.
>>> df.groupby('Zip')[['Jan', 'feb', 'mar']].apply(lambda x: x.gt(0).sum())
       Jan  feb  mar
Zip
09999    1    1    0
11111    2    1    1
NH443    1    1    1


text:
Q: NetworkManager[920]:  Connection disconnected (reason -4) Using 14.04 on a ThinkPad X1 Carbon, a WiFi which works fine on other laptops regularly disconnects "by itself", and only comes back on after a forced Disable/re-Enable WiFi.  In /var/log/syslog I've, among other things, noticed this:
NetworkManager[920]: <info> (wlan0): supplicant interface state: authenticating -> associating
NetworkManager[920]: <info> (wlan0): supplicant interface state: associating -> associated
NetworkManager[920]: <info> (wlan0): supplicant interface state: associated -> 4-way handshake
wpa_supplicant[1343]: wlan0: WPA: Key negotiation completed with a4:52:6f:8e:ff:01 [PTK=CCMP GTK=TKIP]
wpa_supplicant[1343]: wlan0: CTRL-EVENT-CONNECTED - Connection to a4:52:6f:8e:ff:01 completed [id=0 id_str=]
NetworkManager[920]: <info> (wlan0): supplicant interface state: 4-way handshake -> completed
wpa_supplicant[1343]: wlan0: CTRL-EVENT-DISCONNECTED bssid=a4:52:6f:8e:ff:01 reason=4 locally_generated=1
NetworkManager[920]: <warn> Connection disconnected (reason -4)

What does mean, and (more importantly ;-) how can this be fixed?
I'd be happy to update the Q with more information if you respond to the Q with what's needed.

A: I found this: http://wireless.kernel.org/en/users/Documentation/Bluetooth-coexistence
It may be bluetooth interference with a bluetooth device on the laptop itself... try to change wifi channel to 13 or disable bluetooth on the laptop when not used.
UPDATE: changing wifi channel solved my stability problem, i had the very same error message (reason -4).


text:
Q: Accent insensitive searching in RadComboBox I'm relatively new to using ASP webforms and Telerik, but I'm looking for a way that allows me to type special characters (é, ù, à, ...) in a RadComboBox.
Lets say I have a name in my ObjectDataSource called "René Somebody". I need to be able to find him by searching for "Rene" and "René", but so far no luck.
In the application they managed to do this on a RadGrid with filters, but this same solution doesn't work for the RadComboBox as far as I know.
The solution they used in the RadGrid: http://www.telerik.com/forums/accent-insensitive-filtering-filtering-on-a-different-column#YS1QT8P1U0-cRPFNfjvDzA

A: I have no access to the backend components but the demo you linked contains frontend code and it looks like you can hack in there. It looks like this control may be both client-server and client-side only. For client-side only hacks looks kind of complicated and invloves non-public API (_onInputChange) but for client-server case (which is probably your case) the doc on client side of RadComboBox Object mentions requestItems method so hacking it is probably reasonably future safe:
var hackRadComboBoxFilter = function (combobox, filterProcessingFunction) {
    var oldRequestItems = combobox.requestItems;

    combobox.requestItems = function() {
        var args = Array.prototype.slice.call(arguments);
        // requestItems has several arguments but the text seems to be the
        // first one, so let's modify it and call the original method
        var origFilter = args[0];
        args[0] = filterProcessingFunction(origFilter);
        oldRequestItems.apply(this, args);
    }
};

Unfortunately I don't know a built-in way to deal with accents in JS but you can hack something simple here as well:
var accents = 'ÀÁÂÃÄÅàáâãäåÒÓÔÕÕÖØòóôõöøÈÉÊËèéêëðÇçÐÌÍÎÏìíîïÙÚÛÜùúûüÑñŠšŸÿýŽž';
var mappedAccents = "AAAAAAaaaaaaOOOOOOOooooooEEEEeeeeeCcDIIIIiiiiUUUUuuuuNnSsYyyZz";
var removeAccents = function (origStr) {
    var components = [];
    var len = origStr.length;
    var afterLastAccent = 0;
    for (var i = 0; i < len; i++) {
        var mapPos = accents.indexOf(origStr[i]);
        if (mapPos != -1) {
            components.push(origStr.substr(afterLastAccent, i - afterLastAccent) + mappedAccents[mapPos]);
            afterLastAccent = i + 1;
        }
    }
    if (afterLastAccent < len)
        components.push(origStr.substr(afterLastAccent, len - afterLastAccent));
    return components.join('');
};

So now you can combine it in something like this:
// In real app you probably want something like this
// var targetComboBox = $find("<%= RadComboBox1.ClientID %>");
// but for test let's just hack first combobox on the page
var targetComboBox = Telerik.Web.UI.RadComboBox.ComboBoxes[0];
hackRadComboBoxFilter(targetComboBox, removeAccents);

or if you want to modify all the comboboxes on the page, you can change prototype using the same trick:
hackRadComboBoxFilter(Telerik.Web.UI.RadComboBox.prototype, removeAccents)


text:
Q: php type def doesn't match bind params I have a table with 5 columns where the first column is a primary key and has a Auto_INCREMENT attribute. I am trying to insert a row into the table using the following code:
    <?php

include "DBConstants.php";

$db = new DBConstants();

$connection = new mysqli($db->SERVER_NAME,$db->DB_USERNAME,$db->DB_PASSWORD,$db->DB_NAME);
$query = "INSERT INTO mailinglist (email, validationID, usRequest, isValidated) VALUES (?,?,?,?)";

$statement = $connection->prepare($query);

$email = $_GET["email"];
$validationID = openssl_random_pseudo_bytes ( 10, $crstrong);
$usRequest=false;
$isValidated = false;

$statement->bind_param($email,$validationID,$usRequest,$isValidated);
$statement->execute();

$statement->close();
$connection->close();

$array = array("result"=>true,"message"=>"You have successfully subscribed");
echo json_encode($array);

?>

But I am getting a warning like this:

Warning: mysqli_stmt::bind_param(): Number of elements in type definition string doesn't match number of bind variables

And hence the table is not being updated. Where am I going wrong?

A: The first parameter of bind_param should be type of corresponding bind variables.
$statement->bind_param('sisi', $email, $validationID, $usRequest, $isValidated);

Note: Change the types in first param based on your data type.
Reference Link


text:
Q: Hello...does the website layout must be flex or float in order to apply @media? I just want to apply @media for mobile with these sizes: smaller than 400px,between 401px and 750px, larger than 750px.But its not working..so i think is because there is not flex or float layout.

A: There is no connection between media queries and flexbox/float.
Make sure you have the proper viewport tag within the head section:
<meta name="viewport" content="width=device-width, initial-scale=1.0">


text:
Q: Deploying to a different heroku app As advised here, in rails 3.1 I should use cedar instead of bamboo.
I did
heroku create --stack:cedar

and now I want to deploy only to that.
When I do
git push heroku

It deploys to the old app (bamboo stack)
How do I force deployment to the new app (and new address as well)?

A: I think your git remote heroku is linked to the old stack app.
First do a git remote rm heroku
then do a git remote add heroku git@heroku.com:your-appname-cedar-stack.git


text:
Q: react native webview:when add baseRrl,then just show html string In order to achieve the WebView display custom font
on rn 0.28:
    var html = 'test';
    html = `<!DOCTYPE html>
            <head>
            <meta charset="utf-8">
            <style type="text/css">
            @font-face {
                font-family: "MyFont";
                src: url("fonts/fzbys.ttf");
            }
            body{font-family: "MyFont"; font-size:28px;}
            </style>
            </head>
            <body>`+html+`
            </body>
            </html>`;
    return (
        <View style={[{width:this.state.width, alignItems:'center'}, this.props.styles]}>
            <WebView
                ref={"wv"}
                style={{width:this.state.width, height:100}}
                source={{html:html, baseUrl:"file:///android_asset/"}}
                domStorageEnabled={true}
                javaScriptEnabled={true} />
        </View>
        );

the font file had in android/app/src/main/assets/fonts, then :
run res


text:
Q: Why not gerund after a preposition? I have always known that after a preposition you have to use the following verb in the gerund form, however, it seems I have wrong al this time and I  would like to know the reason. Sentence: "I have to leave for work now", as far as I know, this sentence is well constructed, but why?

A: Objects of prepositions (like any other object) have to be nouns or noun phrases.
Many (but not all) words in English can function as verbs or nouns, and the meanings will typically be related.  Work is one of those.  Because of this, you don't need to change it by adding -ing to it.
The usual way English causes a word to only be a verb is by putting a subject in front of it - I walk to the park - I makes walk unquestionably a verb.
The usual way English causes a word to only be a noun is by putting a determiner, like a possessive pronoun or article in front of it - I walk to the park - the makes park unquestionably a noun.
This does not mean articles are strictly required in prepositional phrases and there's numerous well-known phrases that don't take articles, like in bed.


text:
Q: Ошибка при работе с input В этой строке:
!!checkMobileOperator.check(input.val()) && submit.removeprop('disabled');

выбивает ошибку: Uncaught TypeError: checkMobileOperator.check is not a function
Вот весь код: http://jsfiddle.net/t52ka/28/

A: Если вопрос в том, что это за ошибка, то:

У объекта checkMobileOperator нет метода check

UPDATE:
Я бы написал так:
Объявление:
var checkMobileOperator = (function() {
    return {
        check: checkFunction
    };

    function checkFunction(arg) {
        // logic
        return result;
    }
})();

....
где-то далее
....
checkMobileOperator.check(arg)

A: Очень много ошибок в коде:

*

*Не определена переменная which;

*Вы создали объект CheckMobileOperator, а метод check пытаетесь вызвать у функции сheckMobileOperator;

*Следом вас ждет ошибка с методом submit.removeprop которого нету, а есть submit.removeProp;

В JavaScript имеет значение регистр идентификаторов. Постарайтесь обращать на это внимание. И уделите внимание оформлению кода.


text:
Q: Python - Read messages from Service bus topic and then store them in a container with the same name I am new to this, but the code seems to be not working.
Intension is to read json message from Service bus endpoint and then copy and store them in a  blob container, but to keep the integrity constant throughout need to keep the name as is.
Do not have much knowledge on this , collected these codes from some blog.
Also if i can listen without func that will also help
Here is the code piece:
with receiver:
    for msg in receiver:
        print(str(msg))
        logging.info('Python ServiceBus trigger processed an Topics: %s', msg.get_body().decode('utf-8'))
        #receiver.complete_message(msg)

        temp_path = tempfile.gettempdir()

        # Create a file in the local data directory to upload and download
        local_file_name = str(uuid.uuid4()) + ".txt"
        upload_file_path = os.path.join(temp_path, local_file_name)

        # Write text to the file
        file = open(upload_file_path, 'w')
        file.write(msg.get_body().decode('utf-8'))
        file.close()

        # Create a blob client using the local file name as the name for the blob
        blob_client = blob_service_client.get_blob_client(container=container_name, blob=local_file_name)

        print("\nUploading to Azure Storage as blob:\n\t" + local_file_name)

        # Upload the created file
        with open(upload_file_path, "rb") as data:
            blob_client.upload_blob(data)

A: Here we need to create a function where we can configure messages to read which are received from Service Bus queues.
For this we need to mention the bindings in function.json file as below:
serviceBusTrigger:
{
"bindings": [
    {
    "type": "serviceBusTrigger",
    "name": "inputMessage",
    "connection": "AzureServiceBusConnectionString",
    "queueName": "inputqueue",
    "accessRights": "listen",
    "direction": "in"
    },
    {
    "type": "blob",
    "name": "inputBlob",
    "path": "container/{inputMessage}",
    "connection": "EnterConnection",
    "direction": "in"
    }
],
"disabled": false
}

queueTrigger:
{
  "bindings": [
    {
      "type": "blob",
      "name": "inputBlob",
      "path": "incontainer/{queueTrigger}",
      "connection": "testweblog_STORAGE",
      "direction": "in"
    },
    {
      "type": "queueTrigger",
      "name": "myQueue",
      "queueName": "myqueue",
      "connection": " EnterConnection _STORAGE",
      "direction": "in"
    }
  ],
  "disabled": false
}

For more information about the triggers please refer to input and output triggers:
A queue is basically for first-in-first-out messages. When a message comes from the service bus, the service bus queue trigger gets fired and the Azure Function is called. In the Azure Function, we can process the message and then deliver it to destination.
Below is the sample code to receive service bus queue.
Import os
from azure.servicebus import ServiceBusClient

CONNECTION_STR = os.environ['SERVICE_BUS_CONNECTION_STR']
QUEUE_NAME = os.environ["SERVICE_BUS_QUEUE_NAME"]

servicebus_client = ServiceBusClient.from_connection_string(conn_str=CONNECTION_STR)

with servicebus_client:
    receiver = servicebus_client.get_queue_receiver(queue_name=QUEUE_NAME)
    with receiver:
        received_msgs = receiver.receive_messages(max_message_count=10, max_wait_time=5)
        for msg in received_msgs:
            print(str(msg))
            receiver.complete_message(msg)

print("Receive is done.")

For more information refer to Azure Service Bus client library for Python

A: servicebus_client = ServiceBusClient.from_connection_string(conn_str=CONNECTION_STR, logging_enable=True)
msg_topic="XYZ"
with servicebus_client:
receiver = servicebus_client.get_subscription_receiver(topic_name=TOPIC_NAME, subscription_name=SUBSCRIPTION_NAME, max_wait_time=5)
with receiver:
for msg in receiver:
print(str(msg))
msg_topic=msg
print(str(msg_topic))
receiver.complete_message(msg)
block_blob_service=BlockBlobService(account_name='stgidpdev',account_key='ZZZZ')
block_blob_service.create_container('servicebuscontainer',public_access=PublicAccess.Container)
print('Container Created')
#from azure.storage.blob import ContentSetting
block_blob_service.create_blob_from_text('servicebuscontainer','myblockblob',str(msg_topic),content_settings=None)


text:
Q: Expect Script: Grabbing the output of a bash command and setting a variable I'm fairly new to expect; however, I have a current expect script that needs modifying and I'm stumped.
Here's what I'm trying to do,
host HOSTNAME | awk '{print $3}' | awk -v FS='.' '{print $4}' | tr -d ','
If the results are a specific number (4th octet of the IP address), then assign a variable to a specific value to be used in the script.  If it's a different value, then assign it a different variable value.
More details about what I'm trying to do with the script:
 - I have 2 different environments (both ending with specific 4th octet)
 - scp a file to the remote server (each environment has a different file)
 - connect to the system (the login prompts are also different for each environment, so would be passing different values for each environment)
* sorry if this is confusing *
This is what I have so far (yes, I changed some values to protect my environment).
spawn host hostname | awk {print \$3} | awk -v FS=. {print \$4} | tr -d ,
expect -exact 15 {
set PSWPROMPT password:
set REXPECT remotescript.exp
} -exact 10 {
set PSWPROMPT Password:
set REXPECT remotescript.exp_rh
}
send_user $PSWPROMPT $REXPECT
expect "$"
spawn scp -p filename user@hostname:PATH_FILENAME*
expect -exact "connecting (yes/no)?" {
   send  "yes\r"
   expect -exact $PSWPROMPT
   send  "filename\r"
   } -exact $PSWPROMPT {
      send  "filename\r"
   }
expect "$"
spawn scp -p filename user@hostname:PATH_FILENAME
expect -exact "connecting (yes/no)?" {
   send  "yes\r"
   expect -exact $PSWPROMPT
   send  "password\r"
   } -exact $PSWPROMPT {
      send  "password\r"
   }
expect "$"
spawn scp -p $REXPECT *username*@$hostname:PATH_FILENAME*
expect -exact "connecting (yes/no)?" {
   send  "yes\r"
   expect -exact $PSWPROMPT
   send  "password\r"
   } -exact $PSWPROMPT {
      send  "password\r"
   }
expect "$"

A: Since you're executing that on your local machine, and the command does not have any interactivity, just use exec and capture the output:
set output [exec host hostname | awk {{print $3}} | awk -v FS=. {{print $4}} | tr -d ,]

Note that curly braces in Tcl/expect act like single quotes in the shell. To pass the required braces to awk, we need to double up the braces. Or use double quotes, and escape the awk dollar sign:
set output [exec host hostname | awk "{print \$3}" | awk -v FS=. "{print \$4}" | tr -d ,]

Or we could do much of the work in expect:
set host_output [exec host hostname]
set first_list [lindex [split $output \n] 0]
set 3rd_word [lindex [split $first_line] 2]
set 4th_octet [lindex [split $3rd_word .] end]
set no_commas [string map {, ""} $4th_octet]

OR use a regular expression:
regexp {.*\.(\d+)} [exec host hostname] -> last_octet


text:
Q: How to find atleast one field has the value in mongodb using Java I am a newbie to mongodb.I store JSON in mongodb and this JSON has the value fields
I want to find and return an array/record where atleast one field has value . Basically I want to find partially filled records where not all of its fields has a value .I am using Aggregates in Java.
This is how the document returned after querying for the records,I have the list of languages the user should be able to see let's say in this case(user has access to see en_US and en_FR)
tralation{
    env{
        mytext{
          en_US: "yes",
          en_FR: ""
        }myanothertext{
          en_US: "no"
        }
      }
}

In this data given for partial result I should get both records(mytext,myanothertext).


text:
Q: Toggle between functions when key is pressed using Python Hey Guys I am doing an assingment for uni and I have to make a colouring book which enables the user to swap between two modes using the space key. In the first mode the user must be able to move the turtle with out drawing any lines and the second mode must initiate the paint brush mode where the user can draw.I want to be able to toggle between penup() and the pendown() turtle functions when the space button is pressed. Any ideas?
This is what I have so far:
from turtle import *
bgpic("Colour_A_Turkey.gif") # change this to change the picture

# PUT YOUR CODE HERE
setup(800,600)
home()
pen_size = 2
color("red")
title("Colouring Book")
speed("fastest") # Doesn't make any difference to accuracy, just makes turtle turn animation faster.
drawdist=10 # Distance in pixels pen travels when arrow key is pressed

penup()
###################BUTTON INSTRUCTIONS########################
def move_up():
        seth(90)
        forward(drawdist)

def move_down():
        seth(270)
        forward(drawdist)

def move_left():
        seth(180)
        forward(drawdist)

def move_right():
        seth(0)
        forward(drawdist)

def space_bar():

        if isdown()==True:
                penup()

        if isdown()==False:
                       pendown()
####Change pen color####
def red():
        color("red")

def green():
        color("green")

def blue():
        color("blue")

################BUTTON TRIGGERS##################
s= getscreen()

s.onkey(move_up,"Up")

s.onkey(move_down,"Down")

s.onkey(move_left,"Left")

s.onkey(move_right,"Right")

s.onkey(space_bar,"space")

s.onkey(red,"r")

s.onkey(green,"g")

s.onkey(blue,"b")

listen()

done()

A: When space_bar is called, isdown() is always true.
Do you want to toggle or draw only when the spacebar is pressed?
If you want to toggle, here's what you can do:
current_state = penup
next_state = pendown
def space_bar():
    global current_state, next_state
    next_state()
    current_state, next_state = next_state, current_state

A: from itertools import cycle

funcs = cycle([f1, f2])
next(funcs)() # alternates

A: This is how you toggle between pen up and pen down.
up = False

def pen_up():

    global up
    up = not up
    if up:
        t.penup()
    else:
        t.pendown()

ts.onkey(pen_up, 'space')


text:
Q: Change color of expressions that starts with '@' I need to create a winform to color expressions that starts with '@' that the user wrote in a textbox (can be a richTextBox or some Infragistics tool, does't really  matter, it just have to work).
Exemple:
nothing @expression nothingelse
the @expression must be colored
I've tried to split the string from the textbox by the spaces to identify the word, but I wasn't abble to replace it correctly. Now I'm learning about Regex and trying to apply it to my problem.
I'm using C# in Visual Studio Community 2017.
EDIT
I changed a little the code from here, trying to fit it into my problem. But the limiter doesnt work as it is suppouse to. I belive that it is happening becouse that the selection starts in the '@', but there can be a space before that, so the code doesn't work.
Here is the code as I'm using it:
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
    int current = richTextBox1.SelectionStart;
    for (int i = 0; i < richTextBox1.Lines.Length; i++)
    {
        string line = richTextBox1.Lines[i];

        int index = line.IndexOf(' '), lineFirstIndex = line.IndexOf('@');

        if (index != -1 && lineFirstIndex != -1)
        {
            richTextBox1.Select(lineFirstIndex, index);
            richTextBox1.SelectionColor = Color.Red;
        }
        else
        {
            lineFirstIndex = richTextBox1.GetFirstCharIndexFromLine(i);

            richTextBox1.Select(lineFirstIndex, line.Length);
            richTextBox1.SelectionColor = Color.Empty;

        }
    }
    richTextBox1.Select(current, 0);
}

A: You need to use Regex like this :
foreach (string result in Regex.Split(TextBox1, @" @\w+"))
{
  //do stuff...
}

A: I got the result that I wished, but there is a little problem. If i erase something with BackSpace, the backcolor starts to highlight everything.
I belive that this is something of the SelectionBackColor propriety, becouse it doesn't happend when I'm using SelectionColor.
The code:
 private void FindAt() //acha arrobas
    {
        for(int r = 0; r <= tam; r++)
        {
            for(int z = 0; z < (tam - r); z++)
            {
                if (z > 8) break;

                String temp = text.Substring(r, z);
                char aux = '\0';

                if (lista.FindStringExact(temp) != -1)
                {
                    if (tam > r + z) aux = text.ElementAt(r + z);
                    if ((r > 0 && text.ElementAt(r - 1) == '@') && aux == ' ')
                    {
                        atIndex[0, ctrlAt] = r-1;   //salva posição inicial da variavel, incluindo o @ (por isso o -1)
                        atIndex[1, ctrlAt] = z + 1;   //salva comprimento da variavel, + 1 por causa do @ (segundo argumento da substring)
                        ctrlAt++;
                    }
                }
            }
        }
    }

and the function to color the substring:
private void ColorAt() //colore variaveis
    {
        for (int a = 0; a < ctrlAt; a++)
        {
            if (atIndex[0, a] != -1)
            {
                richTextBox1.Select(atIndex[0, a], atIndex[1, a]);
                richTextBox1.SelectionBackColor = Color.Green;
            }
            else richTextBox1.SelectionBackColor = Color.Empty;
        }
    }


text:
Q: Cython for loop conversion Using cython -a, I found that a for i in range(0, a, b) statement was run as a python loop (very yellow line in cython -a html output). i, a and b were cdef-ed as int64_t.
Then I tried the 'old' syntax for i from 0 <= i < b by a. From the output of cython -a it seemed to compile quite optimal as expected.
Is it expected behaviour that range(0, a, b) is not optimized here or is this rather bound to the implementation?

A: Automatic range conversion is only applied when cython can determine the sign of the step at compile time. As the step in this case is a signed type it cannot and so falls back to the python loop.
Note that currently even when the type is unsigned cython still falls back onto the python loop, this is a (rather old) outstanding further optimisation that the compiler could do but doesn't. Have a look at this ticket for more information:
http://trac.cython.org/ticket/546


text:
Q: two instances of a static member, how could that be? I have a multithreaded application.
I declare a class with a static member in a shared library.
Printing the address of the member from different threads from different libraries shows different results.
//declaration
template <class OBJECT>
struct Container
{
   static int m_member;
};

template <class OBJECT>
int Container<OBJECT>::m_member;

// printing
cout << (void*) &Container<int>::m_member << endl;

How could that be?

A: If you have different libraries, (I'm guessing different dynamic libraries), then you may have some duplication of both code and static variables.
The exact details will depend on the particular dynamic library technology you are using. I'd say that, for example, in Windows DLLs you will have duplicated code and variables, but in Linux SOs you will not.
Anyway, you should give more details on the Operating System and the layout of your project.
UPDATE: Ahh, but your class is a template! Template instantiations in a shared library are a strange beast! To make sure that only one copy of your class is used across all the process you have to explicitly instantiate the template and make sure that this instantiation is exported in the SO, and that it is used from the client code. The details vary with the compiler, but you can check how the std::string is done, for example:
In the header file:
namespace std
{
    extern template class basic_string<wchar_t>;
}

In the source of the library:
namespace std
{
    template class basic_string<wchar_t>;
}

Naturally you need to know in advance which instantiations will be needed of your template. Obviously, the SO cannot export an instantiation that uses a type it knows nothing about.
UPDATE: Ahh, but you have two different libraries instantating the template... then if both libraries define the explicit instantiation as extern the shared ELF magic should merge both instantiations into one.
YET ANOTHER UPDATE: After playing with templates and shared objects, it usually just works. My guess now is that you are compiling the libraries with -fvisibility=hidden or similar. If that is the case, it would be enough just to write:
template <class OBJECT>
struct __attribute__((visibility("default"))) Container
{
   static int m_member;
};

To make the specializations of the template to enter the dynamic symbol table, and thus avoid the duplication.


text:
Q: Let $R$ be a ring . Then prove that $(R/ \langle x \rangle )/ \langle y \rangle \approx R/ \langle x,y \rangle $ Let $R$ be a ring and $x,y \in R$ s.t. $ \langle x \rangle , \langle  y \rangle $ are ideals of $R$, then prove that $(R/ \langle x \rangle )/ \langle y \rangle \approx R/ \langle x,y \rangle  $
Not sure if the conditions listed are enough to prove this but here's my attempt:
Attempt: Consider a mapping $\Psi : R/  \langle x  \rangle \rightarrow R/ \langle  x,y \rangle   $ Such that
$ \Psi(r + \langle x  \rangle) = r + \langle x,y  \rangle  $
This is clearly a ring homomorphism as :
(i) $\Psi[ (r_1 + \langle x  \rangle ) + (r_2 + \langle x  \rangle )] = \Psi[ (r_1 + \langle x  \rangle )] + \Psi[(r_2 + \langle x  \rangle )] $
(ii) $\Psi[ (r_1 + \langle x  \rangle )\cdot (r_2 + \langle x  \rangle )] = \Psi[ (r_1 + \langle x  \rangle )]\cdot \Psi[(r_2 + \langle x  \rangle )]$
To find the kernel of this homomorphism : We need a particular $r + \langle x  \rangle$ such that $\Psi(r + \langle x  \rangle) \in \langle x,y  \rangle$
$i.e ~~r + \langle x,y  \rangle \in \langle x,y \rangle  \implies r \in \langle x,y  \rangle \implies r+\langle x  \rangle=\langle x,y  \rangle \implies $ Kernel of $\Psi=\langle x,y \rangle$
Where could I have gone wrong?
Thank you for your help..

A: IMO, the fact there are some technical details left out from the homomorphism verification is secondary to a more important problem: keeping ideals of $R$ and $R/\langle x\rangle$ separate, especially when using $\langle\rangle$ to denote ideals generated by elements in both of these rings.
If you overcome this first problem I might check you on the issue of the homomorphism too, but that would be a simpler issue :) Actually, your line of reasoning contains all the seeds of a reasonable answer (modulo the way you've expressed them.)
When you write "$(R/\langle x\rangle)/\langle y\rangle$" where $\langle x\rangle$ and $\langle y\rangle$ are ideals of $R$," we immediately need to point out that anything written under "$(R/\langle x\rangle)/-$" is a subset of  $R/\langle x\rangle$, not of $R$. So the only way this is meaningful is if by $\langle y\rangle$, you meant the ideal generated in $R/\langle x\rangle$ rather than in $R$. (In the original problem, you may as well just have said $y\in R$ rather than $\langle y \rangle \lhd R$.)
For clarity, you'd probably rather write $\langle y +\langle x\rangle \rangle$ rather than $\langle y\rangle$ to sidestep this issue. We will see, after all, that you are really interested in the ideal of $R/\langle x\rangle$ generated by $y+\langle x\rangle$.
With this in mind, let's look at your last line:

$r + \langle x,y  \rangle \in \langle x,y \rangle  \implies r \in \langle x,y  \rangle \implies r+\langle x  \rangle=\langle x,y  \rangle \implies \ker\Psi=\langle x,y \rangle$

The first half is fine, but the last half uses some fuzzy bookkeeping with cosets that leads to a confused conclusion.
Let's start from $r\in \langle x,y\rangle$ and try something naive. We know that $r=\sum a_ixb_i +\sum c_iyd_i$  since it's in $\langle x ,y\rangle$. But then $r+\langle x\rangle$ would be $$r+\langle x\rangle=\sum a_ixb_i +\sum c_iyd_i +\langle x\rangle=\sum c_iyd_i +\langle x\rangle\in \langle y +\langle x\rangle\rangle$$.
So we should conclude that $\langle y +\langle x\rangle\rangle$ is the kernel of $\Psi$ rather than $\langle x,y \rangle$. Notice that this is a subset of $R/\langle x\rangle$, as compared to $\langle y\rangle$ which you initially emphasized to be an ideal of $R$.)
What's that look like in your original expression? As you were angling for, the first isomorphism theorem says:
$(R/\langle x\rangle)/\langle y +\langle x\rangle\rangle\cong R/\langle x,y\rangle$
So, you were headed for the right idea, but the slightly ambiguous use of notation was making you unsure.

A: The points (i) and (ii) do not verify that $\Psi$ is a ring homomorphism. You forgot to show that it is well defined, preserves the one element, and is compatible with subtraction. But nevertheless is not necessary here to check any of these properties, since the existence of $\Psi$ is given by the fundamental theorem on homomorphisms.
Regarding your question: In the ring $R/ \langle x \rangle$ we have $\langle x,y \rangle = \langle y \rangle$, since $x = 0$. Also note that the statement you want to show is a special case of the third isomorphism theorem, from which it easily follows.


text:
Q: Run time error 1004 method range of object_global failed on a search in Excel with a named range I am getting error:

Run time error 1004 method range of object_global failed

in the following code line:
Set br = Range("rg").Find(Range("$d$3").Value)
Following is the complete code:
Private Sub ComboBox1_Change()
Dim y As String
Dim q As Variant
Dim j As Double
Dim i As Variant
Dim k As Variant
Dim l As Double
Dim qst As Variant
Dim br As Range
Dim bra As Variant

qst = MsgBox("Entire data will be removed & archived" & vbNewLine & "Are you sure you want to proceed?", vbYesNo, fnb)
If qst = vbYes Then
Worksheets("Marcopolo").Unprotect myp
Worksheets("Marcopolo").Activate

Dim arch_iv(1 To 5, 1 To 2) As Variant

Dim rg As Variant
Dim fd As Variant

For rg = 1 To 5
    For fd = 1 To 2
        arch_iv(rg, fd) = Worksheets("arrays").Cells(rg, fd).Value
    Next fd
Next rg

For rg = 1 To 5
    For fd = 1 To 2
        Set br = Range("rg").Find(Range("$d$3").Value)
            br.Select
                br.Offset(0, 2).Select
                  bra = ActiveCell.Address
                MsgBox bra
            Range("fd").Copy
        Worksheets("marcopolo").Range(bra).PasteSpecial Paste:=xlPasteValues
    Next fd
Next rg

Else
GoTo Gtout
End If

A: The error comes, because the named range is not found.
If the named range rg should be on the "Marcopolo" worksheet, then it should be referred like this:
With Worksheets("Marcopolo")
    Set br = .Range("rg").Find(Range("D3"))
    If br Is Nothing Then
        MsgBox "D3 NOT FOUND!"
        Exit Sub
    End If
end with

The above has another problem, because the parent of the Range("D3") is not explicitly defined. Thus, it is either the ActiveSheet or the Worksheet, in which the code is residing. To avoid this problem, consider defining it like this Worksheets("SomeName").Range("D3").


text:
Q: FromDate ToDate clientside validation using foolproof in MVC not working I have two date field in my Page fromDate and ToDate. ToDate should be greater than FromDate. I need to validate it in client side.
I'm using Foolprof for clied side validation

*

*reference added
 using Foolproof;

*Script added

*My model contains below code
[Required(ErrorMessage = "The start date is required")]
public DateTime StartDate { get; set; }

[Required(ErrorMessage = "The end date is required")]

[GreaterThan("StartDate")]
public DateTime EndDate { get; set; }

and in controller done using default scaffolding.
my .cshtml contain below code for Dates

        @Html.LabelFor(model => model.StartDate, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.StartDate, new { htmlAttributes = new { @class = "form-control" } })

            @Html.ValidationMessageFor(model => model.StartDate, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.EndDate, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.EndDate, new { htmlAttributes = new { @class = "form-control" } })

            @Html.ValidationMessageFor(model => model.EndDate, "", new { @class = "text-danger" })

Now my validation is not working in Client side but working in server side after clicking submit button.
Please provide me some guidence..
Thank you.

A: I think you have not referenced jQuery Library.  If you are using Unobtrusive, you should use below scripts

If you are using jQuery validation, include MvcFoolproofJQueryValidation.js with the standard client validation script files


text:
Q: Excel VBA Sorting on Range Fails I am having some trouble getting a range to sort. Interestingly enough, this was working until I tried to add some options to the Range.sort function (which I've since removed). The error code given is "Run-time error '1004': Sort method of Range class Failed". I've posted my code below, but I can't pinpoint why the sort is failing. I've looked at all the column and row values, and they are all correct. It's trying to sort "B2:B39" which looks fine on my sheet. I also attached a picture of the hidden variables sheet to show what the output looks like until the sort fails.
Edit: To clarify, I have tried copying, removing uniques, and then sorting in the first row as well, but I get the same error regardless. The last time the function was working, I believe the range did start from the second row.

Sub addUniques()
    Dim i As Long
    For i = 2 To 9
        Call copyColToSheet(ThisWorkbook.Sheets("CallLog"), ThisWorkbook.Sheets("HiddenVariables"), NumToLet(i), NumToLet(i))
    Next i
End Sub

Function copyColToSheet(wsSource As Worksheet, wsDest As Worksheet, colSource As String, colDest As String)
    wsSource.Range(colSource & "2:" & colSource & CStr(getLastRowInCol(wsSource, colSource))).Copy wsDest.Range(colDest & "2:" & colDest & CStr(getLastRowInCol(wsDest, colDest)))
    wsDest.Range(colDest & "2:" & colDest & CStr(getLastRowInCol(wsDest, colDest))).RemoveDuplicates Columns:=1, Header:=xlNo
    wsDest.Range(colDest & "2:" & colDest & CStr(getLastRowInCol(wsDest, colDest))).Sort
End Function

Function getLastRowInCol(ws As Worksheet, col As String) As Long
    With ws
        getLastRowInCol = .Range(col & .Rows.Count).End(xlUp).Row
    End With
End Function

Function NumToLet(lngCol As Long) As String
    Dim vArr
    vArr = Split(Cells(1, lngCol).Address(True, False), "$")
    NumToLet = vArr(0)
End Function

A: I think you need to set a Key
Try this:
Function copyColToSheet(wsSource As Worksheet, wsDest As Worksheet, colSource As String, colDest As String)
wsSource.Range(colSource & "2:" & colSource & CStr(getLastRowInCol(wsSource, colSource))).Copy wsDest.Range(colDest & "2:" & colDest & CStr(getLastRowInCol(wsDest, colDest)))
wsDest.Range(colDest & "2:" & colDest & CStr(getLastRowInCol(wsDest, colDest))).RemoveDuplicates Columns:=1, Header:=xlNo
wsDest.Range(colDest & "2:" & colDest & CStr(getLastRowInCol(wsDest, colDest))).Sort Key1:=wsDest.Range(colDest & "2")
End Function


text:
Q: how to find a specific character combination and add a newline I have a large file that looks like this
(something,something1,something2),(something,something1,something2)
how do I use sed and find ),( and replace it with );( or add a newline between the parentheses that has a comma character.
I did try sed 's/),(/),\n(/g' filename.txt but for some reason it does not work

A: for those who come here and want to know how this work without getting a lot of stackoverflow "greetings"
since I was on Mac os x you need to replace your \n with \'$'\n''
so to find ),( and add a new line between the parentheses  this is the command I used
sed 's/;/\'$'\n''/g' testdone.txt > testdone2.txt
ES

A: echo "(something,something1,something2),(something,something1,something2)" | sed "s|),(|);(|"

This prints the below for me.
(something,something1,something2);(something,something1,something2)

For new line
echo "(something,something1,something2),(something,something1,something2)" | sed "s|),(|)\n(|"

And the above prints the below.
(something,something1,something2)
(something,something1,something2)


text:
Q: How to get information from a static class that is called by an event handler? I am new to C# and to object-orientation in general having come from C.
My problem is that I trying to create a program that will read from multiple serialports at the same time. I have been given a program that processes a single serial port.
Currently I have a static function which is used to configure the 8 serial ports I wish to use. Within this static function I call:
SerialPortToSetup.DataReceived += new SerialDataReceivedEventHandler(SerialPortEventHandler);
This function itself calls a class to read data from the serialport and passes it back. How can I get at the information coming out of the SerialPort whilst attempting to maintain abstraction for the possibility of adding more SerialPorts later?
In the codes present state I get an error as flowmeter_data_array is not a static object and so cannot be called, and the function cannot be made non-static as the function which sets the event handler is static.
 private static void SetupSerialPort(SerialPort SerialPortToSetup, ComboBox PortNameComboBox, ComboBox BaudRateComboBox)
    {
        SerialPortToSetup.BaudRate = Convert.ToInt32(BaudRateComboBox.Text);
        SerialPortToSetup.DataReceived += new SerialDataReceivedEventHandler(SerialPortEventHandler);
        SerialPortToSetup.PortName = PortNameComboBox.Text;
    }

    private static void SerialPortEventHandler(object sender, SerialDataReceivedEventArgs e)
    {
        data_array[data_array.Length] = SerialData.GetSerialData((SerialPort) sender);
    }

The class so far is shown below
public static class SerialData
{
    public static string GetSerialData(SerialPort SerialPortSent)
    {
        string data_string = string.Empty;
        try
        {
            if (SerialPortSent.IsOpen)
            {
                data_string = SerialPortSent.ReadLine();
            }
            else
            {
                MessageBox.Show("Serial Port not open", "Read Error",
                MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                data_string = "ABORT CODE";
            }
        }
        catch (ArgumentNullException)
        {
            MessageBox.Show("Read Buffer = NULL", "Read Error",
                MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
        catch (IOException)
        {
            MessageBox.Show("Recieve DUT data exception, Serial Port not open", "Read Error",
                MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            Thread.Sleep(1000);
            data_string = "ABORT CODE";
        }

        return data_string;
    }

Previously the program used a single class for all of its calculations and operations. But I am also concerned that by creating a new class, then I will run into "Class Envy" by calling the class too much from my main class.
Thank you in advance for any help you may be able to offer me.


text:
Q: How can I get rid of Reference error using music-metadata in electron app I am trying to use music-metadata but keep getting the following error. I already checked the package.json file and deleted the nodes_modules folder several times.

const $ = require('jquery');
const mm = require('music-metadata');

function chooseMusic() {
  $('input').click();
}

function musicSelected() {
  const files = $('input').get(0).files;
  console.log(files);

  for (let i = 0; i < files.length; i++) {
    const {path} = files[i];
    mm.parseFile(path).then((metadata) => {
      console.log(metadata.common.title);
    });

  }
}

A: The problem was that I was using an older version of music-metadata. I reinstalled it with the newest version and the error disappeared.


text:
Q: ¿Cómo crear nuevos attributos html con JavaScript? Lo que deseo saber es como utilizar un atributo para poder ejecutar cualquier método en HTML en cualquier parte que lo use, como lo hacen las librerias. Por ejemplo si deseo usar un atributo HTML llamado "a-toUpperCase" en cualquier etiqueta que contenga texto lo convierta en mayuscula:

Hola Mundo

Alguien me podría decir en cómo hacerlo o darme una referencia por favor, he buscado por todos lados pero nada que sirva.
PD: Todo debe ser JavaScript puro

A: puedes hacerlo asi:

en el arreglo fun debes agregar los metodos de acuerdo a su nombre real.
  ya que buscara en todo el documento los tag y los cambiara.

   // selector de elementos
var $ = (s) => document.querySelectorAll(s);
// crear otros metodos
String.prototype.red=function(e)  {
return `<span style="color:red;">${this}<span>`;
}
// arreglo contenedor de funciones de tipo cadena
var fun = ["toUpperCase","toLowerCase","bold","italics","red","sup","sub","strike","small","big"];

// recorre el arreglo
for(let s of fun){
    // busca elementos que contenga a-"tipo de funcion" a-bold, a-small etc.. y hace un recorrido de todos
    for(let x of $(`*[a-${s}]`)){
       // eval() evalua el string que se le pasa y lo combierte a funcion y la ejecuta
        let e = eval(`'${x.innerText}'.${s}()`);
        // agrega el resultado a elemento con el respectivo tag
        x.innerHTML = e;
    }
}

TEXTO A MINUSCULA

texto a mayuscula

TEXTO A NEGRITA

TEXTO A ITALICS

TEXTO A SUP

texto a sub

texto a small

texto a big

texto a strike

texto a mayuscula negrita y strike

texto rojo

A: Una forma de hacerlo con sólo Javascript sería asignando un atributo class a los elementos, luego con querySelectorAll agrupas todos los elementos de una clase y le asignas a cada uno dentro de un forEach el estado deseado: MAYÚSCULAS, minúsculas, color..., etc.
Por ejemplo:

var allUpper = document.querySelectorAll('.a-toUpperCase');
allUpper.forEach(function(elem) {
  elem.textContent = elem.textContent.toUpperCase();
});

var allLower = document.querySelectorAll('.a-toLowerCase');
allLower.forEach(function(elem) {
  elem.textContent = elem.textContent.toLowerCase();
});

var allRed = document.querySelectorAll('.color');
allRed.forEach(function(elem) {
  var color = elem.className.split(' ')[1]
  elem.style.color = color;
});

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

Lorem ipsum dolor sit amet

NÓTESE  que esto ser haría mucho más fácil mediante el manejo de clases CSS, sería cuestión de poner la clase al elemento y CSS haría
  el resto.


text:
Q: iPad - topmost modal view controller won't dismiss when there are multiple I'm working on a dual-iPad/iPhone application.
I'm having a problem that is occurring on the iPad only:

*

*Root view controller is a UISplitViewController on iPad, UITabBarController on iPhone

*A modal UIViewController can appear over the root controller

*A modal UIViewController can appear over the previous modal controller

*On iPad, modal controllers are using UIModalPresentationStyle.PageSheet

Everything works, except dismissing the topmost modal controller from the iPad--the method is called, but the modal view controller doesn't dismiss.  I dismiss by calling DismissModalViewControllerAnimated from the previous modal controller.
Any ideas why this wouldn't be working on the iPad?
In all cases, I call PresentModalViewController and DismissModalViewControllerAnimated from the parent controller to work its child modal controller.
I'm using MonoTouch (you can tell by my casing of methods), but that is probably irrelevant.  I can take answers in Obj-C as well.
UPDATE, following might make what it should do more clear:

*

*Root => Modal A => Modal B

*Dismissing Modal B should just return
to Modal A

*Dismissing Modal A should just return
to Root

A: Are you sure you are dismissing the right view?  Inside the modal view, lets say that you want to dismiss the view with a button click.  In that button's method, you want to call the DismissModalViewControllerAnimated method.   Just say
[self dismissModalViewControllerAnimated:YES];

*

*Present the modal window from the root

*when finished, dismiss the view from the modal view's controller.

It's hard to really diagnose the problem without seeing how you are trying to present and dismiss the controller, but that should work.  You shouldn't need to do anything from the parent controller once the new view is displayed...

A: Found a workaround.  All of these conditions had to be met to fix it:

*

*First modal has default ModalPresentationStyle

*Second modal has UIModalPresentationStyle.PageSheet

*My second modal is displayed in the ViewDidAppear of the first.  For some reason, I needed to call PresentModalViewController from BeginInvokeOnMainThread.  (A one-liner in MonoTouch)  This is a trick I learned from Windows development and message pumps. I have seen iPhone devs do similar workarounds with timers--this is much better.

I will post-back if we have trouble getting this through the app store.  But for now, it is a good solution for us.


text:
Q: How to use Laravel revisionable with morphMaps? I have a morphMap setup in my AppServiceProvider boot method that is firing when the Laravel revisionable package calls for the record so nothing is being returned. I am looking to figure out how to make revisionable work with morphMaps. Please note that revisionable is storing the full namespace when saving the record but when calling the record revisionable is using the value I put in for the morphMap.
For example revisionable saves App\Models\Organization\Organization but my morphMap translates that to just organization when calling for the revisionHistory().

A: I know this is an old question but I see Venturecraft/Revisionable developers are not giving answers to this problem.
The error ocurrs when the package try to instatiate a new model with the value of the property $this->revisionable_type in Venturecraft\Revisionable\Revision, because the class does't exist when using the key of $morphClass array instead of the real namespace of the model.
I figured out that the problem is solved when I override the value of this property with an Laravel Accessor like this:
use Illuminate\Database\Eloquent\Relations\Relation;

public function getRevisionableTypeAttribute($value)
{
    $morphedModel = Relation::getMorphedModel($value);
    return !empty($morphedModel) ? $morphedModel : abort(400, "The namespace {$value} hasn't been added to the Relation::morphMap() method.");
}

Now, I don't know how to add this Accessor to the Revision model without editing the one that comes in the vendor folder.
If you can give a try and share what you get will be helpful.


text:
Q: How to use "edit" command via telnet I use telnet to connect my client, and try to edit a file. But I find that I can't edit it. I can't even use "Alt" key to control the application. How can I solve this problem? (I can't install any program on the client.)
(Windows 7 telnet to Windows XP. )

A: You could make use of the fine text editing facilities that Microsoft has included with XP.  That means edlin.

A: Try PSExec to run processes on the remote machine:
http://technet.microsoft.com/en-us/sysinternals/bb896649.aspx

A: If you are using the Telnet daemon that comes with Windows, the Alt key should be mapped to Ctrl+A.


text:
Q: Тестировние с Mockito объясните на пальцах Проверяю метод
public Message findOne(Long id) {
    Message message = messageRepository.findOne(id);
    if (message == null) {
        throw  new DataNotFoundException("Data with id=" + id + " not found.");
    }
    return message;
}

тест вариант 1, проходит даже если в проверяемом методе заменить DataNotFoundException на NullPointerException. Не должен вроде?
@Test(expected = DataNotFoundException.class)
public void findOneIsNullThenException1() {
    when(messageServiceImp.findOne(2L)).thenThrow(DataNotFoundException.class);
    Message testMessage = messageServiceImp.findOne(2L);
}

Тест вариант 2, не проходит ни как
@Test(expected = DataNotFoundException.class)
public void findOneIsNullThenException() {
    //prepare
    when(messageServiceImp.findOne(2L));
    then(caughtException())
            .isInstanceOf(DataNotFoundException.class)
            .hasMessageContaining("Data with id=2 not found.");
// А так же пробовал с
    thenThrown(DataNotFoundException.class);
}

получаю ошибку
java.lang.Exception: Unexpected exception, expected<com.sttech.springrest.exception.DataNotFoundException> but was<java.lang.AssertionError>
....
Caused by: java.lang.AssertionError:
Expecting actual not to be null
....
E.g. thenReturn() may be missing.
Examples of correct stubbing:
when(mock.isOk()).thenReturn(true);
when(mock.isOk()).thenThrow(exception);
doThrow(exception).when(mock).someVoidMethod();
Hints:
 1. missing thenReturn()
 2. you are trying to stub a final method, you naughty developer!
 3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed

Дополнение:
Я что то перестал понимать как вообще тестировать с помощью mockito. У меня есть класс MessageServiceImp в нем есть методы которые я хочу протестировать.
Буду отталкиваться все от того же метода что выше, но протестировать его не только на исключения.
В классе MessageServiceImp есть зависимость MessageRepository которую надо проинжектировать, по этому отмечаем ее как мок и инжектируем в класс.
@Mock
private MessageRepository messageRepository;
@InjectMocks
MessageServiceImp messageServiceImp;

Далее сам тест.
@Test
public void findOne() throws Exception {
    //prepare
    when(messageRepository.findOne(ID)).thenReturn(MESSAGE);
    //testing
    Message testMessage = messageServiceImp.findOne(ID);
    //validate
    verify(messageRepository).findOne(ID);
}

В таком виде тест проходит, смотрим, а что он там вообще тестирует? вроде как должен вызов метода findOne и вернуть должен объект MESSAGE (по сути мне бы подошел и возврат любого объекта anyObject()).
Проверяем, меняем в проверяемом методе возвращаемое значение на null и ... тест все равно проходит. Я ведь объект ожидаю, а получаю null и тест проходит.
Что я делаю не так?

A: @Test
public void findOne() throws Exception {
    // prepare
    when(messageRepository.findOne(ID)).thenReturn(MESSAGE);
    // testing
    Message testMessage = messageServiceImp.findOne(ID);
    // validate
    verify(messageRepository).findOne(ID);
    assertEquals(MESSAGE, messageServiceImp.findOne(ID));
}

Конструкция when.thenReturn и последующая verify проверяет, что сработал вызов мока, в данном случае
Message message = messageRepository.findOne(id);

И возвращает объект а не что то иное.
И дополнительная проверка assertEquals уже проверяет возвращаемое значение самого метода MessageServiceImp.findOne()


text:
Q: crontab dont execute require I'm using a osx and I created a ruby script in the path: /Users/diogo/workspace/outros/crawler_trf with name get_news.rb
So I tried to execute it via crontab with the following line: */1 * * * * 'ruby /Users/diogo/workspace/outros/crawler_trf/get_news.rb' > /tmp/crawler_trf.out and I've got the error: /bin/sh: ruby /Users/diogo/workspace/outros/crawler_trf/get_news.rb: No such file or directory
After some searches and a question here I solved this problem removing the quotes and now my crontab looks like that: */1 * * * * cd /Users/diogo/workspace/outros/crawler_trf/ && ruby get_news.rb > /tmp/crawler_trf.out
But now I'm having a new error that is:
/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- mail (LoadError)
from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from get_news.rb:3:in `<main>'

The beginning of my file is:
require 'nokogiri'
require 'open-uri'
require 'mail'

My ruby version is 2.3.0 and I have it specified in .ruby-version and using gemset specified in `.ruby-gemset
I installed the gems via bundle
I really had searching for my answers for long but I didn't found nothing.

A: You should always fully specify the paths of all files when executing them out of cron, since the environment provided by cron will be different from your login environment. That might mean replacing the invocation of ruby with the full path to your ruby binary (maybe /usr/local/bin/ruby).
Try running ruby -v out of cron to see what version you are picking up. On my Mac OS system I have two:
Edwards-MacBook-Air:~ emv$ /usr/bin/ruby -v
ruby 2.0.0p648 (2015-12-16 revision 53162) [universal.x86_64-darwin15]
Edwards-MacBook-Air:~ emv$ /usr/local/bin/ruby -v
ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin15]

one from the operating system, and one from Homebrew.


text:
Q: How do I allow post requests from my pages only? Ok, the question is just theoretical but pretty simple, I don't want people to send post request from modified versions of my modules or jquery $.ajax scripts. Are there particular techniques to do that (mod rewrites configuration, .htacces, crc, and so on)?

A: An overly simple way to explain one common practice is that you generate a large random number or string at the time that the form is requested. This value is called a token, and since it is only used once, it is often called a nonce.
Store that token in the current session on the server and place it in the form as the value of a hidden field. When the user submits the form, compare the submitted token to the stored one.
You should also check the request headers to verify that the request looks like it is coming from the right page.
owasp csrf cheat sheet


text:
Q: 2N7000 NMOS only switches properly when gate and source is connected with 1MΩ I am building a circuit on a breadboard to see if I can get a 2N7000 NMOS to switch using a 3.3V V_gs signal. As far as I know, I've set up the circuit properly:

simulate this circuit – Schematic created using CircuitLab
However,

*

*This circuit causes the LED to light up regardless if V_gs is 3.3V or 0V. The transistor conducts no matter what.

*It works properly when I connect a 1MΩ resistor between Gate and Source. Now, when V_gs is 0V, the LED turns off and when V_gs is 3.3V, the LED turns on. I discovered this when I was probing Gate and Source with a multimeter, and I wondered if an 1MΩ resistor would achieve the same effect.

Can someone explain this phenomenon for me? Thank you very much.

A: With your multimeter or the resistor, you are providing a path to ground at the gate. The gate is essentially a small capacitor, and is very high impedance. This means that charge may accumulate, and raise \$V_\mathrm{gs}\$ sufficiently to allow the MOSFET to conduct. Hence, your LED was lighting up. It is always good practice to include this "pull down" resistor.


text:
Q: Legality of Reverse Engineering If there was a "law/legal" stack exchange site I'd post it there, but it's in its infant stages in Area 51. I'm a musician and an electrical engineering student. I've designed a modification to the pickup system of my acoustic/electric guitar that I know some people within a certain circle would be pretty interested in. I've read a lot of complaints about the stock pickup system on electronics forums, and it doesn't seem that anyone has figured out a solution, so I thought I'd make a detailed video on the work I've done. To be honest there's not too much to it, but if I post some partial schematics of the part of the original preamp I've managed to reverse engineer, can that get me into legal trouble at all? I don't plan on marketing this modification at all; I just want to share what I've done.

A: AndrejaKo is right about the patents. To prevent you to come up with some variation to the invention patents are never very specific, so that they cover any possible variant.
Also, most of the time it's not just the product which is patented, but patents are registered for every possible detail. I've seen relatively simple products listing over 150 patents. It's almost impossible that you can use anything from that design.
You can reverse engineer as much as you want to study the design, but you can't use any of it, especially not for production. It's unlikely that lawyers will hunt you down if you reproduce a design for your own use, just a single copy, albeit because they won't be aware of it.
The layout copyright is hardly relevant if you can't use the schematic anyway.

A: The concept of patents is disclosure of invention and make minor improvements to prior art.  So you are not violating their design, but showing creative improvements . The value of a patents only comes to bear when others profit by similar results and get caught or the patents are worth selling.
This company  would not likely waste their time or money taking you to court.
But for the entertainment field, it might detract from revenue to copy ideas and make free so people like Google/ YouTube censor copyright protected music etc. on personal uploads.

A: Reverse engineering is understanding of how things work.
I think it is not illegal when to reverse engineering anything.
It's like hear the chords of a song and write it down to a paper.
Unless you use the design to produce and sell copies, if you do it will be copyright infringement and or patent violation.
But this is just my opinion, I'm not a laywer.
In fact if something is patented and have a patent number, it makes it a lot easier to reverse engineer. Because in order to have a patent granted, the owner have to provide all the information about the related patent, through a public domain.
A patent does not make anything harder to be copied, it makes it easier, it just give the owner legal rights to sue anyone that is using your patent.
A example can be found here:
http://youtu.be/Fj7e3WGUKO8?t=35m37s

A: Sounds legal, but I'm not a lawyer.  Is the original preamp you're concerned about patented?  If so, is the patent expired?  Even if its still covered by active patent, you're probably not violating the patent.

A: The best answer is always "talk to a lawyer."  That being said, you could check out any kind of license agreement you may have implicitly agreed to when you purchased the item.  Since you are not marketing this modification, the worst that could happen is that you could get a takedown request/notice for the video or a cease and desist letter.  Odds are, the company either will not care or will see this as free advertising.

A: In general there are two main problems with reverse engineering: patents and copyrights. For US, it is often said that only the actual component layout is covered by copyright and you'll have problems if you directly copy it.
The patents on the other hand protect the idea itself and the patent descriptions try to be as broad and vague as possible in order to cover a much room as possible. If you reverse engineer a patented idea, the idea is still covered by patent and the company can still chase you in case of reverse engineering.


text:
Q: Diff docker registry images Recently the centos images in the global docker registry were updated (~4 days ago it seems). Before the update, I could successfully build off of the Centos 6 image but now I have some installation errors for some packages. When I look at the images from before and after, and then attempt to follow version history it looks something like
f1b10cd84249 -->  b9aeeaeb5e17 (originally worked)
             \->  fb9cc58bde0c -->  a005304e4e74 (current version where my code breaks)

where the arrows show how the image was updated (left is oldest while right is newest). I'm curious as to how the images are different. Is there anyway to do a diff of the a005304e4e74 and b9aeeaeb5e17 images?

A: I've never tried, but I guess you could do:
$ docker export -o f1.tar b9aeeaeb5e17
$ docker export -o f2.tar a005304e4e74
$ diff <(tar -tvf f1.tar | sort) <(tar -tvf f2.tar | sort)

Export will create a tar of the filesystem, which we then use to get a diff of the file differences. (I got the diff syntax from Diff between two .tar.gz file lists in liunx )
You might find just running docker history on the images gives you enough information though.


text:
Q: No standard output received inside foreach loop I'm using doParallel to do fairly long parallel processing with foreach. Rather than most examples I see, where a computationally-intensive but input-light code is fed into the loop, I'm using foreach to coordinate the simultaneous processing of a number of large, independent datasets. So inside the loop, I'm using metadata to read in a file from disk, operate on it, and write back out.
Before I turned this operation into a foreach loop, I was writing out debug messages using messages(). However, since I've switched to using foreach and %dopar%, I've noticed that the loop 'goes dark': it's doing what it ought to, but I'm not receiving any output. (I should mention that this loop is written into a script that I'm calling from the shell with Rscript.)
I'm guessing that this has something to do with the fact that doParallel spins off other threads—maybe those threads no longer know where to dump standard output? Thoughts?

A: If you want to output from a parallel-foreach loop, just use the option outfile: makeCluster(no_cores, outfile = "").


text:
Q: Where do search engines start crawling? What do search engine bots use as a starting point? Is it DNS look-up or do they start with some fixed list of well-know sites? Any guesses or suggestions?

A: Your question can be interpreted in two ways:
Are you asking where search engines start their crawl from in general, or where they start to crawl a particular site?
I don't know how the big players work; but if you were to make your own search engine you'd probably seed it with popular portal sites.  DMOZ.org seems to be a popular starting point.  Since the big players have so much more data than we do they probably start their crawls from a variety of places.
If you're asking where a SE starts to crawl your particular site, it probably has a lot to do with which of your pages are the most popular.  I imagine that if you have one super popular page that lots of other sites link to, then that would be the page that SEs starts will enter from because there are so many more entry points from other sites.
Note that I am not in SEO or anything; I just studied bot and SE traffic for a while for a project I was working on.

A: You can submit your site to search engines using their site submission forms - this will get you into their system. When you actually get crawled after that is impossible to say - from experience it's usually about a week or so for an initial crawl (homepage, couple of other pages 1-link deep from there). You can increase how many of your pages get crawled and indexed using clear semantic link structure and submitting a sitemap - these allow you to list all of your pages, and weight them relative to one another, which helps the search engines understand how important you view each part of site relative to the others.
If your site is linked from other crawled websites, then your site will also be crawled, starting with the page linked, and eventually spreading to the rest of your site. This can take a long time, and depends on the crawl frequency of the linking sites, so the url submission is the quickest way to let google know about you!
One tool I can't recommend highly enough is the Google Webmaster Tool. It allows you to see how often you've been crawled, any errors the googlebot has stumbled across (broken links, etc) and has a host of other useful tools in there.

A: In principle they start with nothing. Only when somebody explicitly tells them to include their website they can start crawling this site and use the links on that site to search more.
However, in practice the creator(s) of a search engine will put in some arbitrary sites they can think of. For example, their own blogs or the sites they have in their bookmarks.
In theory one could also just pick some random adresses and see if there is a website there. I doubt anyone does this though; the above method will work just fine and does not require extra coding just to bootstrap the search engine.


text:
Q: Remove a class on click with RegEx I have a small app weather app that displays some basic info from public API and based on that info I add a certain icon (e.g. sun, cloudy) to the App. User can check another city after the first, and I'd like to change that icon every time conditions changes. I could do it with clearing all classes, adding basic classes and then adding right icon class, or just changing every if to "classList(all relevant classes) but I'd rather do that with RegEx. Here is how the App works:
cityButton.addEventListener("click", function() {
    if (mainIcon.classList.contains(new RegExp(/^wi-.+$/))) {
        console.log("Icon contains wi-");
    }
    fetch(api + "q=" + cityInput.value + "&APPID=" + key + "&units=metric")
    .then((resp) => resp.json())
    .then((data) => {
        let date = new Date();
        let currentTime = date.getHours();
        if (currentTime >= 6 && currentTime <= 18 && data.clouds.all < "25") {;
            mainIcon.classList.add("wi-day-sunny");
        } else if (currentTime >= 18 && currentTime <= 6 && data.clouds.all < "25") {
            mainIcon.classList.add("wi-night-clear");
        } else if (currentTime >= 6 && currentTime <= 18 && data.clouds.all >= "25" && data.clouds.all < "50") {
            mainIcon.classList.add("wi-day-cloudy");
        } else if (currentTime >= 18 && currentTime <= 6 && data.clouds.all >= "25" && data.clouds.all < "50") {
            mainIcon.classList.add("wi-night-alt-cloudy");
        } else if (currentTime >= 6 && currentTime <= 18 && data.clouds.all >= "50" && data.clouds.all < "75") {
            mainIcon.classList.add("wi-day-cloudy-high");
        } else if (currentTime >= 18 && currentTime <= 6 && data.clouds.all >= "50" && data.clouds.all < "75") {
            mainIcon.classList.add("wi-night-alt-cloudy-high");
        } else if (data.clouds.all >= "75") {
            mainIcon.classList.add("wi-cloudy");
        }
        temperature.innerHTML = data.main.temp;
        tempMin.textContent = data.main.temp_min;
        tempMax.textContent = data.main.temp_max;
        pressure.textContent = data.main.pressure + " hPa";
        humidity.textContent = data.main.humidity + " %";
        wind.textContent = data.wind.speed + " m/s";
        clouds.textContent = data.clouds.all + " %";
        windDir.textContent = data.wind.deg;
        city.textContent = data.name;
        if (data.rain !== undefined) {
            rain.textContent = data.rain + " %";
        }
    })
    .catch(function(error) {
        console.log(error);
    })
});

As you can see, user puts city name in the input, click search and then the app should check if the span "mainIcon" contains a class with name that starts with "wi-". RegEx is correct, I've tested it using https://regexr.com/, but in the console there is nothing showing up. i've tried also:
const wiClass = new RegExp(/^wi-.+$/);
    if (mainIcon.classList.contains(wiClass)) {
        console.log("Icon contains wi-");
    }

But again, no luck. What I want to do is something like this:
if (mainIcon.classList.contains(wiClass)) {
        mainIcon.classList.remove(wiClass);
    } else {
        return;
    }

Why doesn't that work? I'll appreciate all of your answers, as long as there is no jQuery involved (I like it, but I want to do it in vanilla JS).

A: You should not use classList with regular expression, contains method works with string parameter, not regex. You could just use plain old className property with match method:
const wiClass = new RegExp(/\bwi-.+?\b/, 'g');

if (mainIcon.className.match(wiClass)) {
    console.log("Icon contains wi-");
}

To remove class with regular expression you would again use className
if (mainIcon.className.match(wiClass)) {
    console.log("Icon contains wi-");
    mainIcon.className = mainIcon.className.replace(wiClass, '')
}

Note, g global flag in regular expression necessary to remove all wi- classes.


text:
Q: how to select particular cells in excel using VBA? im trying to select cell B4 and all the cells from column A to Z and row 10 and below, so basically A10:Z150. And trying to unlocked it before i protect the sheet.
Right now im using Sheets("DR02").Range("B4", "A10:Z200").Locked = False but its not working. Its only unlocking cells above row 4 instead of only cell B4.

A: Try to use:
  With Sheets("DR02")
    .Unprotect "password"
    .Range("B4,A10:Z200").Locked = False
    .protect "password"
  End With

Or (to get the last row in column "A"):
With Sheets("DR02")
 .Unprotect "password"
 .Range("B4,A10:Z" & .Range("A" & .Rows.Count).End(xlUp).Row).Locked = False
 .protect "password"
End With

EDIT:
From comments it seems that cell B4 is merged with other cells if so then we can use:
With Sheets("DR02")
 .Unprotect "password"
  Union(.Range("B4").MergeArea, .Range("A10:Z" & .Range("A" & .Rows.Count).End(xlUp).Row)).Locked = False
 .Protect "password"
End With

A: Union(Range("B4").MergeArea, Range("A10:Z" & Range("B" & Rows.Count).End(xlUp).Row)).Locked = False


text:
Q: RNN model predicting only one class? I am trying to use GloVe embeddings to train a rnn model based on this article.
I have a labeled data: text(tweets) on one column, labels on another (hate, offensive or neither).
However the model seems to predict only one class in the result.
This is the LSTM model:
model = Sequential()
hidden_layer = 3
gru_node = 32

# model embedding matrix here....

for i in range(0,hidden_layer):
    model.add(GRU(gru_node,return_sequences=True, recurrent_dropout=0.2))
    model.add(Dropout(dropout))
model.add(GRU(gru_node, recurrent_dropout=0.2))
model.add(Dropout(dropout))
model.add(Dense(64, activation='softmax'))
model.add(Dense(nclasses, activation='softmax'))
start=time.time()
model.compile(loss='sparse_categorical_crossentropy',optimizer='adam',metrics=['accuracy'])

fitting the model:
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 1)
X_train_Glove,X_test_Glove, word_index, embeddings_index = loadData_Tokenizer(X_train, X_test)

model_RNN = Build_Model_RNN_Text(word_index,embeddings_index, 20)
model_RNN.fit(X_train_Glove,y_train,
                            validation_data=(X_test_Glove, y_test),
                            epochs=4,
                            batch_size=128,
                            verbose=2)
y_preds = model_RNN.predict_classes(X_test_Glove)
print(metrics.classification_report(y_test, y_preds))

Results:

*

*classification report

*Confusion matrix

Am I missing something here?
Update:
this is what the distribution looks like

and the model summary, more or less

A: How the distribution of your data looks like? The first suggestion is to stratify train/test split (here is the link for the documentation).
The second question is how much data do you have in comparison with the complexity of the model? Maybe, your model is so complex, that just do overfitting. You can use the command model.summary() to see the number of trainable parameters.


text:
Q: Unable to copy() image from one folder to another I am trying to copy an image from one folder to another. I feel that my paths are wrong, but I have tried so many path combinations that I am now unsure whether it is the problem.
I am trying to copy an image (if it exists) from the user_photos folder, into the profile_pics folder. Here are where they are located, as well as the script, known as, change_dp.php, which once called, will execute the copy().
www > user_data > user_photos > photos_are_here
www > user_data > profile_pics > photos_are_here
www > inc > change_dp.php

Here is change_dp.php:
$all_pics = mysqli_query ($connect, "SELECT * FROM user_photos WHERE username = '$username'");
    $row_query = mysqli_fetch_assoc($all_pics);
            $get_photo_owner = $row_query['username'];
            $get_photo_id = $_GET['id'];

$get_pic_with_id = mysqli_query ($connect, "SELECT * FROM user_photos WHERE id = '$get_photo_id'");
    $row_query2 = mysqli_fetch_assoc($get_pic_with_id);
            $img_url = $row_query2['img_url'];

    $file = $img_url;
    $arrPathInfo = pathinfo($file);
    $shortened_url = $arrPathInfo['basename'];

if (file_exists($file)) {
copy("../../" . $file, "../../profile_pics/" . $shortened_url);
}

$pro_pic_change = mysqli_query($connect, "UPDATE users SET profile_pic='$shortened_url' WHERE username = '$username'") or die ($connect);
     header("Location: /photos/$get_photo_owner");

Just to illustrate the issue more:

*

*User uploaded photos (which are stored in user_photos) are stored in there full path in my database, for example, if Alice uploads a file called alice.jpg, it will be stored as user_data/user_photos/alice.jpg. This is why I have varible $shortened_url which will only get the base name of the file i.e. get the alice.jpg from user_data/user_photos/alice.jpg. I need the $shortened_url because column profile_pics in the database holds just the base name of the image, not the full path.

*With the if statement, I am trying to get the basename of the image, see if an image with the same name in my user_photos file exists, and if it does, copy it into the profile_pics folder and set the basename to profile_pics column via an UPDATE statement. The UPDATE statement works fine, the image name does change in the database, but the image just doesn't copy over, which corrupts the image since it cant find it in the profile_pics folder.

What I have tried:
copy($file, "../profile_pics/" . $shortened_url);
copy("../../" . $file, "../../profile_pics/" . $shortened_url);
copy($file, "user_data/profile_pics/" . $shortened_url);

None which work.
Edit:
Here's what I want the code to do:
Lets assign values to $file for an example:
$file = user_data/user_photos/alice.jpg

*

*See if an image with the name of $file exists in the user_photos folder.

*If there is a file with the name of alice.jpg in the folder, then copy that image into the profile_pics folder.

*That's it.

A: You could use __DIR__ magic constant and then based on that you can go to upper levels in the directory hierarchy, by using realpath() function or even dirname() function. This way it will be less confusing and less error prone.
E.g.:
$upOneLevel = realpath(__DIR__."../");
$upTwoLevels = realpath(__DIR__."../../");

So to access your file you shoud use:
$fileRealPath = $upOneLevel."/".$file;
$fileRealDestination = $upOneLevel."user_data/profile_pics/".$shortened_url;

I also recommend to update the data in the DB only if the file exists and the copy command executes successfully:
if (file_exists($fileRealPath)) {
    if(copy($fileRealPath, $fileRealDestination)) {
        //TODO db logic here
    } else {
        //TODO error handling here
    }
} else {
    //TODO error handling here
}


text:
Q: How to find midpoint of an array of points and continue recursive call till a number of times? The idea is to find the mid point of a bezeir curve. Following is the De Casteljau's algorithm for finding the midpoint of a curve with four points.
How can I implement such an algorithm in javascript using recursion?
Following is the four starting points. From here we start the algorithm and through recursion we arrive the tip of the tree.
(0, 0)
      \
       (1/2, 0) --> this node is calculated as follows [(x1 + x2)/2, (y1 + y2)/2]
      /        \
(1, 0)          (3/4, 1/4)
      \        /          \
       (1, 1/2)            (3/4, 1/2)
      /        \          /
(1, 1)          (3/4, 3/4)
      \        /
       (1/2, 1)
      /
(0, 1)

for example the sample input of points will be like this
const points = [[0,2], [4,5], [6,7], [3,8]]

output = [3,5]

// so the output will be just an array of two numbers for eg: [3,5] (just a rough figure for demo) which represents the midpoint of the above four points obtained by the above algorithm.

So this tip of the tree (output) will be the midpoint of the given curve.
This is the code a fellow coder of stack overflow (Nina Scholz) have come up with and it works perfectly for me. But I want to extend it further. I've given an illustration. Nina's code is perfect for finding the midpoint for the first time. I want to find the remaining points by segmenting the curve as follows.
const
    getB = array => {
        if (array.length === 1) return array[0];

        const result = [];

        for (let i = 1; i < array.length; i++) {
            result.push([(array[i - 1][0] + array[i][0]) / 2, (array[i - 1][1] + array[i][1]) / 2]);
        }

        return getB(result);
    },
    points = [[0, 2], [4, 5], [6, 7], [3, 8]];

console.log(getB(points));

UPDATE
Remember each node is calculated as follows [(x1 + x2)/2, (y1 + y2)/2]. i.e., by taking the average of similar coordinates of two adjacent points.= .
UPDATE
The code suggested by Nina Scholz works fine.
But I want to extend it further. Ninas code returns the first midpoint. But I want to extend it to find more points as illustrated below.

UPDATE
This is not to segment the curve. But to find points at equal distance, by starting at the mid point then dividing the curve in to two segment, then again finding midpoint of those two segments, like wise this repeats till the number of points required is reached/exhausted. So the requirement is to find the points of a cubic bezeir curve.
NOTE
Once the middle point is returned this point becomes the starting point and ending point of the lines obtained by the previous midpoint, in this way it proceeds further till the number of points required is reached. This way we can find the location/coordinates of points separated by equal distance starting at the midpoint.
JUST CONSIDER IT LIKE FOLDING A PAPER. INSTEAD HERE WE FOLDS THE CURVE & finds the points of the curve at each fold/ points of segmentation.


text:
Q: ¿Cómo ingresar valores en un array usando JavaScript?

var sum = [];
var value1 = [];
var value2 = [];

for(i=1;i<=1000;i++){
    var result = '';
    if(i % 3 == 0){
        result+=' multiplo de 3: '+i;
    }
    if(i % 5 == 0){
       result+=' multiplo de 5: '+i;
    }
}
console.log(result);

Saludos, lo que deseo hacer es ingresar todos los múltiplos de 3 y de 5 en dos arrays distintos, para sumarlos ¿Cómo lo hago?

A: Debes usar Array.prototype.push
Este método inserta elementos dentro de un array

const miArray = [];
miArray.push("Hola mundo");
console.log(miArray) // ["Hola mundo"]

Este método Reasigna el array, por lo que no tendrás que reasignarlo con el valor de devolución del método

En tu código veo un error:
console.log(result)

No estará definido, ya que solo es válido durante el bucle y el bucle tampoco está haciendo gran cosa, ya que siempre se va a reiniciar result, recuerda que var define una variable global, a no ser que se defina en una función o bucle
Tu solución quedaría así

var sum = [];
var value1 = []; // múltiplos de 3
var value2 = []; // múltiplos de 5
var result = '';

for(i=1;i<=10;i++){
    if(i % 3 == 0){
        result+=' multiplo de 3: '+i+" ";
        value1.push(i);
    }
    if(i % 5 == 0){
       result+=' multiplo de 5: '+i+" ";
       value2.push(i);
    }
}
console.log(result);

Además, no te recomiendo para nada hacer un bucle tan largo: <=1000, ya que eventualmente te traerá problemas


text:
Q: Unable to delete Excel file after reading from the file in NodeJS I have file hosted on S3 bucket from where I am fetching the Excel file using an Axios request. After that I am writing that Excel file in the local filesystem. After that I am converting that Excel file data into JSON and sending it as a response; for that I am using XLSX library.
After sending the Excel file data as a JSON response I want to delete that Excel file from local filesystem.
When I am trying to delete the file it's failing to delete as well as failed to read the file. But when file is already available then it's reading the file and sending the response also.
Below is my code:
const response = await axios.get(data.me_url, { responseType: 'arraybuffer' });

        if (response) {

            const ostream = await fs.createWriteStream(`./${filename}`, 'binary');
            ostream.write(response.data);
            ostream.end();

            const file = xlsx.readFile(`./${filename}`);
            const sheetNames = file.SheetNames;
            const totalSheets = sheetNames.length;

            let parsedData = [];

            for (let i = 0; i < totalSheets; i++) {

                const tempData = xlsx.utils.sheet_to_json(file.Sheets[sheetNames[i]]);
                tempData.shift();
                parsedData.push(...tempData);
            }

            if (parsedData.length > 0) {
                console.log('if filename',filename);
                try {
                    fs.unlinkSync(`./${filename}`);

                    console.log("Delete File successfully.");
                    return res.status(200).send({ 'data': parsedData, 'message': 'Success', 'code': 200 });
                  } catch (error) {
                    console.log(error);
                  }
            }
        }

What am I doing wrong in the above code?

A: You don't need to create file in the local machine, send the file Array Buffer directly to xlsx directly as mentioned in the link here


text:
Q: Show that the gradient of the curve is positive for all x in the given interval (for a trig function) I am given the following question:

The equation of a curve is $\ y = \frac{\sin x}{1+\cos x}$ for $−π<x<π$. Show that
the gradient of the curve is positive for all $x$ in the given interval.

I've successfully differentiated the curve's equation to get:
$ \frac{dy}{dx} = \frac{1}{1 + cosx}$
My last issue is mathematically proving that the derivative function stays above 0 for all values of x. I understand that $\ -1 < \cos x < 1 $, so $\ 0 < \cos x + 1 < 2$. However, how do I figure out the max and min values that the derivative function $ \frac{dy}{dx} = \frac{1}{1 + cosx}$ can take?
P.S.: I'm still learning formatting equations and such into the correct format, and am using this place as an alternative to no teachers and peers due to the virus situation (have AP-equivalent calc exams soon).

A: Firstly note that your function is undefined at $x=-\pi$. So I think the interval should be $-\pi<x<\pi$.
As @lab bhattacharjee mentioned in the comments we have $\cos(2x)=2\cos^{2}(x)-1$ so $$\cos(x)=2\cos^{2}(\frac{x}{2})-1$$ and $\cos(x)+1=2\cos^{2}(\frac{x}{2}).$
Clearly $\cos^{2}(\frac{\pi}{2})=\cos^{2}(\frac{-\pi}{2})=0$, $\cos^2(0)=1$ and it follows that $0<2\cos^2(\frac{x}{2})\leq2$ for all $x\in(-\pi,\pi).$
Hence $$\frac{dy}{dx}=\frac{1}{1+\cos(x)}=\frac{1}{2\cos^{2}(\frac{x}{2})}$$ and from the previous calculations we have $\frac{1}{2\cos^{2}(\frac{x}{2})}\geq\frac{1}{2}$ for $-\pi<x<\pi.$

A: We know that
$$\frac{\sin{x}}{1+\cos{x}}=\frac{2\sin\frac{x}{2} \cos\frac{x}{2}}{1+2\cos^2\frac{x}{2}-1}=\frac{2\sin\frac{x}{2} \cos\frac{x}{2}}{2\cos^2\frac{x}{2}}=\tan\frac{x}{2}$$
And we know that
$$\frac{d}{dx}\tan\frac{x}{2}=\frac{1}{2}\sec^2\frac{x}{2}$$
As something squared is always positive, then the gradient must always be positive as required.
(Note: we have proved a stronger result; namely that the gradient is positive for all $x\in\mathbb R$, not just in the given interval.)
EDIT:
In answer to your comment:
We have
$$0<1+\cos{x}<2$$
Assuming you understand why this true, consider
$$\frac{1}{1+\cos{x}}$$
If $1+\cos{x}$ is very very very close to $2$, which is possible according to the inequality, then $\frac{1}{1+\cos{x}}$ is very very very close to- but very slightly greater- than $\frac{1}{2}$. (If you have trouble understanding why, here's another example: $\frac{1}{1.9}>\frac{1}{2}$.) So we have
$$\frac{1}{1+\cos{x}}>\frac{1}{2}$$
However, if $1+\cos{x}$ is very close to $0$, then the expression $\frac{1}{1+\cos{x}}$ gets extremely big; mathematically we say that as $1+\cos{x}$ approaches $0$, then $\frac{1}{1+\cos{x}}$ approaches infinity, or $\infty$ if you prefer.
Obviously, for the values of $1+\cos{x}$ in between $0$ and $2$, the value of $\frac{1}{1+\cos{x}}$ will be 'between' $\frac{1}{2}$ and $\infty$.
So, we can write that
$$\frac{1}{2}<\frac{1}{1+\cos{x}}<\infty$$
ie $$\frac{1}{2}<\frac{1}{1+\cos{x}}$$ as required. Remember; anything divide by $0$ is infinitely large, not $0$ (I believe that's the mistake that the examiners were alluding to). I hope that helps. If not, don't hesitate to ask any further questions.
Good luck in your A Levels, from one A-Level Student to another :)

A: Expressed  in terms of half angles
$$ y=\dfrac{2sc}{2cc}= \tan \frac x2$$
Its derivative $\dfrac{1}{2\cos^2(x/2)}$ is always $>0$ and increases monotonously between x-limits $\pm \pi. $


text:
Q: 3 integer unknowns and 1 equation All numbers are integers and none equate to 0.
$$ 4=\frac{a}{b+c}+ \frac{b}{a+c} + \frac{c}{b+a} $$
My friend made this question, I tried to solve it for 2 hours and then he told me that I needed to use cryptology. I want to see how questions like these are solved. Answers: -1, 4, 11