for i=1,#target do
game.Players.target[i].Character:BreakJoints()
end
Is incorrect, if "target" contains "FakeNameHereSoNoStalkers" then the run code would be:
game.Players.target.1.Character:BreakJoints()
Which is completely incorrect.
c = game.Players:GetChildren()
Never use "Players:GetChildren()", it is not guaranteed to return only players.
Instead use:
c = Game.Players:GetPlayers()
if msg:lower()=="me" then
table.insert(people, source)
return people
Here you add the player's name in the list "people", where you in the other places adds the player object.
Fixed code:
local Admins = {"FakeNameHereSoNoStalkers"}
function Kill(Players)
for i,Player in ipairs(Players) do
if Player.Character then
Player.Character:BreakJoints()
end
end
end
function IsAdmin(Player)
for i,AdminName in ipairs(Admins) do
if Player.Name:lower() == AdminName:lower() then return true end
end
return false
end
function GetPlayers(Player,Msg)
local Targets = {}
local Players = Game.Players:GetPlayers()
if Msg:lower() == "me" then
Targets = { Player }
elseif Msg:lower() == "all" then
Targets = Players
elseif Msg:lower() == "others" then
for i,Plr in ipairs(Players) do
if Plr ~= Player then
table.insert(Targets,Plr)
end
end
else
for i,Plr in ipairs(Players) do
if Plr.Name:lower():sub(1,Msg:len()) == Msg then
table.insert(Targets,Plr)
end
end
end
return Targets
end
Game.Players.PlayerAdded:connect(function(Player)
if IsAdmin(Player) then
Player.Chatted:connect(function(Msg)
if Msg:lower():sub(1,6) == ":kill " then
Kill(GetPlayers(Player,Msg:sub(7)))
end
end)
end
end)
You can (should) declare it as extern
in a header file, and define it in exactly 1 .c file.
Note that that .c file should also use the header and that the standard pattern looks like:
// file.h
extern int x; // declaration
// file.c
#include "file.h"
int x = 1; // definition and re-declaration
I am using Ubuntu. I just disabled ssl mode of apache2 and it worked for me.
a2dismod ssl
and then restarted apache2.
service apache2 restart
typedef will not provide a co-dependent set of data structures. This you cannot do with typdef:
struct bar;
struct foo;
struct foo {
struct bar *b;
};
struct bar {
struct foo *f;
};
Of course you can always add:
typedef struct foo foo_t;
typedef struct bar bar_t;
What exactly is the point of that?
Your problem is that excel does not recognize your text strings of "mm/dd/yyyy" as date objects in it's internal memory. Therefore when you create pivottable it doesn't consider these strings to be dates.
You'll need to first convert your dates to actual date values before creating the pivottable. This is a good resource for that: http://office.microsoft.com/en-us/excel-help/convert-dates-stored-as-text-to-dates-HP001162867.aspx
In your spreadsheet I created a second date column in B with the formula =DATEVALUE(A2)
. Creating a pivot table with this new date column and Count of Sales
then sorts correctly in the pivot table (option becomes Sort Oldest to Newest
instead of Sort A to Z
).
These are few things which will help you in understanding everything... using iloc
In iloc, [initial row:ending row, initial column:ending column]
case 1: if you want only last column --- df.iloc[:,-1] & df.iloc[:,-1:]
this means that you want only the last column...
case 2: if you want all columns and all rows except the last column --- df.iloc[:,:-1]
this means that you want all columns and all rows except the last column...
case 3: if you want only last row --- df.iloc[-1:,:] & df.iloc[-1,:]
this means that you want only the last row...
case 4: if you want all columns and all rows except the last row --- df.iloc[:-1,:]
this means that you want all columns and all rows except the last column...
case 5: if you want all columns and all rows except the last row and last column --- df.iloc[:-1,:-1]
this means that you want all columns and all rows except the last column and last row...
If you don't want to use another ViewModel you can disable client validations on the view and also remove the validations on the server for those properties you want to ignore. Please check this answer for a deeper explanation https://stackoverflow.com/a/15248790/1128216
You should upgrade the version of gradle. for example: com.android.build.gradle 1.3.0
this issue occurs when version of the gradle is changed.
You need to add the content-disposition header to the response:
response.StatusCode = HttpStatusCode.OK;
response.Content = new StreamContent(result);
response.AppendHeader("content-disposition", "attachment; filename=" + fileName);
return response;
From C#3.5 I assume you're using WPF.
Just make a two-way data binding from an integer property to your text-box. WPF will show the validation error for you automatically.
For the email case, make a two-way data binding from a string property that does Regexp validation in the setter and throw an Exception upon validation error.
Look up Binding on MSDN.
Another alternative to @TouchBoarder's answer above is that you may also have two layout files with the same name but for different api versions. You should delete the older my_file.xml file
my_file.xml
my_file.xml(v21)
I was looking into this but wanted to have a different transition rate for in and out.
This is what I ended up doing:
//css
.addedClass {
background: #5eb4fc;
}
// js
function setParentTransition(id, prop, delay, style, callback) {
$(id).css({'-webkit-transition' : prop + ' ' + delay + ' ' + style});
$(id).css({'-moz-transition' : prop + ' ' + delay + ' ' + style});
$(id).css({'-o-transition' : prop + ' ' + delay + ' ' + style});
$(id).css({'transition' : prop + ' ' + delay + ' ' + style});
callback();
}
setParentTransition(id, 'background', '0s', 'ease', function() {
$('#elementID').addClass('addedClass');
});
setTimeout(function() {
setParentTransition(id, 'background', '2s', 'ease', function() {
$('#elementID').removeClass('addedClass');
});
});
This instantly turns the background color to #5eb4fc and then slowly fades back to normal over 2 seconds.
Here's a fiddle
Good and convenient solution:
In your ViewController:
@IBOutlet weak var label: LabelButton!
override func viewDidLoad() {
super.viewDidLoad()
self.label.onClick = {
// TODO
}
}
You can place this in your ViewController or in another .swift file(e.g. CustomView.swift):
@IBDesignable class LabelButton: UILabel {
var onClick: () -> Void = {}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
onClick()
}
}
In Storyboard select Label and on right pane in "Identity Inspector" in field class select LabelButton.
Don't forget to enable in Label Attribute Inspector "User Interaction Enabled"
Dictionaries are not Serializable in C# by default, I don't know why, but it seems to have been a design choice.
Right now, I'd recommend using Json.NET to convert it to JSON and from there into a dictionary (and vice versa). Unless you really need the XML, I'd recommend using JSON completely.
I prefer the Execute via SQL*Plus option. It's in the little down-arrow menu under the "Execute as script" toolbar button.
//if passed exMins=0 it will delete as soon as it creates it.
function setCookie(cname, cvalue, exMins) {
var d = new Date();
d.setTime(d.getTime() + (exMins*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
setCookie('cookieNameToDelete','',0) // this will delete the cookie.
The link you gave seems to be attempting something different to the test you are trying to avoid repeating.
if (a == null || a=='')
tests if the string is an empty string or null. The article you linked to tests if the string consists entirely of whitespace (or is empty).
The test you described can be replaced by:
if (!a)
Because in javascript, an empty string, and null, both evaluate to false in a boolean context.
version 4.7.1 was slightly different : for import:
import org.antlr.v4.runtime.*;
for the main segment - note the CharStreams:
CharStream in = CharStreams.fromString("12*(5-6)");
ExpLexer lexer = new ExpLexer(in);
CommonTokenStream tokens = new CommonTokenStream(lexer);
ExpParser parser = new ExpParser(tokens);
Try the following regex:
var removedText = self.val().replace(/[^0-9]/, '');
This will match every character that is not (^
) in the interval 0-9.
Demo.
From Laravel 5.7 with Illuminate\Database\Query\Builder
you can use insertUsing method.
$query = [];
foreach($oXML->results->item->item as $oEntry){
$date = date("Y-m-d H:i:s")
$query[] = "('{$oEntry->firstname}', '{$oEntry->lastname}', '{$date}')";
}
Builder::insertUsing(['first_name', 'last_name', 'date_added'], implode(', ', $query));
diff -r
will do this, telling you both if any files have been added or deleted, and what's changed in the files that have been modified.
Take a look at the ListBox control to allow multi-select.
<asp:ListBox runat="server" ID="lblMultiSelect" SelectionMode="multiple">
<asp:ListItem Text="opt1" Value="opt1" />
<asp:ListItem Text="opt2" Value="opt2" />
<asp:ListItem Text="opt3" Value="opt3" />
</asp:ListBox>
in the code behind
foreach(ListItem listItem in lblMultiSelect.Items)
{
if (listItem.Selected)
{
var val = listItem.Value;
var txt = listItem.Text;
}
}
Here I wrote one for dd/mm/yyyy
where separator can be one of -.,/
year range 0000-9999
.
It deals with leap years and is designed for regex flavors, that support lookaheads, capturing groups and backreferences. NOT valid for such as d/m/yyyy
. If needed add further separators to [-.,/]
^(?=\d{2}([-.,\/])\d{2}\1\d{4}$)(?:0[1-9]|1\d|[2][0-8]|29(?!.02.(?!(?!(?:[02468][1-35-79]|[13579][0-13-57-9])00)\d{2}(?:[02468][048]|[13579][26])))|30(?!.02)|31(?=.(?:0[13578]|10|12))).(?:0[1-9]|1[012]).\d{4}$
Test at regex101; as a Java string:
"^(?=\\d{2}([-.,\\/])\\d{2}\\1\\d{4}$)(?:0[1-9]|1\\d|[2][0-8]|29(?!.02.(?!(?!(?:[02468][1-35-79]|[13579][0-13-57-9])00)\\d{2}(?:[02468][048]|[13579][26])))|30(?!.02)|31(?=.(?:0[13578]|10|12))).(?:0[1-9]|1[012]).\\d{4}$"
explained:
(?x) # modifier x: free spacing mode (for comments)
# verify date dd/mm/yyyy; possible separators: -.,/
# valid year range: 0000-9999
^ # start anchor
# precheck xx-xx-xxxx,... add new separators here
(?=\d{2}([-.,\/])\d{2}\1\d{4}$)
(?: # day-check: non caturing group
# days 01-28
0[1-9]|1\d|[2][0-8]|
# february 29d check for leap year: all 4y / 00 years: only each 400
# 0400,0800,1200,1600,2000,...
29
(?!.02. # not if feb: if not ...
(?!
# 00 years: exclude !0 %400 years
(?!(?:[02468][1-35-79]|[13579][0-13-57-9])00)
# 00,04,08,12,...
\d{2}(?:[02468][048]|[13579][26])
)
)|
# d30 negative lookahead: february cannot have 30 days
30(?!.02)|
# d31 positive lookahead: month up to 31 days
31(?=.(?:0[13578]|10|12))
) # eof day-check
# month 01-12
.(?:0[1-9]|1[012])
# year 0000-9999
.\d{4}
$ # end anchor
Also see SO Regex FAQ; Please let me know, if it fails.
The following is a solution for MySQL (not SQL Server), i couldn't easily find a solution to this on stackoverflow for mysql, so i figured maybe this could help someone...
ref: https://forums.mysql.com/read.php?10,285268,285286#msg-285286
original query...
SELECT StudentId FROM Student WHERE condition = xyz
original result set...
StudentId
1236
7656
8990
new query w/ concat...
SELECT group_concat(concat_ws(',', StudentId) separator '; ')
FROM Student
WHERE condition = xyz
concat string result set...
StudentId
1236; 7656; 8990
note: change the 'separator' to whatever you would like
GLHF!
I've deleted java files at windows/system32 and I also have removed c:\ProgramData\Oracle\Java\javapath from the PATH variable, because there was 3 symlinks to java 1.8 files.
I had JDK 1.7 in the %JAVA_HOME% variable and java1.7/bin in the PATH.
PS1: My problem was between Java 1.7 and Java 1.8.
PS2: I can't add this as a comment to Victor's answer because I haven't enough points.
Well by studying the code above a bit (specifically using TextTestRunner
and defaultTestLoader
), I was able to get pretty close. Eventually I fixed my code by also just passing all test suites to a single suites constructor, rather than adding them "manually", which fixed my other problems. So here is my solution.
import glob
import unittest
test_files = glob.glob('test_*.py')
module_strings = [test_file[0:len(test_file)-3] for test_file in test_files]
suites = [unittest.defaultTestLoader.loadTestsFromName(test_file) for test_file in module_strings]
test_suite = unittest.TestSuite(suites)
test_runner = unittest.TextTestRunner().run(test_suite)
Yeah, it is probably easier to just use nose than to do this, but that is besides the point.
You can use this:
function getMeta(metaName) {
const metas = document.getElementsByTagName('meta');
for (let i = 0; i < metas.length; i++) {
if (metas[i].getAttribute('name') === metaName) {
return metas[i].getAttribute('content');
}
}
return '';
}
console.log(getMeta('video'));
http://msdn.microsoft.com/en-us/library/system.type.gettype.aspx
Console.WriteLine("typeField is a {0}", typeField.GetType());
which would give you something like
typeField is a String
typeField is a DateTime
or
http://msdn.microsoft.com/en-us/library/58918ffs(v=vs.71).aspx
A quick way to execute some time-consuming operation in any constructor is by creating an action and run them asynchronously.
new Action( async() => await InitializeThingsAsync())();
Running this piece of code will neither block your UI nor leave you with any loose threads. And if you need to update any UI (considering you are not using MVVM approach), you can use the Dispatcher to do so as many have suggested.
A Note: This option only provides you a way to start an execution of a method from the constructor if you don't have any init
or onload
or navigated
overrides. Most likely this will keep on running even after the construction has been completed. Hence the result of this method call may NOT be available in the constructor itself.
2018 edit: This answer is from 2011, before browsers had widely supported array filtering methods and arrow functions. Have a look at CAFxX's answer.
There is no "magic" way to check for something in an array without a loop. Even if you use some function, the function itself will use a loop. What you can do is break out of the loop as soon as you find what you're looking for to minimize computational time.
var found = false;
for(var i = 0; i < vendors.length; i++) {
if (vendors[i].Name == 'Magenic') {
found = true;
break;
}
}
Look at the traceback:
Traceback (most recent call last):
File "C:\Python33\lib\site-packages\bottle.py", line 821, in _cast
out = iter(out)
TypeError: 'bool' object is not iterable
Your code isn't iterating the value, but the code receiving it is.
The solution is: return an iterable. I suggest that you either convert the bool to a string (str(False)
) or enclose it in a tuple ((False,)
).
Always read the traceback: it's correct, and it's helpful.
I am very late for answering this question still i want to share this answer so that in future anyone can use this.
I have used this code in my project it works in lower version as well as higher version.
Just use this theme inside onCreateDialog() like this :
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
View view = getActivity().getLayoutInflater().inflate(R.layout.dialog_pump_details, null);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), android.R.style.Theme_Black_NoTitleBar_Fullscreen);
return builder.create();
}
android.R.style.Theme_Black_NoTitleBar_Fullscreen - Here is the source code for this theme you can see only this theme is enough to make DialogFragment appear in full screen.
<!-- Variant of {@link #Theme_Black} that has no title bar and
no status bar. This theme
sets {@link android.R.attr#windowFullscreen} to true. -->
<style name="Theme.Black.NoTitleBar.Fullscreen">
<item name="windowFullscreen">true</item>
<item name="windowContentOverlay">@null</item>
</style>
Please let me know if anyone face any issue. Hope this is helpful. Thanks :)
You can use snprintf to get a substring of a char array with precision. Here is a file example called "substring.c":
#include <stdio.h>
int main()
{
const char source[] = "This is a string array";
char dest[17];
// get first 16 characters using precision
snprintf(dest, sizeof(dest), "%.16s", source);
// print substring
puts(dest);
} // end main
Output:
This is a string
Note:
For further information see printf man page.
If you are using XAMPP in Mac OS X and have installed MySQL with Homebrew you may have this problem. In XAMPP manager window go to Manage Servers and select MySQL, then click configure and open the configuration file, there you have the socket file path, put the path in your MySQL host config and it should work.
It's something like this:
...
[client]
#password = your_password
port = 3306
socket = /Applications/XAMPP/xamppfiles/var/mysql/mysql.sock
...
then, for instance in Django:
...
DATABASES = {
"default": {
"ENGINE": "django.db.backends.mysql",
"NAME": "database_name",
"USER": "user",
"PASSWORD": "password",
"HOST": "/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock",
"PORT": "",
}
}
...
Hope this helps.
@echo off :start :: Insert your code here echo.%%1 is now:%~1 :: End insert your code here if "%~2" NEQ "" ( shift goto :start )
It looks like you are trying to read an object from JSON that actually describes an array. Java objects are mapped to JSON objects with curly braces {}
but your JSON actually starts with square brackets []
designating an array.
What you actually have is a List<product>
To describe generic types, due to Java's type erasure, you must use a TypeReference
. Your deserialization could read: myProduct = objectMapper.readValue(productJson, new TypeReference<List<product>>() {});
A couple of other notes: your classes should always be PascalCased. Your main method can just be public static void main(String[] args) throws Exception
which saves you all the useless catch
blocks.
$("#test").keyup(
function () {
this.value = this.value.substr(0, 1).toUpperCase() + this.value.substr(1).toLowerCase();
}
);
check this code:
CREATE TRIGGER trig_Update_Employee ON [EmployeeResult] FOR INSERT AS Begin
Insert into Employee (Name, Department)
Select Distinct i.Name, i.Department
from Inserted i
Left Join Employee e on i.Name = e.Name and i.Department = e.Department
where e.Name is null
End
Put in gradle.properties file the following code line:
org.gradle.java.home=C:\\Program Files\\Java\\jdk1.8.0_45
HttpUtility.ParseQueryString will work as long as you are in a web app or don't mind including a dependency on System.Web. Another way to do this is:
NameValueCollection queryParameters = new NameValueCollection();
string[] querySegments = queryString.Split('&');
foreach(string segment in querySegments)
{
string[] parts = segment.Split('=');
if (parts.Length > 0)
{
string key = parts[0].Trim(new char[] { '?', ' ' });
string val = parts[1].Trim();
queryParameters.Add(key, val);
}
}
function my_simple_crypt( $string, $action = 'e' ) {
// you may change these values to your own
$secret_key = 'my_simple_secret_key';
$secret_iv = 'my_simple_secret_iv';
$output = false;
$encrypt_method = "AES-256-CBC";
$key = hash( 'sha256', $secret_key );
$iv = substr( hash( 'sha256', $secret_iv ), 0, 16 );
if( $action == 'e' ) {
$output = base64_encode( openssl_encrypt( $string, $encrypt_method, $key, 0, $iv ) );
}
else if( $action == 'd' ){
$output = openssl_decrypt( base64_decode( $string ), $encrypt_method, $key, 0, $iv );
}
return $output;
}
For "Visual Studio Team Test" it appears you apply the ExpectedException attribute to the test's method.
Sample from the documentation here: A Unit Testing Walkthrough with Visual Studio Team Test
[TestMethod]
[ExpectedException(typeof(ArgumentException),
"A userId of null was inappropriately allowed.")]
public void NullUserIdInConstructor()
{
LogonInfo logonInfo = new LogonInfo(null, "P@ss0word");
}
DECLARE @MyList TABLE (Value INT)
INSERT INTO @MyList VALUES (1)
INSERT INTO @MyList VALUES (2)
INSERT INTO @MyList VALUES (3)
INSERT INTO @MyList VALUES (4)
SELECT *
FROM MyTable
WHERE MyColumn IN (SELECT Value FROM @MyList)
If you already fetched your remote branch and do git branch -a
,
you obtain something like :
* 8.0
xxx
remotes/origin/xxx
remotes/origin/8.0
remotes/origin/HEAD -> origin/8.0
remotes/rep_mirror/8.0
After that, you can use rep_mirror/8.0
to designate locally your remote branch.
The trick is that remotes/rep_mirror/8.0
doesn't work but rep_mirror/8.0
does.
So, a command like git merge -m "my msg" rep_mirror/8.0
do the merge.
(note : this is a comment to @VonC answer. I put it as another answer because code blocks don't fit into the comment format)
As Greg D said, I think that an alternative to Automation
to click a button using the MVVM pattern (click event raised and command executed) is to call the OnClick
method using reflection:
typeof(System.Windows.Controls.Primitives.ButtonBase).GetMethod("OnClick", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(button, new object[0]);
Usinge the file
argument in the print
function, you can have different files per print:
print('Redirect output to file', file=open('/tmp/example.log', 'w'))
You can use btoa()/atob() in browser, but some improvements required, as described here https://base64tool.com/uncaught-domexception-btoa-on-window/ and there https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/btoa for UTF strings support!
Resource based .aar-projects
Finding the classes.jar file inside the .aar file is pretty trivial. However, that approach does not work, if the .aar-project defined some resources (example: R.layout.xyz)
Therefore deaar from CommonsGuy helped me to get a valid ADT-friendly project out of an .aar-file. In my case I converted subsampling-scale-image-view. It took me about an hour to set up ruby on my PC.
Another approach is using android-maven-plugin for Eclipse/ADT as CommonsGuy writes in his blog.
Yet another approach could be, just cloning the whole desired project as source from git and import it as "Existing Android project"
So there is another way you can actually fire it from any language. The best way I think, you can just create a batch file which will call your .dtsx package.
Next you call the batch file from any language. As in windows platform, you can run batch file from anywhere, I think this will be the most generic approach for your purpose. No code dependencies.
Below is a blog for more details..
https://www.mssqltips.com/sqlservertutorial/218/command-line-tool-to-execute-ssis-packages/
Happy coding.. :)
Thanks, Ayan
The built-in string constructor will automatically call obj.__str__
:
''.join(map(str,list))
(char)myint;
for example:
Console.WriteLine("(char)122 is {0}", (char)122);
yields:
(char)122 is z
In Java, once you have the reference of the button:
Button button = (Button) findviewById(R.id.button);
To enable/disable the button, you can use either:
button.setEnabled(false);
button.setEnabled(true);
Or:
button.setClickable(false);
button.setClickable(true);
Since you want to disable the button from the beginning, you can use button.setEnabled(false); in the onCreate method. Otherwise, from XML, you can directly use:
android:clickable = "false"
So:
<Button
android:id="@+id/button"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="@string/button_text"
android:clickable = "false" />
To solve such kind of problems I created library in swift which is called Atributika.
let str = "<r>first</r><g>second</g><b>third</b>".style(tags:
Style("r").foregroundColor(.red),
Style("g").foregroundColor(.green),
Style("b").foregroundColor(.blue)).attributedString
label.attributedText = str
You can find it here https://github.com/psharanda/Atributika
On mine it's Tools --> Preferences --> Editor and "Syntax Color Scheme" dropdown is at the very bottom of the list.
Bitcode (iOS, watchOS)
Bitcode is an intermediate representation of a compiled program. Apps you upload to iTunes Connect that contain bitcode will be compiled and linked on the App Store. Including bitcode will allow Apple to re-optimize your app binary in the future without the need to submit a new version of your app to the store.
Basically this concept is somewhat similar to java where byte code is run on different JVM's and in this case the bitcode is placed on iTune store and instead of giving the intermediate code to different platforms(devices) it provides the compiled code which don't need any virtual machine to run.
Thus we need to create the bitcode once and it will be available for existing or coming devices. It's the Apple's headache to compile an make it compatible with each platform they have.
Devs don't have to make changes and submit the app again to support new platforms.
Let's take the example of iPhone 5s when apple introduced x64
chip in it. Although x86
apps were totally compatible with x64
architecture but to fully utilise the x64
platform the developer has to change the architecture or some code. Once s/he's done the app is submitted to the app store for the review.
If this bitcode concept was launched earlier then we the developers doesn't have to make any changes to support the x64
bit architecture.
has_key
is fast and efficient.
Instead of array use an hash:
valueTo1={"a","b","c"}
if valueTo1.has_key("a"):
print "Found key in dictionary"
Simplest example using the Standard Library.
#include <iostream>
using namespace std;
int main()
{
char c = 'n';
cout << "HEX " << hex << (int)c << endl; // output in hexadecimal
cout << "ASC" << c << endl; // output in ascii
return 0;
}
To check the output, codepad returns: 6e
and an online ascii-to-hexadecimal conversion tool yields 6e as well. So it works.
You can also do this:
template<class T> std::string toHexString(const T& value, int width) {
std::ostringstream oss;
oss << hex;
if (width > 0) {
oss << setw(width) << setfill('0');
}
oss << value;
return oss.str();
}
Please find inner join for more than 2 table here
Here are 4 table name like
So the SQL code would be:
select o.orderid, c.customername, l.lname, s.studadd, s.studmarks
from orders o
inner join customers c on o.customrid = c.customerid
inner join lecturer l on o.customrid = l.id
inner join student s on o.customrid=s.studmarks;
If we are using asp.net "FileUpload" control and want to preview image before upload we can use below code.
<asp:FileUpload ID="fileUpload" runat="server" Style="border: none;" onchange="showpreview(this);" />
<img id="previewImage" src="C:\fakepath\natureImage.jpg">
<script>
function showpreview(Imagepath) {
var reader = new FileReader();
reader.onload = function (e) {
$("#previewImage").attr("src", e.target.result);
}
reader.readAsDataURL(Imagepath.files[0]);
}
</script>
If you want to remove \n
from the last element only, use this:
t[-1] = t[-1].strip()
If you want to remove \n
from all the elements, use this:
t = map(lambda s: s.strip(), t)
You might also consider removing \n
before splitting the line:
line = line.strip()
# split line...
string firstdayofyear = new DateTime(DateTime.Now.Year, 1, 1).ToString("MM-dd-yyyy");
string lastdayofyear = new DateTime(DateTime.Now.Year, 12, 31).ToString("MM-dd-yyyy");
string firstdayofmonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).ToString("MM-dd-yyyy");
string lastdayofmonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(1).AddDays(-1).ToString("MM-dd-yyyy");
A simple way using std::next_permutation
:
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
int n, r;
std::cin >> n;
std::cin >> r;
std::vector<bool> v(n);
std::fill(v.end() - r, v.end(), true);
do {
for (int i = 0; i < n; ++i) {
if (v[i]) {
std::cout << (i + 1) << " ";
}
}
std::cout << "\n";
} while (std::next_permutation(v.begin(), v.end()));
return 0;
}
or a slight variation that outputs the results in an easier to follow order:
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
int n, r;
std::cin >> n;
std::cin >> r;
std::vector<bool> v(n);
std::fill(v.begin(), v.begin() + r, true);
do {
for (int i = 0; i < n; ++i) {
if (v[i]) {
std::cout << (i + 1) << " ";
}
}
std::cout << "\n";
} while (std::prev_permutation(v.begin(), v.end()));
return 0;
}
A bit of explanation:
It works by creating a "selection array" (v
), where we place r
selectors, then we create all permutations of these selectors, and print the corresponding set member if it is selected in in the current permutation of v
.
You can implement it if you note that for each level r you select a number from 1 to n.
In C++, we need to 'manually' keep the state between calls that produces results (a combination): so, we build a class that on construction initialize the state, and has a member that on each call returns the combination while there are solutions: for instance
#include <iostream>
#include <iterator>
#include <vector>
#include <cstdlib>
using namespace std;
struct combinations
{
typedef vector<int> combination_t;
// initialize status
combinations(int N, int R) :
completed(N < 1 || R > N),
generated(0),
N(N), R(R)
{
for (int c = 1; c <= R; ++c)
curr.push_back(c);
}
// true while there are more solutions
bool completed;
// count how many generated
int generated;
// get current and compute next combination
combination_t next()
{
combination_t ret = curr;
// find what to increment
completed = true;
for (int i = R - 1; i >= 0; --i)
if (curr[i] < N - R + i + 1)
{
int j = curr[i] + 1;
while (i <= R-1)
curr[i++] = j++;
completed = false;
++generated;
break;
}
return ret;
}
private:
int N, R;
combination_t curr;
};
int main(int argc, char **argv)
{
int N = argc >= 2 ? atoi(argv[1]) : 5;
int R = argc >= 3 ? atoi(argv[2]) : 2;
combinations cs(N, R);
while (!cs.completed)
{
combinations::combination_t c = cs.next();
copy(c.begin(), c.end(), ostream_iterator<int>(cout, ","));
cout << endl;
}
return cs.generated;
}
test output:
1,2,
1,3,
1,4,
1,5,
2,3,
2,4,
2,5,
3,4,
3,5,
4,5,
Here's a functional way of accomplishing it in Java 8 using http://www.vavr.io/
import static io.vavr.API.*;
import static io.vavr.Predicates.instanceOf;
public Throwable liftRootCause(final Throwable throwable) {
return Match(throwable).of(
Case($(instanceOf(CompletionException.class)), Throwable::getCause),
Case($(instanceOf(ExecutionException.class)), Throwable::getCause),
Case($(), th -> th)
);
}
My default 3306 port was in use, so Ive changed it to 8111, then I had this error. Ive fixed it by adding
$cfg['Servers'][$i]['port'] = '8111';
into config.inc.php . If you are using different port number then set yours.
m <- matrix(1:20, ncol = 4)
colnames(m) <- letters[1:4]
The following command will select the first row of the matrix above.
subset(m, m[,4] == 16)
And this will select the last three.
subset(m, m[,4] > 17)
The result will be a matrix in both cases. If you want to use column names to select columns then you would be best off converting it to a dataframe with
mf <- data.frame(m)
Then you can select with
mf[ mf$a == 16, ]
Or, you could use the subset command.
This worked for me: Open task manager (of your OS) and kill adb.exe process. Now start adb again, now adb should start normally.
Anything if you use directly in the Codeigniter framework directly, like base_url()
, uri_string()
, or word_limiter()
, All of these are coming from some sort of Helper
function of framework.
While some of Helpers
may be available globally to use just like log_message()
which are extremely useful everywhere, rest of the Helpers are optional and use case varies application to application. base_url()
is a function defined in url
helper of the Framework.
You can learn more about helper in Codeigniter user guide's helper section.
You can use base_url()
function once your current class have access to it, for which you needs to load it first.
$this->load->helper('url')
You can use this line anywhere in the application before using the base_url()
function.
If you need to use it frequently, I will suggest adding this function in config/autoload.php
in the autoload helpers
section.
Also, make sure you have well defined base_url
value in your config/config.php
file.
This will be the first configuration you will see,
$config['base_url'] = 'http://yourdomain.com/';
You can check quickly by
echo base_url();
Reference: https://codeigniter.com/user_guide/helpers/url_helper.html
I built an extension method to make for easy reuse.
using System.Windows.Forms;
namespace YourNamespace{
public static class WindowsFormExtensions {
public static void PutOnTop(this Form form) {
form.Show();
form.Activate();
}// END PutOnTop()
}// END class
}// END namespace
Call in the Form Constructor
namespace YourNamespace{
public partial class FormName : Form {
public FormName(){
this.PutOnTop();
InitalizeComponents();
}// END Constructor
} // END Form
}// END namespace
The Facebook "Graph API Rate Limiting" docs says that an error with code #4
is an app level rate limit, which is different than user level rate limits. Although it doesn't give any exact numbers, it describes their app level rate-limit as:
This rate limiting is applied globally at the app level. Ads api calls are excluded.
- Rate limiting happens real time on sliding window for past one hour.
- Stats is collected for number of calls and queries made, cpu time spent, memory used for each app.
- There is a limit for each resource multiplied by monthly active users of a given app.
- When the app uses more than its allowed resources the error is thrown.
- Error, Code: 4, Message: Application request limit reached
The docs also give recommendations for avoiding the rate limits. For app level limits, they are:
Recommendations:
- Verify the error code (4) to confirm the throttling type.
- Do not make burst of calls, spread out the calls throughout the day.
- Do smart fetching of data (important data, non duplicated data, etc).
- Real-time insights, make sure API calls are structured in a way that you can read insights for as many as Page posts as possible, with minimum number of requests.
- Don't fetch users feed twice (in the case that two App users have a specific friend in common)
- Don't fetch all user's friends feed in a row if the number of friends is more than 250. Separate the fetches over different days. As an option, fetch first the app user's news feed (me/home) in order to detect which friends are more important to the App user. Then, fetch those friends feeds first.
- Consider to limit/filter the requests by using the following parameters: "since", "until", "limit"
- For page related calls use realtime updates to subscribe to changes in data.
- Field expansion allows ton "join" multiple graph queries into a single call.
- Etags to check if the data querying has changed since the last check.
- For page management developers who does not have massive user base, have the admins of the page to accept the app to increase the number of users.
Finally, the docs give the following informational tips:
- Batching calls will not reduce the number of api calls.
- Making parallel calls will not reduce the number of api calls.
This example is for working with .xlsx file types. This example comes from a .jsp page used to create a .xslx spreadsheet.
import org.apache.poi.xssf.usermodel.*; //import needed
XSSFWorkbook wb = new XSSFWorkbook (); // Create workbook
XSSFSheet sheet = wb.createSheet(); // Create spreadsheet in workbook
XSSFRow row = sheet.createRow(rowIndex); // Create the row in the spreadsheet
//1. Create the date cell style
XSSFCreationHelper createHelper = wb.getCreationHelper();
XSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setDataFormat(
createHelper.createDataFormat().getFormat("MMMM dd, yyyy"));
//2. Apply the Date cell style to a cell
//This example sets the first cell in the row using the date cell style
cell = row.createCell(0);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);
You need to include the protocol scheme:
'http://192.168.1.61:8080/api/call'
Without the http://
part, requests
has no idea how to connect to the remote server.
Note that the protocol scheme must be all lowercase; if your URL starts with HTTP://
for example, it won’t find the http://
connection adapter either.
This is a Windows specific way, but it is at least half of your answer.
GetThisPath.h
/// dest is expected to be MAX_PATH in length.
/// returns dest
/// TCHAR dest[MAX_PATH];
/// GetThisPath(dest, MAX_PATH);
TCHAR* GetThisPath(TCHAR* dest, size_t destSize);
GetThisPath.cpp
#include <Shlwapi.h>
#pragma comment(lib, "shlwapi.lib")
TCHAR* GetThisPath(TCHAR* dest, size_t destSize)
{
if (!dest) return NULL;
if (MAX_PATH > destSize) return NULL;
DWORD length = GetModuleFileName( NULL, dest, destSize );
PathRemoveFileSpec(dest);
return dest;
}
mainProgram.cpp
TCHAR dest[MAX_PATH];
GetThisPath(dest, MAX_PATH);
I would suggest using platform detection as preprocessor directives to change the implementation of a wrapper function that calls GetThisPath
for each platform.
In mac osx , you can use the following command:
system_profiler SPUSBDataType
Gone views returns 0 as height if app in background. This my code (1oo% works)
fun View.postWithTreeObserver(postJob: (View, Int, Int) -> Unit) {
viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
val widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
val heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
measure(widthSpec, heightSpec)
postJob(this@postWithTreeObserver, measuredWidth, measuredHeight)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
@Suppress("DEPRECATION")
viewTreeObserver.removeGlobalOnLayoutListener(this)
} else {
viewTreeObserver.removeOnGlobalLayoutListener(this)
}
}
})
}
You can use Java Pluggable Annotation Processing API to write annotation processor which will be executed during the compilation process and will collect all annotated classes and build the index file for runtime use.
This is the fastest way possible to do annotated class discovery because you don't need to scan your classpath at runtime, which is usually very slow operation. Also this approach works with any classloader and not only with URLClassLoaders usually supported by runtime scanners.
The above mechanism is already implemented in ClassIndex library.
To use it annotate your custom annotation with @IndexAnnotated meta-annotation. This will create at compile time an index file: META-INF/annotations/com/test/YourCustomAnnotation listing all annotated classes. You can acccess the index at runtime by executing:
ClassIndex.getAnnotated(com.test.YourCustomAnnotation.class)
The problem is in new PHP Version in macOS Sierra
Please add
stream_context_set_option($ctx, 'ssl', 'verify_peer', false);
Global makes the variable "Global"
def out():
global x
x = 1
print(x)
return
out()
print (x)
This makes 'x' act like a normal variable outside the function. If you took the global out then it would give an error since it cannot print a variable inside a function.
def out():
# Taking out the global will give you an error since the variable x is no longer 'global' or in other words: accessible for other commands
x = 1
print(x)
return
out()
print (x)
I believe that before we started using ES6, an approach with a single var declaration was neither good nor bad (in case if you have linters and 'use strict'
. It was really a taste preference. But now things changed for me. These are my thoughts in favour of multiline declaration:
Now we have two new kinds of variables, and var
became obsolete. It is good practice to use const
everywhere until you really need let
. So quite often your code will contain variable declarations with assignment in the middle of the code, and because of block scoping you quite often will move variables between blocks in case of small changes. I think that it is more convenient to do that with multiline declarations.
ES6 syntax became more diverse, we got destructors, template strings, arrow functions and optional assignments. When you heavily use all those features with single variable declarations, it hurts readability.
The "reference" Java implementation by Sean Leary is here on github. Make sure to have the latest version - different libraries pull in versions buggy old versions from 2009.
Java EE 7 has a JSON API in javax.json
, see the Javadoc. From what I can tell, it doesn't have a simple method to marshall any object to JSON, you need to construct a JsonObject
or a JsonArray
.
import javax.json.*;
JsonObject value = Json.createObjectBuilder()
.add("firstName", "John")
.add("lastName", "Smith")
.add("age", 25)
.add("address", Json.createObjectBuilder()
.add("streetAddress", "21 2nd Street")
.add("city", "New York")
.add("state", "NY")
.add("postalCode", "10021"))
.add("phoneNumber", Json.createArrayBuilder()
.add(Json.createObjectBuilder()
.add("type", "home")
.add("number", "212 555-1234"))
.add(Json.createObjectBuilder()
.add("type", "fax")
.add("number", "646 555-4567")))
.build();
JsonWriter jsonWriter = Json.createWriter(...);
jsonWriter.writeObject(value);
jsonWriter.close();
But I assume the other libraries like GSON will have adapters to create objects implementing those interfaces.
I had that problem, if you are calling your REST Methods from another Assembly you must be sure that all your references have the same version as your main project references, otherwise will never find your controllers.
Regards.
If the display of the div is block by default, you can just use .show()
and .hide()
, or even simpler, .toggle()
to toggle between visibility.
I wrote a function that check remaining execution time.
Warning: Execution time counting is different on Windows and on Linux platform.
/**
* Check if more that `$miliseconds` ms remains
* to error `PHP Fatal error: Maximum execution time exceeded`
*
* @param int $miliseconds
* @return bool
*/
function isRemainingMaxExecutionTimeBiggerThan($miliseconds = 5000) {
$max_execution_time = ini_get('max_execution_time');
if ($max_execution_time === 0) {
// No script time limitation
return true;
}
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
// On Windows: The real time is measured.
$spendMiliseconds = (microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"]) * 1000;
} else {
// On Linux: Any time spent on activity that happens outside the execution
// of the script such as system calls using system(), stream operations
// database queries, etc. is not included.
// @see http://php.net/manual/en/function.set-time-limit.php
$resourceUsages = getrusage();
$spendMiliseconds = $resourceUsages['ru_utime.tv_sec'] * 1000 + $resourceUsages['ru_utime.tv_usec'] / 1000;
}
$remainingMiliseconds = $max_execution_time * 1000 - $spendMiliseconds;
return ($remainingMiliseconds >= $miliseconds);
}
Using:
while (true) {
// so something
if (!isRemainingMaxExecutionTimeBiggerThan(5000)) {
// Time to die.
// Safely close DB and done the iteration.
}
}
Strangely enough, I wrote some code to do this back when 1.1 came out (what was that, seven years ago?) and tweaked it a little when 2.0 came out. I haven't looked at it in years as we no longer manage our servers.
It's not foolproof, but I'm posting it anyway because I find it humorous; in that it's easier to do in .NET and easier still in power shell.
bool GetFileVersion(LPCTSTR filename,WORD *majorPart,WORD *minorPart,WORD *buildPart,WORD *privatePart)
{
DWORD dwHandle;
DWORD dwLen = GetFileVersionInfoSize(filename,&dwHandle);
if (dwLen) {
LPBYTE lpData = new BYTE[dwLen];
if (lpData) {
if (GetFileVersionInfo(filename,0,dwLen,lpData)) {
UINT uLen;
VS_FIXEDFILEINFO *lpBuffer;
VerQueryValue(lpData,_T("\\"),(LPVOID*)&lpBuffer,&uLen);
*majorPart = HIWORD(lpBuffer->dwFileVersionMS);
*minorPart = LOWORD(lpBuffer->dwFileVersionMS);
*buildPart = HIWORD(lpBuffer->dwFileVersionLS);
*privatePart = LOWORD(lpBuffer->dwFileVersionLS);
delete[] lpData;
return true;
}
}
}
return false;
}
int _tmain(int argc,_TCHAR* argv[])
{
_TCHAR filename[MAX_PATH];
_TCHAR frameworkroot[MAX_PATH];
if (!GetEnvironmentVariable(_T("systemroot"),frameworkroot,MAX_PATH))
return 1;
_tcscat_s(frameworkroot,_T("\\Microsoft.NET\\Framework\\*"));
WIN32_FIND_DATA FindFileData;
HANDLE hFind = FindFirstFile(frameworkroot,&FindFileData);
if (hFind == INVALID_HANDLE_VALUE)
return 2;
do {
if ((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
_tcslen(FindFileData.cAlternateFileName) != 0) {
_tcsncpy_s(filename,frameworkroot,_tcslen(frameworkroot)-1);
filename[_tcslen(frameworkroot)] = 0;
_tcscat_s(filename,FindFileData.cFileName);
_tcscat_s(filename,_T("\\mscorlib.dll"));
WORD majorPart,minorPart,buildPart,privatePart;
if (GetFileVersion(filename,&majorPart,&minorPart,&buildPart,&privatePart )) {
_tprintf(_T("%d.%d.%d.%d\r\n"),majorPart,minorPart,buildPart,privatePart);
}
}
} while (FindNextFile(hFind,&FindFileData) != 0);
FindClose(hFind);
return 0;
}
There's a function that does exactly this:
http://api.jquery.com/serialize/
var data = $('form').serialize();
$.post('url', data);
this did it for me. you can vary the options for the output format to Base64.Default whatsoever.
// encode base64 from image
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
encodedString = Base64.encodeToString(b, Base64.URL_SAFE | Base64.NO_WRAP);
I will also add my experience here in case it helps someone:
At work we commonly use the following two commands to enable IntelliJ IDEA to talk to various servers, for example our internal maven repositories:
[Elevated]C:\Program Files\JetBrains\IntelliJ IDEA {version}\jre64>bin\keytool
-printcert -rfc -sslserver maven.services.{our-company}.com:443 > public.crt
[Elevated]C:\Program Files\JetBrains\IntelliJ IDEA {version}\jre64>bin\keytool
-import -storepass changeit -noprompt -trustcacerts -alias services.{our-company}.com
-keystore lib\security\cacerts -file public.crt
Now, what sometimes happens is that the keytool -printcert
command is unable to communicate with the outside world due to temporary connectivity issues, such as the firewall preventing it, the user forgot to start his VPN, whatever. It is a fact of life that this may happen. This is not actually the problem.
The problem is that when the stupid tool encounters such an error, it does not emit the error message to the standard error device, it emits it to the standard output device!
So here is what ends up happening:
public.crt
file now contains an error message saying keytool error: java.lang.Exception: No certificate from the SSL server
.public.crt
, so it fails, saying keytool error: java.lang.Exception: Input not an X.509 certificate
.Bottom line is: after keytool -printcert ... > public.crt
always dump the contents of public.crt
to make sure it is actually a key and not an error message before proceeding to run keytool -import ... -file public.crt
The C++ string class is std::string
. To use it you need to include the <string>
header.
For the fundamentals of how to use std::string
, you'll want to consult a good introductory C++ book.
List<String> sids = new ArrayList<String>();
List<String> lids = new ArrayList<String>();
String query = "SELECT rlink_id, COUNT(*)"
+ "FROM dbo.Locate "
+ "GROUP BY rlink_id ";
Statement stmt = yourconnection.createStatement();
try {
ResultSet rs4 = stmt.executeQuery(query);
while (rs4.next()) {
sids.add(rs4.getString(1));
lids.add(rs4.getString(2));
}
} finally {
stmt.close();
}
String show[] = sids.toArray(sids.size());
String actuate[] = lids.toArray(lids.size());
For anyone who fumbled with this, here is how I got to grant the privileges, hope it helps someone
GRANT ALL ON yourdatabasename.* TO root@'%' IDENTIFIED BY
'yourRootPassword';
As noted %
is a wildcard and this will allow any IP address to connect to your database. The assumption I make here is when you connect you'll have a user named root
(which is the default though). Feed in the root password and you are good to go. Note that I have no single quotes ('
) around the user root.
You need to install Dot Net 4.0.2 or above as mentioned here.
The 4.0 bits don't understand the syntax required by LocalDB
You can dowload the update here
Simplest solution without changing configs. (ubuntu) Change user, then connect to database cli.
sudo -i -u postgres
psql
taken from https://www.digitalocean.com/community/tutorials/how-to-install-and-use-postgresql-on-ubuntu-18-04
Using a primary key on multiple tables comes in handy when you're using an intermediate table in a relational database.
I'll use a database I once made for an example and specifically three tables within that table. I creäted a database for a webcomic some years ago. One table was called "comics"—a listing of all comics, their titles, image file name, etc. The primary key was "comicnum".
The second table was "characters"—their names and a brief description. The primary key was on "charname".
Since each comic—with some exceptions—had multiple characters and each character appeared within multiple comics, it was impractical to put a column in either "characters" or "comics" to reflect that. Instead, I creäted a third table was called "comicchars", and that was a listing of which characters appeared in which comics. Since this table essentially joined the two tables, it needed but two columns: charname and comicnum, and the primary key was on both.
Use this Python script: https://github.com/goerz/convert_encoding.py Works on any platform. Requires Python 2.7.
sa
is enabledWe use the extension methods listed below. I think you should make the developer make a decision about the encoding, so there is less magic involved.
public static class StringExtensions {
public static Stream ToStream(this string s) {
return s.ToStream(Encoding.UTF8);
}
public static Stream ToStream(this string s, Encoding encoding) {
return new MemoryStream(encoding.GetBytes(s ?? ""));
}
}
Use selectionStart
, it is compatible with all major browsers.
document.getElementById('foobar').addEventListener('keyup', e => {
console.log('Caret at: ', e.target.selectionStart)
})
_x000D_
<input id="foobar" />
_x000D_
Update: This works only when no type is defined or type="text"
or type="textarea"
on the input.
If you want to display directory than edit htdocs/index.php
file
Below code is display all directory in table
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Welcome to Nims Server</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="server/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<!-- START PAGE SOURCE -->
<div id="wrap">
<div id="top">
<h1 id="sitename">Nims <em>Server</em> Directory list</h1>
<div id="searchbar">
<form action="#">
<div id="searchfield">
<input type="text" name="keyword" class="keyword" />
<input class="searchbutton" type="image" src="server/images/searchgo.gif" alt="search" />
</div>
</form>
</div>
</div>
<div class="background">
<div class="transbox">
<table width="100%" border="0" cellspacing="3" cellpadding="5" style="border:0px solid #333333;background: #F9F9F9;">
<tr>
<?php
//echo md5("saketbook007");
//File functuion DIR is used here.
$d = dir($_SERVER['DOCUMENT_ROOT']);
$i=-1;
//Loop start with read function
while ($entry = $d->read()) {
if($entry == "." || $entry ==".."){
}else{
?>
<td class="site" width="33%"><a href="<?php echo $entry;?>" ><?php echo ucfirst($entry); ?></a></td>
<?php
}
if($i%3 == 0){
echo "</tr><tr>";
}
$i++;
}?>
</tr>
</table>
<?php $d->close();
?>
</div>
</div>
</div>
</div></div></body>
</html>
Style:
@import url("fontface.css");
* {
padding:0;
margin:0;
}
.clear {
clear:both;
}
body {
background:url(images/bg.jpg) repeat;
font-family:"Palatino Linotype", "Book Antiqua", Palatino, serif;
color:#212713;
}
#wrap {
width:1300px;
margin:auto;
}
#sitename {
font: normal 46px chunk;
color:#1b2502;
text-shadow:#5d7a17 1px 1px 1px;
display:block;
padding:45px 0 0 0;
width:60%;
float:left;
}
#searchbar {
width:39%;
float:right;
}
#sitename em {
font-family:"Palatino Linotype", "Book Antiqua", Palatino, serif;
}
#top {
height:145px;
}
img {
width:90%;
height:250px;
padding:10px;
border:1px solid #000;
margin:0 0 0 50px;
}
.post h2 a {
color:#656f42;
text-decoration:none;
}
#searchbar {
padding:55px 0 0 0;
}
#searchfield {
background:url(images/searchbar.gif) no-repeat;
width:239px;
height:35px;
float:right;
}
#searchfield .keyword {
width:170px;
background:transparent;
border:none;
padding:8px 0 0 10px;
color:#fff;
display:block;
float:left;
}
#searchfield .searchbutton {
display:block;
float:left;
margin:7px 0 0 5px;
}
div.background
{
background:url(h.jpg) repeat-x;
border: 2px solid black;
width:99%;
}
div.transbox
{
margin: 15px;
background-color: #ffffff;
border: 1px solid black;
opacity:0.8;
filter:alpha(opacity=60); /* For IE8 and earlier */
height:500px;
}
.site{
border:1px solid #CCC;
}
.site a{text-decoration:none;font-weight:bold; color:#000; line-height:2}
.site:hover{background:#000; border:1px solid #03C;}
.site:hover a{color:#FFF}
Try this:
myApp.service('userService', [
'$http', '$q', '$rootScope', '$location', function($http, $q, $rootScope, $location) {
var deferred= $q.defer();
this.user = {
access: false
};
try
{
this.isAuthenticated = function() {
this.user = {
first_name: 'First',
last_name: 'Last',
email: '[email protected]',
access: 'institution'
};
deferred.resolve();
};
}
catch
{
deferred.reject();
}
return deferred.promise;
]);
/*
Here's a rough one not relying on any libraries.
Example:
-wi | -iw //word case insensitive
-li | -il //line case insensitive
-- file //specify the first filename (you could just get the files
as positional arguments in the else statement instead)
PS: don't mind the #define's, they're just pasting code :D
*/
#ifndef OPT_H
#define OPT_H
//specify option requires argument
#define require \
optarg = opt_pointer + 1; \
if (*optarg == '\0') \
{ \
if (++optind == argc) \
goto opt_err_arg; \
else \
optarg = argv[optind]; \
} \
opt_pointer = opt_null_terminator;
//start processing argv
#define opt \
int optind = 1; \
char *opt_pointer = argv[1]; \
char *optarg = NULL; \
char opt_null_terminator[2] = {'\0','\0'}; \
if (0) \
{ \
opt_err_arg: \
fprintf(stderr,"option %c requires argument.\n",*opt_pointer); \
return 1; \
opt_err_opt: \
fprintf(stderr,"option %c is invalid.\n",*opt_pointer); \
return 1; \
} \
for (; optind < argc; opt_pointer = argv[++optind]) \
if (*opt_pointer++ == '-') \
{ \
for (;;++opt_pointer) \
switch (*opt_pointer) \
{
//stop processing argv
#define done \
default: \
if (*opt_pointer != '\0') \
goto opt_err_opt; \
else \
goto opt_next; \
break; \
} \
opt_next:; \
}
#endif //opt.h
#include <stdio.h>
#include "opt.h"
int
main (int argc, char **argv)
{
#define by_character 0
#define by_word 1
#define by_line 2
int cmp = by_character;
int case_insensitive = 0;
opt
case 'h':
puts ("HELP!");
break;
case 'v':
puts ("fileCMP Version 1.0");
break;
case 'i':
case_insensitive = 1;
break;
case 'w':
cmp = by_word;
break;
case 'l':
cmp = by_line;
break;
case '-':required
printf("first filename: %s\n", optarg);
break;
done
else printf ("Positional Argument %s\n", argv[optind]);
return 0;
}
-qscale:v
to control qualityUse -qscale:v
(or the alias -q:v
) as an output option.
-qmin 1
output option (because the default is -qmin 2
).ffmpeg -i input.mp4 -qscale:v 2 output_%03d.jpg
See the image muxer documentation for more options involving image outputs.
ffmpeg -ss 60 -i input.mp4 -qscale:v 4 -frames:v 1 output.jpg
you could submit all parameters with such naming:
params[0][topdiameter]
params[0][bottomdiameter]
params[1][topdiameter]
params[1][bottomdiameter]
then later you do something like this:
foreach ($_REQUEST['params'] as $item) {
echo $item['topdiameter'];
echo $item['bottomdiameter'];
}
There is an API that's called SubnetTree available in python that do this job very well. This is a simple example :
import SubnetTree
t = SubnetTree.SubnetTree()
t.insert("10.0.1.3/32")
print("10.0.1.3" in t)
cmd /c pause | out-null
(It is not the PowerShell way, but it's so much more elegant.)
Save trees. Use one-liners.
$("#myDiv").hide();
will set the css display to none. if you need to set visibility to hidden as well, could do this via
$("#myDiv").css("visibility", "hidden");
or combine both in a chain
$("#myDiv").hide().css("visibility", "hidden");
or write everything with one css() function
$("#myDiv").css({
display: "none",
visibility: "hidden"
});
Use padding in percentages too and remove from the width:
padding: 5%; width: 90%;
You can specify a width on string fields, e.g.
printf("%-20s", "initialization...");
And then whatever's printed with that field will be blank-padded to the width you indicate.
The -
left-justifies your text in that field.
A connected socket is assigned to a new (dedicated) port
That's a common intuition, but it's incorrect. A connected socket is not assigned to a new/dedicated port. The only actual constraint that the TCP stack must satisfy is that the tuple of (local_address, local_port, remote_address, remote_port) must be unique for each socket connection. Thus the server can have many TCP sockets using the same local port, as long as each of the sockets on the port is connected to a different remote location.
See the "Socket Pair" paragraph at: http://books.google.com/books?id=ptSC4LpwGA0C&lpg=PA52&dq=socket%20pair%20tuple&pg=PA52#v=onepage&q=socket%20pair%20tuple&f=false
You can easily iterate over your view controllers if you are using a navigation controller. And then you can check for the particular instance as:
Swift 5
if let viewControllers = navigationController?.viewControllers {
for viewController in viewControllers {
if viewController.isKind(of: LoginViewController.self) {
}
}
}
See PEP 308 for more info.
Also apply text-align: center; on the html element like so:
html {
text-align: center;
}
A better approach though is to have an inner container div, which will be centralized, and not the body.
For me it was just to clean project.
I cleaned project, and run again. And all errors gone.
The easiest solution I found is to just rename the php folder version as such:
That way only two of them will be read by MAMP. Done!
Unfortunately, the most popular answer did not work for me entirely. I had to add .select_option
to end of the statement
select("option_name_here", from: "organizationSelect").select_option
without the select_option
, no select was being performed
I am using PHP for webservice and Android 4.x. device for connecting to the webservice. I had similar problem where, using 10.0.2.2
worked well with emulator but failed to connect from device. The solution that worked for me is: Find IP of your computer ... say 192.168.0.103
Find the port of your apache ... say 8080
Now open httpd.conf and locate following line Listen 127.0.0.1:8080
After this line add following Listen 192.168.0.103:8080
Thats it. Now if you use 192.168.0.103:8080
in your android code, it will connect!!
Primary key -> Any column or set of columns that can uniquely identify a record in the table is a primary key. (There can be only one Primary key in the table)
Candidate key -> Any column or set of columns that are candidate to become primary key are Candidate key. (There can be one or more candidate key(s) in the table, if there is only one candidate key, it can be chosen as Primary key)
Here is a simple CSS only solution (JSFiddle), works everywhere, mobile and IE included:
CSS 2.0:
html, body {
height: 100%;
margin: 0;
padding: 0;
}
img {
padding: 0;
display: block;
margin: 0 auto;
max-height: 100%;
max-width: 100%;
}
HTML:
<body>
<img src="images/your-image.png" />
</body>
You could use this to pick all li
elements without class:
$('ul#list li:not([class])')
The problem is with the input.nextInt() method - it only reads the int value. So when you continue reading with input.nextLine() you receive the "\n" Enter key. So to skip this you have to add the input.nextLine(). Hope this should be clear now.
Try it like that:
System.out.print("Insert a number: ");
int number = input.nextInt();
input.nextLine(); // This line you have to add (It consumes the \n character)
System.out.print("Text1: ");
String text1 = input.nextLine();
System.out.print("Text2: ");
String text2 = input.nextLine();
usually i don't use for loop in R, but here is my solution using for loops and two packages : plyr and dostats
plyr is on cran and you can download dostats on https://github.com/halpo/dostats (may be using install_github from Hadley devtools package)
Assuming that i have your first two data.frame (Df.1 and Df.2) in csv files, you can do something like this.
require(plyr)
require(dostats)
files <- list.files(pattern = ".csv")
for (i in seq_along(files)) {
assign(paste("Df", i, sep = "."), read.csv(files[i]))
assign(paste(paste("Df", i, sep = ""), "summary", sep = "."),
ldply(get(paste("Df", i, sep = ".")), dostats, sum, min, mean, median, max))
}
Here is the output
R> Df1.summary
.id sum min mean median max
1 A 34 4 5.6667 5.5 8
2 B 22 1 3.6667 3.0 9
R> Df2.summary
.id sum min mean median max
1 A 21 1 3.5000 3.5 6
2 B 16 1 2.6667 2.5 5
We have another way to find out the number of rows in a table without running a select
query on that table.
Every MySQL instance has information_schema database. If you run the following query, it will give complete details about the table including the approximate number of rows in that table.
select * from information_schema.TABLES where table_name = 'table_name'\G
By default, the access modifier for a class is internal
. That means to say, a class is accessible within the same assembly. But if we want the class to be accessed from other assemblies then it has to be made public.
You can use .val() to select the value, like the following:
function select_option(i) {
$("#span_id select").val(i);
}
Here is a jsfiddle: https://jsfiddle.net/tweissin/uscq42xh/8/
Johnny5 suggested creating an extension method. Here's a more complete code example showing how you could do this:
public static class RandomExtensions
{
public static double NextDouble(
this Random random,
double minValue,
double maxValue)
{
return random.NextDouble() * (maxValue - minValue) + minValue;
}
}
Now you can call it as if it were a method on the Random
class:
Random random = new Random();
double value = random.NextDouble(1.23, 5.34);
Note that you should not create lots of new Random
objects in a loop because this will make it likely that you get the same value many times in a row. If you need lots of random numbers then create one instance of Random
and re-use it.
Abstraction delineates a context-specific, simplified representation of something; it ignores contextually-irrelevant details and includes contextually-important details.
Encapsulation restricts outside access to something's parts and bundles that thing's state with the procedures that use the state.
Take people, for instance. In the context of surgery a useful abstraction ignores a person's religious beliefs and includes the person's body. Further, people encapsulate their memories with the thought processes that use those memories. An abstraction need not have encapsulation; for instance, a painting of a person neither hides its parts nor bundles procedures with its state. And, encapsulation need not have an associated abstraction; for instance, real people (not abstract ones) encapsulate their organs with their metabolism.
@ variables are instance variables, without are local variables.
Read more at http://ruby.about.com/od/variables/a/Instance-Variables.htm
It solved throung second parameter in Model load:
$this->load->model('user','User');
first parameter is the model's filename, and second it defining the name of model to be used in the controller:
function alluser()
{
$this->load->model('User');
$result = $this->User->showusers();
}
I have also seen
if [ "x$variable" = "x" ]; then ...
which is obviously very robust and shell independent.
Also, there is a difference between "empty" and "unset". See How to tell if a string is not defined in a Bash shell script.
According to MSDN maxAllowedContentLength
has type uint
, its maximum value is 4,294,967,295 bytes = 3,99 gb
So it should work fine.
See also Request Limits article. Does IIS return one of these errors when the appropriate section is not configured at all?
See also: Maximum request length exceeded
If you want to use a string as a variable name, you can use assign:
var1="string_name"
assign(var1, c(5,4,5,6,7))
string_name
[1] 5 4 5 6 7
Please see Pierre L'Ecuyer's work going back to the late 1980s and early 1990s. There are others as well. Creating a (pseudo) random number generator on your own, if you are not an expert, is pretty dangerous, because there is a high likelihood of either the results not being statistically random or in having a small period. Pierre (and others) have put together some good (pseudo) random number generators that are easy to implement. I use one of his LFSR generators.
https://www.iro.umontreal.ca/~lecuyer/myftp/papers/handstat.pdf
Phil Troy
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysql.sock' (2)
I get the error above when I try to log into MYSQL after installing it using brew, I am running MacOs, Oh yea I also noticed mysql is running I have restarted numerous times with no luck resolving the issue along with removing mysql and numerous reinstalls!
So simple I could slap myself, no but really, I solved this by CD into the temp folder that contains mysqlx.sock and mysql.sock.lock files, I deleted the single sock.lock file only and this solved my issue after doing so and I can log into mysql using the mysql -uroot command. Here are the commands I used. (this issue had me hung up for a while)
~ cd /tmp
/tmp ls
(this will list all the sock files in the temp folder, output shown below)
com.apple.launchd.8AgGW2s9Bb mysql.sock.lock
com.apple.launchd.batxrSISAJ mysqlx.sock
com.apple.launchd.cRCaxtT41m mysqlx.sock.lock
com.google.Keystone powerlog
then run
rm -R mysql.sock.lock
(use command above to remove the sock.lock file from the /tmp directory this resolved my issue)
hope this helped :)
My solution to fix that problem was the following:
Start > search > cmd.exe (Run as administrator)
Inside the Command Prompt (cmd.exe) type:
cd c:/wamp/bin/apache/ApacheX.X.X/bin
httpd.exe -e debug
**Note that the ApacheX.X.X is the version of the Apache wamp is running.
This should output what the apache server is doing. The error that causes Apache from loading should be in there. My problem was that httpd.conf was trying to load a DLL that was missing or was corrupted (php5apache2_4.dll). As soon as I overwrote this file, I restarted Wamp and everything ran smooth.
This little change help with this problem.
I have Solution with 3 project.
connectionString="metadata=res://*/Model.Project.csdl|res://*/Model.Project.ssdl|res://*/Model.Project.msl;
change to
connectionString="metadata=res://*/;
If "debugging information" means the values present when exception was raised, then logging.exception(...)
won't help. So you'll need a tool that logs all variable values along with the traceback lines automatically.
Out of the box you'll get log like
2020-03-30 18:24:31 main ERROR File "./temp.py", line 13, in get_ratio
2020-03-30 18:24:31 main ERROR return height / width
2020-03-30 18:24:31 main ERROR height = 300
2020-03-30 18:24:31 main ERROR width = 0
2020-03-30 18:24:31 main ERROR builtins.ZeroDivisionError: division by zero
Have a look at some pypi tools, I'd name:
Some of them give you pretty crash messages:
But you might find some more on pypi
If you want to take into consideration the platform (x64, x86 etc) and the configuration (Debug or Release) it would be something like this:
xcopy "$(SolutionDir)\$(Platform)\$(Configuration)\$(TargetName).dll" "$(SolutionDir)TestDirectory\bin\$(Platform)\$(Configuration)\" /F /Y
git ls-remote | cut -f1 | git cat-file --batch-check >&-
will list everything referenced in any remote that isn't in your repo. To catch remote ref changes to things you already had (e.g. resets to previous commits) takes a little more:
git pack-refs --all
mine=`mktemp`
sed '/^#/d;/^^/{G;s/.\(.*\)\n.* \(.*\)/\1 \2^{}/;};h' .git/packed-refs | sort -k2 >$mine
for r in `git remote`; do
echo Checking $r ...
git ls-remote $r | sort -k2 | diff -b - $mine | grep ^\<
done
100% robust approach.
In my case, I didn't have access to the XML layout source file, since I get Checkbox from a 3-rd party MaterialDialog lib. So I have to solve this programmatically.
res/color/checkbox_tinit_dark_theme.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/white"
android:state_checked="false"/>
<item android:color="@color/positiveButtonBg"
android:state_checked="true"/>
</selector>
Then apply it to the checkbox:
ColorStateList darkStateList = ContextCompat.getColorStateList(getContext(), R.color.checkbox_tint_dark_theme);
CompoundButtonCompat.setButtonTintList(checkbox, darkStateList);
P.S. In addition if someone is interested, here is how you can get your checkbox from MaterialDialog dialog (if you set it with .checkBoxPromptRes(...)
):
CheckBox checkbox = (CheckBox) dialog.getView().findViewById(R.id.md_promptCheckbox);
Hope this helps.
I get this problem from time to time, and when I do, I have been able to solve it by using a backup of the database folder(s) that give the problem.
When you check your 'Event Viewer > Windows Log > Application', if you see an error:
InnoDB: Attempted to open a previously opened tablespace. Previous tablespace [database]/[table] uses space ID: 59 at filepath: .\[database]\[table].ibd. Cannot open tablespace [different db]/[different table] which uses space ID: 59 at filepath: .\[different db]/[different table].ibd
Then what works for me, is delete the first mentioned [database] folder in your MySQL data directory, and copy the backup of that database folder to where it was previously.
Then start MySQL, and it starts again for me, without this 1067 error.
public static T Clone<T>(T obj)
{
DataContractSerializer dcSer = new DataContractSerializer(obj.GetType());
MemoryStream memoryStream = new MemoryStream();
dcSer.WriteObject(memoryStream, obj);
memoryStream.Position = 0;
T newObject = (T)dcSer.ReadObject(memoryStream);
return newObject;
}
Use properties file. Here is a good start: http://www.mkyong.com/java/java-properties-file-examples/
Add this in your .htaccess file:
Options -Indexes
If it is not work for any reason, try this within your .htaccess file:
IndexIgnore *
ddlutils is my best choice:http://db.apache.org/ddlutils/api/org/apache/ddlutils/platform/SqlBuilder.html
here is create example(groovy):
Platform platform = PlatformFactory.createNewPlatformInstance("oracle");//db2,...
//create schema
def db = new Database();
def t = new Table(name:"t1",description:"XXX");
def col1 = new Column(primaryKey:true,name:"id",type:"bigint",required:true);
t.addColumn(col1);
t.addColumn(new Column(name:"c2",type:"DECIMAL",size:"8,2"));
t.addColumn( new Column(name:"c3",type:"varchar"));
t.addColumn(new Column(name:"c4",type:"TIMESTAMP",description:"date"));
db.addTable(t);
println platform.getCreateModelSql(db, false, false)
//you can read Table Object from platform.readModelFromDatabase(....)
def sqlbuilder = platform.getSqlBuilder();
println "insert:"+sqlbuilder.getInsertSql(t,["id":1,c2:3],false);
println "update:"+sqlbuilder.getUpdateSql(t,["id":1,c2:3],false);
println "delete:"+sqlbuilder.getDeleteSql(t,["id":1,c2:3],false);
//http://db.apache.org/ddlutils/database-support.html
Tried it out. ResponseHeaders do not include status code.
If I'm not mistaken, WebClient
is capable of abstracting away multiple distinct requests in a single method call (e.g. correctly handling 100 Continue responses, redirects, and the like). I suspect that without using HttpWebRequest
and HttpWebResponse
, a distinct status code may not be available.
It occurs to me that, if you are not interested in intermediate status codes, you can safely assume the final status code is in the 2xx (successful) range, otherwise, the call would not be successful.
The status code unfortunately isn't present in the ResponseHeaders
dictionary.
use substring_index, in the example below i have created a table with column score1 and score2, score1 has 3-7, score2 7-3 etc as shown in the image. The below query is able to split using "-" and reverse the order of score2 and compare to score1
SELECT CONCAT(
SUBSTRING_INDEX(score1, '-', 1),
SUBSTRING_INDEX(score1,'-',-1)
) AS my_score1,
CONCAT(
SUBSTRING_INDEX(score2, '-', -1),
SUBSTRING_INDEX(score2, '-', 1)
) AS my_score2
FROM test HAVING my_score1=my_score2
(Update September 2012):
MRT points out in the comments that "Eclipse Version" question references a .eclipseproduct
in the main folder, and it contains:
name=Eclipse Platform
id=org.eclipse.platform
version=3.x.0
So that seems more straightforward than my original answer below.
Also, Neeme Praks mentions below that there is a eclipse/configuration/config.ini
which includes a line like:
eclipse.buildId=4.4.1.M20140925-0400
Again easier to find, as those are Java properties set and found with System.getProperty("eclipse.buildId")
.
Original answer (April 2009)
For Eclipse Helios 3.6, you can deduce the Eclipse Platform version directly from the About screen:
It is a combination of the Eclipse global version and the build Id:
Here is an example for Eclipse 3.6M6:
The version would be: 3.6.0.v201003121448, after the version 3.6.0 and the build Id I20100312-1448 (an Integration build from March 12th, 2010 at 14h48
To see it more easily, click on "Plugin Details" and sort by Version.
Note: Eclipse3.6 has a brand new cool logo:
And you can see the build Id now being displayed during the loading step of the different plugin.
I suggest using Jxpath, it allows you to do queries on object graphs as if it where xpath like
JXPathContext.newContext(cats).
getValue("//*[@drinks='milk']")
There's a method to iterate over only own object properties, not including prototype's ones:
for (var i in array) if (array.hasOwnProperty(i)) {
// Do something with array[i]
}
but it still will iterate over custom-defined properties.
In JavaScript any custom property could be assigned to any object, including an array.
If one wants to iterate over sparsed array, for (var i = 0; i < array.length; i++) if (i in array)
or array.forEach
with es5shim
should be used.
There are two ways to fix the problem which is caused by the last print
statement.
You can assign the result of the str(c)
call to c
as correctly shown by @jamylak and then concatenate all of the strings, or you can replace the last print
simply with this:
print "a + b as integers: ", c # note the comma here
in which case
str(c)
isn't necessary and can be deleted.
Output of sample run:
Enter a: 3
Enter b: 7
a + b as strings: 37
a + b as integers: 10
with:
a = raw_input("Enter a: ")
b = raw_input("Enter b: ")
print "a + b as strings: " + a + b # + everywhere is ok since all are strings
a = int(a)
b = int(b)
c = a + b
print "a + b as integers: ", c
@Max: is right about the creation time.
However, if you want to calculate the elapsed days argument for one of the -atime
, -ctime
, -mtime
parameters, you can use the following expression
ELAPSED_DAYS=$(( ( $(date +%s) - $(date -d '2008-09-24' +%s) ) / 60 / 60 / 24 - 1 ))
Replace "2008-09-24" with whatever date you want and ELAPSED_DAYS will be set to the number of days between then and today. (Update: subtract one from the result to align with find
's date rounding.)
So, to find any file modified on September 24th, 2008, the command would be:
find . -type f -mtime $(( ( $(date +%s) - $(date -d '2008-09-24' +%s) ) / 60 / 60 / 24 - 1 ))
This will work if your version of find
doesn't support the -newerXY
predicates mentioned in @Arve:'s answer.
I think that access() function, which is found in unistd.h
is a good choice for Linux
(you can use stat too).
You can Use it like this:
#include <stdio.h>
#include <stdlib.h>
#include<unistd.h>
void fileCheck(const char *fileName);
int main (void) {
char *fileName = "/etc/sudoers";
fileCheck(fileName);
return 0;
}
void fileCheck(const char *fileName){
if(!access(fileName, F_OK )){
printf("The File %s\t was Found\n",fileName);
}else{
printf("The File %s\t not Found\n",fileName);
}
if(!access(fileName, R_OK )){
printf("The File %s\t can be read\n",fileName);
}else{
printf("The File %s\t cannot be read\n",fileName);
}
if(!access( fileName, W_OK )){
printf("The File %s\t it can be Edited\n",fileName);
}else{
printf("The File %s\t it cannot be Edited\n",fileName);
}
if(!access( fileName, X_OK )){
printf("The File %s\t is an Executable\n",fileName);
}else{
printf("The File %s\t is not an Executable\n",fileName);
}
}
And you get the following Output:
The File /etc/sudoers was Found
The File /etc/sudoers cannot be read
The File /etc/sudoers it cannot be Edited
The File /etc/sudoers is not an Executable
C has always been very specific about the initial values of objects. If global or static
, they will be zeroed. If auto
, the value is indeterminate.
This was the case in pre-C89 compilers and was so specified by K&R and in DMR's original C report.
This was the case in C89, see section 6.5.7 Initialization.
If an object that has automatic storage duration is not initialized explicitely, its value is indeterminate. If an object that has static storage duration is not initialized explicitely, it is initialized implicitely as if every member that has arithmetic type were assigned 0 and every member that has pointer type were assigned a null pointer constant.
This was the case in C99, see section 6.7.8 Initialization.
If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static storage duration is not initialized explicitly, then:
— if it has pointer type, it is initialized to a null pointer;
— if it has arithmetic type, it is initialized to (positive or unsigned) zero;
— if it is an aggregate, every member is initialized (recursively) according to these rules;
— if it is a union, the first named member is initialized (recursively) according to these rules.
As to what exactly indeterminate means, I'm not sure for C89, C99 says:
3.17.2
indeterminate value
either an unspecified value or a trap representation
But regardless of what standards say, in real life, each stack page actually does start off as zero, but when your program looks at any auto
storage class values, it sees whatever was left behind by your own program when it last used those stack addresses. If you allocate a lot of auto
arrays you will see them eventually start neatly with zeroes.
You might wonder, why is it this way? A different SO answer deals with that question, see: https://stackoverflow.com/a/2091505/140740
My task also failed to start.
I solved it by specifying not only the path to the executable, but also the path to the folder of the executable (Tab "Actions" | Edit | TextBox "Start in").
Using Node.js you can export the variable via module.
//first.js
const colorCode = {
black: "#000",
white: "#fff"
};
module.exports = { colorCode };
Then, import the module/variable in second file using require.
//second.js
const { colorCode } = require('./first.js')
You can use the import
and export
aproach from ES6 using Webpack/Babel, but in Node.js you need to enable a flag, and uses the .mjs extension.
foreach (array('one', 'two', 'three') as $v) {
switch ($v) {
case (function ($v) {
if ($v == 'two') return $v;
return 'one';
})($v):
echo "$v min \n";
break;
}
}
this works fine for languages supporting enclosures
This is the method I'm using in a project I am currently working on.
var exec = require('child_process').exec;
function execute(command, callback){
exec(command, function(error, stdout, stderr){ callback(stdout); });
};
Example of retrieving a git user:
module.exports.getGitUser = function(callback){
execute("git config --global user.name", function(name){
execute("git config --global user.email", function(email){
callback({ name: name.replace("\n", ""), email: email.replace("\n", "") });
});
});
};
here's an updated fiddle where the user's input is saved in local storage automatically. each time the fiddle is re-run or the page is refreshed the previous state is restored. this way you do not need to prompt users to save, it just saves on it's own.
http://jsfiddle.net/tZPg4/9397/
stack overflow requires I include some code with a jsFiddle link so please ignore snippet:
localStorage.setItem(...)
I ran into the same problem but wanted to count multiple items in one go..
val s = Seq("apple", "oranges", "apple", "banana", "apple", "oranges", "oranges")
s.foldLeft(Map.empty[String, Int]) { (m, x) => m + ((x, m.getOrElse(x, 0) + 1)) }
res1: scala.collection.immutable.Map[String,Int] = Map(apple -> 3, oranges -> 3, banana -> 1)
window.location.protocol + '//' + window.location.host
Simply call InetAddress.getByName(String host)
passing in your textual IP address.
From the javadoc: The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address.
2x faster than the versions before mentioned - mostly because transform() and inner_product() loops are joined. Sorry about my shortcut/typedefs/macro: Flo = float. CR const ref. VFlo - vector. Tested in VS2010
#define fe(EL, CONTAINER) for each (auto EL in CONTAINER) //VS2010
Flo stdDev(VFlo CR crVec) {
SZ n = crVec.size(); if (n < 2) return 0.0f;
Flo fSqSum = 0.0f, fSum = 0.0f;
fe(f, crVec) fSqSum += f * f; // EDIT: was Cit(VFlo, crVec) {
fe(f, crVec) fSum += f;
Flo fSumSq = fSum * fSum;
Flo fSumSqDivN = fSumSq / n;
Flo fSubSqSum = fSqSum - fSumSqDivN;
Flo fPreSqrt = fSubSqSum / (n - 1);
return sqrt(fPreSqrt);
}
Try just importing the functions needed from main.py? So,
from main import SomeFunction
It could be that you've named a function in batch.py the same as one in main.py, and when you import main.py the program runs the main.py function instead of the batch.py function; doing the above should fix that. I hope.
Just change the directory to another one and come back. Probably that one has been deleted or moved.
The __del__
method (note spelling!) is called when your object is finally destroyed. Technically speaking (in cPython) that is when there are no more references to your object, ie when it goes out of scope.
If you want to delete your object and thus call the __del__
method use
del obj1
which will delete the object (provided there weren't any other references to it).
I suggest you write a small class like this
class T:
def __del__(self):
print "deleted"
And investigate in the python interpreter, eg
>>> a = T()
>>> del a
deleted
>>> a = T()
>>> b = a
>>> del b
>>> del a
deleted
>>> def fn():
... a = T()
... print "exiting fn"
...
>>> fn()
exiting fn
deleted
>>>
Note that jython and ironpython have different rules as to exactly when the object is deleted and __del__
is called. It isn't considered good practice to use __del__
though because of this and the fact that the object and its environment may be in an unknown state when it is called. It isn't absolutely guaranteed __del__
will be called either - the interpreter can exit in various ways without deleteting all objects.
Just for completeness sake:
dplyr also offers to draw a proportion or fraction of the sample by
df %>% sample_frac(0.33)
This is very convenient e.g. in machine learning when you have to do a certain split ratio like 80%:20%
Implement LocalizedError:
struct StringError : LocalizedError
{
var errorDescription: String? { return mMsg }
var failureReason: String? { return mMsg }
var recoverySuggestion: String? { return "" }
var helpAnchor: String? { return "" }
private var mMsg : String
init(_ description: String)
{
mMsg = description
}
}
Note that simply implementing Error, for instance, as described in one of the answers, will fail (at least in Swift 3), and calling localizedDescription will result in the string "The operation could not be completed. (.StringError error 1.)"
DELETE FROM table WHERE edit_user IS NULL;
You can also check your site's properties in IIS. (In IIS, right-click the site and choose Properties.) Make sure the Physical Path setting is pointing to the correct path for your application not some other application. (That fixed this error for me.)
I've been working on something similar and after a few tries and fails came up with this:
Example: STRING-TO-TEST-ON = 'ab,cd,ef,gh'
I wanted to extract everything after the last occurrence of "," (comma) from the string... resulting in "gh".
My query is:
SELECT SUBSTR('ab,cd,ef,gh' FROM (LENGTH('ab,cd,ef,gh') - (LOCATE(",",REVERSE('ab,cd,ef,gh'))-1)+1)) AS `wantedString`
Now let me try and explain what I did ...
I had to find the position of the last "," from the string and to calculate the wantedString length, using LOCATE(",",REVERSE('ab,cd,ef,gh'))-1
by reversing the initial string I actually had to find the first occurrence of the "," in the string ... which wasn't hard to do ... and then -1 to actually find the string length without the ",".
calculate the position of my wantedString by subtracting the string length I've calculated at 1st step from the initial string length:
LENGTH('ab,cd,ef,gh') - (LOCATE(",",REVERSE('ab,cd,ef,gh'))-1)+1
I have (+1) because I actually need the string position after the last "," .. and not containing the ",". Hope it makes sense.
I haven't tested the query on large strings so I do not know how slow it is. So if someone actually tests it on a large string I would very happy to know the results.
If you want to overwrite the existing class for different collection using typescript
then you have to inherit the existing class from different class.
export class User extends Typegoose{
@prop
username?:string
password?:string
}
export class newUser extends User{
constructor() {
super();
}
}
export const UserModel = new User ().getModelForClass(User , { schemaOptions: { collection: "collection1" } });
export const newUserModel = new newUser ().getModelForClass(newUser , { schemaOptions: { collection: "collection2" } });
199 on Windows XP NTFS, I just checked.
This is not theory but from just trying on my laptop. There may be mitigating effects, but it physically won't let me make it bigger.
Is there some other setting limiting this, I wonder? Try it for yourself.
This commands shows the created date of branch dev
from main
$git reflog show --date=iso dev
$7a2b33d dev@{2012-11-23 13:20:28 -2100}: branch: Created from main
Even with a default value, you can always override the column data with null
.
The NOT NULL
restriction won't let you update that row after it was created with null
value
The following (C#) code should do the trick
Uri uri = new Uri("http://www.mywebsite.com:80/pages/page1.aspx");
string requested = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port;
Why not in one line?
$('.offer').click(function(){
$(this).find(':checkbox').attr('checked', !$(this).find(':checkbox').attr('checked'));
});
Apache tomcat is just an only serverlet container it does not support for Enterprise Java application(JEE). JBoss and Glassfish are supporting for JEE application but Glassfish much heavy than JBOSS server : Reference Slide
Much more simple: Right click -> Refactor -> Move.
Don't use @@ERROR
, use BEGIN TRY/BEGIN CATCH
instead. See this article: Exception handling and nested transactions for a sample procedure:
create procedure [usp_my_procedure_name]
as
begin
set nocount on;
declare @trancount int;
set @trancount = @@trancount;
begin try
if @trancount = 0
begin transaction
else
save transaction usp_my_procedure_name;
-- Do the actual work here
lbexit:
if @trancount = 0
commit;
end try
begin catch
declare @error int, @message varchar(4000), @xstate int;
select @error = ERROR_NUMBER(), @message = ERROR_MESSAGE(), @xstate = XACT_STATE();
if @xstate = -1
rollback;
if @xstate = 1 and @trancount = 0
rollback
if @xstate = 1 and @trancount > 0
rollback transaction usp_my_procedure_name;
raiserror ('usp_my_procedure_name: %d: %s', 16, 1, @error, @message) ;
return;
end catch
end
Building upon busylee's answer, this is how you can make a drawable
that only has one unrounded corner (top-left, in this example):
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="@color/white" />
<!-- A numeric value is specified in "radius" for demonstrative purposes only,
it should be @dimen/val_name -->
<corners android:radius="10dp" />
</shape>
</item>
<!-- To keep the TOP-LEFT corner UNROUNDED set both OPPOSITE offsets (bottom+right): -->
<item
android:bottom="10dp"
android:right="10dp">
<shape android:shape="rectangle">
<solid android:color="@color/white" />
</shape>
</item>
</layer-list>
Please note that the above drawable
is not shown correctly in the Android Studio preview (2.0.0p7). To preview it anyway, create another view and use this as android:background="@drawable/..."
.
In order to get the popup exactly centered, it's a simple matter of applying a negative top margin of half the div height, and a negative left margin of half the div width. For this example, like so:
.div {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 50%;
}
Also if you are using ECLIPSE yet, try clean your project:
Project > Clean...
I realize this is an old post but I find myself coming back to this thread a lot as it is one of the top search results when searching for this topic. However, I always leave more confused then when I came due to the conflicting information. Ultimately I always have to perform my own tests to figure it out. So this time I will post my findings.
TL;DR Most people will want to use Exit
to terminate a running scripts. However, if your script is merely declaring functions to later be used in a shell, then you will want to use Return
in the definitions of said functions.
Exit: This will "exit" the currently running context. If you call this command from a script it will exit the script. If you call this command from the shell it will exit the shell.
If a function calls the Exit command it will exit what ever context it is running in. So if that function is only called from within a running script it will exit that script. However, if your script merely declares the function so that it can be used from the current shell and you run that function from the shell, it will exit the shell because the shell is the context in which the function contianing the Exit
command is running.
Note: By default if you right click on a script to run it in PowerShell, once the script is done running, PowerShell will close automatically. This has nothing to do with the Exit
command or anything else in your script. It is just a default PowerShell behavior for scripts being ran using this specific method of running a script. The same is true for batch files and the Command Line window.
Return: This will return to the previous call point. If you call this command from a script (outside any functions) it will return to the shell. If you call this command from the shell it will return to the shell (which is the previous call point for a single command ran from the shell). If you call this command from a function it will return to where ever the function was called from.
Execution of any commands after the call point that it is returned to will continue from that point. If a script is called from the shell and it contains the Return
command outside any functions then when it returns to the shell there are no more commands to run thus making a Return
used in this way essentially the same as Exit
.
Break: This will break out of loops and switch cases. If you call this command while not in a loop or switch case it will break out of the script. If you call Break
inside a loop that is nested inside a loop it will only break out of the loop it was called in.
There is also an interesting feature of Break
where you can prefix a loop with a label and then you can break out of that labeled loop even if the Break
command is called within several nested groups within that labeled loop.
While ($true) {
# Code here will run
:myLabel While ($true) {
# Code here will run
While ($true) {
# Code here will run
While ($true) {
# Code here will run
Break myLabel
# Code here will not run
}
# Code here will not run
}
# Code here will not run
}
# Code here will run
}
Yesterday, I started to write my own way to bind data.
It's very funny to play with it.
I think it's beautiful and very useful. At least on my tests using firefox and chrome, Edge must works too. Not sure about others, but if they support Proxy, I think it will work.
https://jsfiddle.net/2ozoovne/1/
<H1>Bind Context 1</H1>
<input id='a' data-bind='data.test' placeholder='Button Text' />
<input id='b' data-bind='data.test' placeholder='Button Text' />
<input type=button id='c' data-bind='data.test' />
<H1>Bind Context 2</H1>
<input id='d' data-bind='data.otherTest' placeholder='input bind' />
<input id='e' data-bind='data.otherTest' placeholder='input bind' />
<input id='f' data-bind='data.test' placeholder='button 2 text - same var name, other context' />
<input type=button id='g' data-bind='data.test' value='click here!' />
<H1>No bind data</H1>
<input id='h' placeholder='not bound' />
<input id='i' placeholder='not bound'/>
<input type=button id='j' />
Here is the code:
(function(){
if ( ! ( 'SmartBind' in window ) ) { // never run more than once
// This hack sets a "proxy" property for HTMLInputElement.value set property
var nativeHTMLInputElementValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value');
var newDescriptor = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value');
newDescriptor.set=function( value ){
if ( 'settingDomBind' in this )
return;
var hasDataBind=this.hasAttribute('data-bind');
if ( hasDataBind ) {
this.settingDomBind=true;
var dataBind=this.getAttribute('data-bind');
if ( ! this.hasAttribute('data-bind-context-id') ) {
console.error("Impossible to recover data-bind-context-id attribute", this, dataBind );
} else {
var bindContextId=this.getAttribute('data-bind-context-id');
if ( bindContextId in SmartBind.contexts ) {
var bindContext=SmartBind.contexts[bindContextId];
var dataTarget=SmartBind.getDataTarget(bindContext, dataBind);
SmartBind.setDataValue( dataTarget, value);
} else {
console.error( "Invalid data-bind-context-id attribute", this, dataBind, bindContextId );
}
}
delete this.settingDomBind;
}
nativeHTMLInputElementValue.set.bind(this)( value );
}
Object.defineProperty(HTMLInputElement.prototype, 'value', newDescriptor);
var uid= function(){
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
}
// SmartBind Functions
window.SmartBind={};
SmartBind.BindContext=function(){
var _data={};
var ctx = {
"id" : uid() /* Data Bind Context Id */
, "_data": _data /* Real data object */
, "mapDom": {} /* DOM Mapped objects */
, "mapDataTarget": {} /* Data Mapped objects */
}
SmartBind.contexts[ctx.id]=ctx;
ctx.data=new Proxy( _data, SmartBind.getProxyHandler(ctx, "data")) /* Proxy object to _data */
return ctx;
}
SmartBind.getDataTarget=function(bindContext, bindPath){
var bindedObject=
{ bindContext: bindContext
, bindPath: bindPath
};
var dataObj=bindContext;
var dataObjLevels=bindPath.split('.');
for( var i=0; i<dataObjLevels.length; i++ ) {
if ( i == dataObjLevels.length-1 ) { // last level, set value
bindedObject={ target: dataObj
, item: dataObjLevels[i]
}
} else { // digg in
if ( ! ( dataObjLevels[i] in dataObj ) ) {
console.warn("Impossible to get data target object to map bind.", bindPath, bindContext);
break;
}
dataObj=dataObj[dataObjLevels[i]];
}
}
return bindedObject ;
}
SmartBind.contexts={};
SmartBind.add=function(bindContext, domObj){
if ( typeof domObj == "undefined" ){
console.error("No DOM Object argument given ", bindContext);
return;
}
if ( ! domObj.hasAttribute('data-bind') ) {
console.warn("Object has no data-bind attribute", domObj);
return;
}
domObj.setAttribute("data-bind-context-id", bindContext.id);
var bindPath=domObj.getAttribute('data-bind');
if ( bindPath in bindContext.mapDom ) {
bindContext.mapDom[bindPath][bindContext.mapDom[bindPath].length]=domObj;
} else {
bindContext.mapDom[bindPath]=[domObj];
}
var bindTarget=SmartBind.getDataTarget(bindContext, bindPath);
bindContext.mapDataTarget[bindPath]=bindTarget;
domObj.addEventListener('input', function(){ SmartBind.setDataValue(bindTarget,this.value); } );
domObj.addEventListener('change', function(){ SmartBind.setDataValue(bindTarget, this.value); } );
}
SmartBind.setDataValue=function(bindTarget,value){
if ( ! ( 'target' in bindTarget ) ) {
var lBindTarget=SmartBind.getDataTarget(bindTarget.bindContext, bindTarget.bindPath);
if ( 'target' in lBindTarget ) {
bindTarget.target=lBindTarget.target;
bindTarget.item=lBindTarget.item;
} else {
console.warn("Still can't recover the object to bind", bindTarget.bindPath );
}
}
if ( ( 'target' in bindTarget ) ) {
bindTarget.target[bindTarget.item]=value;
}
}
SmartBind.getDataValue=function(bindTarget){
if ( ! ( 'target' in bindTarget ) ) {
var lBindTarget=SmartBind.getDataTarget(bindTarget.bindContext, bindTarget.bindPath);
if ( 'target' in lBindTarget ) {
bindTarget.target=lBindTarget.target;
bindTarget.item=lBindTarget.item;
} else {
console.warn("Still can't recover the object to bind", bindTarget.bindPath );
}
}
if ( ( 'target' in bindTarget ) ) {
return bindTarget.target[bindTarget.item];
}
}
SmartBind.getProxyHandler=function(bindContext, bindPath){
return {
get: function(target, name){
if ( name == '__isProxy' )
return true;
// just get the value
// console.debug("proxy get", bindPath, name, target[name]);
return target[name];
}
,
set: function(target, name, value){
target[name]=value;
bindContext.mapDataTarget[bindPath+"."+name]=value;
SmartBind.processBindToDom(bindContext, bindPath+"."+name);
// console.debug("proxy set", bindPath, name, target[name], value );
// and set all related objects with this target.name
if ( value instanceof Object) {
if ( !( name in target) || ! ( target[name].__isProxy ) ){
target[name]=new Proxy(value, SmartBind.getProxyHandler(bindContext, bindPath+'.'+name));
}
// run all tree to set proxies when necessary
var objKeys=Object.keys(value);
// console.debug("...objkeys",objKeys);
for ( var i=0; i<objKeys.length; i++ ) {
bindContext.mapDataTarget[bindPath+"."+name+"."+objKeys[i]]=target[name][objKeys[i]];
if ( typeof value[objKeys[i]] == 'undefined' || value[objKeys[i]] == null || ! ( value[objKeys[i]] instanceof Object ) || value[objKeys[i]].__isProxy )
continue;
target[name][objKeys[i]]=new Proxy( value[objKeys[i]], SmartBind.getProxyHandler(bindContext, bindPath+'.'+name+"."+objKeys[i]));
}
// TODO it can be faster than run all items
var bindKeys=Object.keys(bindContext.mapDom);
for ( var i=0; i<bindKeys.length; i++ ) {
// console.log("test...", bindKeys[i], " for ", bindPath+"."+name);
if ( bindKeys[i].startsWith(bindPath+"."+name) ) {
// console.log("its ok, lets update dom...", bindKeys[i]);
SmartBind.processBindToDom( bindContext, bindKeys[i] );
}
}
}
return true;
}
};
}
SmartBind.processBindToDom=function(bindContext, bindPath) {
var domList=bindContext.mapDom[bindPath];
if ( typeof domList != 'undefined' ) {
try {
for ( var i=0; i < domList.length ; i++){
var dataTarget=SmartBind.getDataTarget(bindContext, bindPath);
if ( 'target' in dataTarget )
domList[i].value=dataTarget.target[dataTarget.item];
else
console.warn("Could not get data target", bindContext, bindPath);
}
} catch (e){
console.warn("bind fail", bindPath, bindContext, e);
}
}
}
}
})();
Then, to set, just:
var bindContext=SmartBind.BindContext();
SmartBind.add(bindContext, document.getElementById('a'));
SmartBind.add(bindContext, document.getElementById('b'));
SmartBind.add(bindContext, document.getElementById('c'));
var bindContext2=SmartBind.BindContext();
SmartBind.add(bindContext2, document.getElementById('d'));
SmartBind.add(bindContext2, document.getElementById('e'));
SmartBind.add(bindContext2, document.getElementById('f'));
SmartBind.add(bindContext2, document.getElementById('g'));
setTimeout( function() {
document.getElementById('b').value='Via Script works too!'
}, 2000);
document.getElementById('g').addEventListener('click',function(){
bindContext2.data.test='Set by js value'
})
For now, I've just added the HTMLInputElement value bind.
Let me know if you know how to improve it.
@DRapp is a genius. I never understood how he coded his SQL,so I tried coding it in my own understanding.
SELECT
f.username,
f.point,
f.avg_time
FROM
(
SELECT
userscores.username,
userscores.point,
userscores.avg_time
FROM
(
SELECT
users.username,
scores.point,
scores.avg_time
FROM
scores
JOIN users
ON scores.user_id = users.id
ORDER BY scores.point DESC
) userscores
ORDER BY
point DESC,
avg_time
) f
GROUP BY f.username
ORDER BY point DESC
It yields the same result by using GROUP BY instead of the user @variables.
You have to execute your query and add single quote to $email in the query beacuse it's a string, and remove the is_resource($query)
$query is a string, the $result will be the resource
$query = "SELECT `email` FROM `tblUser` WHERE `email` = '$email'";
$result = mysqli_query($link,$query); //$link is the connection
if(mysqli_num_rows($result) > 0 ){....}
UPDATE
Base in your edit just change:
if(is_resource($query) && mysqli_num_rows($query) > 0 ){
$query = mysqli_fetch_assoc($query);
echo $email . " email exists " . $query["email"] . "\n";
By
if(is_resource($result) && mysqli_num_rows($result) == 1 ){
$row = mysqli_fetch_assoc($result);
echo $email . " email exists " . $row["email"] . "\n";
and you will be fine
UPDATE 2
A better way should be have a Store Procedure that execute the following SQL passing the Email as Parameter
SELECT IF( EXISTS (
SELECT *
FROM `Table`
WHERE `email` = @Email)
, 1, 0) as `Exist`
and retrieve the value in php
Pseudocodigo:
$query = Call MYSQL_SP($EMAIL);
$result = mysqli_query($conn,$query);
$row = mysqli_fetch_array($result)
$exist = ($row['Exist']==1)? 'the email exist' : 'the email doesnt exist';
import numpy as np
import threading
def threaded_process(items_chunk):
""" Your main process which runs in thread for each chunk"""
for item in items_chunk:
try:
api.my_operation(item)
except Exception:
print('error with item')
n_threads = 20
# Splitting the items into chunks equal to number of threads
array_chunk = np.array_split(input_image_list, n_threads)
thread_list = []
for thr in range(n_threads):
thread = threading.Thread(target=threaded_process, args=(array_chunk[thr]),)
thread_list.append(thread)
thread_list[thr].start()
for thread in thread_list:
thread.join()
Have you tried git push? gitref.org has a nice section dealing with remote repositories.
You can also get help from the command line using the --help
option. For example:
% git push --help
GIT-PUSH(1) Git Manual GIT-PUSH(1)
NAME
git-push - Update remote refs along with associated objects
SYNOPSIS
git push [--all | --mirror | --tags] [-n | --dry-run] [--receive-pack=<git-receive-pack>]
[--repo=<repository>] [-f | --force] [-v | --verbose] [-u | --set-upstream]
[<repository> [<refspec>...]]
...
I really like the settingslogic gem. Very easy to set up and use.
Angular JS provide this functionality in ng-class Directive. In which you can put condition and also assign conditional class. You can achieve this in two different ways.
<div ng-class="{0:'one', 1:'two',2:'three'}[status]"></div>
In this code class will be apply according to value of status value
if status value is 0 then apply class one
if status value is 1 then apply class two
if status value is 2 then apply class three
<div ng-class="{1:'test_yes', 0:'test_no'}[status]"></div>
In which class will be apply by value of status
if status value is 1 or true then it will add class test_yes
if status value is 0 or false then it will add class test_no
Yes.
This is so that you can control how the class is instantiated. If you make the constructor private, and then create a visible constructor method that returns instances of the class, you can do things like limit the number of creations (typically, guarantee there is exactly one instance) or recycle instances or other construction-related tasks.
Doing new x()
never returns null
, but using the factory pattern, you can return null
, or even return different subtypes.
You might use it also for a class which has no instance members or properties, just static ones - as in a utility function class.
In my case, I have done following:
extension UITextField {
@IBInspectable var placeHolderColor: UIColor? {
get {
if let color = self.attributedPlaceholder?.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? UIColor {
return color
}
return nil
}
set (setOptionalColor) {
if let setColor = setOptionalColor {
let string = self.placeholder ?? ""
self.attributedPlaceholder = NSAttributedString(string: string , attributes:[NSAttributedString.Key.foregroundColor: setColor])
}
}
}
}
You need to quote that values.
Here is a more detailed spec.
You want
#content div:first-child {
/*css*/
}
Request.Form is a NameValueCollection. In NameValueCollection you can find the GetAllValues() method.
By the way the LINQ method also works.
The Material Design Typography page has demos for some of these fonts and suggestions on choosing fonts and styles.
For code sleuths: fonts.xml
is the definitive and ever-expanding list of Android fonts.
Set the android:fontFamily
and android:textStyle
attributes, e.g.
<!-- Roboto Bold -->
<TextView
android:fontFamily="sans-serif"
android:textStyle="bold" />
to the desired values from this table:
Font | android:fontFamily | android:textStyle
-------------------------|-----------------------------|-------------------
Roboto Thin | sans-serif-thin |
Roboto Light | sans-serif-light |
Roboto Regular | sans-serif |
Roboto Bold | sans-serif | bold
Roboto Medium | sans-serif-medium |
Roboto Black | sans-serif-black |
Roboto Condensed Light | sans-serif-condensed-light |
Roboto Condensed Regular | sans-serif-condensed |
Roboto Condensed Medium | sans-serif-condensed-medium |
Roboto Condensed Bold | sans-serif-condensed | bold
Noto Serif | serif |
Noto Serif Bold | serif | bold
Droid Sans Mono | monospace |
Cutive Mono | serif-monospace |
Coming Soon | casual |
Dancing Script | cursive |
Dancing Script Bold | cursive | bold
Carrois Gothic SC | sans-serif-smallcaps |
(Noto Sans is a fallback font; you can't specify it directly)
Note: this table is derived from fonts.xml
. Each font's family name and style is listed in fonts.xml, e.g.
<family name="serif-monospace">
<font weight="400" style="normal">CutiveMono.ttf</font>
</family>
serif-monospace
is thus the font family, and normal
is the style.
Based on the log of fonts.xml and the former system_fonts.xml, you can see when each font was added:
How did you pass object to method?
Are you doing new inside that method for object? If so, you have to use ref
in method.
Following link give you better idea.
http://dotnetstep.blogspot.com/2008/09/passing-reference-type-byval-or-byref.html
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.js"></script>
<script type="text/javascript" src="jquery-2.1.0.js"></script>
<script type="text/javascript" >
function openOnImageClick(event)
{
//alert("Jai Sh Raam");
// document.getElementById("images").src = "fruits.jpg";
var target = event.target || event.srcElement; // IE
console.log(target);
console.log(target.id);
var img = document.createElement('img');
img.setAttribute('src', target.src);
img.setAttribute('width', '200');
img.setAttribute('height', '150');
document.getElementById("images").appendChild(img);
}
</script>
</head>
<body>
<h1>Screen Shot View</h1>
<p>Click the Tiger to display the Image</p>
<div id="images" >
</div>
<img id="muID1" src="tiger.jpg" width="100" height="50" alt="unfinished bingo card" onclick="openOnImageClick(event)" />
<img id="myID2" src="sabaLogo1.jpg" width="100" height="50" alt="unfinished bingo card" onclick="openOnImageClick(event)" />
</body>
</html>