To add a header just add the following code to the location block where you want to add the header:
location some-location {
add_header X-my-header my-header-content;
}
Obviously, replace the x-my-header and my-header-content with what you want to add. And that's all there is to it.
I also faced it and encorrected it like below successfully.
File > Settings > Build, Execution, Deployment > Gradle > Use local gradle distribution
Set the home path as : C:/Program Files/Android/Android Studio/gradle/gradle-version
You may need to upgrade your gradle version.
I will suppose your JPanel contains JTextField, for the sake of the demo.
Those components provides JTextComponent#setMargin()
method which seems to be what you're looking for.
If you're looking for an empty border of any size around your text, well, use EmptyBorder
Swift 4 solution:
UIApplication.shared.open(NSURL(string:"http://yo.lo")! as URL, options: [String : Any](), completionHandler: nil)
Just for the sake of performance, I tested all the answers given here:
var substringTest = function (str) {
return str.substring(str.lastIndexOf('/')+1);
}
var replaceTest = function (str) {
return str.replace(/^.*(\\|\/|\:)/, '');
}
var execTest = function (str) {
return /([^\\]+)$/.exec(str)[1];
}
var splitTest = function (str) {
return str.split('\\').pop().split('/').pop();
}
substringTest took 0.09508600000000023ms
replaceTest took 0.049203000000000004ms
execTest took 0.04859899999999939ms
splitTest took 0.02505500000000005ms
And the winner is the Split and Pop style answer, Thanks to bobince !
Posting a new answer since it is 2019.
TLDR: AMD is now supported on both Windows and Linux via WHPX and yes, Genymotion is faster as it is using x86 architecture virtualization.
From the Android docs (January 2019):
Though we recommend using HAXM on Windows, it is possible to use Windows Hypervisor Platform (WHPX) with the emulator. You should use WHPX with the emulator if you are using an AMD CPU or if you need to use Hyper-V at the same time.
To use WHPX acceleration on Windows, you must enable the Windows Hypervisor Platform option in the Turn Windows features on or off dialog box. For changes to this option to take effect, restart your computer.
Additionally, the following changes must be made in the BIOS settings:
Intel CPU: VT-x must be enabled. AMD CPU: Virtualization or SVM must be enabled.
Diff from 2016:
Virtualization extension requirements
Before attempting to use acceleration, you should first determine if your CPU supports one of the following virtualization extensions technologies:
- Intel Virtualization Technology (VT, VT-x, vmx) extensions
- AMD Virtualization (AMD-V, SVM) extensions
(only supported for Linux)Most modern computers do. If you use an older computer and you're not sure, consult the specifications from the manufacturer of your CPU to determine if it supports virtualization extensions. If your CPU doesn't support one of these virtualization technologies, then you can't use VM acceleration.
Virtualization extensions are typically enabled through your computer BIOS and are frequently turned off by default. Check the documentation for your motherboard to find out how to enable virtualization extensions.
This is a quicker fix in one-liner.
Hope this will help.
// WAIT FOR 200 MILISECONDS TO GET DATA //
await setTimeout(()=>{}, 200);
Also if you're using 3rd party libraries make sure you have the correct 32/64 bit binaries
try {
JSONObject jsonObject = new JSONObject(response.body().string());
System.out.println(jsonObject);
} catch (JSONException | IOException e ) {
e.printStackTrace();
}
This doesn't work in IE6, which may be an issue, but it'll work in IE7+ and Firefox, Safari etc. It'll align the 3rd column right and all of the subsequent columns left.
td + td + td { text-align: right; }
td + td + td + td { text-align: left; }
I believe that if you run git branch --all
from Bash that the list of remote and local branches you see will reflect what your local Git "knows" about at the time you run the command. Because your Git is always up to date with regard to the local branches in your system, the list of local branches will always be accurate.
However, for remote branches this need not be the case. Your local Git only knows about remote branches which it has seen in the last fetch (or pull). So it is possible that you might run git branch --all
and not see a new remote branch which appeared after the last time you fetched or pulled.
To ensure that your local and remote branch list be up to date you can do a git fetch
before running git branch --all
.
For further information, the "remote" branches which appear when you run git branch --all
are not really remote at all; they are actually local. For example, suppose there be a branch on the remote called feature
which you have pulled at least once into your local Git. You will see origin/feature
listed as a branch when you run git branch --all
. But this branch is actually a local Git branch. When you do git fetch origin
, this tracking branch gets updated with any new changes from the remote. This is why your local state can get stale, because there may be new remote branches, or your tracking branches can become stale.
Spring has something called a AnnotatedTypeScanner
class.
This class internally uses
ClassPathScanningCandidateComponentProvider
This class has the code for actual scanning of the classpath resources. It does this by using the class metadata available at runtime.
One can simply extend this class or use the same class for scanning. Below is the constructor definition.
/**
* Creates a new {@link AnnotatedTypeScanner} for the given annotation types.
*
* @param considerInterfaces whether to consider interfaces as well.
* @param annotationTypes the annotations to scan for.
*/
public AnnotatedTypeScanner(boolean considerInterfaces, Class<? extends Annotation>... annotationTypes) {
this.annotationTypess = Arrays.asList(annotationTypes);
this.considerInterfaces = considerInterfaces;
}
I am highlighting the solution in both 1.9 and 2.0 since it is useful for some
In 1.9
, I think the better solution is to save the file to disk and use it as Typed file like:
(I don't know about your server-side implementation) have an API interface method similar to this
@POST("/en/Api/Results/UploadFile")
void UploadFile(@Part("file") TypedFile file,
@Part("folder") String folder,
Callback<Response> callback);
And use it like
TypedFile file = new TypedFile("multipart/form-data",
new File(path));
API Interface:
public interface ApiInterface {
@Multipart
@POST("/api/Accounts/editaccount")
Call<User> editUser(@Header("Authorization") String authorization,
@Part("file\"; filename=\"pp.png\" ") RequestBody file,
@Part("FirstName") RequestBody fname,
@Part("Id") RequestBody id);
}
Use it like:
File file = new File(imageUri.getPath());
RequestBody fbody = RequestBody.create(MediaType.parse("image/*"),
file);
RequestBody name = RequestBody.create(MediaType.parse("text/plain"),
firstNameField.getText()
.toString());
RequestBody id = RequestBody.create(MediaType.parse("text/plain"),
AZUtils.getUserId(this));
Call<User> call = client.editUser(AZUtils.getToken(this),
fbody,
name,
id);
call.enqueue(new Callback<User>() {
@Override
public void onResponse(retrofit.Response<User> response,
Retrofit retrofit) {
AZUtils.printObject(response.body());
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
});
You have to just add the index_col=False
parameter
df1 = pd.read_csv('foo.csv',
header=0,
index_col=False,
names=["dummy", "date", "loc", "x"],
usecols=["dummy", "date", "loc", "x"],
parse_dates=["date"])
print df1
Note : Everything up here is correct,just replace sort --> sort_values() So, it becomes:
import pandas as pd
df = pd.read_csv('data.csv')
df.sort_values(ascending=False,inplace=True)
Refer to the official website here.
If you already have your code setup and you don’t want to make changes on the different interfaces you can, use the solution described in this link.
The main point is the method changeApiBaseUrl
that updates the URL and recreates the Retrofit builder.
public class ServiceGenerator {
public static String apiBaseUrl = "http://futurestud.io/api";
private static Retrofit retrofit;
private static Retrofit.Builder builder =
new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(apiBaseUrl);
private static OkHttpClient.Builder httpClient =
new OkHttpClient.Builder();
// No need to instantiate this class.
private ServiceGenerator() {
}
public static void changeApiBaseUrl(String newApiBaseUrl) {
apiBaseUrl = newApiBaseUrl;
builder = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(apiBaseUrl);
}
public static <S> S createService(Class<S> serviceClass, AccessToken token) {
String authToken = token.getTokenType().concat(token.getAccessToken());
return createService(serviceClass, authToken);
}
// more methods
// ...
}
You can use it as follows:
public class DynamicBaseUrlActivity extends AppCompatActivity {
public static final String TAG = "CallInstances";
private Callback<ResponseBody> downloadCallback;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_file_upload);
downloadCallback = new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.d(TAG, "server contacted at: " + call.request().url());
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.d(TAG, "call failed against the url: " + call.request().url());
}
};
// first request
FileDownloadService downloadService = ServiceGenerator.create(FileDownloadService.class);
Call<ResponseBody> originalCall = downloadService.downloadFileWithFixedUrl();
originalCall.enqueue(downloadCallback);
// change base url
ServiceGenerator.changeApiBaseUrl("http://development.futurestud.io/api");
// new request against new base url
FileDownloadService newDownloadService = ServiceGenerator.create(FileDownloadService.class);
Call<ResponseBody> newCall = newDownloadService.downloadFileWithFixedUrl();
newCall.enqueue(downloadCallback);
}
}
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTest {
public static void main(String[] args) {
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
Date date = new Date(timestamp.getTime());
// S is the millisecond
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy' 'HH:mm:ss:S");
System.out.println(simpleDateFormat.format(timestamp));
System.out.println(simpleDateFormat.format(date));
}
}
call listView.scheduleLayoutAnimation(); before changing the list
you can read a text from a text file in to string as follows also
string str = "";
StreamReader sr = new StreamReader(Application.StartupPath + "\\Sample.txt");
while(sr.Peek() != -1)
{
str = str + sr.ReadLine();
}
I am using kue: https://github.com/learnboost/kue . It is pretty nice.
The official features and my comments:
Edit:
The easiest way is probably just to use list()
, but there is at least one other option as well:
s = "Word to Split"
wordlist = list(s) # option 1,
wordlist = [ch for ch in s] # option 2, list comprehension.
They should both give you what you need:
['W','o','r','d',' ','t','o',' ','S','p','l','i','t']
As stated, the first is likely the most preferable for your example but there are use cases that may make the latter quite handy for more complex stuff, such as if you want to apply some arbitrary function to the items, such as with:
[doSomethingWith(ch) for ch in s]
$name = 'file.pdf';
//file_get_contents is standard function
$content = file_get_contents($name);
header('Content-Type: application/pdf');
header('Content-Length: '.strlen( $content ));
header('Content-disposition: inline; filename="' . $name . '"');
header('Cache-Control: public, must-revalidate, max-age=0');
header('Pragma: public');
header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
echo $content;
Go to you MainActivity.java
and below this code
-> NavigationView navigationView = findViewById(R.id.nav_view);
Add single line of code -> navigationView.setItemIconTintList(null);
i.e. the last line of my code
I hope this might solve your problem.
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setItemIconTintList(null);
As with @Kametrixom answer here I believe returning an array would be better than returning AnySequence, since you can have access to all of Array's goodies such as count, etc.
Here's the re-write:
public protocol EnumCollection : Hashable {}
extension EnumCollection {
public static func allValues() -> [Self] {
typealias S = Self
let retVal = AnySequence { () -> AnyGenerator<S> in
var raw = 0
return AnyGenerator {
let current : Self = withUnsafePointer(&raw) { UnsafePointer($0).memory }
guard current.hashValue == raw else { return nil }
raw += 1
return current
}
}
return [S](retVal)
}
}
I found this blog post which explains the problem very well, and defines a few different solutions:
(dead link removed)
I've settled for the idea that the best way to do it is to completely omit the XML declaration when in memory. It actually is UTF-16 at that point anyway, but the XML declaration doesn't seem meaningful until it has been written to a file with a particular encoding; and even then the declaration is not required. It doesn't seem to break deserialization, at least.
As @Jon Hanna mentions, this can be done with an XmlWriter created like this:
XmlWriter writer = XmlWriter.Create (output, new XmlWriterSettings() { OmitXmlDeclaration = true });
Change
Range(DataImportColumn & DataImportRow).Offset(0, 2).Value
to
Cells(DataImportRow,DataImportColumn).Value
When you just have the row and the column then you can use the cells()
object. The syntax is Cells(Row,Column)
Also one more tip. You might want to fully qualify your Cells
object. for example
ThisWorkbook.Sheets("WhatEver").Cells(DataImportRow,DataImportColumn).Value
The stable of APC is having option to clear a cache in its interface itself. To clear those entries you must login to apc interface.
APC is having option to set username and password in apc.php file.
All the answers that I can see here, including the currently "accepted" one, is actually wrong in that they set:
scrollTop = scrollHeight
Whereas the correct approach is to set:
scrollTop = scrollHeight - clientHeight
In other words:
$('#div1').scrollTop($('#div1')[0].scrollHeight - $('#div1')[0].clientHeight);
Or animated:
$("#div1").animate({
scrollTop: $('#div1')[0].scrollHeight - $('#div1')[0].clientHeight
}, 1000);
The html
data attribute does exactly what it says it does in the docs. Try this little example, no JavaScript necessary (broken into lines for clarification):
<span rel="tooltip"
data-toggle="tooltip"
data-html="true"
data-title="<table><tr><td style='color:red;'>complex</td><td>HTML</td></tr></table>"
>
hover over me to see HTML
</span>
JSFiddle demos:
I'm working with Angular2 and SCSS, as a best practice I copied to my project only the bootstrap files that I'm modifying the other are imported from node_modules.. the only problem was with Glyphicons. After many tries I found that the best solution to me is to copy the font files to my project and set directly this path to $ icon-font-path as shown in the image:
packed
means it will use the smallest possible space for struct Ball
- i.e. it will cram fields together without paddingaligned
means each struct Ball
will begin on a 4 byte boundary - i.e. for any struct Ball
, its address can be divided by 4These are GCC extensions, not part of any C standard.
I found a solution on this site where someone had a valuable comment:
The solution is:
if (Function('/*@cc_on return document.documentMode===10@*/')()){
document.documentElement.className+=' ie10';
}
It
>>> [[int(i) for i in line.strip().split(',')] for line in open('input.txt').readlines()]
[[995957, 16833579], [995959, 16777241], [995960, 16829368], [995961, 50431654]]
In case somebody wonders what is the faster way to filter (the accepted answer or the one from @redreamality):
import pandas as pd
import numpy as np
length = 100_000
df = pd.DataFrame()
df['Year'] = np.random.randint(1950, 2019, size=length)
df['Gender'] = np.random.choice(['Male', 'Female'], length)
%timeit df.query('Gender=="Male" & Year=="2014" ')
%timeit df[(df['Gender']=='Male') & (df['Year']==2014)]
Results for 100,000 rows:
6.67 ms ± 557 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
5.54 ms ± 536 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Results for 10,000,000 rows:
326 ms ± 6.52 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
472 ms ± 25.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
So results depend on the size and the data. On my laptop, query()
gets faster after 500k rows. Further, the string search in Year=="2014"
has an unnecessary overhead (Year==2014
is faster).
Look here: http://www.w3schools.com/tags/tag_p.asp
The p element automatically creates some space before and after itself. The space is automatically applied by the browser, or you can specify it in a style sheet.
you could remove the extra space by using css
p {
margin: 0px;
padding: 0px;
}
or use the element <span>
which has no default margins and is an inline element.
FileZilla does not have any command line arguments (nor any other way) that allow an automatic transfer.
Some references:
Though you can use any other client that allows automation.
You have not specified, what protocol you are using. FTP or SFTP? You will definitely be able to use WinSCP, as it supports all protocols that FileZilla does (and more).
Combine WinSCP scripting capabilities with Windows Scheduler:
A typical WinSCP script for upload (with SFTP) looks like:
open sftp://user:[email protected]/ -hostkey="ssh-rsa 2048 xxxxxxxxxxx...="
put c:\mypdfs\*.pdf /home/user/
close
With FTP, just replace the sftp://
with the ftp://
and remove the -hostkey="..."
switch.
Similarly for download: How to schedule an automatic FTP download on Windows?
WinSCP can even generate a script from an imported FileZilla session.
For details, see the guide to FileZilla automation.
(I'm the author of WinSCP)
Another option, if you are using SFTP, is the psftp.exe
client from PuTTY suite.
Has anyone mentioned std::call_once
and std::once_flag
?
Most other approaches - including double checked locking - are broken.
One major problem in singleton pattern implementation is safe initialization. The only safe way is to guard the initialization sequence with synchronizing barriers. But those barriers themselves need to be safely initiated. std::once_flag
is the mechanism to get guaranteed safe initialization.
For asp.net users, the .NET framework provides a class to create a content disposition header: System.Net.Mime.ContentDisposition
Basic usage:
var cd = new System.Net.Mime.ContentDisposition();
cd.FileName = "myFile.txt";
cd.ModificationDate = DateTime.UtcNow;
cd.Size = 100;
Response.AppendHeader("content-disposition", cd.ToString());
You have some data that is being entered by users somewhere in the application.
the component in which the data is being entered should have this data in its state because it needs to manipulate and change it during data entry
anywhere else in the application the data should be passed down as props to all the other components
So yes the props are changing but they are changed at the 'source' and will then simply flow down from there. So props are immutable in the context of the component receiving them.
E.g. a reference data screen where users edit a list of suppliers would manage this in state, which would then have an action cause the updated data to be saved in ReferenceDataState which could be one level below AppState and then this supplier list would be passed as props to all the components that needed to use it.
This is one solution. If you want to make it more generic, you can use the StringUtils
library.
String value = "{first_name = naresh,last_name = kumar,gender = male}";
value = value.substring(1, value.length()-1); //remove curly brackets
String[] keyValuePairs = value.split(","); //split the string to creat key-value pairs
Map<String,String> map = new HashMap<>();
for(String pair : keyValuePairs) //iterate over the pairs
{
String[] entry = pair.split("="); //split the pairs to get key and value
map.put(entry[0].trim(), entry[1].trim()); //add them to the hashmap and trim whitespaces
}
For example you can switch
value = value.substring(1, value.length()-1);
to
value = StringUtils.substringBetween(value, "{", "}");
if you are using StringUtils
which is contained in apache.commons.lang
package.
$(document).ready(function() {
$('select#select_2').change(function() {
var selectedText = $(this).find('option:selected').text();
alert(selectedText);
});
});
This error message comes specifically from the XDebug extension. PHP itself does not have a function nesting limit. Change the setting in your php.ini:
xdebug.max_nesting_level = 200
or in your PHP code:
ini_set('xdebug.max_nesting_level', 200);
As for if you really need to change it (i.e.: if there's a alternative solution to a recursive function), I can't tell without the code.
As long as you do not allow NULL for a value, they should be handled the same, but the value NULL is handled differently on databases(AFAIK MS-SQL do not allow more than one(1) NULL value, mySQL and Oracle allow this, if a column is UNIQUE) So you must define this column NOT NULL UNIQUE INDEX
Using EntityFramework, you can go with a solution like this. I use this code to initialize e2e tests. De prevent sql injection attacks, make sure not to generate this script based on user input or use command parameters for this (see overload of ExecuteSqlCommand that accepts parameters).
public static void ExecuteSqlScript(string sqlScript)
{
using (MyEntities dataModel = new MyEntities())
{
// split script on GO commands
IEnumerable<string> commands =
Regex.Split(
sqlScript,
@"^\s*GO\s*$",
RegexOptions.Multiline | RegexOptions.IgnoreCase);
foreach (string command in commands)
{
if (command.Trim() != string.Empty)
{
dataModel.Database.ExecuteSqlCommand(command);
}
}
}
}
&&
and ||
take scalar inputs and short-circuit always. |
and &
take array inputs and short-circuit only in if/while statements. For assignment, the latter do not short-circuit.
See these doc pages for more information.
If you didn't change anything related to certificates (didn't replace or update them) just do a Product -> Clean
. It helped me several times. (Xcode 6.2)
you can use WeakMaps for implementing private property in ES6 class and benefits of String propeties and methods in JavaScript language like below:
const _items = new WeakMap();
class Stack {
constructor() {
_items.set(this, []);
}
push(obj) {
_items.get(this).push(obj);
}
pop() {
const L = _items.get(this).length;
if(L===0)
throw new Error('Stack is empty');
return _items.get(this).pop();
}
peek() {
const items = _items.get(this);
if(items.length === 0)
throw new Error ('Stack is empty');
return items[items.length-1];
}
get count() {
return _items.get(this).length;
}
}
const stack = new Stack();
//now in console:
//stack.push('a')
//stack.push(1)
//stack.count => 2
//stack.peek() => 1
//stack.pop() => 1
//stack.pop() => "a"
//stack.count => 0
//stack.pop() => Error Stack is empty
$cs = mysql_query("describe tbl_info");
$column_count = mysql_num_rows($cs);
Or just:
$column_count = mysql_num_rows(mysql_query("describe tbl_info"));
C is a only programming language its used in system programming. but embedded C is used to implement the projects like real time applications
The px to pt fix worked for me on a site that uses a font from Google Web Fonts. On Win7 - IE8 it correctly fixed the lack of anti-alias rendering.
My own experience has been that it's best to stick to one of two kinds of assembly references:
I've found (much like you've described) other methods to either be too easily broken or have annoying maintenance requirements.
Any assembly I don't want to GAC, has to live in the execution directory. Any assembly that isn't or can't be in the execution directory I GAC (managed by automatic build events).
This hasn't given me any problems so far. While I'm sure there's a situation where it won't work, the usual answer to any problem has been "oh, just GAC it!". 8 D
Hope that helps!
<pre><form name="myform" method="post" enctype="multipart/form-data">
<input type="text" id="name" name="name" />
<input type="submit"/>
</form></pre>
<script language="JavaScript" type="text/javascript">
var frmvalidator = new Validator("myform");
frmvalidator.EnableFocusOnError(false);
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("name","req","Plese Enter Name");
</script>
Note: before using the code above you have to add the gen_validatorv31.js
file.
OK - what you're missing is that its designed to be more industrial and serve many sites, so the config you want is probably:
/etc/apache2/sites-available/default
which on my system is linked to from /etc/apache2/sites-enabled/
if you want to have different sites with different options, copy the file and then change those...
As paxdiablo said make -f pax.mk
would execute the pax.mk makefile, if you directly execute it by typing ./pax.mk, then you would get syntax error.
Also you can just type make
if your file name is makefile/Makefile
.
Suppose you have two files named makefile
and Makefile
in the same directory then makefile
is executed if make
alone is given. You can even pass arguments to makefile.
Check out more about makefile at this Tutorial : Basic understanding of Makefile
I upgraded from 2010 to 2013 and after changing all the projects' Platform Toolset, I need to right-click on the Solution and choose Retarget... to make it work.
This code works well for returning all of the IP addresses that might belong to a particular URI. Since many systems are now in a hosted environment (AWS/Akamai/etc.), systems may return several IP addresses. The lambda was "borrowed" from @Peter Silva.
def get_ips_by_dns_lookup(target, port=None):
'''
this function takes the passed target and optional port and does a dns
lookup. it returns the ips that it finds to the caller.
:param target: the URI that you'd like to get the ip address(es) for
:type target: string
:param port: which port do you want to do the lookup against?
:type port: integer
:returns ips: all of the discovered ips for the target
:rtype ips: list of strings
'''
import socket
if not port:
port = 443
return list(map(lambda x: x[4][0], socket.getaddrinfo('{}.'.format(target),port,type=socket.SOCK_STREAM)))
ips = get_ips_by_dns_lookup(target='google.com')
I had the same problem you did - didn't find much that worked. The following code, however, works like a charm.
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6) # "6" refers to the index of a folder - in this case,
# the inbox. You can change that number to reference
# any other folder
messages = inbox.Items
message = messages.GetLast()
body_content = message.body
print body_content
You can use Web SQL API which is an ordinary SQLite database in your browser and you can open/modify it like any other SQLite databases for example with Lita.
Chrome locates databases automatically according to domain names or extension id. A few months ago I posted on my blog short article on how to delete Chrome's database because when you're testing some functionality it's quite useful.
The performance benefit is from not having to reopen the file once the #pragma once have been read. With guards, the compiler have to open the file (that can be costly in time) to get the information that it shouldn't include it's content again.
That is theory only because some compilers will automatically not open files that didn't have any read code in, for each compilation unit.
Anyway, it's not the case for all compilers, so ideally #pragma once have to be avoided for cross-platform code has it's not standard at all / have no standardized definition and effect. However, practically, it's really better than guards.
In the end, the better suggestion you can get to be sure to have the best speed from your compiler without having to check the behavior of each compiler in this case, is to use both pragma once and guards.
#ifndef NR_TEST_H
#define NR_TEST_H
#pragma once
#include "Thing.h"
namespace MyApp
{
// ...
}
#endif
That way you get the best of both (cross-platform and help compilation speed).
As it's longer to type, I personally use a tool to help generate all that in a very wick way (Visual Assist X).
SQL Server databases use two files - an MDF file, known as the primary database file, which contains the schema and data, and a LDF file, which contains the logs. See wikipedia. A database may also use secondary database file, which normally uses a .ndf extension.
As John S. indicates, these file extensions are purely convention - you can use whatever you want, although I can't think of a good reason to do that.
More info on MSDN here and in Beginning SQL Server 2005 Administation (Google Books) here.
So, based on the 'button in header' solution, here is a clean and minimalist implementation:
Here is the code:
@interface MyTableViewController ()
@property (nonatomic, strong) NSMutableIndexSet *collapsedSections;
@end
...
@implementation MyTableViewController
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (!self)
return;
self.collapsedSections = [NSMutableIndexSet indexSet];
return self;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// if section is collapsed
if ([self.collapsedSections containsIndex:section])
return 0;
// if section is expanded
#warning incomplete implementation
return [super tableView:tableView numberOfRowsInSection:section];
}
- (IBAction)toggleSectionHeader:(UIView *)sender
{
UITableView *tableView = self.tableView;
NSInteger section = sender.tag;
MyTableViewHeaderFooterView *headerView = (MyTableViewHeaderFooterView *)[self tableView:tableView viewForHeaderInSection:section];
if ([self.collapsedSections containsIndex:section])
{
// section is collapsed
headerView.button.selected = YES;
[self.collapsedSections removeIndex:section];
}
else
{
// section is expanded
headerView.button.selected = NO;
[self.collapsedSections addIndex:section];
}
[tableView beginUpdates];
[tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationAutomatic];
[tableView endUpdates];
}
@end
You can append array of Data at the end of custom state:
const [vehicleData, setVehicleData] = React.useState<any[]>([]);
setVehicleData(old => [...old, ...newArrayData]);
For example, In below, you appear an example of axios:
useEffect(() => {
const fetchData = async () => {
const result = await axios(
{
url: `http://localhost:4000/api/vehicle?page=${page + 1}&pageSize=10`,
method: 'get',
}
);
setVehicleData(old => [...old, ...result.data.data]);
};
fetchData();
}, [page]);
This is a highly inefficient way of doing it. You can use the merge
statement and then there's no need for cursors, looping or (if you can do without) PL/SQL.
MERGE INTO studLoad l
USING ( SELECT studId, studName FROM student ) s
ON (l.studId = s.studId)
WHEN MATCHED THEN
UPDATE SET l.studName = s.studName
WHERE l.studName != s.studName
WHEN NOT MATCHED THEN
INSERT (l.studID, l.studName)
VALUES (s.studId, s.studName)
Make sure you commit
, once completed, in order to be able to see this in the database.
To actually answer your question I would do it something like as follows. This has the benefit of doing most of the work in SQL and only updating based on the rowid, a unique address in the table.
It declares a type, which you place the data within in bulk, 10,000 rows at a time. Then processes these rows individually.
However, as I say this will not be as efficient as merge
.
declare
cursor c_data is
select b.rowid as rid, a.studId, a.studName
from student a
left outer join studLoad b
on a.studId = b.studId
and a.studName <> b.studName
;
type t__data is table of c_data%rowtype index by binary_integer;
t_data t__data;
begin
open c_data;
loop
fetch c_data bulk collect into t_data limit 10000;
exit when t_data.count = 0;
for idx in t_data.first .. t_data.last loop
if t_data(idx).rid is null then
insert into studLoad (studId, studName)
values (t_data(idx).studId, t_data(idx).studName);
else
update studLoad
set studName = t_data(idx).studName
where rowid = t_data(idx).rid
;
end if;
end loop;
end loop;
close c_data;
end;
/
There is an usage scenario where you might need this. I'm not implying there are not better ways or achieving the same functionality.
This would be useful in order to 'dump' an arbitrary list of dictionaries in case of error, in debug modes and other similar situations.
What would be needed, is the reverse of the eval()
function:
get_indentifier_name_missing_function()
which would take an identifier name ('variable','dictionary',etc) as an argument, and return a string containing the identifier’s name.
Consider the following current state of affairs:
random_function(argument_data)
If one is passing an identifier name ('function','variable','dictionary',etc) argument_data
to a random_function()
(another identifier name), one actually passes an identifier (e.g.: <argument_data object at 0xb1ce10>
) to another identifier (e.g.: <function random_function at 0xafff78>
):
<function random_function at 0xafff78>(<argument_data object at 0xb1ce10>)
From my understanding, only the memory address is passed to the function:
<function at 0xafff78>(<object at 0xb1ce10>)
Therefore, one would need to pass a string as an argument to random_function()
in order for that function to have the argument's identifier name:
random_function('argument_data')
Inside the random_function()
def random_function(first_argument):
, one would use the already supplied string 'argument_data'
to:
serve as an 'identifier name' (to display, log, string split/concat, whatever)
feed the eval()
function in order to get a reference to the actual identifier, and therefore, a reference to the real data:
print("Currently working on", first_argument)
some_internal_var = eval(first_argument)
print("here comes the data: " + str(some_internal_var))
Unfortunately, this doesn't work in all cases. It only works if the random_function()
can resolve the 'argument_data'
string to an actual identifier. I.e. If argument_data
identifier name is available in the random_function()
's namespace.
This isn't always the case:
# main1.py
import some_module1
argument_data = 'my data'
some_module1.random_function('argument_data')
# some_module1.py
def random_function(first_argument):
print("Currently working on", first_argument)
some_internal_var = eval(first_argument)
print("here comes the data: " + str(some_internal_var))
######
Expected results would be:
Currently working on: argument_data
here comes the data: my data
Because argument_data
identifier name is not available in the random_function()
's namespace, this would yield instead:
Currently working on argument_data
Traceback (most recent call last):
File "~/main1.py", line 6, in <module>
some_module1.random_function('argument_data')
File "~/some_module1.py", line 4, in random_function
some_internal_var = eval(first_argument)
File "<string>", line 1, in <module>
NameError: name 'argument_data' is not defined
Now, consider the hypotetical usage of a get_indentifier_name_missing_function()
which would behave as described above.
Here's a dummy Python 3.0 code: .
# main2.py
import some_module2
some_dictionary_1 = { 'definition_1':'text_1',
'definition_2':'text_2',
'etc':'etc.' }
some_other_dictionary_2 = { 'key_3':'value_3',
'key_4':'value_4',
'etc':'etc.' }
#
# more such stuff
#
some_other_dictionary_n = { 'random_n':'random_n',
'etc':'etc.' }
for each_one_of_my_dictionaries in ( some_dictionary_1,
some_other_dictionary_2,
...,
some_other_dictionary_n ):
some_module2.some_function(each_one_of_my_dictionaries)
# some_module2.py
def some_function(a_dictionary_object):
for _key, _value in a_dictionary_object.items():
print( get_indentifier_name_missing_function(a_dictionary_object) +
" " +
str(_key) +
" = " +
str(_value) )
######
Expected results would be:
some_dictionary_1 definition_1 = text_1
some_dictionary_1 definition_2 = text_2
some_dictionary_1 etc = etc.
some_other_dictionary_2 key_3 = value_3
some_other_dictionary_2 key_4 = value_4
some_other_dictionary_2 etc = etc.
......
......
......
some_other_dictionary_n random_n = random_n
some_other_dictionary_n etc = etc.
Unfortunately, get_indentifier_name_missing_function()
would not see the 'original' identifier names (some_dictionary_
,some_other_dictionary_2
,some_other_dictionary_n
). It would only see the a_dictionary_object
identifier name.
Therefore the real result would rather be:
a_dictionary_object definition_1 = text_1
a_dictionary_object definition_2 = text_2
a_dictionary_object etc = etc.
a_dictionary_object key_3 = value_3
a_dictionary_object key_4 = value_4
a_dictionary_object etc = etc.
......
......
......
a_dictionary_object random_n = random_n
a_dictionary_object etc = etc.
So, the reverse of the eval()
function won't be that useful in this case.
Currently, one would need to do this:
# main2.py same as above, except:
for each_one_of_my_dictionaries_names in ( 'some_dictionary_1',
'some_other_dictionary_2',
'...',
'some_other_dictionary_n' ):
some_module2.some_function( { each_one_of_my_dictionaries_names :
eval(each_one_of_my_dictionaries_names) } )
# some_module2.py
def some_function(a_dictionary_name_object_container):
for _dictionary_name, _dictionary_object in a_dictionary_name_object_container.items():
for _key, _value in _dictionary_object.items():
print( str(_dictionary_name) +
" " +
str(_key) +
" = " +
str(_value) )
######
eval()
function if the name identifier is available in the current namespace.eval()
function, would not be useful in cases where the identifier name is not 'seen' directly by the calling code. E.g. inside any called function.This can be achieved by passing both the 'string'
and eval('string')
to the called function at the same time. I think this is the most 'general' way of solving this egg-chicken problem across arbitrary functions, modules, namespaces, without using corner-case solutions. The only downside is the use of the eval()
function which may easily lead to unsecured code. Care must be taken to not feed the eval()
function with just about anything, especially unfiltered external-input data.
First:
Transmitting end:
text.getBytes(encodingName)
)Base64
classReceiving end:
Base64
classnew String(bytes, encodingName)
)So something like:
// Sending side
byte[] data = text.getBytes("UTF-8");
String base64 = Base64.encodeToString(data, Base64.DEFAULT);
// Receiving side
byte[] data = Base64.decode(base64, Base64.DEFAULT);
String text = new String(data, "UTF-8");
Or with StandardCharsets
:
// Sending side
byte[] data = text.getBytes(StandardCharsets.UTF_8);
String base64 = Base64.encodeToString(data, Base64.DEFAULT);
// Receiving side
byte[] data = Base64.decode(base64, Base64.DEFAULT);
String text = new String(data, StandardCharsets.UTF_8);
Remove all forward slash occurrences with blank char in Javascript
.
modelData = modelData.replace(/\//g, '');
You can use ajax upload to preview your selected file.. http://zurb.com/playground/ajax-upload
No need to edit any database directly, there is a command for it :)
svc wifi [enable|disable]
I have written comments below to understand code sample. Some one if using, they can follow it , as I named the files accordingly.
IF server is sending blob in the response, then our client should be able to produce it.
As my purpose is solved by using these. I can able to download files, as I have used type: 'application/*' for all files.
Created "downloadLink" variable is just technique used in response so that, it would fill like some clicked on link, then response comes and then its href would be triggered.
controller.js_x000D_
//this function is in controller, which will be trigered on download button hit. _x000D_
_x000D_
$scope.downloadSampleFile = function() {_x000D_
//create sample hidden link in document, to accept Blob returned in the response from back end_x000D_
_x000D_
var downloadLink = document.createElement("a");_x000D_
_x000D_
document.body.appendChild(downloadLink);_x000D_
downloadLink.style = "display: none";_x000D_
_x000D_
//This service is written Below how does it work, by aceepting necessary params_x000D_
downloadFile.downloadfile(data).then(function (result) {_x000D_
_x000D_
var fName = result.filename;_x000D_
var file = new Blob([result.data], {type: 'application/*'});_x000D_
var fileURL = (window.URL || window.webkitURL).createObjectURL(file);_x000D_
_x000D_
_x000D_
//Blob, client side object created to with holding browser specific download popup, on the URL created with the help of window obj._x000D_
_x000D_
downloadLink.href = fileURL;_x000D_
downloadLink.download = fName;_x000D_
downloadLink.click();_x000D_
});_x000D_
};_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
services.js_x000D_
_x000D_
.factory('downloadFile', ["$http", function ($http) {_x000D_
return {_x000D_
downloadfile : function () {_x000D_
return $http.get(//here server endpoint to which you want to hit the request_x000D_
, {_x000D_
responseType: 'arraybuffer',_x000D_
params: {_x000D_
//Required params_x000D_
},_x000D_
}).then(function (response, status, headers, config) {_x000D_
return response;_x000D_
});_x000D_
},_x000D_
};_x000D_
}])
_x000D_
Rewrite @Juned Ahsan solution via stream in one line (headers are treated the same way):
public static String printRequest(HttpServletRequest req) {
String params = StreamSupport.stream(
((Iterable<String>) () -> req.getParameterNames().asIterator()).spliterator(), false)
.map(pName -> pName + '=' + req.getParameter(pName))
.collect(Collectors.joining("&"));
return req.getRequestURI() + '?' + params;
}
See also how to convert an iterator to a stream solution.
The translation is correct, the typing of the expression isn't. TypeScript is incorrectly typing the expression new Thing[100]
as an array. It should be an error to index Thing
, a constructor function, using the index operator. In C# this would allocate an array of 100 elements. In JavaScript this calls the value at index 100 of Thing
as if was a constructor. Since that values is undefined
it raises the error you mentioned. In JavaScript and TypeScript you want new Array(100)
instead.
You should report this as a bug on CodePlex.
Usually when I want to pass arguments to an alias in Bash, I use a combination of an alias and a function like this, for instance:
function __t2d {
if [ "$1x" != 'x' ]; then
date -d "@$1"
fi
}
alias t2d='__t2d'
Put this inside your package's __init__.py file:
# For relative imports to work in Python 3.6
import os, sys; sys.path.append(os.path.dirname(os.path.realpath(__file__)))
Assuming your package is like this:
+-- project
¦ +-- package
¦ ¦ +-- __init__.py
¦ ¦ +-- module1.py
¦ ¦ +-- module2.py
¦ +-- setup.py
Now use regular imports in you package, like:
# in module2.py
from module1 import class1
This works in both python 2 and 3.
We have to utilize $.ajax.abort() method to abort request if the request is active. This promise object uses readyState property to check whether the request is active or not.
HTML
<h3>Cancel Ajax Request on Demand</h3>
<div id="test"></div>
<input type="button" id="btnCancel" value="Click to Cancel the Ajax Request" />
JS Code
//Initial Message
var ajaxRequestVariable;
$("#test").html("Please wait while request is being processed..");
//Event handler for Cancel Button
$("#btnCancel").on("click", function(){
if (ajaxRequestVariable !== undefined)
if (ajaxRequestVariable.readyState > 0 && ajaxRequestVariable.readyState < 4)
{
ajaxRequestVariable.abort();
$("#test").html("Ajax Request Cancelled.");
}
});
//Ajax Process Starts
ajaxRequestVariable = $.ajax({
method: "POST",
url: '/echo/json/',
contentType: "application/json",
cache: false,
dataType: "json",
data: {
json: JSON.encode({
data:
[
{"prop1":"prop1Value"},
{"prop1":"prop2Value"}
]
}),
delay: 11
},
success: function (response) {
$("#test").show();
$("#test").html("Request is completed");
},
error: function (error) {
},
complete: function () {
}
});
class MyExc1 extends Exception {}
class MyExc2 extends Exception {}
class MyExc3 extends MyExc2 {}
public class C1 {
public static void main(String[] args) throws Exception {
try {
System.out.print("TryA L1\n");
q();
System.out.print("TryB L1\n");
}
catch (Exception i) {
System.out.print("Catch L1\n");
}
finally {
System.out.print("Finally L1\n");
throw new MyExc1();
}
}
static void q() throws Exception {
try {
System.out.print("TryA L2\n");
q2();
System.out.print("TryB L2\n");
}
catch (Exception y) {
System.out.print("Catch L2\n");
throw new MyExc2();
}
finally {
System.out.print("Finally L2\n");
throw new Exception();
}
}
static void q2() throws Exception {
throw new MyExc1();
}
}
Order:
TryA L1
TryA L2
Catch L2
Finally L2
Catch L1
Finally L1
Exception in thread "main" MyExc1 at C1.main(C1.java:30)
Are you looking something like this short and effective:
$('div').on('click',function(){
$('div').removeClass('active');
$(this).addClass('active');
});
you can simply add a general class 'active' for selected div. when a div is clicked, remove the 'active' class, and add it to the clicked div.
You can do it without forcing html
and body
to me 100% height. Use view port height instead. And with mouse wheel control too.
function debounce(func, wait, immediate) {_x000D_
var timeout;_x000D_
return function() {_x000D_
var context = this,_x000D_
args = arguments;_x000D_
var later = function() {_x000D_
timeout = null;_x000D_
if (!immediate) func.apply(context, args);_x000D_
};_x000D_
var callNow = immediate && !timeout;_x000D_
clearTimeout(timeout);_x000D_
timeout = setTimeout(later, wait);_x000D_
if (callNow) func.apply(context, args);_x000D_
};_x000D_
}_x000D_
_x000D_
var slider = document.getElementById("demo");_x000D_
var onScroll = debounce(function(direction) {_x000D_
//console.log(direction);_x000D_
if (direction == false) {_x000D_
$('.carousel-control-next').click();_x000D_
} else {_x000D_
$('.carousel-control-prev').click();_x000D_
}_x000D_
}, 100, true);_x000D_
_x000D_
slider.addEventListener("wheel", function(e) {_x000D_
e.preventDefault();_x000D_
var delta;_x000D_
if (event.wheelDelta) {_x000D_
delta = event.wheelDelta;_x000D_
} else {_x000D_
delta = -1 * event.deltaY;_x000D_
}_x000D_
_x000D_
onScroll(delta >= 0);_x000D_
});
_x000D_
.carousel-item {_x000D_
height: 100vh;_x000D_
background: #212121;_x000D_
}_x000D_
_x000D_
.carousel-control-next,_x000D_
.carousel-control-prev {_x000D_
width: 8% !important;_x000D_
}_x000D_
_x000D_
.carousel-item.active,_x000D_
.carousel-item-left,_x000D_
.carousel-item-right {_x000D_
display: flex !important;_x000D_
justify-content: center;_x000D_
align-items: center;_x000D_
}_x000D_
_x000D_
.carousel-item h1 {_x000D_
color: #fff;_x000D_
font-size: 72px;_x000D_
padding: 0 10%;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<div id="demo" class="carousel slide" data-ride="carousel" data-interval="false">_x000D_
_x000D_
<!-- The slideshow -->_x000D_
<div class="carousel-inner">_x000D_
<div class="carousel-item active">_x000D_
<h1 class="display-1 text-center">Lorem ipsum dolor sit amet adipisicing</h1>_x000D_
</div>_x000D_
<div class="carousel-item">_x000D_
<h1 class="display-1 text-center">Inventore omnis odio, dolore culpa atque?</h1>_x000D_
</div>_x000D_
<div class="carousel-item">_x000D_
<h1 class="display-1 text-center">Lorem ipsum dolor sit</h1>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<!-- Left and right controls -->_x000D_
<a class="carousel-control-prev" href="#demo" data-slide="prev">_x000D_
<span class="carousel-control-prev-icon"></span>_x000D_
</a>_x000D_
<a class="carousel-control-next" href="#demo" data-slide="next">_x000D_
<span class="carousel-control-next-icon"></span>_x000D_
</a>_x000D_
_x000D_
</div>
_x000D_
In python, this is called "unpacking", and you can find a bit about it in the tutorial. The documentation of it sucks, I agree, especially because of how fantasically useful it is.
The getRequestURL()
omits the port when it is 80 while the scheme is http
, or when it is 443 while the scheme is https
.
So, just use getRequestURL()
if all you want is obtaining the entire URL. This does however not include the GET query string. You may want to construct it as follows then:
StringBuffer requestURL = request.getRequestURL();
if (request.getQueryString() != null) {
requestURL.append("?").append(request.getQueryString());
}
String completeURL = requestURL.toString();
Update: This will create a second context same as in applicationContext.xml
or you can add this code snippet to your web.xml
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
instead of
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
TextView tv = new TextView(this);
tv.setText(String.valueOf(number));
or
tv.setText(""+number);
Without explicitly defining the height
I determined I need to apply the flex
value to the parent and grandparent div
elements...
<div style="display: flex;">
<div style="display: flex;">
<img alt="No, he'll be an engineer." src="theknack.png" style="margin: auto;" />
</div>
</div>
If you're using a single element (e.g. dead-centered text in a single flex
element) use the following:
align-items: center;
display: flex;
justify-content: center;
if the name of node is for example : abcd then below query will work :
MATCH (n:abcd)
DETACH DELETE n
This will only delete the node with label "abcd" and all its relation-ships.
max-width is the width of the target display area, e.g. the browser; max-device-width is the width of the device's entire rendering area, i.e. the actual device screen.
• If you are using the max-device-width, when you change the size of the browser window on your desktop, the CSS style won't change to different media query setting;
• If you are using the max-width, when you change the size of the browser on your desktop, the CSS will change to different media query setting and you might be shown with the styling for mobiles, such as touch-friendly menus.
What kind of dates do you have in the column?
Do all of them fit within the range of the type?
As an aside, the correct way to get a Type
object for the DataColumn
constructor is the typeof
keyword, which is orders of magnitude faster.
Therefore, to create the column, you should write
new DataColumn("myDate", typeof(DateTime))
You could try:
#!/bin/bash
### $1 == the first args to this script
### usage: script.sh /path/to/dir/
for f in `find . -maxdepth 1 -mindepth 1 -type d`; do
cd "$f"
<your job here>
done
or similar...
Explanation:
find . -maxdepth 1 -mindepth 1 -type d
:
Only find directories with a maximum recursive depth of 1 (only the subdirectories of $1) and minimum depth of 1 (excludes current folder .
)
I was having same issue, way i have resolved is:
opened the MySQL installer. i was having a Reconfigure link on MYSQL Server row.
Clicked on it, it does reinstalled MySQL Server. after that opened MySQL Workbench, and it was working fine.
In my case, I was able to solve this issue by reinstalling virtual box. I was trying to use laravel's homestead and was having this error. Reinstalling helps creating the directories that are needed for virtual box again. Took me an hour to figure out.
Make sure you set the 'Start in' and 'Program/script' options correctly. If your file address is: C:\Temp\foo.bat, set the 'start in' option to 'C:\Temp' and the 'Program/script' option to 'foo.bat'.
To set the 'Start in' option: Right click task in the task scheduler > Properties > Actions > Edit.
If this alone doesn't work then try moving the .bat file to a directory with basic permissions (maybe a shared directory for example).
I had a problem where my .bat file was located in a folder with some restrictive permissions on it, so that only my user account could access it. Even though I had set up the task scheduler to use my credentials it still failed. Moving the .bat file to another directory sorted the issue.
Good news! Swift 4.2 (Xcode 10) finally provides CommonCrypto!
Just add import CommonCrypto
in your swift file.
you can run your past mysql with run /PATH_PAST_MYSQL/bin/mysqld.exe
it run your last mysql and you can see it in phpmyadmin and other section of your system.
notice: stop your current mysql version.
S F My English.
Based on the above stuff:
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
fontPath = "/usr/share/fonts/abc.ttf"
font = fm.FontProperties(fname=fontPath, size=10)
font2 = fm.FontProperties(fname=fontPath, size=24)
fig = plt.figure(figsize=(32, 24))
fig.text(0.5, 0.93, "This is my Title", horizontalalignment='center', fontproperties=font2)
plot = fig.add_subplot(1, 1, 1)
plot.xaxis.get_label().set_fontproperties(font)
plot.yaxis.get_label().set_fontproperties(font)
plot.legend(loc='upper right', prop=font)
for label in (plot.get_xticklabels() + plot.get_yticklabels()):
label.set_fontproperties(font)
The best way I can think of to accomplish this is via sp_addlinkedserver. You need to make sure that whatever account you use to add the link (via sp_addlinkedsrvlogin) has permissions to the table you're joining, but then once the link is established, you can call the server by name, i.e.:
SELECT *
FROM server1table
INNER JOIN server2.database.dbo.server2table ON .....
You should do it this way ideally
t = TemperatureData.objects.get(id=1)
t.value = 999
t.save(['value'])
This allow you to specify which column should be saved and rest are left as they currently are in database. (https://code.djangoproject.com/ticket/4102)!
With <button>
, you can use img tags, etc. where text is
<button type='submit'> text -- can be img etc. </button>
with <input>
type, you are limited to text
In my somewhat checkered experience, applying -O3
to an entire program almost always makes it slower (relative to -O2
), because it turns on aggressive loop unrolling and inlining that make the program no longer fit in the instruction cache. For larger programs, this can also be true for -O2
relative to -Os
!
The intended use pattern for -O3
is, after profiling your program, you manually apply it to a small handful of files containing critical inner loops that actually benefit from these aggressive space-for-speed tradeoffs. Newer versions of GCC have a profile-guided optimization mode that can (IIUC) selectively apply the -O3
optimizations to hot functions -- effectively automating this process.
Using bookmarks is great way to keep your sanity if you're working with or troubleshooting a really long procedure. Let's say you're working with a derived field in an outer query and it's definition is another 200 lines down inside the inner query. You can bookmark both locations and then quickly go back and forth between the two.
Below Test Init will also do the job.
[TestInitialize]
public void TestInit()
{
HttpContext.Current = new HttpContext(new HttpRequest(null, "http://tempuri.org", null), new HttpResponse(null));
YourControllerToBeTestedController = GetYourToBeTestedController();
}
a = ['it']
b = ['was']
c = ['annoying']
a.extend(b)
a.extend(c)
# a now equals ['it', 'was', 'annoying']
So Soumyaansh's Revo Uninstaller Pro fix worked for me :) ( After 2 days of troubleshooting other options {screams internally 😀} ).
I did run into the an issue with his method though, "Could not find a suitable SDK to target" even though I selected to install Visual Studio with custom settings and selected the SDK I wanted to install. You may need to download the Windows 10 Standalone SDK to resolved this, in order to develop UWP apps if you see this same error after reinstalling Visual Studio.
To do this
Windows 10 SDK (WINDOWS_VERSION_NUMBER_HERE)
-> Windows 10 SDK (14393) etc . . .). If there are no SDKs on your system go to step 2!ProgressBar freeRamPb = findViewById(R.id.free_ram_progress_bar);
freeRamPb.getProgressDrawable().setColorFilter(
Color.BLUE, android.graphics.PorterDuff.Mode.SRC_IN);
You don't have create theme just write it in your dialog creation object
DatePickerDialog datePicker = new DatePickerDialog(getActivity(), AlertDialog.THEME_HOLO_LIGHT,this, mYear, mMonth, mDay);
follow this it will give you all type date picker style it's really work
http://www.android-examples.com/change-datepickerdialog-theme-in-android-using-dialogfragment/
SELECT field1 FROM table1
UNION
SELECT field1 FROM table2
ORDER BY field1
>>> import datetime
>>> d = datetime.datetime.strptime('2011-06-09', '%Y-%m-%d')
>>> d.strftime('%b %d,%Y')
'Jun 09,2011'
In pre-2.5 Python, you can replace datetime.strptime
with time.strptime
, like so (untested): datetime.datetime(*(time.strptime('2011-06-09', '%Y-%m-%d')[0:6]))
Iterate string:
for ($i = 0; $i < strlen($str); $i++){
echo $str[$i];
}
That's because you're using a non-blocking
socket and the output buffer is full.
From the send()
man page
When the message does not fit into the send buffer of the socket,
send() normally blocks, unless the socket has been placed in non-block-
ing I/O mode. In non-blocking mode it would return EAGAIN in this
case.
EAGAIN is the error code tied to "Resource temporarily unavailable"
Consider using select()
to get a better control of this behaviours
Starting Python 3.8
, and the introduction of assignment expressions (PEP 572) (:=
operator), we can now capture the condition value re.search(pattern, statement)
in a variable (let's all it match
) in order to both check if it's not None
and then re-use it within the body of the condition:
if match := re.search('I love (\w+)', statement):
print(f'He loves {match.group(1)}')
elif match := re.search("Ich liebe (\w+)", statement):
print(f'Er liebt {match.group(1)}')
elif match := re.search("Je t'aime (\w+)", statement):
print(f'Il aime {match.group(1)}')
Puts the error message on top.
<style>
.radio-group{
position:relative; margin-top:40px;
}
#myoptions-error{
position:absolute;
top: -25px;
}
</style>
<div class="radio-group">
<input type="radio" name="myoptions" value="blue" class="required"> Blue<br />
<input type="radio" name="myoptions" value="red"> Red<br />
<input type="radio" name="myoptions" value="green"> Green </div>
</div><!-- end radio-group -->
If you want to delete database programatically you can use deleteDatabase
from Context
class:
deleteDatabase(String name)
Delete an existing private SQLiteDatabase associated with this Context's application package.
This link contains relevant information on detecting versions of Internet Explorer:
http://tanalin.com/en/articles/ie-version-js/
Example:
if (document.all && !document.addEventListener) {
alert('IE8 or older.');
}
Solution:
@Entity
@Table(name = "USER")
@Access(AccessType.FIELD)
public class User implements UserDetails, Serializable {
private static final long serialVersionUID = 2L;
@Id
@Column(name = "USER_ID", updatable=false, nullable=false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "USERNAME")
private String username;
@Column(name = "PASSWORD")
private String password;
@Column(name = "NAME")
private String name;
@Column(name = "EMAIL")
private String email;
@Column(name = "LOCKED")
private boolean locked;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, targetEntity = Role.class)
@JoinTable(name = "USER_ROLE", joinColumns = { @JoinColumn(name = "USER_ID") }, inverseJoinColumns = { @JoinColumn(name = "ROLE_ID") })
private Set<Role> roles;
@Override
public GrantedAuthority[] getAuthorities() {
List<GrantedAuthorityImpl> list = new ArrayList<GrantedAuthorityImpl>(0);
for (Role role : roles) {
list.add(new GrantedAuthorityImpl(role.getRole()));
}
return (GrantedAuthority[]) list.toArray(new GrantedAuthority[list.size()]);
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return !isLocked();
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
@Override
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Override
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean isLocked() {
return locked;
}
public void setLocked(boolean locked) {
this.locked = locked;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
}
Role.java same as above.
You can also use the filter function from the dplyr package which returns rows with matching conditions.
> library(dplyr)
> nrow(filter(aaa, sex == 1 & group1 == 2))
[1] 3
> nrow(filter(aaa, sex == 1 & group2 == "A"))
[1] 2
double[,]
is a 2d array (matrix) while double[][]
is an array of arrays (jagged arrays) and the syntax is:
double[][] ServicePoint = new double[10][];
That is very odd.
I went through ItemNotFoundException
's base classes and tested the following multiple catch
es to see what would catch it:
try {
remove-item C:\nonexistent\file.txt -erroraction stop
}
catch [System.Management.Automation.ItemNotFoundException] {
write-host 'ItemNotFound'
}
catch [System.Management.Automation.SessionStateException] {
write-host 'SessionState'
}
catch [System.Management.Automation.RuntimeException] {
write-host 'RuntimeException'
}
catch [System.SystemException] {
write-host 'SystemException'
}
catch [System.Exception] {
write-host 'Exception'
}
catch {
write-host 'well, darn'
}
As it turns out, the output was 'RuntimeException'
. I also tried it with a different exception CommandNotFoundException
:
try {
do-nonexistent-command
}
catch [System.Management.Automation.CommandNotFoundException] {
write-host 'CommandNotFoundException'
}
catch {
write-host 'well, darn'
}
That output 'CommandNotFoundException'
correctly.
I vaguely remember reading elsewhere (though I couldn't find it again) of problems with this. In such cases where exception filtering didn't work correctly, they would catch the closest Type
they could and then use a switch
. The following just catches Exception
instead of RuntimeException
, but is the switch
equivalent of my first example that checks all base types of ItemNotFoundException
:
try {
Remove-Item C:\nonexistent\file.txt -ErrorAction Stop
}
catch [System.Exception] {
switch($_.Exception.GetType().FullName) {
'System.Management.Automation.ItemNotFoundException' {
write-host 'ItemNotFound'
}
'System.Management.Automation.SessionStateException' {
write-host 'SessionState'
}
'System.Management.Automation.RuntimeException' {
write-host 'RuntimeException'
}
'System.SystemException' {
write-host 'SystemException'
}
'System.Exception' {
write-host 'Exception'
}
default {'well, darn'}
}
}
This writes 'ItemNotFound'
, as it should.
Install a cross compiler, like mingw64 from your package manager.
Then compile in the following way: instead of simply calling gcc
call i686-w64-mingw32-gcc
for 32-bit Windows or x86_64-w64-mingw32-gcc"
for 64-bit Windows. I would also use the --static
option, as the target system may not have all the libraries.
If you want to compile other language, like Fortran, replace -gcc
with -gfortran
in the previous commands.
The constructor of your A object allocates another object dynamically and stores a pointer to that dynamically allocated object in a raw pointer.
For that scenario, you must define your own copy constructor , assignment operator and destructor. The compiler generated ones will not work correctly. (This is a corollary to the "Law of the Big Three": A class with any of destructor, assignment operator, copy constructor generally needs all 3).
You have defined your own destructor (and you mentioned creating a copy constructor), but you need to define both of the other 2 of the big three.
An alternative is to store the pointer to your dynamically allocated int[]
in some other object that will take care of these things for you. Something like a vector<int>
(as you mentioned) or a boost::shared_array<>
.
To boil this down - to take advantage of RAII to the full extent, you should avoid dealing with raw pointers to the extent possible.
And since you asked for other style critiques, a minor one is that when you are deleting raw pointers you do not need to check for 0 before calling delete
- delete
handles that case by doing nothing so you don't have to clutter you code with the checks.
Below is a simple command, where a dev or a git user can pass a deleted file name from the repository root directory and get the history:
git log --diff-filter=D --summary | grep filename | awk '{print $4; exit}' | xargs git log --all --
If anybody, can improve the command, please do.
You need to make sure that your project is set to target the AVD that you want to launch.
Right click (ctrl-click MAC) on the project folder in Eclipse. Then click on Properties. In the window that shows up, click on "Android" and then click on the build target you want to launch. Hope that helps.
Here is a concise, pure-python solution that works in both python 3 and 2:
from PIL import Image
infile = '20190206-135938.1273.Easy8thRunnersHopefully.jpg'
chopsize = 300
img = Image.open(infile)
width, height = img.size
# Save Chops of original image
for x0 in range(0, width, chopsize):
for y0 in range(0, height, chopsize):
box = (x0, y0,
x0+chopsize if x0+chopsize < width else width - 1,
y0+chopsize if y0+chopsize < height else height - 1)
print('%s %s' % (infile, box))
img.crop(box).save('zchop.%s.x%03d.y%03d.jpg' % (infile.replace('.jpg',''), x0, y0))
Notes:
I believe you'd want to escape by doubling the single quote:
INSERT INTO table_name (field1, field2) VALUES (123, 'Hello there''s');
If you want the file to be opened with the default application, I mean without specifying Acrobat or Reader, you can't open the file in the specified page.
On the other hand, if you are Ok with specifying Acrobat or Reader, keep reading:
You can do it without telling the full Acrobat path, like this:
Process myProcess = new Process();
myProcess.StartInfo.FileName = "acroRd32.exe"; //not the full application path
myProcess.StartInfo.Arguments = "/A \"page=2=OpenActions\" C:\\example.pdf";
myProcess.Start();
If you don't want the pdf to open with Reader but with Acrobat, chage the second line like this:
myProcess.StartInfo.FileName = "Acrobat.exe";
You can query the registry to identify the default application to open pdf files and then define FileName on your process's StartInfo accordingly.
Follow this question for details on doing that: Finding the default application for opening a particular file type on Windows
Sigh, it took me 45 minutes to find the answer to this simple question. The answer is: grepl(needle, haystack, fixed=TRUE)
# Correct
> grepl("1+2", "1+2", fixed=TRUE)
[1] TRUE
> grepl("1+2", "123+456", fixed=TRUE)
[1] FALSE
# Incorrect
> grepl("1+2", "1+2")
[1] FALSE
> grepl("1+2", "123+456")
[1] TRUE
grep
is named after the linux executable, which is itself an acronym of "Global Regular Expression Print", it would read lines of input and then print them if they matched the arguments you gave. "Global" meant the match could occur anywhere on the input line, I'll explain "Regular Expression" below, but the idea is it's a smarter way to match the string (R calls this "character", eg class("abc")
), and "Print" because it's a command line program, emitting output means it prints to its output string.
Now, the grep
program is basically a filter, from lines of input, to lines of output. And it seems that R's grep
function similarly will take an array of inputs. For reasons that are utterly unknown to me (I only started playing with R about an hour ago), it returns a vector of the indexes that match, rather than a list of matches.
But, back to your original question, what we really want is to know whether we found the needle in the haystack, a true/false value. They apparently decided to name this function grepl
, as in "grep" but with a "Logical" return value (they call true and false logical values, eg class(TRUE)
).
So, now we know where the name came from and what it's supposed to do. Lets get back to Regular Expressions. The arguments, even though they are strings, they are used to build regular expressions (henceforth: regex). A regex is a way to match a string (if this definition irritates you, let it go). For example, the regex a
matches the character "a"
, the regex a*
matches the character "a"
0 or more times, and the regex a+
would match the character "a"
1 or more times. Hence in the example above, the needle we are searching for 1+2
, when treated as a regex, means "one or more 1 followed by a 2"... but ours is followed by a plus!
So, if you used the grepl
without setting fixed
, your needles would accidentally be haystacks, and that would accidentally work quite often, we can see it even works for the OP's example. But that's a latent bug! We need to tell it the input is a string, not a regex, which is apparently what fixed
is for. Why fixed? No clue, bookmark this answer b/c you're probably going to have to look it up 5 more times before you get it memorized.
The better your code is, the less history you have to know to make sense of it. Every argument can have at least two interesting values (otherwise it wouldn't need to be an argument), the docs list 9 arguments here, which means there's at least 2^9=512 ways to invoke it, that's a lot of work to write, test, and remember... decouple such functions (split them up, remove dependencies on each other, string things are different than regex things are different than vector things). Some of the options are also mutually exclusive, don't give users incorrect ways to use the code, ie the problematic invocation should be structurally nonsensical (such as passing an option that doesn't exist), not logically nonsensical (where you have to emit a warning to explain it). Put metaphorically: replacing the front door in the side of the 10th floor with a wall is better than hanging a sign that warns against its use, but either is better than neither. In an interface, the function defines what the arguments should look like, not the caller (because the caller depends on the function, inferring everything that everyone might ever want to call it with makes the function depend on the callers, too, and this type of cyclical dependency will quickly clog a system up and never provide the benefits you expect). Be very wary of equivocating types, it's a design flaw that things like TRUE
and 0
and "abc"
are all vectors.
I would open another terminal on your laptop and do the scp from there, since you already know how to set that connection up.
scp username@remotecomputer:/path/to/file/you/want/to/copy where/to/put/file/on/laptop
The username@remotecomputer
is the same string you used with ssh initially.
You can use one of following:
android:gravity="fill_horizontal|clip_vertical"
Or
android:gravity="fill_vertical|clip_horizontal"
What will you have? You'll probably end up with a default search and a search that you load from somewhere. Default search requires a default constructor, so make one like Dismissile has already suggested.
If you load the search criteria from elsewhere, then you should probably have some mapping logic.
onclick="history.go(-1)"
Simply
my mistake was making the target name "filename.c:" instead of just "filename:"
Q. List the name of each show, and the number of different times it has been held. List the show which has been held most often first.
event_id show_id event_name judge_id
0101 01 Dressage 01
0102 01 Jumping 02
0103 01 Led in 01
0201 02 Led in 02
0301 03 Led in 01
0401 04 Dressage 04
0501 05 Dressage 01
0502 05 Flag and Pole 02
Ans:
select event_name, count(show_id) as held_times from event
group by event_name
order by count(show_id) desc
Option 1
http://jquery.malsup.com/corner/
Option 2
http://code.google.com/p/curved-corner/downloads/detail?name=border-radius-demo.zip
Option 3
Option 4
http://www.netzgesta.de/corner/
Option 5
EDIT: Option 6
The C++ over-engineering mindset is already well accounted for in the other answers here. Here's my attempt at doing it with a C, keep-it-simple-ffs mindset:
unsigned char x = 0xF; // binary: 00001111
After reviewing Microsoft's TechNet article "Azure Active Directory Cmdlets" -> section "Install the Azure AD Module", it seems that this process has been drastically simplified, thankfully.
As of 2016/06/30, in order to successfully execute the PowerShell commands Import-Module MSOnline
and Connect-MsolService
, you will need to install the following applications (64-bit only):
7.250.4556.0
(latest)msoidcli_64.msi
D077CF49077EE133523C1D3AE9A4BF437D220B16D651005BBC12F7BDAD1BF313
AdministrationConfig-en.msi
3.0
(later versions will probably work too)Windows6.1-KB2506143-x64.msu
So, strictly speaking, the "type of a variable" is always present, and can be passed around as a type parameter. For example:
val x = 5
def f[T](v: T) = v
f(x) // T is Int, the type of x
But depending on what you want to do, that won't help you. For instance, may want not to know what is the type of the variable, but to know if the type of the value is some specific type, such as this:
val x: Any = 5
def f[T](v: T) = v match {
case _: Int => "Int"
case _: String => "String"
case _ => "Unknown"
}
f(x)
Here it doesn't matter what is the type of the variable, Any
. What matters, what is checked is the type of 5
, the value. In fact, T
is useless -- you might as well have written it def f(v: Any)
instead. Also, this uses either ClassTag
or a value's Class
, which are explained below, and cannot check the type parameters of a type: you can check whether something is a List[_]
(List
of something), but not whether it is, for example, a List[Int]
or List[String]
.
Another possibility is that you want to reify the type of the variable. That is, you want to convert the type into a value, so you can store it, pass it around, etc. This involves reflection, and you'll be using either ClassTag
or a TypeTag
. For example:
val x: Any = 5
import scala.reflect.ClassTag
def f[T](v: T)(implicit ev: ClassTag[T]) = ev.toString
f(x) // returns the string "Any"
A ClassTag
will also let you use type parameters you received on match
. This won't work:
def f[A, B](a: A, b: B) = a match {
case _: B => "A is a B"
case _ => "A is not a B"
}
But this will:
val x = 'c'
val y = 5
val z: Any = 5
import scala.reflect.ClassTag
def f[A, B: ClassTag](a: A, b: B) = a match {
case _: B => "A is a B"
case _ => "A is not a B"
}
f(x, y) // A (Char) is not a B (Int)
f(x, z) // A (Char) is a B (Any)
Here I'm using the context bounds syntax, B : ClassTag
, which works just like the implicit parameter in the previous ClassTag
example, but uses an anonymous variable.
One can also get a ClassTag
from a value's Class
, like this:
val x: Any = 5
val y = 5
import scala.reflect.ClassTag
def f(a: Any, b: Any) = {
val B = ClassTag(b.getClass)
ClassTag(a.getClass) match {
case B => "a is the same class as b"
case _ => "a is not the same class as b"
}
}
f(x, y) == f(y, x) // true, a is the same class as b
A ClassTag
is limited in that it only covers the base class, but not its type parameters. That is, the ClassTag
for List[Int]
and List[String]
is the same, List
. If you need type parameters, then you must use a TypeTag
instead. A TypeTag
however, cannot be obtained from a value, nor can it be used on a pattern match, due to JVM's erasure.
Examples with TypeTag
can get quite complex -- not even comparing two type tags is not exactly simple, as can be seen below:
import scala.reflect.runtime.universe.TypeTag
def f[A, B](a: A, b: B)(implicit evA: TypeTag[A], evB: TypeTag[B]) = evA == evB
type X = Int
val x: X = 5
val y = 5
f(x, y) // false, X is not the same type as Int
Of course, there are ways to make that comparison return true, but it would require a few book chapters to really cover TypeTag
, so I'll stop here.
Finally, maybe you don't care about the type of the variable at all. Maybe you just want to know what is the class of a value, in which case the answer is rather simple:
val x = 5
x.getClass // int -- technically, an Int cannot be a class, but Scala fakes it
It would be better, however, to be more specific about what you want to accomplish, so that the answer can be more to the point.
From your feature branch (e.g configUpdate
) run:
git fetch
git rebase origin/master
Or the shorter form:
git pull --rebase
Why this works:
git merge branchname
takes new commits from the branch branchname
, and adds them to the current branch. If necessary, it automatically adds a "Merge" commit on top.
git rebase branchname
takes new commits from the branch branchname
, and inserts them "under" your changes. More precisely, it modifies the history of the current branch such that it is based on the tip of branchname
, with any changes you made on top of that.
git pull
is basically the same as git fetch; git merge origin/master
.
git pull --rebase
is basically the same as git fetch; git rebase origin/master
.
So why would you want to use git pull --rebase
rather than git pull
? Here's a simple example:
You start working on a new feature.
By the time you're ready to push your changes, several commits have been pushed by other developers.
If you git pull
(which uses merge), your changes will be buried by the new commits, in addition to an automatically-created merge commit.
If you git pull --rebase
instead, git will fast forward your master to upstream's, then apply your changes on top.
The example packaged with getopt
(my distro put it in /usr/share/getopt/getopt-parse.bash
) looks like it covers all of your cases:
#!/bin/bash
# A small example program for using the new getopt(1) program.
# This program will only work with bash(1)
# An similar program using the tcsh(1) script language can be found
# as parse.tcsh
# Example input and output (from the bash prompt):
# ./parse.bash -a par1 'another arg' --c-long 'wow!*\?' -cmore -b " very long "
# Option a
# Option c, no argument
# Option c, argument `more'
# Option b, argument ` very long '
# Remaining arguments:
# --> `par1'
# --> `another arg'
# --> `wow!*\?'
# Note that we use `"$@"' to let each command-line parameter expand to a
# separate word. The quotes around `$@' are essential!
# We need TEMP as the `eval set --' would nuke the return value of getopt.
TEMP=`getopt -o ab:c:: --long a-long,b-long:,c-long:: \
-n 'example.bash' -- "$@"`
if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi
# Note the quotes around `$TEMP': they are essential!
eval set -- "$TEMP"
while true ; do
case "$1" in
-a|--a-long) echo "Option a" ; shift ;;
-b|--b-long) echo "Option b, argument \`$2'" ; shift 2 ;;
-c|--c-long)
# c has an optional argument. As we are in quoted mode,
# an empty parameter will be generated if its optional
# argument is not found.
case "$2" in
"") echo "Option c, no argument"; shift 2 ;;
*) echo "Option c, argument \`$2'" ; shift 2 ;;
esac ;;
--) shift ; break ;;
*) echo "Internal error!" ; exit 1 ;;
esac
done
echo "Remaining arguments:"
for arg do echo '--> '"\`$arg'" ; done
try following
try {
String[] command = {"cmd.exe", "/C", "Start", "D:\\test.bat"};
Process p = Runtime.getRuntime().exec(command);
} catch (IOException ex) {
}
Here's an example using an IconButton to capture input (photo/video capture) using v3.9.2:
import React, { Component, Fragment } from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import IconButton from '@material-ui/core/IconButton';
import PhotoCamera from '@material-ui/icons/PhotoCamera';
import Videocam from '@material-ui/icons/Videocam';
const styles = (theme) => ({
input: {
display: 'none'
}
});
class MediaCapture extends Component {
static propTypes = {
classes: PropTypes.object.isRequired
};
state: {
images: [],
videos: []
};
handleCapture = ({ target }) => {
const fileReader = new FileReader();
const name = target.accept.includes('image') ? 'images' : 'videos';
fileReader.readAsDataURL(target.files[0]);
fileReader.onload = (e) => {
this.setState((prevState) => ({
[name]: [...prevState[name], e.target.result]
}));
};
};
render() {
const { classes } = this.props;
return (
<Fragment>
<input
accept="image/*"
className={classes.input}
id="icon-button-photo"
onChange={this.handleCapture}
type="file"
/>
<label htmlFor="icon-button-photo">
<IconButton color="primary" component="span">
<PhotoCamera />
</IconButton>
</label>
<input
accept="video/*"
capture="camcorder"
className={classes.input}
id="icon-button-video"
onChange={this.handleCapture}
type="file"
/>
<label htmlFor="icon-button-video">
<IconButton color="primary" component="span">
<Videocam />
</IconButton>
</label>
</Fragment>
);
}
}
export default withStyles(styles, { withTheme: true })(MediaCapture);
I ran into a very similar problem with my Xamarin Windows Phone 8.1 app. The reason JObject.Parse(json) would not work for me was because my Json had a beginning "[" and an ending "]". In order to make it work, I had to remove those two characters. From your example, it looks like you might have the same issue.
jsonResult = jsonResult.TrimStart(new char[] { '[' }).TrimEnd(new char[] { ']' });
I was then able to use the JObject.Parse(jsonResult) and everything worked.
Functions are computed values and cannot perform permanent environmental changes to SQL Server
(i.e., no INSERT
or UPDATE
statements allowed).
A function can be used inline in SQL
statements if it returns a scalar value or can be joined upon if it returns a result set.
A point worth noting from comments, which summarize the answer. Thanks to @Sean K Anderson:
Functions follow the computer-science definition in that they MUST return a value and cannot alter the data they receive as parameters (the arguments). Functions are not allowed to change anything, must have at least one parameter, and they must return a value. Stored procs do not have to have a parameter, can change database objects, and do not have to return a value.
You might be interested in a proposal for some new operators that are similar to the conditional operator. The null-safe operators will enable code like this:
String s = mayBeNull?.toString() ?: "null";
It would be especially convenient where auto-unboxing takes place.
Integer ival = ...; // may be null
int i = ival ?: -1; // no NPE from unboxing
It has been selected for further consideration under JDK 7's "Project Coin."
public ActionResult SomeAction(string start, string end)
The framework will map the query string parameters to the method parameters.
You can use bootstrap tooltip, and don't forget to set the html option to true.
<div id="tool"> tooltip</div>
$('#tool').tooltip({
title: 'line one' +'<br />'+ 'line two',
html: true
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
The below command would do the job.
forfiles /M *.txt /C "cmd /c rename @file \"@fname 1.1.txt\""
source: Rename file extensions in bulk
If you're trying to kill -9 it, you have the correct PID, and nothing happens, then you don't have permissions to kill the process.
Solution:
$ sudo kill -9 PID
Okay, sure enough Mac OS/X does give an error message for this case:
$ kill -9 196
-bash: kill: (196) - Operation not permitted
So, if you're not getting an error message, you somehow aren't getting the right PID.
Thanks for the really useful script.
You may need to add the following modification to the code if your tables have non-convertable fields:
SET @ColumnName =
(
SELECT MIN(QUOTENAME(COLUMN_NAME))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2)
AND TABLE_NAME = PARSENAME(@TableName, 1)
AND DATA_TYPE NOT IN ('text', 'image', 'ntext')
AND QUOTENAME(COLUMN_NAME) > @ColumnName
)
Chris
I'm not sure if this is your issue, but here's how I fixed mine.
I always had this "No DNS servers found" error when starting the emulator and did a lot of research on google to no avail. Anyway, I found a post somewhere (can't find it anymore) that was saying that the number of NICs, number of DNS entries could affect the emulator. Also, knowing that the emulator uses a Windows API function (GetNetworkParams()) to resolve DNS entries, I couldn't rely on the %WINDOWS%\System32\Hosts file.
However, I did went in the NICs properties (on Windows 7) to find that I was specifying a static IP, but no DNS entries. So, I got the DNS entries from my router and plugged them in the NICs property. I restarted the emulator and it is now using the correct DNS entries!
I can use my internet connection with the emulator now, and it works wonders!
Hope it helps!
Use head
:
dnow <- data.frame(x=rnorm(100), y=runif(100))
head(dnow,4) ## default is 6
You can either use
SELECT * FROM v$version;
or
SET SERVEROUTPUT ON
EXEC dbms_output.put_line( dbms_db_version.version );
if you don't want to parse the output of v$version.
I was hoping to add this as a comment to Marcus Westin's reply, but I can't find a link - maybe I need more reputation?
Anyway, thanks, I found this code snippet useful for quick debugging in IE. I have made some quick tweaks to fix a problem that stopped it working for me, also to scroll down automatically and use fixed positioning so it will appear in the viewport. Here's my version in case anyone finds it useful:
myLog = function() {
var _div = null;
this.toJson = function(obj) {
if (typeof window.uneval == 'function') { return uneval(obj); }
if (typeof obj == 'object') {
if (!obj) { return 'null'; }
var list = [];
if (obj instanceof Array) {
for (var i=0;i < obj.length;i++) { list.push(this.toJson(obj[i])); }
return '[' + list.join(',') + ']';
} else {
for (var prop in obj) { list.push('"' + prop + '":' + this.toJson(obj[prop])); }
return '{' + list.join(',') + '}';
}
} else if (typeof obj == 'string') {
return '"' + obj.replace(/(["'])/g, '\\$1') + '"';
} else {
return new String(obj);
}
};
this.createDiv = function() {
myLog._div = document.body.appendChild(document.createElement('div'));
var props = {
position:'fixed', top:'10px', right:'10px', background:'#333', border:'5px solid #333',
color: 'white', width: '400px', height: '300px', overflow: 'auto', fontFamily: 'courier new',
fontSize: '11px', whiteSpace: 'nowrap'
}
for (var key in props) { myLog._div.style[key] = props[key]; }
};
if (!myLog._div) { this.createDiv(); }
var logEntry = document.createElement('span');
for (var i=0; i < arguments.length; i++) {
logEntry.innerHTML += this.toJson(arguments[i]) + '<br />';
}
logEntry.innerHTML += '<br />';
myLog._div.appendChild(logEntry);
// Scroll automatically to the bottom
myLog._div.scrollTop = myLog._div.scrollHeight;
}
As you can see in the documentation of JSHint you can change options per function or per file. In your case just place a comment in your file or even more local just in the function that uses eval
:
/*jshint evil:true */
function helloEval(str) {
/*jshint evil:true */
eval(str);
}
If you want to put some page in the dialog then you can use these
function Popup()
{
$("#pop").load('login.html').dialog({
height: 625,
width: 600,
modal:true,
close: function(event,ui){
$("pop").dialog('destroy');
}
});
}
HTML:
<Div id="pop" style="display:none;">
</Div>
Hi you can download using boto3. In python
import boto3
from boto3.dynamodb.conditions import Key, Attr
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Table')
response = table.scan()
items = response['Items']
while 'LastEvaluatedKey' in response:
print(response['LastEvaluatedKey'])
response = table.scan(ExclusiveStartKey=response['LastEvaluatedKey'])
items.extend(response['Items'])
You can do the following:
Python 2.x
import hashlib
print hashlib.md5("whatever your string is").hexdigest()
Python 3.x
import hashlib
print(hashlib.md5("whatever your string is".encode('utf-8')).hexdigest())
However in this case you're probably better off using this helpful Python module for interacting with the Flickr API:
... which will deal with the authentication for you.
Official documentation of hashlib
I wanted to clarify some more use between the ;
and the /
In SQLPLUS:
;
means "terminate the current statement, execute it and store it to the SQLPLUS buffer"<newline>
after a D.M.L. (SELECT, UPDATE, INSERT,...) statement or some types of D.D.L (Creating Tables and Views) statements (that contain no ;
), it means, store the statement to the buffer but do not run it./
after entering a statement into the buffer (with a blank <newline>
) means "run the D.M.L. or D.D.L. or PL/SQL in the buffer.RUN
or R
is a sqlsplus command to show/output the SQL in the buffer and run it. It will not terminate a SQL Statement./
during the entering of a D.M.L. or D.D.L. or PL/SQL means "terminate the current statement, execute it and store it to the SQLPLUS buffer"NOTE: Because ;
are used for PL/SQL to end a statement ;
cannot be used by SQLPLUS to mean "terminate the current statement, execute it and store it to the SQLPLUS buffer" because we want the whole PL/SQL block to be completely in the buffer, then execute it. PL/SQL blocks must end with:
END;
/
In answer to the original question. Something like Dictionary<string, List<object>>
is implemented in a class called MultiMap
in The Code Project
.
You could find more info to the below link : http://www.codeproject.com/KB/cs/MultiKeyDictionary.aspx
Menu File → Preference → Settings →
Check the "Trim Trailing Whitespace" option - "When enabled, will trim trailing whitespace when saving a file".
If you are still interested, Chris Wolf made a prototype implementation of SQLite with Stored Procedures. You can find the details at his blog post: Adding Stored Procedures to SQLite
Only works in Mozilla, Chrome and Safari..
$(function() {
$('button').click(function() {
var url = 'data:application/vnd.ms-excel,' + encodeURIComponent($('#tableWrap').html())
location.href = url
return false
})
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</script>
<button>click me</button>
<div id="tableWrap">
<table>
<thead>
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</tbody>
</table>
</div>
_x000D_
add [JsonIgnore]
to virtuals properties in your model.
Just add a div around the container
so it looks like:
<div style="background: red;">
<div class="container marketing">
<h2 style="padding-top: 60px;"></h2>
</div>
</div>
Alternate solution. Include your external CSS in your HTML file by
<link rel="stylesheet" href="css/applyCSS.css"/>
inside the applyCSS.css:
#applyCSS {
/** Your Style**/
}
For whats its worth here is my standard answer. The only thing new here is that is uses the Collections.reverseOrder(). Plus it puts all suggestions into one example:
/*
** Use the Collections API to sort a List for you.
**
** When your class has a "natural" sort order you can implement
** the Comparable interface.
**
** You can use an alternate sort order when you implement
** a Comparator for your class.
*/
import java.util.*;
public class Person implements Comparable<Person>
{
String name;
int age;
public Person(String name, int age)
{
this.name = name;
this.age = age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public String toString()
{
return name + " : " + age;
}
/*
** Implement the natural order for this class
*/
public int compareTo(Person p)
{
return getName().compareTo(p.getName());
}
static class AgeComparator implements Comparator<Person>
{
public int compare(Person p1, Person p2)
{
int age1 = p1.getAge();
int age2 = p2.getAge();
if (age1 == age2)
return 0;
else if (age1 > age2)
return 1;
else
return -1;
}
}
public static void main(String[] args)
{
List<Person> people = new ArrayList<Person>();
people.add( new Person("Homer", 38) );
people.add( new Person("Marge", 35) );
people.add( new Person("Bart", 15) );
people.add( new Person("Lisa", 13) );
// Sort by natural order
Collections.sort(people);
System.out.println("Sort by Natural order");
System.out.println("\t" + people);
// Sort by reverse natural order
Collections.sort(people, Collections.reverseOrder());
System.out.println("Sort by reverse natural order");
System.out.println("\t" + people);
// Use a Comparator to sort by age
Collections.sort(people, new Person.AgeComparator());
System.out.println("Sort using Age Comparator");
System.out.println("\t" + people);
// Use a Comparator to sort by descending age
Collections.sort(people,
Collections.reverseOrder(new Person.AgeComparator()));
System.out.println("Sort using Reverse Age Comparator");
System.out.println("\t" + people);
}
}
Please try this one works for me:
<ImageView android:id="@+id/image_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:maxWidth="60dp"
android:layout_gravity="center"
android:maxHeight="60dp"
android:scaleType="fitCenter"
android:src="@drawable/icon"
/>
So what are you doing is with append and concat is almost equivalent. The difference is the empty DataFrame. For some reason this causes a big slowdown, not sure exactly why, will have to look at some point. Below is a recreation of basically what you did.
I almost always use concat (though in this case they are equivalent, except for the empty frame); if you don't use the empty frame they will be the same speed.
In [17]: df1 = pd.DataFrame(dict(A = range(10000)),index=pd.date_range('20130101',periods=10000,freq='s'))
In [18]: df1
Out[18]:
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 10000 entries, 2013-01-01 00:00:00 to 2013-01-01 02:46:39
Freq: S
Data columns (total 1 columns):
A 10000 non-null values
dtypes: int64(1)
In [19]: df4 = pd.DataFrame()
The concat
In [20]: %timeit pd.concat([df1,df2,df3])
1000 loops, best of 3: 270 us per loop
This is equavalent of your append
In [21]: %timeit pd.concat([df4,df1,df2,df3])
10 loops, best of
3: 56.8 ms per loop
I was recently working with IPFS and worked this out. A curl example for IPFS to upload a file looks like this:
curl -i -H "Content-Type: multipart/form-data; boundary=CUSTOM" -d $'--CUSTOM\r\nContent-Type: multipart/octet-stream\r\nContent-Disposition: file; filename="test"\r\n\r\nHello World!\n--CUSTOM--' "http://localhost:5001/api/v0/add"
The basic idea is that each part (split by string in boundary
with --
) has it's own headers (Content-Type
in the second part, for example.) The FormData
object manages all this for you, so it's a better way to accomplish our goals.
This translates to fetch API like this:
const formData = new FormData()
formData.append('blob', new Blob(['Hello World!\n']), 'test')
fetch('http://localhost:5001/api/v0/add', {
method: 'POST',
body: formData
})
.then(r => r.json())
.then(data => {
console.log(data)
})
From ScottGu's blog:
Starting with the ASP.NET MVC 3 Beta release, you can now add a file called _ViewStart.cshtml (or _ViewStart.vbhtml for VB) underneath the \Views folder of your project:
The _ViewStart file can be used to define common view code that you want to execute at the start of each View’s rendering. For example, we could write code within our _ViewStart.cshtml file to programmatically set the Layout property for each View to be the SiteLayout.cshtml file by default:
Because this code executes at the start of each View, we no longer need to explicitly set the Layout in any of our individual view files (except if we wanted to override the default value above).
Important: Because the _ViewStart.cshtml allows us to write code, we can optionally make our Layout selection logic richer than just a basic property set. For example: we could vary the Layout template that we use depending on what type of device is accessing the site – and have a phone or tablet optimized layout for those devices, and a desktop optimized layout for PCs/Laptops. Or if we were building a CMS system or common shared app that is used across multiple customers we could select different layouts to use depending on the customer (or their role) when accessing the site.
This enables a lot of UI flexibility. It also allows you to more easily write view logic once, and avoid repeating it in multiple places.
Also see this.
In a more general sense this ability of MVC framework to "know" about _Viewstart.cshtml is called "Coding by convention".
Convention over configuration (also known as coding by convention) is a software design paradigm which seeks to decrease the number of decisions that developers need to make, gaining simplicity, but not necessarily losing flexibility. The phrase essentially means a developer only needs to specify unconventional aspects of the application. For example, if there's a class Sale in the model, the corresponding table in the database is called “sales” by default. It is only if one deviates from this convention, such as calling the table “products_sold”, that one needs to write code regarding these names.
Wikipedia
There's no magic to it. Its just been written into the core codebase of the MVC framework and is therefore something that MVC "knows" about. That why you don't find it in the .config files or elsewhere; it's actually in the MVC code. You can however override to alter or null out these conventions.
Change the
private static final long serialVersionUID = 1L;
to any other value like
private static final long serialVersionUID = 102831973239L;
also you can generate it automatically in eclipse.
It is because each servlet in a app has a unique id.and tomcat causes problem with two servlets having same id...
To bind any data,which sends service is not a good idea (architecture),but if you need it anymore I suggest you 2 ways to do that
1) you can get the data not inside you service.You can get data inside your controller/directive and you will not have a problem to bind it anywhere
2) you can use angularjs events.Whenever you want,you can send a signal(from $rootScope) and catch it wherever you want.You can even send a data on that eventName.
Maybe this can help you. If you need more with examples,here is the link
http://www.w3docs.com/snippets/angularjs/bind-value-between-service-and-controller-directive.html
For those who are interested in the "efficiency" of the options collected so far...
Jaime RGP's answer led me to restart my computer after timing the somewhat "challenging" solution of Jason literally following my own suggestion (via comment). To spare the curious of you the downtime, I present here my results (worst-first):
Jason's answer (maybe just an excursion into the power of list comprehension):
$ python -m timeit "[9-i for i in range(10)]"
1000000 loops, best of 3: 1.54 usec per loop
martineau's answer (readable if you are familiar with the extended slices syntax):
$ python -m timeit "range(10)[::-1]"
1000000 loops, best of 3: 0.743 usec per loop
Michal Šrajer's answer (the accepted one, very readable):
$ python -m timeit "reversed(range(10))"
1000000 loops, best of 3: 0.538 usec per loop
bene's answer (the very first, but very sketchy at that time):
$ python -m timeit "range(9,-1,-1)"
1000000 loops, best of 3: 0.401 usec per loop
The last option is easy to remember using the range(n-1,-1,-1)
notation by Val Neekman.
It was a silly issue on my side, I had added a defaultproxy to my web.config in order to intercept traffic in Fiddler, and then forgot to remove it!
in additional to your way
you could call system ps command and get memory usage from it output.
or read info from /proc/pid ( see PIOCPSINFO struct )
Update:
So just to verify, it is not currently possible to set the click_action
parameter via the Firebase Console.
So I've been trying to do this in the Firebase Notifications Console with no luck. Since I can't seem to find anywhere to place the click_action
value in the console, what I mainly did to test this out is to add a custom key/value pair in the Notification (Advance Options > Custom Data):
Key: click_action
Value: <your_preferred_value>
then tried calling RemoteMessage.getNotification().getClickAction() in onMessageReceived()
to see if it was retrieving the correct value, but it always returns null
. So next I tried calling RemoteMessage.getData().get(< specified_key >) and was able to retrieve the value I added.
NOTE: I am not entirely sure if that is okay to be used as a workaround, or if it's against best practice. I would suggest using your own app server but your post is specific to the Firebase Console.
The way the client app and the notification behaves still depends on how you program it. With that said, I think you can use the above as a workaround, using the value retrieved from the getData()
, then having the Notification call this or that. Hope this helps somehow. Cheers! :D
You can use the following.
window.open(
'https://google.com',
'_blank' // <- This is what makes it open in a new window.
);
in HTML
<button class="btn btn-success" onclick=" window.open('http://google.com','_blank')"> Google</button>
Bringing this question up to date by providing this answer.
appdmg
is a simple, easy-to-use, open-source command line program that creates dmg-files from a simple json specification. Take a look at the readme at the official website:
https://github.com/LinusU/node-appdmg
Quick example:
Install appdmg
npm install -g appdmg
Write a json file (spec.json
)
{
"title": "Test Title",
"background": "background.png",
"icon-size": 80,
"contents": [
{ "x": 192, "y": 344, "type": "file", "path": "TestApp.app" },
{ "x": 448, "y": 344, "type": "link", "path": "/Applications" }
]
}
Run program
appdmg spec.json test.dmg
(disclaimer. I'm the creator of appdmg)
Just use dt.Clear()
Also you can set your TableAdapter/DataAdapter to clear before it fills with data.
I know this is an expansion off of @tibor-udvari's answer, but for a nicer copy and paste.
async function createFile(url, type){
if (typeof window === 'undefined') return // make sure we are in the browser
const response = await fetch(url)
const data = await response.blob()
const metadata = {
type: type || 'video/quicktime'
}
return new File([data], url, metadata)
}
I believe this example is more barebones and easier to understand then @dowomenfart.
.child {
display: inline-block;
margin: 0 1em;
flex-grow: 1;
width: calc(25% - 2em);
}
This accomplishes the same width calculations while cutting straight to the meat. The math is way easier and em
is the new standard due to its scalability and mobile-friendliness.
The modern recommendation is to use NSURLs for files and directories instead of NSString based paths:
So to get the Document directory for the app as an NSURL:
func databaseURL() -> NSURL? {
let fileManager = NSFileManager.defaultManager()
let urls = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
if let documentDirectory: NSURL = urls.first as? NSURL {
// This is where the database should be in the documents directory
let finalDatabaseURL = documentDirectory.URLByAppendingPathComponent("items.db")
if finalDatabaseURL.checkResourceIsReachableAndReturnError(nil) {
// The file already exists, so just return the URL
return finalDatabaseURL
} else {
// Copy the initial file from the application bundle to the documents directory
if let bundleURL = NSBundle.mainBundle().URLForResource("items", withExtension: "db") {
let success = fileManager.copyItemAtURL(bundleURL, toURL: finalDatabaseURL, error: nil)
if success {
return finalDatabaseURL
} else {
println("Couldn't copy file to final location!")
}
} else {
println("Couldn't find initial database in the bundle!")
}
}
} else {
println("Couldn't get documents directory!")
}
return nil
}
This has rudimentary error handling, as that sort of depends on what your application will do in such cases. But this uses file URLs and a more modern api to return the database URL, copying the initial version out of the bundle if it does not already exist, or a nil in case of error.
You can use The Oracle Enterprise Manager to monitor the active sessions, with the query that is being executed, its execution plan, locks, some statistics and even a progress bar for the longer tasks.
See: http://download.oracle.com/docs/cd/B10501_01/em.920/a96674/db_admin.htm#1013955
Go to Instance -> sessions and watch the SQL Tab of each session.
There are other ways. Enterprise manager just puts with pretty colors what is already available in specials views like those documented here: http://www.oracle.com/pls/db92/db92.catalog_views?remark=homepage
And, of course you can also use Explain PLAN FOR, TRACE tool and tons of other ways of instrumentalization. There are some reports in the enterprise manager for the top most expensive SQL Queries. You can also search recent queries kept on the cache.
Here is a version that will handle multiple files drag and dropped from windows. Based on the above works by
Christian Lemer
plang
ScottF
Open Notepad, create a file called XlsToCsv.vbs and paste this in:
'* Usage: Drop .xl* files on me to export each sheet as CSV
'* Global Settings and Variables
Dim gSkip
Set args = Wscript.Arguments
For Each sFilename In args
iErr = ExportExcelFileToCSV(sFilename)
' 0 for normal success
' 404 for file not found
' 10 for file skipped (or user abort if script returns 10)
Next
WScript.Quit(0)
Function ExportExcelFileToCSV(sFilename)
'* Settings
Dim oExcel, oFSO, oExcelFile
Set oExcel = CreateObject("Excel.Application")
Set oFSO = CreateObject("Scripting.FileSystemObject")
iCSV_Format = 6
'* Set Up
sExtension = oFSO.GetExtensionName(sFilename)
if sExtension = "" then
ExportExcelFileToCSV = 404
Exit Function
end if
sTest = Mid(sExtension,1,2) '* first 2 letters of the extension, vb's missing a Like operator
if not (sTest = "xl") then
if (PromptForSkip(sFilename,oExcel)) then
ExportExcelFileToCSV = 10
Exit Function
end if
End If
sAbsoluteSource = oFSO.GetAbsolutePathName(sFilename)
sAbsoluteDestination = Replace(sAbsoluteSource,sExtension,"{sheet}.csv")
'* Do Work
Set oExcelFile = oExcel.Workbooks.Open(sAbsoluteSource)
For Each oSheet in oExcelFile.Sheets
sThisDestination = Replace(sAbsoluteDestination,"{sheet}",oSheet.Name)
oExcelFile.Sheets(oSheet.Name).Select
oExcelFile.SaveAs sThisDestination, iCSV_Format
Next
'* Take Down
oExcelFile.Close False
oExcel.Quit
ExportExcelFileToCSV = 0
Exit Function
End Function
Function PromptForSkip(sFilename,oExcel)
if not (VarType(gSkip) = vbEmpty) then
PromptForSkip = gSkip
Exit Function
end if
Dim oFSO
Set oFSO = CreateObject("Scripting.FileSystemObject")
sPrompt = vbCRLF & _
"A filename was received that doesn't appear to be an Excel Document." & vbCRLF & _
"Do you want to skip this and all other unrecognized files? (Will only prompt this once)" & vbCRLF & _
"" & vbCRLF & _
"Yes - Will skip all further files that don't have a .xl* extension" & vbCRLF & _
"No - Will pass the file to excel regardless of extension" & vbCRLF & _
"Cancel - Abort any further conversions and exit this script" & vbCRLF & _
"" & vbCRLF & _
"The unrecognized file was:" & vbCRLF & _
sFilename & vbCRLF & _
"" & vbCRLF & _
"The path returned by the system was:" & vbCRLF & _
oFSO.GetAbsolutePathName(sFilename) & vbCRLF
sTitle = "Unrecognized File Type Encountered"
sResponse = MsgBox (sPrompt,vbYesNoCancel,sTitle)
Select Case sResponse
Case vbYes
gSkip = True
Case vbNo
gSkip = False
Case vbCancel
oExcel.Quit
WScript.Quit(10) '* 10 Is the error code I use to indicate there was a user abort (1 because wasn't successful, + 0 because the user chose to exit)
End Select
PromptForSkip = gSkip
Exit Function
End Function
Use OutlineButton
instead of FlatButton
.
new OutlineButton(
child: new Text("Button text"),
onPressed: null,
shape: new RoundedRectangleBorder(borderRadius: new BorderRadius.circular(30.0))
)
Apart from other answers, one could also use format()
print("a + b as integers: {}".format(c))
For example -
hours = 13
minutes = 32
print("Time elapsed - {} hours and {} minutes".format(hours, minutes))
will result in output - Time elapsed - 13 hours and 32 minutes
Check out docs for more information.
This is the recommended way.
$datetime = new DateTime('2010-12-30 23:21:46');
echo $datetime->format(DateTime::ATOM); // Updated ISO8601
For older versions of PHP, or if you are more comfortable with procedural code.
echo date(DATE_ISO8601, strtotime('2010-12-30 23:21:46'));
I just installed the 32bit 11g R2 Express edition version on 64bit windows, created a new database and performed some queries. Seems to work like it should work! :-) I followed the following easy guide!
I wanted a one-liner that didn't download any files; here is an example of piping the cookie output into the next request. I only tested the following on Gentoo, but it should work in most *nix environments:
wget -q -O /dev/null --save-cookies /dev/stdout --post-data 'u=user&p=pass' 'http://example.com/login' | wget -q -O - --load-cookies /dev/stdin 'http://example.com/private/page'
(This is one line, though it likely wraps on your browser)
If you want the output saved to a file, change -O -
to -O /some/file/name.ext
Yes, I can give you the outline but my Python is a bit rusty and I'm too busy to explain in detail.
Basically, you need to put a proxy in the method that will call the original, eg:
class fred(object):
def blog(self):
print "We Blog"
class methCallLogger(object):
def __init__(self, meth):
self.meth = meth
def __call__(self, code=None):
self.meth()
# would also log the fact that it invoked the method
#example
f = fred()
f.blog = methCallLogger(f.blog)
This StackOverflow answer about callable may help you understand the above.
In more detail:
Although the answer was accepted, due to the interesting discussion with Glenn and having a few minutes free, I wanted to enlarge on my answer:
# helper class defined elsewhere
class methCallLogger(object):
def __init__(self, meth):
self.meth = meth
self.was_called = False
def __call__(self, code=None):
self.meth()
self.was_called = True
#example
class fred(object):
def blog(self):
print "We Blog"
f = fred()
g = fred()
f.blog = methCallLogger(f.blog)
g.blog = methCallLogger(g.blog)
f.blog()
assert(f.blog.was_called)
assert(not g.blog.was_called)
An actual JSON request would look like this:
data: '{"command":"on"}',
Where you're sending an actual JSON string. For a more general solution, use JSON.stringify()
to serialize an object to JSON, like this:
data: JSON.stringify({ "command": "on" }),
To support older browsers that don't have the JSON
object, use json2.js which will add it in.
What's currently happening is since you have processData: false
, it's basically sending this: ({"command":"on"}).toString()
which is [object Object]
...what you see in your request.
Pandas: How to replace NaN (nan
) values with the average (mean), median or other statistics of one column
Say your DataFrame is df
and you have one column called nr_items
. This is: df['nr_items']
If you want to replace the NaN
values of your column df['nr_items']
with the mean of the column:
Use method .fillna()
:
mean_value=df['nr_items'].mean()
df['nr_item_ave']=df['nr_items'].fillna(mean_value)
I have created a new df
column called nr_item_ave
to store the new column with the NaN
values replaced by the mean
value of the column.
You should be careful when using the mean
. If you have outliers is more recommendable to use the median
NOTE: Greatly inspired by EscapeNetscape's answer, I've made an edit of his script using modern javascript in a comment. I made an answer of this due to user interest and a massive 4h jsfiddle.net downtime. I chose not to edit the original answer since it would change everything...
Here is a detectSwipe
function, working pretty well (used on one of my websites). I'd suggest you read it before you use it. Feel free to review it/edit the answer.
// usage example_x000D_
detectSwipe('swipeme', (el, dir) => alert(`you swiped on element with id ${el.id} to ${dir} direction`))_x000D_
_x000D_
// source code_x000D_
_x000D_
// Tune deltaMin according to your needs. Near 0 it will almost_x000D_
// always trigger, with a big value it can never trigger._x000D_
function detectSwipe(id, func, deltaMin = 90) {_x000D_
const swipe_det = {_x000D_
sX: 0,_x000D_
sY: 0,_x000D_
eX: 0,_x000D_
eY: 0_x000D_
}_x000D_
// Directions enumeration_x000D_
const directions = Object.freeze({_x000D_
UP: 'up',_x000D_
DOWN: 'down',_x000D_
RIGHT: 'right',_x000D_
LEFT: 'left'_x000D_
})_x000D_
let direction = null_x000D_
const el = document.getElementById(id)_x000D_
el.addEventListener('touchstart', function(e) {_x000D_
const t = e.touches[0]_x000D_
swipe_det.sX = t.screenX_x000D_
swipe_det.sY = t.screenY_x000D_
}, false)_x000D_
el.addEventListener('touchmove', function(e) {_x000D_
// Prevent default will stop user from scrolling, use with care_x000D_
// e.preventDefault();_x000D_
const t = e.touches[0]_x000D_
swipe_det.eX = t.screenX_x000D_
swipe_det.eY = t.screenY_x000D_
}, false)_x000D_
el.addEventListener('touchend', function(e) {_x000D_
const deltaX = swipe_det.eX - swipe_det.sX_x000D_
const deltaY = swipe_det.eY - swipe_det.sY_x000D_
// Min swipe distance, you could use absolute value rather_x000D_
// than square. It just felt better for personnal use_x000D_
if (deltaX ** 2 + deltaY ** 2 < deltaMin ** 2) return_x000D_
// horizontal_x000D_
if (deltaY === 0 || Math.abs(deltaX / deltaY) > 1)_x000D_
direction = deltaX > 0 ? directions.RIGHT : directions.LEFT_x000D_
else // vertical_x000D_
direction = deltaY > 0 ? directions.UP : directions.DOWN_x000D_
_x000D_
if (direction && typeof func === 'function') func(el, direction)_x000D_
_x000D_
direction = null_x000D_
}, false)_x000D_
}
_x000D_
#swipeme {_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
background-color: orange;_x000D_
color: black;_x000D_
text-align: center;_x000D_
padding-top: 20%;_x000D_
padding-bottom: 20%;_x000D_
}
_x000D_
<div id='swipeme'>_x000D_
swipe me_x000D_
</div>
_x000D_
I was running a script from batch file as SYSTEM user and all variables like process.cwd()
, path.resolve()
and all other methods would give me path to C:\Windows\System32 folder instead of actual path. During experiments I noticed that when an error is thrown the stack contains a true path to the node file.
Here's a very hacky way to get true path by triggering an error and extracting path from e.stack. Do not use.
// this should be the name of currently executed file
const currentFilename = 'index.js';
function veryHackyGetFolder() {
try {
throw new Error();
} catch(e) {
const fullMsg = e.stack.toString();
const beginning = fullMsg.indexOf('file:///') + 8;
const end = fullMsg.indexOf('\/' + currentFilename);
const dir = fullMsg.substr(beginning, end - beginning).replace(/\//g, '\\');
return dir;
}
}
Usage
const dir = veryHackyGetFolder();
var = None
"clears the value", setting the value of the variable to "null" like value of "None", however the pointer to the variable remains.
del var
removes the definition for the variable totally.
In case you want to use the variable later, e.g. set a new value for it, i.e. retain the variable, None
would be better.
It is useful when you share a variable between a few modules. You define it in one module, and use extern in the others.
For example:
in file1.cpp:
int global_int = 1;
in file2.cpp:
extern int global_int;
//in some function
cout << "global_int = " << global_int;
If I get you right, you need ..\..\src
Well it depends, if you want to bind datas, there shouldn't be any formatting in it, otherwise you can bind-html
and do description.replace(/\\n/g, '<br>')
not sure it's what you want though.
You need to use the file:///
protocol (yes, that's three slashes) if you want to link to local files.
<a href="file:///C:\Programs\sort.mw">Link 1</a>
<a href="file:///C:\Videos\lecture.mp4">Link 2</a>
These will never open the file in your local applications automatically. That's for security reasons which I'll cover in the last section. If it opens, it will only ever open in the browser. If your browser can display the file, it will, otherwise it will probably ask you if you want to download the file.
Modern versions of many browsers (e.g. Firefox and Chrome) will refuse to cross from the http(s) protocol to the file protocol to prevent malicious behaviour.
This means a webpage hosted on a website somewhere will never be able to link to files on your hard drive. You'll need to open your webpage locally using the file protocol if you want to do this stuff at all.
file:///
?The first part of a URL is the protocol. A protocol is a few letters, then a colon and two slashes. HTTP://
and FTP://
are valid protocols; C:/
isn't and I'm pretty sure it doesn't even properly resemble one.
C:/
also isn't a valid web address. The browser could assume it's meant to be http://c/
with a blank port specified, but that's going to fail.
Your browser may not assume it's referring to a local file. It has little reason to make that assumption because webpages generally don't try to link to peoples' local files.
So if you want to access local files: tell it to use the file protocol.
Because it's part of the File URI scheme. You have the option of specifying a host after the first two slashes. If you skip specifying a host it will just assume you're referring to a file on your own PC. This means file:///C:/etc
is a shortcut for file://localhost/C:/etc
.
Your browser will respond to these files the same way they'd respond to the same file anywhere on the internet. These files will not open in your default file handler (e.g. MS Word or VLC Media Player), and you will not be able to do anything like ask File Explorer to open the file's location.
This is an extremely good thing for your security.
Sites in your browser cannot interact with your operating system very well. If a good site could tell your machine to open lecture.mp4 in VLC.exe, a malicious site could tell it to open virus.bat in CMD.exe. Or it could just tell your machine to run a few Uninstall.exe files or open File Explorer a million times.
This may not be convenient for you, but HTML and browser security weren't really designed for what you're doing. If you want to be able to open lecture.mp4 in VLC.exe consider writing a desktop application instead.
One of the best explanation of lambda expression
is given from author of C++ Bjarne Stroustrup in his book ***The C++ Programming Language***
chapter 11 (ISBN-13: 978-0321563842):
What is a lambda expression?
A lambda expression, sometimes also referred to as a lambda function or (strictly speaking incorrectly, but colloquially) as a lambda, is a simplified notation for defining and using an anonymous function object. Instead of defining a named class with an operator(), later making an object of that class, and finally invoking it, we can use a shorthand.
When would I use one?
This is particularly useful when we want to pass an operation as an argument to an algorithm. In the context of graphical user interfaces (and elsewhere), such operations are often referred to as callbacks.
What class of problem do they solve that wasn't possible prior to their introduction?
Here i guess every action done with lambda expression can be solved without them, but with much more code and much bigger complexity. Lambda expression this is the way of optimization for your code and a way of making it more attractive. As sad by Stroustup :
effective ways of optimizing
Some examples
via lambda expression
void print_modulo(const vector<int>& v, ostream& os, int m) // output v[i] to os if v[i]%m==0
{
for_each(begin(v),end(v),
[&os,m](int x) {
if (x%m==0) os << x << '\n';
});
}
or via function
class Modulo_print {
ostream& os; // members to hold the capture list int m;
public:
Modulo_print(ostream& s, int mm) :os(s), m(mm) {}
void operator()(int x) const
{
if (x%m==0) os << x << '\n';
}
};
or even
void print_modulo(const vector<int>& v, ostream& os, int m)
// output v[i] to os if v[i]%m==0
{
class Modulo_print {
ostream& os; // members to hold the capture list
int m;
public:
Modulo_print (ostream& s, int mm) :os(s), m(mm) {}
void operator()(int x) const
{
if (x%m==0) os << x << '\n';
}
};
for_each(begin(v),end(v),Modulo_print{os,m});
}
if u need u can name lambda expression
like below:
void print_modulo(const vector<int>& v, ostream& os, int m)
// output v[i] to os if v[i]%m==0
{
auto Modulo_print = [&os,m] (int x) { if (x%m==0) os << x << '\n'; };
for_each(begin(v),end(v),Modulo_print);
}
Or assume another simple sample
void TestFunctions::simpleLambda() {
bool sensitive = true;
std::vector<int> v = std::vector<int>({1,33,3,4,5,6,7});
sort(v.begin(),v.end(),
[sensitive](int x, int y) {
printf("\n%i\n", x < y);
return sensitive ? x < y : abs(x) < abs(y);
});
printf("sorted");
for_each(v.begin(), v.end(),
[](int x) {
printf("x - %i;", x);
}
);
}
will generate next
0
1
0
1
0
1
0
1
0
1
0 sortedx - 1;x - 3;x - 4;x - 5;x - 6;x - 7;x - 33;
[]
- this is capture list or lambda introducer
: if lambdas
require no access to their local environment we can use it.
Quote from book:
The first character of a lambda expression is always [. A lambda introducer can take various forms:
• []: an empty capture list. This implies that no local names from the surrounding context can be used in the lambda body. For such lambda expressions, data is obtained from arguments or from nonlocal variables.
• [&]: implicitly capture by reference. All local names can be used. All local variables are accessed by reference.
• [=]: implicitly capture by value. All local names can be used. All names refer to copies of the local variables taken at the point of call of the lambda expression.
• [capture-list]: explicit capture; the capture-list is the list of names of local variables to be captured (i.e., stored in the object) by reference or by value. Variables with names preceded by & are captured by reference. Other variables are captured by value. A capture list can also contain this and names followed by ... as elements.
• [&, capture-list]: implicitly capture by reference all local variables with names not men- tioned in the list. The capture list can contain this. Listed names cannot be preceded by &. Variables named in the capture list are captured by value.
• [=, capture-list]: implicitly capture by value all local variables with names not mentioned in the list. The capture list cannot contain this. The listed names must be preceded by &. Vari- ables named in the capture list are captured by reference.
Note that a local name preceded by & is always captured by reference and a local name not pre- ceded by & is always captured by value. Only capture by reference allows modification of variables in the calling environment.
Additional
Lambda expression
format
Additional references:
One example in order to understand, where the usage of ZEROFILL
might be interesting:
In Germany, we have 5 digit zipcodes. However, those Codes may start with a Zero, so 80337
is a valid zipcode for munic, 01067
is a zipcode of Berlin.
As you see, any German citizen expects the zipcodes to be displayed as a 5 digit code, so 1067
looks strange.
In order to store those data, you could use a VARCHAR(5)
or INT(5) ZEROFILL
whereas the zerofilled integer has two big advantages:
1067
, you still get 01067
backMaybe this example helps understanding the use of ZEROFILL
.
To enable GZIP compression, you need to modify the configuration of the embedded Tomcat instance. To do so, you declare a EmbeddedServletContainerCustomizer
bean in your Java configuration and then register a TomcatConnectorCustomizer
with it.
For example:
@Bean
public EmbeddedServletContainerCustomizer servletContainerCustomizer() {
return new EmbeddedServletContainerCustomizer() {
@Override
public void customize(ConfigurableEmbeddedServletContainerFactory factory) {
((TomcatEmbeddedServletContainerFactory) factory).addConnectorCustomizers(new TomcatConnectorCustomizer() {
@Override
public void customize(Connector connector) {
AbstractHttp11Protocol httpProtocol = (AbstractHttp11Protocol) connector.getProtocolHandler();
httpProtocol.setCompression("on");
httpProtocol.setCompressionMinSize(64);
}
});
}
};
}
See the Tomcat documentation for more details on the various compression configuration options that are available.
You say that you want to selectively enable compression. Depending on your selection criteria, then the above approach may be sufficient. It enables you to control compression by the request's user-agent, the response's size, and the response's mime type.
If this doesn't meet your needs then I believe you will have to perform the compression in your controller and return a byte[] response with a gzip content-encoding header.
Like many of the algorithm functions, an initial reaction is to think it's more unreadable to use foreach than a loop. It's been a topic of many flame wars.
Once you get used to the idiom you may find it useful. One obvious advantage is that it forces the coder to separate the inner contents of the loop from the actual iteration functionality. (OK, I think it's an advantage. Other's say you're just chopping up the code with no real benifit).
One other advantage is that when I see foreach, I know that either every item will be processed or an exception will be thrown.
A for loop allows several options for terminating the loop. You can let the loop run its full course, or you can use the break keyword to explicitly jump out of the loop, or use the return keyword to exit the entire function mid-loop. In contrast, foreach does not allow these options, and this makes it more readable. You can just glance at the function name and you know the full nature of the iteration.
Here's an example of a confusing for loop:
for(std::vector<widget>::iterator i = v.begin(); i != v.end(); ++i)
{
/////////////////////////////////////////////////////////////////////
// Imagine a page of code here by programmers who don't refactor
///////////////////////////////////////////////////////////////////////
if(widget->Cost < calculatedAmountSofar)
{
break;
}
////////////////////////////////////////////////////////////////////////
// And then some more code added by a stressed out juniour developer
// *#&$*)#$&#(#)$#(*$&#(&*^$#(*$#)($*#(&$^#($*&#)$(#&*$&#*$#*)$(#*
/////////////////////////////////////////////////////////////////////////
for(std::vector<widgetPart>::iterator ip = widget.GetParts().begin(); ip != widget.GetParts().end(); ++ip)
{
if(ip->IsBroken())
{
return false;
}
}
}