text:
Q: Python software development (CSV to Pandas to SQL or CSV to SQL to Pandas) I have multiple csv files that I want to manipulate(calculate mean, sum, etc.) and after that I want to store them in a SQLite database.
But I want to know what is the most proper way to do that.
CSV to SQL and manipulate with Pandas
OR
CSV, manipulate with Pandas and store in SQL
For example, I want to store all the data in this table http://financials.morningstar.com/ratios/r.html?t=GOOG&region=USA&culture=en-US.
I will update yearly and add 2013,2014,etc. In my SQL table.
I'll create a column where I will have 10 year average for each rows, etc.
Regards,

A: Right now, pandas's support for manipulating CSV files is far beyond that of its ability to manipulate SQL databases, though there is a significant effort right now to improve the latter by leaps and bounds!
Take a look at the read_csv docs. This is one of the most flexible, fast, and generally powerful text file readers/writers out there for data analysis applications.
On the other hand read_sql can only write to sqlite databases and doesn't store the index.
With read_csv you can even read MultiIndex objects (hierarchical indexes)!
If you aren't tied to a database, then I would recommend that you look into using pandas HDF5 for persistence. I use this all the time and it works great.
In summary, I would recommend the first choice you listed if you must use a database since writing anything to database is not going to work unless you're using sqlite, but you can read from others besides sqlite.


text:
Q: PHP MySQL Negative Value (Balance) Issue I am developing a desktop software where it charge user per execution the main action. For example say it will charge user 0.1$ for per PDF print.
and my software provide multithreading. .
so, if it run single thread it works fine :)
but the problem is if user run multiple thread at one (say 10/20 threads)
it (php) also continues user to allow the server/execution even balance get below zero..
though my php script check whether balance is positive ..
but after user run multiple threads balance become like -5.95$ or -25.75$ etc
and that is a big security/financial issue..
here is the code I am using:
<?php

$strSQL = "Select * from users where Email = '$strUser'";
$return = mysql_query($strSQL, $strDBConn);
$strDBData = mysql_fetch_array($return, MYSQL_ASSOC);
//checking balance
$strBalance = $strDBData['Balance'];
if($strBalance < 0)
{
    // if balance 0 then exit so, my software/thread will not process further
    mysql_close($strDBConn);
    exit('Balance Exceed');
}

//rest of the codes that realted to service executaion

// code that substract the balnce
    $dblCost = 0.25;
    $strSQL = "Update users set Balance = Balance - '$dblCost' where Email = '$strUser'";
    $return = mysql_query($strSQL, $strDBConn);

//rest finising codes

?>
any help/suggestion would be highly appreciated..
thanks in advance.
best regards

A: I think, this is a quite similar question:
What is equivalent of the C# lock statement in PHP?
First, try to switch away from the old "mysql" to somethin new, maybe some PDO like DB access ;).
Then, for getting around with multi-thread in php, it can be a good idea, to write a file for every userid (!) and lock this file, when there's a request. When file is locked in another thread, wait for x seconds for the file to be unlocked by the locker-thread. If it is not unlocked within time, something went wrong. When in locked-thread all went good, unlock the file after every operation needed.
Theoraticaly you will be good with then till there's a multi-thread soloution in PHP ;)

redpajama_set_name: RedPajamaStackExchange


text:
Q: From WatchOS App connect BLE device using iPhone Bluetooth Hi everyone here it's my problem, I have an simple app on my Apple Watch and iPhone. All my goal is using iPhone minimum on the App. Instead of iPhone App I want to use this App mostly from the watch. So I have an UI screen consisting with 2 buttons (Scan and Connect) on the watch. And these buttons should control the iPhone's Bluetooth. I don't want to use Watch Bluetooth. Considering all, is it posibble to trigger the iPhone Bluetooth in background from Watch and connect iPhone to a BLE device.
I think I fix this problem with your help guys;
Hi again, I believe I can fix this problem with the background transfers. Let me first explain the problem better when I want to use iPhone App local database and also want to use iPhone's Bluetooth from the Watch App I had trouble. And then I noticed sending messages from Watch to iOS wakes up iOS in the background (Source for more detail). In this way I'll have using iPhone app only in background and even scan BLE devices from the iPhone in bg and send them to the Watch App (WC Sessions).
Source (Communicate with iPhone and Watch)
https://medium.com/@jackywangdeveloper/apple-watch-communication-with-iphone-af84d51ff810


text:
Q: How to include third party script into background.js I want to include this script https://raw.githubusercontent.com/wrangr/psl/master/dist/psl.min.js into my background.js and use it like:
var url = tabs[0].url;
url = url.split("/")[2];
var domain = psl.parse(url);

where psl is coming from the included script.
What is the correct syntax for including the script in the background.js?


text:
Q: Enabling CLR still doesn't allow me to run code on sql server I'm using the following command to try and enable the CLR on a SQL Server 2008 instance
EXEC sp_configure 'clr enabled', 1
GO

RECONFIGURE
GO

But I still get the following error

Execution of .NET Framework code is disabled. Set "clr enabled"
  configuration option and restart the server

Do I need to do anything else?

A: To review what has been checked and attempted so far:

*

*EXEC sp_configure 'clr enabled', 1; has been executed.

*RECONFIGURE; has been executed.

*The server has been restarted. This should only be
necessary on WOW64 servers.

*Running EXEC sp_configure 'clr enabled'; shows a 1 for run_value.

*Running EXEC sp_configure 'lightweight pooling'; shows a 0 for run_value.

*state property in sys.dm_clr_properties has a value of "Locked CLR version with mscoree", meaning:

The Locked CLR version with mscoree state may be seen where the hosted CLR is not being used and, thus, it has not yet been initialized. The hosted CLR is initialized the first time a DDL statement (such as CREATE ASSEMBLY (Transact-SQL)) or a managed database object is executed.

Additional things to try / check:

*

*Make sure that .NET Framework 2.0 and 3.5 SP1 are installed

*Make sure that .NET Framework patches have been applied through Windows Update

*Possibly make sure, in Control Panel\Programs\Programs and Features that "Microsoft SQL Server System CLR Types" is installed

*Check your authentication type. If set to "both", try change to "Windows Only", restarting the SQL Server service, and see if that helps. Not a good long-term solution, but might point in a direction.

*What account is the MSSQLSERVER service logging on as? There are some reports that "Network Service" or "NT AUTHORITY\Network Service" might have issues and that Local System account might be preferred.

*??

A: Try
EXEC sp_configure 'clr enabled', 1
go
 RECONFIGURE
go
EXEC sp_configure 'clr enabled'
go

Also

To enable CLR integration, you must have ALTER SETTINGS server level permission, which is implicitly held by members of the sysadmin and serveradmin fixed server roles.

A: Are you sure you have advanced options enabled?
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'clr enabled', 1;
GO
RECONFIGURE;
GO


text:
Q: Heatmap of gene subset from microarray expression data in R I have a mircoarray dataset from the illumina beadchip platform which I have been using to examine differential expression between 3 treatment groups.  Following background subtraction and normalisation I have a file of class "Elist" type - represented as below.
$E
                     A         B         C         D        E        F
ILMN_1        9.678162  9.635665  9.420577  9.778417  9.521473  9.820778
ILMN_2       11.458221 11.152161 11.158666 11.410278 11.416522 11.377062
ILMN_3        9.385075  9.087426  9.230654  9.704379  9.720282  9.482488
ILMN_4        9.909423  9.115123  9.693177 10.348670  9.896625  9.729896
ILMN_5       11.826927 12.067796 12.165630 12.256113 12.061949 12.213470

$genes
             SYMBOL
ILMN_1       Gene 1
ILMN_2       Gene 2
ILMN_3       Gene 3
ILMN_4       Gene 4
ILMN_5       Gene 5

I would now like to create an object of "Elist" class which includes only a subset of genes selected by their gene symbol with a view to generating a heatmap of the subset. ( I should be able to manage the heatmap from there)
eg
$E
                     A         B         C         D        E        F
ILMN_2       11.458221 11.152161 11.158666 11.410278 11.416522 11.377062
ILMN_4        9.909423  9.115123  9.693177 10.348670  9.896625  9.729896

$genes
             SYMBOL
ILMN_2       Gene 2
ILMN_4       Gene 4

I have tried

subset = Elist[Elist$genes == c("gene 2", "gene4"), ]

but this seems to only generate a subset of the first gene in the vector or occasionally several rows of NAs. If I inset just one gene into the vector it works fine.

subset = Elist[Elist$genes %in% c("gene 2", "gene4"), ]

returns an object of Elist class with no rows.

Any help much appreciated. (any advice on how to post the question better appreciated too!)
Many thanks - Vincents answer works very well - the solution was

subset = Eset[ Eset$genes$SYMBOL %in% c("Gene2", "Gene4"), ]

I would now like to make a heatmap of the gene subset firstly being able to order the columns myself into treatment groups and secondly replacing the row names with gene names rather than the probe name.
I am able the remove the clustering order using Colv but unable to get any further

heatmap.2(Subset$E, Colv = FALSE, Rowv = FALSE)

Any help much appreciated.

A: Let's call this object expr, instead of EList (the name of the class itself):
require(limma)
expr <- new("EList"
            , .Data = list(structure(list(A = c(9.678162, 11.458221, 9.385075, 9.909423, 11.826927),
                                          B = c(9.635665, 11.152161, 9.087426, 9.115123, 12.067796),
                                          C = c(9.420577, 11.158666, 9.230654, 9.693177, 12.16563),
                                          D = c(9.778417, 11.410278, 9.704379, 10.34867, 12.256113),
                                          E = c(9.521473, 11.416522, 9.720282, 9.896625, 12.061949),
                                          F = c(9.820778, 11.377062, 9.482488, 9.729896, 12.21347)),
                                     .Names = c("A", "B", "C", "D", "E", "F"),
                                     class = "data.frame",
                                     row.names = c("ILMN_1", "ILMN_2", "ILMN_3", "ILMN_4", "ILMN_5")),
                           structure(list(SYMBOL = c("Gene1","Gene2", "Gene3", "Gene4", "Gene5")),
                                     .Names = "SYMBOL",
                                     row.names = c("ILMN_1","ILMN_2", "ILMN_3", "ILMN_4", "ILMN_5"),
                                     class = "data.frame")))

We would like to select in the object the lines corresponding to genes 1 and 3.
A previous comment pointed to the right direction, the following should normally work:
expr[ expr$genes$SYMBOL %in% c("Gene2", "Gene4"), ]

Am I missing a question about heatmaps, I don't see any?


text:
Q: How To Create Custom Transparent Tile with a Simple White Image in Center
(source: heidibone.com)
I'm on Visual Studio Express 2012 writing a WP8 app, but wanting to create Transparent custom tiles, when the WP8.1 users manually create custom tiles through the app, that allow them to see their Background Start Screen Image.
My graphics knowledge is about rock bottom, and so not sure if I use something like WriteableBitmapEx to even start.
Note: My main App pinned Tile will not be transparent, and that's okay.
It's only when I create a custom tile, such as the Local Scout or Data Sense one above - but my tiles would simply have a 3 White Letters in the center, like "ABC".
Does anyone know of a resource that steps you through that, or have a code example?  (The examples I've found through searching on Bing are only for advanced examples of fancy graphics on an actual XAML page).

A: To make the tiles transparent you just need to use transparent PNGs. If the tile names are from a finite set, just create the tile images in a tool like Paint.NET and bundle them with the app.


text:
Q: Angular typecast $event I am trying to apply fix the issues by enabling the strict mode and one of the issue I faced that I don't have a clean answer for that is when $event is unknown
<div
     echarts
     (chartInit)="onChartInit($event)"
     (chartLegendSelectChanged)="onChartLegendSelectChanged($event)"
     (chartRendered)="onChartRender($event)"
></div>

here I have 3 methods that is returning unknown,

but refering to the document for example in onChartLegendSelectChanged I know that it return a LegendOption
so I define the method like this:
onChartLegendSelectChanged($event: LegendOption) {
    //logic when chart legend selected
}

while this is correct and typescript is happy about it, angular isn't happy with it and expect the method definition be type of unknown
while I can change the function argument to unknown and inside the function I cast the type to the desired type, but it's very ugly.
so is there anyway to cast the $event to a type inside the template? i saw other solution use pipe, but you can't use pipe inside a method call.

A: You can use $any() function in template.
In your case:
(chartLegendSelectChanged)="onChartLegendSelectChanged($any($event))"
it's basically declare it as any type :)

A: I'd say you have to provide a type for the @Output:
  @Output() chartLegendSelectChanged = new EventEmitter<LegendOption>();

This way you can maintain type safety (which isn't the case with $any).


text:
Q: Android populate spinner with string array Below I have attached my code for trying to add my string array, names, to the spinner as the options. As of now, I am not getting anything populating the array, and I am really not sure what I'm doing wrong. I have looked over other similar questions on this site, as well as using Google, and have come up empty. Can anyone give me some guidance? Thanks
public class RunesActivity extends Activity {

    public static String page;
    TextView textName;
    Spinner spinner;
    ArrayAdapter<String> adapter;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rune_activity);
        GetRunes getRunes = new GetRunes();
        getRunes.execute();
        spinner = (Spinner) findViewById(R.id.rune_selector);
    }

    public void addListenerOnSpinnerSelection() {
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                ((TextView) adapterView.getChildAt(0)).setTextColor(Color.parseColor("#C49246"));
                Toast.makeText(adapterView.getContext(),
                        "Page Selected: " + adapterView.getItemAtPosition(i).toString(),
                        Toast.LENGTH_SHORT).show();

                page = adapterView.getItemAtPosition(i).toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }
    class GetRunes extends AsyncTask<String, String, JSONObject> {

        private String api_key="d96236d2-6ee3-4cfd-afa7-f41bdbc11128";
        String region = MainActivity.region.toLowerCase();
        String id = StatsActivity.sumID;
        String encodedKey = null;
        String encodedRegion = null;
        String encodedId = null;
        String url = null;

        // JSON Node Names
        String TAG_NAME = "name";
        String TAG_CURRENT = "current";
        String TAG_SLOTS = "slots";
        String TAG_RUNEID = "runeId";
        String TAG_RUNESLOTID = "runeSlotId";

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            try {

                // Assign views
                textName = (TextView) findViewById(R.id.name);

                // Encode URL variables
                encodedId = URLEncoder.encode(id, "UTF-8");
                encodedKey = URLEncoder.encode(api_key, "UTF-8");
                encodedRegion = URLEncoder.encode(region, "UTF-8");

                url = "http://prod.api.pvp.net/api/lol/" + region + "/v1.4/summoner/" + id + "/runes?api_key=" + api_key;
                Log.i("..........", url);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

        }

        @Override
        protected JSONObject doInBackground(String... arg0) {
            JSONParser jParser = new JSONParser();

            // Get JSON from URL
            JSONObject json = jParser.getJSONFromUrl(url);
            Log.i("............", "" + json);
            return json;
        }

        @Override
        protected void onPostExecute(JSONObject json) {
            try {
                // Get JSON Object
                JSONObject runes = json.getJSONObject(encodedId);

                // Get JSON Array node
                JSONArray rune = runes.getJSONArray("pages");

                // Loop through pages, page names stored in string array
                String[] name = new String[rune.length()];
                String curr;
                ArrayList<String> runePageNames = new ArrayList<String>();

                for(int i = 0; i < rune.length(); i++) {
                    JSONObject c = rune.getJSONObject(i);
                    name[i] = c.getString(TAG_NAME);
                    curr = c.getString(TAG_CURRENT);

                    if(curr.equals("true"))
                       name[i] = name[i] + " [Active]";
                    runePageNames.add(name[i]);

                    Log.i(".........", name[i]);
                }

                adapter = new ArrayAdapter(RunesActivity.this,
                        android.R.layout.simple_spinner_dropdown_item,
                        runePageNames);

                addListenerOnSpinnerSelection();

                // Set TextView
                textName.setText(name[0]);

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
}

A: Try this..
before calling addListenerOnSpinnerSelection(); method set adapter for that spinner.
adapter = new ArrayAdapter(RunesActivity.this,
                    android.R.layout.simple_spinner_dropdown_item,
                    runePageNames);
spinner.setAdapter(adapter );
addListenerOnSpinnerSelection();


text:
Q: How to display li tag in JavaScript or how to display p tag I want to complete the following code with Django and JavaScript. What I want is

{{value.extra_cost}}
<option id="value" value="{{value.value_code}}">{{value.name} } (+{{value.extra_cost}}won)</option>

In this part
{{value.extra_cost}}
 I want to float this. So in javascript
var optprice = $("#optprice").text(); I did this, but it doesn't show up. What's the problem? Any help would be appreciated.
        <form method="POST" action="{% url 'zeronine:join_create' id=product.product_code %}">

                옵션

                         <select type="text" class="form-control" name="value_code" id="optionSelect" value="{{ form.value_code }}">
                             <option value="none">옵션을 선택하세요.</option>
                                {% for option in option_object %}
                                   {% if option.option_code.option_code.option_code == value.option_code %}
                                       {%if option.product_code == product %}
                                           <optgroup label="{{option.name}}">
                                {% for value in value_object %}
                                   {% if value.option_code.option_code == option.option_code %}
                                       {%if value.product_code == product %}
                                         <option value="{{value.extra_cost}}">{{value.name}} (+{{value.extra_cost}}원)<option id="optprice" style="display: none">{{value.extra_cost}}</option></option>

                                       {% endif %}
                                   {% endif %}
                                {% endfor %}
                                       {% endif %}
                                   {% endif %}
                                {% endfor %}
                                         </optgroup>
                        </select>

A: Maybe something like this

$(document).ready(function() {
   $("#optionSelect").change(function(){
      var label = $(this.options[this.selectedIndex]).prop('text');
      $('#result').text(label)
        console.log(label);
    })
});

<select type="text" class="form-control" name="value_code" id="optionSelect" value="form.value_code">
  <option value="none">옵션을 선택하세요.</option>
  <optgroup label="title-name">

value.extra_cost-1

      <option id="value" value="value_code">value.name extra_cost 1-원</option>

value.extra_cost-2

      <option id="value" value="value_code">value.name extra_cost 2-원</option>

  </optgroup>
</select>

RESULT : -

Demo jsfiddle : https://jsfiddle.net/k60Lb38f/4/
Demo jsfiddle (get value) : https://jsfiddle.net/k60Lb38f/7/


text:
Q: iPhone 6 won't work unless plugged in My iPhone 6 fell down the toilet two days ago but now it works fine. It charges fine when I plug it in, but once I take it out, it shuts off, and tells me there is not enough battery, when it was at a 96 percent. When I plug it in again, it works perfectly and it is at the same percentage that I had left it at. What can I do?

A: From your question I'm assuming the iPhone battery worked well prior to being dropped in the toilet.
It looks like you need to have the battery replaced.  If you have AppleCare, you should go to and Apple Store or contact Apple support to have the battery properly assessed and, if needed, replaced.  See this Apple page for info on replacing the battery.  I would recommend going this route as it appears to be the lowest cost option.
If you don't have AppleCare, you can go to any 3rd party that you trust to replace the battery.  You can also go to Apple to pay to have them replace it.
If you're handy, you can also replace the battery yourself.

A: A couple of months ago Apple initiated a iPhone battery replacement program. You can take advantage of this to have your battery replaced for some nominal cost, much less than what a normal battery costs. If you just want to replace your battery I'd call the nearest Apple Store and set up an appointment to get your battery replaced. Be sure to ask about their battery replacement program.

A: It appears to be a battery related issue. It is recommended you get in touch with Apple Authorised Service Provider to get the issue identified and resolved. It may help if your iPhone is covered under limited warranty or Apple Care, but be forewarned that Liquid damages to iPhone are not covered under warranty.
For starters, you can contact Apple Online Support where you can discuss your issue with Apple Support Representative over Phone or Chat and arrive at possible solutions.
On the Apple Online Support website, select iPhone -> Battery Power & Charging -> Battery questions or troubleshooting. You can opt to chat with the support representative or request for a phone call.

Alternatively, you can find a local authorized service provider and get the device physically inspected.


text:
Q: removing "_" from a very large csv file I have a large csv file (120GB) that looks like this:
"JE",865438083645,2012-12-05T23:07:36.000Z,24,"NQ",142,"658_55525",475035504705
"JE",875619112765,2012-12-05T23:58:04.000Z,4,"PG",144,"219_9221",835399289335
"JE",125495251245,2012-12-05T18:16:06.000Z,206,"PLJE",153,"763_60771",445355650435

I would like to remove the underscore and the quotation marks from the values in the seventh column (e.g., "658_55525" becomes 65855525). The import tool for the database I am using doesn't allow casting or manipulating the file on import.
What would be an efficient way to do it from the command line?

A: I don't know about efficient, but sed with a regular expression.  Make a backup of the file in case you make a typo, but perhaps something like this:
sed -i  's/"\([0-9]\+\)_\([0-9]\+\)"/\1\2/' bigcsvfile.csv

Edit: removed the g, as kos pointed out, no g is needed.

A: Perl is simply the fastest when editing large files.
perl -pi.bak -e 's/"([0-9]+)_([0-9]+)"/$1$2/' your_file.csv

Your backup file is in
your_file.csv.bak

Without a backup:
perl -pi -e 's/"([0-9]+)_([0-9]+)"/$1$2/' your_file.csv

A: Since your file is big, I'd suggest to use gawk > 4.10.0 instead of awk, which supports in-place editing.
Using gawk > 4.10.0:
gawk -i inplace 'BEGIN {FS=","; OFS=","}; {gsub(/["_]/,"",$7); print}' inputfile

*

*-i inplace: tells gawk to edit the file in-place

awk script breakdown:

*

*BEGIN {FS=","; OFS=","}: sets the field separator and the output field separator to ,

*gsub(/["_]/,"",$7): replaces the " and _ characters contained in the 7th field of the record with an empty string

*print: prints the record


text:
Q: static BOOL in Objective C In the following code, I'm creating a category on UIColor to create a random color.  However, from this code, I would have thought that the 'if' conditional would be true every time the method is run, instead of just the first time.
I think I'm not really understanding static variables correctly.   Does a static variable only get set once, and then the second time the method is run, that line is just ignored? (so seeded would forever be YES after the first run)?
@interface UIColor(Random)
+(UIColor *)randomColor
{
    static BOOL seeded = NO;
    if (!seeded)
    {
        seeded = YES;
        srandom(time(NULL));
    }
    CGFloat red = (CGFloat)random()/(CGFloat)RAND_MAX;
    CGFloat green = (CGFloat)random()/(CGFloat)RAND_MAX;
    CGFloat blue = (CGFloat)random()/(CGFloat)RAND_MAX;
    return [UIColor colorWithRed:red green:green blue:blue alpha:1.0f];
}

A: Here static means that the current value of seeded is not lost from one call of the method to the next. The assignment on the declaration line defines only the first value of seeded.
Yes, seeded will forever be YES after the first run.

A: A static variable maintains its value when control leaves the scope of the function. So seeded will be set to whatever value it last had. In your case, you initialize seeded with NO and then set it to YES. So, to answer your question, yes: seeded will always be YES after the first time this method is called.

A: You are correct that the static variable only is set once.
the code
static BOOL seeded = NO;

is not equivalent to
static BOOL seeded;
seeded = NO;

the second one would always evaluate to NO, while the first one will evaluate to NO until set differently.

A: As others have said, static local variables are initialized to a specific value on creation, and retain that value until changed. Static global variables, on the other hand, mean it is local to the file scope -- that is, unaccessable outside of the current source file.
A little history/low level detail can be found at http://en.wikipedia.org/wiki/Block_Started_by_Symbol

A: Static variables are not allocated on the stack like your red, green and blue variables are in this example.  They:

*

*Are allocated in memory at a single, immutable location,

*Consume memory even if the containing function is never called,

*Can cause problems when the function is used in multiple threads -- although your example has a very small likelihood of a race condition, and

*Are assigned once only; offhand I don't recall if it's on the first time the function is called or on when the code is loaded (the latter, I think).

It might help you to think of it as if the compiler moves the declaration (with assignment) outside the function/class scope but access is restricted to within the function.

A: hey u can change values of static variables as many times you want. The reason your if statement is true only once is because you have declared and assigned no in the same statement. Try seperating the two to see the if statement true on every run


text:
Q: getting error on localhost Warning: preg_match(): Null byte in regex in C:\xampp\htdocs\pamper\wp-includes\functions.php on line 5233 I'm getting this error on my every localhost WordPress projects.
and it is not allowing me to log in to the wp-admin panel.
I'm searching on google but not getting any answer.
The error is Warning: preg_match(): Null byte in regex in C:\xampp\htdocs\pamper\wp-includes\functions.php on line 5233

Please help??


text:
Q: Removing RelativeLayout.END_OF which is added programmatically ,android 5.0 I can't but android 8 I can the RelattiveLayout.END_OF which is added programmatically but can't remove. Atv first it can be effected,but second it doesn't.
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mBtnDownload.getLayoutParams();
    if (visible) {
        params.removeRule(RelativeLayout.CENTER_HORIZONTAL);
        params.addRule(RelativeLayout.END_OF, R.id.hidden_view);
        params.leftMargin = ResourceUtils.getDimensionPixelSize(R.dimen.padding_normal_6);
    } else {
        params.addRule(RelativeLayout.CENTER_HORIZONTAL);
        params.removeRule(RelativeLayout.END_OF);
        params.leftMargin = 0;
    }
    mBtnDownload.setLayoutParams(params);


text:
Q: Do I need OAuth2.0 for Google App Engine PHP? Since I can't get an OAuth2.0 token working on my Google Site, and since Google Sites will not host PHP, I'm considering implementing GAE for PHP.  I know that my app.yaml file has the option for authentication, but I'm wondering if I will generally be able to send a request to GAE (via Javascript's XMLHttpRequest method) if I don't have have a OAuth2.0 access token.
Thanks in advance for the newbie help.  The question is as simple as it seems; I just don't want to spend three days developing if I have to fix my authentication problems anyway.

A: Indeed, the GAE PHP auth option in app.yaml doesn't require your app to handle OAuth2.0 access tokens.
This authentication option uses the simple Users PHP API. An app using it can authenticate users with either Google Accounts or accounts on a Google Apps domain (configurable in the app's settings on the Developer Console).
The usage in your app would be fairly simple, based only on creating some URLs. All the heavy stuff happens between the browser and the Google infrastructure, transparently for your app.


text:
Q: nanoc: How can I pass options to pandoc-ruby? I'm trying to use nanoc 3.5.0 with the pandoc filter that uses pandoc-ruby. Specifically, I'm not able to pass several options from my Rules file such that the final call to PandocRuby.convert() looks like this:
PandocRuby.convert(content,
                   {:from => :markdown, :to => :html}, :no_wrap,
                   :table_of_contents, :mathjax, :standalone,
                   {"template" => Dir.getwd + '/layouts/pandocTemplate.html'})

When I place the above call in a custom filter, everything works fine. However, I would like to specify pandoc options in Rules such that I don't have to create a special filter for every set of options.
The default pandoc filter is defined as the function run(content, params={}) and simply calls PandocRuby.convert(content, params). How can I set params such that PandocRuby.convert() gets called correctly? The following directives in Rules do not work:
filter :pandoc, :params => { :from => :markdown, :to => :html, :no_wrap, :table_of_contents, :mathjax, :standalone, "template" => Dir.getwd + '/layouts/pandocTemplate.html' }
filter :pandoc, :params => { :from => :markdown, :to => :html, :no_wrap => true, :table_of_contents => true, :mathjax => true, :standalone => true, "template" => Dir.getwd + '/layouts/pandocTemplate.html' }

The first directive results in a Ruby error, the second directive runs but gives me a blank page, indicating that pandoc did not get called right. I'm not really familiar with Ruby, so my current efforts are just stabs in the dark.

A: The pandoc filter that comes with nanoc can't properly do that at this point. The params given to the filter are passed through directly to PandocRuby.convert:
def run(content, params={})
  PandocRuby.convert(content, params)
end

(source)
Your invocation of the filter has more than two arguments, which is why it crashes. The filter certainly needs to be updated (My idea of how it could be called was too naïve). If you want to take a shot at improving the filter, you are certainly welcome to submit a pull request! I have reported this as an issue in the mean time (link).
(And hopefully I can update this answer with a proper answer soon!)

A: I've written a basic nanoc pandoc filter which calls pandoc directory without pandoc-ruby:
# All files in the 'lib' directory will be loaded
# before nanoc starts compiling.
# encoding: utf-8

module Nanoc::Filters

  class PandocSystem < Nanoc::Filter
    identifier :pandoc_system
    type :text => :text

    def run(content, params = {})
      if item[:extension] == 'org'
        `pandoc -f org -t html < #{item.raw_filename}`
      elsif ["md", "markdown"].index(item[:extension])
        `pandoc -f markdown -t html < #{item.raw_filename}`
      end
    end

  end

end

You can just pass your own options to pandoc according to item[:extension]. Hope it helps.

Update, I've create a new gist which provides an improved version of pandoc filter for nanoc, check: https://gist.github.com/xiaohanyu/9866531.


text:
Q: Extract sub-list items based on matching strings from a larger list of lists I have the following search list to be used to search any items in it against a larger list of lists. I would like the results to be the complete sub-lists but I only seem to get the items themselves.
search_list = ['a', 'b', 'x']
list_of_lists = [['axh', 'opp'], ['l n', '3b v'], ['09,8', 'cdj l', 'sd9 c']
new_lst=[]
for z in list_of_lists:
    yll = [x for x in z if any(w in x for w in search_list)]
    n_lst.append(yll)

Output of new_lst:
new_lst = [['a xh'], ['3 b v'], []]

I was after getting this output instead to show all items inside the resulting lists that match any items from search_list
[['a xh', 'opp'], ['l n', '3b v'], []]

Any suggestions or tips would be appreciated.
Thanks

A: append the sublist to new_list if any character of search_list matches.
search_list = ['a', 'b', 'x']
list_of_lists = [['axh', 'opp'], ['l n', '3b v'], ['09,8', 'cdj l', 'sd9 c']]

new_list = []
for sub in list_of_lists:
    for l in sub:
        if any(w in l for w in search_list):
            new_list.append(sub)
print(new_list)

# Output
# [['axh', 'opp'], ['l n', '3b v']]

A: search_list = ['a', 'b', 'x']
list_of_lists = [['axh', 'opp'], ['l n', '3b v'], ['09,8', 'cdj l', 'sd9 c']]
new_lst=[]
for sublist in list_of_lists:
    for element in sublist:
        for item in search_list:
            if item in element and sublist not in new_lst:
                new_lst.append(sublist)

print(new_lst)

output: [['axh', 'opp'], ['l n', '3b v']]

A: You can use the following set comprehension if you don't mind turning your sublists into tuples:
result = {tuple(sublist) for sublist in list_of_lists for element in sublist for item in search_list
      if item in element}

#output: {('axh', 'opp'), ('l n', '3b v')}


text:
Q: AWS s3 listing does not work I am running into below issue while I am trying to list files using aws s3 ls command. Any suggestions?
server:~/bin> aws s3 ls

HTTPSConnectionPool(host='s3-us-west-2.amazonaws.com', port=443): Max retries exceeded with url: / (Caused by ConnectTimeoutError(<botocore.awsrequest.AWSHTTPSConnection object at 0x2531450>, 'Connection to s3-us-west-2.amazonaws.com timed out. (connect timeout=60)'))

Does this have anything to do with security groups? Unfortunately I am not able to post verbose output, stackoverflow doesnt allow me to do so..

A: Try to use below command
aws s3 --region us-west-2 ls
Also, check AWS credentials should be there in your /root/.aws/credentials file.
Also check whether you have permission to access S3 from that instance or not.


text:
Q: Polling Amazon SQS Queue with Ruby The Amazon SDK for Ruby changes frequently, the current version of the aws-sdk Ruby gem is 2.0.29. The old method of polling Amazon SQS messages is no longer valid
# polling SQS Queue
queue.poll do |msg|
  puts "Got message: #{msg.body}"
end

What is the correct method now for the version 2.0 of the AWS SDK for Ruby?

A: In the documentation of the latest Ruby AWS SDK, I do not see a polling method. However, there is a method receive_message. The details are at http://docs.aws.amazon.com/sdkforruby/api/Aws/SQS/Client.html#receive_message-instance_method
Also, you can configure your SQS to always return a message in response. Here are the details http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-long-polling.html
You will need to make sure the connection does not timeout in case you have to wait too long for the message to arrive and be delivered to you.
Lastly, you can mimic the poll method by calling the receive_message in a while loop and only breaking out of the loop once the response contains some messages. You can employ recursion to process all the messages in a similar fashion.
Updated March 12, 2015
You will also need to delete the message if you want to imitate the poll method.

A: The version 2 SDK does not implement queue polling yet. It is on the SDK backlog as a feature request: https://github.com/aws/aws-sdk-ruby/blob/master/FEATURE_REQUESTS.md#amazon-sqs-queue-poller.

A: You may check Shoryuken, it's built on top of SQS and also integration with Rails (ActiveJob). But you can also use it without Rails, in a standalone Ruby app.


text:
Q: Cypher Neo4j - Rank similar entities based on same relationships In image you see nodes P which are of the same type, all of them have relations to nodes of type C. This is just a generic view with not to many details but all entities has parameter ID. Lets say that I have P1 with distinct relationship patterns i.e to C1-C5... How can I then fetch similar entities of type P that has same relationships and rank on the amount of similar relationships...
Result I would like to have is based on that I have P1 with known HasProperty to C1 a ranked result as:
P2, has 4 similar relationships and also having C1
P3, has 3 similar relationships and also having C1
P4, has 2 similar relationships and also having C1

Thanks!

A: Given the following graph :
CREATE (p1:P {id: 'p1'})
CREATE (p2:P {id: 'p2'})
CREATE (p3:P {id: 'p3'})
CREATE (c1:C {id: 'c1'})
CREATE (c2:C {id: 'c2'})
CREATE (c3:C {id: 'c3'})
CREATE (c4:C {id: 'c4'})
CREATE (p1)-[:RELA {hasProperty: 1}]->(c1)
CREATE (p1)-[:RELA]->(c2)
CREATE (p1)-[:RELA]->(c3)
CREATE (p1)-[:RELA]->(c4)
CREATE (p2)-[:RELA {hasProperty: 1}]->(c1)
CREATE (p2)-[:RELA]->(c2)
CREATE (p2)-[:RELA]->(c3)
CREATE (p2)-[:RELA]->(c4)
CREATE (p3)-[:RELA]->(c2)
CREATE (p3)-[:RELB]->(c3)
CREATE (p3)-[:RELA]->(c4)

You can return, given p1, for each of p2, p3 two list of booleans, one for same relationship type, one for same hasProperty value :
MATCH (n:P)-[r1]->(c)<-[r2]-(other)
WHERE n.id = 'p1'
WITH other.id AS otherId,
collect(r1.hasProperty = r2.hasProperty) AS sameHasProperty,
collect(type(r1) = type(r2)) AS sameType
RETURN *

╒═════════╤═════════════════╤═════════════════════╕
│"otherId"│"sameHasProperty"│"sameType"           │
╞═════════╪═════════════════╪═════════════════════╡
│"p3"     │[]               │[true,false,true]    │
├─────────┼─────────────────┼─────────────────────┤
│"p2"     │[true]           │[true,true,true,true]│
└─────────┴─────────────────┴─────────────────────┘

Then, you can give a score for true or false in each collection.
Let's say similar hasProperty scores 2.0 and similar relationship type scores 1.0 :
MATCH (n:P)-[r1]->(c)<-[r2]-(other)
WHERE n.id = 'p1'
WITH other.id AS otherId,
collect(r1.hasProperty = r2.hasProperty) AS sameHasProperty,
collect(type(r1) = type(r2)) AS sameType
RETURN otherId, (size([x IN sameHasProperty WHERE x = true])*2.0 + size([x IN sameType WHERE x = true])*1.0) AS score
ORDER BY score DESC

╒═════════╤═══════╕
│"otherId"│"score"│
╞═════════╪═══════╡
│"p2"     │6.0    │
├─────────┼───────┤
│"p3"     │2.0    │
└─────────┴───────┘


text:
Q: Zipping files in python My program runs smoothly but I want my files from ftp to be zip in my local drive
The problem is only 1 file is being zipped after calling my main() function
Here's my code:
import os
import upload
import download
import zipfile
import ConfigParser
import ftputil

def main():

    #create a folder Temp on d drive for later use
    path = r'D:\Temp'
    os.mkdir(path)

    #parse all the  values at config.ini file
    config = ConfigParser.ConfigParser()
    config.readfp(open('config.ini'))
    server = config.get('main', 'Server')
    username = config.get('main', 'Username')
    password = config.get('main', 'Password')
    uploads = config.get('main', 'Upload folder')
    downloads = config.get('main', 'Download folder')

    #connect to ftp
    ftp = ftputil.FTPHost(server, username, password)

    dirlist = ftp.listdir(downloads)

    for list in dirlist:
        ftp.chdir(downloads)
        target = os.path.join(path, list)
        ftp.download(list, target)

    #########################################################
    #   THis section is where algo fails but the program run#
    ########################################################

    #zipping files
    absolute_path = r'D:\Temp'
    dirlist = os.listdir(absolute_path)
    filepath = r'D:\Temp\project2.zip'
    for list in dirlist:
        get_file = os.path.join(absolute_path, list)
        zip_name = zipfile.ZipFile(filepath, 'w')
        zip_name.write(get_file, 'Project2b\\' + list)

if __name__ == '__main__':
    print "cannot be"

A: Have a look at the shutil module. There is an example using shutil.make_archive():
http://docs.python.org/library/shutil.html

A: When you do this :
for list in dirlist:
        get_file = os.path.join(absolute_path, list)
        zip_name = zipfile.ZipFile(filepath, 'w')
        zip_name.write(get_file, 'Project2b\\' + list)

you recreate a ZipFile for each file you want to zip, the "w" mode means you recreate it from scratch.
Try this (create the zip file before the loop) :
zip_name = zipfile.ZipFile(filepath, 'w')
for list in dirlist:
        get_file = os.path.join(absolute_path, list)
        zip_name.write(get_file, 'Project2b\\' + list)

Or this, it will open the zipfile in append mode:
for list in dirlist:
        get_file = os.path.join(absolute_path, list)
        zip_name = zipfile.ZipFile(filepath, 'a')
        zip_name.write(get_file, 'Project2b\\' + list)

A: If you have a lot of files you can zip them in parallel:
import zipfile
from pathlib import Path, WindowsPath
from typing import List, Text
import logging
from time import time
from concurrent.futures import ThreadPoolExecutor

logging.basicConfig(
    format="%(asctime)s - %(message)s", datefmt="%H:%M:%S", level=logging.DEBUG
)

PATH = (r"\\some_directory\subdirectory\zipped")

def file_names() -> List[WindowsPath]:
    p = Path(PATH)
    file_names = list(p.glob("./*.csv"))
    logging.info("There are %d files", len(file_names))
    return file_names

def zip_file(file: WindowsPath) -> None:
    zip_file_name = Path(PATH, f"{file.stem}.zip")
    with zipfile.ZipFile(zip_file_name, "w") as zip:
        zip.write(file, arcname=file.name, compress_type=zipfile.ZIP_DEFLATED)

def main(files: List[Text]) -> None:
    t0 = time()
    number_of_files = len(files)
    with ThreadPoolExecutor() as executor:
        for counter, _ in enumerate(executor.map(zip_file, files), start=1):
            # update progress every 100 files
            if counter % 100 == 0:
                logging.info(
                    "Processed %d/%d. TT: %d:%d",
                    counter,
                    number_of_files,
                    *divmod(int(time() - t0), 60),
                )

    logging.info(
        "Finished zipping %d files. Total time: %d:%d",
        len(files),
        *divmod(int(time() - t0), 60),
    )

if __name__ == "__main__":
    files = file_names()
    main(files)

A: Best way to do this is by putting debug statements at your for loops, there are two possibilities;
one is that the first forloop only downloads one file from the ftp folder
two is that the first loop downloads all files but second loop zips only one of them
use print statements to see which files are downloaded/zipped at the loops, good luck


text:
Q: How can I make the transparent part of an image not show up In Android, I am animating two images one small on top of the larger one. The small is generated using Photoshop and the visible part is surrounded by a checkerboard pattern (which is supposed to be transparent). When the animation runs, the images appear but the checkerboard patters shows up as a grey square.
How can I make it transparent.
This is how the imagebutton is setup in the layout.xml
    <ImageButton
    android:layout_gravity="top|left"
    android:layout_marginLeft="184dp"
    android:layout_marginTop="55dp"
    android:id="@+id/videothumb"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/button_power_on" />

And the animation file:
      <?xml version="1.0" encoding="utf-8"?>
      <alpha
      xmlns:android="http://schemas.android.com/apk/res/android"
      android:fromAlpha="0.0"
      android:toAlpha="0.8"
      android:duration="5000"
      android:repeatMode="reverse"
      android:repeatCount="infinite"
       />

A: I think it's because you are using an ImageButton and the grey color you see is the default background of the button. Use an ImageView instead.


text:
Q: npm nested dependency management I have a question about best practices in managing npm nested dependencies.
Let me explain my situation, and please tell me what I'm doing wrong, or what's the best way to approach this.
I'm running an app using express.js and express-mongostore in a nodeenv. Because of nodeenv, I'm npm-ing everything globally so they all go under the nenv/lib/node_modules folder. The thing is, I'm trying to develop off bleeding edge express.js while express-mongostore hasn't been updated in a while. After installing both modules, I get this folder structure.
nodeenv / lib / node_modules / express / node_modules / connect / ..
                             /
                             / connect-mongodb / node_modules/ connect / ...

So what ends up happening is that I have 2 different versions of connect.
I got burnt because the cookie generated by the mongodb store and the one generated by the session middleware is different because they point to 2 different connect utils implementation (one calls the store which calls utils and the other calls utils directly. Unfortunately, they point to different files during require resolution). The actual difference here is that they sign the cookie using different algorithms. For a while, my sessions were invalidating themselves every page load and it took me a long while to debug down to this level.
I was reading on the Internets and it seems like this is supposed to be the npm way and a good thing. The issue here is that since express relies on a bunch of utils in connect and connect-mongodb inherits some of the same classes in connect, having them be different repos is problematic.
I currently still have 2 versions of connect and I patched one to be like the other. It is obvious that this is not a sustainable solution. How should I proceed and approach dependency management in this case?
Thanks in advance!

A: You can run npm dedupe to move compatible dependencies up the tree. So, assuming that express and connect-mongodb can work with the same version of connect, you'll end up with a tree like this:
nodeenv / lib / node_modules / express / ...
                             /
                             / connect-mongodb / ...
                             /
                             / connect / ...

A: You're experiencing a fundamental incompatibility between two modules which assume they can cooperate with one-another.
This is no fault of NPM or flaw in its design. You will need to solve the logic issue yourself.


text:
Q: Google Apps Scripts: Function running twice from .showModalDialog form submit This is my first post and I have searched for days and can not find a solution for this problem.
I have a custom menu in sheets that pops up a .showModalDialog html. A user fills that out with information and clicks submit. This runs a function in the back end that creates folders/files and adds the user data to various sheets etc.
All this is working I have a Ui.alert that I am using to check the data entered is correct and for some reason the function is being trigger twice and the UI.alert is popping up again as a result. I have a fail safe that checks if one of the fields exists so it doesn't write again but the pop up is a really bad user experience.
Any help would be much appreciated.
Function to create custom menu:
function onOpen() {
  SpreadsheetApp.getUi()
      .createMenu('TOA - Menu')
      .addItem('Add New Account', 'addAccount')
      .addItem('Update Brand', 'updateBrand')
      .addItem('Go Live', 'goLive')
      .addToUi();
}

Function to bring up form:
function addAccount() {
  const html = HtmlService.createHtmlOutputFromFile('newAccount')
      .setTitle('Add New Account')
      .setWidth(1000)
      .setHeight(800);;
  SpreadsheetApp.getUi()
      .showModalDialog(html, 'Add New Account');
}

Code for the form:
<!DOCTYPE html>

    <base target="_top">

        Add New Account

  <form id="myForm" onsubmit="handleNewAccountFormSubmit(this);">

    Brand:
    <input name="newBrand" type="text" placeholder="Brand Name" required>

Location

    Country:
    <select name="country" id="" onchange="" required>
      <option value="" disabled selected>Select Country</option>
      <option value="US">US</option>
    </select>

    State/Province:
    <input name="state" type="text" placeholder="State or province" required>

    City:
    <input name="city" type="text" placeholder="City" required>

    Business Type:
    <select name="businessType" id="businessTypeSelect" onchange="businessOtherDisplay(this.value);" required>
      <option value="" disabled selected>Select Request Reason</option>
      <option value="americanDiner">American Diner</option>
      <option value="pizzaParlor">Pizza Parlor</option>
      <option value="coffeeShop">Coffee Shop</option>
      <option value="candyShop">Candy Store</option>
      <option value="iceCreamParlor">Ice Cream Parlor</option>
      <option value="burgerShop">Burger Shop</option>
      <option value="otherNon_AmericanDiner">Other non-American Diner (Foreign servings)</option>
      <option value="other">Other (not listed above)</option>
    </select>

    Business Type Other:
    <input name="businessTypeOther" type="text" placeholder="Business type if not listed above">

    Integration:
    <select name="integration" required>
      <option value="" disabled selected>Select Request Reason</option>
      <option value="square">Square</option>
      <option value="clover">Clover</option>
      <option value="cloverPilot">Clover Pilot</option>
      <option value="stripe">Stripe</option>
      <option value="gPay">GPAY</option>
      <option value="others" >Others</option>
    </select>

    File Attachment/Source:
    <input name="menuSource" type="text" placeholder="Path to menu" required url>

Do you need an item hidden/disabled?

    Yes
    <input name="disableItemOption" type="radio" value="yes" onclick="showItem()">
    No
    <input name="disableItemOption" type="radio" value="no" checked onclick="hideItem()">

    Which item(s) should be disabled?
    <textarea id="disabledItem" name="itemDisable" cols="40" rows="5"></textarea>

Do you need a modifier hidden/disabled?

    Yes
    <input name="disableModOption" type="radio" value="yes" onclick="showMod()">
    No
    <input name="disableModOption" type="radio" value="no" checked onclick="hideMod()">

    Which modifier(s) should be disbaled?
    <textarea id="disabledMod" name="modDisable" cols="40" rows="5"></textarea>

Do you need to update a price?

    Yes
    <input name="updatePrice" type="radio" value="yes" onclick="showPrice()">
    No
    <input name="updatePrice" type="radio" value="no" checked onclick="hidePrice()">

    Which item/modifier needs a price update?
    <textarea id="updatedPrice" name="priceUpdate" cols="40" rows="5" priceUpdate></textarea>

    Any other information needed on the menu?
    <input name="otherUpdates" type="text" placeholder="List other instructions here">

    Are there special instructions/notes for this brand?
    <input name="specialInstructions" type="text" placeholder="List special instructions here">

    <input id="submitButton" type="submit" value="Submit">
    <input type="button" value="Cancel" onclick="google.script.host.close()">

  </form>

And the code to handle the logic
function processNewAccountForm(formObject) {

  const ui = SpreadsheetApp.getUi();
  const ass = SpreadsheetApp.getActiveSpreadsheet();
  const ss = ass.getActiveSheet();
  const timestamp = Utilities.formatDate(new Date(), "GMT+8", "MM/dd/yyyy HH:mm:ss");
  const userEmail = Session.getActiveUser().getEmail();
  const brandName = formObject.newBrand;

// Add alert to check data entered is correct
  const response = ui.alert('Please confirm the following information is correct:',
                            ' :  ' + formObject.newBrand +
                            '\n:  ' + formObject.country +
                            '\n:  ' + formObject.state +
                            '\n:  ' + formObject.city +
                            '\n :  ' + formObject.businessType +
                            '\n:  ' + formObject.integration +
                            '\n :  ' + formObject.menuSource +
                            '\n     /?:  ' + formObject.disableItemOption +
                            '\n ()   ?:  ' + formObject.itemDisable +
                            '\n     /?:  ' + formObject.disableModOption +
                            '\n    ?:  ' + formObject.modDisable +
                            '\n      ?:  ' + formObject.updatePrice +
                            '\n /    ?:  ' + formObject.priceUpdate +
                            '\n      ?: ' + formObject.otherUpdates +
                            '\n   /   ?:  ' + formObject.specialInstructions
                            , ui.ButtonSet.YES_NO);

    if(response === ui.Button.YES) {
       var lock = LockService.getScriptLock();
  lock.waitLock(60000);
  try {
    const brandColumn = ss.getRange('D:D');
    const brandValues = brandColumn.getValues();
    let i = 1;
    //      Check for exisiting brand name
    for(i=1; i < brandValues.length; i++) {
        if(brandValues[i].toString().toLowerCase().trim() == brandName.toString().toLowerCase().trim() && ss.getRange(i+1,5).getValue() == 'New Brand'){
        ui.alert("Brand name already created");
        return;
        }
    };
//  Create folder and PDF with build instructions
      const parentFolder = DriveApp.getFolderById("RemovedfolderID");// how does this work with Shared drives? Create and move?
    //      const parentFolder = DriveApp.getFolderById("RemovedfolderID"); < ---- Team drive ID (notworking..)  My folder ->  RemovedfolderID

      const newFolder = parentFolder.createFolder(brandName);
      const docFile = newFolder.createFile(brandName+'.pdf',
                            ' :  ' + formObject.newBrand +
                            '\n:  ' + formObject.country +
                            '\n:  ' + formObject.state +
                            '\n:  ' + formObject.city +
                            '\n :  ' + formObject.businessType +
                            '\n:  ' + formObject.integration +
                            '\n :  ' + formObject.menuSource +
                            '\n     /?:  ' + formObject.disableItemOption +
                            '\n ()   ?:  ' + formObject.itemDisable +
                            '\n     /?:  ' + formObject.disableModOption +
                            '\n    ?:  ' + formObject.modDisable +
                            '\n      ?:  ' + formObject.updatePrice +
                            '\n /    ?:  ' + formObject.priceUpdate +
                            '\n      ?: ' + formObject.otherUpdates +
                            '\n   /   ?:  ' + formObject.specialInstructions,
                               MimeType.PDF);
      const fileURL = docFile.getUrl();

  //  add header row to spreadsheet
            //   Create Spreadsheet in Brand folder. Activity log.
      const name = brandName + " Activity Log";
      const id = newFolder.getId();
      const resource = {
        title: name,
        mimeType: MimeType.GOOGLE_SHEETS,
        parents: [{id: id}]
      };

      const fileJson = Drive.Files.insert(resource);
      const fileId = fileJson.id;

      const lastRow = ss.getLastRow();

        const newEntry = [
         lastRow,
         timestamp,
         timestamp,
         formObject.newBrand,
         'New Brand',
         formObject.businessType,
         formObject.integration,
         '=HYPERLINK("'+formObject.menuSource+'")',
         userEmail,
         fileURL,
         ,
         ,
         ,
         ,
         formObject.city,
         formObject.state,
         formObject.country,
         fileId

    ];

    const newSheet = SpreadsheetApp.openById(fileId);
    const sheetRange = newSheet.getSheetByName("Sheet1").getRange(1,1,1,18);
    const headers = [
      ['',
       '   ',
       ' ',
       ' ',
       ' ',
       ' ',
       '',
       ' ',
       ' :',
       ' ',
       ' ?',
       ' ',
       ' ',
       '    ',
       '',
       '/',
       '',
       ' ']
      ];

     sheetRange.setValues(headers);

//    Add data to last row in main tracker
      ss.appendRow(newEntry);

//  Copy data to spreadsheet brand
      const activitySheet = newSheet.getSheetByName("Sheet1")
      activitySheet.appendRow(newEntry);
//    Flush changes before releasing lock
      SpreadsheetApp.flush();
  } catch(e) {
    ui.alert("System is Busy, Please try again in a moment.");
    return
    } finally {

    lock.releaseLock();

    return
  }

  } else {
//     action to take if info is incorrect? or No is clicked
  };

};

I know that multiple triggers have been a known issue as per posts from Cooper and others here and here but I can't seem to be able to adopt them for my solution.
Thanks in advance for any ideas.

A: These are the changes I'd make to the dialog:
 <input id="btn1" type="button" value="Submit" onClick="handleNewAccountFormSubmit(this.parentNode);" />
    <input type="button" value="Cancel" onclick="google.script.host.close()">

  </form>


text:
Q: How to add span to a label using $form->labelEx from Yii? I wish to generate the following markup:
some label here (optional)

Is there a way to do this, by using Yii labelEx or just label?
Thanks

A: If the attribute is required
You can set the CHtml static properties like this
CHtml::$beforeRequiredLabel = '';
CHtml::$afterRequiredLabel = '(optional)';

Yii will generate a tag
CHtml::$beforeRequiredLabel.$label.CHtml::$afterRequiredLabel

but the static properties will effect all labels generated by $form->labelEx() (@see CHtml::activeLabelEx())
if you don't need, you must set the static properties to default
If the attribute is not required
you can set the htmlOptions
$form->labelEx($model, $attribute, array('label' => 'your label'))

A: It's simple, make use of the Decorator pattern:
<?php
// components/CustomCHtml.php

class CustomCHtml extends CHtml
{
    public static function activeLabelEx($model,$attribute,$htmlOptions=array())
    {
        if (isset($htmlOptions['optional']) && $htmlOptions['optional']) {
            if (isset($htmlOptions['label']) && $htmlOptions['label']) {
                $htmlOptions['label'] .= $htmlOptions['optional'];
            } else {
                $htmlOptions['label'] = $htmlOptions['optional'];
            }
        }

        return parent::activeLabelEx($model,$attribute,$htmlOptions);
    }
}

use case:
<?php echo CustomCHtml::activeLabelEx($model, 'field', array('optional'=>' (optional)')); ?>

A: Here is a little hack to make it possible.
<?php
                $username = $form->field($model, 'username')
                ->input('text', ['class' => 'form-control input-lg'])
                ->label(true, 'username', ['class' => 'fa fa-user signin-form-icon']);

                $username->parts['{label}'] = 'dwe';

                echo $username;
            ?>

A: You could use CHtml::$afterRequiredLabel and/or CHtml::$beforeRequiredLabel
$initValue = CHtml::$afterRequiredLabel;
CHtml::$afterRequiredLabel = $initValue.'(optional)';
echo $form->labelEx($model, $fname, array('class' => ''));
echo $form->textField($model, $fname, array('class' => ''));
CHtml::$afterRequiredLabel = $initValue;

This way the label will be applied only on the specified form field. You actually set the initial value of CHtml::$afterRequiredLabel and/or CHtml::$beforeRequiredLabel on a temp variable, you overwrite the value that you need, and then reset it to original value.


text:
Q: Frequency of occurence of character Hey Please refer to following question:
Question Link
I used the HashMap to store frequency of each character and then i stored the frequency in array and we can only remove one letter from string and check if string contains equal number of characters or not.
My code is passing all test case except the following provided in link:
Test Case Link
static String isValid(String s) {
    Map<Character,Integer> freq=new HashMap<Character,Integer>();
    List<Integer> list=new ArrayList<>();
    char[] chars=s.toCharArray();
    for(char c:chars){
        Integer i=freq.get(c);
        if(i==null){
            freq.put(c,1);
        }
        else{
            freq.put(c,i+1);
        }
    }
    for(Integer c:freq.values()){
        list.add(c);
    }
    int[] arr=new int[list.size()];
    for(int i=0;i<list.size();i++){
        arr[i]=list.get(i);
    }
    int count=0;
    int n=arr.length;
    for(int i=0;i<list.size()-1;i++){ //2 2 1 1
        if(arr[i]==arr[i+1]){}
        else{
            if(arr[i]-arr[i+1]==1 || arr[i+1]-arr[i]==1 || arr[i]-arr[i+1]==arr[i]-1 || arr[i+1]-arr[i]==arr[i+1]-1){
                arr[i+1]-=1;
                count++;
                }
            else{
                return "NO";
            }
        }
    }
    if(count==1 || count<1){
        return "YES";
    }
    else
    return "NO";
}

A: The frequency count of the file is
{p=1, a=11111, b=11111, c=11111, d=11111, e=11111, f=11111, g=11111, h=11111, i=11111}

So you need to handle the case when you only have a single character and the rest are equal.  By deleting the single character p, you get a valid solution.


text:
Q: how to read ts file and update code dynamically using fs? i am scaffolding new project using yeoman generator it is creating all the directories and running dependencies , now once files are generated i want to update js class same as appName,
first i am trying to read the ts file which i failed to do it throws error  TypeError: Cannot read property 'toString' of undefined then i would update the file with appName if there is any better approach to achieve this task i will apprecaite the help.
index.js
 updateTsFile () {
    const npmdir = `${process.cwd()}/${this.props.appName}`;
    const dirPath = `${npmdir}/${"./api.ts"}`;
    console.log("path", dirPath);
    let response;
    _fs.readFile(dirPath, (_err, res) => {
      if (_err) {
        console.error(_err);
      }

      let file = res.toString("utf-8");
      console.log(file);
      response = file;
      let lines = file.split("\n");
      for (let i = 0; i < lines.length; i++) {
        console.log(lines[i]);
      }
    });
    return response;
  }

api.ts
export class CAPIClass extends Wrapper {
    public after = after;
    constructor() {
        super({
            configFileName: "package-name-v1.json"
        });
    }
}

expected output
export class CMyAppNameClass extends Wrapper {
    public after = after;
    constructor() {
        super({
            configFileName: "package-name-v1.json"
        });
    }
}

A: In case of an error you're just logging the error but continuing with the logic. So it seems like you're running into an error resulting in res being undefined. Since fs exposes a promise-based api nowadays, I would rewrite this as follows instead of using callbacks (also note that you were using utf-8 for the encoding but it should be utf8):
async updateTsFile() {
    const npmdir = `${process.cwd()}/${this.props.appName}`;
    const dirPath = `${npmdir}/${"./api.ts"}`;
    console.log("path", dirPath);

    try {
        const fileData = await _fs.promises.readFile(dirPath);
        const fileAsStr = fileData.toString("utf8");

        // replace class-name
        fileAsStr = fileAsStr.replace(/CAPIClass/g, "CMyAppNameClass");
        // (over)write file: setting 'utf8' is not actually needed as it's the default
        await _fs.promises.writeFile(dirPath, fileAsStr, 'utf8');
    } catch (err) {
        console.log(err);
        // handle error here
    }

}


text:
Q: Decorators in python: Difference in the args interpretation in class and function based decorators I am trying to create a generic function lifecycle handler in python.
Working in brief:

*

*Logs the signature and return values.

*Handles the exception with or without retry.

*Provide cleanup in case of exception.

The issue which I encountered while doing the cleanup is as follows:
Function-based decorator:
def handler(exception=Exception,cleanup=None):
def func_wrapper(func):
    def wrapper(*args,**kwargs):
        response=None
        try:
            print(args)
            response=func(*args,**kwargs)
        except exception as ex:
            print(f'Exception occurred:{str(ex)}\nCleaning up resources')
            #Passing the object for cleanup, it fails for class based decorators as it does not passes self as argument
            cleanup(args[0])
        return response
    return wrapper
return func_wrapper

The data which is supposed to be cleaned up is stored in the class instance and is cleaned based on the method provided.
For example:

*

*Store some information using third party API.

*In case of exception, the cleanup operation passed would invoke a
delete API.
  class Test:
     def __init__(self,data):
         self.main_data=data

     @handler(exception=Exception,cleanup=lambda x:print(f"Cleaning data:{x.main_data}"))
     def test_data(self):
         print(f'Data is :{self.main_data}')
         i=1/0

Output:
Exception occurred:division by zero
Cleaning up resources
Cleaning:John Doe

I was more inclinded towards Class based decorator.
class LifeCycleHandler:
    def __init__(self,*,func=None,exception=Exception,cleanup=None):
        self.__exception=exception
        self.__cleanup=cleanup
        self.__func=func

    def __call__(self,*args,**kwargs):
        response=None
        try:
            print(args)
            response=self.__func(*args,**kwargs)
        except self.__exception as ex:
            print(f'Exception occurred:{str(ex)}\n cleaning up resources')
            #Passing the object for cleanup
            self.__cleanup(args[0])
        return response

def lifecycle_handler(exception=Exception,cleanup=None):
    def wrapper(func):
        response=LifeCycleHandler(func=func,exception=exception,cleanup=cleanup)
        return response
    return wrapper

With class based decorator with similar functionality i faced the following error:
()
Exception occurred:test_data() missing 1 required positional argument: 'self'
 cleaning up resources
Traceback (most recent call last):
  File "test.py", line 27, in __call__
    response=self.__func(*args,**kwargs)
TypeError: test_data() missing 1 required positional argument: 'self'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "test.py", line 54, in <module>
    test.test_data()
  File "test.py", line 31, in __call__
    self.__cleanup(args[0])
IndexError: tuple index out of range

Can someone guide me regarding the the argument interpretation for callable classes?

A: If my comment correct, you could add __get__ to LifeCycleHandler.
def __get__(self, obj, type=None):
    return functools.partial(self.__call__, obj)

This will make test_data become a non-data descriptor. I assume you already know descriptor. If not, it's definitely worth to check it.
Back to your question, from trace back, your assumed that python will help you pass the caller instance which is instance of Test as second argument to __call__. That's not true. However, that's true in __get__.
Your core logic (try/except block) needs are:

*

*instance of Test, because you need access to main_data.

*instance of LifeCycleHandler in, because you need access to your self.__func.

*args in which isn't acceptable in __get__, but you could have them in __call__.

For example, you have test code below:
t = Test(123)
t.test_data()

t.test_data will invoke __get__. In its arguments, self is an instance of LifeCycleHandler and obj is t (instance of Test). __get__ returned a callable function(__call__) in which its first argument is partially feed by obj.


text:
Q: How to structure a project that dynamically calls a method of subclasses in Python Say I have a base class with a method such as render().
I have ~20 subclasses which inherit this base class and redefine the render() method. At the moment they are alllocated in a package in my project, with each defined in a seperate file. e.g.
__main__.py
baseclass.py -> BaseClass
myclasses
 | subclass1.py -> SubClass1(BaseClass)
 | subclass2.py -> SubClass2(BaseClass)
 | subclass3.py -> SubClass3(BaseClass)
 | ...etc

In my main program, I want to dynamically create instances of these subclasses and call the render() method on them. What is the most pythonic way to do this? Every implementation I've tried seems hacky - I've tried using wildcards and __subclasses__() but this doesn't play well with my linter/type checking. But also, I don't want 20 explicit imports at the top of my file (plus, my linter doesn't like this either).
Am I using the wrong data/file structure here? Is there a smart way to do this I am missing?

A: This is an extension of a technique I've only used once. It's outside my area of expertise so there is room for improvement.
class Base(type):
    subclasses = []

    def __init__(cls, name, bases, namespace):
        super().__init__(name, bases, namespace)
        cls.subclasses.append(cls)

class Child1(metaclass=Base):
    def __init__(self, ver):
        self.ver = ver
    def render(self):
        print(f'{self.ver} render Child1')

class Child2(metaclass=Base):
    def __init__(self, ver):
        self.ver = ver
    def render(self):
        print(f'{self.ver} render Child2')

def main():
    for sub in Base.subclasses:         # iterate the classes
        subs.append(sub(0))             # create a new instance
        subs.append(sub(1))             # create another to prove class property
    """Iterate the classes calling render() on each one."""
    for sub in subs:
        sub.render()

if __name__ == "__main__":
    main()

Output
0 render Child1
1 render Child1
0 render Child2
1 render Child2


text:
Q: Perform Load Testing in Insomnia Can I have some guidance on how to perform load testing by sending multiple POST API calls within a stipulated time frame n Insomnia.
To achieve this, I have to POST the API calls in a for loop going from 0 to 500 in a span of 5 sec.
What can I do to implement this ?

A: Hold CTRL and click the Send button - then select Repeat on Interval and type in the interval you need (I tested with 0.2 sec intervals so you can go pretty low if needed)


text:
Q: Set the path to the global configuration file in cordova? I'm trying to run my cordova project.
What do I really want?
I want to set the path to the config.xml via command prompt.
I tried to do smth like this:
$ cordova run ios --target='iPhone-6' --buildConfig=./app/config.dist.xml
but it says me that
Error: Current working directory is not a Cordova-based project.
If I create config.xml in current working directory and run the project without any arguments everything is fine.
So, is it possible to have config file in another folder?

A: As per the official Cordova documentation, config.xml can either exist in project root folder or project_ root/www folder.
Also the naming convention of the file should be config.xml in order to build the same using  Cordova CLI as far as I know. Moreover, cordova create command sets up the basic project structure for you including config.xml. Its advisable to stick to this structure rather than customizing the locations to avoid errors.


text:
Q: Bootstrap carousel slides out of order Strange problem here, and I can't find anyone else who's encountered it.
My carousel runs fine in Chrome, Safari and Firefox (mac and pc) but in IE7 and 8, the slides appear completely out of order after the first slide appears on page load. The first slide is always correct. If I start using the previous/next buttons, they will cycle through in the correct order.
BUT, I've had 2 other people test in Chrome, FF and Safari, and they are sometimes out of order.
bootstrap-carousel.js is untouched from the original (freshly downloaded).
I do have some custom js going on for some other carousels on my site that use pagination. this one doesn't use it though. The custom code does not refer to the div id of the problem carousel. However when I remove the link on the page to the custom js, the problem goes away, so obviously it's related but I can't figure out why.
Here is the HTML:

        ‹
        ›

here is the custom js that the other carousels use for pagination:
$(document).ready(
function() {
    $('#myCarousel2, #myCarousel3').each(
        function() {
            var html = '

';

            for(var i = 0; i < $(this).find('.item').size(); i ++) {
                html += '
 '  + $(item).attr('data-title') + '
';
            }

            html += '

';
            $(this).after(html);
            $('.carousel-control.left[href="#' + $(this).attr('id') + '"]').hide();
        }
    ).bind('slid',
        function(e) {
            var nav = $('.carousel-nav[data-target="' + $(this).attr('id') + '"] ul');
            var index = $(this).find('.item.active').index();
            var item = nav.find('li').get(index);

            nav.find('li a.active').removeClass('active');
            $(item).find('a').addClass('active');

            if(index == 0) {
                $('.carousel-control.left[href="#' + $(this).attr('id') + '"]').fadeOut();
            } else {
                $('.carousel-control.left[href="#' + $(this).attr('id') + '"]').fadeIn();
            }

            if(index == nav.find('li').size() - 1) {
                $('.carousel-control.right[href="#' + $(this).attr('id') + '"]').fadeOut();
            } else {
                $('.carousel-control.right[href="#' + $(this).attr('id') + '"]').fadeIn();
            }
        }
    );

    $('.carousel-nav a').bind('click',
        function(e) {
            var index = $(this).parent().index();
            var carousel = $('#' + $(this).closest('.carousel-nav').attr('data-target'));

            carousel.carousel(index);
            e.preventDefault();
        }
    );

    $('.carousel').carousel('cycle'); // Start the animation automatically
}

);
Any ideas? Thanks guys.


text:
Q: Best approach for data conversion/mapping The task is to map the fields from one data set to another, some fields require some additional parsing/computation.
(I'm using only a few fields in the examples provided below but there is much more in the original data sets).
Approach 1:
Initially I though to use dict for field mappings and just assign functions to keys that require additional data manipulation:
import base64
import hashlib
import json

from datetime import datetime

def str2base64(event):
    md5 = hashlib.md5(event['id'].encode())
    return base64.b64encode(md5.digest())

def ts2iso(event):
    dt = datetime.fromtimestamp(event['timestamp'])
    return dt.isoformat()

MAPPINGS = {
    'id': id2hash,
    'region': 'site',
    'target': 'host',
    'since': ts2iso
}

def parser(event):
    new = dict()
    for k, v in MAPPINGS.items():
        if callable(v):
            value = v(event)
        else:
            value = event.get(v)
        new[k] = value
    return new

def main():
    for event in events:  # dicts
        event = parser(event)
        print(json.dumps(event, indent=2))

if __name__ == '__main__':
    main()

I don't like the fact that I have to add all parsing function at the top so the MAPPING dict can see it and I'm not sure if that's the best approach? Besides I don't see an easy way to pass default value to dict.get in parser function.
Approach 2 (OOP):
import base64
import hashlib
import json

from datetime import datetime

class Event(object):
    def __init__(self, event):
        self.event = event

    @property
    def id(self):
        md5 = hashlib.md5(self.event['id'].encode())
        return base64.b64encode(md5.digest())

    @property
    def region(self):
        return self.event['site']

    @property
    def target(self):
        return self.event['host']

    @property
    def since(self):
        dt = datetime.fromtimestamp(self.event['timestamp'])
        return dt.isoformat()

    def data(self):
        return {
            attr: getattr(self, attr)
            for attr in dir(self)
            if not attr.startswith('__') and attr not in ['event', 'data']
        }

def main():
    for event in events:  # dicts
        event = Event(event).data()
        print(json.dumps(event, indent=2))

if __name__ == '__main__':
    main()

I'm sure there is a better way to get all properties (property methods only) to avoid this ugly data method? I would like to also avoid adding prefix to relevant methods so I could then filter them with str.startswith or something similar.
What would be the best approach for this task? I was also looking at @functools.singledispatch from functools but I think it won't be helpful in this case.

A: I think that your first approach makes a lot of sense and, if that is important to you, will perform much better than the OO approach. In case you need to process large numbers of events, converting a dict to an object will certainly be quite CPU intensive. I find it also very explicit and clear.
In the OO approach you would convert from dict to object for nothing. There is no benefit of having an object, because all you do later on is converting it to JSON (which you can't do with a custom class unless you write your JSON encoder).
That's why my choice would be option number one, which I would modify slightly like this:
class SimpleConverter:

    def __init__(self, key, default=None):
        self.key = key
        self.default = default

    def __call__(self, event):
        return event.get(self.key, self.default)

class TimestampToISO:

    def __init__(self, key):
        self.key = key

    def __call__(self, event):
        dt = datetime.fromtimestamp(event[self.key])
        return dt.isoformat()

class StringToBase64:

    def __init__(self, key):
        self.key = key

    def __call__(self, event):
        md5 = hashlib.md5(event[self.key].encode())
        return base64.b64encode(md5.digest()).decode()  ## Without .decode() for Python2

def transform_event(event, mapping):
    return {key: convert(event) for key, convert in mapping.items()}

def main(events, mapping):
    for event in events:  # dicts
        event = transform_event(event, mapping)
        print(json.dumps(event, indent=2))

if __name__ == '__main__':
    mapping = {
        'id': StringToBase64("id"),
        'region': SimpleConverter("site"),
        'target': SimpleConverter("region"),
        'with_default': SimpleConverter("missing_key", "Not missing!"),
        'since': TimestampToISO("timestamp"),
    }
    events = [
        {
            'id': 'test',
            'site': 'X',
            'host': 'Y',
            'timestamp': 1582408754.5111449,
        }
    ]
    main(events, mapping)

Which outputs this:
{
  "id": "CY9rzUYh03PK3k6DJie09g==",
  "region": "X",
  "target": null,
  "with_default": "Not missing!",
  "since": "2020-02-22T22:59:14.511145"
}

Notice how with this solution you can reuse all the converter classes for different event keys, which was not possible with pure functions.

A: That's a pretty cool problem you got here, however I feel the solutions are all a bit too code heavy:
MAPPINGS = {
    'id': id2hash,
    'region': ('site', 'default_region'),
    'target': ('host', 'default_target'),
    'since': ts2iso
}
# Unpack tuple if action is not callable. Equivalent to event.get(action[0], action[1])
mapped_event = [
    {key: action(event) if callable(action) else event.get(*action)
    for key, action in mapping} for event in events]

This solution does exactly what your first approach was but in a lot less lines. I agree this is fairly unreadable, so feel free to reuse only the parts you want (maybe have the dict comprehension in a separate function and call that in the list comp).
If what you wanted to express in your mapping for keys like 'target': 'host' is: event.get('target', 'host'), then the comprehension becomes:
mapped_event = [
    {key: action(event) if callable(action) else event.get(key, action)
    for key, action in mapping} for event in events]

A: I like the answer from @matino but here're a few related points that I would like to make:

I think that your first approach makes a lot of sense and, if that is
  important to you, will perform much better than the OO approach. In
  case you need to process large numbers of events, converting a dict to
  an object will certainly be quite CPU intensive.

Your solution is also using objects and actually a few for a single event?!

In the OO approach you would convert from dict to object for nothing.
  There is no benefit of having an object, because all you do later on
  is converting it to JSON (which you can't do with a custom class
  unless you write your JSON encoder).

Again your solution is also creating (many) objects and because some fields will default to None or True/False, we actually create an object(s) just to get a value from dict:
mapping = {
    ...
    'example': SimpleConverter(None, True),
    ...
}

In order to make this work with booleans I had to modify the transform_event function like this:
def transform_event(event, mapping):
    new = dict()
    for key, value in mapping.items():
        if callable(value):
            value = value(event)
        new[key] = value
    return new

Field example:
mapping = {
    ...
    'example': True,
    ...
}

So, now we have a mapping dict, function to convert the fields and a few classes for each conversion...
While looking into your solution I decided to improve the Event class. I made it iterable so it's easy to convert it to dict, json etc.:
class Event(object):
    __slots__ = ('event', 'fields')

    def __init__(self, event):
        self.event = event
        self.fields = [
            'id',
            'region',
            'target',
            'since',
        ]

    def __iter__(self):
        return (self._get(f) for f in self.fields)

    @property
    def id(self):
        md5 = hashlib.md5(self.event['id'].encode())
        return base64.b64encode(md5.digest())

    @property
    def region(self):
        return self.event['site']

    @property
    def target(self):
        return self.event['host']

    @property
    def since(self):
        dt = datetime.fromtimestamp(self.event['timestamp'])
        return dt.isoformat()

    def _get(self, field):
        try:
            return getattr(self, field)
        except AttributeError:
            return self.event.get(field)

    def asdict(self):
        return dict(zip(self.fields, self))

So we keep all data in a single object that should be easily extensible, we have immutable attributes (properties) etc.


text:
Q: Remove id attribute from stylesheet link Right now I'm serving up my own custom stylesheet.
// register main stylesheet
wp_register_style( 'custom-stylesheet', get_stylesheet_directory_uri() . '/library/css/main.css', array(), '', 'all' );

It outputs:
<link rel='stylesheet' id='custom-stylesheet-css'  href='http://localhost/wp-content/themes/custom-theme/library/css/main.css' type='text/css' media='all' />

Is there a way to remove the id='custom-stylesheet-css part of that stylesheet?? Is there a reason that they add an id attribute?

A: You can filter style_loader_tag. You get the HTML element and the handle as arguments.
Example
add_filter( 'style_loader_tag', function( $html, $handle ) {

    if ( 'custom-stylesheet' !== $handle )
        return $html;

    return str_replace( " id='$handle-css'", '', $html );
}, 10, 2 );

But really, I would not waste processing time for that. The id exists to make the element easier to access per JavaScript. It doesn't hurt if you don't need it.

A: Try this in your functions.php:
add_filter("style_loader_tag", function($tag){
    return str_replace("id='custom-stylesheet-css' " ,'',  $tag);
});

Nice and simple.


text:
Q: How do I run a command as root? I've downloaded a driver for a video card (*.run) and tried to install within a terminal. When I started the installation process I got this error: ERROR: nvidia-installer must be run as root. I'm logged in with my own profile.

A: If you have an administrator account, simply
sudo command

runs commands as root after asking your password (for safety).
If your account is not an administrator account, you can't :-).
Notice: in a standard Ubuntu installation, the user you set up in the installation process is an administrator account. Guest account is not. Other users, depends on how you create them.
Notice too: "administrator" account in this context mean an account which has the privilege to become root. There is a lot more info in https://help.ubuntu.com/community/RootSudo and in https://help.ubuntu.com/community/Sudoers. I am using the simple "administrator account here" because it's how it's called in the graphic interface to create a new user:


text:
Q: PHP redirect for www to non-www with 301 on IIS I'd like to get this straighten out once and for all:
<?php if ($_SERVER['HTTP_HOST'] != 'domain.com'){
header("Location: http://domain.com"
.$_SERVER['REQUEST_URI']);
} ?>

This will send all traffic to the NON-WWW version.
My question is - can I add 'header('HTTP/1.1 301 Moved Permanently');' safely without messing everything up?
I'm using IIS server so .htaccess is no good and all pages are coded in PHP - all solutions welcome.

A: Of course you can. Take advantage of all the parameters offered by header():
<?php

if ($_SERVER['HTTP_HOST'] != 'domain.com'){
    header("HTTP/1.1 301 Moved Permanently", true, 301);
    header("Location: http://domain.com".$_SERVER['REQUEST_URI']);
}

The last parameter is forcing the response code to be 301, as you want.

A: Of course you can, it will not mess up anything! But it must be in the if clause behind the header location line:
<?php
if ($_SERVER['HTTP_HOST'] != 'domain.com'){
    header('HTTP/1.1 301 Moved Permanently');
    header("Location: http://domain.com".$_SERVER['REQUEST_URI']);
}
?>

But better if you use URL Rewrite (aka "IIS mod_rewrite"): http://www.iis.net/downloads/microsoft/url-rewrite Or some other redirect not in your php code.


text:
Q: NoMethodError: undefined method `arel_table' for "User":String Rails 4.2
g.user_curator
NoMethodError: undefined method `arel_table' for "User":String

My Tables:
create_table "groups", force: :cascade do |t|
    t.string   "name",            limit: 255, default: "", null: false
    t.integer  "user_curator_id", limit: 4
    t.integer  "user_leader_id",  limit: 4
    t.datetime "created_at",                               null: false
    t.datetime "updated_at",                               null: false
 end

create_table "users", force: :cascade do |t|
    t.string   "email",                  limit: 255, default: "", null: false
    t.string   "encrypted_password",     limit: 255, default: "", null: false
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "access_level",           limit: 4,   default: 0
    t.string   "first_name",             limit: 255
    t.string   "last_name",              limit: 255
    t.string   "middle_name",            limit: 255
  end

My Models:
class User < ActiveRecord::Base
  has_one :user_curator, :class_name => 'Group'
end

class Group < ActiveRecord::Base
  belongs_to :user_curator, :class => 'User', foreign_key: "user_curator_id"
end

Help the correct set associations for tables. In the group to be curator and leader (Table Users)

A: class Group < ActiveRecord::Base
  belongs_to :curator, class_name: 'User', foreign_key: 'user_curator_id'
end

class User < ActiveRecord::Base
  has_one :group, foreign_key: 'user_curator_id'
end

This Will Work


text:
Q: Swap two elements in a list in a recursive manner I have a function which takes a list as an argument, and I have to swap two precise elements of the list. My call is of the form
f[h1_,{n1___}] :=

I need that under a certain test which will be an a If statement, two precise elements of n1 are switched.
I may therefore need a Module to store the intermediate list and call my function f with the new list. I checked Swapping elements of list and Swap elements in list without copy but in both those questions, the proposed function never return the desired list but just modify the actual list.
f[h1_,{n1___}] = If[test=True,f[h1,{swappedN1}],ElseStatement]

I therefore need a function that makes
swap[{1,2,3,4},1,2] -> {2,1,3,4}

such that I can do something like
 f[h1_,{n1___}] = If[test=True,f[h1,swap[{n1},pos1,pos2],ElseStatement]

Is that possible in Mathematica ?

A: Just use a temporary variable:
swap[a_List, p_, q_] := Module[{aa = a}, aa[[{p, q}]] = aa[[{q, p}]]; aa]

swap[{1, 2, 3, 4}, 1, 2]

{2, 1, 3, 4}

Actually I just remembered there is a built-in for this: Permute with Cycles
Permute[{1, 2, 3, 4}, Cycles[{{1, 2}}]]

{2, 1, 3, 4}

Also ReplacePart is rather clean:
swap[a_, p_Integer, q_Integer] := ReplacePart[a, {p -> a[[q]], q -> a[[p]]}]


text:
Q: Adding Data to DB using PHP Form ERROR im having an column error, but i cant seem to find the problem. Im trying to add patient detials to a table called "Patient". And i get the following error:

Could not enter data: Column count doesn't match value count at row 1

Can anyone help as to why?
PHP Code:
 <?php
     if(isset($_POST['add'])) {
        $dbhost = 'localhost';
        $dbuser = 'carl';
        $dbpass = 'password';

        $conn = mysql_connect($dbhost, $dbuser, $dbpass);

        if(! $conn ) {
           die('Could not connect: ' . mysql_error());
        }

            $PatientName = $_POST['PatientName'];
            $IDNumber = $_POST['IDNumber'];
            $Gender = $_POST['Gender'];
            $Address = $_POST['Address'];
            $LandlineTel = $_POST['LandlineTel'];
            $MobileTel = $_POST['MobileTel'];
            $DOB = $_POST['DOB'];
            $Conditions = $_POST['Conditions'];
            $NextOfKin = $_POST['NextOfKin'];
            $ClinicNo = $_POST['ClinicNo'];
            $Appointments = $_POST['Appointments'];

        $sql = "INSERT INTO Patient ". "(PatientName,IDNumber, Gender, Address, LandlineTel, MobileTel, DOB, Conditions, NextOfKin, ClientNo, Appointments) ". "VALUES('$PatientName','$IDNumber', $Gender, $Address, $LandlineTel, $MobileTel, $DOB, $Conditions, $NextOfKin, $ClinicNo, $Appointments, NOW())";

        mysql_select_db('MedicalDB');
        $retval = mysql_query( $sql, $conn );

        if(! $retval ) {
           die('Could not enter data: ' . mysql_error());
        }

        echo "Entered data successfully\n";

        mysql_close($conn);
     }else {
        ?>

HTML Form Code:
<form method = "post" action = "<?php $_PHP_SELF ?>">

                    Employee Name
                    <input name = "PatientName" type = "text"
                       id = "PatientName">

                    ID Number
                    <input name = "IDNumber" type = "text"
                       id = "IDNumber">

                    Gender
                    <input name = "Gender" type = "text"
                       id = "Gender">

                    Address
                    <input name = "Address" type = "text"
                       id = "Address">

                    LandlineTel
                    <input name = "LandlineTel" type = "text"
                       id = "LandlineTel">

                    MobileTel
                    <input name = "MobileTel" type = "text"
                       id = "MobileTel">

                    DOB
                    <input name = "DOB" type = "text"
                       id = "DOB">

                    Conditions
                    <input name = "Conditions" type = "text"
                       id = "Conditions">

                    Next Of Kin
                    <input name = "NextOfKin" type = "text"
                       id = "NextOfKin">

                    Clinic Number
                    <input name = "ClinicNo" type = "text"
                       id = "ClinicNo">

                    Appointments
                    <input name = "Appointments" type = "text"
                       id = "Appointments">

                       <input name = "add" type = "submit" id = "add"
                          value = "Add Employee">

           </form>

A: Your query doesn't specify what column you're trying to insert the value of NOW() into.  You have 11 columns and 12 values.


text:
Q: Hot deployment not working I am using Liferay Portal 6.1 CE.
I have setup the developement environment  in eclipse indigo.
When i deploy a portlet ,it moves to the deploy folder inside the Portal Bundle.But didn't  get deployed.
I have already tested with the other War,placed in deploy folder.but same happens
Hot deployment is not working.
What i can do?Help me

A: It might be that you moved an installation and your current settings include a liferay.home that is different from what you expect.
At startup of Liferay, the log states what auto-deploy directory Liferay monitors. Look for a line in tomcat/logs/catalina.out that looks like this:
08:34:58,902 INFO  [pool-2-thread-1][ServerDetector:154] Server supports hot deploy
08:34:58,910 INFO  [pool-2-thread-1][PluginPackageUtil:1030] Reading plugin package for the root context
08:35:01,137 INFO  [pool-2-thread-1][AutoDeployDir:106] Auto deploy scanner started for /opt/lds/lds161/liferay-portal-6.1.20-ee-ga2/deploy

Also, whatever user Tomcat/Liferay runs as, needs to have read/write access to this directory as well as to tomcat's webapps directory in order for hot-deploy to work. Plugins will not be deployed if they can't be removed from the auto-deploy folder.
Commonly, you'll find a liferay.home setting in portal-setup-wizard.properties (this is the default parent directory of the deploy directory), but this setting might also have been transitioned into your database (in case you're wondering why changes to this value won't be picked up.

A: There are 2 questions I could see in your post.
1. Hot deployment is not working
Make sure you have specified the hot deployment folder in portal-ext.properties file.
auto.deploy.deploy.dir=/app/portal/liferay-portal-6/deploy
You can then deploy your war files in /app/portal/liferay-portal-6/deploy folder.
Liferay picks that up and puts that in /app/portal/liferay-portal-6/../server/default/deploy folder.
More details could be found here.
2. it moves to the deploy folder inside the Portal Bundle.But didn't get deployed
Do you see any exceptions in your logs? Doesn't it say 1 Portlet available for use?

A: check auto deploy path in server config.

A: You need to add following entries in build.(user_name).properties in your plugin sdk. If you didn't find this file, you need to create it. set you directories like

app.server.parent.dir=D:\Projects\Site\liferay-portal-6.2.0-ce-ga1
app.server.portal.dir = D:\Projects\Site\liferay-portal-6.2.0-ce-ga1\tomcat-7.0.42\webapps\ROOT
app.server.lib.global.dir = D:\Projects\Site\liferay-portal-6.2.0-ce-ga1\tomcat-7.0.42\lib\ext
app.server.deploy.dir = D:\Projects\Site\liferay-portal-6.2.0-ce-ga1\tomcat-7.0.42\webapps
app.server.type = tomcat
app.server.dir = D:\Projects\Site\liferay-portal-6.2.0-ce-ga1\tomcat-7.0.42

Hope this will help you.