I had build problem with maven within Eclipse on Windows 7.
Though I observed mvn build was running just fine from command line.
mvn -T 5 -B -e -X -U -P test clean install -Dmaven.surefire.debug --settings ..\..\infra-scripts\maven-conf\settings.xml > output.log
Eclipse was considering as default JVM a JRE installation instead of JDK so it was failing on compilation.
I added to eclipse.ini following line:
-vm
C:\Program Files (x86)\Java\jdk1.8.0_25\bin
Also when starting from eclipse I used in "Goals" section following list:
-T 5 -B -e -X -U -P test clean install -Dmaven.surefire.debug --settings ..\..\infra-scripts\maven-conf\settings.xml
Compilation error got solved.
Works Fine for App Notification settings on IOS 10 (tested)
if(&UIApplicationOpenSettingsURLString != nil){
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
}
I use a utility that I wrote in C called autotab
. It analyzes the first few thousand lines of a file which you load and determines values for the Vim parameters shiftwidth
, tabstop
and expandtab
.
This is compiled using, for instance, gcc -O autotab.c -o autotab
. Instructions for integrating with Vim are in the comment header at the top.
Autotab is fairly clever, but can get confused from time to time, in particular by that have been inconsistently maintained using different indentation styles.
If a file evidently uses tabs, or a combination of tabs and spaces, for indentation, Autotab will figure out what tab size is being used by considering factors like alignment of internal elements across successive lines, such as comments.
It works for a variety of programming languages, and is forgiving for "out of band" elements which do not obey indentation increments, such as C preprocessing directives, C statement labels, not to mention the obvious blank lines.
To increase the phpMyAdmin
Session Timeout, open config.inc.php
in the root phpMyAdmin
directory and add this setting (anywhere).
$cfg['LoginCookieValidity'] = <your_new_timeout>;
Where <your_new_timeout>
is some number larger than 1800.
Note:
Always keep on mind that a short cookie lifetime is all well and good for the development server. So do not do this on your production server.
One of my windows services is logged on as Local System in windows server 2016, and I can find the user.config under C:\Windows\SysWOW64\config\systemprofile\AppData\Local\{your application name}.
I think the easiest way is searching your application name on C drive and then check where is the user.config
You can have separate configuration file, but you'll have to read it "manually", the ConfigurationManager.AppSettings["key"]
will read only the config of the running assembly.
Assuming you're using Visual Studio as your IDE, you can right click the desired project ? Add ? New item ? Application Configuration File
This will add App.config
to the project folder, put your settings in there under <appSettings>
section. In case you're not using Visual Studio and adding the file manually, make sure to give it such name: DllName.dll.config, otherwise the below code won't work properly.
Now to read from this file have such function:
string GetAppSetting(Configuration config, string key)
{
KeyValueConfigurationElement element = config.AppSettings.Settings[key];
if (element != null)
{
string value = element.Value;
if (!string.IsNullOrEmpty(value))
return value;
}
return string.Empty;
}
And to use it:
Configuration config = null;
string exeConfigPath = this.GetType().Assembly.Location;
try
{
config = ConfigurationManager.OpenExeConfiguration(exeConfigPath);
}
catch (Exception ex)
{
//handle errror here.. means DLL has no sattelite configuration file.
}
if (config != null)
{
string myValue = GetAppSetting(config, "myKey");
...
}
You'll also have to add reference to System.Configuration namespace in order to have the ConfigurationManager class available.
When building the project, in addition to the DLL you'll have DllName.dll.config
file as well, that's the file you have to publish with the DLL itself.
The above is basic sample code, for those interested in a full scale example, please refer to this other answer.
In my case, the setting was HKEY_CURRENT_USER\Software\Policies\Google\Chrome
I deleted Chrome
and everything is fine now.
You can use SHOW
:
SHOW max_connections;
This returns the currently effective setting. Be aware that it can differ from the setting in postgresql.conf
as there are a multiple ways to set run-time parameters in PostgreSQL. To reset the "original" setting from postgresql.conf
in your current session:
RESET max_connections;
However, not applicable to this particular setting. The manual:
This parameter can only be set at server start.
To see all settings:
SHOW ALL;
There is also pg_settings
:
The view
pg_settings
provides access to run-time parameters of the server. It is essentially an alternative interface to theSHOW
andSET
commands. It also provides access to some facts about each parameter that are not directly available fromSHOW
, such as minimum and maximum values.
For your original request:
SELECT *
FROM pg_settings
WHERE name = 'max_connections';
Finally, there is current_setting()
, which can be nested in DML statements:
SELECT current_setting('max_connections');
Related:
In all the places I've worked, database has been mandatory because of application support. As Adam said, the user might not be at his desk or the machine might be off, or you might want to quickly change someone's configuration or assign a new-joiner a default (or team member's) config.
If the settings are likely to grow as new versions of the application are released, you might want to store the data as blobs which can then be deserialized by the application. This is especially useful if you use something like Prism which discovers modules, as you can't know what settings a module will return. The blobs could be keyed by username/machine composite key. That way you can have different settings for every machine.
I've not used the in-built Settings class much so I'll abstain from commenting. :)
You can simply use:
mvn --settings YourOwnSettings.xml clean install
or
mvn -s YourOwnSettings.xml clean install
Try using ReadSettings:
from readsettings import ReadSettings
data = ReadSettings("settings.json") # Load or create any json, yml, yaml or toml file
data["name"] = "value" # Set "name" to "value"
data["name"] # Returns: "value"
I ran into this issue. Turns out I was including in the template, using the static
template tag, a file that did not exist anymore. A look in the logs showed me the problem.
I guess this is just one of many possible reasons for this kind of error.
Moral of the story: always log errors and always check logs.
You can set up a default way to shorten the command line and use it as a template for further configurations by changing the default JUnit Run/Debug Configuration template. Then all new Run/Debug configuration you create in project will use the same option.
Here is the related blog post about configurable command line shortener option.
The first response from App-Specific URL Schemes worked for me on iOS 10.3.
if let appSettings = URL(string: UIApplicationOpenSettingsURLString + Bundle.main.bundleIdentifier!) {
if UIApplication.shared.canOpenURL(appSettings) {
UIApplication.shared.open(appSettings)
}
}
There is another way to approach this if you are using Git for source control. Inspired by an answer here, I wrote my own filter for use in a gitattributes file.
To install this filter, save it as noeol_filter
somewhere in your $PATH
, make it executable, and run the following commands:
git config --global filter.noeol.clean noeol_filter
git config --global filter.noeol.smudge cat
To start using the filter only for yourself, put the following line in your $GIT_DIR/info/attributes
:
*.php filter=noeol
This will make sure you do not commit any newline at eof in a .php
file, no matter what Vim does.
And now, the script itself:
#!/usr/bin/python
# a filter that strips newline from last line of its stdin
# if the last line is empty, leave it as-is, to make the operation idempotent
# inspired by: https://stackoverflow.com/questions/1654021/how-can-i-delete-a-newline-if-it-is-the-last-character-in-a-file/1663283#1663283
import sys
if __name__ == '__main__':
try:
pline = sys.stdin.next()
except StopIteration:
# no input, nothing to do
sys.exit(0)
# spit out all but the last line
for line in sys.stdin:
sys.stdout.write(pline)
pline = line
# strip newline from last line before spitting it out
if len(pline) > 2 and pline.endswith("\r\n"):
sys.stdout.write(pline[:-2])
elif len(pline) > 1 and pline.endswith("\n"):
sys.stdout.write(pline[:-1])
else:
sys.stdout.write(pline)
I Found this the most useful and easy to use https://wiki.python.org/moin/ConfigParserExamples
You just create a "myfile.ini" like:
[SectionOne]
Status: Single
Name: Derek
Value: Yes
Age: 30
Single: True
[SectionTwo]
FavoriteColor=Green
[SectionThree]
FamilyName: Johnson
[Others]
Route: 66
And retrieve the data like:
>>> import ConfigParser
>>> Config = ConfigParser.ConfigParser()
>>> Config
<ConfigParser.ConfigParser instance at 0x00BA9B20>
>>> Config.read("myfile.ini")
['c:\\tomorrow.ini']
>>> Config.sections()
['Others', 'SectionThree', 'SectionOne', 'SectionTwo']
>>> Config.options('SectionOne')
['Status', 'Name', 'Value', 'Age', 'Single']
>>> Config.get('SectionOne', 'Status')
'Single'
After this, your configuration should look like:
(On IntelliJ IDEA 13.x, 14.x, 15.x, 2016.x, 2017.x)
To throw another potential solution into the mix, I had a settings
folder as well as a settings.py
in my project dir. (I was switching back from environment-based settings files to one file. I have since reconsidered.)
Python was getting confused about whether I wanted to import project/settings.py
or project/settings/__init__.py
. I removed the settings
dir and everything now works fine.
Here is a simple work around for white space between the '=' sign and the data, in the config file. Assign to the istringstream from the location after the '=' sign and when reading from it, any leading white space is ignored.
Note: while using an istringstream in a loop, make sure you call clear() before assigning a new string to it.
//config.txt
//Input name = image1.png
//Num. of rows = 100
//Num. of cols = 150
std::string ipName;
int nR, nC;
std::ifstream fin("config.txt");
std::string line;
std::istringstream sin;
while (std::getline(fin, line)) {
sin.str(line.substr(line.find("=")+1));
if (line.find("Input name") != std::string::npos) {
std::cout<<"Input name "<<sin.str()<<std::endl;
sin >> ipName;
}
else if (line.find("Num. of rows") != std::string::npos) {
sin >> nR;
}
else if (line.find("Num. of cols") != std::string::npos) {
sin >> nC;
}
sin.clear();
}
For IntelliJ IDEA 2019.3.4 (Ultimate Edition), the following worked for me:
I had the same problem. The reason was that I had two JAR files were not added through the Maven dependency, so when I ran mvn compile
, the console display the error error:
Symbol cannot be found,Class...".
To fix it:
mvn compile
Prefer <appSettings>
to <customUserSetting>
section. It is much easier to read AND write with (Web)ConfigurationManager. ConfigurationSection, ConfigurationElement and ConfigurationElementCollection require you to derive custom classes and implement custom ConfigurationProperty properties. Way too much for mere everyday mortals IMO.
Here is an example of reading and writing to web.config:
using System.Web.Configuration;
using System.Configuration;
Configuration config = WebConfigurationManager.OpenWebConfiguration("/");
string oldValue = config.AppSettings.Settings["SomeKey"].Value;
config.AppSettings.Settings["SomeKey"].Value = "NewValue";
config.Save(ConfigurationSaveMode.Modified);
Before:
<appSettings>
<add key="SomeKey" value="oldValue" />
</appSettings>
After:
<appSettings>
<add key="SomeKey" value="newValue" />
</appSettings>
I know it's already answered but couldn't you just synchronize the settings in the settings designer to move back to your default settings?
The M2_HOME
environment variable for the global one. See Settings Reference:
The
settings
element in thesettings.xml
file contains elements used to define values which configure Maven execution in various ways, like thepom.xml
, but should not be bundled to any specific project, or distributed to an audience. These include values such as the local repository location, alternate remote repository servers, and authentication information. There are two locations where a settings.xml file may live:
- The Maven install:
$M2_HOME/conf/settings.xml
- A user's install:
${user.home}/.m2/settings.xml
the design in android 2.3 (stable version) is slightly changed.
File ? Settings ? Build, Execution, Deployment ? Instant Run and uncheck Enable Instant Run.
Use Bash and the date command to convert from an ISO-like format to the one you want. I wanted an org-mode date format (and list item), so I did this:
echo + [$(date -d "$(git log --pretty=format:%ai -1)" +"%Y-%m-%d %a %H:%M")] \
$(git log --pretty=format:"%h %s" --abbrev=12 -1)
And the result is for example:
+ [2015-09-13 Sun 22:44] 2b0ad02e6cec Merge pull request #72 from 3b/bug-1474631
In this article, they explain it in a very easy way but basically, we just need to execute a git remote set-url origin "https://<yourUserName>@bitbucket.org/<yourRepo>"
and next time you do a git pull
or a git push
you will have to put your password.
You can reference Microsoft.VisualBasic.dll
.
Then using the code below.
Microsoft.VisualBasic.Interaction.InputBox("Question?","Title","Default Text");
Alternatively, by adding a using
directive allowing for a shorter syntax in your code (which I'd personally prefer).
using Microsoft.VisualBasic;
...
Interaction.InputBox("Question?","Title","Default Text");
Or you can do what Pranay Rana suggests, that's what I would've done too...
private String message;
private ScreenManager s;
//Here is an example of code to add the keyListener() as suggested; modify
public void init(){
Window w = s.getFullScreenWindow();
w.addKeyListener(this);
public void keyPressed(KeyEvent e){
int keyCode = e.getKeyCode();
if(keyCode == KeyEvent.VK_F5)
message = "Pressed: " + KeyEvent.getKeyText(keyCode);
}
Derp! I signed into the account and there was a "Suspicious login attempt" warning message at the top of the page. After clicking the warning and authorizing the access, everything works.
First I want to thank you for all the good answers and explanations. This is the method I created based upon all your answer to get the base url. I only use it in very rare situations. So there is NOT a big focus on security issues, like XSS attacks. Maybe someone needs it.
// Get base url
function getBaseUrl($array=false) {
$protocol = "";
$host = "";
$port = "";
$dir = "";
// Get protocol
if(array_key_exists("HTTPS", $_SERVER) && $_SERVER["HTTPS"] != "") {
if($_SERVER["HTTPS"] == "on") { $protocol = "https"; }
else { $protocol = "http"; }
} elseif(array_key_exists("REQUEST_SCHEME", $_SERVER) && $_SERVER["REQUEST_SCHEME"] != "") { $protocol = $_SERVER["REQUEST_SCHEME"]; }
// Get host
if(array_key_exists("HTTP_X_FORWARDED_HOST", $_SERVER) && $_SERVER["HTTP_X_FORWARDED_HOST"] != "") { $host = trim(end(explode(',', $_SERVER["HTTP_X_FORWARDED_HOST"]))); }
elseif(array_key_exists("SERVER_NAME", $_SERVER) && $_SERVER["SERVER_NAME"] != "") { $host = $_SERVER["SERVER_NAME"]; }
elseif(array_key_exists("HTTP_HOST", $_SERVER) && $_SERVER["HTTP_HOST"] != "") { $host = $_SERVER["HTTP_HOST"]; }
elseif(array_key_exists("SERVER_ADDR", $_SERVER) && $_SERVER["SERVER_ADDR"] != "") { $host = $_SERVER["SERVER_ADDR"]; }
//elseif(array_key_exists("SSL_TLS_SNI", $_SERVER) && $_SERVER["SSL_TLS_SNI"] != "") { $host = $_SERVER["SSL_TLS_SNI"]; }
// Get port
if(array_key_exists("SERVER_PORT", $_SERVER) && $_SERVER["SERVER_PORT"] != "") { $port = $_SERVER["SERVER_PORT"]; }
elseif(stripos($host, ":") !== false) { $port = substr($host, (stripos($host, ":")+1)); }
// Remove port from host
$host = preg_replace("/:\d+$/", "", $host);
// Get dir
if(array_key_exists("SCRIPT_NAME", $_SERVER) && $_SERVER["SCRIPT_NAME"] != "") { $dir = $_SERVER["SCRIPT_NAME"]; }
elseif(array_key_exists("PHP_SELF", $_SERVER) && $_SERVER["PHP_SELF"] != "") { $dir = $_SERVER["PHP_SELF"]; }
elseif(array_key_exists("REQUEST_URI", $_SERVER) && $_SERVER["REQUEST_URI"] != "") { $dir = $_SERVER["REQUEST_URI"]; }
// Shorten to main dir
if(stripos($dir, "/") !== false) { $dir = substr($dir, 0, (strripos($dir, "/")+1)); }
// Create return value
if(!$array) {
if($port == "80" || $port == "443" || $port == "") { $port = ""; }
else { $port = ":".$port; }
return htmlspecialchars($protocol."://".$host.$port.$dir, ENT_QUOTES);
} else { return ["protocol" => $protocol, "host" => $host, "port" => $port, "dir" => $dir]; }
}
You're correct that this is really painful to hand out to others, but if you have to, this is how you do it.
References
In Style.xml pre-define the style:
<style name="largeText">
<item name="android:textAppearance">@android:style/TextAppearance.Large.Inverse</item>
<item name="android:textStyle">bold</item>
</style>
in code:
text.setTextAppearance(context, R.style.largeText);
Have you checked if:
class
file under src
folder in your JAVA project?(not file
)I am a newbie who try to run a helloworld example and just got the same error as yours, and these work for me.
If you are locked out and WiFi is turned off in your Androud device then one solution is to connect your phone to a PC (connected to internet) and try to login with your google account. - it worked for me.
Using SMTP is one way to go, and the others have already pointed out ways how to do it. Just note that while doing this, you completely circumvent the built in mail app, and you will have to provide the address of the SMTP server, the user name and password for that server, either statically in your code, or query it from the user.
Another way would involve a simple server side script, like php, that takes some URL parameters and uses them to send a mail. This way, you only need to make an HTTP request from the device (easily possible with the built in libraries) and don't need to store the SMTP login data on the device. This is one more indirection compared to direct SMTP usage, but because it's so very easy to make HTTP request and send mails from PHP, it might even be simpler than the direct way.
If the mail shall be send from the users default mail account that he already registered with the phone, you'd have to take some other approach. If you have enough time and experience, you might want to check the source code of the Android Email application to see if it offers some entry point to send a mail without user interaction (I don't know, but maybe there is one).
Maybe you even find a way to query the users account details (so you can use them for SMTP), though I highly doubt that this is possible, because it would be a huge security risk and Android is built rather securely.
I've made an example without jQuery here : http://codepen.io/sorinnn/pen/ovzdq
/**
by Nemes Ioan Sorin - not an jQuery big fan
therefore this script is for those who love the old clean coding style
@id = the id of the element who need to bring into view
Note : this demo scrolls about 12.700 pixels from Link1 to Link3
*/
(function()
{
window.setTimeout = window.setTimeout; //
})();
var smoothScr = {
iterr : 30, // set timeout miliseconds ..decreased with 1ms for each iteration
tm : null, //timeout local variable
stopShow: function()
{
clearTimeout(this.tm); // stopp the timeout
this.iterr = 30; // reset milisec iterator to original value
},
getRealTop : function (el) // helper function instead of jQuery
{
var elm = el;
var realTop = 0;
do
{
realTop += elm.offsetTop;
elm = elm.offsetParent;
}
while(elm);
return realTop;
},
getPageScroll : function() // helper function instead of jQuery
{
var pgYoff = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;
return pgYoff;
},
anim : function (id) // the main func
{
this.stopShow(); // for click on another button or link
var eOff, pOff, tOff, scrVal, pos, dir, step;
eOff = document.getElementById(id).offsetTop; // element offsetTop
tOff = this.getRealTop(document.getElementById(id).parentNode); // terminus point
pOff = this.getPageScroll(); // page offsetTop
if (pOff === null || isNaN(pOff) || pOff === 'undefined') pOff = 0;
scrVal = eOff - pOff; // actual scroll value;
if (scrVal > tOff)
{
pos = (eOff - tOff - pOff);
dir = 1;
}
if (scrVal < tOff)
{
pos = (pOff + tOff) - eOff;
dir = -1;
}
if(scrVal !== tOff)
{
step = ~~((pos / 4) +1) * dir;
if(this.iterr > 1) this.iterr -= 1;
else this.itter = 0; // decrease the timeout timer value but not below 0
window.scrollBy(0, step);
this.tm = window.setTimeout(function()
{
smoothScr.anim(id);
}, this.iterr);
}
if(scrVal === tOff)
{
this.stopShow(); // reset function values
return;
}
}
}
since olden times, the correct syntax for if/else if
in Python is elif
. By the way, you can use dictionary if you have alot of if/else
.eg
d={"1":"1a","2":"2a"}
if not a in d: print("3a")
else: print (d[a])
For msw, example of executing functions using dictionary.
def print_one(arg=None):
print "one"
def print_two(num):
print "two %s" % num
execfunctions = { 1 : (print_one, ['**arg'] ) , 2 : (print_two , ['**arg'] )}
try:
execfunctions[1][0]()
except KeyError,e:
print "Invalid option: ",e
try:
execfunctions[2][0]("test")
except KeyError,e:
print "Invalid option: ",e
else:
sys.exit()
You can achieve this by "interpolating" the className passed from the parent component to the child component using this.props.className
. Example below:
export default class ParentComponent extends React.Component {
render(){
return <ChildComponent className="your-modifier-class" />
}
}
export default class ChildComponent extends React.Component {
render(){
return <div className={"original-class " + this.props.className}></div>
}
}
Official document of Crypto++ AES is a good start. And from my archive, a basic implementation of AES is as follows:
Please refer here with more explanation, I recommend you first understand the algorithm and then try to understand each line step by step.
#include <iostream>
#include <iomanip>
#include "modes.h"
#include "aes.h"
#include "filters.h"
int main(int argc, char* argv[]) {
//Key and IV setup
//AES encryption uses a secret key of a variable length (128-bit, 196-bit or 256-
//bit). This key is secretly exchanged between two parties before communication
//begins. DEFAULT_KEYLENGTH= 16 bytes
CryptoPP::byte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ], iv[ CryptoPP::AES::BLOCKSIZE ];
memset( key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH );
memset( iv, 0x00, CryptoPP::AES::BLOCKSIZE );
//
// String and Sink setup
//
std::string plaintext = "Now is the time for all good men to come to the aide...";
std::string ciphertext;
std::string decryptedtext;
//
// Dump Plain Text
//
std::cout << "Plain Text (" << plaintext.size() << " bytes)" << std::endl;
std::cout << plaintext;
std::cout << std::endl << std::endl;
//
// Create Cipher Text
//
CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, iv );
CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( ciphertext ) );
stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plaintext.c_str() ), plaintext.length() );
stfEncryptor.MessageEnd();
//
// Dump Cipher Text
//
std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl;
for( int i = 0; i < ciphertext.size(); i++ ) {
std::cout << "0x" << std::hex << (0xFF & static_cast<CryptoPP::byte>(ciphertext[i])) << " ";
}
std::cout << std::endl << std::endl;
//
// Decrypt
//
CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, iv );
CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
stfDecryptor.Put( reinterpret_cast<const unsigned char*>( ciphertext.c_str() ), ciphertext.size() );
stfDecryptor.MessageEnd();
//
// Dump Decrypted Text
//
std::cout << "Decrypted Text: " << std::endl;
std::cout << decryptedtext;
std::cout << std::endl << std::endl;
return 0;
}
For installation details :
sudo apt-get install libcrypto++-dev libcrypto++-doc libcrypto++-utils
Put the threads in a list and then use the Join method
threads = []
t = Thread(...)
threads.append(t)
...repeat as often as necessary...
# Start all threads
for x in threads:
x.start()
# Wait for all of them to finish
for x in threads:
x.join()
var myRedirect = function(redirectUrl) {
var form = $('<form action="' + redirectUrl + '" method="post">' +
'<input type="hidden" name="parameter1" value="sample" />' +
'<input type="hidden" name="parameter2" value="Sample data 2" />' +
'</form>');
$('body').append(form);
$(form).submit();
};
Found code at http://www.prowebguru.com/2013/10/send-post-data-while-redirecting-with-jquery/
Going to try this and other suggestions for my work.
Is there any other way to do the same ?
sprintf('%.2f', number)
is a cryptic, but very powerful way of formatting numbers. The result is always a string, but since you're rounding I assume you're doing it for presentation purposes anyway. sprintf
can format any number almost any way you like, and lots more.
Full sprintf documentation: http://www.ruby-doc.org/core-2.0.0/Kernel.html#method-i-sprintf
With the new syntax of RxJS 5.5+, this becomes as the following:
// RxJS 6
import { EMPTY, empty, of } from "rxjs";
// rxjs 5.5+ (<6)
import { empty } from "rxjs/observable/empty";
import { of } from "rxjs/observable/of";
empty(); // deprecated use EMPTY
EMPTY;
of({});
Just one thing to keep in mind, EMPTY
completes the observable, so it won't trigger next
in your stream, but only completes. So if you have, for instance, tap
, they might not get trigger as you wish (see an example below).
Whereas of({})
creates an Observable
and emits next with a value of {}
and then it completes the Observable
.
E.g.:
EMPTY.pipe(
tap(() => console.warn("i will not reach here, as i am complete"))
).subscribe();
of({}).pipe(
tap(() => console.warn("i will reach here and complete"))
).subscribe();
AndroidStudioFrontScreenI simply double clicked the Android dmg install file that I saved on the hard drive and when the initial screen came up I dragged the icon for Android Studio into the Applications folder, now I know where it is!!! Also when you run it, be sure to right click the Android Studio while on the Dock and select "Options" -> "Keep on Dock". Everything else works.
-webkit-animation-fill-mode: forwards; /* Safari 4.0 - 8.0 */ animation-fill-mode: forwards;
Browser Support
Usage:-
.fadeIn {
animation-name: fadeIn;
-webkit-animation-name: fadeIn;
animation-duration: 1.5s;
-webkit-animation-duration: 1.5s;
animation-timing-function: ease;
-webkit-animation-timing-function: ease;
animation-fill-mode: forwards;
-webkit-animation-fill-mode: forwards;
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@-webkit-keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
This is my C version:
void mergesort(int *a, int len) {
int temp, listsize, xsize;
for (listsize = 1; listsize <= len; listsize*=2) {
for (int i = 0, j = listsize; (j+listsize) <= len; i += (listsize*2), j += (listsize*2)) {
merge(& a[i], listsize, listsize);
}
}
listsize /= 2;
xsize = len % listsize;
if (xsize > 1)
mergesort(& a[len-xsize], xsize);
merge(a, listsize, xsize);
}
void merge(int *a, int sizei, int sizej) {
int temp;
int ii = 0;
int ji = sizei;
int flength = sizei+sizej;
for (int f = 0; f < (flength-1); f++) {
if (sizei == 0 || sizej == 0)
break;
if (a[ii] < a[ji]) {
ii++;
sizei--;
}
else {
temp = a[ji];
for (int z = (ji-1); z >= ii; z--)
a[z+1] = a[z];
ii++;
a[f] = temp;
ji++;
sizej--;
}
}
}
The #1 reason has already been stated - it hides errors that you did not expect.
(#2) - It makes your code difficult for others to read and understand. If you catch a FileNotFoundException when you are trying to read a file, then it is pretty obvious to another developer what functionality the 'catch' block should have. If you do not specify an exception, then you need additional commenting to explain what the block should do.
(#3) - It demonstrates lazy programming. If you use the generic try/catch, it indicates either that you do not understand the possible run-time errors in your program, or that you do not know what exceptions are possible in Python. Catching a specific error shows that you understand both your program and the range of errors that Python throws. This is more likely to make other developers and code-reviewers trust your work.
My case is different. i want check two time ranges overlap. there should not be a unit time overlap. here is Go implementation.
func CheckRange(as, ae, bs, be int) bool {
return (as >= be) != (ae > bs)
}
Test cases
if CheckRange(2, 8, 2, 4) != true {
t.Error("Expected 2,8,2,4 to equal TRUE")
}
if CheckRange(2, 8, 2, 4) != true {
t.Error("Expected 2,8,2,4 to equal TRUE")
}
if CheckRange(2, 8, 6, 9) != true {
t.Error("Expected 2,8,6,9 to equal TRUE")
}
if CheckRange(2, 8, 8, 9) != false {
t.Error("Expected 2,8,8,9 to equal FALSE")
}
if CheckRange(2, 8, 4, 6) != true {
t.Error("Expected 2,8,4,6 to equal TRUE")
}
if CheckRange(2, 8, 1, 9) != true {
t.Error("Expected 2,8,1,9 to equal TRUE")
}
if CheckRange(4, 8, 1, 3) != false {
t.Error("Expected 4,8,1,3 to equal FALSE")
}
if CheckRange(4, 8, 1, 4) != false {
t.Error("Expected 4,8,1,4 to equal FALSE")
}
if CheckRange(2, 5, 6, 9) != false {
t.Error("Expected 2,5,6,9 to equal FALSE")
}
if CheckRange(2, 5, 5, 9) != false {
t.Error("Expected 2,5,5,9 to equal FALSE")
}
you can see there is XOR pattern in boundary comparison
Use cut
:
cut -c6-
This prints each line of the input starting at column 6 (the first column is 1).
May be using List comprehension
import pandas as pd
import numpy as np
df=pd.DataFrame(['ONE','Two', np.nan],columns=['Name']})
df['Name'] = [str(i).lower() for i in df['Name']]
print(df)
This can be useful when your programming functions for a library or dll.
This rethrow structure can be used to purposefully reset the call stack so that instead of seeing the exception thrown from an individual function inside the function, you get the exception from the function itself.
I think this is just used so that the thrown exceptions are cleaner and don't go into the "roots" of the library.
This will find "Mark Sagal" in Student.txt. Assuming Student.txt contains
Student.txt
Amir Amiri
Mark Sagal
Juan Delacruz
Main.java
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
final String file = "Student.txt";
String line = null;
ArrayList<String> fileContents = new ArrayList<>();
try {
FileReader fReader = new FileReader(file);
BufferedReader fileBuff = new BufferedReader(fReader);
while ((line = fileBuff.readLine()) != null) {
fileContents.add(line);
}
fileBuff.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
System.out.println(fileContents.contains("Mark Sagal"));
}
}
Just paste the below code in activity onCreate()
.
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
It will ignore URI exposure.
Happy coding :-)
The representation of the values 65529u and -7 are identical for 16-bit ints. Only the interpretation of the bits is different.
For larger ints and these values, you need to sign extend; one way is with logical operations
int y = (int )(x | 0xffff0000u); // assumes 16 to 32 extension, x is > 32767
If speed is not an issue, or divide is fast on your processor,
int y = ((int ) (x * 65536u)) / 65536;
The multiply shifts left 16 bits (again, assuming 16 to 32 extension), and the divide shifts right maintaining the sign.
It's a place to put an embedded database, such as Sql Server Express, Access, or SQLite.
You can use the function toprettyxml()
from xml.dom.minidom
in order to do that:
def prettify(elem):
"""Return a pretty-printed XML string for the Element.
"""
rough_string = ElementTree.tostring(elem, 'utf-8')
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent="\t")
The idea is to print your Element
in a string, parse it using minidom and convert it again in XML using the toprettyxml
function.
Source: http://pymotw.com/2/xml/etree/ElementTree/create.html
Please check this example here: Accessing Structure Members
There is explained that the right way to do it is like this:
strcpy(s1.name , "Egzona");
printf( "Name : %s\n", s1.name);
// Sending and receiving data in JSON format using POST method
//
var xhr = new XMLHttpRequest();
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.email + ", " + json.password);
}
};
var data = JSON.stringify({"email": "[email protected]", "password": "101010"});
xhr.send(data);
// Sending a receiving data in JSON format using GET method
//
var xhr = new XMLHttpRequest();
var url = "url?data=" + encodeURIComponent(JSON.stringify({"email": "[email protected]", "password": "101010"}));
xhr.open("GET", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.email + ", " + json.password);
}
};
xhr.send();
<?php
// Handling data in JSON format on the server-side using PHP
//
header("Content-Type: application/json");
// build a PHP variable from JSON sent using POST method
$v = json_decode(stripslashes(file_get_contents("php://input")));
// build a PHP variable from JSON sent using GET method
$v = json_decode(stripslashes($_GET["data"]));
// encode the PHP variable to JSON and send it back on client-side
echo json_encode($v);
?>
The limit of the length of an HTTP Get request is dependent on both the server and the client (browser) used, from 2kB - 8kB. The server should return 414 (Request-URI Too Long) status if an URI is longer than the server can handle.
Note Someone said that I could use state names instead of state values; in other words I could use xhr.readyState === xhr.DONE
instead of xhr.readyState === 4
The problem is that Internet Explorer uses different state names so it's better to use state values.
string mypath = @"..\folder1\folder2\folder2";
string[] directories = mypath.Split(Path.DirectorySeparatorChar);
Edit: This returns each individual folder in the directories array. You can get the number of folders returned like this:
int folderCount = directories.Length;
$save_folder = "some/path/" . date('dmy');
if (!file_exists($save_folder)) {
mkdir($save_folder, 0777);
}
Basic difference is that Google App Engine (GAE) is a Platform as a Service (PaaS) whereas Google Compute Engine (GCE) is an Infrastructure as a Service (IaaS).
To run your application in GAE you just need to write your code and deploy it into GAE, no other headache. Since GAE is fully scalable, it will automatically acquire more instances in case the traffic goes higher and decrease the instances when traffic decreases. You will be charged for the resources you really use, I mean, you will be billed for the Instance-Hours, Transferred Data, Storage etc your app really used. But the restriction is, you can create your application in only Python, PHP, Java, NodeJS, .NET, Ruby and **Go.
On the other hand, GCE provides you full infrastructure in the form of Virtual Machine. You have complete control over those VMs' environment and runtime as you can write or install any program there. Actually GCE is the way to use Google Data Centers virtually. In GCE you have to manually configure your infrastructure to handle scalability by using Load Balancer.
Both GAE and GCE are part of Google Cloud Platform.
Update: In March 2014 Google announced a new service under App Engine named Managed Virtual Machine. Managed VMs offers app engine applications a bit more flexibility over app platform, CPU and memory options. Like GCE you can create a custom runtime environment in these VMs for app engine application. Actually Managed VMs of App Engine blurs the frontier between IAAS and PAAS to some extent.
Please try this one:
function used_to_compare_two_arrays(a, b)
{
// This block will make the array of indexed that array b contains a elements
var c = a.filter(function(value, index, obj) {
return b.indexOf(value) > -1;
});
// This is used for making comparison that both have same length if no condition go wrong
if (c.length !== a.length) {
return 0;
} else{
return 1;
}
}
Here is how to add inline code:
You can add inline code with {\tt code }
or \texttt{ code }
. If you want to format the inline code, then it would be best to make your own command
\newcommand{\code}[1]{\texttt{#1}}
Also, note that code blocks can be loaded from other files with
\lstinputlisting[breaklines]{source.c}
breaklines
isn't required, but I find it useful. Be aware that you'll have to specify \usepackage{
listings }
for this one.
Update: The listings package also includes the \lstinline
command, which has the same syntax highlighting features as the \lstlisting
and \lstinputlisting
commands (see Cloudanger's answer for configuration details). As mentioned in a few other answers, there's also the minted package, which provides the \mintinline
command. Like \lstinline
, \mintinline
provides the same syntax highlighting as a regular minted code block:
\documentclass{article}
\usepackage{minted}
\begin{document}
This is a sentence with \mintinline{python}{def inlineCode(a="ipsum)}
\end{document}
It is absolutely possible to install side-by-side several JRE/JDK versions. Moreover, you don't have to do anything special for that to happen, as Sun is creating a different folder for each (under Program Files).
There is no control panel to check which JRE works for each application. Basically, the JRE that will work would be the first in your PATH environment variable. You can change that, or the JAVA_HOME variable, or create specific cmd/bat files to launch the applications you desire, each with a different JRE in path.
Download the source of deme from here(Json parsing in android kotlin)
Add this dependency:
compile 'com.squareup.okhttp3:okhttp:3.8.1'
Call api function:
fun run(url: String) {
dialog.show()
val request = Request.Builder()
.url(url)
.build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
dialog.dismiss()
}
override fun onResponse(call: Call, response: Response) {
var str_response = response.body()!!.string()
val json_contact:JSONObject = JSONObject(str_response)
var jsonarray_contacts:JSONArray= json_contact.getJSONArray("contacts")
var i:Int = 0
var size:Int = jsonarray_contacts.length()
al_details= ArrayList();
for (i in 0.. size-1) {
var json_objectdetail:JSONObject=jsonarray_contacts.getJSONObject(i)
var model:Model= Model();
model.id=json_objectdetail.getString("id")
model.name=json_objectdetail.getString("name")
model.email=json_objectdetail.getString("email")
model.address=json_objectdetail.getString("address")
model.gender=json_objectdetail.getString("gender")
al_details.add(model)
}
runOnUiThread {
//stuff that updates ui
val obj_adapter : CustomAdapter
obj_adapter = CustomAdapter(applicationContext,al_details)
lv_details.adapter=obj_adapter
}
dialog.dismiss()
}
})
I hope this example will be helpful for you)
print(type(None)) # NoneType
So, you can check type of the variable name
# Example
name = 12 # name = None
if type(name) is type(None):
print("Can't find name")
else:
print(name)
Child can ask kernel to deliver SIGHUP
(or other signal) when parent dies by specifying option PR_SET_PDEATHSIG
in prctl()
syscall like this:
prctl(PR_SET_PDEATHSIG, SIGHUP);
See man 2 prctl
for details.
Edit: This is Linux-only
A <context:component-scan/>
custom tag registers the same set of bean definitions as is done by , apart from its primary responsibility of scanning the java packages and registering bean definitions from the classpath.
If for some reason this registration of default bean definitions are to be avoided, the way to do that is to specify an additional "annotation-config" attribute in component-scan, this way:
<context:component-scan basePackages="" annotation-config="false"/>
Reference: http://www.java-allandsundry.com/2012/12/contextcomponent-scan-contextannotation.html
There are already great answers about the advantages of using list initialization, however my personal rule of thumb is NOT to use curly braces whenever possible, but instead make it dependent on the conceptual meaning:
In my experience, this ruleset can be applied much more consistently than using curly braces by default, but having to explicitly remember all the exceptions when they can't be used or have a different meaning than the "normal" function-call syntax with parenthesis (calls a different overload).
It e.g. fits nicely with standard library-types like std::vector
:
vector<int> a{10,20}; //Curly braces -> fills the vector with the arguments
vector<int> b(10,20); //Parentheses -> uses arguments to parametrize some functionality,
vector<int> c(it1,it2); //like filling the vector with 10 integers or copying a range.
vector<int> d{}; //empty braces -> default constructs vector, which is equivalent
//to a vector that is filled with zero elements
To install it on a Debian based system simply do
# Install latest JDK
sudo apt install default-jdk
# install unzip if not installed yet
sudo apt install unzip
# get latest sdk tools - link will change. go to https://developer.android.com/studio/#downloads to get the latest one
cd ~
wget https://dl.google.com/android/repository/sdk-tools-linux-4333796.zip
# unpack archive
unzip sdk-tools-linux-4333796.zip
rm sdk-tools-linux-4333796.zip
mkdir android-sdk
mv tools android-sdk/tools
Then add the Android SDK to your PATH, open ~/.bashrc
in editor and add the following lines into the file
# Export the Android SDK path
export ANDROID_HOME=$HOME/android-sdk
export PATH=$PATH:$ANDROID_HOME/tools/bin
export PATH=$PATH:$ANDROID_HOME/platform-tools
# Fixes sdkmanager error with java versions higher than java 8
export JAVA_OPTS='-XX:+IgnoreUnrecognizedVMOptions --add-modules java.se.ee'
Run
source ~/.bashrc
Show all available sdk packages
sdkmanager --list
Identify latest android platform (here it's 28) and run
sdkmanager "platform-tools" "platforms;android-28"
Now you have adb, fastboot and the latest sdk tools installed
Using overloads or using C# 4.0 or above
private void GetVal(string sName, int sRoll)
{
if (sRoll > 0)
{
// do some work
}
}
private void GetVal(string sName)
{
GetVal("testing", 0);
}
Your character class (the part in the square brackets) is saying that you want to match anything except 0-9 and a-z and +. You aren't explicit about how many a-z or 0-9 you want to match, but I assume the + means you want to replace strings of at least one alphanumeric character. It should read instead:
str = str.replace(/[^-a-z0-9]+/g, "");
Also, if you need to match upper-case letters along with lower case, you should use:
str = str.replace(/[^-a-zA-Z0-9]+/g, "");
For future visitors - use this for range: ($A$1:$A$10)
Example
=COUNTIF($G$6:$G$9;J6)>0
Just to confirm: You are sure you are running MySQL 5.7, and not MySQL 5.6 or earlier version. And the plugin column contains "mysql_native_password". (Before MySQL 5.7, the password hash was stored in a column named password. Starting in MySQL 5.7, the password column is removed, and the password has is stored in the authentication_string column.) And you've also verified the contents of authentication string matches the return from PASSWORD('mysecret'). Also, is there a reason we are using DML against the mysql.user table instead of using the SET PASSWORD FOR syntax? – spencer7593
So Basically Just make sure that the Plugin Column contains "mysql_native_password".
Not my work but I read comments and noticed that this was stated as the answer but was not posted as a possible answer yet.
You're getting the error because result
defined as Sequential()
is just a container for the model and you have not defined an input for it.
Given what you're trying to build set result
to take the third input x3
.
first = Sequential()
first.add(Dense(1, input_shape=(2,), activation='sigmoid'))
second = Sequential()
second.add(Dense(1, input_shape=(1,), activation='sigmoid'))
third = Sequential()
# of course you must provide the input to result which will be your x3
third.add(Dense(1, input_shape=(1,), activation='sigmoid'))
# lets say you add a few more layers to first and second.
# concatenate them
merged = Concatenate([first, second])
# then concatenate the two outputs
result = Concatenate([merged, third])
ada_grad = Adagrad(lr=0.1, epsilon=1e-08, decay=0.0)
result.compile(optimizer=ada_grad, loss='binary_crossentropy',
metrics=['accuracy'])
However, my preferred way of building a model that has this type of input structure would be to use the functional api.
Here is an implementation of your requirements to get you started:
from keras.models import Model
from keras.layers import Concatenate, Dense, LSTM, Input, concatenate
from keras.optimizers import Adagrad
first_input = Input(shape=(2, ))
first_dense = Dense(1, )(first_input)
second_input = Input(shape=(2, ))
second_dense = Dense(1, )(second_input)
merge_one = concatenate([first_dense, second_dense])
third_input = Input(shape=(1, ))
merge_two = concatenate([merge_one, third_input])
model = Model(inputs=[first_input, second_input, third_input], outputs=merge_two)
ada_grad = Adagrad(lr=0.1, epsilon=1e-08, decay=0.0)
model.compile(optimizer=ada_grad, loss='binary_crossentropy',
metrics=['accuracy'])
To answer the question in the comments:
Concatenation works like this:
a b c
a b c g h i a b c g h i
d e f j k l d e f j k l
i.e rows are just joined.
x1
is input to first, x2
is input into second and x3
input into third.I can speak from experience on this, beware of nvarchar
. Unless you absolutely require it this data field type destroys performance on larger database. I inherited a database that was hurting in terms of performance and space. We were able to reduce a 30GB database in size by 70%! There were some other modifications made to help with performance but I'm sure the varchar
's helped out significantly with that as well. If your database has the potential for growing tables to a million + records stay away from nvarchar
at all costs.
... Thanks guys... all I needed was the 'value' of the checked radio button where each radio button in the set had a different id...
var user_cat = $("input[name='user_cat']:checked").val();
works for me...
Do dtEmp
on your current working DataTable:
DataTable distinctTable = dtEmp.DefaultView.ToTable( /*distinct*/ true);
It's nice.
I found the answer. IE stores passwords in two different locations based on the password type:
%APPDATA%\Microsoft\Credentials
, in encrypted filesHKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\IntelliForms\Storage2
, encrypted with the urlFrom a very good page on NirSoft.com:
Starting from version 7.0 of Internet Explorer, Microsoft completely changed the way that passwords are saved. In previous versions (4.0 - 6.0), all passwords were saved in a special location in the Registry known as the "Protected Storage". In version 7.0 of Internet Explorer, passwords are saved in different locations, depending on the type of password. Each type of passwords has some limitations in password recovery:
AutoComplete Passwords: These passwords are saved in the following location in the Registry:
HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\IntelliForms\Storage2
The passwords are encrypted with the URL of the Web sites that asked for the passwords, and thus they can only be recovered if the URLs are stored in the history file. If you clear the history file, IE PassView won't be able to recover the passwords until you visit again the Web sites that asked for the passwords. Alternatively, you can add a list of URLs of Web sites that requires user name/password into the Web sites file (see below).HTTP Authentication Passwords: These passwords are stored in the Credentials file under
Documents and Settings\Application Data\Microsoft\Credentials
, together with login passwords of LAN computers and other passwords. Due to security limitations, IE PassView can recover these passwords only if you have administrator rights.
In my particular case it answers the question of where; and I decided that I don't want to duplicate that. I'll continue to use CredRead
/CredWrite
, where the user can manage their passwords from within an established UI system in Windows.
I guess you should differentiate the target (before and after Oreo)
int LAYOUT_FLAG;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
LAYOUT_FLAG = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
} else {
LAYOUT_FLAG = WindowManager.LayoutParams.TYPE_PHONE;
}
params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
LAYOUT_FLAG,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
The reason your code fails is because post()
will start an asynchronous request to the server. What that means for you is that post()
returns immediately, not after the request completes, like you are expecting.
What you need, then, is for the request to be synchronous and block the current thread until the request completes. Thus,
var it_works = false;
$.ajax({
url: 'some_file.php',
async: false, # makes request synchronous
success: function() {
it_works = true;
}
});
alert(it_works);
You don't really need jQuery for this as there is a Media API that provides you with all you need.
var video = document.getElementById('myVideo');
video.src = 'my_video_' + value + '.ogg';
video.load();
The Media API also contains a load()
method which: "Causes the element to reset and start selecting and loading a new media resource from scratch."
(Ogg isn't the best format to use, as it's only supported by a limited number of browsers. I'd suggest using WebM and MP4 to cover all major browsers - you can use the canPlayType()
function to decide on which one to play).
You can then wait for either the loadedmetadata
or loadeddata
(depending on what you want) events to fire:
video.addEventListener('loadeddata', function() {
// Video is loaded and can be played
}, false);
for ( i = 0; i < total.length; i++ );
^-- remove the semi-colon here
With this semi-colon, the loop loops until i == total.length
, doing nothing, and then what you thought was the body of the loop is executed.
It's easy, if your mailx
command supports the -a
(append header) option:
$ mailx -a 'Content-Type: text/html' -s "my subject" [email protected] < email.html
If it doesn't, try using sendmail
:
# create a header file
$ cat mailheader
To: [email protected]
Subject: my subject
Content-Type: text/html
# send
$ cat mailheader email.html | sendmail -t
Many thanks for the information about using the QueryDefs collection! I have been wondering about this for a while.
I did it a different way, without using VBA, by using a table containing the query parameters.
E.g:
SELECT a_table.a_field
FROM QueryParameters, a_table
WHERE a_table.a_field BETWEEN QueryParameters.a_field_min
AND QueryParameters.a_field_max
Where QueryParameters
is a table with two fields, a_field_min
and a_field_max
It can even be used with GROUP BY
, if you include the query parameter fields in the GROUP BY
clause, and the FIRST
operator on the parameter fields in the HAVING
clause.
LGrind does this. It's a mature LaTeX package that's been around since adam was a cowboy and has support for many programming languages.
typedef enum state {DEAD,ALIVE} State;
| | | | | |^ terminating semicolon, required!
| | | type specifier | | |
| | | | ^^^^^ declarator (simple name)
| | | |
| | ^^^^^^^^^^^^^^^^^^^^^^^
| |
^^^^^^^-- storage class specifier (in this case typedef)
The typedef
keyword is a pseudo-storage-class specifier. Syntactically, it is used in the same place where a storage class specifier like extern
or static
is used. It doesn't have anything to do with storage. It means that the declaration doesn't introduce the existence of named objects, but rather, it introduces names which are type aliases.
After the above declaration, the State
identifier becomes an alias for the type enum state {DEAD,ALIVE}
. The declaration also provides that type itself. However that isn't typedef
doing it. Any declaration in which enum state {DEAD,ALIVE}
appears as a type specifier introduces that type into the scope:
enum state {DEAD, ALIVE} stateVariable;
If enum state
has previously been introduced the typedef
has to be written like this:
typedef enum state State;
otherwise the enum
is being redefined, which is an error.
Like other declarations (except function parameter declarations), the typedef
declaration can have multiple declarators, separated by a comma. Moreover, they can be derived declarators, not only simple names:
typedef unsigned long ulong, *ulongptr;
| | | | | 1 | | 2 |
| | | | | | ^^^^^^^^^--- "pointer to" declarator
| | | | ^^^^^^------------- simple declarator
| | ^^^^^^^^^^^^^-------------------- specifier-qualifier list
^^^^^^^---------------------------------- storage class specifier
This typedef
introduces two type names ulong
and ulongptr
, based on the unsigned long
type given in the specifier-qualifier list. ulong
is just a straight alias for that type. ulongptr
is declared as a pointer to unsigned long
, thanks to the *
syntax, which in this role is a kind of type construction operator which deliberately mimics the unary *
for pointer dereferencing used in expressions. In other words ulongptr
is an alias for the "pointer to unsigned long
" type.
Alias means that ulongptr
is not a distinct type from unsigned long *
. This is valid code, requiring no diagnostic:
unsigned long *p = 0;
ulongptr q = p;
The variables q
and p
have exactly the same type.
The aliasing of typedef
isn't textual. For instance if user_id_t
is a typedef
name for the type int
, we may not simply do this:
unsigned user_id_t uid; // error! programmer hoped for "unsigned int uid".
This is an invalid type specifier list, combining unsigned
with a typedef name. The above can be done using the C preprocessor:
#define user_id_t int
unsigned user_id_t uid;
whereby user_id_t
is macro-expanded to the token int
prior to syntax analysis and translation. While this may seem like an advantage, it is a false one; avoid this in new programs.
Among the disadvantages that it doesn't work well for derived types:
#define silly_macro int *
silly_macro not, what, you, think;
This declaration doesn't declare what
, you
and think
as being of type "pointer to int" because the macro-expansion is:
int * not, what, you, think;
The type specifier is int
, and the declarators are *not
, what
, you
and think
. So not
has the expected pointer type, but the remaining identifiers do not.
And that's probably 99% of everything about typedef
and type aliasing in C.
To do the conversion in respect of the current locale, you can use the strftime
function:
setlocale(LC_TIME, 'fr_FR.UTF-8');
$monthName = strftime('%B', mktime(0, 0, 0, $monthNumber));
date
doesn't respect the locale, strftime
does.
You can use lamba function:
index = df.index[lambda x : for x in df.index() ]
print(index)
It worked i used userdell --force USERNAME Some times eventhough -f and --force is same -f is not working sometimes After i removed the account i exit back to that removed username which i removed from root then what happened is this
If you don't use a passphrase, then the private key is not encrypted with any symmetric cipher - it is output completely unprotected.
You can generate a keypair, supplying the password on the command-line using an invocation like (in this case, the password is foobar
):
openssl genrsa -aes128 -passout pass:foobar 3072
However, note that this passphrase could be grabbed by any other process running on the machine at the time, since command-line arguments are generally visible to all processes.
A better alternative is to write the passphrase into a temporary file that is protected with file permissions, and specify that:
openssl genrsa -aes128 -passout file:passphrase.txt 3072
Or supply the passphrase on standard input:
openssl genrsa -aes128 -passout stdin 3072
You can also used a named pipe with the file:
option, or a file descriptor.
To then obtain the matching public key, you need to use openssl rsa
, supplying the same passphrase with the -passin
parameter as was used to encrypt the private key:
openssl rsa -passin file:passphrase.txt -pubout
(This expects the encrypted private key on standard input - you can instead read it from a file using -in <file>
).
Example of creating a 3072-bit private and public key pair in files, with the private key pair encrypted with password foobar
:
openssl genrsa -aes128 -passout pass:foobar -out privkey.pem 3072
openssl rsa -in privkey.pem -passin pass:foobar -pubout -out privkey.pub
Try this:
return Redirect("http://www.website.com");
sed -i s/$/:80/ file.txt
sed
stream editor
-i
in-place (edit file in place)s
substitution command/replacement_from_reg_exp/replacement_to_text/
statement$
matches the end of line (replacement_from_reg_exp):80
text you want to add at the end of every line (replacement_to_text)file.txt
the file nameselect *
from emp
where rownum <= &upperlimit
minus
select *
from emp
where rownum <= &lower limit ;
In my case, I was getting the error because I upgraded from Laravel Mix Version 2 to 5.
In Laravel Mix Version 2, you import vue components as follows:
Vue.component(
'example-component',
require('./components/ExampleComponent.vue')
);
In Laravel Mix Version 5, you have to import your components as follows:
import ExampleComponent from './components/ExampleComponent.vue';
Vue.component('example-component', ExampleComponent);
Here is the documentation: https://laravel-mix.com/docs/5.0/upgrade
Better, to improve performance of your app, you can lazy load your components as follows:
Vue.component("ExampleComponent", () => import("./components/ExampleComponent"));
```{r results='hide', message=FALSE, warning=FALSE}
library(RJSONIO)
library(AnotherPackage)
```
see Chunk Options in the Knitr docs
Use document height if you want to show it beyond the visible area of browser(scrollable area).
CSS Portion
#foo {
position:absolute;
top:0;
left:0;
}
JQuery Portion
$(document).ready(function() {
$('#foo').css({
width: $(document).width(),
height: $(document).height()
});
});
Great answers!
One thing that I would like to clarify deeper is nonatomic
/atomic
.
The user should understand that this property - "atomicity" spreads only on the attribute's reference and not on it's contents.
I.e. atomic
will guarantee the user atomicity for reading/setting the pointer and only the pointer to the attribute.
For example:
@interface MyClass: NSObject
@property (atomic, strong) NSDictionary *dict;
...
In this case it is guaranteed that the pointer to the dict
will be read/set in the atomic manner by different threads.
BUT the dict
itself (the dictionary dict
pointing to) is still thread unsafe, i.e. all read/add operations to the dictionary are still thread unsafe.
If you need thread safe collection you either have bad architecture (more often) OR real requirement (more rare). If it is "real requirement" - you should either find good&tested thread safe collection component OR be prepared for trials and tribulations writing your own one. It latter case look at "lock-free", "wait-free" paradigms. Looks like rocket-science at a first glance, but could help you achieving fantastic performance in comparison to "usual locking".
(new Double(d)).longValue()
internally just does a cast, so there's no reason to create a Double object.
//this gets you both the item (myItem.value) and its index (myItem.i)
@foreach (var myItem in Model.Members.Select((value,i) => new {i, value}))
{
<li>The index is @myItem.i and a value is @myItem.value.Name</li>
}
More info on my blog post http://jimfrenette.com/2012/11/razor-foreach-loop-with-index/
Truncate the contents of a variable
$ var="abcde"; echo ${var%d*}
abc
Make substitutions similar to sed
$ var="abcde"; echo ${var/de/12}
abc12
Use a default value
$ default="hello"; unset var; echo ${var:-$default}
hello
Create PROCEDURE Stored_Procedure_Name_2
(
@param1 int = 5 ,
@param2 varchar(max),
@param3 varchar(max)
)
AS
DECLARE @Table TABLE
(
/*TABLE DEFINITION*/
id int,
name varchar(max),
address varchar(max)
)
INSERT INTO @Table
EXEC Stored_Procedure_Name_1 @param1 , @param2 = 'Raju' ,@param3 =@param3
SELECT id ,name ,address FROM @Table
Three years later, I ran into the same problem. Here's my solution, everybody feel free to cut-n-paste. The simplest things keep us up all night! Running on an ATMega, and Adafruit Feather M0:
void setup() {
// turn on Serial so we can see...
Serial.begin(9600);
// the culprit:
uint8_t my_str[6]; // an array big enough for a 5 character string
// give it something so we can see what it's doing
my_str[0] = 'H';
my_str[1] = 'e';
my_str[2] = 'l';
my_str[3] = 'l';
my_str[4] = 'o';
my_str[5] = 0; // be sure to set the null terminator!!!
// can we see it?
Serial.println((char*)my_str);
// can we do logical operations with it as-is?
Serial.println((char*)my_str == 'Hello');
// okay, it can't; wrong data type (and no terminator!), so let's do this:
String str((char*)my_str);
// can we see it now?
Serial.println(str);
// make comparisons
Serial.println(str == 'Hello');
// one more time just because
Serial.println(str == "Hello");
// one last thing...!
Serial.println(sizeof(str));
}
void loop() {
// nothing
}
And we get:
Hello // as expected
0 // no surprise; wrong data type and no terminator in comparison value
Hello // also, as expected
1 // YAY!
1 // YAY!
6 // as expected
Hope this helps someone!
You are right, there is no datatype in SQL-Server which can hold a list of integers. But what you can do is store a list of integers as a string.
DECLARE @listOfIDs varchar(8000);
SET @listOfIDs = '1,2,3,4';
You can then split the string into separate integer values and put them into a table. Your procedure might already do this.
You can also use a dynamic query to achieve the same outcome:
DECLARE @SQL nvarchar(8000);
SET @SQL = 'SELECT * FROM TabA WHERE TabA.ID IN (' + @listOfIDs + ')';
EXECUTE (@SQL);
import win32com.client as win32
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = 'To address'
mail.Subject = 'Message subject'
mail.Body = 'Message body'
mail.HTMLBody = '<h2>HTML Message body</h2>' #this field is optional
# To attach a file to the email (optional):
attachment = "Path to the attachment"
mail.Attachments.Add(attachment)
mail.Send()
Will use your local outlook account to send.
Note if you are trying to do something not mentioned above, look at the COM docs properties/methods: https://msdn.microsoft.com/en-us/vba/outlook-vba/articles/mailitem-object-outlook. In the code above, mail
is a MailItem Object.
Complete example based on the excellent @Hackaholic's answer:
def get_process_id(name):
"""Return process ids found by (partial) name or regex.
>>> get_process_id('kthreadd')
[2]
>>> get_process_id('watchdog')
[10, 11, 16, 21, 26, 31, 36, 41, 46, 51, 56, 61] # ymmv
>>> get_process_id('non-existent process')
[]
"""
child = subprocess.Popen(['pgrep', '-f', name], stdout=subprocess.PIPE, shell=False)
response = child.communicate()[0]
return [int(pid) for pid in response.split()]
Tables ::
SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'
columns ::
SELECT * FROM INFORMATION_SCHEMA.COLUMNS
or
SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='your_table_name'
You can try something like this:
$scope.test = "test1,test2";
{{test.split(',')[0]}}
now you will get "test1" while you try {{test.split(',')[0]}}
and you will get "test2" while you try {{test.split(',')[1]}}
here is my plnkr:
I create a function on most SQL DB I work on to do just this.
CREATE OR ALTER FUNCTION [dbo].[UTIL_SplitList](@parList Varchar(MAX),@splitChar Varchar(1)=',')
Returns @t table (Column_Value varchar(MAX))
as
Begin
Declare @pos integer
set @pos = CharIndex(@splitChar, @parList)
while @pos > 0
Begin
Insert Into @t (Column_Value) VALUES (Left(@parList, @pos-1))
set @parList = Right(@parList, Len(@parList) - @pos)
set @pos = CharIndex(@splitChar, @parList)
End
Insert Into @t (Column_Value) VALUES (@parList)
Return
End
Once the function exists, it is as easy as
SELECT DISTINCT
*
FROM
[dbo].[UTIL_SplitList]('1,1,1,2,5,1,6',',')
Firstly create a class Instance and call the non-static method using that instance. e.g,
class demo {
public static void main(String args[]) {
demo d = new demo();
d.add(10,20); // to call the non-static method
}
public void add(int x ,int y) {
int a = x;
int b = y;
int c = a + b;
System.out.println("addition" + c);
}
}
Another easy way is to use the WC_Product_Factory class and then call function get_product(ID)
http://docs.woothemes.com/wc-apidocs/source-class-WC_Product_Factory.html#16-63
sample:
// assuming the list of product IDs is are stored in an array called IDs;
$_pf = new WC_Product_Factory();
foreach ($IDs as $id) {
$_product = $_pf->get_product($id);
// from here $_product will be a fully functional WC Product object,
// you can use all functions as listed in their api
}
You can then use all the function calls as listed in their api: http://docs.woothemes.com/wc-apidocs/class-WC_Product.html
You have your storyboard set up to expect an outlet called tableView
but the actual outlet name is myTableView
.
If you delete the connection in the storyboard and reconnect to the right variable name, it should fix the problem.
To move and delete specific records by selecting using WHERE query,
BEGIN TRANSACTION;
Insert Into A SELECT * FROM B where URL="" AND email ="" AND Annual_Sales_Vol="" And OPENED_In="" AND emp_count="" And contact_person= "" limit 0,2000;
delete from B where Id In (select Id from B where URL="" AND email ="" AND Annual_Sales_Vol="" And OPENED_In="" AND emp_count="" And contact_person= "" limit 0,2000);
commit;
I've seen some people promote 'package by feature' over 'package by layer' but I've used quite a few approaches over many years and found 'package by layer' much better than 'package by feature'.
Further to that I have found that a hybrid: 'package by module, layer then feature' strategy works extremely well in practice as it has many advantages of 'package by feature':
I explain in depth here: Java Package Name Structure and Organization but my standard package structure is:
revdomain.moduleType.moduleName.layer.[layerImpl].feature.subfeatureN.subfeatureN+1...
Where:
revdomain Reverse domain e.g. com.mycompany
moduleType [app*|framework|util]
moduleName e.g. myAppName if module type is an app or 'finance' if its an accounting framework
layer [model|ui|persistence|security etc.,]
layerImpl eg., wicket, jsp, jpa, jdo, hibernate (Note: not used if layer is model)
feature eg., finance
subfeatureN eg., accounting
subfeatureN+1 eg., depreciation
*Sometimes 'app' left out if moduleType is an application but putting it in there makes the package structure consistent across all module types.
a = ["foo","bar","baz",'bar','any','much']
indexes = [index for index in range(len(a)) if a[index] == 'bar']
IE doesn't allow this anymore (since Version 10, I believe) and will ignore such scripts. FF and Chrome still tolerate them, but there are chances that some day they will drop this as non-standard.
I like the bytes.Buffer struct. I see it has ReadFrom and String methods. I've used it with a []byte but not an io.Reader.
As per Angular2 final, you do not even have to import FORM_DIRECTIVES
as suggested above by many. However, the syntax has been changed as kebab-case was dropped for the betterment.
Just replace ng-model
with ngModel
and wrap it in a box of bananas. But you have spilt the code into two files now:
app.ts:
import { Component } from '@angular/core';
@Component({
selector: 'ng-app',
template: `
<input id="name" type="text" [(ngModel)]="name" />
{{ name }}
`
})
export class DataBindingComponent {
name: string;
constructor() {
this.name = 'Jose';
}
}
app.module.ts:
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { DataBindingComponent } from './app'; //app.ts above
@NgModule({
declarations: [DataBindingComponent],
imports: [BrowserModule, FormsModule],
bootstrap: [DataBindingComponent]
})
export default class MyAppModule {}
platformBrowserDynamic().bootstrapModule(MyAppModule);
Found this works for me:
In the link:
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#message<?php echo $row['id'];?>">Message</button>
In the modal:
<div id="message<?php echo $row['id'];?>" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
<?php echo $row['id'];?>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Ideally, you want to be using window.location.replace(...)
.
See this answer here for a full explanation: How do I redirect to another webpage?
Python is garbage-collected, so if you reduce the size of your list, it will reclaim memory. You can also use the "del" statement to get rid of a variable completely:
biglist = [blah,blah,blah]
#...
del biglist
For any object array with header and data.jsfiddle
https://jsfiddle.net/AmrendraKumar/9ac75Lg0/2/
<table id="myTable" border='1|1'></table>
<script>
const userObjectArray = [{
name: "Ajay",
age: 27,
height: 5.10,
address: "Bangalore"
}, {
name: "Vijay",
age: 24,
height: 5.10,
address: "Bangalore"
}, {
name: "Dinesh",
age: 27,
height: 5.10,
address: "Bangalore"
}];
const headers = Object.keys(userObjectArray[0]);
var tr1 = document.createElement('tr');
var htmlHeaderStr = '';
for (let i = 0; i < headers.length; i++) {
htmlHeaderStr += "<th>" + headers[i] + "</th>"
}
tr1.innerHTML = htmlHeaderStr;
document.getElementById('myTable').appendChild(tr1);
for (var j = 0; j < userObjectArray.length; j++) {
var tr = document.createElement('tr');
var htmlDataString = '';
for (var k = 0; k < headers.length; k++) {
htmlDataString += "<td>" + userObjectArray[j][headers[k]] + "</td>"
}
tr.innerHTML = htmlDataString;
document.getElementById('myTable').appendChild(tr);
}
</script>
There is a simple function subtract
which moment library gives us to subtract time from some time.
Using it is also very simple.
moment(Date.now()).subtract(7, 'days'); // This will subtract 7 days from current time
moment(Date.now()).subtract(3, 'd'); // This will subtract 3 days from current time
//You can do this for days, years, months, hours, minutes, seconds
//You can also subtract multiple things simulatneously
//You can chain it like this.
moment(Date.now()).subtract(3, 'd').subtract(5. 'h'); // This will subtract 3 days and 5 hours from current time
//You can also use it as object literal
moment(Date.now()).subtract({days:3, hours:5}); // This will subtract 3 days and 5 hours from current time
Hope this helps!
Just type the following command in terminal at the project directory and installation is done according the Laravel version:
composer require "laravelcollective/html"
Then add these lines in config/app.php
'providers' => [
// ...
Collective\Html\HtmlServiceProvider::class,
// ...
],
'aliases' => [
// ...
'Form' => Collective\Html\FormFacade::class,
'Html' => Collective\Html\HtmlFacade::class,
// ...
],
I would either one of the following:
Application.Exit();
for a winform or
Environment.Exit(0);
for a console application (works on winforms too).
Thanks!
With Java 8's lambdas, a convenient way is to use
org.mockito.invocation.InvocationOnMock
when(client.deleteByQuery(anyString(), anyString())).then(invocationOnMock -> {
assertEquals("myCollection", invocationOnMock.getArgument(0));
assertThat(invocationOnMock.getArgument(1), Matchers.startsWith("id:"));
}
When you get a UnicodeEncodeError
, it means that somewhere in your code you convert directly a byte string to a unicode one. By default in Python 2 it uses ascii encoding, and utf8 encoding in Python3 (both may fail because not every byte is valid in either encoding)
To avoid that, you must use explicit decoding.
If you may have 2 different encoding in your input file, one of them accepts any byte (say UTF8 and Latin1), you can try to first convert a string with first and use the second one if a UnicodeDecodeError occurs.
def robust_decode(bs):
'''Takes a byte string as param and convert it into a unicode one.
First tries UTF8, and fallback to Latin1 if it fails'''
cr = None
try:
cr = bs.decode('utf8')
except UnicodeDecodeError:
cr = bs.decode('latin1')
return cr
If you do not know original encoding and do not care for non ascii character, you can set the optional errors
parameter of the decode
method to replace
. Any offending byte will be replaced (from the standard library documentation):
Replace with a suitable replacement character; Python will use the official U+FFFD REPLACEMENT CHARACTER for the built-in Unicode codecs on decoding and ‘?’ on encoding.
bs.decode(errors='replace')
For those that are not familiar:
sudo chown -R YOUR_COMPUTER_USER_NAME PATH_OF_FILE
Bind the event to a parent which already exists:
$(document).on("click", "selector", function() {
// Your code here
});
The team size was about a dozen. For C# methods we had to put a huge XML formatted function before every function. I don't remember the format exactly but it involved XML tags nested about three to five levels deep. Here's a sketch from memory of the comment.
/// <comment>
/// </comment>
/// <table>
/// <thead>
/// <tcolumns>
/// <column>Date</column>
/// <column>Modified By</column>
/// <column>Comment</column>
/// </tcolumns>
/// </thead>
/// <rows>
/// <row>
/// <column>10/10/2006</column>
/// <column>Fred</column>
/// <column>Created function</column>
/// </row>
/// </rows>
/// <parameters>
I've got to stop there....
The downsides were many.
I used a code snippet (Emacs YAS) to add this code to my methods.
For this i looked into running LaTeX apps to generate a pdf. Although this option is likely to be far more complicated and heavy duty than the ones listed here.
Actually we can do it. we can set the file value default by using webbrowser control in c# using FormToMultipartPostData Library.We have to download and include this Library in our project. Webbrowser enables the user to navigate Web pages inside form. Once the web page loaded , the script inside the webBrowser1_DocumentCompleted will be executed. So,
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
FormToMultipartPostData postData =
new FormToMultipartPostData(webBrowser1, form);
postData.SetFile("fileField", @"C:\windows\win.ini");
postData.Submit();
}
Refer the below link for downloading and complete reference.
https://www.codeproject.com/Articles/28917/Setting-a-file-to-upload-inside-the-WebBrowser-com
This seems to work:
/descendant::input[@id="search_query"][2]
I go this from "XSLT 2.0 and XPath 2.0 Programmer's Reference, 4th Edition" by Michael Kay.
There is also a note in the "Abbreviated Syntax" section of the XML Path Language specification http://www.w3.org/TR/xpath/#path-abbrev that provided a clue.
I've had luck recovering the commit by looking at the reflog, which was located at .git/logs/HEAD
I then had to scoll down to the end of the file, and I found the commit I just lost.
Read up some on css, it's fun: http://www.w3.org/Style/Examples/007/units.en.html
<style>
.bottom-three {
margin-bottom: 3cm;
}
</style>
<p class="bottom-three">
This is the first question?
</p>
<p class="bottom-three">
This is the second question?
</p>
You forgot about Action-Domain-Responder (ADR).
As explained in some graphics above, there's a direct relation/link between the Model and the View in MVC. An action is performed on the Controller, which will execute an action on the Model. That action in the Model, will trigger a reaction in the View. The View, is always updated when the Model's state changes.
Some people keep forgetting, that MVC was created in the late 70", and that the Web was only created in late 80"/early 90". MVC wasn't originally created for the Web, but for Desktop applications instead, where the Controller, Model and View would co-exist together.
Because we use web frameworks (eg:. Laravel) that still use the same naming conventions (model-view-controller), we tend to think that it must be MVC, but it's actually something else.
Instead, have a look at Action-Domain-Responder.
In ADR, the Controller gets an Action, which will perform an operation in the Model/Domain. So far, the same.
The difference is, it then collects that operation's response/data, and pass it to a Responder (eg:. view()
) for rendering.
When a new action is requested on the same component, the Controller is called again, and the cycle repeats itself.
In ADR, there's no connection between the Model/Domain and the View (Reponser's response).
Note: Wikipedia states that "Each ADR action, however, is represented by separate classes or closures.". This is not necessarily true. Several Actions can be in the same Controller, and the pattern is still the same.
set android:dividerHeight="1dp"
<ListView
android:id="@+id/myphnview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@drawable/dividerheight"
android:background="#E9EAEC"
android:clickable="true"
android:divider="@color/white"
android:dividerHeight="1dp"
android:headerDividersEnabled="true" >
</ListView>
Try the following -
mylist = [1, 2, 3, 4]
def add(mylist):
total = 0
for i in mylist:
total += i
return total
result = add(mylist)
print("sum = ", result)
What happens here is the particular package is not available in the cache. Resetting will help solve the problem.
Goto terminal and build the project again
./gradlew build
This should download all the missing packages again
NOTE: This will only remove a device configuration from the Xcode devices list. To remove the simulator files from your hard drive see the previous answer.
For Xcode 7 just use Window \ Devices menu in Xcode:
Then select emulator to delete in the list on the left side and right click on it. Here is Delete option:
That's all.
Sounds like you're looking for rbind
:
> a<-matrix(nrow=10,ncol=5)
> b<-matrix(nrow=20,ncol=5)
> dim(rbind(a,b))
[1] 30 5
Similarly, cbind
stacks the matrices horizontally.
I am not entirely sure what you mean by the last question ("Can I do this for matrices of different rows and columns.?")
You can use color code also.
const marker: Marker = this.map.addMarkerSync({
icon: '#008000',
animation: 'DROP',
position: {lat: 39.0492127, lng: -111.1435662},
map: this.map,
});
In Rails 4.1.0, I have faced problem with saving latitude and longitude to MySql database. It can't save large fraction number with float data type. And I change the data type to decimal and working for me.
def change change_column :cities, :latitude, :decimal, :precision => 15, :scale => 13 change_column :cities, :longitude, :decimal, :precision => 15, :scale => 13 end
You have to add a CSP meta tag in the head section of your app's index.html
As per https://github.com/apache/cordova-plugin-whitelist#content-security-policy
Content Security Policy
Controls which network requests (images, XHRs, etc) are allowed to be made (via webview directly).
On Android and iOS, the network request whitelist (see above) is not able to filter all types of requests (e.g.
<video>
& WebSockets are not blocked). So, in addition to the whitelist, you should use a Content Security Policy<meta>
tag on all of your pages.On Android, support for CSP within the system webview starts with KitKat (but is available on all versions using Crosswalk WebView).
Here are some example CSP declarations for your
.html
pages:<!-- Good default declaration: * gap: is required only on iOS (when using UIWebView) and is needed for JS->native communication * https://ssl.gstatic.com is required only on Android and is needed for TalkBack to function properly * Disables use of eval() and inline scripts in order to mitigate risk of XSS vulnerabilities. To change this: * Enable inline JS: add 'unsafe-inline' to default-src * Enable eval(): add 'unsafe-eval' to default-src --> <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com; style-src 'self' 'unsafe-inline'; media-src *"> <!-- Allow requests to foo.com --> <meta http-equiv="Content-Security-Policy" content="default-src 'self' foo.com"> <!-- Enable all requests, inline styles, and eval() --> <meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'"> <!-- Allow XHRs via https only --> <meta http-equiv="Content-Security-Policy" content="default-src 'self' https:"> <!-- Allow iframe to https://cordova.apache.org/ --> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; frame-src 'self' https://cordova.apache.org">
You should use static_cast<char>(i)
to cast the integer i
to char
.
reinterpret_cast
should almost never be used, unless you want to cast one type into a fundamentally different type.
Also reinterpret_cast
is machine dependent so safely using it requires complete understanding of the types as well as how the compiler implements the cast.
For more information about C++ casting see:
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<style>_x000D_
table{_x000D_
border-spacing: 16px 4px;_x000D_
}_x000D_
_x000D_
td {_x000D_
border: 1px solid black;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<table style="width:100%">_x000D_
<tr>_x000D_
<td>Jill</td>_x000D_
<td>Smith</td> _x000D_
<td>50</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Eve</td>_x000D_
<td>Jackson</td> _x000D_
<td>94</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>John</td>_x000D_
<td>Doe</td> _x000D_
<td>80</td>_x000D_
</tr>_x000D_
</table>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
Using padding is not correct way of doing it, it may change the look but it is not what you wanted. This may solve your issue.
You have empty $_POST
. If your web-server wants see data in json-format you need to read the raw input and then parse it with JSON decode.
You need something like that:
$json = file_get_contents('php://input');
$obj = json_decode($json);
Also you have wrong code for testing JSON-communication...
CURLOPT_POSTFIELDS
tells curl
to encode your parameters as application/x-www-form-urlencoded
. You need JSON-string here.
UPDATE
Your php code for test page should be like that:
$data_string = json_encode($data);
$ch = curl_init('http://webservice.local/');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
$result = json_decode($result);
var_dump($result);
Also on your web-service page you should remove one of the lines header('Content-type: application/json');
. It must be called only once.
You can try to use this function if you need to round down to a specific number of decimal places
function roundDown(number, decimals) {
decimals = decimals || 0;
return ( Math.floor( number * Math.pow(10, decimals) ) / Math.pow(10, decimals) );
}
examples
alert(roundDown(999.999999)); // 999
alert(roundDown(999.999999, 3)); // 999.999
alert(roundDown(999.999999, -1)); // 990
please try to install the dependencie with pip, run this command:
sudo pip install -U setuptools
<script type="text/javascript">
function lnkLogout_Confirm()
{
var bResponse = confirm('Are you sure you want to exit?');
if (bResponse === true) {
////console.log("lnkLogout_Confirm clciked.");
var url = '@Url.Action("Login", "Login")';
window.location.href = url;
}
return bResponse;
}
</script>
These are ranked in order of difficulty to break your hidden info.
Store in cleartext
Store encrypted using a symmetric key
Using the Android Keystore
Store encrypted using asymmetric keys
source: Where is the best place to store a password in your Android app
The Keystore itself is encrypted using the user’s own lockscreen pin/password, hence, when the device screen is locked the Keystore is unavailable. Keep this in mind if you have a background service that could need to access your application secrets.
source: Simple use the Android Keystore to store passwords and other sensitive information
As an answer I say No. You can only get values from jstl to javascript. But u can display the user name using javascript itself. Best ways are here. To display user name, if u have html like
<div id="uName"></div>
You can display user name as follows.
var val1 = document.getElementById('userName').value;
document.getElementById('uName').innerHTML = val1;
var userName = '<c:out value="${user}"/>';
here ${user} is the data you get as response(from backend).
var arrayLength = <c:out value="${details.size()}"/>;
function advanced(){
var values = new Array();
<c:if test="${empty details.users}">
values.push("No user found");
</c:if>
<c:if test="${!empty details.users}">
<c:forEach var="user" items="${details.users}" varStatus="stat">
values.push("${user.name}");
</c:forEach>
</:c:if>
alert("values[0] "+values[0]);
});
Well, just to be different, I found an article that references using Reflection.Emit to do so.
Here's the link: http://www.codeproject.com/KB/cs/dotnetattributes.aspx , you will also want to look into some of the comments at the bottom of the article, because possible approaches are discussed.
I have tried to use the above robot there is a need to add a delay :( also you cannot debug or do something else because you lose the focus :(
//open upload window upload.click();
//put path to your image in a clipboard
StringSelection ss = new StringSelection(file.getAbsoluteFile());
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
//imitate mouse events like ENTER, CTRL+C, CTRL+V
Robot robot = new Robot();
robot.delay(250);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
robot.delay(50);
robot.keyRelease(KeyEvent.VK_ENTER);
Yes, according to RFC 3696 apostrophes are valid as long as they come before the @ symbol.
So there are few places where terminal looks for commands. This places are stored in your $PATH
variable. Think of it as a global variable where terminal iterates over to look up for any command. This are usually binaries look how /bin folder is usually referenced.
/bin
folder has lots of executable files inside it. Turns out this are command. This different folder locations are stored inside one Global variable i.e. $PATH
separated by :
Now usually programs upon installation takes care of updating PATH
& telling your terminal that hey i can be all commands inside my bin
folder.
Turns out MySql doesn't do it upon install so we manually have to do it.
We do it by following command,
export PATH=$PATH:/usr/local/mysql/bin
If you break it down, export
is self explanatory. Think of it as an assignment. So export
a variable PATH
with value old $PATH
concat with new bin
i.e. /usr/local/mysql/bin
This way after executing it all the commands inside /usr/local/mysql/bin
are available to us.
There is a small catch here. Think of one terminal window as one instance of program and maybe something like $PATH
is class variable ( maybe ). Note this is pure assumption. So upon close we lose the new assignment. And if we reopen terminal we won't have access to our command again because last when we exported, it was stored in primary memory which is volatile.
Now we need to have our mysql binaries exported every-time we use terminal. So we have to persist concat in our path.
You might be aware that our terminal using something called dotfiles
to load configuration on terminal initialisation. I like to think of it's as sets of thing passed to constructer every-time a new instance of terminal is created ( Again an assumption but close to what it might be doing ). So yes by now you get the point what we are going todo.
.bash_profile
is one of the primary known dotfile
.
So in following command,
echo 'export PATH=$PATH:/usr/local/mysql/bin' >> ~/.bash_profile
What we are doing is saving result of echo
i.e. output string to ~/.bash_profile
So now as we noted above every-time we open terminal or instance of terminal our dotfiles
are loaded. So .bash_profile
is loaded respectively and export
that we appended above is run & thus a our global $PATH
gets updated and we get all the commands inside /usr/local/mysql/bin
.
P.s.
if you are not running first command export directly but just running second in order to persist it? Than for current running instance of terminal you have to,
source ~/.bash_profile
This tells our terminal to reload that particular file.
A solution without dependencies.
Node
headers.set('Authorization', 'Basic ' + Buffer.from(username + ":" + password).toString('base64'));
Browser
headers.set('Authorization', 'Basic ' + btoa(username + ":" + password));
To stop apache process try this command
ps aux | grep tomcat | awk '{print $2}' | xargs kill -9
If you prefer not to write your own function, try check.integer
from package installr. Currently it uses VitoshKa's answer.
Also try check.numeric(v, only.integer=TRUE)
from package varhandle, which has the benefit of being vectorized.
As explained by this answer, the exact location of the string pool is not specified and can vary from one JVM implementation to another.
It is interesting to note that until Java 7, the pool was in the permgen space of the heap on hotspot JVM but it has been moved to the main part of the heap since Java 7:
Area: HotSpot
Synopsis: In JDK 7, interned strings are no longer allocated in the permanent generation of the Java heap, but are instead allocated in the main part of the Java heap (known as the young and old generations), along with the other objects created by the application. This change will result in more data residing in the main Java heap, and less data in the permanent generation, and thus may require heap sizes to be adjusted. Most applications will see only relatively small differences in heap usage due to this change, but larger applications that load many classes or make heavy use of the String.intern() method will see more significant differences. RFE: 6962931
And in Java 8 Hotspot, Permanent Generation has been completely removed.
If you are solely interested in outputting the JSON somewhere in your HTML, you could also use a pipe inside an interpolation. For example:
<p> {{ product | json }} </p>
I am not entirely sure it works for every AngularJS version, but it works perfectly in my Ionic App (which uses Angular 2+).
I think the answer is here (possibly duplicate):
How to test if a file is a directory in a batch script?
IF EXIST %VAR%\NUL ECHO It's a directory
Replace %VAR% with your directory. Please read the original answer because includes details about handling white spaces in the folder name.
As foxidrive said, this might not be reliable on NT class windows. It works for me, but I know it has some limitations (which you can find in the referenced question)
if exist "c:\folder\" echo folder exists
should be enough for modern windows.
declare @MyNumber int
set @MyNumber = 123
select 'My number is ' + CAST(@MyNumber as nvarchar(20))
You can directly specify the item's alignment, for example:
textright: {
alignSelf: 'flex-end',
},
from scipy.optimize import fsolve
def double_solve(f1,f2,x0,y0):
func = lambda x: [f1(x[0], x[1]), f2(x[0], x[1])]
return fsolve(func,[x0,y0])
def n_solve(functions,variables):
func = lambda x: [ f(*x) for f in functions]
return fsolve(func, variables)
f1 = lambda x,y : x**2+y**2-1
f2 = lambda x,y : x-y
res = double_solve(f1,f2,1,0)
res = n_solve([f1,f2],[1.0,0.0])
If you are looking for a form reset:
<input type="reset" value="Reset Form Values"/>
or to reset other aspects of the form not handled by the browser
<input type="reset" onclick="doFormReset();" value="Reset Form Values"/>
Using jQuery
function doFormReset(){
$(".invalid").removeClass("invalid");
}
You can also do this in Kate.
If you just want to execute the shell command in your c program, you could use,
#include <stdlib.h>
int system(const char *command);
In your case,
system("pwd");
The issue is that there isn't an executable file called "pwd" and I'm unable to execute "echo $PWD", since echo is also a built-in command with no executable to be found.
What do you mean by this? You should be able to find the mentioned packages in /bin/
sudo find / -executable -name pwd
sudo find / -executable -name echo
Whenever I have to do something like this I just become root:
# sudo -s
# ls -hal /root/ > /root/test.out
# exit
It's probably not the best way, but it works.
qrcode-generator on Github. Simplest script and works like charm.
Pros:
Here's the issue: You can't specify font weights that don't exist in the font set from Google. Click on the SEE SPECIMEN link below the font, then scroll down to the STYLES section. There you'll see each of the "styles" available for that particular font. Sadly Google doesn't list the CSS font weights for each style. Here's how the names map to CSS font weight numbers:
Thin 100
Extra Light 200
Light 300
Regular 400
Medium 500
Semi-Bold 600
Bold 700
Extra-Bold 800
Black 900
Note that very few fonts come in all 9 weights.
After t.thielemans' answer, I worked that just
=VLOOKUP(A1, B:C, 2, FALSE)
works fine and does what I wanted, except that it returns #N/A
for non-matches; so it is suitable for the case where it is known that the value definitely exists in the look-up column.
Edit (based on t.thielemans' comment):
To avoid #N/A
for non-matches, do:
=IFERROR(VLOOKUP(A1, B:C, 2, FALSE), "No Match")
ok, Im using mac to generate my self signed keys. Here is the working method I used.
I created a shell script to speed up my key generation.
genkey.sh
#/bin/sh
ssh-keygen -f host.key
openssl req -new -key host.key -out request.csr
openssl x509 -req -days 99999 -in request.csr -signkey host.key -out server.crt
openssl pkcs12 -export -inkey host.key -in server.crt -out private_public.p12 -name "SslCert"
openssl base64 -in private_public.p12 -out Base64.key
add the +x execute flag to the script
chmod +x genkey.sh
then call genkey.sh
./genkey.sh
I enter a password (important to include a password at least for the export at the end)
Enter pass phrase for host.key:
Enter Export Password: {Important to enter a password here}
Verifying - Enter Export Password: { Same password here }
I then take everything in Base64.Key and put it into a string named sslKey
private string sslKey = "MIIJiAIBA...................................." +
"......................ETC...................." +
"......................ETC...................." +
"......................ETC...................." +
".............ugICCAA=";
I then used a lazy load Property getter to get my X509 Cert with a private key.
X509Certificate2 _serverCertificate = null;
X509Certificate2 serverCertificate{
get
{
if (_serverCertificate == null){
string pass = "Your Export Password Here";
_serverCertificate = new X509Certificate(Convert.FromBase64String(sslKey), pass, X509KeyStorageFlags.Exportable);
}
return _serverCertificate;
}
}
I wanted to go this route because I am using .net 2.0 and Mono on mac and I wanted to use vanilla Framework code with no compiled libraries or dependencies.
My final use for this was the SslStream to secure TCP communication to my app
SslStream sslStream = new SslStream(serverCertificate, false, SslProtocols.Tls, true);
I hope this helps other people.
NOTE
Without a password I was unable to correctly unlock the private key for export.
May be include Jquery Widget first, then Draggable? I guess that will solve the problem.....
Try and override bootstrap's:
.modal {
position: fixed;
With:
.modal {
position: absolute;
It worked for me.
Initializing the contents of a list like that isn't really what lists are for. Lists are designed to hold objects. If you want to map particular numbers to particular objects, consider using a key-value pair structure like a hash table or dictionary instead of a list.
Sign in and the 30 day trial will go away!
"And if you're already signed in, sign out then sign in again." –b1nary.atr0phy
In Windows you can use a Powershell Script with CompareObject
compare-object -IncludeEqual -ExcludeDifferent -PassThru (get-content A.txt) (get-content B.txt)> MATCHING.txt | Out-Null #Find Matching Lines
CompareObject:
Tick 'Full Index Enabled' and then 'Rebuild Index' of the central repository in 'Global Repositories' under Window > Show View > Other > Maven > Maven Repositories
, and it should work.
The rebuilding may take a long time depending on the speed of your internet connection, but eventually it works.
Are these really lists (ordered, with duplicates), or are they sets (unordered, no duplicates)?
Because if it's the latter, then you can use, say, a java.util.HashSet<E>
and do this in expected linear time using the convenient retainAll
.
List<String> list1 = Arrays.asList(
"milan", "milan", "iga", "dingo", "milan"
);
List<String> list2 = Arrays.asList(
"hafil", "milan", "dingo", "meat"
);
// intersection as set
Set<String> intersect = new HashSet<String>(list1);
intersect.retainAll(list2);
System.out.println(intersect.size()); // prints "2"
System.out.println(intersect); // prints "[milan, dingo]"
// intersection/union as list
List<String> intersectList = new ArrayList<String>();
intersectList.addAll(list1);
intersectList.addAll(list2);
intersectList.retainAll(intersect);
System.out.println(intersectList);
// prints "[milan, milan, dingo, milan, milan, dingo]"
// original lists are structurally unmodified
System.out.println(list1); // prints "[milan, milan, iga, dingo, milan]"
System.out.println(list2); // prints "[hafil, milan, dingo, meat]"
Simply
if(isset($_POST['filename'])){
$filename = $_POST['filename'];
echo $filename;
}
else{
echo "POST filename is not assigned";
}
I'm developing a scientific calculator that sports an Int button. I've found the following is a simple, reliable solution:
double dblInteger;
if( dblNumber < 0 )
dblInteger = Math.Ceiling(dblNumber);
else
dblInteger = Math.Floor(dblNumber);
Math.Round sometimes produces unexpected or undesirable results, and explicit conversion to integer (via cast or Convert.ToInt...) often produces wrong values for higher-precision numbers. The above method seems to always work.
This issue is caused by the URL bars shrinking/sliding out of the way and changing the size of the #bg1 and #bg2 divs since they are 100% height and "fixed". Since the background image is set to "cover" it will adjust the image size/position as the containing area is larger.
Based on the responsive nature of the site, the background must scale. I entertain two possible solutions:
1) Set the #bg1, #bg2 height to 100vh. In theory, this an elegant solution. However, iOS has a vh bug (http://thatemil.com/blog/2013/06/13/viewport-relative-unit-strangeness-in-ios-6/). I attempted using a max-height to prevent the issue, but it remained.
2) The viewport size, when determined by Javascript, is not affected by the URL bar. Therefore, Javascript can be used to set a static height on the #bg1 and #bg2 based on the viewport size. This is not the best solution as it isn't pure CSS and there is a slight image jump on page load. However, it is the only viable solution I see considering iOS's "vh" bugs (which do not appear to be fixed in iOS 7).
var bg = $("#bg1, #bg2");
function resizeBackground() {
bg.height($(window).height());
}
$(window).resize(resizeBackground);
resizeBackground();
On a side note, I've seen so many issues with these resizing URL bars in iOS and Android. I understand the purpose, but they really need to think through the strange functionality and havoc they bring to websites. The latest change, is you can no longer "hide" the URL bar on page load on iOS or Chrome using scroll tricks.
EDIT: While the above script works perfectly for keeping the background from resizing, it causes a noticeable gap when users scroll down. This is because it is keeping the background sized to 100% of the screen height minus the URL bar. If we add 60px to the height, as swiss suggests, this problem goes away. It does mean we don't get to see the bottom 60px of the background image when the URL bar is present, but it prevents users from ever seeing a gap.
function resizeBackground() {
bg.height( $(window).height() + 60);
}
You can always do Object.getOwnPropertyNames(myObject).length
to get the same result as [].length
would give for normal array.
This worked for me:
python3 -m venv env
source ./env/bin/activate
python -m pip install package
(From Github: https://github.com/googlesamples/assistant-sdk-python/issues/236 )
Fastest way for Android Studio 3.x.x and Android Studio 4.x.x
1.Go to the design tab of the activity layout
2.At the top you should press on the orientation for preview button, there is a option to create a landscape layout (check image), a new folder will be created as your xml layout file for that particular orientation
I assumed openjdk8 would work with tomcat8 but I had to remove it and keep openjdk7 only, this fixed the issue in my case. I really don't know why or if there is something else I could have done.
This might be a bit late, but i also had the same issue. Converting to char was addressed in C++17 with the "charconv" library.
I guess I'm a bit late on this question but I'll write something anyway for anyone having the same problem. This is the same answer as I gave to this question.
My problem was that I'd like my application to be a GUI application but the processes executed should be run in the background without any interactive console window attached. I think this solution should also work when the parent process is a console process. You may have to remove the "CREATE_NO_WINDOW" flag though.
I managed to solve this using GenerateConsoleCtrlEvent() with a wrapper app. The tricky part is just that the documentation is not really clear on exactly how it can be used and the pitfalls with it.
My solution is based on what is described here. But that didn't really explain all the details either and with an error, so here is the details on how to get it working.
Create a new helper application "Helper.exe". This application will sit between your application (parent) and the child process you want to be able to close. It will also create the actual child process. You must have this "middle man" process or GenerateConsoleCtrlEvent() will fail.
Use some kind of IPC mechanism to communicate from the parent to the helper process that the helper should close the child process. When the helper get this event it calls "GenerateConsoleCtrlEvent(CTRL_BREAK, 0)" which closes down itself and the child process. I used an event object for this myself which the parent completes when it wants to cancel the child process.
To create your Helper.exe create it with CREATE_NO_WINDOW and CREATE_NEW_PROCESS_GROUP. And when creating the child process create it with no flags (0) meaning it will derive the console from its parent. Failing to do this will cause it to ignore the event.
It is very important that each step is done like this. I've been trying all different kinds of combinations but this combination is the only one that works. You can't send a CTRL_C event. It will return success but will be ignored by the process. CTRL_BREAK is the only one that works. Doesn't really matter since they will both call ExitProcess() in the end.
You also can't call GenerateConsoleCtrlEvent() with a process groupd id of the child process id directly allowing the helper process to continue living. This will fail as well.
I spent a whole day trying to get this working. This solution works for me but if anyone has anything else to add please do. I went all over the net finding lots of people with similar problems but no definite solution to the problem. How GenerateConsoleCtrlEvent() works is also a bit weird so if anyone knows more details on it please share.
First
Make a dir c:\command
Second Make a ll.bat
ll.bat
dir
Definitely not the ideal solution, but it's easier for me to understand if I convert the list into tuples and then sort it.
mylist = [[1,2,3,4],[4,5,6,7]]
mylist2 = []
for thing in mylist:
thing = tuple(thing)
mylist2.append(thing)
set(mylist2)
Check this answer: https://stackoverflow.com/a/7346598/1764509
$.getJSON("test.json", function(json) {
console.log(json); // this will show the info it in firebug console
});
I was also trying to run Spring Boot application in Eclipse, without any plugins.
Step 1
Right click on your project. Select "Run As" -> "Maven build...". Then in "Goals" field, enter "spring-boot:run". Apply & Run.
After this you do not have to Run again.
Step 2
After making any change, clean your project. After cleaning, it automatically builds the project once. Then when you will refresh your pages on browser, change will be reflected.
Sharing host display :0, as stated in some other answers, has two drawbacks:
xev
or xinput
is possible, and remote control of host applications with xdotool
. --ipc=host
).Below an example script to run a docker image in Xephyr that addresses this issues.
--cap-drop ALL --security-opt no-new-privileges
. Also the container user is not root.The script expects some arguments, first a host window manager to run in Xephyr, second a docker image, optionally third an image command to be executed. To run a desktop environment in docker, use ":" instead of a host window manager.
Closing Xephyr window terminates docker container applications. Terminating the dockered applications closes Xephyr window.
Examples:
xephyrdocker "openbox --sm-disable" x11docker/lxde pcmanfm
xephyrdocker : x11docker/lxde
xephyrdocker xfwm4 --device /dev/snd jess/nes /games/zelda.rom
xephyrdocker script:
#! /bin/bash
#
# Xephyrdocker: Example script to run docker GUI applications in Xephyr.
#
# Usage:
# Xephyrdocker WINDOWMANAGER DOCKERIMAGE [IMAGECOMMAND [ARGS]]
#
# WINDOWMANAGER host window manager for use with single GUI applications.
# To run without window manager from host, use ":"
# DOCKERIMAGE docker image containing GUI applications or a desktop
# IMAGECOMMAND command to run in image
#
Windowmanager="$1" && shift
Dockerimage="$*"
# Container user
Useruid=$(id -u)
Usergid=$(id -g)
Username="$(id -un)"
[ "$Useruid" = "0" ] && Useruid=1000 && Usergid=1000 && Username="user$Useruid"
# Find free display number
for ((Newdisplaynumber=1 ; Newdisplaynumber <= 100 ; Newdisplaynumber++)) ; do
[ -e /tmp/.X11-unix/X$Newdisplaynumber ] || break
done
Newxsocket=/tmp/.X11-unix/X$Newdisplaynumber
# cache folder and files
Cachefolder=/tmp/Xephyrdocker_X$Newdisplaynumber
[ -e "$Cachefolder" ] && rm -R "$Cachefolder"
mkdir -p $Cachefolder
Xclientcookie=$Cachefolder/Xcookie.client
Xservercookie=$Cachefolder/Xcookie.server
Xinitrc=$Cachefolder/xinitrc
Etcpasswd=$Cachefolder/passwd
# command to run docker
# --rm created container will be discarded.
# -e DISPLAY=$Newdisplay set environment variable to new display
# -e XAUTHORITY=/Xcookie set environment variable XAUTHORITY to provided cookie
# -v $Xclientcookie:/Xcookie:ro provide cookie file to container
# -v $NewXsocket:$NewXsocket:ro Share new X socket of Xephyr
# --user $Useruid:$Usergid Security: avoid root in container
# -v $Etcpasswd:/etc/passwd:ro /etc/passwd file with user entry
# --group-add audio Allow access to /dev/snd if shared with '--device /dev/snd'
# --cap-drop ALL Security: disable needless capabilities
# --security-opt no-new-privileges Security: forbid new privileges
Dockercommand="docker run --rm \
-e DISPLAY=:$Newdisplaynumber \
-e XAUTHORITY=/Xcookie \
-v $Xclientcookie:/Xcookie:ro \
-v $Newxsocket:$Newxsocket:rw \
--user $Useruid:$Usergid \
-v $Etcpasswd:/etc/passwd:ro \
--group-add audio \
--env HOME=/tmp \
--cap-drop ALL \
--security-opt no-new-privileges \
$(command -v docker-init >/dev/null && echo --init) \
$Dockerimage"
echo "docker command:
$Dockercommand
"
# command to run Xorg or Xephyr
# /usr/bin/Xephyr an absolute path to X server executable must be given for xinit
# :$Newdisplaynumber first argument has to be new display
# -auth $Xservercookie path to cookie file for X server. Must be different from cookie file of client, not sure why
# -extension MIT-SHM disable MIT-SHM to avoid rendering glitches and bad RAM access (+ instead of - enables it)
# -nolisten tcp disable tcp connections for security reasons
# -retro nice retro look
Xcommand="/usr/bin/Xephyr :$Newdisplaynumber \
-auth $Xservercookie \
-extension MIT-SHM \
-nolisten tcp \
-screen 1000x750x24 \
-retro"
echo "X server command:
$Xcommand
"
# create /etc/passwd with unprivileged user
echo "root:x:0:0:root:/root:/bin/sh" >$Etcpasswd
echo "$Username:x:$Useruid:$Usergid:$Username,,,:/tmp:/bin/sh" >> $Etcpasswd
# create xinitrc
{ echo "#! /bin/bash"
echo "# set environment variables to new display and new cookie"
echo "export DISPLAY=:$Newdisplaynumber"
echo "export XAUTHORITY=$Xclientcookie"
echo "# same keyboard layout as on host"
echo "echo '$(setxkbmap -display $DISPLAY -print)' | xkbcomp - :$Newdisplaynumber"
echo "# create new XAUTHORITY cookie file"
echo ":> $Xclientcookie"
echo "xauth add :$Newdisplaynumber . $(mcookie)"
echo "# create prepared cookie with localhost identification disabled by ffff,"
echo "# needed if X socket is shared instead connecting over tcp. ffff means 'familiy wild'"
echo 'Cookie=$(xauth nlist '":$Newdisplaynumber | sed -e 's/^..../ffff/')"
echo 'echo $Cookie | xauth -f '$Xclientcookie' nmerge -'
echo "cp $Xclientcookie $Xservercookie"
echo "chmod 644 $Xclientcookie"
echo "# run window manager in Xephyr"
echo $Windowmanager' & Windowmanagerpid=$!'
echo "# show docker log"
echo 'tail --retry -n +1 -F '$Dockerlogfile' 2>/dev/null & Tailpid=$!'
echo "# run docker"
echo "$Dockercommand"
} > $Xinitrc
xinit $Xinitrc -- $Xcommand
rm -Rf $Cachefolder
This script is maintained at x11docker wiki. A more advanced script is x11docker that also supports features like GPU acceleration, webcam and printer sharing and so on.
I like to declare a modifier for changing the background color of a view.
extension View {
func background(with color: Color) -> some View {
background(GeometryReader { geometry in
Rectangle().path(in: geometry.frame(in: .local)).foregroundColor(color)
})
}
}
Then I use the modifier by passing in a color to a view.
struct Content: View {
var body: some View {
Text("Foreground Label").foregroundColor(.green).background(with: .black)
}
}
Your list just contains a string. Convert it to integer IDs:
L = ['350882 348521 350166\r\n']
ids = [int(i) for i in L[0].strip().split()]
print(ids)
id = 348521
if id not in ids:
ids.append(id)
print(ids)
id = 348522
if id not in ids:
ids.append(id)
print(ids)
# Turn it back into your odd format
L = [' '.join(str(id) for id in ids) + '\r\n']
print(L)
Output:
[350882, 348521, 350166]
[350882, 348521, 350166]
[350882, 348521, 350166, 348522]
['350882 348521 350166 348522\r\n']
I once tried to make a computer player for the game of Go, exclusively based on genetic programming. Each program would be treated as an evaluation function for a sequence of moves. The programs produced weren't very good though, even on a rather diminuitive 3x4 board.
I used Perl, and coded everything myself. I would do things differently today.
if (input == undefined) { ... }
works just fine. It is of course not a null
comparison, but I usually find that if I need to distinguish between undefined
and null
, I actually rather need to distinguish between undefined
and just any false value, so
else if (input) { ... }
does it.
If a program redefines undefined
it is really braindead anyway.
The only reason I can think of was for IE4 compatibility, it did not understand the undefined
keyword (which is not actually a keyword, unfortunately), but of course values could be undefined
, so you had to have this:
var undefined;
and the comparison above would work just fine.
In your second example, you probably need double parentheses to make lint happy?
I was struggling with this exact issue for three days. I had set permissions on the script to 755. I had been calling my script as follows.
<?php
$outcome = shell_exec('/tmp/clearUp.sh');
echo $outcome;
?>
My script was as follows.
#!bin/bash
find . -maxdepth 1 -name "search*.csv" -mmin +0 -exec rm {} \;
I was getting no output or feedback. The change I made to get the script to run was to add a cd to tmp inside the script:
#!bin/bash
cd /tmp;
find . -maxdepth 1 -name "search*.csv" -mmin +0 -exec rm {} \;
This was more by luck than judgement but it is now working perfectly. I hope this helps.
If you want to ensure the values in the resultant List<Value>
are in the key-ordering of the input Map<Key, Value>
, you need to "go via" SortedMap
somehow.
Either start with a concrete SortedMap
implementation (Such as TreeMap
) or insert your input Map
into a SortedMap
before converting that to List
. e.g.:
Map<Key,Value> map;
List<Value> list = new ArrayList<Value>( new TreeMap<Key Value>( map ));
Otherwise you'll get whatever native ordering the Map
implementation provides, which can often be something other than the natural key ordering (Try Hashtable
or ConcurrentHashMap
, for variety).
kubectl create can work with one object configuration file at a time. This is also known as imperative management
kubectl create -f filename|url
kubectl apply works with directories and its sub directories containing object configuration yaml files. This is also known as declarative management. Multiple object configuration files from directories can be picked up. kubectl apply -f directory/
Details :
https://kubernetes.io/docs/tasks/manage-kubernetes-objects/declarative-config/
https://kubernetes.io/docs/tasks/manage-kubernetes-objects/imperative-config/
I use the latest version of SSMS or sql server management studio. I have a SQL script (in query editor) which has about 100 lines of code. This is error I got in the query:
Msg 245, Level 16, State 1, Line 2
Conversion failed when converting the nvarchar value 'abcd' to data type int.
Solution - I had seen this kind of error before when I forgot to enclose a number (in varchar column) in single quotes.
As an aside, the error message is misleading. The actual error on line number 70 in the query editor and not line 2 as the error says!
Even if fileno(FILE *)
may return a file descriptor, be VERY careful not to bypass stdio's buffer. If there is buffer data (either read or unflushed write), reads/writes from the file descriptor might give you unexpected results.
To answer one of the side questions, to convert a file descriptor to a FILE pointer, use fdopen(3)
I use either BloodShed's DEV C++, CygWin, or Visual C++ Express. All of which are free and work well. I have found that for me, DEV C++ worked the best and was the least quirky. Each compiler has it's own quirks and deifferences, you need to try out a few and find the one with which you are most comfortable. I also liked the fact that DEV C++ allowed me to change the fonts that are used in the editor. I like Proggy Programming fonts!
From your description, it looks like that you want to "reserve" the allocated storage space of vector t_Names.
Take note that resize
initialize the newly allocated vector where reserve
just allocates but does not construct. Hence, 'reserve' is much faster than 'resize'
You can refer to the documentation regarding the difference of resize and reserve
You want to restrict to input fields that are of type text so use the selector input[type=text]
rather than input
(which will apply to all input fields (e.g. those of type submit as well)).
I found that this can happen if the referenced project is targeting a higher version of the framework than the project that is trying to use it. You can tell if this is the problem by going to the output window and looking for something similar to this:
The primary reference "my_reference" could not be resolved because it was built against the ".NETFramework,Version=v4.7.2" framework. This is a higher version than the currently targeted framework ".NETFramework,Version=v4.7".
The solution is to change the target framework of one or other of the projects.
There are many uses for the **null** value in the Boolean wrapper! :)
For example, you may have in a form a field named "newsletter" that indicate if the user want or doesn't want a newsletter from your site. If the user doesn't select a value in this field, you may want to implement a default behaviour to that situation (send? don't send?, question again?, etc) . Clearly, not set (or not selected or **null**), is not the same that true or false.
But, if "not set" doesn't apply to your model, don't change the boolean primitive ;)
I found solution in this post: https://stackoverflow.com/questions/11883378/class-memcache-not-found-php#=
I found the working dll files for PHP 5.4.4
I don't knowhow stable they are but they work for sure. Credits goes to this link.
http://x32.elijst.nl/php_memcache-5.4-nts-vc9-x86.zip
http://x32.elijst.nl/php_memcache-5.4-vc9-x86.zip
It is the 2.2.5.0 version, I noticed after compiling it (for PHP 5.4.4).
Please note that it is not 2.2.6 but works. I also mirrored them in my own FTP. Mirror links:
http://mustafabugra.com/resim/php_memcache-5.4-vc9-x86.zip http://mustafabugra.com/resim/php_memcache-5.4-nts-vc9-x86.zip
The command pm clear com.android.browser
requires root permission.
So, run su
first.
Here is the sample code:
private static final String CHARSET_NAME = "UTF-8";
String cmd = "pm clear com.android.browser";
ProcessBuilder pb = new ProcessBuilder().redirectErrorStream(true).command("su");
Process p = pb.start();
// We must handle the result stream in another Thread first
StreamReader stdoutReader = new StreamReader(p.getInputStream(), CHARSET_NAME);
stdoutReader.start();
out = p.getOutputStream();
out.write((cmd + "\n").getBytes(CHARSET_NAME));
out.write(("exit" + "\n").getBytes(CHARSET_NAME));
out.flush();
p.waitFor();
String result = stdoutReader.getResult();
The class StreamReader
:
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.concurrent.CountDownLatch;
class StreamReader extends Thread {
private InputStream is;
private StringBuffer mBuffer;
private String mCharset;
private CountDownLatch mCountDownLatch;
StreamReader(InputStream is, String charset) {
this.is = is;
mCharset = charset;
mBuffer = new StringBuffer("");
mCountDownLatch = new CountDownLatch(1);
}
String getResult() {
try {
mCountDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
return mBuffer.toString();
}
@Override
public void run() {
InputStreamReader isr = null;
try {
isr = new InputStreamReader(is, mCharset);
int c = -1;
while ((c = isr.read()) != -1) {
mBuffer.append((char) c);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (isr != null)
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
mCountDownLatch.countDown();
}
}
}
As mentioned above several times, it's not possible to catch a StackOverflowException that was raised by the System due to corrupted process-state. But there's a way to notice the exception as an event:
http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspxStarting with the .NET Framework version 4, this event is not raised for exceptions that corrupt the state of the process, such as stack overflows or access violations, unless the event handler is security-critical and has the HandleProcessCorruptedStateExceptionsAttribute attribute.
Nevertheless your application will terminate after exiting the event-function (a VERY dirty workaround, was to restart the app within this event haha, havn't done so and never will do). But it's good enough for logging!
In the .NET Framework versions 1.0 and 1.1, an unhandled exception that occurs in a thread other than the main application thread is caught by the runtime and therefore does not cause the application to terminate. Thus, it is possible for the UnhandledException event to be raised without the application terminating. Starting with the .NET Framework version 2.0, this backstop for unhandled exceptions in child threads was removed, because the cumulative effect of such silent failures included performance degradation, corrupted data, and lockups, all of which were difficult to debug. For more information, including a list of cases in which the runtime does not terminate, see Exceptions in Managed Threads.
There is a brand new version of Jsch up on github: https://github.com/vngx/vngx-jsch Some of the improvements include: comprehensive javadoc, enhanced performance, improved exception handling, and better RFC spec adherence. If you wish to contribute in any way please open an issue or send a pull request.
Right click on the project
->Run As
--> Run configurations
.
Then select Maven Build
Then click new button to create a configuration of the selected type. Click on Browse workspace
(now is Workspace...
) then select your project and in goals specify eclipse:eclipse
If at all possible, its always a good idea to create your XML using the XML classes rather than string manipulation - one of the benefits being that the classes will automatically escape characters as needed.
Here's an algorithm for elegant, in-place replacement. Tested with Python 2.7 and Python 3.5. Using the dot character as a separator.
def flatten_json(json):
if type(json) == dict:
for k, v in list(json.items()):
if type(v) == dict:
flatten_json(v)
json.pop(k)
for k2, v2 in v.items():
json[k+"."+k2] = v2
Example:
d = {'a': {'b': 'c'}}
flatten_json(d)
print(d)
unflatten_json(d)
print(d)
Output:
{'a.b': 'c'}
{'a': {'b': 'c'}}
I published this code here along with the matching unflatten_json
function.
Now that you know the difference between char * const a
and const char * a
. Many times we get confused if its a constant pointer or pointer to a constant variable.
How to read it? Follow the below simple step to identify between upper two.
Lets see how to read below declaration
char * const a;
read from Right to Left
Now start with a
,
1 . adjacent to a
there is const
.
char * (const a)
;
---> So a
is a constant
(????)
.
2 . Now go along you get *
char (* (const a))
;
---> So a
is a constant
pointer
to (????)
.
3 . Go along and there is char
(char (* (const a)))
;
---> a
is a constant
pointer
to character
variable
a is constant pointer to character variable.
Isn't it easy to read?
Similarily for second declaration
const char * a;
Now again start with a
,
1 . Adjacent to a
there is *
---> So a
is a pointer
to (????)
2 . Now there is char
---> so a
is pointer
character
,
Well that doesn't make any sense!!! So shuffle pointer
and character
---> so a
is character
pointer
to (?????)
3 . Now you have constant
---> so a
is character
pointer
to constant
variable
But though you can make out what declaration means, lets make it sound more sensible.
a is pointer to constant character variable
Here is a simple customview for display circle progress. You can modify and optimize more to suitable for your project.
class CircleProgressBar @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
private val backgroundWidth = 10f
private val progressWidth = 20f
private val backgroundPaint = Paint().apply {
color = Color.LTGRAY
style = Paint.Style.STROKE
strokeWidth = backgroundWidth
isAntiAlias = true
}
private val progressPaint = Paint().apply {
color = Color.RED
style = Paint.Style.STROKE
strokeWidth = progressWidth
isAntiAlias = true
}
var progress: Float = 0f
set(value) {
field = value
invalidate()
}
private val oval = RectF()
private var centerX: Float = 0f
private var centerY: Float = 0f
private var radius: Float = 0f
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
centerX = w.toFloat() / 2
centerY = h.toFloat() / 2
radius = w.toFloat() / 2 - progressWidth
oval.set(centerX - radius,
centerY - radius,
centerX + radius,
centerY + radius)
super.onSizeChanged(w, h, oldw, oldh)
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
canvas?.drawCircle(centerX, centerY, radius, backgroundPaint)
canvas?.drawArc(oval, 270f, 360f * progress, false, progressPaint)
}
}
Example using
xml
<com.example.androidcircleprogressbar.CircleProgressBar
android:id="@+id/circle_progress"
android:layout_width="200dp"
android:layout_height="200dp" />
kotlin
class MainActivity : AppCompatActivity() {
val TOTAL_TIME = 10 * 1000L
override fun onCreate(savedInstanceState: Bundle?) {
...
timeOutRemoveTimer.start()
}
private var timeOutRemoveTimer = object : CountDownTimer(TOTAL_TIME, 10) {
override fun onFinish() {
circle_progress.progress = 1f
}
override fun onTick(millisUntilFinished: Long) {
circle_progress.progress = (TOTAL_TIME - millisUntilFinished).toFloat() / TOTAL_TIME
}
}
}
Result
To reload the same page you don't need the 2nd argument. You can just use:
<meta http-equiv="refresh" content="30" />
This triggers a reload every 30 seconds.