set d=%date:~-4,4%-%date:~-10,2%-%date:~7,2% d: cd work mkdir %d% cd %d% explorer d:\work\%d%
Monday
automatically create a folder with today's date
Tuesday
run python script as ubuntu service
[Unit] Description=archivebot [Service] ExecStart=/bin/bash -c "cd /home/al/slack-archive-bot;export SLACK_API_TOKEN=TOKEN_HERE && python archivebot.py" [Install] WantedBy=multi-user.target
Step 1: I created this file (note location) which essentially fires a bash process with an extended argument. You could fire your own command which could be different from bash.
[root@y500-fedora ~]# cat /etc/systemd/system/foo.service [Unit] Description=foo [Service] ExecStart=/bin/bash -c "while true; do /bin/inotifywait -qq --event close_write /sys/class/backlight/acpi_video0/brightness; su myusername -c '/bin/xbacklight -display :0 -set $(cat /sys/class/backlight/acpi_video0/brightness)'; done" [Install] WantedBy=multi-user.target
Step 2:
Reload systemd:
systemctl daemon-reload
Start the new service:
systemctl enable foo
(similarly you can disable it)
(optional) Step 3: It should start automatically at next reboot into multi-user mode (run level 3) but if you want to start it right away:
systemctl start foo
systemctl status foo # optional, just to verify
Update: For completeness, I should add that ubuntu bionic seems to have a very thorough man page. RTFM here
Monday
Study path for artificial intelligence and Machine learning:
Andrew Ng's lecture series on AI
Andrew Ng's lecture at the Stanford Business School
Andrew Ng - The State of Artificial Intelligence
Andrew Ng is a visiting professor at Stanford, founder of Coursera and currently the head of research at Alibaba. The above videos should give you all the basics you need about AI.
Below schema from this article
I like this map below - because there are a lot of areas and directions in learning AI it shows it as subway map: AI study map
powershell sitecore remove item from pipe separated list
[string]$test ="{uka}|{taka}|{4aka}|{boom}" function RemovePipeElement { param ( [string]$body, [string]$elem ) [string]$res=$body; [int]$a=$body.IndexOf($elem) if ($a -gt -1) { [string]$newbod=""; [bool] $first=$TRUE; $arr=$body.split("|"); foreach ($e in $arr) { if ($e -ne $elem ) { if ($first){ [string]$newbod=$e; $first=$FALSE; }else{ [string]$newbod=$newbod+"|"+$e; } } } $res=$newbod; } return $res; } Write-Host "$test" [string]$uid=RemovePipeElement $test "{uka}"; Write-Host "$uid" [string]$uid=RemovePipeElement $test "{4aka}"; Write-Host "$uid" [string]$uid=RemovePipeElement $test "{boom}"; Write-Host "$uid" [string]$uid=RemovePipeElement $test "{taka}"; Write-Host "$uid"
Tuesday
change exe or dll file description
set VERSION="1.2.3.4 (%date%)" set FILEDESCR=/s desc "sample foodll description" set BUILDINFO=/s pb "Built by %USERNAME%" set COMPINFO=/s company "sample company" /s (c) "(c) Sample copyleft 2009" set PRODINFO=/s product "sample product" /pv "1.0.22.33" verpatch /va foodll.dll %VERSION% %FILEDESCR% %COMPINFO% %PRODINFO% %BUILDINFO%
Monday
powershell search string
cd c:\inetpub\Data\logs Get-ChildItem -Recurse *.* | Select-String -Pattern "my search string" | Select-Object -Unique Path
Wednesday
startup podcast shows list
- The Art of Product
- Build Your SaaS
- Bootstrapped Web
- Founder’s Journey
- Hooked on Product
- RogueStartups
- The Tropical MBA
- Indie Hackers
- ZenFounder
- This Week in Startups
- Startup
- Akimbo
- Stacking Benjamins
- Money For The Rest Of Us
- Planet Money
- Reply All
- Daily Tech Headlines
- Current Geek
- 99% Invisible
- System Mastery
Friday
Tuesday
sitecore upload image programmatically to media library
using MyCorp.MyLib.Entities.WebService; using Sitecore.Configuration; using Sitecore.Resources.Media; using Sitecore.SecurityModel; using Sitecore.Services.Infrastructure.Web.Http; using System; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Web; using System.Web.Http; namespace MyCorp.MyLib.Feature.EmailService { [OverrideExceptionFilters] public class ImageServiceController : ServicesApiController { /// <summary> /// Save stream as file into sitecore /// </summary> /// <param name="stream"></param> /// <param name="req"></param> private void SaveFileIntoSitecore(Stream stream, ImageRequest req ) { var mediaCreator = new MediaCreator(); var options = new MediaCreatorOptions { AlternateText = req.AltText, OverwriteExisting = true, FileBased = false, Versioned = false, IncludeExtensionInItemName = false, Database = Factory.GetDatabase("master"),//web? Destination = req.DestinationName ///logo.jpg }; using (var memoryStream = new MemoryStream()) { stream.CopyTo(memoryStream); using (new SecurityDisabler()) mediaCreator.CreateFromStream(memoryStream, req.DestinationName, options); } } [HttpPost, OverrideExceptionFilters] public async Task<HttpResponseMessage> Upload() { if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } string root = HttpContext.Current.Server.MapPath("~/App_Data"); var provider = new MultipartFormDataStreamProvider(root); try { // Read the form data and return an async data. var result = await Request.Content.ReadAsMultipartAsync(provider); ImageRequest req = new ImageRequest(); // This illustrates how to get the form data. foreach (var key in provider.FormData.AllKeys) { foreach (var val in provider.FormData.GetValues(key)) { // return multiple value from FormData if (key == "DestinationName") { req.DestinationName = val; } else if (key == "DestinationFolder") { req.DestinationFolder = val; } } } if (result.FileData.Any()) { // This illustrates how to get the file names for uploaded files. foreach (var file in result.FileData) { FileInfo fileInfo = new FileInfo(file.LocalFileName); if (fileInfo.Exists) { //Save every file to sitecore var s = fileInfo.OpenRead(); SaveFileIntoSitecore(s, req); } } } HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, req); return response; } catch (System.Exception e) { return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e); } } } }
Monday
javascript next month date formatting coupon source code
function NextMonth1() { var now = new Date(); if (now.getMonth() == 11) { return new Date(now.getFullYear() + 1, 0, 1); } else { return new Date(now.getFullYear(), now.getMonth() + 1, 1); } } function formatDate(date) { var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; var day = date.getDate(); var monthIndex = date.getMonth(); var year = date.getFullYear(); return day + ' ' + monthNames[monthIndex] + ' ' + year; } var div = document.getElementById('couponText'); div.innerHTML += "Effective till " + formatDate(NextMonth1());
Wednesday
c# return zip stream from api
public Stream GetDataFile(string locationId)
{
int cid;
DateTime tran = DateTime.Now.Date;
Check(string.IsNullOrWhiteSpace(locationId), "locationId field is missing.");
Check(!int.TryParse(locationId, out cid), "locationId must be numeric.");
DataFileRepository repository = new DataFileRepository();
/*returning stream*/
var resp = WebOperationContext.Current.OutgoingResponse;
resp.ContentType = "application/octet-stream";
resp.Headers.Add("Content-Disposition", "attachment; filename=\"myfile.zip\"");
return ZipStream(repository.GetCSVStream(cid));
}
/// <summary>
/// Check condition and generate exception if condition met.
/// </summary>
/// <param name="condition"></param>
/// <param name="exp"></param>
public void Check(bool condition, string exp)
{
if (condition)
{
AssertionException up = new AssertionException(exp);
throw up;
}
}
/// <summary>
/// Method for zipping streams
/// </summary>
/// <param name="stream"></param>
/// <returns></returns>
public Stream ZipStream(Stream stream)
{
stream.Position = 0;
var ar = new ZipArchive();
ar.AddItem("myfile.csv", stream, true, FileAttributes.Normal);
var zip = new TempFileStream();
ar.Save(zip, false);
zip.Position = 0;
return zip;
}
[OperationContract]
[WebGet(UriTemplate = "menu/datafile/{locationId}")]
Stream GetDataFile(string locationId);
IDataReader into csv
/// <summary>
/// Method for converting reader into CSV
/// </summary>
/// <param name="dataReader"></param>
/// <param name="includeHeaderAsFirstRow"></param>
/// <param name="separator"></param>
/// <returns></returns>
public Stream ToCSV(IDataReader dataReader, bool includeHeaderAsFirstRow, string separator)
{
Stream csv = new TempFileStream();
StreamWriter csvRows = new StreamWriter(csv);
StringBuilder sb = null;
if (includeHeaderAsFirstRow)
{
sb = new StringBuilder();
for (int index = 0; index < dataReader.FieldCount; index++)
{
if (dataReader.GetName(index) != null)
sb.Append(dataReader.GetName(index));
if (index < dataReader.FieldCount - 1)
sb.Append(separator);
}
csvRows.WriteLine(sb.ToString());
}
while (dataReader.Read())
{
sb = new StringBuilder();
for (int index = 0; index < dataReader.FieldCount - 1; index++)
{
if (!dataReader.IsDBNull(index))
{
string value = dataReader.GetValue(index).ToString();
if (dataReader.GetFieldType(index) == typeof(String))
{
//If double quotes are used in value, ensure each are replaced but 2.
if (value.IndexOf("\"") >= 0)
value = value.Replace("\"", "\"\"");
//If separtor are is in value, ensure it is put in double quotes.
if (value.IndexOf(separator) >= 0)
value = "\"" + value + "\"";
}
sb.Append(value);
}
if (index < dataReader.FieldCount - 1)
sb.Append(separator);
}
if (!dataReader.IsDBNull(dataReader.FieldCount - 1))
sb.Append(dataReader.GetValue(dataReader.FieldCount - 1).ToString().Replace(separator, " "));
csvRows.WriteLine(sb.ToString());
}
csvRows.Flush();
dataReader.Close();
return csv;
}
Monday
register dlls into GAC on server 2012
# adds all dll files from folders into GAC # **** Attention *** in case of permission/signature error Execute this command from powershell to allow run powershell files : Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass # load System.EnterpriseServices assembly [Reflection.Assembly]::LoadWithPartialName("System.EnterpriseServices") > $null # create an instance of publish class [System.EnterpriseServices.Internal.Publish] $publish = new-object System.EnterpriseServices.Internal.Publish Get-ChildItem "C:\Program Files (x86)\Microsoft Enterprise Library 5.0\Bin" -Filter *.dll | Foreach-Object { $content = $_.FullName Write-Output "registering "+$content; $publish.GacInstall($content) }
Wednesday
add xml to xmldocument
static string module = @" <Module> <CustomerSortOrder>60</CustomerSortOrder> <LinkText_Customer>{0}</LinkText_Customer> <LocationId>4291</LocationId> <LocationModuleId>26544</LocationModuleId> <ModuleId>30</ModuleId> <ModuleName>Menu</ModuleName> <NavigateUrl>menu.aspx</NavigateUrl> <pageId>20</pageId> <IsModuleGroup>1</IsModuleGroup> <sort_order>1</sort_order> <MenuId>{1}</MenuId> </Module> "; public string AddWeekMenu(string xml2015, string xml2010) { string result = xml2015; try { XmlDocument x2015 = new XmlDocument(); x2015.LoadXml(xml2015); //step 1 find menu tag group var menutag = x2015.SelectSingleNode("//Group[Group_Name='Menu']"); //remove Menu text from second list menutag.ChildNodes[0].SelectSingleNode("//LinkText_Customer").InnerText = ""; XmlDocument x2010 = new XmlDocument(); x2010.LoadXml(xml2010); XmlNodeList m2010 = x2010.SelectNodes("//ChildNavigation[moduleid=30]"); foreach (XmlNode item in m2010) { //append menu links from 2010 AppendMenuLink(x2015, menutag, item.SelectSingleNode("ChildLinkText").InnerText, item.SelectSingleNode("ChildLinkCustomPageID").InnerText); } //updting menu tag with correct count menutag.SelectSingleNode("//numModules").InnerText = ""+m2010.Count; return x2015.OuterXml; } catch (Exception ex) { LogException(ex); } return result; }
Tuesday
handlebars.js subtemplate example
step1.create subtemplate <script id="nutri" type="text/x-handlebars"> <p> This is subtemplate in Handelbars </p> </script> step2.register it in javascript <script type="text/javascript"> Handlebars.registerPartial('nutri', $('#nutri').html()); </script> step3. use it into another subtemplate <script id="package-list-bottom" type="text/x-handlebars-template"> <div class='po-qty form-el bottom'> <p> {{> nutri}} </p> </div> </script>
why my app is not popular on appstore?
You finished app uploaded it on appstore and .... nothing happens. You probably was expecting skyrocketing installs and in-app sales but after days,weeks you got some 10,20 installs. And you thinking what is wrong with my app.
The best way to look at this situation is to look at app like art-artifact. Let's say when you have painting picture or sculpture you are not expecting it to look like Rembrant's or Michelangelo's aren't you ? So why it is different in regards of apps ?
Probably because at first look all applications are looking alike and have unified interface and same buttons and UI elements. But the most important things are in details, in iterations between application and user.
The best way to handle this situation is to continue perfecting and creating more apps and make them looks closer to perfect apps every day and learn. As Michelangelo said : "I am still learning."
Monday
c# custom webservice logging and error handling
//step1.declare delagate public delegate T UnSafeProcedure<T>(); /*step2. add performance and error handling methods */ public string Concat(params object[] arguments) { StringBuilder sb = new StringBuilder(); foreach (var item in arguments) { sb.AppendFormat("\"{0}\",", item); } return sb.ToString(); } public T RunSafe<T>(UnSafeProcedure<T> s, params object[] arguments) { DateTime st = DateTime.Now; try { return s(); } catch (Exception e1) { { Debug.Write("Error," + Concat(arguments) + "\r\n" + e1.ToString()); } return default(T); } finally { var sec = DateTime.Now.Subtract(st).TotalSeconds; if (sec > 20) { string tm = ">20sec,start," + st.ToLongTimeString() + ",End," + DateTime.Now.ToLongTimeString(); Debug.Write(tm+ Concat(arguments)); } } } /*3.performance counting procedures will looks like:*/ public Receipt VerifyUser(int Id, string username, string password) { return RunSafe<Receipt>(delegate() { //internal procedure that needs to be chcked troubleshooted using (var service = Instance()) { return service.VerifyAccount(Id, username, password); } }, "VerifyUser,facilityId",Id,"username",username,"password",password); }
how to add vim pandoc integration for markdown files
autocmd BufEnter *.md exe 'noremap <F5> :silent !start c:\tools\pd.bat % <CR>'
and autorefresh plugin for chrome: so every time I hit F5 on markdown (.md) file I can see compiled html version in chrome
Where pd.bat file is following:
pandoc "%1" -f markdown -t html -s -o "%1.html"
create sign up form for google group
here is javascrip/html code how to do it:
<script type="text/javascript"> function msgbox() { alert("An Invatation has been sent to " + _gel("emailconf").value + ". You will have to confirm the email invitation to join and recieve future emails. You can opt out of our group at anytime using the Unsubscribe link in the email."); } </script> Sign up with our google group to receive [product] updates or ask questions. <form action="http://groups.google.com/group/whiterocksoftware/boxsubscribe" id="formconf" onsubmit="msgbox()"> Email: <input type=text name=email id="emailconf"> <input type="submit" value="Subscribe"> </form>
Thursday
rainmeter slideshow skin tutorial
[Rainmeter] Update=100000 BackgroundMode=3 SolidColor=0,0,0,255 BackgroundMode=3 BackgroundMargins=0,34,0,14 [MeasureQuote] Measure=Plugin Plugin=QuotePlugin PathName=c:\temp\trig Subfolders=1 FileFilter=*.jpg;*.png;*.gif [MeterQuote] Meter=Image MeasureName=MeasureQuote X=0 Y=0 W=200 PreserveAspectRatio=1 LeftMouseUpAction=[!Refresh]
Friday
c# binary deserialize unable to find assembly version=1.0.0.0, culture=neutral, publickeytoken=null
It requires to have additional SerializationBinder class .
Here is whole workable storage class:
using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System; using System.Runtime.Serialization; using System.Reflection; public static class Storage { public const string ConfigurationName = "dev.settings"; public static string SettingFileName { get { return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), ConfigurationName); } } public static void Save(cProfile gh) { FileStream writeStream = new FileStream(SettingFileName, FileMode.Create); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(writeStream, gh); writeStream.Close(); } public static cProfile Load() { cProfile ret= new cProfile(); Manager.getInstance().RunSafe (delegate() { if (File.Exists(SettingFileName)) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Binder = new PreMergeToMergedDeserializationBinder(); FileStream readStream = new FileStream(SettingFileName, FileMode.Open); ret = (cProfile)formatter.Deserialize(readStream); readStream.Close(); } }); return ret; } sealed class PreMergeToMergedDeserializationBinder : SerializationBinder { public override Type BindToType(string assemblyName, string typeName) { Type typeToDeserialize = null; // For each assemblyName/typeName that you want to deserialize to // a different type, set typeToDeserialize to the desired type. String exeAssembly = Assembly.GetExecutingAssembly().FullName; // The following line of code returns the type. typeToDeserialize = Type.GetType(String.Format("{0}, {1}", typeName, exeAssembly)); return typeToDeserialize; } } }
Thursday
"app_name" is not translated in "af" (Afrikaans), "am" (Amharic), "ar" (Arabic), "az" (Azerbaijani), "be" (Belarusian), "bg" (Bulgarian), "bn" (Bengali), "bs" (Bosnian), "ca" (Catalan), "cs" (Czech), "da" (Danish), "de" (German), "el" (Greek), "es" (Spanish), "es-US" (Spanish: United States), "et" (Estonian), "eu" (Basque), "fa" (Persian), "fi" (Finnish), "fr" (French), "fr-CA" (French: Canada), "gl" (Galician), "gu" (Gujarati), "hi" (Hindi), "hr" (Croatian), "hu" (Hungarian), "hy" (Armenian), "in" (Indonesian), "is" (Icelandic), "it" (Italian), "iw" (Hebrew), "ja" (Japanese), "ka" (Georgian), "kk" (Kazakh), "km" (Khmer), "kn" (Kannada), "ko" (Korean), "ky" (Kyrgyz), "lo" (Lao), "lt" (Lithuanian), "lv" (Latvian), "mk" (Macedonian), "ml" (Malayalam), "mn" (Mongolian), "mr" (Marathi), "ms" (Malay), "my" (Burmese), "nb" (Norwegian Bokm?l), "ne" (Nepali), "nl" (Dutch), "pa" (Punjabi), "pl" (Polish), "pt-BR" (Portuguese: Brazil), "pt-PT" (Portuguese: Portugal), "ro" (Romanian), "ru" (Russian), "si" (Sinhala), "sk" (Slovak), "sl" (Slovenian), "sq" (Albanian), "sr" (Serbian), "sv" (Swedish), "sw" (Swahili), "ta" (Tamil), "te" (Telugu), "th" (Thai), "tl" (Tagalog), "tr" (Turkish), "uk" (Ukrainian), "ur" (Urdu), "uz" (Uzbek), "vi" (Vietnamese), "zh-CN" (Chinese: China), "zh-HK" (Chinese: Hong Kong SAR China), "zh-TW" (Chinese: Taiwan), "zu" (Zulu)
Severity Code Description Project File Line Suppression State
Error C:\Cordova\SpaceRiddle\SpaceRiddle\platforms\android\res\values\strings.xml:3: Error: "app_name" is not translated in "af" (Afrikaans), "am" (Amharic), "ar" (Arabic), "az" (Azerbaijani), "be" (Belarusian), "bg" (Bulgarian), "bn" (Bengali), "bs" (Bosnian), "ca" (Catalan), "cs" (Czech), "da" (Danish), "de" (German), "el" (Greek), "es" (Spanish), "es-US" (Spanish: United States), "et" (Estonian), "eu" (Basque), "fa" (Persian), "fi" (Finnish), "fr" (French), "fr-CA" (French: Canada), "gl" (Galician), "gu" (Gujarati), "hi" (Hindi), "hr" (Croatian), "hu" (Hungarian), "hy" (Armenian), "in" (Indonesian), "is" (Icelandic), "it" (Italian), "iw" (Hebrew), "ja" (Japanese), "ka" (Georgian), "kk" (Kazakh), "km" (Khmer), "kn" (Kannada), "ko" (Korean), "ky" (Kyrgyz), "lo" (Lao), "lt" (Lithuanian), "lv" (Latvian), "mk" (Macedonian), "ml" (Malayalam), "mn" (Mongolian), "mr" (Marathi), "ms" (Malay), "my" (Burmese), "nb" (Norwegian Bokm?l), "ne" (Nepali), "nl" (Dutch), "pa" (Punjabi), "pl" (Polish), "pt-BR" (Portuguese: Brazil), "pt-PT" (Portuguese: Portugal), "ro" (Romanian), "ru" (Russian), "si" (Sinhala), "sk" (Slovak), "sl" (Slovenian), "sq" (Albanian), "sr" (Serbian), "sv" (Swedish), "sw" (Swahili), "ta" (Tamil), "te" (Telugu), "th" (Thai), "tl" (Tagalog), "tr" (Turkish), "uk" (Ukrainian), "ur" (Urdu), "uz" (Uzbek), "vi" (Vietnamese), "zh-CN" (Chinese: China), "zh-HK" (Chinese: Hong Kong SAR China), "zh-TW" (Chinese: Taiwan), "zu" (Zulu) [MissingTranslation] SpaceRiddle 1
with adding translatable="false" so final file looks like :
<?xml version='1.0' encoding='utf-8'?> <resources> <string name="app_name" translatable="false">SpaceRiddle</string> <string name="launcher_name" translatable="false">@string/app_name</string> <string name="activity_name" translatable="false">@string/launcher_name</string> </resources>
Monday
Configuring Web for ASP.NET 4.5 failed .
Configuring Web for ASP.NET 4.5 failed. You must manually configure this site for ASP.NET 4.5 in order for the site to run correctly. ASP.NET 4.0 has not been registered on the Web server. You need to manually configure your Web server for ASP.NET 4.0 in order for your site to run correctly.”
I manually created pool for with 4.5, in order to create it I had to do following:
Because there is no v4.5 shown in the gui, and typically you don't need to manually specify v4.5 since it's an in-place update. However, you can set it explicitly with appcmd like this:
appcmd set apppool /apppool.name: [App Pool Name] /managedRuntimeVersion:v4.5
Appcmd is located in %windir%\System32\inetsrv.
This helped me to fix an issue with Web Deploy, where it was throwing an ERROR_APPPOOL_VERSION_MISMATCH error after upgrading from v4.0 to v4.5
Sunday
Requested registry access is not allowed Error in webservice or website.
- Log on to the computer as an administrator.
- Click Start, click Run, type regedit in the Open box, and then click OK. The Registry Editor window appears.
- Locate the following registry subkey:
- Right-click Eventlog, and then click Permissions. The Permissions for Eventlog dialog box appears.
- Click Advanced. The Advanced Security Settings for Eventlog dialog box appears.
- In the Name column, double-click the Users group. The Permission Entry for Eventlog dialog box appears.
- Select the Set Value check box, select the Create Subkey check box, and then click OK.
- Quit Registry Editor, and then log off from the administrator account.
make ubuntu business casual
to make ubuntu business casual - make it black remove background: gsettings set org.gnome.desktop.background picture-options ...
-
2010-11-24 Update: Please download latest version of Pidgin , that has this problem fixed , no additional steps required. Here are 3 ways to...
-
get ez_setup.py and setuptools-0.6c9-py2.6.egg . type: python ez_setup.py setuptools-0.6c9-py2.6.egg and that should get setuptools install...
-
from here , it's not perfect, but at least i can see internal API calls: < system . diagnostics > < sources > < ...